<?php

declare(strict_types=1);

require_once __DIR__ . '/Core/AppConfiguration.php';
AppConfiguration::initializePhpTimezone();

function app_base_path(): string
{
    static $basePath;

    if ($basePath !== null) {
        return $basePath;
    }

    $scriptName = str_replace('\\', '/', $_SERVER['SCRIPT_NAME'] ?? '');
    $indexPath = '/index.php';

    if ($scriptName === $indexPath) {
        $basePath = '';
        return $basePath;
    }

    if (str_ends_with($scriptName, $indexPath)) {
        $basePath = substr($scriptName, 0, -strlen($indexPath));
        return $basePath === '/' ? '' : rtrim($basePath, '/');
    }

    $basePath = rtrim(dirname($scriptName), '/.');
    return $basePath === '/' ? '' : $basePath;
}

function app_url(string $path = '/'): string
{
    $normalizedPath = '/' . ltrim($path, '/');
    $basePath = app_base_path();

    if ($normalizedPath === '/') {
        return $basePath === '' ? '/' : $basePath . '/';
    }

    return ($basePath === '' ? '' : $basePath) . $normalizedPath;
}

$requestPath = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';
$basePath = app_base_path();

if ($basePath !== '' && str_starts_with($requestPath, $basePath)) {
    $requestPath = substr($requestPath, strlen($basePath));
}

$requestPath = '/' . trim($requestPath, '/');
if ($requestPath === '//') {
    $requestPath = '/';
}

$routes = require __DIR__ . '/routes.php';
$route = $routes[$requestPath] ?? null;

if ($route === null) {
    http_response_code(404);
echo '<!doctype html><html lang="en"><head><meta charset="utf-8"><title>404 | BEAM</title></head><body><h1>404</h1><p>Page not found.</p></body></html>';
    exit;
}

require_once __DIR__ . '/Core/Authentication.php';

$authentication = new Authentication();
$authentication->authorizeViewAccess($requestPath);

require $route;
