<?php
$config = require __DIR__ . '/../config/database.php';

// Check if PDO is available
if (!class_exists('PDO')) {
    die('<div style="text-align:center; padding:50px; font-family:sans-serif;">
            <h2 style="color:red">Module PHP PDO Tidak Aktif</h2>
            <p>Server hosting Anda belum mengaktifkan extension <b>pdo_mysql</b>.</p>
            <p>Silakan masuk ke cPanel -> <b>Select PHP Version</b> -> Centang <b>pdo</b> dan <b>pdo_mysql</b>.</p>
         </div>');
}

$dsn = "mysql:host={$config['db_host']};dbname={$config['db_name']};charset={$config['charset']}";
$options = [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES => false,
];

try {
    // Debug: Check config values (Uncomment if needed, but for now we rely on the error block)
    // echo "Debug: Trying to connect to {$config['db_host']} with user {$config['db_user']}...<br>";
    $pdo = new PDO($dsn, $config['db_user'], $config['db_pass'], $options);
} catch (PDOException $e) {
    // Check if we are in CLI mode or Web
    if (php_sapi_name() === 'cli') {
        echo "Database connection failed: " . $e->getMessage() . "\n";
    } else {
        // Show a nice error message to the user
        echo '<div style="text-align: center; padding: 50px; font-family: sans-serif; color: #4a4a4a;">';
        echo '<h2 style="color: #ff9ab7;">Gagal Terhubung ke Database</h2>';
        echo '<p>Pastikan username dan password di <code>config/database.php</code> sudah benar.</p>';
        echo '<p style="font-size: 0.9em; color: #888;">Error: ' . htmlspecialchars($e->getMessage()) . '</p>';
        echo '</div>';
    }
    exit;
}

return $pdo;
