<?php

$pdo = null; 

if (!defined('DB_HOST')) {
    $dbConfigFile = __DIR__ . '/../config/database.php';
    if (file_exists($dbConfigFile)) {
        require_once $dbConfigFile;
    } else {
        error_log("FATAL ERROR in db_connect.php: Cannot find database config file at " . $dbConfigFile);
        return; 
    }
}
if (!defined('APP_NAME')) {
    @include_once __DIR__ . '/../config/config.php';
}

if (!defined('DB_HOST') || !defined('DB_USER') || !defined('DB_PASS') || !defined('DB_NAME') || !defined('DB_CHARSET')) {
    error_log("FATAL ERROR in db_connect.php: Konstanta database tidak lengkap setelah include.");
    return;
}

$dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET;
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];

try {
    $pdo = new PDO($dsn, DB_USER, DB_PASS, $options);

} catch (\PDOException $e) {
    error_log("!!! DATABASE CONNECTION FAILED in db_connect.php !!!");
    error_log("PDOException Message: " . $e->getMessage());
    error_log("PDOException Code: " . $e->getCode());
    error_log("Attempted connect: host=" . DB_HOST . ", db=" . DB_NAME . ", user=" . DB_USER);

    $pdo = null;

}

?>
