<?php
/**
 * BOAFO CSRF Protection
 */
class CSRF {
    private const TOKEN_KEY = 'csrf_token';
    private const TOKEN_LENGTH = 32;

    public static function generate(): string {
        if (empty($_SESSION[self::TOKEN_KEY])) {
            $_SESSION[self::TOKEN_KEY] = bin2hex(random_bytes(self::TOKEN_LENGTH));
        }
        return $_SESSION[self::TOKEN_KEY];
    }

    public static function token(): string {
        return self::generate();
    }

    public static function field(): string {
        return '<input type="hidden" name="_csrf_token" value="' . htmlspecialchars(self::token(), ENT_QUOTES, 'UTF-8') . '">';
    }

    public static function verify(): bool {
        $token = $_POST['_csrf_token'] ?? $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
        if (empty($token) || empty($_SESSION[self::TOKEN_KEY])) {
            return false;
        }
        return hash_equals($_SESSION[self::TOKEN_KEY], $token);
    }

    public static function check(): void {
        if (!self::verify()) {
            http_response_code(403);
            die(json_encode(['success' => false, 'message' => 'Invalid CSRF token. Please refresh and try again.']));
        }
    }
}
