<?php
class CSRF
{
    public static function token(): string
    {
        if (!Session::has('_csrf_token')) {
            Session::set('_csrf_token', bin2hex(random_bytes(32)));
        }
        return Session::get('_csrf_token');
    }

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

    public static function validate(?string $token): bool
    {
        if ($token === null) {
            return false;
        }
        return hash_equals(self::token(), $token);
    }

    public static function regenerate(): void
    {
        Session::set('_csrf_token', bin2hex(random_bytes(32)));
    }
}