<?php
/**
 * CSRF Protection Service
 */
class CsrfProtection {
    private static $tokenName = 'csrf_token';
    private static $sessionKey = 'csrf_token';
    
    /**
     * Generate a new CSRF token
     */
    public static function generateToken() {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        
        $token = bin2hex(random_bytes(32));
        $_SESSION[self::$sessionKey] = $token;
        
        return $token;
    }
    
    /**
     * Get the current CSRF token
     */
    public static function getToken() {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        
        if (empty($_SESSION[self::$sessionKey])) {
            return self::generateToken();
        }
        
        return $_SESSION[self::$sessionKey];
    }
    
    /**
     * Validate a CSRF token
     */
    public static function validateToken($token) {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        
        if (empty($token) || empty($_SESSION[self::$sessionKey])) {
            return false;
        }
        
        return hash_equals($_SESSION[self::$sessionKey], $token);
    }
    
    /**
     * Get HTML input field for CSRF token
     */
    public static function getHtmlInput() {
        $token = self::getToken();
        return '<input type="hidden" name="' . self::$tokenName . '" value="' . htmlspecialchars($token, ENT_QUOTES, 'UTF-8') . '">';
    }
    
    /**
     * Get token name for JavaScript
     */
    public static function getTokenName() {
        return self::$tokenName;
    }
    
    /**
     * Clear the CSRF token
     */
    public static function clearToken() {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        
        unset($_SESSION[self::$sessionKey]);
    }
}
