<?php

$path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);
$path = is_string($path) ? $path : '/';
$documentRoot = realpath((string) ($_SERVER['DOCUMENT_ROOT'] ?? ''));
$applicationRoot = realpath(dirname(__DIR__));
$publicRoot = realpath(__DIR__);
$basePath = '';

if ($documentRoot && $publicRoot && $documentRoot !== $publicRoot && $applicationRoot) {
    if ($documentRoot === $applicationRoot) {
        $basePath = '';
    } elseif (str_starts_with($applicationRoot, rtrim($documentRoot, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR)) {
        $basePath = '/' . trim(substr($applicationRoot, strlen($documentRoot)), DIRECTORY_SEPARATOR);
    }
}

$publicPath = $path;
if ($basePath !== '' && ($publicPath === $basePath || str_starts_with($publicPath, $basePath . '/'))) {
    $publicPath = substr($publicPath, strlen($basePath)) ?: '/';
}

$file = realpath(__DIR__ . '/' . ltrim($publicPath, '/'));
$isPublicFile = $file
    && $publicRoot
    && str_starts_with($file, rtrim($publicRoot, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR)
    && is_file($file);

if ($publicPath !== '/' && $isPublicFile) {
    if ($documentRoot === $publicRoot) {
        return false;
    }

    $contentTypes = [
        'css' => 'text/css; charset=UTF-8',
        'js' => 'application/javascript; charset=UTF-8',
        'json' => 'application/json; charset=UTF-8',
        'png' => 'image/png',
        'jpg' => 'image/jpeg',
        'jpeg' => 'image/jpeg',
        'gif' => 'image/gif',
        'svg' => 'image/svg+xml',
        'webp' => 'image/webp',
        'ico' => 'image/x-icon',
    ];
    $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
    header('Content-Type: ' . ($contentTypes[$extension] ?? 'application/octet-stream'));
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}

require __DIR__ . '/index.php';
