<?php

class Database
{
    private static $instance = null;
    private $pdo;

    private function __construct()
    {
        $dataDir = __DIR__ . "/../../data/";
        $dbPath = $dataDir . 'tribegen.db';

        if (!is_dir($dataDir)) {
            if (!mkdir($dataDir, 0775, true) && !is_dir($dataDir)) {
                throw new RuntimeException("Failed to create data directory: $dataDir");
            }
        }

        if (!is_writable($dataDir)) {
            throw new RuntimeException("Data directory is not writable: $dataDir");
        }

        $this->pdo = new \PDO('sqlite:' . $dbPath);
        $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        $this->pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
    }

    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function getPDO()
    {
        return $this->pdo;
    }

    public function initializeTables()
    {
        // Only the users table is stored in the database
        // All game data is stored as JSON files in /data/saves/
        $this->pdo->exec("
            CREATE TABLE IF NOT EXISTS users (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                email TEXT UNIQUE NOT NULL,
                password_hash TEXT NOT NULL,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP
            );
        ");
    }
}
