<?php
class CSRF
{
    public static function token(): string
    {
        if (empty($_SESSION['_csrf'])) {
            $_SESSION['_csrf'] = bin2hex(random_bytes(32));
        }
        return $_SESSION['_csrf'];
    }

    public static function input(): string
    {
        return '<input type="hidden" name="_csrf" value="' . e(self::token()) . '">';
    }

    public static function check(): void
    {
        $posted = $_POST['_csrf'] ?? '';
        $valid = isset($_SESSION['_csrf']) && hash_equals($_SESSION['_csrf'], $posted);
        if (!$valid) {
            http_response_code(419);
            exit('Sessao expirada ou formulario invalido. Volte e tente novamente.');
        }
    }
}
