<?php
// Database configuration
define('DB_HOST', '127.0.0.1');
define('DB_NAME', 'app_38350');
define('DB_USER', 'app_38350');
define('DB_PASS', 'c79d2d31-7d44-4d51-ac22-5bfd0886fcc2');

function db() {
    static $pdo;
    if (!$pdo) {
        try {
            $pdo = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset=utf8mb4', DB_USER, DB_PASS, [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            ]);

            // Auto-install check: if 'settings' table doesn't exist, run install.sql
            static $checked = false;
            if (!$checked) {
                $checked = true;
                $res = $pdo->query("SHOW TABLES LIKE 'settings'");
                if ($res->rowCount() == 0) {
                    $sql_file = __DIR__ . '/install.sql';
                    if (file_exists($sql_file)) {
                        $sql = file_get_contents($sql_file);
                        $pdo->exec($sql);
                    }
                }
            }
        } catch (PDOException $e) {
            die("Database connection failed: " . $e->getMessage());
        }
    }
    return $pdo;
}