<?php
/**
 * includes/csrf.php — CSRF protection
 *
 * Usage:
 *   In a form:  <?= csrf_field() ?>
 *   On POST:    csrf_verify();  (dies with 403 if invalid)
 */

function csrf_token(): string {
    start_session();
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function csrf_field(): string {
    return '<input type="hidden" name="_csrf_token" value="' . htmlspecialchars(csrf_token()) . '">';
}

function csrf_verify(): void {
    $token = $_POST['_csrf_token'] ?? '';
    $valid = hash_equals(csrf_token(), $token);
    if (!$valid) {
        http_response_code(403);
        die('<p style="font-family:sans-serif;padding:2rem;">
            Invalid form submission. Please go back and try again.
        </p>');
    }
}
