<?php
define('ROOT', __DIR__);

// Autoloader — mapeia namespaces para ficheiros
spl_autoload_register(function(string $class) {
    $map = [
        'App\\Core\\'               => ROOT . '/app/Core/',
        'App\\Middleware\\'         => ROOT . '/app/Middleware/',
        'App\\Models\\'             => ROOT . '/app/Models/Models.php',
        'App\\Controllers\\Admin\\' => ROOT . '/app/Controllers/AdminControllers.php',
        'App\\Controllers\\'        => ROOT . '/app/Controllers/PublicControllers.php',
    ];

    foreach ($map as $prefix => $target) {
        if (!str_starts_with($class, $prefix)) continue;

        if (str_ends_with($target, '.php')) {
            // Ficheiro combinado — carrega o ficheiro todo
            if (file_exists($target)) require_once $target;
            return;
        }

        // Ficheiro individual — constrói o caminho
        $file = $target . str_replace('\\', '/', substr($class, strlen($prefix))) . '.php';
        if (file_exists($file)) require_once $file;
        return;
    }
});

require_once ROOT . '/app/Core/helpers.php';

// Nonce CSP — gerado uma vez por request
$_GLOBALS_CSP_NONCE = base64_encode(random_bytes(16));

session_start([
    'cookie_httponly' => true,
    'cookie_samesite' => 'Lax',
    'cookie_secure'   => isset($_SERVER['HTTPS']),
    'gc_maxlifetime'  => 7200,
    'use_strict_mode' => true,
]);

// Headers de segurança
\App\Core\Security::sendHeaders();

if (config('app.debug')) { ini_set('display_errors',1); error_reporting(E_ALL); }
else { ini_set('display_errors',0); error_reporting(0); }

date_default_timezone_set(config('app.timezone','Europe/Lisbon'));

// Migrações automáticas
static $migrated = false;
if (!$migrated) {
    try { require_once ROOT.'/database/migrations.php'; runMigrations(); $migrated=true; }
    catch(\Throwable $e) { if(config('app.debug')) die('Migration: '.$e->getMessage()); }
}

// Guardar dados do formulário só em POST (não apagar em redirects GET)
if (!empty($_POST)) {
    $_SESSION['_old'] = $_POST;
} elseif (!isset($_SESSION['_old'])) {
    $_SESSION['_old'] = [];
}

$method = $_POST['_method'] ?? $_SERVER['REQUEST_METHOD'];
$uri    = $_SERVER['REQUEST_URI'];
$base   = parse_url(config('app.url'), PHP_URL_PATH) ?? '';
if ($base && str_starts_with($uri, $base)) $uri = substr($uri, strlen($base));

$router = require ROOT . '/routes/web.php';
$router->dispatch($method, $uri ?: '/');
