<?php
namespace App\Core;

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

    public static function validateFromRequest(): void
    {
        Auth::start();
        $token = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? $_POST['_csrf'] ?? '';
        if (!$token || empty($_SESSION['_csrf']) || !hash_equals($_SESSION['_csrf'], $token)) {
            Response::error('Invalid CSRF token.', 419);
        }
    }
}
