<?php

use Illuminate\Http\Request;

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

if (file_exists($maintenance = __DIR__.'/../storage/framework/maintenance.php')) {
    require $maintenance;
}

$autoload = __DIR__.'/../vendor/autoload.php';
if (!file_exists($autoload)) {
    http_response_code(503);
    header('Content-Type: text/html; charset=utf-8');
    echo '<!DOCTYPE html><html><head><meta charset="utf-8"><title>Setup required</title></head><body style="font-family:sans-serif;max-width:600px;margin:50px auto;padding:20px;">';
    $dir = dirname(__DIR__);
    echo '<h1>Setup required</h1><p>Run:</p><pre style="background:#f5f5f5;padding:15px;">cd '.$dir."\n".'composer install</pre></body></html>';
    exit;
}
require $autoload;

$app = require_once __DIR__.'/../bootstrap/app.php';

// When app is in a subdirectory, strip base path so routes like /api/health match
$scriptName = $_SERVER['SCRIPT_NAME'] ?? '';
$basePath = str_replace('\\', '/', dirname($scriptName));
if ($basePath !== '/' && $basePath !== '' && isset($_SERVER['REQUEST_URI'])) {
    $uri = $_SERVER['REQUEST_URI'];
    $query = '';
    if (strpos($uri, '?') !== false) {
        $query = substr($uri, strpos($uri, '?'));
        $uri = substr($uri, 0, strpos($uri, '?'));
    }
    if (strpos($uri, $basePath) === 0) {
        $_SERVER['REQUEST_URI'] = (substr($uri, strlen($basePath)) ?: '/') . $query;
    }
}
// When using index.php/route (e.g. no mod_rewrite), strip /index.php so Laravel sees /route
$uri = $_SERVER['REQUEST_URI'] ?? '/';
if (strpos($uri, '/index.php') === 0) {
    $q = strpos($uri, '?');
    $path = $q !== false ? substr($uri, 0, $q) : $uri;
    $path = substr($path, strlen('/index.php')) ?: '/';
    $_SERVER['REQUEST_URI'] = $path . ($q !== false ? substr($uri, $q) : '');
}

$app->handleRequest(Request::capture());
