<?php

namespace App;

use PDO;
use PDOException;

class Database {
    private static ?PDO $instance = null;
    // Gebruik de globale constante DB_PATH uit config.php
    private static string $dbFile = DB_PATH; 

    public static function getInstance(): PDO {
        if (self::$instance === null) {
            try {
                self::$instance = new PDO('sqlite:' . self::$dbFile);
                self::$instance->exec('PRAGMA journal_mode = WAL;');
                self::$instance->exec('PRAGMA busy_timeout = 5000;');
                self::$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                self::createTables();
            } catch (PDOException $e) {
                error_log("Database connection failed: " . $e->getMessage());
                // Verbeterde foutmelding voor de gebruiker
                die("FATAL ERROR: Database connection failed. This is often a permission issue.
                <br>Error: " . $e->getMessage() . "
                <br>Database Path: " . self::$dbFile . "
                <br>Please ensure the web server user (www-data) has write permissions to the database file and its directory.");
            }
        }
        return self::$instance;
    }

    private static function createTables(): void {
        $db = self::getInstance();
        $db->exec('CREATE TABLE IF NOT EXISTS categories (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL UNIQUE,
            parent_id INTEGER DEFAULT NULL
        )');
        $db->exec('CREATE TABLE IF NOT EXISTS items (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL,
            description TEXT,
            category_id INTEGER,
            id_code TEXT UNIQUE,
            image TEXT,
            location TEXT,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (category_id) REFERENCES categories(id)
        )');

        // Create trigger for updated_at
        $db->exec('CREATE TRIGGER IF NOT EXISTS update_items_updated_at 
            AFTER UPDATE ON items
            FOR EACH ROW
            BEGIN
                UPDATE items SET updated_at = CURRENT_TIMESTAMP WHERE id = NEW.id;
            END');
    }
}
