<?php
declare(strict_types=1);

/**
 * Per-session CSRF token. Every state-changing form carries one.
 */
final class Csrf
{
    public static function token(): string
    {
        if (empty($_SESSION['csrf'])) {
            $_SESSION['csrf'] = bin2hex(random_bytes(32));
        }
        return $_SESSION['csrf'];
    }

    /** Hidden input for forms. */
    public static function field(): string
    {
        return '<input type="hidden" name="csrf" value="' . e(self::token()) . '">';
    }

    public static function valid(?string $token): bool
    {
        return is_string($token)
            && !empty($_SESSION['csrf'])
            && hash_equals($_SESSION['csrf'], $token);
    }

    /** Halt the request unless the submitted token matches. */
    public static function check(): void
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            http_response_code(405);
            exit('This action requires a POST request.');
        }
        if (!self::valid($_POST['csrf'] ?? null)) {
            http_response_code(419);
            Flash::add('error', 'That form expired. Please try again.');
            redirect('dashboard');
        }
    }
}
