<?php

declare(strict_types=1);

// CORS safety net at entrypoint level (still applies when router/bootstrap fails).
$origin = trim((string) ($_SERVER['HTTP_ORIGIN'] ?? ''));
if ($origin !== '') {
    $requestHost = strtolower((string) preg_replace('/:\d+$/', '', (string) ($_SERVER['HTTP_HOST'] ?? '')));
    $originHost = strtolower((string) (parse_url($origin, PHP_URL_HOST) ?? ''));
    $originHost = (string) preg_replace('/:\d+$/', '', $originHost);

    $isAllowedLocalOrigin = preg_match('#^https?://(localhost|127\.0\.0\.1)(:\d+)?$#i', $origin) === 1;
    $isAllowedSameSiteOrigin = $requestHost !== ''
        && $originHost !== ''
        && (
            $originHost === $requestHost
            || $originHost === ('www.' . $requestHost)
            || ('www.' . $originHost) === $requestHost
        );

    if ($isAllowedLocalOrigin || $isAllowedSameSiteOrigin) {
        header('Access-Control-Allow-Origin: ' . $origin);
        header('Access-Control-Allow-Credentials: true');
        header('Vary: Origin');
    }
}
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
header('Access-Control-Max-Age: 600');

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'OPTIONS') {
    http_response_code(204);
    exit;
}

try {
    require_once dirname(__DIR__) . '/app/bootstrap.php';
    require_once base_path('app/http/router.php');

    handle_request();
} catch (Throwable $exception) {
    $debugRaw = getenv('APP_DEBUG');
    $debug = $debugRaw === false ? true : $debugRaw === '1';

    http_response_code(500);
    header('Content-Type: application/json; charset=utf-8');

    echo json_encode([
        'success' => false,
        'error' => $debug ? $exception->getMessage() : 'Erreur serveur.',
        'details' => $debug ? [
            'type' => get_class($exception),
        ] : [],
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
