<?php
/**
 * Database Connection Tester
 * Tests different common MySQL passwords for MAMP
 */

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

// Common MAMP MySQL passwords to test
$passwords_to_test = [
    '',           // No password (default for some MAMP installations)
    'root',       // Common default
    'password',   // Another common default
    'admin',      // Sometimes used
    'mamp'        // MAMP specific
];

$host = 'localhost';
$dbname = 'school_management';
$username = 'root';

echo "<h3>Testing Database Connections:</h3>";

foreach ($passwords_to_test as $password) {
    echo "<p>Testing password: '<strong>" . ($password === '' ? '(empty)' : $password) . "</strong>'</p>";
    
    try {
        $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false,
        ]);
        
        echo "<p style='color: green;'>✅ SUCCESS! Connected with password: '<strong>" . ($password === '' ? '(empty)' : $password) . "</strong>'</p>";
        
        // Test a simple query
        $stmt = $pdo->query("SELECT COUNT(*) as count FROM users");
        $count = $stmt->fetch()['count'];
        echo "<p>Database contains $count users</p>";
        
        // Show current SMS settings
        echo "<h3>Current SMS Settings:</h3>";
        $stmt = $pdo->query("SELECT setting_key, setting_value FROM settings WHERE setting_key LIKE '%sms%' OR setting_key LIKE '%non_musking%' ORDER BY setting_key");
        echo "<table border='1' cellpadding='5'>";
        echo "<tr><th>Setting Key</th><th>Setting Value</th></tr>";
        while ($row = $stmt->fetch()) {
            $value = $row['setting_key'] === 'non_musking_password' || $row['setting_key'] === 'sms_password' ? '***HIDDEN***' : htmlspecialchars($row['setting_value']);
            echo "<tr><td>" . htmlspecialchars($row['setting_key']) . "</td><td>$value</td></tr>";
        }
        echo "</table>";
        
        break;
        
    } catch (PDOException $e) {
        echo "<p style='color: red;'>❌ Failed: " . $e->getMessage() . "</p>";
    }
    echo "<hr>";
}

echo "<h3>If none worked, try these solutions:</h3>";
echo "<ol>";
echo "<li>Open MAMP application and check MySQL password in preferences</li>";
echo "<li>Check MAMP phpMyAdmin at: http://localhost/phpMyAdmin/</li>";
echo "<li>Look in MAMP conf files for actual password</li>";
echo "</ol>";

echo "<h3>Manual Fix:</h3>";
echo "<p>Once you find the correct password, update <code>config/database.php</code> line 6:</p>";
echo "<pre>\$password = 'your_actual_password';</pre>";
?>