<?php
declare(strict_types=1);
$configFile = __DIR__ . '/config.php';
if (!file_exists($configFile)) {
    http_response_code(500);
    exit('Konfiguration fehlt. Bitte install.php ausführen.');
}
$config = require $configFile;
$GLOBALS['qrator_csp_nonce'] = base64_encode(random_bytes(16));
function qrmanager_csp_nonce(): string { return (string)($GLOBALS['qrator_csp_nonce'] ?? ''); }
function qrmanager_security_headers(array $config): void {
    if (headers_sent() || PHP_SAPI === 'cli') { return; }
    $nonce = qrmanager_csp_nonce();
    header('X-Frame-Options: DENY');
    header('X-Content-Type-Options: nosniff');
    header('Referrer-Policy: strict-origin-when-cross-origin');
    header('Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=()');
    $csp = "default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; img-src 'self' data: blob:; style-src 'self'; script-src 'nonce-".$nonce."' https://cdn.jsdelivr.net; connect-src 'self'; form-action 'self'; upgrade-insecure-requests";
    header('Content-Security-Policy: '.$csp);
}
qrmanager_security_headers($config);

// QRator release version. This value is intentionally defined by the shipped update package.
if (!defined('QRATOR_VERSION')) { define('QRATOR_VERSION', '24.3'); }
if (!defined('QRATOR_VERSION_LABEL')) { define('QRATOR_VERSION_LABEL', 'v'.QRATOR_VERSION); }

// QRator update manifest URL is intentionally defined by the shipped release package,
// not by app/config.php. This prevents stale installed config files from keeping old update paths.
if (!defined('QRATOR_UPDATE_CHANNEL')) { define('QRATOR_UPDATE_CHANNEL', 'platform'); }
if (!defined('QRATOR_UPDATE_MANIFEST_URL')) { define('QRATOR_UPDATE_MANIFEST_URL', 'https://qrator.web2use.ch/update-platform.json'); }


function qrmanager_trusted_proxy(): bool {
    global $config;
    $trusted = $config['trusted_proxies'] ?? [];
    if (!is_array($trusted) || !$trusted) { return false; }
    $remote = $_SERVER['REMOTE_ADDR'] ?? '';
    return $remote !== '' && in_array($remote, $trusted, true);
}

function qrmanager_is_https(): bool {
    if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') { return true; }
    if (!qrmanager_trusted_proxy()) { return false; }
    return (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower((string)$_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https')
        || (isset($_SERVER['HTTP_X_FORWARDED_SSL']) && strtolower((string)$_SERVER['HTTP_X_FORWARDED_SSL']) === 'on');
}

function qrmanager_force_ssl_redirect(array $config): void {
    $force = array_key_exists('force_ssl', $config) ? (bool)$config['force_ssl'] : true;
    if (!$force || qrmanager_is_https()) { return; }
    $host = $_SERVER['HTTP_HOST'] ?? '';
    if ($host === '') { return; }
    $uri = $_SERVER['REQUEST_URI'] ?? '/';
    header('Location: https://' . $host . $uri, true, 301);
    exit;
}

qrmanager_force_ssl_redirect($config);

function qrmanager_cookie_path(array $config): string {
    $script = $_SERVER['SCRIPT_NAME'] ?? '';
    $pos = strpos($script, '/admin/');
    if ($pos !== false) {
        $base = substr($script, 0, $pos);
        return $base !== '' ? $base : '/';
    }
    $path = parse_url($config['base_url'] ?? '', PHP_URL_PATH);
    $path = is_string($path) ? rtrim($path, '/') : '';
    return $path !== '' ? $path : '/';
}

function qrmanager_session_name(array $config): string {
    $configured = $config['session_name'] ?? '';
    if ($configured) {
        $safe = preg_replace('/[^a-zA-Z0-9_-]/', '', (string)$configured);
        if ($safe !== '') return $safe;
    }
    $seed = ($config['base_url'] ?? '') . '|' . ($config['table_prefix'] ?? '');
    return 'qrmanager_' . substr(hash('sha256', $seed), 0, 16);
}

$secure = qrmanager_is_https();
if (session_status() === PHP_SESSION_NONE) {
    session_name(qrmanager_session_name($config));
    session_set_cookie_params([
        'lifetime' => 0,
        'path' => qrmanager_cookie_path($config),
        'secure' => $secure,
        'httponly' => true,
        'samesite' => 'Strict',
    ]);
    session_start();
}

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/security.php';
require_once __DIR__ . '/tables.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/update_status.php';
require_once __DIR__ . '/mailer.php';
require_once __DIR__ . '/analytics.php';
require_once __DIR__ . '/logo.php';
require_once __DIR__ . '/migrations.php';
$pdo = db($config);
// v15.1: keep installations updated enough for auth/registration changes.
try {
    if (function_exists("run_migrations")) { run_migrations($pdo); }
} catch (Throwable $e) {
    error_log("KuhRator migration check failed: ".$e->getMessage());
}
