<?php

declare(strict_types=1);

// Managed by ProAutoSites domain provisioning. Dealer code remains in the shared web66 application.
$sharedPrivate = '/var/www/clients/client0/web66/private';
$sharedWeb = dirname($sharedPrivate) . '/web';
$requestPath = rawurldecode((string) (parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/'));
$relativePath = ltrim(str_replace('\\', '/', $requestPath), '/');
$isSharedAsset = str_starts_with($relativePath, 'assets/');
$isFavicon = $relativePath === 'favicon.ico';

if ($isSharedAsset || $isFavicon) {
    $target = realpath($sharedWeb . '/' . $relativePath);
    $assetRoot = realpath($sharedWeb . '/assets');
    $allowed = $target !== false && is_file($target)
        && (($isSharedAsset && $assetRoot !== false && str_starts_with($target, $assetRoot . DIRECTORY_SEPARATOR))
            || ($isFavicon && $target === realpath($sharedWeb . '/favicon.ico')));

    if (!$allowed) {
        http_response_code(404);
        exit('Not Found');
    }

    $mime = match (strtolower(pathinfo($target, PATHINFO_EXTENSION))) {
        'css' => 'text/css; charset=UTF-8',
        'js' => 'application/javascript; charset=UTF-8',
        'json' => 'application/json; charset=UTF-8',
        'svg' => 'image/svg+xml',
        'png' => 'image/png',
        'jpg', 'jpeg' => 'image/jpeg',
        'gif' => 'image/gif',
        'webp' => 'image/webp',
        'ico' => 'image/x-icon',
        'woff' => 'font/woff',
        'woff2' => 'font/woff2',
        default => null,
    };
    if ($mime === null) {
        $detectedMime = function_exists('mime_content_type') ? mime_content_type($target) : false;
        $mime = is_string($detectedMime) && $detectedMime !== '' ? $detectedMime : 'application/octet-stream';
    }

    header('Content-Type: ' . $mime);
    header('Content-Length: ' . (string) filesize($target));
    header('Cache-Control: public, max-age=604800, immutable');
    header('X-Content-Type-Options: nosniff');
    readfile($target);
    exit;
}

require_once $sharedPrivate . '/app/bootstrap.php';

use App\Services\Router;

$router = new Router();

require base_path('routes/api.php');
require base_path('routes/web.php');

send_security_headers();

try {
    $router->dispatch($_SERVER['REQUEST_METHOD'] ?? 'GET', $_SERVER['REQUEST_URI'] ?? '/');
} finally {
    if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
        $_SESSION['_old'] = $_POST;
    }

    clear_flash();
}