<?php

namespace App\Helpers;

class Csrf
{
    public static function token(): string
    {
        SessionHelper::start();
        if (empty($_SESSION['_token'])) {
            $_SESSION['_token'] = bin2hex(random_bytes(32));
        }
        return $_SESSION['_token'];
    }

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

    public static function validate(?string $token): bool
    {
        SessionHelper::start();
        return isset($_SESSION['_token']) && hash_equals($_SESSION['_token'], (string) $token);
    }
}

