<?php
/**
 * Database Connection Handler
 */
require_once __DIR__ . '/Env.php';

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

    /**
     * Private constructor to prevent direct instantiation
     */
    private function __construct() {
        // Ensure .env is loaded (root or auth-backend)
        TonEnv::load();

        // Read DB config from environment with safe defaults
        $dbHost = TonEnv::get('DB_HOST', 'localhost');
        $dbName = TonEnv::get('DB_NAME', 'tonsui_test');
        $dbUser = TonEnv::get('DB_USER', 'root');
        $dbPass = TonEnv::get('DB_PASS', '');
        $dbPort = TonEnv::get('DB_PORT', '3306');

        $dsn = "mysql:host={$dbHost};port={$dbPort};dbname={$dbName};charset=utf8mb4";

        try {
            $this->pdo = new PDO($dsn, $dbUser, $dbPass, [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false,
            ]);
        } catch (PDOException $e) {
            throw new Exception('Database connection failed: ' . $e->getMessage());
        }
    }

    /**
     * Get database connection instance (singleton)
     */
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Get PDO connection
     */
    public function getConnection() {
        return $this->pdo;
    }

    /**
     * Convenience query helper
     */
    public function query($sql, array $params = []) {
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($params);
        return $stmt;
    }

    /**
     * Prevent cloning of the instance
     */
    private function __clone() {}

    /**
     * Prevent unserializing of the instance
     * Must be public visibility per PHP 8 magic method requirements
     */
    public function __wakeup() {}
}
