<?php
// Secure session cookie configuration (must be set before session_start)
$isHttps = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
    || (($_SERVER['SERVER_PORT'] ?? null) == 443)
    || strtolower((string)($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '')) === 'https';

session_set_cookie_params([
    'lifetime' => 0,
    'path'     => '/',
    'secure'   => $isHttps,
    'httponly' => true,
    // 'Lax' (not 'Strict') is required so the session cookie is sent when
    // the user returns from a cross-site OAuth redirect (e.g. Google Sheets).
    // 'Strict' would drop the cookie on that redirect, breaking the OAuth flow.
    'samesite' => 'Lax',
]);

session_start();

if (!defined('ROOT_PATH')) {
    define('ROOT_PATH', __DIR__);
}

if (!defined('APP_BASE')) {
    define('APP_BASE', __DIR__);
}

spl_autoload_register(function ($class) {
    $class = ltrim($class, '\\');

    $relativePath = str_replace('\\', '/', $class) . '.php';
    $relativePath = str_replace(
        ['Core/', 'System/', 'App/'],
        ['core/', 'system/', 'app/'],
        $relativePath
    );

    $file = APP_BASE . '/' . $relativePath;

    if (file_exists($file)) {
        require_once $file;
    }
});

use Core\System\App;
use Core\System\Env;
use Core\System\PageCache;

Env::bootstrap(ROOT_PATH);
define('APP_DEBUG', Env::isDebug());

if (APP_DEBUG) {
    ini_set('display_errors', '1');
    error_reporting(E_ALL);
} else {
    ini_set('display_errors', '0');
    ini_set('log_errors', '1');
    error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT);
}

PageCache::init();

$app = new App();
$app->boot();
