<?php
// Database Test for localhost
error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "<h2>Local Database Connection Test</h2>";

// Check if required files exist
$files_to_check = [
    'config/EnvLoader.php',
    'config/database.php',
    '.env'
];

echo "<h3>File Check:</h3>";
foreach ($files_to_check as $file) {
    $path = __DIR__ . '/' . $file;
    if (file_exists($path)) {
        echo "<p style='color: green;'>✓ $file exists</p>";
    } else {
        echo "<p style='color: red;'>✗ $file NOT FOUND</p>";
    }
}

// Test direct connection
echo "<h3>Direct Connection Test:</h3>";
try {
    $pdo = new PDO("mysql:host=localhost;dbname=school_management;charset=utf8mb4", "root", "root", [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    ]);
    echo "<p style='color: green;'>✓ Connected successfully!</p>";
    
    // Check tables
    $stmt = $pdo->query("SHOW TABLES");
    $tables = $stmt->fetchAll(PDO::FETCH_COLUMN);
    echo "<p>Total tables: " . count($tables) . "</p>";
    
    if (count($tables) > 0) {
        echo "<p>Sample tables: " . implode(", ", array_slice($tables, 0, 5)) . "...</p>";
    }
} catch(PDOException $e) {
    echo "<p style='color: red;'>✗ Connection failed: " . $e->getMessage() . "</p>";
    echo "<p>Error Code: " . $e->getCode() . "</p>";
    
    // Provide solutions
    echo "<h3>Possible Solutions:</h3>";
    echo "<ol>";
    echo "<li><strong>Start MAMP:</strong> Make sure MAMP server is running</li>";
    echo "<li><strong>Check MySQL:</strong> Start MySQL from MAMP control panel</li>";
    echo "<li><strong>Check Port:</strong> MySQL usually runs on port 3306 or 8889 in MAMP</li>";
    echo "<li><strong>Create Database:</strong> Run this in phpMyAdmin: CREATE DATABASE bidda;</li>";
    echo "</ol>";
}

// Check PHP extensions
echo "<h3>PHP Extensions:</h3>";
$required_extensions = ['pdo', 'pdo_mysql', 'mysqli'];
foreach ($required_extensions as $ext) {
    if (extension_loaded($ext)) {
        echo "<p style='color: green;'>✓ $ext loaded</p>";
    } else {
        echo "<p style='color: red;'>✗ $ext NOT loaded</p>";
    }
}
