<?php
// Public folder entry point: redirect back into the installation admin area.
declare(strict_types=1);

function qr_manager_install_base_path(): string {
    $script = str_replace('\\', '/', $_SERVER['SCRIPT_NAME'] ?? '');
    $base = rtrim(dirname(dirname($script)), '/');
    return ($base === '' || $base === '.') ? '' : $base;
}

$configFile = __DIR__ . '/../app/config.php';
if (!file_exists($configFile)) {
    header('Location: ' . qr_manager_install_base_path() . '/install.php');
    exit;
}

$config = require $configFile;
$secure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') || (isset($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] === 'on');
$forceSsl = array_key_exists('force_ssl', $config) ? (bool)$config['force_ssl'] : true;
if ($forceSsl && !$secure && !empty($_SERVER['HTTP_HOST'])) {
    header('Location: https://' . $_SERVER['HTTP_HOST'] . ($_SERVER['REQUEST_URI'] ?? '/'), true, 301);
    exit;
}
if (session_status() !== PHP_SESSION_ACTIVE) {
    ini_set('session.cookie_httponly', '1');
    ini_set('session.cookie_samesite', 'Lax');
    if ($secure) {
        ini_set('session.cookie_secure', '1');
    }
    session_name($config['session_name'] ?? 'qrmanager_session');
    session_start();
}

$target = !empty($_SESSION['user_id']) ? '/admin/dashboard.php' : '/admin/login.php';
header('Location: ' . qr_manager_install_base_path() . $target);
exit;
