<?php
function generateCSRFToken($form = 'default') {
    if (!isset($_SESSION['csrf_tokens'])) {
        $_SESSION['csrf_tokens'] = [];
    }

    // Generate token if not existing or expired (15 minutes)
    if (empty($_SESSION['csrf_tokens'][$form]) || time() > $_SESSION['csrf_tokens'][$form]['expires']) {
        $_SESSION['csrf_tokens'][$form] = [
            'token' => bin2hex(random_bytes(32)),
            'expires' => time() + 900 // 15 minutes
        ];
    }

    return $_SESSION['csrf_tokens'][$form]['token'];
}

function verifyCSRFToken($token, $form = 'default') {
    if (isset($_SESSION['csrf_tokens'][$form])) {
        $csrfData = $_SESSION['csrf_tokens'][$form];
        if ($csrfData['expires'] >= time() && hash_equals($csrfData['token'], $token)) {
            unset($_SESSION['csrf_tokens'][$form]); // One-time token
            return true;
        }
    }
    return false;
}
?>