<?php

declare(strict_types=1);

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

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

spl_autoload_register(function (string $class): void {
    $prefix = 'App\\';
    if (strncmp($class, $prefix, strlen($prefix)) !== 0) {
        return;
    }

    $relative = substr($class, strlen($prefix));
    $file = APP_PATH . '/' . str_replace('\\', '/', $relative) . '.php';
    if (is_file($file)) {
        require_once $file;
    }
});

\App\Core\Env::load(APP_BASE_PATH . '/.env');

$config = require APP_PATH . '/config.php';
\App\Core\Exceptions\Handler::register((bool) ($config['app']['debug'] ?? false));
$dateTimezone = $config['app']['timezone'] ?? 'UTC';
date_default_timezone_set($dateTimezone);

if (!headers_sent()) {
    header('X-Frame-Options: SAMEORIGIN');
    header('X-Content-Type-Options: nosniff');
    header('Referrer-Policy: strict-origin-when-cross-origin');
    header('Permissions-Policy: geolocation=(), microphone=(), camera=()');

    $isHttpsRequest = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
        || (($_SERVER['SERVER_PORT'] ?? null) === '443')
        || (strtolower((string) ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '')) === 'https');

    if ($isHttpsRequest) {
        header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
    }

    header("Content-Security-Policy: default-src 'self'; base-uri 'self'; frame-ancestors 'self'; form-action 'self'; object-src 'none'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; font-src 'self' data:; connect-src 'self';");
}

if (session_status() !== PHP_SESSION_ACTIVE) {
    $isHttps = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
        || (($_SERVER['SERVER_PORT'] ?? null) === '443');

    ini_set('session.use_strict_mode', '1');
    ini_set('session.use_only_cookies', '1');
    ini_set('session.cookie_httponly', '1');
    ini_set('session.cookie_samesite', 'Lax');

    session_set_cookie_params([
        'lifetime' => 0,
        'path' => '/',
        'domain' => '',
        'secure' => $isHttps,
        'httponly' => true,
        'samesite' => 'Lax',
    ]);
}

\App\Core\Session::start();

$licenseManager = new \App\Services\License\LicenseManager($config);
$licenseState = $licenseManager->evaluate();
\App\Core\Session::put('_license_state', $licenseState);

$pathInfo = (string) parse_url((string) ($_SERVER['REQUEST_URI'] ?? '/'), PHP_URL_PATH);
$licenseBypassPaths = ['/login', '/logout', '/system/license-status', '/system/license-request'];
if ($licenseManager->isDeveloperConsoleEnabled() && str_starts_with($pathInfo, '/system/license-admin')) {
    $licenseBypassPaths[] = '/system/license-admin';
    $licenseBypassPaths[] = '/system/license-admin/issue';
    $licenseBypassPaths[] = '/system/license-admin/keypair';
    $licenseBypassPaths[] = '/system/license-admin/download';
}
if (!$licenseState['valid'] && !in_array($pathInfo, $licenseBypassPaths, true)) {
    if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'GET') {
        if (!headers_sent()) {
            http_response_code(423);
            header('Content-Type: text/html; charset=UTF-8');
        }
        echo '<!doctype html><html lang="ar"><head><meta charset="utf-8"><title>License Required</title></head><body style="font-family:Tahoma,Arial,sans-serif;padding:24px"><h2>تعذر تنفيذ العملية</h2><p>' . htmlspecialchars((string) $licenseState['message'], ENT_QUOTES, 'UTF-8') . '</p><p>Code: <code>' . htmlspecialchars((string) $licenseState['code'], ENT_QUOTES, 'UTF-8') . '</code></p><p>Fingerprint: <code>' . htmlspecialchars((string) $licenseState['fingerprint'], ENT_QUOTES, 'UTF-8') . '</code></p></body></html>';
        exit;
    }

    \App\Core\Flash::set(str_starts_with((string) $licenseState['code'], 'DEV_OVERRIDE') ? 'info' : 'warning', (string) $licenseState['message']);
}

require_once APP_PATH . '/helpers.php';
