<?php

declare(strict_types=1);

define('BASE_PATH', dirname(__DIR__) . '/private/civigo');

$uri = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';
$staticPath = __DIR__ . $uri;
if (PHP_SAPI === 'cli-server' && is_file($staticPath)) {
    return false;
}

require BASE_PATH . '/app/helpers.php';

date_default_timezone_set((string) config('app.timezone', 'Europe/Sofia'));
ini_set('session.cookie_httponly', '1');
ini_set('session.cookie_samesite', 'Lax');
session_name((string) config('security.session_name', 'civigo_session'));
session_start();

spl_autoload_register(static function (string $class): void {
    $prefix = 'App\\';

    if (!str_starts_with($class, $prefix)) {
        return;
    }

    $relative = substr($class, strlen($prefix));
    $path = BASE_PATH . '/app/' . str_replace('\\', '/', $relative) . '.php';

    if (is_file($path)) {
        require $path;
    }
});

if (is_file(BASE_PATH . '/vendor/autoload.php')) {
    require BASE_PATH . '/vendor/autoload.php';
}

$router = require BASE_PATH . '/config/routes.php';

try {
    echo $router->dispatch($_SERVER['REQUEST_METHOD'] ?? 'GET', $uri);
} catch (Throwable $exception) {
    http_response_code(500);

    if (config('app.debug')) {
        echo '<pre style="white-space:pre-wrap;font:14px/1.5 monospace;padding:24px">' . e($exception->getMessage() . "\n" . $exception->getTraceAsString()) . '</pre>';
        exit;
    }

    echo 'Възникна грешка. Моля, опитайте отново.';
}
