<?php

declare(strict_types=1);

/**
 * Pasarguard plan settings (server_plans.custom_sni).
 * Plans are now group-based: the group determines inbound routing.
 * All other specs (volume, days, price) are defined in the WizWiz plan.
 */
class PasarguardConfig
{
    public static function isPanelServer(array $serverConfig): bool
    {
        return ($serverConfig['type'] ?? '') === 'pasarguard';
    }

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

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

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

    /** Plan is ready to use if it has a group_id (or legacy template_id). */
    public static function hasPlanConfig(array $planSettings): bool
    {
        return (int) ($planSettings['group_id'] ?? 0) > 0
            || (int) ($planSettings['template_id'] ?? 0) > 0;
    }

    /** @deprecated Use hasPlanConfig() */
    public static function hasTemplate(array $planSettings): bool
    {
        return self::hasPlanConfig($planSettings);
    }

    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);
    }
}
