<?php
/**
 * CSRF Protection
 */

class Csrf
{
    public static function generateToken(): string
    {
        $token = bin2hex(random_bytes(32));
        $_SESSION[CSRF_TOKEN_NAME] = $token;
        return $token;
    }

    public static function getToken(): string
    {
        if (!isset($_SESSION[CSRF_TOKEN_NAME])) {
            self::generateToken();
        }
        return $_SESSION[CSRF_TOKEN_NAME];
    }

    public static function validateToken(?string $token): bool
    {
        if (empty($token) || !isset($_SESSION[CSRF_TOKEN_NAME])) {
            return false;
        }
        return hash_equals($_SESSION[CSRF_TOKEN_NAME], $token);
    }

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

    public static function check(): void
    {
        $token = $_POST[CSRF_TOKEN_NAME] ?? $_SERVER['HTTP_X_CSRF_TOKEN'] ?? null;
        if (!self::validateToken($token)) {
            http_response_code(403);
            die('Invalid CSRF token. Please refresh the page and try again.');
        }
    }
}
