<?php
declare(strict_types=1);

namespace App\Core\Security;

final class Csrf
{
    private const SESSION_KEY = '_csrf_token';

    public static function token(): string
    {
        if (empty($_SESSION[self::SESSION_KEY])) {
            $_SESSION[self::SESSION_KEY] = bin2hex(random_bytes(32));
        }

        return (string) $_SESSION[self::SESSION_KEY];
    }

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

        $storedToken = (string) ($_SESSION[self::SESSION_KEY] ?? '');
        if ($storedToken === '') {
            return false;
        }

        return hash_equals($storedToken, $token);
    }
}
