<?php
/**
 * CSRF protection helpers for Ton Sui Mining
 * Provides functions for generating and validating CSRF tokens
 */

/**
 * Generate a new CSRF token and store it in the session
 * 
 * @return string The generated CSRF token
 */
function generate_csrf_token() {
    if (session_status() === PHP_SESSION_NONE) {
        // Define TONSUI_LOADED constant to prevent direct access to session_init.php
define('TONSUI_LOADED', true);

// Include centralized session initialization
require_once __DIR__ . '/session_init.php';

// session_start(); // Already started by session_init.php
    }
    
    // Generate a random token
    $token = bin2hex(random_bytes(32));
    
    // Store it in the session
    $_SESSION['csrf_token'] = $token;
    $_SESSION['csrf_token_time'] = time();
    
    return $token;
}

/**
 * Validate a CSRF token against the one stored in session
 * 
 * @param string $token The token to validate
 * @param int $max_age Maximum age of the token in seconds (default: 3600 seconds = 1 hour)
 * @return bool True if the token is valid, false otherwise
 */
function validate_csrf_token($token, $max_age = 3600) {
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    
    // Check if token exists in session
    if (!isset($_SESSION['csrf_token']) || !isset($_SESSION['csrf_token_time'])) {
        return false;
    }
    
    // Check if token has expired
    $token_age = time() - $_SESSION['csrf_token_time'];
    if ($token_age > $max_age) {
        // Token has expired, remove it
        unset($_SESSION['csrf_token']);
        unset($_SESSION['csrf_token_time']);
        return false;
    }
    
    // Check if token matches
    return hash_equals($_SESSION['csrf_token'], $token);
}

/**
 * Get the current CSRF token or generate a new one if none exists
 *
 * @return string The CSRF token
 */
function get_csrf_token() {
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    
    if (!isset($_SESSION['csrf_token'])) {
        return generate_csrf_token();
    }
    
    return $_SESSION['csrf_token'];
}

/**
 * Output a hidden input field with the CSRF token
 *
 * @return string HTML for the hidden input field
 */
function csrf_token_field() {
    $token = get_csrf_token();
    return '<input type="hidden" name="csrf_token" value="' . htmlspecialchars($token) . '">';
}

/**
 * Add a CSRF token to a URL
 *
 * @param string $url The URL to add the token to
 * @return string The URL with the token added as a query parameter
 */
function add_csrf_token_to_url($url) {
    $token = get_csrf_token();
    $separator = (parse_url($url, PHP_URL_QUERY) ? '&' : '?');
    return $url . $separator . 'csrf_token=' . urlencode($token);
}
