<?php

declare(strict_types=1);

require_once __DIR__ . '/helpers.php';

spl_autoload_register(function (string $class): void {
    $prefixes = [
        'App\\' => __DIR__ . '/',
    ];

    foreach ($prefixes as $prefix => $baseDir) {
        if (substr($class, 0, strlen($prefix)) === $prefix) {
            $relativeClass = substr($class, strlen($prefix));
            $file = $baseDir . str_replace('\\', DIRECTORY_SEPARATOR, $relativeClass) . '.php';
            if (is_file($file)) {
                require_once $file;
            }
        }
    }
});

App\Core\Env::load(base_path('.env'));

date_default_timezone_set((string) env('APP_TIMEZONE', 'Asia/Riyadh'));

ini_set('session.cookie_httponly', '1');
ini_set('session.cookie_samesite', 'Strict');
if ((string) env('APP_ENV', 'local') !== 'local') {
    ini_set('session.cookie_secure', '1');
}

App\Core\Session::start();

set_exception_handler(function (Throwable $e): void {
    $debug = filter_var(env('APP_DEBUG', 'false'), FILTER_VALIDATE_BOOLEAN);
    $logDir = storage_path('logs');
    if (!is_dir($logDir)) {
        mkdir($logDir, 0775, true);
    }
    error_log('[' . date('c') . '] ' . $e . PHP_EOL, 3, $logDir . '/app.log');

    http_response_code(500);
    if ($debug) {
        echo '<pre style="direction:ltr;text-align:left;white-space:pre-wrap">' . e((string) $e) . '</pre>';
        return;
    }

    App\Core\View::render('errors/500', [
        'title' => 'خطأ في النظام',
    ]);
});
