<?php
echo "<h1>🔧 Fix Database Host Configuration</h1>";
echo "<style>body{font-family:Arial,sans-serif;margin:20px;} .success{color:green;font-weight:bold;} .error{color:red;font-weight:bold;} .info{color:blue;}</style>";

$envFile = '../.env';

if (file_exists($envFile)) {
    echo "<p class='info'>Reading current .env file...</p>";

    $envContent = file_get_contents($envFile);
    $lines = explode("\n", $envContent);

    echo "<p>Current DB_HOST configuration:</p>";
    $foundHost = false;
    foreach ($lines as $line) {
        if (strpos($line, 'DB_HOST=') === 0) {
            echo "<p><strong>$line</strong></p>";
            $foundHost = true;
            break;
        }
    }

    if (!$foundHost) {
        echo "<p class='error'>DB_HOST not found in .env file</p>";
    }

    // Try different host configurations
    $hostsToTry = ['localhost', '127.0.0.1', '::1'];

    echo "<h2>Testing different host configurations:</h2>";

    foreach ($hostsToTry as $host) {
        echo "<h3>Testing DB_HOST=$host</h3>";
        try {
            $pdo = new PDO("mysql:host=$host;dbname=spm_db;charset=utf8", 'root', '');
            echo "<p class='success'>✅ Connection successful with host: $host</p>";

            // Update .env file
            $updatedContent = str_replace('DB_HOST=127.0.0.1', "DB_HOST=$host", $envContent);
            $updatedContent = str_replace('DB_HOST=localhost', "DB_HOST=$host", $updatedContent);

            if (file_put_contents($envFile, $updatedContent)) {
                echo "<p class='success'>✅ .env file updated with DB_HOST=$host</p>";
            } else {
                echo "<p class='error'>❌ Failed to update .env file</p>";
            }

            // Test Laravel connection
            echo "<p class='info'>Testing Laravel database connection...</p>";
            require_once '../vendor/autoload.php';
            $app = require_once '../bootstrap/app.php';
            $app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();

            $laravelPdo = DB::connection('mysql')->getPdo();
            echo "<p class='success'>✅ Laravel database connection successful!</p>";

            $profiles = DB::table('profiles')->where('is_active', 1)->count();
            echo "<p>Found $profiles active profiles in database.</p>";

            echo "<h2>🎉 SUCCESS! Problem solved!</h2>";
            echo "<p>You can now access your Laravel application normally.</p>";
            break;

        } catch (Exception $e) {
            echo "<p class='error'>❌ Failed with host $host: " . $e->getMessage() . "</p>";
        }
    }

} else {
    echo "<p class='error'>❌ .env file not found</p>";
}

echo "<hr>";
echo "<p><a href='test.php'>← Back to Test Page</a></p>";
?>
