<?php
/**
 * CSRF Protection
 */
class CSRF {
    
    public static function init(): void {
        if (empty($_SESSION['csrf_token']) || (time() - ($_SESSION['csrf_time'] ?? 0)) > CSRF_TOKEN_LIFETIME) {
            $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
            $_SESSION['csrf_time'] = time();
        }
    }
    
    public static function token(): string {
        return $_SESSION['csrf_token'] ?? '';
    }
    
    public static function field(): string {
        return '<input type="hidden" name="_csrf_token" value="' . self::token() . '">';
    }
    
    public static function verify(): bool {
        $token = $_POST['_csrf_token'] ?? $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
        return hash_equals(self::token(), $token);
    }
    
    public static function check(): void {
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && !self::verify()) {
            http_response_code(403);
            die('Invalid security token. Please refresh and try again.');
        }
    }
}
