<?php
if (file_exists(__DIR__ . '/config.php')) {
    require_once __DIR__ . '/config.php';
} elseif (file_exists(__DIR__ . '/../config.php')) {
    require_once __DIR__ . '/../config.php';
}

if (!function_exists('getDBConnection')) {
    function getDBConnection() {
        static $pdo = null;
        if ($pdo === null) {
            $host    = defined('DB_HOST') ? DB_HOST : 'localhost';
            $dbName  = defined('DB_NAME') ? DB_NAME : '';
            $charset = defined('DB_CHARSET') ? DB_CHARSET : 'utf8';
            $user    = defined('DB_USER') ? DB_USER : '';
            $pass    = defined('DB_PASS') ? DB_PASS : '';

            $dsn = "mysql:host=" . $host . ";dbname=" . $dbName . ";charset=" . $charset;
            $options = [
                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 " . $charset
            ];
            try {
                $pdo = new PDO($dsn, $user, $pass, $options);
                $pdo->exec("SET NAMES " . $charset);
            } catch (PDOException $e) {
                // Log error safely
                error_log("DB Connection Error: " . $e->getMessage());
                http_response_code(500);
                die("<h2>เกิดข้อผิดพลาด: ไม่สามารถเชื่อมต่อฐานข้อมูลได้</h2><p>กรุณาตรวจสอบการตั้งค่า DB_HOST, DB_USER, DB_PASS, DB_NAME ใน config.php และลองใหม่อีกครั้ง</p><p>รายละเอียด: " . htmlspecialchars($e->getMessage()) . "</p>");
            }
        }
        return $pdo;
    }
}

// Auto init database tables if not created yet
function autoInitDatabase() {
    $pdo = getDBConnection();
    $sqlFile = __DIR__ . '/../schema.sql';
    if (file_exists($sqlFile)) {
        $sql = file_get_contents($sqlFile);
        try {
            $pdo->exec($sql);
        } catch (Exception $e) {
            // Ignore if tables exist
        }
    }
}

