<?php
// Test Database Connection - Debug Mode
error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "<h1>Database Connection Test</h1>";
echo "<pre>";

$envPath = __DIR__ . '/.env';
echo "Checking .env file at: $envPath\n";
if (file_exists($envPath)) {
    echo ".env file EXISTS.\n";
    $content = file_get_contents($envPath);
    echo "Content Preview (first 50 chars): " . substr($content, 0, 50) . "...\n";
} else {
    echo "FATAL: .env file NOT FOUND.\n";
}

echo "\nLoading config...\n";
// Manually load config to catch errors
try {
    require_once __DIR__ . '/includes/config.php';
    echo "Config loaded.\n";
} catch (Throwable $t) {
    echo "Error loading config: " . $t->getMessage() . "\n";
}

echo "\nChecking Environment Variables (via getenv):\n";
$vars = ['DB_HOST', 'DB_NAME', 'DB_USER', 'DB_PASS'];
foreach ($vars as $var) {
    $val = getenv($var);
    echo "$var: [" . ($val === false ? "FALSE" : $val) . "]\n";
}

echo "\nAttempting PDO Connection...\n";
try {
    $dsn = 'mysql:host=' . getenv('DB_HOST') . ';dbname=' . getenv('DB_NAME') . ';charset=' . (getenv('DB_CHARSET') ?: 'utf8mb4');
    echo "DSN: $dsn\n";
    $pdo = new PDO($dsn, getenv('DB_USER'), getenv('DB_PASS'), [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    ]);
    echo "SUCCESS: Connection established!\n";
} catch (PDOException $e) {
    echo "FAILURE: Connection Error: " . $e->getMessage() . "\n";
}

echo "</pre>";
