<?php

declare(strict_types=1);

namespace Core;

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

        return (string) $_SESSION['_csrf_token'];
    }

    public static function verify(?string $token): bool
    {
        $sessionToken = (string) ($_SESSION['_csrf_token'] ?? '');
        $providedToken = trim((string) $token);

        if ($sessionToken === '' || $providedToken === '') {
            return false;
        }

        return hash_equals($sessionToken, $providedToken);
    }
}
