<?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;
function qrmanager_security_headers(array $config): void {
    if (headers_sent() || PHP_SAPI === 'cli') { return; }
    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' 'unsafe-inline'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; connect-src 'self'; form-action 'self'; upgrade-insecure-requests";
    header('Content-Security-Policy: '.$csp);
}
qrmanager_security_headers($config);


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__ . '/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());
}
