<?php
/**
 * Telegram SOCKS proxy helpers (for hosts without direct api.telegram.org access).
 *
 * Supported formats:
 * - https://t.me/socks?server=IP&port=PORT&user=USER&pass=PASS
 * - socks5://user:pass@host:port
 * - socks5h://user:pass@host:port
 */

function parse_telegram_proxy(?string $proxy): ?array
{
    if ($proxy === null) {
        return null;
    }

    $proxy = trim($proxy);
    if ($proxy === '' || strtolower($proxy) === 'null' || strtolower($proxy) === 'off') {
        return null;
    }

    if (preg_match('#^(https?://)?(t\.me|telegram\.me)/socks#i', $proxy)) {
        $query = parse_url($proxy, PHP_URL_QUERY);
        parse_str((string) $query, $params);
        if (empty($params['server']) || empty($params['port'])) {
            return null;
        }
        return [
            'type' => 'socks5',
            'host' => (string) $params['server'],
            'port' => (int) $params['port'],
            'user' => (string) ($params['user'] ?? ''),
            'pass' => (string) ($params['pass'] ?? ''),
        ];
    }

    if (preg_match('#^socks5h?://#i', $proxy)) {
        $parsed = parse_url($proxy);
        if (empty($parsed['host'])) {
            return null;
        }
        return [
            'type' => 'socks5',
            'host' => (string) $parsed['host'],
            'port' => (int) ($parsed['port'] ?? 1080),
            'user' => (string) ($parsed['user'] ?? ''),
            'pass' => (string) ($parsed['pass'] ?? ''),
        ];
    }

    // host:port:user:pass
    if (preg_match('/^([^:]+):(\d+):([^:]*):(.*)$/', $proxy, $m)) {
        return [
            'type' => 'socks5',
            'host' => $m[1],
            'port' => (int) $m[2],
            'user' => $m[3],
            'pass' => $m[4],
        ];
    }

    return null;
}

function get_active_telegram_proxy(): ?array
{
    global $telegram_proxy;
    return parse_telegram_proxy($telegram_proxy ?? null);
}

function curl_apply_telegram_proxy($ch): bool
{
    $cfg = get_active_telegram_proxy();
    if (!$cfg || $ch === false) {
        return false;
    }

    $proxyAddress = $cfg['host'] . ':' . $cfg['port'];
    $proxyType = defined('CURLPROXY_SOCKS5_HOSTNAME') ? CURLPROXY_SOCKS5_HOSTNAME : CURLPROXY_SOCKS5;

    curl_setopt($ch, CURLOPT_PROXYTYPE, $proxyType);
    curl_setopt($ch, CURLOPT_PROXY, $proxyAddress);

    if (($cfg['user'] ?? '') !== '') {
        curl_setopt($ch, CURLOPT_PROXYUSERPWD, $cfg['user'] . ':' . ($cfg['pass'] ?? ''));
    }

    return true;
}

/**
 * HTTP request helper for Telegram API URLs (GET/POST) with optional proxy.
 */
function telegram_http_request(string $url, string $method = 'GET', $postFields = null, int $timeout = 25): ?string
{
    $ch = curl_init($url);
    if ($ch === false) {
        return null;
    }

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    if (strtoupper($method) === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        if ($postFields !== null) {
            curl_setopt(
                $ch,
                CURLOPT_POSTFIELDS,
                is_array($postFields) ? http_build_query($postFields) : $postFields
            );
        }
    }

    curl_apply_telegram_proxy($ch);

    $response = curl_exec($ch);
    if ($response === false) {
        error_log('telegram_http_request failed: ' . curl_error($ch));
        curl_close($ch);
        return null;
    }

    curl_close($ch);
    return $response;
}

function telegram_proxy_is_enabled(): bool
{
    return get_active_telegram_proxy() !== null;
}
