<?php
// ─────────────────────────────────────────────
// api/auth.php
// HQ-Login + Session-Check + Logout
//
// Frontend ruft /c2c/api/auth (ohne .php) — siehe .htaccess.
//
// GET    → prüft ob Token gültig         → { angemeldet: true/false }
// POST   → loggt ein, gibt Token zurück  → { ok: true, token: "..." }
// DELETE → loggt aus, löscht Token       → { ok: true }
//
// Token wird im Header X-C2C-Token erwartet (oder ?token= als Fallback).
// ─────────────────────────────────────────────

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';

// ── CORS ─────────────────────────────────────
$origin  = $_SERVER['HTTP_ORIGIN'] ?? '';
$allowed = [
    'https://come2canada.life',
    'https://www.come2canada.life',
    'https://christianwehrli.ca',
];
if (in_array($origin, $allowed, true)) {
    header("Access-Control-Allow-Origin: $origin");
    header('Access-Control-Allow-Credentials: true');
}
header('Access-Control-Allow-Methods: GET, POST, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, X-C2C-Token');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

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

$method = $_SERVER['REQUEST_METHOD'];
$db     = C2CDatabase::get();

// Helper: Token aus Header oder Query
function get_request_token(): string {
    $h = $_SERVER['HTTP_X_C2C_TOKEN'] ?? '';
    if ($h) return trim($h);
    return trim($_GET['token'] ?? '');
}

// ─────────────────────────────────────────────
// GET — prüft Session
// ─────────────────────────────────────────────
if ($method === 'GET') {
    $token = get_request_token();
    if (!$token) {
        echo json_encode(['angemeldet' => false]);
        exit;
    }

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

    echo json_encode([
        'angemeldet' => (bool)$stmt->fetch(),
    ]);
    exit;
}

// ─────────────────────────────────────────────
// DELETE — Logout
// ─────────────────────────────────────────────
if ($method === 'DELETE') {
    $token = get_request_token();
    if ($token) {
        $db->prepare("DELETE FROM hq_sessions WHERE token = ?")->execute([$token]);
    }
    echo json_encode(['ok' => true]);
    exit;
}

// ─────────────────────────────────────────────
// POST — Login
// ─────────────────────────────────────────────
if ($method === 'POST') {
    if (!defined('HQ_PASSWORD_HASH') || empty(HQ_PASSWORD_HASH)) {
        http_response_code(500);
        echo json_encode([
            'ok'    => false,
            'error' => 'HQ_PASSWORD_HASH nicht in secrets.php gesetzt',
        ]);
        exit;
    }

    $body = json_decode(file_get_contents('php://input'), true) ?: [];
    // Frontend (index.html) sendet "pass" — alte login.php erwartete "passwort".
    // Akzeptiere beide.
    $pass = trim($body['pass'] ?? $body['passwort'] ?? '');

    if (empty($pass) || !password_verify($pass, HQ_PASSWORD_HASH)) {
        sleep(1); // Brute-Force-Bremse
        http_response_code(401);
        echo json_encode(['ok' => false, 'error' => 'Ungültiges Passwort']);
        exit;
    }

    // Abgelaufene Sessions aufräumen
    $db->exec("DELETE FROM hq_sessions WHERE expires_at < NOW()");

    // Neuer Token, 8 Stunden gültig
    $token   = bin2hex(random_bytes(32));
    $expires = date('Y-m-d H:i:s', strtotime('+8 hours'));

    $db->prepare("INSERT INTO hq_sessions (token, expires_at) VALUES (?, ?)")
       ->execute([$token, $expires]);

    echo json_encode([
        'ok'      => true,
        'token'   => $token,
        'expires' => $expires,
    ]);
    exit;
}

// Anderer Method → 405
http_response_code(405);
echo json_encode(['ok' => false, 'error' => 'Methode nicht erlaubt']);
