<?php

declare(strict_types=1);

require __DIR__ . '/../vendor/autoload.php';

$requestUri = (string) ($_SERVER['REQUEST_URI'] ?? '/');
$requestPath = parse_url($requestUri, PHP_URL_PATH);
$requestPath = is_string($requestPath) ? trim($requestPath, '/') : '';

if ($requestPath !== '' && servePublicFile($requestPath)) {
    return;
}

$container = App\Bootstrap::boot()
    ->createContainer();

$requestPath = is_string($requestPath) ? strtolower(trim($requestPath, '/')) : '';
$requestMethod = strtoupper((string) ($_SERVER['REQUEST_METHOD'] ?? 'GET'));
$requiresEarlySession = $requestMethod !== 'GET'
    && $requestMethod !== 'HEAD';
$requiresEarlySession = $requiresEarlySession
    || $requestPath === 'kontakt'
    || str_starts_with($requestPath, 'admin')
    || isset($_GET[Nette\Application\UI\Presenter::FlashKey]);

$session = $container->getByType(Nette\Http\Session::class);
if ($requiresEarlySession && !$session->isStarted()) {
    $session->start();
}

$container->getByType(Nette\Application\Application::class)->run();

function servePublicFile(string $publicPath): bool
{
    if (str_contains($publicPath, '..')) {
        return false;
    }

    $fullPath = realpath(__DIR__ . '/' . ltrim($publicPath, '/'));
    $publicRoot = realpath(__DIR__);
    if (!is_string($fullPath) || !is_string($publicRoot) || !str_starts_with($fullPath, $publicRoot . DIRECTORY_SEPARATOR) || !is_file($fullPath) || !is_readable($fullPath)) {
        return false;
    }

    $extension = strtolower((string) pathinfo($fullPath, PATHINFO_EXTENSION));
    $contentTypes = [
        'css' => 'text/css; charset=UTF-8',
        'gif' => 'image/gif',
        'ico' => 'image/x-icon',
        'js' => 'application/javascript; charset=UTF-8',
        'jpg' => 'image/jpeg',
        'jpeg' => 'image/jpeg',
        'json' => 'application/json; charset=UTF-8',
        'pdf' => 'application/pdf',
        'png' => 'image/png',
        'svg' => 'image/svg+xml',
        'txt' => 'text/plain; charset=UTF-8',
        'webmanifest' => 'application/manifest+json; charset=UTF-8',
        'webp' => 'image/webp',
        'xml' => 'application/xml; charset=UTF-8',
    ];

    header('Content-Type: ' . ($contentTypes[$extension] ?? 'application/octet-stream'));
    header('Content-Length: ' . (string) filesize($fullPath));
    header('Cache-Control: public, max-age=604800');
    readfile($fullPath);

    return true;
}
