<?php
declare(strict_types=1);

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

function validateCsrfToken(?string $token): bool
{
    if (empty($_SESSION['_csrf_token'])) {
        return false;
    }
    return hash_equals($_SESSION['_csrf_token'], $token ?? '');
}

function enforceCsrfToken(): void
{
    header('Content-Type: application/json; charset=utf-8');
    $header = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
    $post = $_POST['_csrf_token'] ?? $_POST['csrf_token'] ?? '';
    $token = $header ?: $post;

    if (!validateCsrfToken($token)) {
        http_response_code(419);
        echo json_encode(['status' => 'error', 'message' => 'CSRF token validation failed']);
        exit;
    }
}

function skipCsrfForReadActions(string $action): bool
{
    $readActions = ['reference_data', 'jobs', 'timeline', 'job_details', 'rfq_list', 'requisition_report'];
    return in_array($action, $readActions, true);
}
