<?php

use Illuminate\Http\Request;
use Illuminate\Contracts\Http\Kernel;

// Define the Laravel start time
define('LARAVEL_START', microtime(true));

// Core path definition
$corePath = __DIR__ . '/core';

/**
 * --------------------------------------------
 * ✅ Maintenance Mode Check (Early Exit)
 * --------------------------------------------
 */
if (file_exists($maintenance = $corePath . '/storage/framework/maintenance.php')) {
    require $maintenance;
    exit;
}

/**
 * --------------------------------------------
 * ✅ Load Composer Autoloader with optimized classmap
 * --------------------------------------------
 */
$autoloadPath = $corePath . '/vendor/autoload.php';
if (!file_exists($autoloadPath)) {
    http_response_code(500);
    echo "Autoload file not found. Did you run 'composer install'?";
    exit;
}
require $autoloadPath;

/**
 * --------------------------------------------
 * ✅ Opcache Preloading for Critical Files
 * --------------------------------------------
 */
if (function_exists('opcache_compile_file')) {
    opcache_compile_file($corePath . '/bootstrap/app.php');
    opcache_compile_file($autoloadPath);
}

/**
 * --------------------------------------------
 * ✅ Bootstrap Laravel Application
 * --------------------------------------------
 */
$appPath = $corePath . '/bootstrap/app.php';
if (!file_exists($appPath)) {
    http_response_code(500);
    echo "Application bootstrap file not found. Path: $appPath";
    exit;
}
$app = require_once $appPath;

/**
 * --------------------------------------------
 * ✅ Kernel Initialization with Error Handling
 * --------------------------------------------
 */
try {
    $kernel = $app->make(Kernel::class);
} catch (Exception $e) {
    http_response_code(500);
    echo "Failed to initialize Kernel: " . $e->getMessage();
    exit;
}

/**
 * --------------------------------------------
 * ✅ Request Handling (FastCGI optimization if available)
 * --------------------------------------------
 */
$request = Request::capture();

try {
    if (function_exists('fastcgi_finish_request')) {
        $response = $kernel->handle($request);
        $response->send();
        fastcgi_finish_request();
        $kernel->terminate($request, $response);
    } else {
        $response = $kernel->handle($request);
        $response->send();
        $kernel->terminate($request, $response);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo "Error processing request: " . $e->getMessage();
    exit;
}

/**
 * --------------------------------------------
 * ✅ Memory Cleanup
 * --------------------------------------------
 */
unset($kernel, $request, $response);

