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

    public static function input()
    {
        return '<input type="hidden" name="_csrf" value="' . htmlspecialchars(self::token()) . '">';
    }

    /**
     * Skip CSRF for provider callbacks (authenticated by signature / checkout id).
     */
    public static function isExemptPath(string $path): bool
    {
        $path = trim($path, '/');
        $exempt = [
            'premium/mpesa/callback', 'analytics/geo',
            'premium/stripe/webhook',
        ];
        return in_array($path, $exempt, true);
    }

    public static function verify(?string $path = null)
    {
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
            return;
        }
        if ($path !== null && self::isExemptPath($path)) {
            return;
        }
        if (!hash_equals($_SESSION['_csrf'] ?? '', $_POST['_csrf'] ?? '')) {
            http_response_code(419);
            exit('Invalid request token.');
        }
    }
}
