<?php
declare(strict_types=1);

require __DIR__ . '/core/helpers.php';

spl_autoload_register(static function (string $class): void {
    $prefix = 'App\\';
    if (! str_starts_with($class, $prefix)) {
        return;
    }

    $relative = substr($class, strlen($prefix));
    $path = null;

    if (str_starts_with($relative, 'Core\\')) {
        $path = __DIR__ . '/core/' . str_replace('\\', '/', substr($relative, strlen('Core\\'))) . '.php';
    } elseif (str_starts_with($relative, 'Modules\\PublicArea\\')) {
        $path = __DIR__ . '/src/modules/public/' . str_replace('\\', '/', substr($relative, strlen('Modules\\PublicArea\\'))) . '.php';
    } elseif (str_starts_with($relative, 'Modules\\Admin\\')) {
        $path = __DIR__ . '/src/modules/admin/' . str_replace('\\', '/', substr($relative, strlen('Modules\\Admin\\'))) . '.php';
    } else {
        $path = __DIR__ . '/core/' . str_replace('\\', '/', $relative) . '.php';
    }

    if ($path !== null && is_file($path)) {
        require $path;
        return;
    }
});

use App\Core\Config;
use App\Core\Database;
use App\Core\Env;
use App\Core\Request;
use App\Core\Router;
use App\Core\SecurityHeaders;
use App\Core\Session;
use App\Core\View;

Env::load(__DIR__ . '/.env');

Config::set([
    'app' => require __DIR__ . '/config/app.php',
    'database' => require __DIR__ . '/config/database.php',
    'routes' => require __DIR__ . '/config/routes.php',
]);

Session::start(Config::get('app.session'));
SecurityHeaders::send();
Database::connection();
App\Core\Auth::enforceTimeout((int) Config::get('app.session.lifetime', 1800));

$router = new Router(Config::get('routes'));
$response = $router->dispatch(Request::capture());

if (is_string($response)) {
    echo $response;
    return;
}

if ($response instanceof View) {
    echo $response->render();
}
