<?php
// ── CSRF helpers ─────────────────────────────────────────────────────────────
// csrf_generate()      – call once per session (header.php does this)
// csrf_field()         – echo hidden <input> inside every POST form
// csrf_verify()        – verify POST token, abort 403 on failure
// csrf_meta()          – echo <meta> tag for JS to read the token

function csrf_generate(): void {
    if (empty($_SESSION['csrf_token']))
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

function csrf_token(): string {
    return $_SESSION['csrf_token'] ?? '';
}

function csrf_field(): void {
    echo '<input type="hidden" name="csrf_token" value="'
        . htmlspecialchars(csrf_token(), ENT_QUOTES) . '">';
}

function csrf_meta(): void {
    echo '<meta name="csrf-token" content="'
        . htmlspecialchars(csrf_token(), ENT_QUOTES) . '">';
}

function csrf_verify(): void {
    $post   = $_POST['csrf_token']                  ?? '';
    $header = $_SERVER['HTTP_X_CSRF_TOKEN']         ?? '';
    $token  = !empty($post) ? $post : $header;
    if (!hash_equals(csrf_token(), $token)) {
        http_response_code(403);
        header('Content-Type: application/json');
        die(json_encode(['success' => false, 'error' => 'Invalid CSRF token']));
    }
}
