<?php

namespace App\Util;

class CSRF
{
    private static string $tokenSessionKey = 'csrf_token';

    public static function getToken(): string {
        if (!isset($_SESSION[self::$tokenSessionKey])) {
            $_SESSION[self::$tokenSessionKey] = bin2hex(random_bytes(32));
        }
        return $_SESSION[self::$tokenSessionKey];
    }

    public static function getHiddenInputString(string $tokenName = 'csrf_token'): string {
        return '<input type="hidden" name="' . htmlspecialchars($tokenName) . '" value="' . self::getToken() . '">';
    }

    public static function getQueryString(string $tokenName = 'csrf_token'): string {
        return htmlspecialchars($tokenName) . '=' . self::getToken();
    }

    public static function validate(array $postData, string $tokenName = 'csrf_token'): bool {
        if (!isset($postData[$tokenName])) {
            return false;
        }
        $postToken = $postData[$tokenName];
        if (!is_string($postToken)) {
            return false;
        }
        return hash_equals($_SESSION[self::$tokenSessionKey] ?? '', $postToken);
    }
}
