<?php
// ============================================================
// come2canada.life — API: Login
// Hochladen als: christianwehrli.ca/c2c/api/login.php
// ============================================================

// CORS manuell (Bootstrap noch nicht laden — kein Auth-Check hier)
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
$allowed = ['https://come2canada.life', 'https://www.come2canada.life'];
if (in_array($origin, $allowed)) {
    header("Access-Control-Allow-Origin: $origin");
    header("Access-Control-Allow-Credentials: true");
}
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Content-Type: application/json; charset=utf-8');

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'Methode nicht erlaubt']);
    exit;
}

require_once __DIR__ . '/config.php';

// Passwort-Hash in config.php definieren als:
// define('HQ_PASSWORD_HASH', password_hash('deinPasswort', PASSWORD_DEFAULT));
if (!defined('HQ_PASSWORD_HASH')) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'HQ_PASSWORD_HASH nicht konfiguriert']);
    exit;
}

$body = json_decode(file_get_contents('php://input'), true);
$pw   = trim($body['passwort'] ?? '');

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

// Token generieren (64 Zeichen hex = 256 bit)
$token  = bin2hex(random_bytes(32));
$expiry = date('Y-m-d H:i:s', strtotime('+8 hours'));

try {
    require_once __DIR__ . '/bootstrap.php';
    $pdo = db();

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

    // Neue Session speichern
    $pdo->prepare(
        "INSERT INTO hq_sessions (token, expires_at) VALUES (?, ?)"
    )->execute([$token, $expiry]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'Datenbankfehler']);
    exit;
}

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