<?php
declare(strict_types=1);

if (basename(__FILE__) === basename($_SERVER['SCRIPT_FILENAME'] ?? '')) {
    http_response_code(403);
    exit('Forbidden');
}

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

function generate_csrf_token(): string
{
    return csrf_token();
}

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

function verify_csrf(): void
{
    $token = $_POST['csrf_token'] ?? '';
    verify_csrf_token(is_string($token) ? $token : '');
}

function verify_csrf_token(string $token): void
{
    if (!is_string($token) || !hash_equals($_SESSION['csrf_token'] ?? '', $token)) {
        if (function_exists('log_activity')) {
            log_activity('security.csrf_failed', 'Invalid CSRF token on ' . ($_SERVER['REQUEST_URI'] ?? 'unknown'));
        }
        http_response_code(403);
        exit('Invalid CSRF token. Please go back and try again.');
    }
}
