<?php

declare(strict_types=1);

/**
 * Pasarguard plan settings (server_plans.custom_sni) — user template only.
 */
class PasarguardConfig
{
    public static function isPanelServer(array $serverConfig): bool
    {
        return ($serverConfig['type'] ?? '') === 'pasarguard';
    }

    /** @return array{template_id:int} */
    public static function parsePlanSettings(?string $customSni): array
    {
        if ($customSni === null || $customSni === '') {
            return ['template_id' => 0];
        }
        $decoded = json_decode($customSni, true);
        if (!is_array($decoded)) {
            return ['template_id' => 0];
        }

        return [
            'template_id' => (int) ($decoded['template_id'] ?? $decoded['user_template_id'] ?? 0),
        ];
    }

    public static function encodePlanSettings(int $templateId): string
    {
        return json_encode([
            'pasarguard' => true,
            'template_id' => $templateId,
        ], JSON_UNESCAPED_UNICODE);
    }

    public static function hasTemplate(array $planSettings): bool
    {
        return (int) ($planSettings['template_id'] ?? 0) > 0;
    }

    public static function extractSubPath(string $subscriptionUrl): string
    {
        if (preg_match('~/sub/([^/?#]+)~', $subscriptionUrl, $match)) {
            return '/sub/' . $match[1];
        }

        return $subscriptionUrl;
    }

    /** Full subscription URL for delivery (ignores subLinkState). */
    public static function buildSubscriptionUrl(string $panelUrl, string $subscriptionUrlOrPath): string
    {
        $subscriptionUrlOrPath = trim($subscriptionUrlOrPath);
        if ($subscriptionUrlOrPath === '') {
            return '';
        }
        if (preg_match('~^https?://~i', $subscriptionUrlOrPath)) {
            return $subscriptionUrlOrPath;
        }
        $path = self::extractSubPath($subscriptionUrlOrPath);
        if ($path !== '' && $path[0] !== '/') {
            $path = '/' . ltrim($path, '/');
        }

        return rtrim($panelUrl, '/') . $path;
    }

    public static function extractSubToken(string $panelUrl, string $subscriptionUrlOrPath): string
    {
        $url = self::buildSubscriptionUrl($panelUrl, $subscriptionUrlOrPath);
        if (preg_match('~/sub/([^/?#]+)~', $url, $match)) {
            return urldecode($match[1]);
        }

        return '';
    }

    /** Customer-visible link (respects subLinkState). */
    public static function buildCustomerSubLink(string $panelUrl, string $subscriptionUrlOrPath): string
    {
        global $botState;
        if (($botState['subLinkState'] ?? 'off') !== 'on') {
            return '';
        }

        return self::buildSubscriptionUrl($panelUrl, $subscriptionUrlOrPath);
    }
}
