<?php

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

    private function __construct() {
        $host = getenv('DB_HOST') ?: 'localhost';
        $port = getenv('DB_PORT') ?: '3306';
        $dbname = getenv('DB_NAME') ?: 'smartform_db';
        $user = getenv('DB_USER') ?: 'root';
        $pass = getenv('DB_PASS') ?: '';

        try {
            $dsn = "mysql:host={$host};port={$port};dbname={$dbname};charset=utf8mb4";
            $this->pdo = new PDO($dsn, $user, $pass, [
                PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES   => false,
            ]);
        } catch (PDOException $e) {
            // Show setup page if DB not connected
            if (!defined('SKIP_DB_ERROR')) {
                showDbError($e->getMessage());
            }
        }
    }

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

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

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

    public function fetch($sql, $params = []) {
        return $this->query($sql, $params)->fetch();
    }

    public function fetchAll($sql, $params = []) {
        return $this->query($sql, $params)->fetchAll();
    }

    public function insert($sql, $params = []) {
        $this->query($sql, $params);
        return $this->pdo->lastInsertId();
    }

    public function execute($sql, $params = []) {
        return $this->query($sql, $params)->rowCount();
    }
}

function showDbError($msg) {
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Database Setup Required</title>
        <script src="https://cdn.tailwindcss.com"></script>
    </head>
    <body class="bg-gray-900 text-white flex items-center justify-center min-h-screen">
        <div class="bg-gray-800 rounded-2xl p-8 max-w-lg w-full mx-4 text-center">
            <div class="text-6xl mb-4">🗄️</div>
            <h1 class="text-2xl font-bold mb-2 text-red-400">Database Connection Failed</h1>
            <p class="text-gray-400 mb-4 text-sm"><?= htmlspecialchars($msg) ?></p>
            <div class="bg-gray-700 rounded-lg p-4 text-left text-sm mb-4">
                <p class="text-yellow-400 font-semibold mb-2">Steps to fix:</p>
                <ol class="text-gray-300 space-y-1 list-decimal list-inside">
                    <li>Create MySQL database: <code class="text-green-400">smartform_db</code></li>
                    <li>Update <code class="text-green-400">.env</code> with your DB credentials</li>
                    <li>Import <code class="text-green-400">storage/schema.sql</code></li>
                    <li>Refresh this page</li>
                </ol>
            </div>
            <a href="/smartform/setup" class="bg-blue-600 hover:bg-blue-700 px-6 py-2 rounded-lg text-sm font-medium transition-colors">Run Setup Wizard</a>
        </div>
    </body>
    </html>
    <?php
    exit();
}
