<?php

// 0) Umgebung / Domains / Error-Level
require_once __DIR__ . "/config.php";

// -----------------------------------------------------------
// Session starten
// -----------------------------------------------------------
if (php_sapi_name() !== 'cli') {
    if (session_status() === PHP_SESSION_NONE) {

        session_name('usbcheck_session');

        session_set_cookie_params([
            'lifetime' => 0,
            'path'     => '/',
            'domain'   => '',
            'secure'   => (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'),
            'httponly' => true,
            'samesite' => 'Lax',
        ]);

        session_start();
    }
}

/**
 * ---------------------------------------------------------
 * Persistente Client-ID (über Logins & Sessions hinweg)
 * ---------------------------------------------------------
 * Cookie-Name: usbcheck_client
 * Domain:
 *   - staging: .staging.usbcheck.it
 *   - live:    .usbcheck.it
 */
if (php_sapi_name() !== 'cli') {
    $clientId = $_COOKIE['usbcheck_client'] ?? null;

    // jetzt 64 Hex-Zeichen (32 Bytes → 64 Hex)
    if (
        !is_string($clientId)
        || $clientId === ''
        || !preg_match('/^[a-f0-9]{64}$/', $clientId)
    ) {
        // neue ID erzeugen
        try {
            $clientId = bin2hex(random_bytes(32)); // 32 Bytes → 64 Hex
        } catch (Throwable $e) {
            // Fallback – sollte praktisch nie passieren
            $clientId = bin2hex(openssl_random_pseudo_bytes(32));
        }

        $host = $_SERVER['HTTP_HOST'] ?? '';
        $cookieDomain = null;

        if (preg_match('/\.staging\.usbcheck\.it$/', $host)) {
            $cookieDomain = '.staging.usbcheck.it';
        } elseif (preg_match('/\.usbcheck\.it$/', $host)) {
            $cookieDomain = '.usbcheck.it';
        }

        $cookieOpts = [
            'expires'  => time() + 365 * 24 * 60 * 60, // ~1 Jahr
            'path'     => '/',
            'secure'   => (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'),
            'httponly' => false, // darf JS lesen, falls du es mal brauchst
            'samesite' => 'Lax',
        ];

        if ($cookieDomain) {
            $cookieOpts['domain'] = $cookieDomain;
        }

        setcookie('usbcheck_client', $clientId, $cookieOpts);
        $_COOKIE['usbcheck_client'] = $clientId; // lokal auch verfügbar
    }

    // global verfügbar machen
    $GLOBALS['usb_client_id'] = $clientId;
}

require_once __DIR__ . '/i18n.php';  // <— zentrale Sprachlogik

// ab hier kannst du überall $GLOBALS['lang'] und $GLOBALS['availableLangs'] nutzen
// und für JS:
$usbConfig = [
    // ... dein sonstiges Zeug ...
    'i18n' => app_i18n_get_frontend_config(),
];

// -----------------------------------------------------------
// Rest des Systems laden
// -----------------------------------------------------------
require_once __DIR__ . "/db.php";
require_once __DIR__ . "/../src/functions.php";
