<?php
declare(strict_types=1);

namespace App\Core;

final class Csrf
{
    public static function token(): string
    {
        $token = Session::get('csrf_token');
        if (! is_string($token) || $token === '') {
            $token = bin2hex(random_bytes(32));
            Session::put('csrf_token', $token);
        }

        return $token;
    }

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

    public static function verify(?string $token): void
    {
        $sessionToken = Session::get('csrf_token');
        if (! is_string($token) || ! is_string($sessionToken) || ! hash_equals($sessionToken, $token)) {
            abort(403, 'CSRF token tidak valid.');
        }
    }
}
