<?php
declare(strict_types=1);

namespace App;

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

    public static function verify(?string $provided): bool
    {
        $expected = $_SESSION['_csrf'] ?? '';
        return is_string($provided) && $expected !== '' && hash_equals($expected, $provided);
    }

    public static function requireValid(): void
    {
        $token = $_POST['_csrf'] ?? $_SERVER['HTTP_X_CSRF_TOKEN'] ?? null;
        if (!self::verify($token)) {
            // Regenerate token so the next page load has a valid one
            unset($_SESSION['_csrf']);
            self::token();

            // Try to redirect back with a flash error instead of dying
            $_SESSION['_flash']['error'] = t('error.csrf_expired');
            $referer = $_SERVER['HTTP_REFERER'] ?? null;
            if ($referer && str_contains($referer, $_SERVER['HTTP_HOST'] ?? '')) {
                redirect(parse_url($referer, PHP_URL_PATH) ?: '/');
            }
            // Fallback: if no referer, redirect to a safe page
            if (!empty($_SESSION['user_id'])) {
                redirect('/hub');
            }
            redirect('/');
        }
    }
}
