<?php

namespace App\Database;

use PDO;
use PDOException;

class Database {
    private static ?PDO $instance = null;
    private static string $dbFile = '/var/www/localweb/collections.sqlite';

    public static function getInstance(): PDO {
        if (self::$instance === null) {
            try {
                self::$instance = new PDO('sqlite:' . self::$dbFile);
                self::$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                self::createTables();
            } catch (PDOException $e) {
                error_log("Database connection failed: " . $e->getMessage());
                throw new PDOException("Database connection failed: could not open database file. Please check server logs for details.");
            }
        }
        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
        )');
        $db->exec('CREATE TABLE IF NOT EXISTS items (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL,
            description TEXT,
            category_id INTEGER,
            FOREIGN KEY (category_id) REFERENCES categories(id)
        )');
    }
}
