<?php

// ---------------------------------------------------------------------------
// SiteCake bootstrap — pure PHP, no Composer / Silex / Symfony dependencies
// ---------------------------------------------------------------------------

// 1. Load custom PSR-4 autoloader (replaces vendor/autoload.php)
require __DIR__ . '/../src/autoload.php';

use Sitecake\Container;
use Sitecake\Error\ErrorHandler;
use Sitecake\Log\Formatter\PathReplaceFormatter;
use Sitecake\Log\SimpleLogger;

// 2. Create the DI container (replaces Silex\Application / Pimple\Container)
$app = new Container();

// 3. Detect environment
if (defined('SITECAKE_ENVIRONMENT') && in_array(SITECAKE_ENVIRONMENT, ['prod', 'dev', 'test'], true)) {
    $app['environment'] = SITECAKE_ENVIRONMENT;
} else {
    $app['environment'] = 'prod';
}

// 4. Check system requirements (PHP version, extensions, permissions)
if (in_array($app['environment'], ['prod', 'dev'], true)) {
    require __DIR__ . '/requirements.php';
}

// 5. Version constant — stamped by build-release.sh
define('SITECAKE_VERSION', "4.0.21");

// 6. CORS headers — only reflect the origin when it matches the site's own host (HIGH-1)
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
$host   = $_SERVER['HTTP_HOST'] ?? '';
if ($origin && parse_url($origin, PHP_URL_HOST) === $host) {
    header('Access-Control-Allow-Origin: ' . $origin);
    header('Vary: Origin');
} else {
    $scheme = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http';
    header('Access-Control-Allow-Origin: ' . $scheme . '://' . $host);
}
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, X-Requested-With, X-CSRF-Token');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

// Security headers (MED-5 + MED-6)
if ($_SERVER['REQUEST_METHOD'] !== 'OPTIONS') {
    header('X-Content-Type-Options: nosniff');
    header('X-Frame-Options: SAMEORIGIN');
    header('Referrer-Policy: strict-origin-when-cross-origin');
    header("Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; connect-src 'self' https://admin.sitecake.com; frame-src https://www.google.com https://www.youtube.com https://www.openstreetmap.org;");
    header("Permissions-Policy: geolocation=(), camera=(), microphone=()");
}

// 7. Debug flag (true enables verbose error display)
$app['debug'] = false;

// 8. Logging — SimpleLogger writes to PHP error_log().
//    Upgraded to FileLog in Phase 4 once filesystem paths are known.
$app['logger'] = function ($app) {
    return new SimpleLogger();
};

// 9. Error / exception handler (replaces Monolog + Silex error listener)
//    Fully configured after Sitecake::boot() sets paths; we register now with
//    a SimpleLogger so at least fatal errors during boot are captured.
$app['exception_handler'] = function ($app) {
    return ErrorHandler::register(
        E_ALL & ~E_DEPRECATED & ~E_STRICT,
        $app['logger'],
        new PathReplaceFormatter([
            // Paths replaced after Sitecake::boot() sets SITE_ROOT
        ])
    )->setDebug($app['debug']);
};

// Trigger the exception handler registration eagerly so boot-time errors are caught
$app['exception_handler'];
