<?php
declare(strict_types=1);

foreach ([(dirname(__DIR__) . '/.env'), (dirname(__DIR__) . '/.env.example')] as $envFile) {
    if (file_exists($envFile)) {
        foreach (file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
            $line = trim($line);
            if ($line === '' || $line[0] === '#' || strpos($line, '=') === false) continue;
            [$k, $v] = explode('=', $line, 2);
            $_ENV[trim($k)] = trim($v);
        }
        if ($envFile !== dirname(__DIR__) . '/.env') break;
    }
}

date_default_timezone_set($_ENV['APP_TZ'] ?? 'Asia/Muscat');

$debug = (($_ENV['APP_DEBUG'] ?? '0') === '1') || isset($_GET['debug']);
ini_set('display_errors', $debug ? '1' : '0');
ini_set('log_errors', '1');
error_reporting(E_ALL);

session_set_cookie_params([
    'httponly' => true,
    'samesite' => 'Lax',
]);
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

header('X-Frame-Options: SAMEORIGIN');
header('X-Content-Type-Options: nosniff');
header('Referrer-Policy: strict-origin-when-cross-origin');
header("Content-Security-Policy: default-src 'self' 'unsafe-inline' 'unsafe-eval' data: https:;");

spl_autoload_register(function (string $class): void {
    $prefix = 'App\\';
    if (strpos($class, $prefix) !== 0) return;
    $relative = str_replace('\\', '/', substr($class, strlen($prefix)));
    $file = __DIR__ . '/' . $relative . '.php';
    if (file_exists($file)) require_once $file;
});

require_once __DIR__ . '/helpers.php';

set_exception_handler(function (Throwable $e) use ($debug) {
    error_log('[FAKHR][EXCEPTION] ' . $e);
    http_response_code(500);
    if ($debug) {
        include __DIR__ . '/Views/errors/500_debug.php';
    } else {
        echo '<h2>Application Error</h2><p>حدث خطأ داخلي في النظام.</p>';
    }
    exit;
});

register_shutdown_function(function () use ($debug) {
    $error = error_get_last();
    if (!$error || !in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR], true)) return;
    http_response_code(500);
    if ($debug) {
        $fatalError = $error;
        include __DIR__ . '/Views/errors/500_fatal.php';
    } else {
        echo '<h2>Fatal Error</h2><p>حدث خطأ داخلي في النظام.</p>';
    }
});
