<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}



function generate_csrf_token()
{
    $token = bin2hex(random_bytes(32));
    $_SESSION['csrf_token'] = $token;
    $_SESSION['csrf_token_time'] = time();
   
    return $token;
}

function get_csrf_token()
{
      $now = time();

    if (
        !isset($_SESSION['csrf_token']) || !isset($_SESSION['csrf_token_time']) ||
        time() - $_SESSION['csrf_token_time'] > CSRF_EXPIRY_SECONDS
    ) {
        // Remove old/expired token from session
        unset($_SESSION['csrf_token']);
        unset($_SESSION['csrf_token_time']);

        return generate_csrf_token();
   }
      $age = $now - $_SESSION['csrf_token_time'];
    $timeLeft = CSRF_EXPIRY_SECONDS - $age;

    // Refresh if expired OR will expire before next heartbeat
    if ($timeLeft <= 0 || $timeLeft <= CSRF_HEARTBEAT_INTERVAL /1000) {
        return generate_csrf_token();
    }


   return $_SESSION['csrf_token'];
}

function validate_csrf_token($token)
{
    if (!isset($_SESSION['csrf_token']) || $token !== $_SESSION['csrf_token']) {
        echo "SESSION_EXPIRED";
        http_response_code(403);
        exit;
    }

    if (time() - $_SESSION['csrf_token_time'] > CSRF_EXPIRY_SECONDS) {
        echo "SESSION_EXPIRED";
        http_response_code(403);
        exit;
    }
}
function validate_csrf_request($csrf_token)
{
    if (!isset($csrf_token)) {
        echo "SESSION_EXPIRED";
        http_response_code(403);
        exit;
    }

    validate_csrf_token($csrf_token);
}