<?php
/**
 * Database Connection - PDO with prepared statements
 */

if (!defined('INSTALLED')) {
    require_once dirname(__DIR__) . '/config/config.php';
}

// Redirect to installer if site has not been set up yet
if (!defined('INSTALL_MODE') && (!defined('INSTALLED') || INSTALLED === false)) {
    header('Location: /install/');
    exit;
}

class Database {
    private static ?PDO $instance = null;

    public static function getInstance(): PDO {
        if (self::$instance === null) {
            try {
                $dsn = 'mysql:host=' . DB_HOST . ';port=' . DB_PORT . ';dbname=' . DB_NAME . ';charset=utf8mb4';
                self::$instance = new PDO($dsn, DB_USER, DB_PASS, [
                    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                    PDO::ATTR_EMULATE_PREPARES   => false,
                    PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci",
                ]);
            } catch (PDOException $e) {
                error_log("DB Connection Error: " . $e->getMessage());
                http_response_code(503);
                
                // If it's an AJAX/API request, return JSON
                $isAjax = (
                    (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') || 
                    (stripos($_SERVER['HTTP_ACCEPT'] ?? '', 'application/json') !== false) ||
                    (stripos($_SERVER['REQUEST_URI'], '/api/') !== false)
                );

                if ($isAjax) {
                    header('Content-Type: application/json');
                    die(json_encode([
                        'success' => false,
                        'error' => 'Database connection failed. Please contact administrator.',
                        'debug' => (defined('SITE_DEBUG') && SITE_DEBUG) ? $e->getMessage() : null
                    ]));
                }

                die('<!DOCTYPE html><html><head><title>Database Error</title><style>body{background:#0a0e1a;color:#e8eaed;font-family:sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0}.box{background:#1a1f2e;padding:40px;border-radius:12px;border:1px solid #dc2626;max-width:500px;text-align:center}h2{color:#fca5a5;margin-bottom:12px}p{color:#9ca3af;font-size:14px}code{background:#0a0e1a;padding:2px 8px;border-radius:4px;font-size:13px}</style></head><body><div class="box"><h2>Database Connection Failed</h2><p>Could not connect to the database. Please check your <code>config/config.php</code> settings or run the <a href="/install/" style="color:#ff6b00">install wizard</a>.</p></div></body></html>');
            }
        }
        return self::$instance;
    }

    // Shortcut helpers
    public static function query(string $sql, array $params = []): \PDOStatement {
        $stmt = self::getInstance()->prepare($sql);
        $stmt->execute($params);
        return $stmt;
    }

    public static function fetchOne(string $sql, array $params = []): ?array {
        $row = self::query($sql, $params)->fetch();
        return $row ?: null;
    }

    public static function fetchAll(string $sql, array $params = []): array {
        return self::query($sql, $params)->fetchAll();
    }

    public static function insert(string $sql, array $params = []): int {
        self::query($sql, $params);
        return (int) self::getInstance()->lastInsertId();
    }

    public static function execute(string $sql, array $params = []): int {
        return self::query($sql, $params)->rowCount();
    }

    public static function getSetting(string $key, string $default = ''): string {
        $row = self::fetchOne("SELECT setting_value FROM settings WHERE setting_key = ?", [$key]);
        return $row ? ($row['setting_value'] ?? $default) : $default;
    }
}

// Convenience alias
function db(): PDO { return Database::getInstance(); }
