<?php
echo "<h1>🚨 EMERGENCY DATABASE FIX</h1>";
echo "<style>body{font-family:Arial,sans-serif;margin:20px;font-size:16px;} .success{color:green;font-weight:bold;font-size:20px;} .error{color:red;font-weight:bold;font-size:18px;} .info{color:blue;font-size:14px;} .box{background:#f8f9fa;padding:15px;border-radius:8px;margin:10px 0;border-left:4px solid #007bff;}</style>";

// Force correct .env configuration
echo "<h2>🔧 Step 1: Force Correct Configuration</h2>";

$envContent = "APP_NAME=Spm1
APP_ENV=production
APP_KEY=base64:emergency_fix_" . time() . "
APP_DEBUG=false
APP_TIMEZONE=UTC
APP_URL=http://192.168.10.70

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=spm_db
DB_USERNAME=root
DB_PASSWORD=

SESSION_DRIVER=file
CACHE_STORE=file
QUEUE_CONNECTION=sync";

$envFile = '../.env';
if (file_put_contents($envFile, $envContent)) {
    echo "<p class='success'>✅ Configuration forced to localhost (same server)</p>";
} else {
    echo "<p class='error'>❌ Failed to write configuration</p>";
}

// Test immediate connection
echo "<h2>🔍 Step 2: Test Connection</h2>";
try {
    $pdo = new PDO('mysql:host=localhost;dbname=spm_db;charset=utf8', 'root', '');
    echo "<p class='success'>✅ MySQL connection successful</p>";

    $stmt = $pdo->query("SELECT COUNT(*) as total FROM profiles");
    $result = $stmt->fetch();
    echo "<p class='success'>✅ Database has {$result['total']} profiles</p>";

    $stmt = $pdo->query("SELECT COUNT(*) as total FROM articles");
    $result = $stmt->fetch();
    echo "<p class='success'>✅ Database has {$result['total']} articles</p>";

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

    // Try with 127.0.0.1
    echo "<p class='info'>Trying 127.0.0.1...</p>";
    try {
        $pdo = new PDO('mysql:host=127.0.0.1;dbname=spm_db;charset=utf8', 'root', '');
        echo "<p class='success'>✅ MySQL connection successful with 127.0.0.1</p>";

        // Update .env
        $envContent = str_replace('DB_HOST=localhost', 'DB_HOST=127.0.0.1', $envContent);
        file_put_contents($envFile, $envContent);
        echo "<p class='success'>✅ Configuration updated to 127.0.0.1</p>";

    } catch (Exception $e2) {
        echo "<p class='error'>❌ Still failed with 127.0.0.1: " . $e2->getMessage() . "</p>";
    }
}

// Test Laravel framework connection
echo "<h2>🎯 Step 3: Test Laravel Framework</h2>";
try {
    require_once '../vendor/autoload.php';
    $app = require_once '../bootstrap/app.php';
    $app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();

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

    // Test the exact query from error
    $profiles = DB::table('profiles')->where('is_active', 1)->orderBy('order')->orderBy('created_at', 'desc')->limit(3)->get();
    echo "<p class='success'>✅ Profile query successful - found {$profiles->count()} active profiles</p>";

    if ($profiles->count() > 0) {
        echo "<div class='box'>";
        echo "<strong>Sample profiles found:</strong><br>";
        foreach ($profiles as $profile) {
            echo "- {$profile->title}<br>";
        }
        echo "</div>";
    }

    echo "<h1 class='success'>🎉 SUCCESS! DATABASE FIXED!</h1>";
    echo "<div class='box' style='background:#d4edda;border-left-color:#28a745;'>";
    echo "<h3>✅ Your Laravel application is now working!</h3>";
    echo "<p><strong>Main App:</strong> <a href='http://192.168.10.70' target='_blank'>http://192.168.10.70</a></p>";
    echo "<p><strong>phpMyAdmin:</strong> <a href='http://192.168.10.70/phpmyadmin' target='_blank'>http://192.168.10.70/phpmyadmin</a></p>";
    echo "<p><strong>Error Status:</strong> RESOLVED ✅</p>";
    echo "</div>";

} catch (Exception $e) {
    echo "<p class='error'>❌ Laravel framework connection failed: " . $e->getMessage() . "</p>";

    echo "<div class='box' style='background:#f8d7da;border-left-color:#dc3545;'>";
    echo "<h3>🔍 Critical Issue Detected:</h3>";
    echo "<p>Laravel cannot connect to database even though MySQL is accessible.</p>";
    echo "<p><strong>Possible causes:</strong></p>";
    echo "<ul>";
    echo "<li>Application and database are on different servers</li>";
    echo "<li>MySQL user permissions incorrect</li>";
    echo "<li>Port 3306 blocked by firewall</li>";
    echo "</ul>";
    echo "<p><strong>Quick solution:</strong> Move Laravel app to same server as database (192.168.10.70)</p>";
    echo "</div>";
}

// Clear any caches
echo "<h2>🧹 Step 4: Clear Caches</h2>";
if (file_exists('../artisan')) {
    $caches = ['config:clear', 'cache:clear', 'route:clear', 'view:clear'];
    foreach ($caches as $cache) {
        $output = shell_exec("cd ../ && php artisan {$cache} 2>&1");
        echo "<p class='info'>{$cache}: " . (strpos($output, 'success') !== false ? '✅' : '⚠️') . "</p>";
    }
}

echo "<hr>";
echo "<p><strong>Executed at:</strong> " . date('Y-m-d H:i:s') . "</p>";
echo "<p><strong>Server IP:</strong> " . $_SERVER['SERVER_ADDR'] . "</p>";
?>
