<?php
declare(strict_types=1);

use App\Core\Config;
use App\Core\Router;

$appRoot = __DIR__;

spl_autoload_register(function (string $class) use ($appRoot) {
    if (strpos($class, 'App\\') !== 0) return;
    $relative = substr($class, strlen('App\\'));
    $file = $appRoot . '/' . str_replace('\\', '/', $relative) . '.php';
    if (is_file($file)) require $file;
});

require $appRoot . '/Core/helpers.php';

Config::load();
date_default_timezone_set(Config::get('app.timezone', 'UTC'));

if (Config::get('app.debug')) {
    ini_set('display_errors', '1');
    error_reporting(E_ALL);
} else {
    ini_set('display_errors', '0');
    error_reporting(E_ALL & ~E_DEPRECATED & ~E_NOTICE);
}

set_exception_handler(function (Throwable $e) {
    error_log($e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine());
    http_response_code(500);
    if (Config::get('app.debug')) {
        echo '<pre style="padding:20px;background:#1e1e1e;color:#f87171;white-space:pre-wrap">';
        echo htmlspecialchars($e->getMessage() . "\n\n" . $e->getTraceAsString());
        echo '</pre>';
    } else {
        echo '<!doctype html><html><body style="font-family:sans-serif;padding:40px"><h1>Something went wrong</h1><p>Please try again, or contact your administrator if the problem continues.</p></body></html>';
    }
});

$router = new Router();
require $appRoot . '/routes.php';

return $router;
