<?php

/**
 * Shared helpers for wizpanel ↔ bot (3x-ui v3 connection test, env file).
 */
class PanelBridge
{
    public static function botRoot(): string
    {
        $path = realpath(__DIR__ . '/..');
        return $path ?: dirname(__DIR__);
    }

    public static function envFilePath(): string
    {
        return self::botRoot() . DIRECTORY_SEPARATOR . 'xui-env.local.php';
    }

    /** @return array<string, string> */
    public static function loadXuiEnv(): array
    {
        $defaults = [
            'XUI_AUTH_MODE' => 'auto',
            'XUI_BASE_URL' => '',
            'XUI_API_TOKEN' => '',
            'XUI_USERNAME' => '',
            'XUI_PASSWORD' => '',
            'XUI_SUBSCRIPTION_BASE_URL' => '',
            'XUI_SUB_PATH' => '/sub/',
            'XUI_HTTP_TIMEOUT_SECONDS' => '15',
        ];

        $file = self::envFilePath();
        if (!file_exists($file)) {
            return $defaults;
        }

        $XUI_AUTH_MODE = $defaults['XUI_AUTH_MODE'];
        $XUI_BASE_URL = $defaults['XUI_BASE_URL'];
        $XUI_API_TOKEN = $defaults['XUI_API_TOKEN'];
        $XUI_USERNAME = $defaults['XUI_USERNAME'];
        $XUI_PASSWORD = $defaults['XUI_PASSWORD'];
        $XUI_SUBSCRIPTION_BASE_URL = $defaults['XUI_SUBSCRIPTION_BASE_URL'];
        $XUI_SUB_PATH = $defaults['XUI_SUB_PATH'];
        $XUI_HTTP_TIMEOUT_SECONDS = (int) $defaults['XUI_HTTP_TIMEOUT_SECONDS'];
        include $file;

        return [
            'XUI_AUTH_MODE' => (string) ($XUI_AUTH_MODE ?? $defaults['XUI_AUTH_MODE']),
            'XUI_BASE_URL' => (string) ($XUI_BASE_URL ?? $defaults['XUI_BASE_URL']),
            'XUI_API_TOKEN' => (string) ($XUI_API_TOKEN ?? $defaults['XUI_API_TOKEN']),
            'XUI_USERNAME' => (string) ($XUI_USERNAME ?? $defaults['XUI_USERNAME']),
            'XUI_PASSWORD' => (string) ($XUI_PASSWORD ?? $defaults['XUI_PASSWORD']),
            'XUI_SUBSCRIPTION_BASE_URL' => (string) ($XUI_SUBSCRIPTION_BASE_URL ?? $defaults['XUI_SUBSCRIPTION_BASE_URL']),
            'XUI_SUB_PATH' => (string) ($XUI_SUB_PATH ?? $defaults['XUI_SUB_PATH']),
            'XUI_HTTP_TIMEOUT_SECONDS' => (string) ($XUI_HTTP_TIMEOUT_SECONDS ?? $defaults['XUI_HTTP_TIMEOUT_SECONDS']),
        ];
    }

    /** @param array<string, string> $data */
    public static function saveXuiEnv(array $data): array
    {
        $path = self::envFilePath();
        $dir = dirname($path);
        if (!is_dir($dir) || !is_writable($dir)) {
            return ['success' => false, 'msg' => 'پوشه ربات قابل نوشتن نیست: ' . $dir];
        }

        $esc = static function ($s) {
            return str_replace("'", "\\'", (string) $s);
        };

        $content = "<?php\n"
            . "// Generated from wizpanel — 3x-ui v3 settings\n"
            . "\$XUI_AUTH_MODE = '" . $esc($data['XUI_AUTH_MODE'] ?? 'auto') . "';\n"
            . "\$XUI_BASE_URL = '" . $esc($data['XUI_BASE_URL'] ?? '') . "';\n"
            . "\$XUI_API_TOKEN = '" . $esc($data['XUI_API_TOKEN'] ?? '') . "';\n"
            . "\$XUI_USERNAME = '" . $esc($data['XUI_USERNAME'] ?? '') . "';\n"
            . "\$XUI_PASSWORD = '" . $esc($data['XUI_PASSWORD'] ?? '') . "';\n"
            . "\$XUI_SUBSCRIPTION_BASE_URL = '" . $esc($data['XUI_SUBSCRIPTION_BASE_URL'] ?? '') . "';\n"
            . "\$XUI_SUB_PATH = '" . $esc($data['XUI_SUB_PATH'] ?? '/sub/') . "';\n"
            . "\$XUI_HTTP_TIMEOUT_SECONDS = " . (int) ($data['XUI_HTTP_TIMEOUT_SECONDS'] ?? 15) . ";\n";

        if (@file_put_contents($path, $content) === false) {
            return ['success' => false, 'msg' => 'نوشتن فایل env ناموفق بود'];
        }
        return ['success' => true, 'msg' => 'ذخیره شد', 'path' => $path];
    }

    /**
     * @return array{success:bool,msg:string,detail?:string}
     */
    public static function testPanelConnection(string $panelType, string $panelUrl, string $username, string $password, string $apiToken = '', string $subscriptionBaseUrl = ''): array
    {
        $panelUrl = rtrim(trim($panelUrl), '/');
        if ($panelUrl === '') {
            return ['success' => false, 'msg' => 'آدرس پنل خالی است'];
        }

        if ($panelType === 'marzban') {
            return self::testMarzban($panelUrl, $username, $password);
        }

        if ($panelType === 'pasarguard') {
            require_once __DIR__ . '/PasarguardApiClient.php';
            $result = PasarguardApiClient::probeConnection($panelUrl, $username, $password);
            return [
                'success' => !empty($result['success']),
                'msg' => (string) ($result['msg'] ?? ''),
            ];
        }

        require_once __DIR__ . '/XuiV3Config.php';

        $token = trim($apiToken);
        if ($token === '') {
            $env = self::loadXuiEnv();
            $token = trim($env['XUI_API_TOKEN'] ?? '');
        }

        $result = XuiV3Config::probeConnection($panelUrl, $username, $password, $token);
        if (!empty($result['success'])) {
            return [
                'success' => true,
                'msg' => 'اتصال موفق — API v3',
                'detail' => (string) ($result['detail'] ?? $result['msg'] ?? ''),
            ];
        }

        return [
            'success' => false,
            'msg' => (string) ($result['msg'] ?? 'اتصال برقرار نشد'),
            'detail' => (string) ($result['detail'] ?? ''),
        ];
    }

    /** @return array{success:bool,msg:string} */
    private static function testMarzban(string $panelUrl, string $username, string $password): array
    {
        $url = rtrim($panelUrl, '/') . '/api/admin/token';
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => http_build_query(['username' => $username, 'password' => $password]),
            CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded', 'Accept: application/json'],
            CURLOPT_CONNECTTIMEOUT => 15,
            CURLOPT_TIMEOUT => 15,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_SSL_VERIFYPEER => false,
        ]);
        $raw = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);
        if ($raw === false) {
            return ['success' => false, 'msg' => 'curl: ' . $err];
        }
        $json = json_decode($raw, true);
        if (!empty($json['access_token'])) {
            return ['success' => true, 'msg' => 'اتصال Marzban موفق'];
        }
        return ['success' => false, 'msg' => 'Marzban: ' . ($json['detail'] ?? $json['msg'] ?? 'login failed')];
    }
}
