<?php

namespace App\Core;

class CSRF
{
    public static function generateToken(bool $forceRefresh = false): string
    {
        if ($forceRefresh || !isset($_SESSION['csrf_token'])) {
            $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
        }
        return $_SESSION['csrf_token'];
    }

    public static function verify(string $token): bool
    {
        return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
    }

    public static function reset(): void
    {
        unset($_SESSION['csrf_token']);
    }

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