<?php
/**
 * Zabibu Residence - Front Controller
 */

define('ROOT_PATH', dirname(__DIR__));

// Autoloader
spl_autoload_register(function (string $class): void {
    $class = str_replace('\\', DIRECTORY_SEPARATOR, $class);
    $paths = [
        ROOT_PATH . DIRECTORY_SEPARATOR . $class . '.php',
        ROOT_PATH . DIRECTORY_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . $class . '.php',
    ];
    foreach ($paths as $path) {
        if (file_exists($path)) {
            require_once $path;
            return;
        }
    }
    // Handle App\ namespace
    $baseNamespace = 'App' . DIRECTORY_SEPARATOR;
    if (str_starts_with($class, $baseNamespace)) {
        $file = ROOT_PATH . DIRECTORY_SEPARATOR . 'app' . DIRECTORY_SEPARATOR .
                substr($class, strlen($baseNamespace)) . '.php';
        if (file_exists($file)) require_once $file;
    }
});

// Bootstrap
require_once ROOT_PATH . '/config/config.php';

// Session
$isHttps = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
        || (($_SERVER['SERVER_PORT'] ?? 80) == 443)
        || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https');

ini_set('session.cookie_httponly', 1);
ini_set('session.use_strict_mode', 1);
ini_set('session.cookie_samesite', 'Lax');
ini_set('session.gc_maxlifetime', SESSION_LIFETIME);
ini_set('session.cookie_lifetime', 0);
if ($isHttps) {
    ini_set('session.cookie_secure', 1);
}
session_name(SESSION_NAME);
session_start();

// Error handling
if (APP_DEBUG) {
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
} else {
    error_reporting(0);
    ini_set('display_errors', 0);
}

// Load routes
$router = new Core\Router();
require_once ROOT_PATH . '/routes/web.php';
require_once ROOT_PATH . '/routes/api.php';

$router->dispatch();
