<?php

use Illuminate\Foundation\Application;
use Illuminate\Http\Request;

define('LARAVEL_START', microtime(true));

// ─────────────────────────────────────────────────────────────
// HELPER: Show a styled error page
// ─────────────────────────────────────────────────────────────
function showError(string $title, string $message, array $steps = [], string $badge = 'DEPLOYMENT ERROR'): never
{
    http_response_code(500);
    ?>
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>500 — <?= htmlspecialchars($title) ?></title>
<style>
    body{font-family:system-ui,sans-serif;background:#0f172a;color:#e2e8f0;display:flex;justify-content:center;align-items:center;min-height:100vh;margin:0;padding:1rem}
    .card{max-width:680px;width:100%;background:#1e293b;border-radius:24px;padding:2.5rem;border:1px solid #334155;box-shadow:0 25px 50px -12px #00000080}
    h1{font-size:1.4rem;color:#fb7185;margin:0 0 .75rem}
    p{color:#94a3b8;line-height:1.6;margin:0 0 1rem;font-size:.9rem}
    code{background:#0f172a;color:#a5b4fc;padding:2px 6px;border-radius:4px;font-size:.85rem}
    .path{background:#0f172a;border:1px solid #334155;border-radius:12px;padding:1rem;font-family:monospace;font-size:.85rem;color:#e2e8f0;margin:1rem 0;word-break:break-all;overflow:auto}
    .steps{background:#0f172a;border-radius:12px;padding:1rem 1rem 1rem 2rem;margin:1rem 0;border:1px solid #334155}
    .steps li{margin-bottom:.5rem;color:#94a3b8;font-size:.85rem}
    .steps li:last-child{margin-bottom:0}
    .badge{display:inline-block;background:#4c0519;color:#fb7185;padding:2px 12px;border-radius:999px;font-size:.75rem;font-weight:600;margin-bottom:1rem}
    .btn{display:inline-block;background:#1e40af;color:#fff;padding:10px 24px;border-radius:12px;text-decoration:none;font-weight:600;font-size:.9rem;margin-top:.5rem}
    .btn:hover{background:#2563eb}
</style>
</head>
<body>
<div class="card">
    <div class="badge"><?= htmlspecialchars($badge) ?></div>
    <h1><?= htmlspecialchars($title) ?></h1>
    <p><?= nl2br(htmlspecialchars($message)) ?></p>
    <?php if (!empty($steps)): ?>
    <ol class="steps">
        <?php foreach ($steps as $step): ?>
        <li><?= $step ?></li>
        <?php endforeach; ?>
    </ol>
    <?php endif; ?>
    <a class="btn" href="server-check.php">Run Diagnostic (server-check.php)</a>
</div>
</body>
</html>
    <?php
    die;
}

// ─────────────────────────────────────────────────────────────
// PRE-FLIGHT 1: Check vendor/autoload.php
// ─────────────────────────────────────────────────────────────
$autoloadPath = __DIR__.'/../vendor/autoload.php';
if (!file_exists($autoloadPath)) {
    showError(
        'Composer Dependencies Missing',
        'The vendor/autoload.php file was not found. Laravel requires Composer dependencies to run.',
        [
            '<strong>On your local PC:</strong> Open a terminal in the project folder and run: <code>composer install --no-dev --optimize-autoloader</code>',
            '<strong>Then re-upload</strong> the entire <code>vendor/</code> folder to your cPanel via File Manager or FTP',
            '<strong>Or via SSH on cPanel:</strong> <code>cd ' . htmlspecialchars(dirname(__DIR__)) . ' && composer install --no-dev --optimize-autoloader</code>',
        ]
    );
}

// ─────────────────────────────────────────────────────────────
// PRE-FLIGHT 2: Check storage directory
// ─────────────────────────────────────────────────────────────
$storageDir = __DIR__.'/../storage';
if (!is_dir($storageDir)) {
    @mkdir($storageDir, 0755, true);
}

// ─────────────────────────────────────────────────────────────
// PRE-FLIGHT 3: Check bootstrap/cache directory
// ─────────────────────────────────────────────────────────────
$cacheDir = __DIR__.'/../bootstrap/cache';
if (!is_dir($cacheDir)) {
    @mkdir($cacheDir, 0755, true);
}

// Determine if the application is in maintenance mode...
if (file_exists($maintenance = $storageDir.'/framework/maintenance.php')) {
    require $maintenance;
}

// Register the Composer autoloader...
require $autoloadPath;

// ─────────────────────────────────────────────────────────────
// Bootstrap Laravel with error catching
// ─────────────────────────────────────────────────────────────
try {
    /** @var Application $app */
    $app = require_once __DIR__.'/../bootstrap/app.php';

    $app->handleRequest(Request::capture());
} catch (Throwable $e) {
    $message = $e->getMessage();
    $file = $e->getFile();
    $line = $e->getLine();

    // Determine the most likely fix based on the error
    $steps = [];
    $badge = 'LARAVEL ERROR';

    if (str_contains($message, 'No application encryption key')) {
        $title = 'APP_KEY Missing';
        $msg = "Laravel encryption key is not set.\n\nError: {$message}";
        $steps = [
            'The installer will auto-generate the APP_KEY. But first, make sure the <code>.env</code> file exists.',
            'If <code>.env</code> is missing: copy <code>.env.example</code> to <code>.env</code> in your project root.',
            'If the issue persists, add this to your <code>.env</code> file: <code>APP_KEY=base64:0/IjI5crJj4wxwxk0Q/a712HwDRgD5dVfHpN7j+MJ/U=</code>',
        ];
    } elseif (str_contains($message, 'could not find driver') || str_contains($message, 'SQLSTATE')) {
        $title = 'Database Connection Error';
        $msg = "Laravel cannot connect to the database.\n\nError: {$message}";
        $steps = [
            'Go to cPanel → MySQL Databases and create a database + user.',
            'Edit your <code>.env</code> file and update: <code>DB_DATABASE</code>, <code>DB_USERNAME</code>, <code>DB_PASSWORD</code>',
            'Or use the installer at <a href="install" style="color:#818cf8">/install</a> — step 3 will ask for DB credentials.',
        ];
    } elseif (str_contains($message, 'putenv') || str_contains($message, 'putenv()')) {
        $title = 'PHP putenv() Disabled';
        $msg = "Your hosting has disabled the putenv() function which Laravel needs.\n\nError: {$message}";
        $steps = [
            'Contact your hosting provider and ask them to enable <code>putenv</code> in PHP settings.',
            'Or in cPanel → Select PHP Version → Extensions, make sure no function is disabled.',
        ];
    } elseif (str_contains($message, 'Allowed memory size')) {
        $title = 'PHP Memory Limit Exceeded';
        $msg = "Laravel needs more memory.\n\nError: {$message}";
        $steps = [
            'In cPanel → Select PHP Version → switch to "Options" tab.',
            'Increase <code>memory_limit</code> to at least <strong>128M</strong> (256M recommended).',
        ];
    } elseif (str_contains($message, 'Maximum execution time')) {
        $title = 'PHP Execution Time Too Low';
        $msg = "The PHP max_execution_time is too low.\n\nError: {$message}";
        $steps = [
            'In cPanel → Select PHP Version → Options tab.',
            'Increase <code>max_execution_time</code> to at least <strong>120</strong>.',
        ];
    } else {
        $title = 'Laravel Boot Error';
        $msg = "An unexpected error occurred while Laravel was starting.\n\n{$message}\n\nFile: {$file}:{$line}";
        $steps = [
            'Check your cPanel "Error Log" for more details.',
            'Run <a href="server-check.php" style="color:#818cf8">server-check.php</a> for a full system diagnostic.',
            'Contact support with the error details above.',
        ];
    }

    showError($title, $msg, $steps, $badge);
}
