<?php
// ============================================================
//  CSRF protection
// ============================================================
//
//  Every form in the member portal and every auth form includes
//  a hidden `_csrf` field. The handler verifies it before doing
//  anything that changes state.
//
//  Token is stored in the PHP session, regenerated when the user
//  logs in or out.
//
// ============================================================

require_once __DIR__ . '/session.php';

/** Get the current token, creating one if needed. */
function csrf_token(): string {
    session_start_once();
    if (empty($_SESSION['_csrf'])) {
        $_SESSION['_csrf'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['_csrf'];
}

/** Rotate the token — call on login and logout. */
function csrf_rotate(): void {
    session_start_once();
    $_SESSION['_csrf'] = bin2hex(random_bytes(32));
}

/** Render a hidden input with the current token. */
function csrf_field(): string {
    return '<input type="hidden" name="_csrf" value="' . htmlspecialchars(csrf_token()) . '">';
}

/**
 * Verify the token on a POST request. Aborts with 403 if invalid.
 * Call at the very top of every POST handler.
 */
function csrf_verify(): void {
    $sent = $_POST['_csrf'] ?? '';
    if (!hash_equals(csrf_token(), (string)$sent)) {
        http_response_code(403);
        echo 'CSRF token mismatch. Please reload the form and try again.';
        exit;
    }
}
