<?php
// ============================================================
// come2canada.life — Bootstrap
// Wird von API-Dateien als erstes eingebunden, die das alte
// "deutsche" System nutzen (formular.php, news.php etc).
// ============================================================

require_once __DIR__ . '/config.php';

// -- CORS-Header setzen --------------------------------------
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (defined('ALLOWED_ORIGINS') && in_array($origin, ALLOWED_ORIGINS, true)) {
    header("Access-Control-Allow-Origin: $origin");
    header("Access-Control-Allow-Credentials: true");
}
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-C2C-Token');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }

header('Content-Type: application/json; charset=utf-8');
header('X-Content-Type-Options: nosniff');

// -- Fehlerbehandlung ----------------------------------------
set_exception_handler(function(Throwable $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'Serverfehler', 'detail' => $e->getMessage()]);
    exit;
});

// -- Datenbankverbindung -------------------------------------
function db(): PDO {
    static $pdo = null;
    if ($pdo === null) {
        $charset = defined('DB_CHARSET') ? DB_CHARSET : 'utf8mb4';
        $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=" . $charset;
        $pdo = new PDO($dsn, DB_USER, DB_PASS, [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES   => false,
        ]);
    }
    return $pdo;
}

// -- JSON-Anfrage lesen --------------------------------------
function body(): array {
    $raw = file_get_contents('php://input');
    if (empty($raw)) return [];
    $data = json_decode($raw, true);
    return is_array($data) ? $data : [];
}

// -- Antwort senden ------------------------------------------
function respond(array $data, int $code = 200): void {
    http_response_code($code);
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

function ok(array $data = []): void  { respond(array_merge(['ok' => true],  $data)); }
function err(string $msg, int $code = 400): void { respond(['ok' => false, 'error' => $msg], $code); }

// -- Auth-Check für API-Endpunkte ---------------------------
// Verwendet das hq_sessions-Token-System (siehe api/auth.php).
// Token im Header X-C2C-Token oder ?token=
function requireAuth(): void {
    $token = trim($_SERVER['HTTP_X_C2C_TOKEN'] ?? ($_GET['token'] ?? ''));

    if (empty($token)) {
        err('Nicht autorisiert', 401);
    }

    $stmt = db()->prepare(
        "SELECT id FROM hq_sessions WHERE token = ? AND expires_at > NOW()"
    );
    $stmt->execute([$token]);

    if (!$stmt->fetch()) {
        err('Token ungültig oder abgelaufen', 401);
    }
}

// -- UUID generieren -----------------------------------------
function newUuid(): string {
    return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff),
        mt_rand(0, 0x0fff) | 0x4000, mt_rand(0, 0x3fff) | 0x8000,
        mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff));
}

// -- Aktivität loggen ----------------------------------------
function logAktivitaet(string $aktion, ?int $klientId = null, string $beschreibung = '', array $meta = []): void {
    try {
        $stmt = db()->prepare("INSERT INTO aktivitaeten (klient_id, aktion, beschreibung, meta_json) VALUES (?,?,?,?)");
        $stmt->execute([$klientId, $aktion, $beschreibung, $meta ? json_encode($meta) : null]);
    } catch (Exception $e) { /* Logging darf nie den Hauptfluss stoppen */ }
}
