<?php
include_once dirname(__DIR__) . '/settings/config_xui_api.php'; // لود مستقیم فایل توابع API
include_once dirname(__DIR__) . '/settings/config_utils.php';
global $connection, $data, $text, $from_id, $admin, $userInfo, $message_id, $mainValues, $buttonValues, $cancelKey, $removeKeyboard, $fileid, $caption, $botState, $first_name, $username, $newRremark, $days, $volume, $marzbanText, $configLocation, $configReality, $botUrl;


// --- Start of Range 1676 to 1745 ---
if ($data == "availableServers") {
    $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `active` = 1 AND `type` = 'client_centric'");
    $stmt->execute();
    $serversList = $stmt->get_result();
    $stmt->close();

    $keys = array();
    $keys[] = [
        ['text' => "تعداد باقیمانده", 'callback_data' => "NetFreedomVPN"],
        ['text' => "پلن", 'callback_data' => "NetFreedomVPN"],
        ['text' => 'سرور', 'callback_data' => "NetFreedomVPN"]
    ];
    while ($file_detail = $serversList->fetch_assoc()) {
        $title = $file_detail['title'];
        $server_id = $file_detail['server_id'];
        $acount = $file_detail['acount'];

        $stmt = $connection->prepare("SELECT `title` FROM `server_info` WHERE `id` = ?");
        $stmt->bind_param("i", $server_id);
        $stmt->execute();
        $nameRes = $stmt->get_result();
        $stmt->close();

        if ($nameRes->num_rows > 0) {
            $name = $nameRes->fetch_assoc()['title'];
            $keys[] = [
                ['text' => ($acount == 0 ? "نامحدود ♾" : $acount . " اکانت"), 'callback_data' => "NetFreedomVPN"],
                ['text' => $title ?? " ", 'callback_data' => "NetFreedomVPN"],
                ['text' => $name ?? " ", 'callback_data' => "NetFreedomVPN"]
            ];
        }
    }
    $keys[] = [getBtn('back_button', 'mainMenu')];
    bot('editMessageText', ['chat_id' => $from_id, 'message_id' => $message_id, 'text' => "🟢 | موجودی پلن‌های متصل به سرور (v3.1.0):", 'reply_markup' => json_encode(['inline_keyboard' => $keys]), 'parse_mode' => "HTML"]);
    exit();
}

if ($data == "availableServers2") {
    $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `active` = 1 AND `type` = 'client_centric'");
    $stmt->execute();
    $serversList = $stmt->get_result();
    $stmt->close();

    $keys = array();
    $keys[] = [
        ['text' => "ظرفیت سرور", 'callback_data' => "NetFreedomVPN"],
        ['text' => 'نام سرور', 'callback_data' => "NetFreedomVPN"]
    ];
    while ($file_detail2 = $serversList->fetch_assoc()) {
        $server_id2 = $file_detail2['server_id'];

        $stmt = $connection->prepare("SELECT * FROM `server_info` WHERE `id` = ? AND `active` = 1");
        $stmt->bind_param("i", $server_id2);
        $stmt->execute();
        $nameRes = $stmt->get_result();
        $stmt->close();

        if ($nameRes->num_rows > 0) {
            $sInfo = $nameRes->fetch_assoc();
            $name = $sInfo['title'];
            $acount2 = $sInfo['ucount'];

            $keys[] = [
                ['text' => $acount2 . " ظرفیت خروجی", 'callback_data' => "NetFreedomVPN"],
                ['text' => $name ?? " ", 'callback_data' => "NetFreedomVPN"],
            ];
        }
    }
    // حذف سطرهای تکراری سرورها در آرایه برای تمیزی خروجی شیشه‌ای
    $keys = array_map("unserialize", array_unique(array_map("serialize", $keys)));
    $keys[] = [getBtn('back_button', 'mainMenu')];
    bot('editMessageText', ['chat_id' => $from_id, 'message_id' => $message_id, 'text' => "🟢 | وضعیت کلی ظرفیت اتمی سرورها:", 'reply_markup' => json_encode(['inline_keyboard' => array_values($keys)]), 'parse_mode' => "HTML"]);
    exit();
}

// -------------------------------------------------------------------------
// ۲. مدیریت درخواست‌های نمایندگی (Agency Settings) - نسخه فیکس شده
// -------------------------------------------------------------------------

// --- Start of Range 3453 to 3762 ---
if ($data == "showUUIDLeft" && ($botState['searchState'] == "on" || $from_id == $admin)) {
    delMessage();
    sendMessage($mainValues['send_config_uuid'], $cancelKey);
    setUser('showAccount');
}

if ($data == "promptSendSubLink") {
    delMessage();
    $kb = json_encode(['inline_keyboard' => [
        [['text' => "❌ انصراف", 'callback_data' => "mainMenu", 'style' => 'danger', 'icon_custom_emoji_id' => '5215680783863261658']]
    ]]);
    sendMessage("🔗 لطفاً لینک ساب (اشتراک) خود را ارسال کنید تا مشخصات کانفیگ‌ها استخراج شود:", $kb);
    setUser('sendSubLinkStep');
    exit();
}

if ($userInfo['step'] == "sendSubLinkStep" && $text != $buttonValues['cancel']) {
    $token = trim($text);
    if (preg_match('/\/sub\/([a-zA-Z0-9\-]+)/', $text, $subMatch)) {
        $token = $subMatch[1];
    }
    
    // Find the UUID from orders_list using the token
    $stmt = $connection->prepare("SELECT `uuid`, `remark` FROM `orders_list` WHERE `token` = ? OR `remark` = ? OR `uuid` = ? LIMIT 1");
    $stmt->bind_param("sss", $token, $token, $token);
    $stmt->execute();
    $dbRes = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if ($dbRes) {
        $text = !empty($dbRes['uuid']) ? $dbRes['uuid'] : $dbRes['remark'];
        $userInfo['step'] = "showAccount"; // change step to showAccount and proceed
    } else {
        $kb = json_encode(['inline_keyboard' => [
            [['text' => "❌ انصراف", 'callback_data' => "mainMenu", 'style' => 'danger', 'icon_custom_emoji_id' => '5215680783863261658']]
        ]]);
        sendMessage("❌ متأسفانه اشتراکی با این مشخصات یا لینک ساب یافت نشد. لطفا لینک صحیح را بفرستید یا انصراف دهید:", $kb);
        exit();
    }
}
if ($userInfo['step'] == "showAccount" and $text != $buttonValues['cancel']) {
    // Automatically detect sub link or token in showAccount step
    if (preg_match('/\/sub\/([a-zA-Z0-9\-]+)/', (string)$text, $subMatch)) {
        $token = $subMatch[1];
        $stmt = $connection->prepare("SELECT `uuid`, `remark` FROM `orders_list` WHERE `token` = ? LIMIT 1");
        $stmt->bind_param("s", $token);
        $stmt->execute();
        $dbRes = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        if ($dbRes) {
            $text = !empty($dbRes['uuid']) ? $dbRes['uuid'] : $dbRes['remark'];
        }
    }

    if (preg_match('/^vmess:\/\/(.*)/', (string)$text, $match)) {
        $jsonDecode = json_decode(base64_decode($match[1]), true);
        $text = $jsonDecode['id'];
        $marzbanText = $match[1];
    } elseif (preg_match('/^vless:\/\/(.*?)\@/', (string)$text, $match)) {
        $marzbanText = $text = $match[1];
    } elseif (preg_match('/^trojan:\/\/(.*?)\@/', (string)$text, $match)) {
        $marzbanText = $text = $match[1];
    } elseif (!preg_match('/[a-f0-9]{8}\-[a-f0-9]{4}\-4[a-f0-9]{3}\-(8|9|a|b)[a-f0-9]{3}\-[a-f0-9]{12}/', (string)$text)) {
        sendMessage($mainValues['not_correct_text']);
        exit();
    }
    $text = htmlspecialchars(stripslashes(trim($text)));
    sendMessage($mainValues['please_wait_message'], $removeKeyboard);

    $stmt = $connection->prepare("SELECT * FROM `server_config`");
    $stmt->execute();
    $serversList = $stmt->get_result();
    $stmt->close();
    $found = false;
    $isMarzban = false;
    while ($row = $serversList->fetch_assoc()) {
        $serverId = $row['id'];
        $serverType = $row['type'];

        if ($serverType == "marzban") {
            $usersList = getMarzbanJson($serverId)->users;
            if (strstr(json_encode($usersList, JSON_UNESCAPED_UNICODE), $marzbanText) && !empty($marzbanText)) {
                $found = true;
                $isMarzban = true;
                foreach ($usersList as $key => $config) {
                    if (strstr(json_encode($config->links, JSON_UNESCAPED_UNICODE), $marzbanText)) {
                        $remark = $config->username;
                        $total = $config->data_limit != 0 ? sumerize($config->data_limit) : "نامحدود";
                        $totalUsed = sumerize($config->used_traffic);
                        $state = $config->status == "active" ? $buttonValues['active'] : $buttonValues['deactive'];
                        $expiryTime = $config->expire != 0 ? jdate("Y-m-d H:i:s", $config->expire) : "نامحدود";
                        $leftMb = $config->data_limit != 0 ? $config->data_limit - $config->used_traffic : "نامحدود";

                        if (is_numeric($leftMb)) {
                            if ($leftMb < 0)
                                $leftMb = 0;
                            else
                                $leftMb = sumerize($leftMb);
                        }

                        $expiryDay = $config->expire != 0 ?
                            floor(
                                ($config->expire - time()) / (60 * 60 * 24)
                            ) :
                            "نامحدود";
                        if (is_numeric($expiryDay)) {
                            if ($expiryDay < 0)
                                $expiryDay = 0;
                        }
                        $configLocation = ["remark" => $remark, "uuid" => $text, "marzban" => true];
                        break;
                    }
                }
                break;
            }
        } else {
            $response = getJson($serverId);
            if ($response->success) {
                if (strstr(json_encode($response->obj), $text)) {
                    $found = true;
                    $list = $response->obj;
                    if (!isset($list[0]->clientStats)) {
                        foreach ($list as $keys => $packageInfo) {
                            if (strstr($packageInfo->settings, $text)) {
                                $configLocation = ["remark" => $packageInfo->remark, "uuid" => $text];
                                $remark = $packageInfo->remark;
                                $upload = sumerize($packageInfo->up);
                                $download = sumerize($packageInfo->down);
                                $state = $packageInfo->enable == true ? $buttonValues['active'] : $buttonValues['deactive'];
                                $totalUsed = sumerize($packageInfo->up + $packageInfo->down);
                                $total = $packageInfo->total != 0 ? sumerize($packageInfo->total) : "نامحدود";
                                $expiryTime = $packageInfo->expiryTime != 0 ? jdate("Y-m-d H:i:s", substr($packageInfo->expiryTime, 0, -3)) : "نامحدود";
                                $leftMb = $packageInfo->total != 0 ? sumerize($packageInfo->total - $packageInfo->up - $packageInfo->down) : "نامحدود";
                                $expiryDay = $packageInfo->expiryTime != 0 ?
                                    floor(
                                        (substr($packageInfo->expiryTime, 0, -3) - time()) / (60 * 60 * 24)
                                    )
                                    :
                                    "نامحدود";
                                if (is_numeric($expiryDay)) {
                                    if ($expiryDay < 0)
                                        $expiryDay = 0;
                                }
                                break;
                            }
                        }
                    } else {
                        $keys = -1;
                        $settings = array_column($list, 'settings');
                        foreach ($settings as $key => $value) {
                            if (strstr($value, $text)) {
                                $keys = $key;
                                break;
                            }
                        }
                        if ($keys == -1) {
                            $found = false;
                            break;
                        }
                        $clientsSettings = json_decode($list[$keys]->settings, true)['clients'];
                        if (!is_array($clientsSettings)) {
                            sendMessage("با عرض پوزش، متأسفانه مشکلی رخ داده است، لطفا مجدد اقدام کنید");
                            exit();
                        }
                        $settingsId = array_column($clientsSettings, 'id');
                        $settingKey = array_search($text, $settingsId);

                        if (!isset($clientsSettings[$settingKey]['email'])) {
                            $packageInfo = $list[$keys];
                            $configLocation = ["remark" => $packageInfo->remark, "uuid" => $text];
                            $remark = $packageInfo->remark;
                            $upload = sumerize($packageInfo->up);
                            $download = sumerize($packageInfo->down);
                            $state = $packageInfo->enable == true ? $buttonValues['active'] : $buttonValues['deactive'];
                            $totalUsed = sumerize($packageInfo->up + $packageInfo->down);
                            $total = $packageInfo->total != 0 ? sumerize($packageInfo->total) : "نامحدود";
                            $expiryTime = $packageInfo->expiryTime != 0 ? jdate("Y-m-d H:i:s", substr($packageInfo->expiryTime, 0, -3)) : "نامحدود";
                            $leftMb = $packageInfo->total != 0 ? sumerize($packageInfo->total - $packageInfo->up - $packageInfo->down) : "نامحدود";
                            if (is_numeric($leftMb)) {
                                if ($leftMb < 0) {
                                    $leftMb = 0;
                                } else {
                                    $leftMb = sumerize($packageInfo->total - $packageInfo->up - $packageInfo->down);
                                }
                            }


                            $expiryDay = $packageInfo->expiryTime != 0 ?
                                floor(
                                    (substr($packageInfo->expiryTime, 0, -3) - time()) / (60 * 60 * 24)
                                ) :
                                "نامحدود";
                            if (is_numeric($expiryDay)) {
                                if ($expiryDay < 0)
                                    $expiryDay = 0;
                            }
                        } else {
                            $email = $clientsSettings[$settingKey]['email'];
                            $clientState = $list[$keys]->clientStats;
                            $emails = array_column($clientState, 'email');
                            $emailKey = array_search($email, $emails);

                            // if($clientState[$emailKey]->total != 0 || $clientState[$emailKey]->up != 0  ||  $clientState[$emailKey]->down != 0 || $clientState[$emailKey]->expiryTime != 0){
                            if (count($clientState) > 1) {
                                $configLocation = ["id" => $list[$keys]->id, "remark" => $email, "uuid" => $text];
                                $upload = sumerize($clientState[$emailKey]->up);
                                $download = sumerize($clientState[$emailKey]->down);
                                $total = $clientState[$emailKey]->total == 0 && $list[$keys]->total != 0 ? $list[$keys]->total : $clientState[$emailKey]->total;
                                $leftMb = $total != 0 ? ($total - $clientState[$emailKey]->up - $clientState[$emailKey]->down) : "نامحدود";
                                if (is_numeric($leftMb)) {
                                    if ($leftMb < 0) {
                                        $leftMb = 0;
                                    } else {
                                        $leftMb = sumerize($total - $clientState[$emailKey]->up - $clientState[$emailKey]->down);
                                    }
                                }
                                $totalUsed = sumerize($clientState[$emailKey]->up + $clientState[$emailKey]->down);
                                $total = $total != 0 ? sumerize($total) : "نامحدود";
                                $expTime = $clientState[$emailKey]->expiryTime == 0 && $list[$keys]->expiryTime ? $list[$keys]->expiryTime : $clientState[$emailKey]->expiryTime;
                                $expiryTime = $expTime != 0 ? jdate("Y-m-d H:i:s", substr($expTime, 0, -3)) : "نامحدود";
                                $expiryDay = $expTime != 0 ?
                                    floor(
                                        ((substr($expTime, 0, -3) - time()) / (60 * 60 * 24))
                                    ) :
                                    "نامحدود";
                                if (is_numeric($expiryDay)) {
                                    if ($expiryDay < 0)
                                        $expiryDay = 0;
                                }
                                $state = $clientState[$emailKey]->enable == true ? $buttonValues['active'] : $buttonValues['deactive'];
                                $remark = $email;
                            } else {
                                $clientUpload = $clientState[$emailKey]->up;
                                $clientDownload = $clientState[$emailKey]->down;
                                $clientTotal = $clientState[$emailKey]->total;
                                $clientExpTime = $clientState[$emailKey]->expiryTime;

                                $up = $list[$keys]->up;
                                $down = $list[$keys]->down;
                                $total = $list[$keys]->total;
                                $expiry = $list[$keys]->expiryTime;

                                if (($clientTotal != 0 || $clientTotal != null) && ($clientExpTime != 0 || $clientExpTime != null)) {
                                    $up = $clientUpload;
                                    $down = $clientDownload;
                                    $total = $clientTotal;
                                    $expiry = $clientExpTime;
                                }

                                $upload = sumerize($up);
                                $download = sumerize($down);
                                $configLocation = ["uuid" => $text, "remark" => $list[$keys]->remark];
                                $leftMb = $total != 0 ? ($total - $up - $down) : "نامحدود";
                                if (is_numeric($leftMb)) {
                                    if ($leftMb < 0) {
                                        $leftMb = 0;
                                    } else {
                                        $leftMb = sumerize($total - $up - $down);
                                    }
                                }
                                $totalUsed = sumerize($up + $down);
                                $total = $total != 0 ? sumerize($total) : "نامحدود";


                                $expiryTime = $expiry != 0 ? jdate("Y-m-d H:i:s", substr($expiry, 0, -3)) : "نامحدود";
                                $expiryDay = $expiry != 0 ?
                                    floor(
                                        ((substr($expiry, 0, -3) - time()) / (60 * 60 * 24))
                                    ) :
                                    "نامحدود";
                                if (is_numeric($expiryDay)) {
                                    if ($expiryDay < 0)
                                        $expiryDay = 0;
                                }
                                $state = $list[$keys]->enable == true ? $buttonValues['active'] : $buttonValues['deactive'];
                                $remark = $list[$keys]->remark;
                            }
                        }
                    }
                    break;
                }
            }
        }
    }
    if (!$found) {
        $keyboard = json_encode(['inline_keyboard' => [
            [['text' => "🔗 ارسال لینک ساب", 'callback_data' => "promptSendSubLink"]],
            [['text' => "🔙 بازگشت", 'callback_data' => "mainMenu", 'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']]
        ]]);
        sendMessage("ای وای ، کانفیگ شما یافت نشد! 😔\n\nاگر لینک ساب (اشتراک) خود را دارید، روی دکمه زیر کلیک کنید و آن را بفرستید تا مشخصات آن را استخراج کنیم:", $keyboard);
    } else {
        setUser();
        @bot('deleteMessage', ['chat_id' => $from_id, 'message_id' => $message_id]);
        @bot('deleteMessage', ['chat_id' => $from_id, 'message_id' => $message_id - 1]);
        $keys = json_encode(['inline_keyboard' => array_merge([
            [
                ['text' => $state ?? " ", 'callback_data' => "NetFreedomVPN"],
                ['text' => "🔘 وضعیت اکانت 🔘", 'callback_data' => "NetFreedomVPN"],
            ],
            [
                ['text' => $remark ?? " ", 'callback_data' => "NetFreedomVPN"],
                ['text' => "« نام اکانت »", 'callback_data' => "NetFreedomVPN"],
            ]
        ], (!$isMarzban ? [
            [
                ['text' => $upload ?? " ", 'callback_data' => "NetFreedomVPN"],
                ['text' => "√ آپلود √", 'callback_data' => "NetFreedomVPN"],
            ],
            [
                ['text' => $download ?? " ", 'callback_data' => "NetFreedomVPN"],
                ['text' => "√ دانلود √", 'callback_data' => "NetFreedomVPN"],
            ]
        ] : [
            [
                ['text' => $totalUsed ?? " ", 'callback_data' => "NetFreedomVPN"],
                ['text' => "√ آپلود + دانلود √", 'callback_data' => "NetFreedomVPN"],
            ]
        ]), [
            [
                ['text' => $total ?? " ", 'callback_data' => "NetFreedomVPN"],
                ['text' => "† حجم کلی †", 'callback_data' => "NetFreedomVPN"],
            ],
            [
                ['text' => $leftMb ?? " ", 'callback_data' => "NetFreedomVPN"],
                ['text' => "~ حجم باقیمانده ~", 'callback_data' => "NetFreedomVPN"],
            ],
            [
                ['text' => $expiryTime ?? " ", 'callback_data' => "NetFreedomVPN"],
                ['text' => "تاریخ اتمام", 'callback_data' => "NetFreedomVPN"],
            ],
            [
                ['text' => $expiryDay ?? " ", 'callback_data' => "NetFreedomVPN"],
                ['text' => "تعداد روز باقیمانده", 'callback_data' => "NetFreedomVPN"],
            ],
            (($botState['renewAccountState'] == "on" && $botState['updateConfigLinkState'] == "on") ?
                [
                    ['text' => $buttonValues['renew_config'], 'callback_data' => "sConfigRenew" . $serverId],
                    ['text' => $buttonValues['update_config_connection'], 'callback_data' => "sConfigUpdate" . $serverId],
                ] : []
            ),
            (($botState['renewAccountState'] != "on" && $botState['updateConfigLinkState'] == "on") ?
                [
                    ['text' => $buttonValues['update_config_connection'], 'callback_data' => "sConfigUpdate" . $serverId]
                ] : []
            ),
            (($botState['renewAccountState'] == "on" && $botState['updateConfigLinkState'] != "on") ?
                [
                    ['text' => $buttonValues['renew_config'], 'callback_data' => "sConfigRenew" . $serverId]
                ] : []
            ),
            [['text' => "صفحه اصلی", 'callback_data' => "mainMenu"]]
        ])]);
        setUser(json_encode($configLocation, 488), "temp");
        sendMessage("🔰مشخصات حسابت:", $keys, "MarkDown");
    }
}


// --- Start of Range 3763 to 4089 ---
if (preg_match('/sConfigRenew(\d+)/', (string)$data, $match)) {
    if ($botState['sellState'] == "off" && $from_id != $admin) {
        alert($mainValues['bot_is_updating']);
        exit();
    }

    alert($mainValues['please_wait_message']);
    $server_id = $match[1];
    if (empty($userInfo['temp'])) {
        delMessage();
        exit();
    }

    $configInfo = json_decode($userInfo['temp'], true);
    $inboundId = $configInfo['id'] ?? 0;
    $uuid = $configInfo['uuid'];
    $remark = $configInfo['remark'];

    if (isset($configInfo['marzban'])) {
        $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `server_id` = ? AND `custom_sni` LIKE '%inbounds%' AND `active` = 1 AND `price` != 0");
        $stmt->bind_param("i", $server_id);
    } else {
        $response = getJson($server_id)->obj;
        if ($response == null) {
            delMessage();
            exit();
        }
        if ($inboundId == 0) {
            foreach ($response as $row) {
                $clients = json_decode($row->settings)->clients;
                if ($clients[0]->id == $uuid || $clients[0]->password == $uuid) {
                    $port = $row->port;
                    $protocol = $row->protocol;
                    $configReality = json_decode($row->streamSettings)->security == "reality" ? "true" : "false";
                    break;
                }
            }
            $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `server_id` = ? AND `inbound_id` = 0 AND `protocol` = ? AND `active` = 1 AND `price` != 0 AND `rahgozar` = 0");
        } else {
            foreach ($response as $row) {
                if ($row->id == $inboundId) {
                    $port = $row->port;
                    $protocol = $row->protocol;
                    $configReality = json_decode($row->streamSettings)->security == "reality" ? "true" : "false";
                    break;
                }
            }
            $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `server_id` = ? AND `inbound_id` != 0 AND `protocol` = ? AND `active` = 1 AND `price` != 0 AND `rahgozar` = 0");
        }
        $stmt->bind_param("is", $server_id, $protocol);
    }

    $stmt->execute();
    $plans = $stmt->get_result();
    $stmt->close();
    if ($plans->num_rows > 0) {
        $keyboard = [];
        while ($file = $plans->fetch_assoc()) {
            $add = false;

            if (isset($configInfo['marzban']))
                $add = true;
            else {
                $stmt = $connection->prepare("SELECT * FROM `server_config` WHERE `id` = ?");
                $stmt->bind_param("i", $server_id);
                $stmt->execute();
                $isReality = $stmt->get_result()->fetch_assoc()['reality'];
                $stmt->close();

                if ($isReality == $configReality)
                    $add = true;
            }

            if ($add) {
                $id = $file['id'];
                $name = $file['title'];
                $price = $file['price'];
                $price = ($price == 0) ? 'رایگان' : number_format($price) . ' تومان ';
                $keyboard[] = ['text' => "$name - $price", 'callback_data' => "sConfigRenewPlan{$id}_{$inboundId}"];
            }
        }
        $keyboard[] = ['text' => $buttonValues['back_to_main'], 'callback_data' => "mainMenu", 'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747'];
        $keyboard = array_chunk($keyboard, 1);

        // متن تغییر کرده است
        editText($message_id, "مرحله سوم:

لطفا جهت تمدید سرویس، یکی از پلن های زیر را انتخاب نمایید.", json_encode(['inline_keyboard' => $keyboard]));
    } else {
        // متن پیام خطا هم رسمی شد
        sendMessage("در حال حاضر پلنی برای تمدید موجود نیست.");
    }
}
if (preg_match('/sConfigRenewPlan(\d+)_(\d+)/', (string)$data, $match) && ($botState['sellState'] == "on" || $from_id == $admin) && $text != $buttonValues['cancel']) {
    $id = $match[1];
    $inbound_id = $match[2];


    if (empty($userInfo['temp'])) {
        delMessage();
        exit();
    }

    $configInfo = json_decode($userInfo['temp'], true);
    $uuid = $configInfo['uuid'];
    $remark = $configInfo['remark'];

    alert($mainValues['receving_information']);
    delMessage();
    $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `id`=? and `active`=1");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $respd = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    // بررسی تمدید از سهمیه نماینده
    $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `uuid` = ? LIMIT 1");
    $stmt->bind_param("s", $uuid);
    $stmt->execute();
    $orderRow = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if ($orderRow && $orderRow['agent_bought'] == 1) {
        $agentUserId = $orderRow['userid'];
        $stmt = $connection->prepare("SELECT * FROM `users` WHERE `userid` = ?");
        $stmt->bind_param("s", $agentUserId);
        $stmt->execute();
        $agentUser = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if ($agentUser && $agentUser['is_agent'] == 1) {
            $agent_vol = floatval($agentUser['agent_volume'] ?? 0);
            $agent_lim = intval($agentUser['agent_limit'] ?? 0);

            // اگر نماینده سهمیه فعال دارد (بیشتر از صفر)
            if ($agent_lim > 0 || $agent_vol > 0) {
                $plan_vol = floatval($respd['volume']);
                $days = intval($respd['days']);
                $server_id = $respd['server_id'];
                $isMarzban = isset($configInfo['marzban']);

                // کسر سهمیه نماینده
                if ($agent_vol > 0 && $agent_lim > 0) {
                    $stmt = $connection->prepare("UPDATE `users` SET `agent_volume` = GREATEST(0, `agent_volume` - ?), `agent_limit` = GREATEST(0, `agent_limit` - 1) WHERE `userid` = ?");
                    $stmt->bind_param("ds", $plan_vol, $agentUserId);
                } elseif ($agent_vol > 0) {
                    $stmt = $connection->prepare("UPDATE `users` SET `agent_volume` = GREATEST(0, `agent_volume` - ?) WHERE `userid` = ?");
                    $stmt->bind_param("ds", $plan_vol, $agentUserId);
                } else {
                    $stmt = $connection->prepare("UPDATE `users` SET `agent_limit` = GREATEST(0, `agent_limit` - 1) WHERE `userid` = ?");
                    $stmt->bind_param("s", $agentUserId);
                }
                $stmt->execute();
                $stmt->close();

                // انجام عملیات تمدید کلاینت روی سرور
                if ($isMarzban) {
                    $apiRes = editMarzbanConfig($server_id, ['remark' => $remark, 'days' => $days, 'volume' => $plan_vol]);
                } else {
                    if ($inbound_id > 0) {
                        $apiRes = editClientTraffic($server_id, $inbound_id, $uuid, $plan_vol, $days, "renew");
                    } else {
                        $apiRes = editInboundTraffic($server_id, $uuid, $plan_vol, $days, "renew");
                    }
                }

                if (is_null($apiRes) || (isset($apiRes->success) && !$apiRes->success)) {
                    // در صورت خطای پنل، سهمیه کسر شده را بازمی‌گردانیم تا حقی ضایع نشود
                    if ($agent_vol > 0 && $agent_lim > 0) {
                        $stmt = $connection->prepare("UPDATE `users` SET `agent_volume` = `agent_volume` + ?, `agent_limit` = `agent_limit` + 1 WHERE `userid` = ?");
                        $stmt->bind_param("ds", $plan_vol, $agentUserId);
                    } elseif ($agent_vol > 0) {
                        $stmt = $connection->prepare("UPDATE `users` SET `agent_volume` = `agent_volume` + ? WHERE `userid` = ?");
                        $stmt->bind_param("ds", $plan_vol, $agentUserId);
                    } else {
                        $stmt = $connection->prepare("UPDATE `users` SET `agent_limit` = `agent_limit` + 1 WHERE `userid` = ?");
                        $stmt->bind_param("s", $agentUserId);
                    }
                    $stmt->execute();
                    $stmt->close();
                    
                    alert('🔻مشکل فنی در اتصال به سرور جهت تمدید با سهمیه. لطفا به مدیریت یا نماینده اطلاع دهید', true);
                    exit;
                }

                // آپدیت دیتابیس ربات
                $time = time();
                $baseExpire = ($orderRow['expire_date'] > $time) ? $orderRow['expire_date'] : $time;
                $new_expire_date = $baseExpire + (86400 * $days);

                $stmt = $connection->prepare("UPDATE `orders_list` SET `expire_date` = ?, `status` = 1 WHERE `uuid` = ? AND `server_id` = ?");
                $stmt->bind_param("isi", $new_expire_date, $uuid, $server_id);
                $stmt->execute();
                $stmt->close();

                // ثبت تاریخچه
                $stmt = $connection->prepare("INSERT INTO `increase_order` VALUES (NULL, ?, ?, ?, ?, 0, ?);");
                $stmt->bind_param("iiisi", $from_id, $server_id, $inbound_id, $remark, $time);
                $stmt->execute();
                $stmt->close();

                // اطلاع‌رسانی به کلاینت
                sendMessage("🎉 <b>سرویس شما با موفقیت از سهمیه نماینده تمدید شد!</b>\n\n🔹 نام سرویس: <code>{$remark}</code>\n🔹 ترافیک تمدید شده: <code>" . ($plan_vol == 0 ? "نامحدود" : $plan_vol . " گیگ") . "</code>\n🔹 زمان اضافه شده: <code>{$days} روز</code>", getMainKeys(), "HTML");

                // اطلاع‌رسانی به نماینده
                $msgToAgent = "🔄 <b>کاهش سهمیه بابت تمدید کاربر</b>\n\n👤 یکی از کاربران شما سرویس خود را تمدید کرد و سهمیه مربوطه از پنل شما کسر شد.\n🔹 نام اکانت: <code>{$remark}</code>\n🔹 حجم: <code>" . ($plan_vol == 0 ? "نامحدود" : $plan_vol . " گیگ") . "</code>\n🔹 مدت: <code>{$days} روز</code>";
                sendMessage($msgToAgent, null, "HTML", $agentUserId);
                
                setUser('', 'temp');
                exit();
            }
        }
    }

    $stmt = $connection->prepare("SELECT * FROM `server_categories` WHERE `id`=?");
    $stmt->bind_param("i", $respd['catid']);
    $stmt->execute();
    $catname = $stmt->get_result()->fetch_assoc()['title'];
    $stmt->close();

    $name = $catname . " " . $respd['title'];
    $desc = $respd['descr'];
    $sid = $respd['server_id'];
    $keyboard = array();
    $price = $respd['price'];
    $token = base64_encode("{$from_id}.{$id}");

    $hash_id = RandomString();
    $stmt = $connection->prepare("DELETE FROM `pays` WHERE `user_id` = ? AND `type` = 'RENEW_SCONFIG' AND `state` = 'pending'");
    $stmt->bind_param("i", $from_id);
    $stmt->execute();
    $stmt->close();

    setUser('', 'temp');
    $description = json_encode(["uuid" => $uuid, "remark" => $remark, 'marzban' => isset($configInfo['marzban'])], 488);
    $time = time();
    $stmt = $connection->prepare("INSERT INTO `pays` (`hash_id`, `description`, `user_id`, `type`, `plan_id`, `volume`, `day`, `price`, `request_date`, `state`)
                                VALUES (?, ?, ?, 'RENEW_SCONFIG', ?, ?, '0', ?, ?, 'pending')");
    $stmt->bind_param("ssiiiii", $hash_id, $description, $from_id, $id, $inbound_id, $price, $time);
    $stmt->execute();
    $rowId = $stmt->insert_id;
    $stmt->close();


    if ($botState['cartToCartState'] == "on")
        $keyboard[] = [['text' => $buttonValues['cart_to_cart'], 'callback_data' => "payWithCartToCart$hash_id"]];
    if ($botState['nowPaymentOther'] == "on")
        $keyboard[] = [['text' => $buttonValues['now_payment_gateway'], 'url' => $botUrl . "pay/?nowpayment&hash_id=" . $hash_id]];
    if ($botState['zarinpal'] == "on")
        $keyboard[] = [['text' => $buttonValues['zarinpal_gateway'], 'url' => $botUrl . "pay/?zarinpal&hash_id=" . $hash_id]];
    if ($botState['nextpay'] == "on")
        $keyboard[] = [['text' => $buttonValues['nextpay_gateway'], 'url' => $botUrl . "pay/?nextpay&hash_id=" . $hash_id]];
    if ($botState['weSwapState'] == "on")
        $keyboard[] = [['text' => $buttonValues['weswap_gateway'], 'callback_data' => "payWithWeSwap" . $hash_id]];
    if ($botState['walletState'] == "on")
        $keyboard[] = [['text' => $buttonValues['pay_with_wallet'], 'callback_data' => "payWithWallet$hash_id"]];
    if ($botState['tronWallet'] == "on")
        $keyboard[] = [['text' => $buttonValues['tron_gateway'], 'callback_data' => "payWithTronWallet" . $hash_id]];
    if ($botState['stars'] == "on")
        $keyboard[] = [['text' => $buttonValues['stars_gateway'], 'callback_data' => "payWithStars" . $hash_id]];

    $keyboard[] = [['text' => $buttonValues['back_to_main'], 'callback_data' => "mainMenu", 'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']];
    sendMessage(str_replace(['PLAN-NAME', 'PRICE', 'DESCRIPTION'], [$name, $price, $desc], $mainValues['buy_subscription_detail']), json_encode(['inline_keyboard' => $keyboard]), "HTML");
}
if (preg_match('/sConfigUpdate(\d+)/', (string)$data, $match)) {
    alert($mainValues['please_wait_message']);
    $server_id = $match[1];
    if (empty($userInfo['temp'])) {
        delMessage();
        exit();
    }

    $configInfo = json_decode($userInfo['temp'], true);
    $inboundId = $configInfo['id'] ?? 0;
    $uuid = $configInfo['uuid'];
    $remark = $configInfo['remark'];


    if (isset($configInfo['marzban'])) {
        $info = getMarzbanUserInfo($server_id, $remark);
        $vraylink = $info->links;
    } else {
        $response = getJson($server_id)->obj;
        if ($response == null) {
            delMessage();
            exit();
        }

        if ($inboundId == 0) {
            foreach ($response as $row) {
                $clients = json_decode($row->settings)->clients;
                if ($clients[0]->id == $uuid || $clients[0]->password == $uuid) {
                    $port = $row->port;
                    $protocol = $row->protocol;
                    $netType = json_decode($row->streamSettings)->network;
                    break;
                }
            }
        } else {
            foreach ($response as $row) {
                if ($row->id == $inboundId) {
                    $port = $row->port;
                    $protocol = $row->protocol;
                    $netType = json_decode($row->streamSettings)->network;
                    break;
                }
            }
        }

        if ($uuid == null) {
            delMessage();
            exit();
        }
        $vraylink = getConnectionLink($server_id, $uuid, $protocol, $remark, $port, $netType, $inboundId);
    }

    if ($vraylink == null) {
        delMessage();
        exit();
    }
    include 'phpqrcode/qrlib.php';
    define('IMAGE_WIDTH', 540);
    define('IMAGE_HEIGHT', 540);
    foreach ($vraylink as $vray_link) {
        $acc_text = $botState['configLinkState'] != "off" ? "<code>$vray_link</code>" : ".";

        $ecc = 'L';
        $pixel_Size = 11;
        $frame_Size = 0;

        $file = RandomString() . ".png";
        QRcode::png($vray_link, $file, $ecc, $pixel_Size, $frame_Size);
        addBorderImage($file);

        $backgroundImage = imagecreatefromjpeg(dirname(__DIR__) . "/settings/QRCode.jpg");
        $qrImage = imagecreatefrompng($file);

        $qrWidth = imagesx($qrImage); $qrHeight = imagesy($qrImage);
        $newWidth = round($qrWidth * 1.5); $newHeight = round($qrHeight * 1.5);
        $startX = round((imagesx($backgroundImage) - $newWidth) / 2);
        $startY = round(300 - ($newHeight - $qrHeight) / 2);
        imagecopyresampled($backgroundImage, $qrImage, $startX, $startY, 0, 0, $newWidth, $newHeight, $qrWidth, $qrHeight);
        imagepng($backgroundImage, $file);
        imagedestroy($backgroundImage);
        imagedestroy($qrImage);

        sendPhoto($file, $acc_text, null, "HTML");
        unlink($file);
    }
}

// -------------------------------------------------------------------------
// توابع کمکی برای نمایش وضعیت و دکمه‌های بازگشت (نسخه مجهز به محدودیت کاربر)
// -------------------------------------------------------------------------

// سیستم بازگشت به مرحله قبل در ساخت پلن (دکمه شیشه‌ای)
if (preg_match('/^backPlanStep_(.*)/', (string)$data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $targetStep = $match[1];
    preg_match('/^[a-zA-Z]+({.*})/', $userInfo['step'], $jsonMatch);
    $d = json_decode($jsonMatch[1], true) ?? [];
    $prompt_id = $d['prompt_id'];

    $kb = [];
    $msg = "";

    switch ($targetStep) {
        case 'addPlanTitle':
            unset($d['title']);
            $msg = "✍️ مرحله اول:\n▪️لطفاً یک نام یا عنوان برای این پلن انتخاب کنید (مثلا: پلن یک‌ماهه VIP):";
            $kb = [[['text' => "❌ انصراف", 'callback_data' => "mainMenu", 'style' => 'danger', 'icon_custom_emoji_id' => '5215680783863261658']]];
            break;

        case 'addPlanPrice':
            unset($d['price']);
            $msg = "💰 مرحله دوم:\n▪️لطفاً قیمت پلن را به <b>تومان</b> وارد کنید (فقط عدد):";
            $kb = [
                [['text' => "🔙 مرحله قبل", 'callback_data' => "backPlanStep_addPlanTitle", 'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']],
                [['text' => "❌ انصراف", 'callback_data' => "mainMenu", 'style' => 'danger', 'icon_custom_emoji_id' => '5215680783863261658']]
            ];
            break;

        case 'addPlanDescr':
            unset($d['descr']);
            $msg = "📃 <b>مرحله سوم: توضیحات پلن</b>\n\nلطفاً توضیحات پلن را وارد کنید (مثلا ویژگی‌های خاص یا اطلاعات اتصال):\n\n💡 (اگر نمی‌خواهید توضیحی بنویسید، عبارت <code>بدون توضیحات</code> یا یک علامت مثل <code>.</code> بفرستید)";
            $kb = [
                [['text' => "🔙 مرحله قبل", 'callback_data' => "backPlanStep_addPlanPrice", 'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']],
                [['text' => "❌ انصراف", 'callback_data' => "mainMenu", 'style' => 'danger', 'icon_custom_emoji_id' => '5215680783863261658']]
            ];
            break;

        case 'addPlanCategory':
            unset($d['catid'], $d['cat_name']);
            $msg = "📂 مرحله چهارم:\n▪️لطفاً یک دسته بندی برای این پلن انتخاب کنید:";
            $stmt = $connection->prepare("SELECT * FROM `server_categories` WHERE `parent` = 0 AND `active` = 1");
            $stmt->execute();
            $cats = $stmt->get_result();
            $stmt->close();
            while ($cat = $cats->fetch_assoc()) {
                $kb[] = [['text' => "📁 " . $cat['title'], 'callback_data' => "setPlanCat_" . $cat['id'] . "_" . $cat['title']]];
            }
            $kb[] = [['text' => "🔙 مرحله قبل", 'callback_data' => "backPlanStep_addPlanDescr", 'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']];
            $kb[] = [['text' => "❌ انصراف", 'callback_data' => "mainMenu", 'style' => 'danger', 'icon_custom_emoji_id' => '5215680783863261658']];
            break;

        case 'addPlanServerStep':
            unset($d['server_id'], $d['server_name']);
            $msg = "🖥 مرحله پنجم:\n▪️لطفاً سرور میزبان این پلن را انتخاب کنید:";
            $stmt = $connection->prepare("SELECT * FROM `server_info` WHERE `active` = 1");
            $stmt->execute();
            $servers = $stmt->get_result();
            $stmt->close();
            while ($srv = $servers->fetch_assoc()) {
                $kb[] = [['text' => "🖥 " . $srv['title'], 'callback_data' => "setPlanServer_" . $srv['id'] . "_" . $srv['title']]];
            }
            $kb[] = [['text' => "🔙 مرحله قبل", 'callback_data' => "backPlanStep_addPlanCategory", 'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']];
            $kb[] = [['text' => "❌ انصراف", 'callback_data' => "mainMenu", 'style' => 'danger', 'icon_custom_emoji_id' => '5215680783863261658']];
            break;

        case 'addPlanLimitIPStep':
            unset($d['limitip']);
            $msg = "🧲 <b>مرحله ششم: تعیین تعداد کاربر (محدودیت IP هم‌زمان)</b>\n\nلطفاً مشخص کنید چند کاربر به صورت هم‌زمان می‌توانند از این پلن استفاده کنند؟\n(برای حالت بدون محدودیت عدد 0 را ارسال کنید)";
            $kb = [
                [['text' => "🔙 مرحله قبل", 'callback_data' => "backPlanStep_addPlanServerStep", 'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']],
                [['text' => "❌ انصراف", 'callback_data' => "mainMenu", 'style' => 'danger', 'icon_custom_emoji_id' => '5215680783863261658']]
            ];
            break;
    }

    bot('editMessageText', ['chat_id' => $from_id, 'message_id' => $prompt_id, 'text' => wizwiz_getPlanSummaryTxt($d) . $msg, 'reply_markup' => json_encode(['inline_keyboard' => $kb]), 'parse_mode' => "HTML"]);
    setUser($targetStep . json_encode($d, JSON_UNESCAPED_UNICODE));
    exit();
}

// -------------------------------------------------------------------------
// شروع پروسه ساخت پلن
// -------------------------------------------------------------------------

// --- Start of Range 4762 to 4921 ---
if (($data == 'mySubscriptions' || $data == "agentConfigsList" || preg_match('/(changeAgentOrder|changeOrdersPage)(\d+)/', (string)$data, $match)) && ($botState['sellState'] == "on" || $from_id == $admin)) {
    $matchType = '';
    $page = 1;
    if (preg_match('/(changeAgentOrder|changeOrdersPage)(\d+)/', (string)$data, $m)) {
        $matchType = $m[1];
        $page = (int)$m[2];
    }
    $results_per_page = 10;
    $isAgentList = ($data == "agentConfigsList" || $matchType == "changeAgentOrder");

    if ($isAgentList) {
        $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `userid`=? AND `status` IN (0, 1)");
    } else {
        $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `userid`=? AND `status` IN (0, 1) AND `agent_bought` = 0");
    }
    $stmt->bind_param("i", $from_id);
    $stmt->execute();
    $number_of_result = $stmt->get_result()->num_rows;
    $stmt->close();

    $number_of_page = ceil($number_of_result / $results_per_page);
    $page_first_result = ($page - 1) * $results_per_page;

    if ($isAgentList) {
        $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `userid`=? AND `status` IN (0, 1) ORDER BY `id` DESC LIMIT ?, ?");
    } else {
        $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `userid`=? AND `status` IN (0, 1) AND `agent_bought` = 0 ORDER BY `id` DESC LIMIT ?, ?");
    }
    $stmt->bind_param("iii", $from_id, $page_first_result, $results_per_page);
    $stmt->execute();
    $orders = $stmt->get_result();
    $stmt->close();

    if ($orders->num_rows == 0) {
        alert($mainValues['you_dont_have_config']);
        exit;
    }

    $keyboard = [];
    while ($cat = $orders->fetch_assoc()) {
        $id = $cat['id'];
        $remark = $cat['remark'];
        $expire_date = $cat['expire_date'];

        $isActive = ($expire_date > time() || $expire_date == 0) ? true : false;
        $btnStyle = $isActive ? "success" : "danger";

        $keyboard[] = [
            'text' => "$remark", 
            'callback_data' => "orderDetails$id",
            'style' => $btnStyle
        ];
    }
    $keyboard = array_chunk($keyboard, 2);

    $prev = $page - 1;
    $next = $page + 1;
    $buttons = [];

    if ($prev > 0) {
        $callback = $isAgentList ? "changeAgentOrder$prev" : "changeOrdersPage$prev";
        $buttons[] = ['text' => "◀", 'callback_data' => $callback];
    }
    if ($next > 0 && $page != $number_of_page) {
        $callback = $isAgentList ? "changeAgentOrder$next" : "changeOrdersPage$next";
        $buttons[] = ['text' => "➡", 'callback_data' => $callback];
    }
    if (!empty($buttons)) $keyboard[] = $buttons;

    if ($isAgentList)
        $keyboard[] = [['text' => $buttonValues['search_agent_config'], 'callback_data' => "searchAgentConfig"]];
    else
        $keyboard[] = [['text' => $buttonValues['search_config'], 'callback_data' => "searchMyConfig"]];

    $keyboard[] = [getMiniAppBtn("مشاهده اشتراک‌ها در مینی‌اپ 📱", "subscriptions")];
    $keyboard[] = [['text' => $buttonValues['back_to_main'], 'callback_data' => "mainMenu", 'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']];
    $msg_text = $mainValues['select_one_to_show_detail'] . "\n\n🟢 <b>دکمه‌های سبز: فعال و متصل</b>\n🔴 <b>دکمه‌های قرمز: منقضی / پایان حجم</b>";

    if (isset($data)) {
        editText($message_id, $msg_text, json_encode(['inline_keyboard' => $keyboard]), "HTML");
    } else {
        sendAction('typing');
        sendMessage($msg_text, json_encode(['inline_keyboard' => $keyboard]), "HTML");
    }
    exit;
}

// -------------------------------------------------------------------
// بخش جستجو (Search)
// -------------------------------------------------------------------
if ($data == "searchAgentConfig" || $data == "searchMyConfig" || $data == "searchUsersConfig") {
    delMessage();
    sendMessage($mainValues['send_config_remark'], $cancelKey);
    setUser($data);
}

if (($userInfo['step'] == "searchAgentConfig" || $userInfo['step'] == "searchMyConfig") && $text != $buttonValues['cancel']) {
    sendMessage($mainValues['please_wait_message'], $removeKeyboard);

    $condition = "";
    if ($userInfo['step'] == "searchMyConfig")
        $condition = "AND `agent_bought` = 0";

    $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `userid` = ? AND `remark` LIKE CONCAT('%', ?, '%') $condition");
    $stmt->bind_param("is", $from_id, $text);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc(); // اصلاح خط 7514
    $stmt->close();

    if (!$result) { // اگر نتیجه‌ای یافت نشد
        sendMessage($mainValues['no_order_found']);
    } else {
        $orderId = $result['id'];
        $keys = getOrderDetailKeys($from_id, $orderId);

        if ($keys == null)
            sendMessage($mainValues['no_order_found']);
        else {
            sendMessage($keys['msg'], $keys['keyboard'], "HTML");
            setUser();
        }
    }
}
if (($userInfo['step'] == "searchUsersConfig" && $text != $buttonValues['cancel']) || preg_match('/^userOrderDetails(\d+)_(\d+)/', (string)$data, $match)) {
    if (isset($data)) {
        $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `id` = ?");
        $stmt->bind_param("i", $match[1]);
    } else {
        sendMessage($mainValues['please_wait_message'], $removeKeyboard);
        $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `remark` LIKE CONCAT('%', ?, '%')");
        $stmt->bind_param("s", $text);
    }
    $stmt->execute();
    $orderInfo = $stmt->get_result();
    $stmt->close();


    if ($orderInfo->num_rows == 0)
        sendMessage($mainValues['no_order_found']);
    else {
        $orderId = $orderInfo->fetch_assoc()['id'];
        $keys = getUserOrderDetailKeys($orderId, isset($data) ? $match[2] : 0);
        if ($keys == null)
            sendMessage($mainValues['no_order_found']);
        else {
            if (!isset($data))
                sendMessage($keys['msg'], $keys['keyboard'], "HTML");
            else
                editText($message_id, $keys['msg'], $keys['keyboard'], "HTML");
            setUser();
        }
    }
}
if (preg_match('/^orderDetails(\d+)(_|)(?<offset>\d+|)/', (string)$data, $match) && ($botState['sellState'] == "on" || ($from_id == $admin || $userInfo['isAdmin'] == true))) {
    $keys = getOrderDetailKeys($from_id, $match[1], !empty($match['offset']) ? $match['offset'] : 0);
    if ($keys == null) {
        alert($mainValues['no_order_found']);
        exit;
    } else
        editText($message_id, $keys['msg'], $keys['keyboard'], "HTML");
}
if ($data == "cantEditGrpc") {
    alert("نوعیت این کانفیگ رو تغییر داده نمیتونید!");
    exit();
}

// --- Start of Range 4970 to 5259 ---
if (preg_match('/changeNetworkType(\d+)_(\d+)/', (string)$data, $match)) {
    $fid = $match[1];
    $oid = $match[2];

    $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `id`=? AND `active`=1");
    $stmt->bind_param("i", $fid);
    $stmt->execute();
    $respd = $stmt->get_result();
    $stmt->close();


    if ($respd) {
        $respd = $respd->fetch_assoc();
        $stmt = $connection->prepare("SELECT * FROM `server_categories` WHERE `id`=?");
        $stmt->bind_param("i", $respd['catid']);
        $stmt->execute();
        $cadquery = $stmt->get_result();
        $stmt->close();


        if ($cadquery) {
            $catname = $cadquery->fetch_assoc()['title'];
            $name = $catname . " " . $respd['title'];
        } else
            $name = "$oid";
    } else
        $name = "$oid";

    $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `id`=?");
    $stmt->bind_param("i", $oid);
    $stmt->execute();
    $order = $stmt->get_result()->fetch_assoc();
    $stmt->close();


    $date = jdate("Y-m-d H:i", $order['date']);
    $expire_date = jdate("Y-m-d H:i", $order['expire_date']);
    $remark = $order['remark'];
    $uuid = $order['uuid'] ?? "0";
    $acc_link = $order['link'];
    $protocol = $order['protocol'];
    $server_id = $order['server_id'];
    $price = $order['amount'];

    $response = getJson($server_id)->obj;
    foreach ($response as $row) {
        $clients = json_decode($row->settings)->clients;
        if ($clients[0]->id == $uuid || $clients[0]->password == $uuid) {
            $total = $row->total;
            $up = $row->up;
            $down = $row->down;
            $port = $row->port;
            $netType = json_decode($row->streamSettings)->network;
            $security = json_decode($row->streamSettings)->security;
            $netType = ($netType == 'tcp') ? 'ws' : 'tcp';
            break;
        }
    }

    if ($protocol == 'trojan')
        $netType = 'tcp';

    $update_response = editInbound($server_id, $uuid, $uuid, $protocol, $netType);
    $vraylink = getConnectionLink($server_id, $uuid, $protocol, $remark, $port, $netType);

    $vray_link = json_encode($vraylink);
    $stmt = $connection->prepare("UPDATE `orders_list` SET `protocol`=?,`link`=? WHERE `id`=?");
    $stmt->bind_param("ssi", $protocol, $vray_link, $oid);
    $stmt->execute();
    $stmt->close();

    $keys = getOrderDetailKeys($from_id, $oid);
    editText($message_id, $keys['msg'], $keys['keyboard'], "HTML");
}
if ($data == "changeProtocolIsDisable") {
    alert("تغییر پروتکل غیر فعال است");
}
if (preg_match('/updateConfigConnectionLink(\d+)/', (string)$data, $match)) {
    alert($mainValues['please_wait_message']);
    $oid = $match[1];

    $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `id`=?");
    $stmt->bind_param("i", $oid);
    $stmt->execute();
    $order = $stmt->get_result()->fetch_assoc();
    $stmt->close();


    $remark = $order['remark'];
    $uuid = $order['uuid'] ?? "0";
    $inboundId = $order['inbound_id'];
    $server_id = $order['server_id'];
    $file_id = $order['fileid'];

    $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `id`=?");
    $stmt->bind_param("i", $file_id);
    $stmt->execute();
    $file_detail = $stmt->get_result()->fetch_assoc();

    $rahgozar = $order['rahgozar'];
    $customPath = $file_detail['custom_path'];
    $customPort = $file_detail['custom_port'];
    $customSni = $file_detail['custom_sni'];

    $stmt = $connection->prepare("SELECT * FROM `server_config` WHERE `id`=?");
    $stmt->bind_param("i", $server_id);
    $stmt->execute();
    $server_config = $stmt->get_result()->fetch_assoc();
    $serverType = $server_config['type'];
    $netType = $file_detail['type'];
    $protocol = $file_detail['protocol'];
    $security = $server_config['security'];

    if ($serverType == "marzban") {
        $info = getMarzbanUser($server_id, $remark);
        $vraylink = $info->links;
    } else {
        $response = getJson($server_id)->obj;
        if ($inboundId == 0) {
            foreach ($response as $row) {
                $clients = json_decode($row->settings)->clients;
                if ($clients[0]->id == $uuid || $clients[0]->password == $uuid) {
                    $inboundRemark = $row->remark;
                    $iId = $row->id;
                    $port = $row->port;
                    $protocol = $row->protocol;
                    $netType = json_decode($row->streamSettings)->network;
                    break;
                }
            }
        } else {
            foreach ($response as $row) {
                if ($row->id == $inboundId) {
                    $iId = $row->id;
                    $inboundRemark = $row->remark;
                    $port = $row->port;
                    $protocol = $row->protocol;
                    $netType = json_decode($row->streamSettings)->network;
                    break;
                }
            }
        }

        if ($botState['updateConnectionState'] == "robot") {
            updateConfig($server_id, $iId, $protocol, $netType, $security, $rahgozar);
        }
        $vraylink = getConnectionLink($server_id, $uuid, $protocol, $remark, $port, $netType, $inboundId, $rahgozar, $customPath, $customPort, $customSni);
    }
    $vray_link = json_encode($vraylink);
    $stmt = $connection->prepare("UPDATE `orders_list` SET `link`=? WHERE `id`=?");
    $stmt->bind_param("si", $vray_link, $oid);
    $stmt->execute();
    $stmt->close();
    $keys = getOrderDetailKeys($from_id, $oid);
    editText($message_id, $keys['msg'], $keys['keyboard'], "HTML");
}
if (preg_match('/changAccountConnectionLink(\d+)/', (string)$data, $match)) {
    alert($mainValues['please_wait_message']);
    $oid = $match[1];

    $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `id`=?");
    $stmt->bind_param("i", $oid);
    $stmt->execute();
    $order = $stmt->get_result()->fetch_assoc();
    $stmt->close();


    $date = jdate("Y-m-d H:i", $order['date']);
    $expire_date = jdate("Y-m-d H:i", $order['expire_date']);
    $remark = $order['remark'];
    $uuid = $order['uuid'] ?? "0";
    $inboundId = $order['inbound_id'];
    $acc_link = $order['link'];
    $server_id = $order['server_id'];
    $rahgozar = $order['rahgozar'];

    $file_id = $order['fileid'];

    $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `id`=?");
    $stmt->bind_param("i", $file_id);
    $stmt->execute();
    $file_detail = $stmt->get_result()->fetch_assoc();
    $customPath = $file_detail['custom_path'];
    $customPort = $file_detail['custom_port'];
    $customSni = $file_detail['custom_sni'];


    $stmt = $connection->prepare("SELECT * FROM server_config WHERE id=?");
    $stmt->bind_param("i", $server_id);
    $stmt->execute();
    $server_info = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    $serverType = $server_info['type'];

    if ($serverType == "marzban") {
        $res = renewMarzbanUUID($server_id, $remark);
        $vraylink = $res->links;
        $newUuid = $newToken = str_replace("/sub/", "", $res->subscription_url);
    } else {
        $response = getJson($server_id)->obj;
        if ($inboundId == 0) {
            foreach ($response as $row) {
                $clients = json_decode($row->settings)->clients;
                if ($clients[0]->id == $uuid || $clients[0]->password == $uuid) {
                    $port = $row->port;
                    $protocol = $row->protocol;
                    $netType = json_decode($row->streamSettings)->network;
                    break;
                }
            }

            $update_response = renewInboundUuid($server_id, $uuid);
        } else {
            foreach ($response as $row) {
                if ($row->id == $inboundId) {
                    $port = $row->port;
                    $protocol = $row->protocol;
                    $netType = json_decode($row->streamSettings)->network;
                    break;
                }
            }
            $update_response = renewClientUuid($server_id, $inboundId, $uuid);
        }
        $newUuid = $update_response->newUuid;
        $vraylink = getConnectionLink($server_id, $newUuid, $protocol, $remark, $port, $netType, $inboundId, $rahgozar, $customPath, $customPort, $customSni);
        $newToken = RandomString(30);
    }


    $vray_link = json_encode($vraylink);
    $stmt = $connection->prepare("UPDATE `orders_list` SET `link`=?, `uuid` = ?, `token` = ? WHERE `id`=?");
    $stmt->bind_param("sssi", $vray_link, $newUuid, $newToken, $oid);
    $stmt->execute();
    $stmt->close();
    $keys = getOrderDetailKeys($from_id, $oid);
    editText($message_id, $keys['msg'], $keys['keyboard'], "HTML");
}
if (preg_match('/changeUserConfigState(\d+)/', (string)$data, $match)) {
    alert($mainValues['please_wait_message']);
    $oid = $match[1];

    $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `id`=?");
    $stmt->bind_param("i", $oid);
    $stmt->execute();
    $order = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    $userId = $order['userid'];
    $uuid = $order['uuid'] ?? "0";
    $inboundId = $order['inbound_id'];
    $server_id = $order['server_id'];
    $remark = $order['remark'];

    $stmt = $connection->prepare("SELECT * FROM server_config WHERE id=?");
    $stmt->bind_param("i", $server_id);
    $stmt->execute();
    $server_info = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $serverType = $server_info['type'];


    if ($inboundId == 0) {
        if ($serverType == "marzban")
            $update_response = changeMarzbanState($server_id, $remark);
        else
            $update_response = changeInboundState($server_id, $uuid);
    } else {
        $update_response = changeClientState($server_id, $inboundId, $uuid);
    }

    if ($update_response->success) {
        alert($mainValues['please_wait_message']);

        $keys = getUserOrderDetailKeys($oid);
        editText($message_id, $keys['msg'], $keys['keyboard'], "HTML");
    } else
        sendMessage("عملیه مورد نظر با مشکل روبرو شد\n" . $update_response->msg);
}


// --- Start of Range 5260 to 5344 ---
if (preg_match('/changeAccProtocol(\d+)_(\d+)_(.*)/', (string)$data, $match)) {
    $fid = $match[1];
    $oid = $match[2];
    $protocol = $match[3];

    $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `id`=? AND `active`=1");
    $stmt->bind_param("i", $fid);
    $stmt->execute();
    $respd = $stmt->get_result();
    $stmt->close();


    if ($respd) {
        $respd = $respd->fetch_assoc();
        $stmt = $connection->prepare("SELECT * FROM `server_categories` WHERE `id`=?");
        $stmt->bind_param("i", $respd['catid']);
        $stmt->execute();
        $cadquery = $stmt->get_result();
        $stmt->close();


        if ($cadquery) {
            $catname = $cadquery->fetch_assoc()['title'];
            $name = $catname . " " . $respd['title'];
        } else
            $name = "$id";
    } else
        $name = "$id";

    $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `id`=?");
    $stmt->bind_param("i", $oid);
    $stmt->execute();
    $order = $stmt->get_result()->fetch_assoc();
    $stmt->close();


    $date = jdate("Y-m-d H:i", $order['date']);
    $expire_date = jdate("Y-m-d H:i", $order['expire_date']);
    $remark = $order['remark'];
    $uuid = $order['uuid'] ?? "0";
    $acc_link = $order['link'];
    $server_id = $order['server_id'];
    $price = $order['amount'];
    $rahgozar = $order['rahgozar'];
    $file_id = $order['fileid'];

    $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `id`=?");
    $stmt->bind_param("i", $file_id);
    $stmt->execute();
    $file_detail = $stmt->get_result()->fetch_assoc();
    $customPath = $file_detail['custom_path'];
    $customPort = $file_detail['custom_port'];
    $customSni = $file_detail['custom_sni'];

    $response = getJson($server_id)->obj;
    foreach ($response as $row) {
        $clients = json_decode($row->settings)->clients;
        if ($clients[0]->id == $uuid || $clients[0]->password == $uuid) {
            $total = $row->total;
            $up = $row->up;
            $down = $row->down;
            $port = $row->port;
            $netType = json_decode($row->streamSettings)->network;
            $security = json_decode($row->streamSettings)->security;
            break;
        }
    }
    if ($protocol == 'trojan')
        $netType = 'tcp';
    $uniqid = generateRandomString(42, $protocol);
    $leftgb = round(($total - $up - $down) / 1073741824, 2) . " GB";
    $update_response = editInbound($server_id, $uniqid, $uuid, $protocol, $netType, $security, $rahgozar);
    $vraylink = getConnectionLink($server_id, $uniqid, $protocol, $remark, $port, $netType, 0, $rahgozar, $customPath, $customPort, $customSni);

    $vray_link = json_encode($vraylink);
    $stmt = $connection->prepare("UPDATE `orders_list` SET `protocol`=?,`link`=?, `uuid` = ? WHERE `id`=?");
    $stmt->bind_param("sssi", $protocol, $vray_link, $uniqid, $oid);
    $stmt->execute();
    $stmt->close();
    $keys = getOrderDetailKeys($from_id, $oid);
    editText($message_id, $keys['msg'], $keys['keyboard'], "HTML");
}

// --- Start of Range 5505 to 5534 ---
if (preg_match('/switchLocation(.+)_(.+)_(.+)_(.+)/', (string)$data, $match)) {
    $order_id = $match[1];
    $server_id = $match[2];
    $leftgp = $match[3];
    $expire = $match[4];
    if ($expire < time() or $leftgp <= 0) {
        alert("سرویس شما غیرفعال است.لطفا ابتدا آن را تمدید کنید", true);
        exit;
    }
    $stmt = $connection->prepare("SELECT * FROM `server_info` WHERE `active` = 1 and `state` = 1 and ucount > 0 AND `id` != ?");
    $stmt->bind_param("i", $server_id);
    $stmt->execute();
    $respd = $stmt->get_result();
    $stmt->close();
    if ($respd->num_rows == 0) {
        alert('در حال حاضر هیچ سرور فعالی برای تغییر لوکیشن وجود ندارد', true);
        exit;
    }
    $keyboard = [];
    while ($cat = $respd->fetch_assoc()) {
        $sid = $cat['id'];
        $name = $cat['title'];
        $keyboard[] = ['text' => "$name", 'callback_data' => "switchServer{$sid}_{$order_id}"];
    }
    $keyboard = array_chunk($keyboard, 2);
    $keyboard[] = [getBtn('back_button', 'mainMenu')];
    editText($message_id, ' 📍 لطفا برای تغییر لوکیشن سرویس فعلی, یکی از سرورها را انتخاب کنید👇', json_encode([
        'inline_keyboard' => $keyboard
    ]));
}

// --- Start of Range 5592 to 5827 ---
if (preg_match('/switchLocation(.+)_(.+)_(.+)_(.+)/', (string)$data, $match)) {
    $order_id = $match[1];
    $server_id = $match[2];
    $leftgp = $match[3];
    $expire = $match[4];
    if ($expire < time() or $leftgp <= 0) {
        alert("سرویس شما غیرفعال است.لطفا ابتدا آن را تمدید کنید", true);
        exit;
    }
    $stmt = $connection->prepare("SELECT * FROM `server_info` WHERE `active` = 1 and `state` = 1 and ucount > 0 AND `id` != ?");
    $stmt->bind_param("i", $server_id);
    $stmt->execute();
    $respd = $stmt->get_result();
    $stmt->close();
    if ($respd->num_rows == 0) {
        alert('در حال حاضر هیچ سرور فعالی برای تغییر لوکیشن وجود ندارد', true);
        exit;
    }
    $keyboard = [];
    while ($cat = $respd->fetch_assoc()) {
        $sid = $cat['id'];
        $name = $cat['title'];
        $keyboard[] = ['text' => "$name", 'callback_data' => "switchServer{$sid}_{$order_id}"];
    }
    $keyboard = array_chunk($keyboard, 2);
    $keyboard[] = [getBtn('back_button', 'mainMenu')];
    editText($message_id, ' 📍 لطفا برای تغییر لوکیشن سرویس فعلی, یکی از سرورها را انتخاب کنید👇', json_encode([
        'inline_keyboard' => $keyboard
    ]));
}
if (preg_match('/switchServer(.+)_(.+)/', (string)$data, $match)) {
    $sid = $match[1];
    $oid = $match[2];
    $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `id` = ?");
    $stmt->bind_param("i", $oid);
    $stmt->execute();
    $order = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $inbound_id = $order['inbound_id'];
    $server_id = $order['server_id'];
    $remark = $order['remark'];
    $uuid = $order['uuid'] ?? "0";
    $fid = $order['fileid'];
    $protocol = $order['protocol'];
    $link = json_decode($order['link'])[0];

    $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `id`=?");
    $stmt->bind_param("i", $fid);
    $stmt->execute();
    $file_detail = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    $flow = $file_detail['flow'] == "None" ? "" : $file_detail['flow'];

    $stmt = $connection->prepare("SELECT * FROM server_config WHERE id=?");
    $stmt->bind_param("i", $server_id);
    $stmt->execute();
    $server_info = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $reality = $server_info['reality'];
    $serverType = $server_info['type'];
    $panelUrl = $server_info['panel_url'];

    $stmt = $connection->prepare("SELECT * FROM `server_info` WHERE `id`=?");
    $stmt->bind_param("i", $sid);
    $stmt->execute();
    $srv_remark = $stmt->get_result()->fetch_assoc()['remark'];


    if ($botState['remark'] == "digits") {
        $rnd = rand(10000, 99999);
        $newRemark = "{$srv_remark}-{$rnd}";
    } else {
        $rnd = rand(1111, 99999);
        $newRemark = "{$srv_remark}-{$from_id}-{$rnd}";
    }

    if (preg_match('/vmess/', $link)) {
        $link_info = json_decode(base64_decode(str_replace('vmess://', '', $link)));
        $uniqid = $link_info->id;
        $port = $link_info->port;
        $netType = $link_info->net;
    } else {
        $link_info = parse_url($link);
        $panel_ip = $link_info['host'];
        $uniqid = $link_info['user'];
        $protocol = $link_info['scheme'];
        $port = $link_info['port'];
        $netType = explode('type=', $link_info['query'])[1];
        $netType = explode('&', $netType)[0];
    }

    if ($inbound_id > 0) {
        $remove_response = deleteClient($server_id, $inbound_id, $uuid);
        if (is_null($remove_response)) {
            alert('🔻اتصال به سرور برقرار نیست. لطفا به مدیریت اطلاع بدید', true);
            exit;
        }
        if ($remove_response) {
            $total = $remove_response['total'];
            $up = $remove_response['up'];
            $down = $remove_response['down'];
            $id_label = $protocol == 'trojan' ? 'password' : 'id';
            if ($serverType == "sanaei" || $serverType == "alireza") {
                if ($reality == "true") {
                    $newArr = [
                        "$id_label" => $uniqid,
                        "email" => $newRemark,
                        "enable" => true,
                        "flow" => $flow,
                        "limitIp" => $remove_response['limitIp'],
                        "totalGB" => $total - $up - $down,
                        "expiryTime" => $remove_response['expiryTime'],
                        "subId" => RandomString(16)
                    ];
                } else {
                    $newArr = [
                        "$id_label" => $uniqid,
                        "email" => $newRemark,
                        "enable" => true,
                        "limitIp" => $remove_response['limitIp'],
                        "totalGB" => $total - $up - $down,
                        "expiryTime" => $remove_response['expiryTime'],
                        "subId" => RandomString(16)
                    ];
                }
            } else {
                $newArr = [
                    "$id_label" => $uniqid,
                    "flow" => $remove_response['flow'],
                    "email" => $newRremark,
                    "limitIp" => $remove_response['limitIp'],
                    "totalGB" => $total - $up - $down,
                    "expiryTime" => $remove_response['expiryTime']
                ];
            }

            $response = addInboundAccount($sid, '', $inbound_id, 1, $newRemark, 0, 1, $newArr);
            if (is_null($response)) {
                alert('🔻اتصال به سرور برقرار نیست. لطفا به مدیریت اطلاع بدید', true);
                exit;
            }
            if ($response == "inbound not Found") {
                alert("🔻سطر (inbound) با آیدی $inbound_id در این سرور یافت نشد. لطفا به مدیریت اطلاع بدید", true);
                exit;
            }
            if (!$response->success) {
                alert('🔻خطا در ساخت کانفیگ. لطفا به مدیریت اطلاع بدید', true);
                exit;
            }
            $vray_link = getConnectionLink($sid, $uniqid, $protocol, $newRemark, $port, $netType, $inbound_id);
            deleteClient($server_id, $inbound_id, $uuid, 1);
        }
    } else {
        $response = deleteInbound($server_id, $uuid);
        if (is_null($response)) {
            alert('🔻اتصال به سرور برقرار نیست. لطفا به مدیریت اطلاع بدید', true);
            exit;
        }
        if ($response) {
            if ($serverType == "marzban") {
                $response = addMarzbanUser($server_id, $newRemark, $volume, $days, $fid);
                if (!$response->success) {
                    if ($response->msg == "User already exists") {
                        $newRemark .= rand(1111, 99999);
                        $response = addMarzbanUser($server_id, $newRemark, $volume, $days, $fid);
                    }
                }
                $uniqid = $token = str_replace("/sub/", "", $response->sub_link);
                $subLink = $botState['subLinkState'] == "on" ? $panelUrl . $response->sub_link : "";
                $vraylink = $response->vray_links;

                $stmt = $connection->prepare("UPDATE `orders_list` SET `token` = ?, `uuid` =? WHERE `id` = ?");
                $stmt->bind_param("ssi", $token, $uniqid, $oid);
                $stmt->execute();
                $stmt->close();
            } else {
                $res = addUser($sid, $response['uniqid'], $response['protocol'], $response['port'], $response['expiryTime'], $newRemark, $response['volume'] / 1073741824, $response['netType'], $response['security']);
                $vray_link = getConnectionLink($sid, $response['uniqid'], $response['protocol'], $newRemark, $response['port'], $response['netType'], $inbound_id);
            }
            deleteInbound($server_id, $uuid, 1);
        }
    }
    $stmt = $connection->prepare("UPDATE `server_info` SET `ucount` = `ucount` + 1 WHERE `id` = ?");
    $stmt->bind_param("i", $server_id);
    $stmt->execute();
    $stmt->close();

    $stmt = $connection->prepare("UPDATE `server_info` SET `ucount` = `ucount` - 1 WHERE `id` = ?");
    $stmt->bind_param("i", $sid);
    $stmt->execute();
    $stmt->close();

    $vray_link = json_encode($vray_link);
    $stmt = $connection->prepare("UPDATE `orders_list` SET `server_id` = ?, `link`=?, `remark` = ? WHERE `id` = ?");
    $stmt->bind_param("issi", $sid, $vray_link, $newRemark, $oid);
    $stmt->execute();
    $stmt->close();

    $stmt = $connection->prepare("SELECT * FROM `server_info` WHERE `id` = ?");
    $stmt->bind_param("i", $sid);
    $stmt->execute();
    $server_title = $stmt->get_result()->fetch_assoc()['title'];
    $stmt->close();

    $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `userid` = ? AND `status` = 1 ORDER BY `id` DESC");
    $stmt->bind_param("i", $from_id);
    $stmt->execute();
    $orders = $stmt->get_result();
    $stmt->close();

    $keyboard = [];
    while ($cat = $orders->fetch_assoc()) {
        $id = $cat['id'];
        $cremark = $cat['remark'];
        $keyboard[] = ['text' => "$cremark", 'callback_data' => "orderDetails$id"];
    }
    $keyboard = array_chunk($keyboard, 2);
    $keyboard[] = [['text' => $buttonValues['back_to_main'], 'callback_data' => "mainMenu", 'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']];
    $msg = " 📍لوکیشن سرویس $remark به $server_title با ریمارک $newRemark تغییر یافت.\n لطفا برای مشاهده مشخصات, روی آن بزنید👇";

    editText($message_id, $msg, json_encode([
        'inline_keyboard' => $keyboard
    ]));
    exit();
}
// -------------------------------------------------------------------------
// بخش تاییدیه حذف کانفیگ توسط کاربر
// -------------------------------------------------------------------------

// -------------------------------------------------------------------------
// بخش ارسال فایل اختصاصی .npvt برای نپسترنت به درخواست کاربر
// -------------------------------------------------------------------------
if (preg_match('/^getNpvtFile(\d+)/', (string)$data, $match)) {
    $oid = $match[1];
    $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `id` = ?");
    $stmt->bind_param("i", $oid);
    $stmt->execute();
    $order = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if ($order) {
        $remark = $order['remark'];
        $linksJson = $order['link'] ?? '';
        $linksArray = json_decode($linksJson, true);
        if (!is_array($linksArray) || empty($linksArray)) {
            $linksArray = !empty($linksJson) ? [$linksJson] : [];
        }

        $botUrl = 'https://wizwiz.villux.ir:8443/Netfreedom/';
        $subLink = !empty($order['token']) ? $botUrl . "sub/" . $order['token'] : null;

        sendNpvtDocument($linksArray, $remark, $from_id, $subLink);
        alert("📄 فایل نپستر با موفقیت برای شما ارسال گردید.");
    } else {
        alert("❌ اطلاعات کانفیگ یافت نشد.", true);
    }
    exit();
}

// --- Start of Range 5828 to 6058 ---
elseif (preg_match('/^deleteMyConfig(\d+)/', (string)$data, $match)) {
    $oid = $match[1];
    $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `id` = ?");
    $stmt->bind_param("i", $oid);
    $stmt->execute();
    $order = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $remark = $order['remark'];

    // دکمه خیر به جای منوی اصلی، مستقیما به مشخصات همان کانفیگ برمی‌گردد
    editText($message_id, "⚠️ آیا از حذف کانفیگ <code>$remark</code> مطمئن هستید؟\n(این عمل غیرقابل بازگشت است)", json_encode([
        'inline_keyboard' => [
            [
                ['text' => "بله، حذف شود 🗑", 'callback_data' => "yesDeleteConfig" . $match[1], 'style' => 'danger', 'icon_custom_emoji_id' => '5215680783863261658'],
                ['text' => "خیر، منصرف شدم ❌", 'callback_data' => "orderDetails" . $match[1], 'style' => 'success', 'icon_custom_emoji_id' => '5208880351690112495']
            ]
        ]
    ]), "HTML");
}

// -------------------------------------------------------------------------
// بخش پردازش حذف کانفیگ توسط کاربر
// -------------------------------------------------------------------------
elseif (preg_match('/^yesDeleteConfig(\d+)/', (string)$data, $match)) {
    $oid = $match[1];
    $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `id` = ?");
    $stmt->bind_param("i", $oid);
    $stmt->execute();
    $order = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if (!$order) {
        editText($message_id, "❌ کانفیگ یافت نشد یا قبلاً حذف شده است.", json_encode(['inline_keyboard' => [[['text' => '🔙 بازگشت', 'callback_data' => 'mySubscriptions']]]]));
        exit();
    }

    $inbound_id = $order['inbound_id'];
    $server_id = $order['server_id'];
    $remark = $order['remark'];
    $uuid = $order['uuid'] ?? "0";
    $fileid = $order['fileid'];

    $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `id` = ?");
    $stmt->bind_param("i", $fileid);
    $stmt->execute();
    $planDetail = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $volume = isset($planDetail['volume']) ? $planDetail['volume'] : "سفارشی";
    $days = isset($planDetail['days']) ? $planDetail['days'] : (($order['expire_date'] == 0) ? "نامحدود" : round((intval($order['expire_date']) - intval($order['date'])) / 86400));

    $stmt = $connection->prepare("SELECT * FROM `server_config` WHERE `id` = ?");
    $stmt->bind_param('i', $server_id);
    $stmt->execute();
    $serverConfig = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $serverType = $serverConfig['type'];

    if ($serverType != "marzban") {
        $res = deleteClient($server_id, $inbound_id, $uuid, 1);
        if (!$res) {
            $res = deleteInbound($server_id, $uuid, 1);
        }

        $leftMb = isset($res['total']) ? sumerize($res['total'] - $res['up'] - $res['down']) : "0";
        $expiryDay = (isset($res['expiryTime']) && $res['expiryTime'] != 0) ?
            floor((substr($res['expiryTime'], 0, -3) - time()) / (60 * 60 * 24)) : "نامحدود";
    } else {
        $configInfo = getMarzbanUser($server_id, $remark);
        deleteMarzban($server_id, $remark);
        $leftMb = isset($configInfo->data_limit) ? sumerize($configInfo->data_limit - $configInfo->used_traffic) : "0";
        $expiryDay = (isset($configInfo->expire) && $configInfo->expire != 0) ?
            floor(($configInfo->expire - time()) / 86400) : "نامحدود";
    }

    if (is_numeric($expiryDay) && $expiryDay < 0) $expiryDay = 0;

    $stmt = $connection->prepare("UPDATE `server_info` SET `ucount` = `ucount` + 1 WHERE `id` = ?");
    $stmt->bind_param("i", $server_id);
    $stmt->execute();
    $stmt->close();

    $stmt = $connection->prepare("DELETE FROM `orders_list` WHERE `id` = ?");
    $stmt->bind_param("i", $oid);
    $stmt->execute();
    $stmt->close();

    $msg = "🔋|💰 <b>حذف کانفیگ انجام شد</b>\n\n" .
        "▫️آیدی کاربر: <code>{$from_id}</code>\n" .
        "👨‍💼اسم کاربر: {$first_name}\n" .
        "⚡️ نام کاربری: @{$username}\n" .
        "🎈 نام سرویس: <code>{$remark}</code>\n" .
        "🔋حجم سرویس: {$volume} گیگ\n" .
        "⏰ مدت زمان سرویس: {$days} روز\n" .
        "❌ حجم باقی مانده: {$leftMb}\n" .
        "📆 روز باقیمانده: {$expiryDay}";

    $backCallback = ($order['agent_bought'] == 1) ? "agentConfigsList" : "mySubscriptions";
    editText($message_id, $msg, json_encode([
        'inline_keyboard' => [
            [getBtn('back_button', $backCallback)]
        ]
    ]), "HTML");

    exit();
}

// -------------------------------------------------------------------------
// بخش تاییدیه حذف کانفیگ کاربر توسط ادمین
// -------------------------------------------------------------------------
elseif (preg_match('/^delUserConfig(\d+)/', (string)$data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $oid = $match[1];
    $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `id` = ?");
    $stmt->bind_param("i", $oid);
    $stmt->execute();
    $order = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $remark = $order['remark'];

    // دکمه خیر به جای منوی اصلی، مستقیما به پنل مشخصات کاربر در مدیریت برمی‌گردد
    editText($message_id, "⚠️ آیا از حذف کانفیگ <code>$remark</code> کاربر مطمئن هستید؟", json_encode([
        'inline_keyboard' => [
            [
                ['text' => "بله، حذف شود 🗑", 'callback_data' => "yesDeleteUserConfig" . $match[1], 'style' => 'danger', 'icon_custom_emoji_id' => '5215680783863261658'],
                ['text' => "خیر، منصرف شدم ❌", 'callback_data' => "userOrderDetails" . $match[1], 'style' => 'success', 'icon_custom_emoji_id' => '5208880351690112495']
            ]
        ]
    ]), "HTML");
}

// -------------------------------------------------------------------------
// بخش پردازش حذف کانفیگ کاربر توسط ادمین
// -------------------------------------------------------------------------
elseif (preg_match('/^yesDeleteUserConfig(\d+)/', (string)$data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $oid = $match[1];
    $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `id` = ?");
    $stmt->bind_param("i", $oid);
    $stmt->execute();
    $order = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if (!$order) {
        editText($message_id, "❌ کانفیگ یافت نشد.", json_encode(['inline_keyboard' => [[['text' => '🔙 بازگشت', 'callback_data' => 'managePanel']]]]));
        exit();
    }

    $userId = $order['userid'];
    $inbound_id = $order['inbound_id'];
    $server_id = $order['server_id'];
    $remark = $order['remark'];
    $uuid = $order['uuid'] ?? "0";
    $fileid = $order['fileid'];

    // دریافت اطلاعات خریدار جهت درج در رسید ادمین
    $stmt = $connection->prepare("SELECT * FROM `users` WHERE `userid` = ?");
    $stmt->bind_param("i", $userId);
    $stmt->execute();
    $uInfo = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $uFirstName = $uInfo['name'] ?? "کاربر";
    $uUsername = $uInfo['username'] ?? "ندارد";

    // دریافت اطلاعات حجم و روز اولیه
    $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `id` = ?");
    $stmt->bind_param("i", $fileid);
    $stmt->execute();
    $planDetail = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $volume = isset($planDetail['volume']) ? $planDetail['volume'] : "سفارشی";
    $days = isset($planDetail['days']) ? $planDetail['days'] : (($order['expire_date'] == 0) ? "نامحدود" : round((intval($order['expire_date']) - intval($order['date'])) / 86400));

    $stmt = $connection->prepare("SELECT * FROM `server_config` WHERE `id` = ?");
    $stmt->bind_param('i', $server_id);
    $stmt->execute();
    $serverConfig = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $serverType = $serverConfig['type'];

    if ($serverType != "marzban") {
        $res = deleteClient($server_id, $inbound_id, $uuid, 1);
        if (!$res) {
            $res = deleteInbound($server_id, $uuid, 1);
        }

        $leftMb = isset($res['total']) ? sumerize($res['total'] - $res['up'] - $res['down']) : "0";
        $expiryDay = (isset($res['expiryTime']) && $res['expiryTime'] != 0) ?
            floor((substr($res['expiryTime'], 0, -3) - time()) / (60 * 60 * 24)) : "نامحدود";
    } else {
        $configInfo = getMarzbanUser($server_id, $remark);
        deleteMarzban($server_id, $remark);
        $leftMb = isset($configInfo->data_limit) ? sumerize($configInfo->data_limit - $configInfo->used_traffic) : "0";
        $expiryDay = (isset($configInfo->expire) && $configInfo->expire != 0) ?
            floor(($configInfo->expire - time()) / 86400) : "نامحدود";
    }

    if (is_numeric($expiryDay) && $expiryDay < 0) $expiryDay = 0;

    $stmt = $connection->prepare("UPDATE `server_info` SET `ucount` = `ucount` + 1 WHERE `id` = ?");
    $stmt->bind_param("i", $server_id);
    $stmt->execute();
    $stmt->close();

    $stmt = $connection->prepare("DELETE FROM `orders_list` WHERE `id` = ?");
    $stmt->bind_param("i", $oid);
    $stmt->execute();
    $stmt->close();

    $msgAdmin = "🔋|💰 <b>حذف کانفیگ انجام شد</b>\n\n" .
        "▫️آیدی کاربر: <code>{$userId}</code>\n" .
        "👨‍💼اسم کاربر: {$uFirstName}\n" .
        "⚡️ نام کاربری: @{$uUsername}\n" .
        "🎈 نام سرویس: <code>{$remark}</code>\n" .
        "🔋حجم سرویس: {$volume} گیگ\n" .
        "⏰ مدت زمان سرویس: {$days} روز\n" .
        "❌ حجم باقی مانده: {$leftMb}\n" .
        "📆 روز باقیمانده: {$expiryDay}";

    // ادیت مسیج لوکس ادمین به همراه دکمه بازگشت به لیست مدیریت کانفیگ‌ها
    editText($message_id, $msgAdmin, json_encode([
        'inline_keyboard' => [
            [getBtn('back_button', 'managePanel')]
        ]
    ]), "HTML");

    exit();
}
