<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

echo "<html><body style='font-family: sans-serif; padding: 20px;'>";
echo "<h1>🚑 System Health Check</h1>";

// 1. PHP Version
echo "<h2>1. PHP Version</h2>";
echo "<strong>Web Server PHP:</strong> " . phpversion() . "<br>";
if (version_compare(phpversion(), '8.1.0', '<')) {
    echo "<div style='color:red; font-weight:bold;'>❌ CRITICAL: You are running PHP " . phpversion() . ". Laravel requires PHP 8.1 or 8.2!</div>";
    echo "Please update your hosting PHP version to 8.2.";
} else {
    echo "<div style='color:green; font-weight:bold;'>✅ PHP Version is OK</div>";
}

// 2. Permissions
echo "<h2>2. Permissions Check</h2>";
$dirs = [
    '../storage' => 'Storage Directory',
    '../storage/framework' => 'Framework Directory',
    '../storage/logs' => 'Logs Directory',
    '../bootstrap/cache' => 'Bootstrap Cache'
];

foreach ($dirs as $path => $label) {
    if (file_exists($path)) {
        if (is_writable($path)) {
            echo "✅ <strong>$label:</strong> Writable<br>";
        } else {
            echo "❌ <strong>$label:</strong> <span style='color:red'>NOT WRITABLE (Permission Denied)</span><br>";
        }
    } else {
        echo "❌ <strong>$label:</strong> <span style='color:red'>Directory Not Found ($path)</span><br>";
    }
}

// 3. Environment File
echo "<h2>3. Environment (.env)</h2>";
if (file_exists('../.env')) {
    echo "✅ .env file exists.<br>";
    $env = file_get_contents('../.env');
    
    // Check Debug Mode
    if (strpos($env, 'APP_DEBUG=true') !== false) {
        echo "ℹ️ Debug Mode is ON<br>";
    } else {
        echo "ℹ️ Debug Mode is OFF<br>";
    }
} else {
    echo "❌ <span style='color:red'>.env file is MISSING!</span><br>";
}

// 4. Database Check
echo "<h2>4. Database Connection</h2>";
if (file_exists('../.env')) {
    preg_match('/DB_HOST=(.*)/', $env, $host);
    preg_match('/DB_DATABASE=(.*)/', $env, $db);
    preg_match('/DB_USERNAME=(.*)/', $env, $user);
    preg_match('/DB_PASSWORD=(.*)/', $env, $pass);

    $h = trim($host[1] ?? '127.0.0.1');
    $u = trim($user[1] ?? '');
    $p = trim($pass[1] ?? '');
    $d = trim($db[1] ?? '');

    $conn = @new mysqli($h, $u, $p, $d);
    if ($conn->connect_error) {
        echo "❌ <span style='color:red'>Connection Failed: " . $conn->connect_error . "</span><br>";
    } else {
        echo "✅ Database Connected Successfully!<br>";
    }
}

// 5. Last Log Entries
echo "<h2>5. Recent Errors (storage/logs/laravel.log)</h2>";
$logFile = '../storage/logs/laravel.log';
if (file_exists($logFile)) {
    $lines = file($logFile);
    $lastLines = array_slice($lines, -30);
    echo "<div style='background: #f0f0f0; padding: 10px; border: 1px solid #ccc; overflow: auto; max-height: 400px;'><pre>";
    foreach ($lastLines as $line) {
        echo htmlspecialchars($line);
    }
    echo "</pre></div>";
} else {
    echo "ℹ️ No log file found yet.";
}

echo "</body></html>";
?>
