<?php

class TelegramButton {
    public static function cancelBtn(string $lang = 'fa', string $textFa = "انصراف", string $textEn = "Cancel", string $callback = 'main_menu'): array
    {
        return [
            "text" => ($lang === 'fa') ? $textFa : $textEn,
            "callback_data" => $callback,
            "style" => "danger",
            "icon_custom_emoji_id" => "5215680783863261658"
        ];
    }
    public static function backBtn(string $lang = 'fa', string $callback = 'main_menu'): array
    {
        return [
            "text" => function_exists('__') ? (__('bot.buttons.back', [], $lang) ?? (($lang === 'fa') ? "بازگشت" : "Back")) : (($lang === 'fa') ? "بازگشت" : "Back"),
            "callback_data" => $callback,
            "style" => "danger",
            "icon_custom_emoji_id" => "5352759161945867747"
        ];
    }
}

function getMiniAppBtn(string $text, string $hash = '') {
    $baseUrl = "https://wizwiz.villux.ir:8443/Netfreedom/mini-app/";
    if (!empty($hash)) {
        $baseUrl .= "#" . ltrim($hash, '#');
    }
    return [
        'text' => $text,
        'web_app' => ['url' => $baseUrl]
    ];
}

// --- Function getMainKeys ---
function getMainKeys()
{
    global $connection, $userInfo, $from_id, $admin, $botState;
    $mainKeys = [];

    // دکمه ورود به مینی اپ در سطر اول
    $webAppUrl = "https://wizwiz.villux.ir:8443/Netfreedom/mini-app/";
    $mainKeys[] = [getBtn('mini_app', null, null, $webAppUrl)];

    // بخش نماینده‌ها
    if ($botState['agencyState'] == "on" && $userInfo['is_agent'] == 1) {
        $mainKeys[] = [getBtn('agency_setting', "agencySettings")];
        $mainKeys[] = [getBtn('agent_one_buy', "agentOneBuy"), getBtn('agent_much_buy', "agentMuchBuy")];
        $mainKeys[] = [getBtn('my_subscriptions', "agentConfigsList")];
    } 
    // بخش کاربران عادی و ادمین
    else {
        if ($botState['agencyState'] == "on" && $userInfo['is_agent'] == 0) {
            $mainKeys[] = [getBtn('request_agency', "requestAgency")];
        }
        
        if ($botState['sellState'] == "on" || $from_id == $admin || $userInfo['isAdmin'] == true) {
            $mainKeys[] = [getBtn('my_subscriptions', 'mySubscriptions'), getBtn('buy_subscriptions', "buySubscription")];
        } else {
            $mainKeys[] = [getBtn('my_subscriptions', 'mySubscriptions')];
        }
    }

    // اکانت تست
    if ($botState['testAccount'] == "on") {
        $mainKeys[] = [getBtn('test_account', "getTestAccount")];
    }

    // شارژ کیف پول و اطلاعات حساب
    $mainKeys[] = [getBtn('sharj', "increaseMyWallet")];
    $mainKeys[] = [getBtn('invite_friends', "inviteFriends"), getBtn('my_info', "myInfo")];

    // موجودی سرورها
    if ($botState['sharedExistence'] == "on" && $botState['individualExistence'] == "on") {
        $mainKeys[] = [getBtn('shared_existence', "availableServers"), getBtn('individual_existence', "availableServers2")];
    } elseif ($botState['sharedExistence'] == "on") {
        $mainKeys[] = [getBtn('shared_existence', "availableServers")];
    } elseif ($botState['individualExistence'] == "on") {
        $mainKeys[] = [getBtn('individual_existence', "availableServers2")];
    }

    // لینک برنامه‌ها و پشتیبانی
    $mainKeys[] = [getBtn('application_links', "reciveApplications"), getBtn('my_tickets', "supportSection")];

    // جستجوی کانفیگ
    if ($botState['searchState'] == "on" || $from_id == $admin || $userInfo['isAdmin'] == true) {
        $mainKeys[] = [getBtn('search_config', "showUUIDLeft")];
    }

    // دکمه‌های متفرقه از دیتابیس
    $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` LIKE '%MAIN_BUTTONS%'");
    $stmt->execute();
    $buttons = $stmt->get_result();
    $stmt->close();
    
    $temp = [];
    if ($buttons->num_rows > 0) {
        while ($row = $buttons->fetch_assoc()) {
            $title = str_replace("MAIN_BUTTONS", "", $row['type']);
            $temp[] = ['text' => $title, 'callback_data' => "showMainButtonAns" . $row['id']];
            
            // چیدن دکمه‌های دیتابیس به صورت دو تایی
            if (count($temp) >= 2) {
                $mainKeys[] = $temp;
                $temp = [];
            }

        }
    }
    if (!empty($temp)) {
        $mainKeys[] = $temp;
    }

    // دکمه مدیریت برای ادمین (با استایل آبی)
    if ($from_id == $admin || $userInfo['isAdmin'] == true) {
        $mainKeys[] = [['text' => "مدیریت ربات ⚙️", 'callback_data' => "managePanel", 'style' => 'primary']];
    }

    return json_encode(['inline_keyboard' => $mainKeys]);
}

// --- Function getAgentKeys ---
function getAgentKeys()
{
    global $buttonValues, $mainValues, $from_id, $userInfo, $connection;
    $agencyDate = jdate("Y-m-d H:i:s", $userInfo['agent_date']);
    $joinedDate = jdate("Y-m-d H:i:s", $userInfo['date']);
    $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `userid` = ? AND `agent_bought` = 1");
    $stmt->bind_param("i", $from_id);
    $stmt->execute();
    $boughtAccounts = $stmt->get_result()->num_rows;
    $stmt->close();

    $agent_vol = floatval($userInfo['agent_volume'] ?? 0);
    $agent_vol_txt = ($agent_vol == 0) ? "نامحدود" : number_format($agent_vol, 1) . " GB";
    $agent_lim = intval($userInfo['agent_limit'] ?? 0);
    $agent_lim_txt = ($agent_lim == 0) ? "نامحدود" : $agent_lim . " عدد";

    return json_encode(['inline_keyboard' => [
        [['text' => "$agent_vol_txt", 'callback_data' => "NetFreedomVPN"], ['text' => "🔋 حجم باقی‌مانده:", 'callback_data' => "NetFreedomVPN"]],
        [['text' => "$agent_lim_txt", 'callback_data' => "NetFreedomVPN"], ['text' => "👤 اکانت‌های قابل ساخت:", 'callback_data' => "NetFreedomVPN"]],
        [['text' => "➕ ساخت کانفیگ (از سهمیه)", 'callback_data' => "agentCreateConfig_selectServer"]],
        [['text' => "🛍 خرید سهمیه جدید", 'callback_data' => "agentBuyQuota_stepVolume"]],
        [getMiniAppBtn(" ورود به پنل نمایندگی مینی‌اپ 📱", "reseller-panel")],
        [['text' => $boughtAccounts, 'callback_data' => "NetFreedomVPN"], ['text' => $buttonValues['agent_bought_accounts'], 'callback_data' => "NetFreedomVPN"]],
        [['text' => $joinedDate, 'callback_data' => "NetFreedomVPN"], ['text' => $buttonValues['agent_joined_date'], 'callback_data' => "NetFreedomVPN"]],
        [['text' => $agencyDate, 'callback_data' => "NetFreedomVPN"], ['text' => $buttonValues['agent_agency_date'], 'callback_data' => "NetFreedomVPN"]],
        [getBtn('back_to_main', 'mainMenu')],
    ]]);
}

// --- Function getAdminKeys ---
function getAdminKeys()
{
    global $buttonValues, $mainValues, $from_id, $admin;

    return json_encode(['inline_keyboard' => [
            [['text' => $buttonValues['bot_reports'], 'callback_data' => "botReports"], ['text' => $buttonValues['message_to_user'], 'callback_data' => "messageToSpeceficUser"]],
            [['text' => $buttonValues['user_reports'], 'callback_data' => "userReports"]],
            ($from_id == $admin ? [['text' => $buttonValues['admins_list'], 'callback_data' => "adminsList"]] : []),
            [['text' => $buttonValues['increase_wallet'], 'callback_data' => "increaseUserWallet"], ['text' => $buttonValues['decrease_wallet'], 'callback_data' => "decreaseUserWallet"]],
            [['text' => $buttonValues['create_account'], 'callback_data' => "createMultipleAccounts"],
                ['text' => $buttonValues['gift_volume_day'], 'callback_data' => "giftVolumeAndDay"]],
            [['text' => $buttonValues['ban_user'], 'callback_data' => "banUser"], ['text' => $buttonValues['unban_user'], 'callback_data' => "unbanUser"]],
            [['text' => $buttonValues['search_admin_config'], 'callback_data' => "searchUsersConfig"]],
            [['text' => $buttonValues['server_settings'], 'callback_data' => "serversSetting"]],
            [['text' => $buttonValues['categories_settings'], 'callback_data' => "categoriesSetting"]],
            [['text' => $buttonValues['plan_settings'], 'callback_data' => "backplan"]],
            [['text' => $buttonValues['discount_settings'], 'callback_data' => "discount_codes"], ['text' => $buttonValues['main_button_settings'], 'callback_data' => "mainMenuButtons"]],
            [['text' => $buttonValues['gateways_settings'], 'callback_data' => "gateWays_Channels"], ['text' => $buttonValues['bot_settings'], 'callback_data' => 'botSettings']],
            [['text' => $buttonValues['tickets_list'], 'callback_data' => "ticketsList"], ['text' => $buttonValues['message_to_all'], 'callback_data' => "message2All"]],
            [['text' => $buttonValues['forward_to_all'], 'callback_data' => "forwardToAll"]],
            [
                ['text' => $buttonValues['agent_list'], 'callback_data' => "agentsList"],
                ['text' => 'درخواست های رد شده', 'callback_data' => "rejectedAgentList"]
            ],
            [getBtn('back_to_main', 'mainMenu')],
        ]]);

}

// --- Function getServerConfigKeys ---
function getServerConfigKeys($serverId, $offset = 0)
{
    global $connection, $mainValues, $buttonValues;
    $stmt = $connection->prepare("SELECT * FROM `server_info` WHERE `id`=?");
    $stmt->bind_param("i", $serverId);
    $stmt->execute();
    $cats = $stmt->get_result();
    $stmt->close();

    $cty = $cats->fetch_assoc();
    $id = $cty['id'];
    $cname = $cty['title'];
    $flagwizwiz = $cty['flag'];
    $remarkwizwiz = $cty['remark'];
    $ucount = $cty['ucount'];
    $stmt = $connection->prepare("SELECT * FROM `server_config` WHERE `id`=?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $serverConfig = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $reality = $serverConfig['reality'] == "true" ? $buttonValues['active'] : $buttonValues['deactive'];
    $panelUrl = $serverConfig['panel_url'];
    $sni = !empty($serverConfig['sni']) ? $serverConfig['sni'] : " ";
    $headerType = !empty($serverConfig['header_type']) ? $serverConfig['header_type'] : " ";
    $requestHeader = !empty($serverConfig['request_header']) ? $serverConfig['request_header'] : " ";
    $responseHeader = !empty($serverConfig['response_header']) ? $serverConfig['response_header'] : " ";
    $security = !empty($serverConfig['security']) ? $serverConfig['security'] : " ";
    $portType = $serverConfig['port_type'] == "auto" ? "خودکار" : "تصادفی";
    $serverType = " ";
    switch ($serverConfig['type']) {
        case "sanaei":
            $serverType = "سنایی";
            break;
        case "alireza":
            $serverType = "علیرضا";
            break;
        case "normal":
            $serverType = "ساده";
            break;
        case "marzban":
            $serverType = "مرزبان";
            break;
    }
    return json_encode(['inline_keyboard' => array_merge([
            [
                ['text' => $panelUrl, 'callback_data' => "NetFreedomVPN"],
            ],
            [
                ['text' => $cname, 'callback_data' => "editServerName$id"],
                ['text' => "❕نام سرور", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                ['text' => $flagwizwiz, 'callback_data' => "editServerFlag$id"],
                ['text' => "🚩 پرچم سرور", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                ['text' => $remarkwizwiz, 'callback_data' => "editServerRemark$id"],
                ['text' => "📣 ریمارک سرور", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                ['text' => $serverType ?? " ", 'callback_data' => "changeServerType$id"],
                ['text' => "نوعیت سرور", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                ['text' => $ucount, 'callback_data' => "editServerMax$id"],
                ['text' => "ظرفیت سرور", 'callback_data' => "NetFreedomVPN"]
            ]
        ],
        ($serverConfig['type'] != "marzban" ? [
            [
                ['text' => $portType, 'callback_data' => "changePortType$id"],
                ['text' => "نوعیت پورت", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                ['text' => $sni, 'callback_data' => "editsServersni$id"],
                ['text' => "sni", 'callback_data' => "NetFreedomVPN"],
            ],
            [
                ['text' => $headerType, 'callback_data' => "editsServerheader_type$id"],
                ['text' => "header type", 'callback_data' => "NetFreedomVPN"],
            ],
            [
                ['text' => $requestHeader, 'callback_data' => "editsServerrequest_header$id"],
                ['text' => "request header", 'callback_data' => "NetFreedomVPN"],
            ],
            [
                ['text' => $responseHeader, 'callback_data' => "editsServerresponse_header$id"],
                ['text' => "response header", 'callback_data' => "NetFreedomVPN"],
            ],
            [
                ['text' => $security, 'callback_data' => "editsServersecurity$id"],
                ['text' => "security", 'callback_data' => "NetFreedomVPN"],
            ],
            (($serverConfig['type'] == "sanaei" || $serverConfig['type'] == "alireza") ? 
            [
                ['text' => $reality, 'callback_data' => "changeRealityState$id"],
                ['text' => "reality", 'callback_data' => "NetFreedomVPN"],
            ] : []),
            [
                ['text' => "♻️ تغییر آیپی های سرور", 'callback_data' => "changesServerIp$id"],
            ],
            [
                ['text' => "♻️ تغییر security setting", 'callback_data' => "editsServertlsSettings$id"],
            ]
        ] : []), [
            [
                ['text' => "🔅تغییر اطلاعات ورود", 'callback_data' => "changesServerLoginInfo$id"],
            ],
            [
                ['text' => "✂️ حذف سرور", 'callback_data' => "wizwizdeleteserver$id"],
            ],
            [['text' => $buttonValues['back_button'], 'callback_data' => "nextServerPage" . $offset]]
        ])]);
}

// --- Function getServerListKeys ---
function getServerListKeys($offset = 0)
{
    global $connection, $mainValues, $buttonValues;

    $limit = 15;
    $offset = intval($offset);

    $stmt = $connection->prepare("SELECT * FROM `server_info` WHERE `active`=1 LIMIT ? OFFSET ?");
    $stmt->bind_param('ii', $limit, $offset);
    $stmt->execute();
    $cats = $stmt->get_result();
    $stmt->close();

    $keys = array();
    $keys[] = [['text' => "وضعیت", 'callback_data' => "NetFreedomVPN"], ['text' => "تنظیمات", 'callback_data' => "NetFreedomVPN"], ['text' => "نوعیت", 'callback_data' => "NetFreedomVPN"], ['text' => "سرور", 'callback_data' => "NetFreedomVPN"]];
    
    if ($cats->num_rows == 0) {
        $keys[] = [['text' => "سروری یافت نشد", 'callback_data' => "NetFreedomVPN"]];
    }
    else {
        while ($cty = $cats->fetch_assoc()) {
            $id = $cty['id'];
            $cname = $cty['title'];
            $state = (isset($cty['state']) && $cty['state'] == "1") ? $buttonValues['active'] : $buttonValues['deactive'];
            
            $stmt = $connection->prepare("SELECT * FROM `server_config` WHERE `id`=?");
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $serverTypeInfo = $stmt->get_result()->fetch_assoc();
            $stmt->close();
            
            // جلوگیری از خطای امنیتی Trying to access array offset on null
            $savedType = isset($serverTypeInfo['type']) ? $serverTypeInfo['type'] : 'normal';
            $serverType = "ساده";
            
            switch ($savedType) {
                case "sanaei":
                    $serverType = "سنایی"; break;
                case "alireza":
                    $serverType = "علیرضا"; break;
                case "normal":
                    $serverType = "ساده"; break;
                case "marzban":
                    $serverType = "مرزبان"; break;
            }
            
            $keys[] = [
                ['text' => $state, 'callback_data' => 'toggleServerState' . $id . "_" . $offset], 
                ['text' => "⚙️", 'callback_data' => "showServerSettings" . $id . "_" . $offset], 
                ['text' => $serverType, 'callback_data' => "NetFreedomVPN"], 
                ['text' => $cname, 'callback_data' => "NetFreedomVPN"]
            ];
        }
    }
    
    if ($offset == 0 && $cats->num_rows >= $limit) {
        $keys[] = [['text' => " »» صفحه بعدی »»", 'callback_data' => "nextServerPage" . ($offset + $limit)]];
    }
    elseif ($cats->num_rows >= $limit) {
        $keys[] = [
            ['text' => " »» صفحه بعدی »»", 'callback_data' => "nextServerPage" . ($offset + $limit)],
            ['text' => " «« صفحه قبلی ««", 'callback_data' => "nextServerPage" . ($offset - $limit)]
        ];
    }
    elseif ($offset != 0) {
        $keys[] = [['text' => " «« صفحه قبلی ««", 'callback_data' => "nextServerPage" . ($offset - $limit)]];
    }
    
    $keys[] = [
        ['text' => '➕ ثبت سرور xui', 'callback_data' => "addNewServer"],
        ['text' => "➕ ثبت سرور مرزبان", 'callback_data' => "addNewMarzbanPanel"]
    ];
    $keys[] = [['text' => $buttonValues['back_button'], 'callback_data' => "managePanel"]];
    return json_encode(['inline_keyboard' => $keys]);
}

// --- Function getCategoriesKeys ---
function getCategoriesKeys($offset = 0)
{
    $limit = 15;

    global $connection, $mainValues, $buttonValues;
    $stmt = $connection->prepare("SELECT * FROM `server_categories` WHERE `active`=1 AND `parent`=0 LIMIT ? OFFSET ?");
    $stmt->bind_param('ii', $limit, $offset);
    $stmt->execute();
    $cats = $stmt->get_result();
    $stmt->close();


    $keys = array();
    $keys[] = [['text' => "حذف", 'callback_data' => "NetFreedomVPN"], ['text' => "اسم دسته", 'callback_data' => "NetFreedomVPN"]];
    if ($cats->num_rows == 0) {
        $keys[] = [['text' => "دسته بندی یافت نشد", 'callback_data' => "NetFreedomVPN"]];
    }
    else {
        while ($cty = $cats->fetch_assoc()) {
            $id = $cty['id'];
            $cname = $cty['title'];
            $keys[] = [['text' => "❌", 'callback_data' => "wizwizcategorydelete$id" . "_" . $offset], ['text' => $cname, 'callback_data' => "wizwizcategoryedit$id" . "_" . $offset]];
        }
    }

    if ($offset == 0 && $cats->num_rows >= $limit) {
        $keys[] = [['text' => " »» صفحه بعدی »»", 'callback_data' => "nextCategoryPage" . ($offset + $limit)]];
    }
    elseif ($cats->num_rows >= $limit) {
        $keys[] = [
            ['text' => " »» صفحه بعدی »»", 'callback_data' => "nextCategoryPage" . ($offset + $limit)],
            ['text' => " «« صفحه قبلی ««", 'callback_data' => "nextCategoryPage" . ($offset - $limit)]
        ];
    }
    elseif ($offset != 0) {
        $keys[] = [['text' => " «« صفحه قبلی ««", 'callback_data' => "nextCategoryPage" . ($offset - $limit)]];
    }

    $keys[] = [['text' => '➕ افزودن دسته جدید', 'callback_data' => "addNewCategory"]];
    $keys[] = [['text' => $buttonValues['back_button'], 'callback_data' => "managePanel"]];
    return json_encode(['inline_keyboard' => $keys]);
}

// --- Function getGateWaysKeys ---
function getGateWaysKeys()
{
    global $connection, $mainValues, $buttonValues;

    $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'BOT_STATES'");
    $stmt->execute();
    $botState = $stmt->get_result()->fetch_assoc()['value'];
    if (!is_null($botState))
        $botState = json_decode($botState, true);
    else
        $botState = array();
    $stmt->close();

    $cartToCartState = $botState['cartToCartState'] == "on" ? $buttonValues['on'] : $buttonValues['off'];
    $walletState = $botState['walletState'] == "on" ? $buttonValues['on'] : $buttonValues['off'];
    $sellState = $botState['sellState'] == "on" ? $buttonValues['on'] : $buttonValues['off'];
    $weSwapState = $botState['weSwapState'] == "on" ? $buttonValues['on'] : $buttonValues['off'];
    $robotState = $botState['botState'] == "on" ? $buttonValues['on'] : $buttonValues['off'];
    $nowPaymentWallet = $botState['nowPaymentWallet'] == "on" ? $buttonValues['on'] : $buttonValues['off'];
    $nowPaymentOther = $botState['nowPaymentOther'] == "on" ? $buttonValues['on'] : $buttonValues['off'];
    $tronWallet = $botState['tronWallet'] == "on" ? $buttonValues['on'] : $buttonValues['off'];
    $zarinpal = $botState['zarinpal'] == "on" ? $buttonValues['on'] : $buttonValues['off'];
    $nextpay = $botState['nextpay'] == "on" ? $buttonValues['on'] : $buttonValues['off'];
    $stars = ($botState['stars'] ?? 'off') == "on" ? $buttonValues['on'] : $buttonValues['off'];
    $rewaredChannel = $botState['rewardChannel'] ?? " ";
    $lockChannel = $botState['lockChannel'] ?? " ";

    $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'PAYMENT_KEYS'");
    $stmt->execute();
    $paymentKeys = $stmt->get_result()->fetch_assoc()['value'];
    if (!is_null($paymentKeys))
        $paymentKeys = json_decode($paymentKeys, true);
    else
        $paymentKeys = array();
    $stmt->close();
    return json_encode(['inline_keyboard' => [
            [
                ['text' => (!empty($paymentKeys['bankAccount']) ? $paymentKeys['bankAccount'] : " "), 'callback_data' => "changePaymentKeysbankAccount"],
                ['text' => "شماره حساب", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                ['text' => (!empty($paymentKeys['holderName']) ? $paymentKeys['holderName'] : " "), 'callback_data' => "changePaymentKeysholderName"],
                ['text' => "دارنده حساب", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                ['text' => (!empty($paymentKeys['nowpayment']) ? $paymentKeys['nowpayment'] : " "), 'callback_data' => "changePaymentKeysnowpayment"],
                ['text' => "کد درگاه nowPayment", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                ['text' => (!empty($paymentKeys['zarinpal']) ? $paymentKeys['zarinpal'] : " "), 'callback_data' => "changePaymentKeyszarinpal"],
                ['text' => "کد درگاه زرین پال", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                ['text' => (!empty($paymentKeys['nextpay']) ? $paymentKeys['nextpay'] : " "), 'callback_data' => "changePaymentKeysnextpay"],
                ['text' => "کد درگاه نکست پی", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                ['text' => (!empty($paymentKeys['tronwallet']) ? $paymentKeys['tronwallet'] : " "), 'callback_data' => "changePaymentKeystronwallet"],
                ['text' => "آدرس والت ترون", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                ['text' => $weSwapState, 'callback_data' => "changeGateWaysweSwapState"],
                ['text' => "درگاه وی سواپ", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                ['text' => $cartToCartState, 'callback_data' => "changeGateWayscartToCartState"],
                ['text' => "کارت به کارت", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                ['text' => $nextpay, 'callback_data' => "changeGateWaysnextpay"],
                ['text' => "درگاه نکست پی", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                ['text' => $zarinpal, 'callback_data' => "changeGateWayszarinpal"],
                ['text' => "درگاه زرین پال", 'callback_data' => "NetFreedomVPN"]
            ],

            [
                ['text' => $stars, 'callback_data' => "changeGateWaysstars"],
                ['text' => "درگاه ستاره", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                ['text' => $nowPaymentWallet, 'callback_data' => "changeGateWaysnowPaymentWallet"],
                ['text' => "درگاه NowPayment کیف پول", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                ['text' => $nowPaymentOther, 'callback_data' => "changeGateWaysnowPaymentOther"],
                ['text' => "درگاه NowPayment سایر", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                ['text' => $tronWallet, 'callback_data' => "changeGateWaystronWallet"],
                ['text' => "درگاه ترون", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                ['text' => $walletState, 'callback_data' => "changeGateWayswalletState"],
                ['text' => "کیف پول", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                ['text' => $rewaredChannel, 'callback_data' => 'editRewardChannel'],
                ['text' => "کانال گزارش درآمد", 'callback_data' => 'NetFreedomVPN']
            ],
            [
                ['text' => $lockChannel, 'callback_data' => 'editLockChannel'],
                ['text' => "کانال قفل", 'callback_data' => 'NetFreedomVPN']
            ],
            [['text' => $buttonValues['back_button'], 'callback_data' => "managePanel"]]
        ]]);

}

// --- Function getBotSettingKeys ---
function getBotSettingKeys()
{
    global $connection, $mainValues, $buttonValues;

    $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'BOT_STATES'");
    $stmt->execute();
    $botState = $stmt->get_result()->fetch_assoc()['value'];
    if (!is_null($botState))
        $botState = json_decode($botState, true);
    else
        $botState = array();
    $stmt->close();

    $changeProtocole = $botState['changeProtocolState'] == "on" ? $buttonValues['on'] : $buttonValues['off'];
    $renewAccount = $botState['renewAccountState'] == "on" ? $buttonValues['on'] : $buttonValues['off'];
    $plandelkhahwiz = $botState['plandelkhahState'] == "on" ? $buttonValues['on'] : $buttonValues['off'];
    $switchLocation = $botState['switchLocationState'] == "on" ? $buttonValues['on'] : $buttonValues['off'];
    $increaseTime = $botState['increaseTimeState'] == "on" ? $buttonValues['on'] : $buttonValues['off'];
    $increaseVolume = $botState['increaseVolumeState'] == "on" ? $buttonValues['on'] : $buttonValues['off'];
    $subLink = ($botState['subLinkState'] ?? "off") == "on" ? $buttonValues['on'] : $buttonValues['off'];
    $configLink = ($botState['configLinkState'] ?? "off") == "off" ? $buttonValues['off'] : $buttonValues['on']; // فیکس
    $renewConfigLink = ($botState['renewConfigLinkState'] ?? "off") == "on" ? $buttonValues['on'] : $buttonValues['off'];
    $updateConfigLink = ($botState['updateConfigLinkState'] ?? "off") == "on" ? $buttonValues['on'] : $buttonValues['off']; // فیکس
    $individualExistence = ($botState['individualExistence'] ?? "off") == "on" ? $buttonValues['on'] : $buttonValues['off'];
    $sharedExistence = ($botState['sharedExistence'] ?? "off") == "on" ? $buttonValues['on'] : $buttonValues['off'];
    $testAccount = ($botState['testAccount'] ?? "off") == "on" ? $buttonValues['on'] : $buttonValues['off'];
    $agency = ($botState['agencyState'] ?? "off") == "on" ? $buttonValues['on'] : $buttonValues['off'];
    $agencyPlanDiscount = ($botState['agencyPlanDiscount'] ?? "off") == "on" ? $buttonValues['plan_discount'] : $buttonValues['server_discount'];
    $qrConfig = ($botState['qrConfigState'] ?? "off") == "on" ? $buttonValues['on'] : $buttonValues['off'];
    $qrSub = ($botState['qrSubState'] ?? "off") == "on" ? $buttonValues['on'] : $buttonValues['off']; // فیکس
    $stars = ($botState['stars'] ?? "off") == "on" ? $buttonValues['on'] : $buttonValues['off'];

    $requirePhone = $botState['requirePhone'] == "on" ? $buttonValues['on'] : $buttonValues['off'];
    $requireIranPhone = $botState['requireIranPhone'] == "on" ? $buttonValues['on'] : $buttonValues['off'];
    $sellState = $botState['sellState'] == "on" ? $buttonValues['on'] : $buttonValues['off'];
    $robotState = $botState['botState'] == "on" ? $buttonValues['on'] : $buttonValues['off'];
    $searchState = $botState['searchState'] == "on" ? $buttonValues['on'] : $buttonValues['off'];
    $updateConnectionState = $botState['updateConnectionState'] == "robot" ? "از روی ربات" : "از روی سایت";
    $rewaredTime = ($botState['rewaredTime'] ?? 0) . " ساعت";
    switch ($botState['remark']) {
        case "digits":
            $remarkType = "عدد رندم 5 حرفی";
            break;
        case "manual":
            $remarkType = "توسط کاربر";
            break;
        default:
            $remarkType = "آیدی و عدد رندوم";
            break;
    }

    $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'PAYMENT_KEYS'");
    $stmt->execute();
    $paymentKeys = $stmt->get_result()->fetch_assoc()['value'];
    if (!is_null($paymentKeys))
        $paymentKeys = json_decode($paymentKeys, true);
    else
        $paymentKeys = array();
    $stmt->close();
    return json_encode(['inline_keyboard' => [
            [
                ['text' => "🎗 بنر بازاریابی 🎗", 'callback_data' => "inviteSetting"]
            ],
            [
                ['text' => $updateConnectionState, 'callback_data' => "changeUpdateConfigLinkState"],
                ['text' => "آپدیت کانفیگ", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                getBtn(($botState['agencyState'] ?? 'off') == 'on' ? 'on' : 'off', "changeBotagencyState"),
                ['text' => "نمایندگی", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                ['text' => $agencyPlanDiscount, 'callback_data' => "changeBotagencyPlanDiscount"],
                ['text' => "نوع تخفیف نمایندگی", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                getBtn(($botState['individualExistence'] ?? 'off') == 'on' ? 'on' : 'off', "changeBotindividualExistence"),
                ['text' => "موجودی اختصاصی", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                getBtn(($botState['sharedExistence'] ?? 'off') == 'on' ? 'on' : 'off', "changeBotsharedExistence"),
                ['text' => "موجودی اشتراکی", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                getBtn(($botState['testAccount'] ?? 'off') == 'on' ? 'on' : 'off', "changeBottestAccount"),
                ['text' => "اکانت تست", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                getBtn(($botState['changeProtocolState'] ?? 'off') == 'on' ? 'on' : 'off', "changeBotchangeProtocolState"),
                ['text' => "تغییر پروتکل", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                getBtn(($botState['renewAccountState'] ?? 'off') == 'on' ? 'on' : 'off', "changeBotrenewAccountState"),
                ['text' => "تمدید سرویس", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                getBtn(($botState['plandelkhahState'] ?? 'off') == 'on' ? 'on' : 'off', "changeBotplandelkhahState"),
                ['text' => "پلن دلخواه", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                getBtn(($botState['switchLocationState'] ?? 'off') == 'on' ? 'on' : 'off', "changeBotswitchLocationState"),
                ['text' => "تغییر لوکیشن", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                getBtn(($botState['increaseTimeState'] ?? 'off') == 'on' ? 'on' : 'off', "changeBotincreaseTimeState"),
                ['text' => "افزایش زمان", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                getBtn(($botState['increaseVolumeState'] ?? 'off') == 'on' ? 'on' : 'off', "changeBotincreaseVolumeState"),
                ['text' => "افزایش حجم", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                getBtn(($botState['requirePhone'] ?? 'off') == 'on' ? 'on' : 'off', "changeBotrequirePhone"),
                ['text' => "تأیید شماره", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                getBtn(($botState['requireIranPhone'] ?? 'off') == 'on' ? 'on' : 'off', "changeBotrequireIranPhone"),
                ['text' => "تأیید شماره ایرانی", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                getBtn(($botState['sellState'] ?? 'off') == 'on' ? 'on' : 'off', "changeBotsellState"),
                ['text' => "فروش", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                getBtn(($botState['botState'] ?? 'off') == 'on' ? 'on' : 'off', "changeBotbotState"),
                ['text' => "وضعیت ربات", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                getBtn(($botState['subLinkState'] ?? 'off') == 'on' ? 'on' : 'off', "changeBotsubLinkState"),
                ['text' => "لینک ساب و مشخصات وب", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                getBtn(($botState['configLinkState'] ?? 'off') == 'on' ? 'on' : 'off', "changeBotconfigLinkState"),
                ['text' => "لینک کانفیگ", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                getBtn(($botState['searchState'] ?? 'off') == 'on' ? 'on' : 'off', "changeBotsearchState"),
                ['text' => "مشخصات کانفیگ", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                getBtn(($botState['renewConfigLinkState'] ?? 'off') == 'on' ? 'on' : 'off', "changeBotrenewConfigLinkState"),
                ['text' => "دریافت لینک جدید", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                getBtn(($botState['updateConfigLinkState'] ?? 'off') == 'on' ? 'on' : 'off', "changeBotupdateConfigLinkState"),
                ['text' => "بروز رسانی لینک", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                getBtn(($botState['qrConfigState'] ?? 'off') == 'on' ? 'on' : 'off', "changeBotqrConfigState"),
                ['text' => "کیو آر کد کانفیگ", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                getBtn(($botState['qrSubState'] ?? 'off') == 'on' ? 'on' : 'off', "changeBotqrSubState"),
                ['text' => "کیو آر کد ساب", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                ['text' => $remarkType, 'callback_data' => "changeConfigRemarkType"],
                ['text' => "نوع ریمارک", 'callback_data' => "NetFreedomVPN"]
            ],
            [
                ['text' => $rewaredTime, 'callback_data' => 'editRewaredTime'],
                ['text' => "ارسال گزارش درآمد", 'callback_data' => 'NetFreedomVPN']
            ],
            [
                getBtn(($botState['cartToCartAutoAcceptState'] ?? 'off') == 'on' ? 'on' : 'off', "changeBotcartToCartAutoAcceptState"),
                ['text' => "تأیید خودکار کارت به کارت", 'callback_data' => "NetFreedomVPN"]
            ],
            ($botState['cartToCartAutoAcceptState'] == "on" ? [
                ['text' => ($botState['cartToCartAutoAcceptType'] == "0" ? "نماینده" : ($botState['cartToCartAutoAcceptType'] == "1" ? "کاربر" : "همه")), 'callback_data' => "changeBotcartToCartAutoAcceptType"],
                ['text' => "نوع تأیید", 'callback_data' => "NetFreedomVPN"]
            ] : []),
            ($botState['cartToCartAutoAcceptState'] == "on" ? [
                ['text' => ($botState['cartToCartAutoAcceptTime'] ?? "10") . " دقیقه", 'callback_data' => "editcartToCartAutoAcceptTime"],
                ['text' => "زمان تأیید خودکار ", 'callback_data' => "NetFreedomVPN"]
            ] : []),
            [['text' => $buttonValues['back_button'], 'callback_data' => "managePanel"]]
        ]]);

}

// --- Function getBotReportKeys ---
function getBotReportKeys()
{
    global $connection, $mainValues, $buttonValues;
    $stmt = $connection->prepare("SELECT * FROM `users`");
    $stmt->execute();
    $allUsers = $stmt->get_result()->num_rows;
    $stmt->close();

    $stmt = $connection->prepare("SELECT * FROM `orders_list`");
    $stmt->execute();
    $allOrders = $stmt->get_result()->num_rows;
    $stmt->close();

    $stmt = $connection->prepare("SELECT * FROM `server_config`");
    $stmt->execute();
    $allServers = $stmt->get_result()->num_rows;
    $stmt->close();

    $stmt = $connection->prepare("SELECT * FROM `server_categories`");
    $stmt->execute();
    $allCategories = $stmt->get_result()->num_rows;
    $stmt->close();

    $stmt = $connection->prepare("SELECT * FROM `server_plans`");
    $stmt->execute();
    $allPlans = $stmt->get_result()->num_rows;
    $stmt->close();

    $stmt = $connection->prepare("SELECT SUM(price) as total FROM `pays` WHERE `state` = 'paid' OR `state` = 'approved'");
    $stmt->execute();
    $totalRewards = number_format($stmt->get_result()->fetch_assoc()['total']) . " تومان";
    $stmt->close();


    $persian = explode("-", jdate("Y-n-1", time()));
    $gregorian = jalali_to_gregorian($persian[0], $persian[1], $persian[2]);
    $date = $gregorian[0] . "-" . $gregorian[1] . "-" . $gregorian[2];
    $dayTime = strtotime($date);
    $stmt = $connection->prepare("SELECT SUM(price) as total FROM `pays` WHERE `request_date` > ? AND (`state` = 'paid' OR `state` = 'approved')");
    $stmt->bind_param("i", $dayTime);
    $stmt->execute();
    $monthReward = number_format($stmt->get_result()->fetch_assoc()['total']) . " تومان";
    $stmt->close();

    $dayTime = strtotime("-" . (date("w") + 1) . " days");
    $stmt = $connection->prepare("SELECT SUM(price) as total FROM `pays` WHERE `request_date` > ?  AND (`state` = 'paid' OR `state` = 'approved')");
    $stmt->bind_param("i", $dayTime);
    $stmt->execute();
    $weekReward = number_format($stmt->get_result()->fetch_assoc()['total']) . " تومان";
    $stmt->close();

    $dayTime = strtotime("today");
    $stmt = $connection->prepare("SELECT SUM(price) as total FROM `pays` WHERE `request_date` > ? AND (`state` = 'paid' OR `state` = 'approved')");
    $stmt->bind_param("i", $dayTime);
    $stmt->execute();
    $dayReward = number_format($stmt->get_result()->fetch_assoc()['total']) . " تومان";
    $stmt->close();

    return json_encode(['inline_keyboard' => [
            [
                ['text' => $allUsers, 'callback_data' => 'NetFreedomVPN'],
                ['text' => "تعداد کل کاربران", 'callback_data' => 'NetFreedomVPN']
            ],
            [
                ['text' => $allOrders, 'callback_data' => 'NetFreedomVPN'],
                ['text' => "کل محصولات خریداری شده", 'callback_data' => 'NetFreedomVPN']
            ],
            [
                ['text' => $allServers, 'callback_data' => 'NetFreedomVPN'],
                ['text' => "تعداد سرورها", 'callback_data' => 'NetFreedomVPN']
            ],
            [
                ['text' => $allCategories, 'callback_data' => 'NetFreedomVPN'],
                ['text' => "تعداد دسته ها", 'callback_data' => 'NetFreedomVPN']
            ],
            [
                ['text' => $allPlans, 'callback_data' => 'NetFreedomVPN'],
                ['text' => "تعداد پلن ها", 'callback_data' => 'NetFreedomVPN']
            ],
            [
                ['text' => $totalRewards, 'callback_data' => 'NetFreedomVPN'],
                ['text' => "درآمد کل", 'callback_data' => 'NetFreedomVPN']
            ],
            [
                ['text' => $dayReward, 'callback_data' => 'NetFreedomVPN'],
                ['text' => "درآمد امروز", 'callback_data' => 'NetFreedomVPN']
            ],
            [
                ['text' => $weekReward, 'callback_data' => 'NetFreedomVPN'],
                ['text' => "درآمد هفته", 'callback_data' => 'NetFreedomVPN']
            ],
            [
                ['text' => $monthReward, 'callback_data' => 'NetFreedomVPN'],
                ['text' => "درآمد ماه", 'callback_data' => 'NetFreedomVPN']
            ],
            [
                ['text' => "برگشت به مدیریت", 'callback_data' => 'managePanel']
            ]
        ]]);
}

// --- Function getAdminsKeys ---
function getAdminsKeys()
{
    global $connection, $mainValues, $buttonValues;
    $keys = array();

    $stmt = $connection->prepare("SELECT * FROM `users` WHERE `isAdmin` = true");
    $stmt->execute();
    $usersList = $stmt->get_result();
    $stmt->close();
    if ($usersList->num_rows > 0) {
        while ($user = $usersList->fetch_assoc()) {
            $keys[] = [['text' => "❌", 'callback_data' => "delAdmin" . $user['userid']], ['text' => $user['name'], "callback_data" => "NetFreedomVPN"]];
        }
    }
    else {
        $keys[] = [['text' => "لیست ادمین ها خالی است ❕", 'callback_data' => "NetFreedomVPN"]];
    }
    $keys[] = [['text' => "➕ افزودن ادمین", 'callback_data' => "addNewAdmin"]];
    $keys[] = [['text' => $buttonValues['back_button'], 'callback_data' => "managePanel"]];
    return json_encode(['inline_keyboard' => $keys]);
}

// --- Function getUserInfoKeys ---
function getUserInfoKeys($userId)
{
    global $connection, $mainValues, $buttonValues;
    $stmt = $connection->prepare("SELECT * FROM `users` WHERE `userid` = ?");
    $stmt->bind_param("i", $userId);
    $stmt->execute();
    $userCount = $stmt->get_result();
    $stmt->close();
    if ($userCount->num_rows > 0) {
        $userInfos = $userCount->fetch_assoc();
        $userWallet = number_format($userInfos['wallet']) . " تومان";

        $stmt = $connection->prepare("SELECT COUNT(amount) as count, SUM(amount) as total FROM `orders_list` WHERE `userid` = ?");
        $stmt->bind_param("i", $userId);
        $stmt->execute();
        $info = $stmt->get_result()->fetch_assoc();

        $boughtService = $info['count'];
        $totalBoughtPrice = number_format((float)($info['total'] ?? 0)) . " تومان";

        $userDetail = bot('getChat', ['chat_id' => $userId])->result;
        $userUserName = $userDetail->username;
        $fullName = $userDetail->first_name . " " . $userDetail->last_name;

        return json_encode(['inline_keyboard' => [
                [
                    ['text' => $userUserName ?? " ", 'url' => "t.me/$userUserName"],
                    ['text' => "یوزرنیم", 'callback_data' => "NetFreedomVPN"]
                ],
                [
                    ['text' => $fullName ?? " ", 'callback_data' => "NetFreedomVPN"],
                    ['text' => "نام", 'callback_data' => "NetFreedomVPN"]
                ],
                [
                    ['text' => $boughtService ?? " ", 'callback_data' => "NetFreedomVPN"],
                    ['text' => "سرویس ها", 'callback_data' => "NetFreedomVPN"]
                ],
                [
                    ['text' => $totalBoughtPrice ?? " ", 'callback_data' => "NetFreedomVPN"],
                    ['text' => "مبلغ خرید", 'callback_data' => "NetFreedomVPN"]
                ],
                [
                    ['text' => $userWallet ?? " ", 'callback_data' => "NetFreedomVPN"],
                    ['text' => "موجودی کیف پول", 'callback_data' => "NetFreedomVPN"]
                ],
                [
                    getBtn('back_button', 'mainMenu')
                ],
            ]]);
    }
    else
        return null;
}

// --- Function getDiscountCodeKeys ---
function getDiscountCodeKeys()
{
    global $connection, $mainValues, $buttonValues;
    $time = time();
    $stmt = $connection->prepare("SELECT * FROM `discounts` WHERE (`expire_date` > $time OR `expire_date` = 0) AND (`expire_count` > 0 OR `expire_count` = -1)");
    $stmt->execute();
    $list = $stmt->get_result();
    $stmt->close();
    $keys = array();
    if ($list->num_rows > 0) {
        $keys[] = [['text' => 'حذف', 'callback_data' => "NetFreedomVPN"], ['text' => "استفاده هر یوزر", 'callback_data' => "NetFreedomVPN"], ['text' => "تاریخ ختم", 'callback_data' => "NetFreedomVPN"], ['text' => "تعداد استفاده", 'callback_data' => "NetFreedomVPN"], ['text' => "مقدار تخفیف", 'callback_data' => "NetFreedomVPN"], ['text' => "کد تخفیف", 'callback_data' => "NetFreedomVPN"]];
        while ($row = $list->fetch_assoc()) {
            $date = $row['expire_date'] != 0 ? jdate("Y/n/j H:i", $row['expire_date']) : "نامحدود";
            $count = $row['expire_count'] != -1 ? $row['expire_count'] : "نامحدود";
            $amount = $row['amount'];
            $amount = $row['type'] == 'percent' ? $amount . "%" : $amount = number_format($amount) . " تومان";
            $hashId = $row['hash_id'];
            $rowId = $row['id'];
            $canUse = $row['can_use'];

            $keys[] = [['text' => '❌', 'callback_data' => "delDiscount" . $rowId], ['text' => $canUse, 'callback_data' => "NetFreedomVPN"], ['text' => $date, 'callback_data' => "NetFreedomVPN"], ['text' => $count, 'callback_data' => "NetFreedomVPN"], ['text' => $amount, 'callback_data' => "NetFreedomVPN"], ['text' => $hashId, 'callback_data' => 'copyHash' . $hashId]];
        }
    }
    else {
        $keys[] = [['text' => "کد تخفیفی یافت نشد", 'callback_data' => "NetFreedomVPN"]];
    }

    $keys[] = [['text' => "افزودن کد تخفیف", 'callback_data' => "addDiscountCode"]];
    $keys[] = [['text' => $buttonValues['back_button'], 'callback_data' => "managePanel"]];
    return json_encode(['inline_keyboard' => $keys]);
}

// --- Function getMainMenuButtonsKeys ---
function getMainMenuButtonsKeys()
{
    global $connection, $mainValues, $buttonValues;

    $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` LIKE '%MAIN_BUTTONS%'");
    $stmt->execute();
    $buttons = $stmt->get_result();
    $stmt->close();

    $keys = array();
    if ($buttons->num_rows > 0) {
        while ($row = $buttons->fetch_assoc()) {
            $rowId = $row['id'];
            $title = str_replace("MAIN_BUTTONS", "", $row['type']);
            $answer = $row['value'];
            $keys[] = [
                ['text' => "❌", 'callback_data' => "delMainButton" . $rowId],
                ['text' => $title ?? " ", 'callback_data' => "NetFreedomVPN"]];
        }
    }
    else {
        $keys[] = [['text' => "دکمه ای یافت نشد ❕", 'callback_data' => "NetFreedomVPN"]];
    }
    $keys[] = [['text' => "افزودن دکمه جدید ➕", 'callback_data' => "addNewMainButton"]];
    $keys[] = [['text' => $buttonValues['back_button'], 'callback_data' => "managePanel"]];
    return json_encode(['inline_keyboard' => $keys]);
}

// --- Function getPlanDetailsKeys ---
function getPlanDetailsKeys($planId)
{
    global $connection, $mainValues, $buttonValues;
    $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `id`=?");
    $stmt->bind_param("i", $planId);
    $stmt->execute();
    $pdResult = $stmt->get_result();
    $pd = $pdResult->fetch_assoc();
    $stmt->close();


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

    $reality = $server_info['reality'];


    if ($pdResult->num_rows == 0)
        return null;
    else {
        $id = $pd['id'];
        $name = $pd['title'];
        $price = $pd['price'];
        $acount = $pd['acount'];
        $rahgozar = $pd['rahgozar'];
        $customPath = $pd['custom_path'] == true ? $buttonValues['on'] : $buttonValues['off'];
        $dest = $pd['dest'] ?? " ";
        $spiderX = $pd['spiderX'] ?? " ";
        $serverName = $pd['serverNames'] ?? " ";
        $flow = $pd['flow'];
        $customPort = $pd['custom_port'];
        $customSni = $pd['custom_sni'] ?? " ";

        $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `status`=1 AND `fileid`=?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $wizwizplanaccnumber = $stmt->get_result()->num_rows;
        $stmt->close();

        $srvid = $pd['server_id'];
        $keyboard = [
            ($rahgozar == true ? [['text' => "* نوع پلن: رهگذر *", 'callback_data' => 'NetFreedomVPN']] : []),
            ($rahgozar == true ? [
                ['text' => $customPath, 'callback_data' => 'changeCustomPath' . $id],
                ['text' => "Path Custom", 'callback_data' => 'NetFreedomVPN'],
            ] : []),
            ($rahgozar == true ? [
                ['text' => $customPort, 'callback_data' => 'changeCustomPort' . $id],
                ['text' => "پورت دلخواه", 'callback_data' => 'NetFreedomVPN'],
            ] : []),
            ($rahgozar == true ? [
                ['text' => $customSni, 'callback_data' => 'changeCustomSni' . $id],
                ['text' => "sni دلخواه", 'callback_data' => 'NetFreedomVPN'],
            ] : []),
            [['text' => $name, 'callback_data' => "wizwizplanname$id"], ['text' => "🔮 نام پلن", 'callback_data' => "NetFreedomVPN"]],
            ($reality == "true" ? [['text' => $dest, 'callback_data' => "editDestName$id"], ['text' => "dest", 'callback_data' => "NetFreedomVPN"]] : []),
            ($reality == "true" ? [['text' => $serverName, 'callback_data' => "editServerNames$id"], ['text' => "serverNames", 'callback_data' => "NetFreedomVPN"]] : []),
            ($reality == "true" ? [['text' => $spiderX, 'callback_data' => "editSpiderX$id"], ['text' => "spiderX", 'callback_data' => "NetFreedomVPN"]] : []),
            ($reality == "true" ? [['text' => $flow, 'callback_data' => "editFlow$id"], ['text' => "flow", 'callback_data' => "NetFreedomVPN"]] : []),
            [['text' => $wizwizplanaccnumber, 'callback_data' => "NetFreedomVPN"], ['text' => "🎗 تعداد اکانت های فروخته شده", 'callback_data' => "NetFreedomVPN"]],
            ($pd['type'] == 'agent_quota' ? [['text' => ($acount == 0 ? "نامحدود" : "$acount"), 'callback_data' => "editAgentPlanAccounts$id"], ['text' => "👥 تعداد اکانت مجاز", 'callback_data' => "NetFreedomVPN"]] : []),
            ($pd['inbound_id'] != 0 && $pd['type'] != 'agent_quota' ? [['text' => ($pd['limitip'] == 0 ? "نامحدود" : $pd['limitip']), 'callback_data' => "wizwizplanslimit$id"], ['text' => "🚪 محدودیت کاربر (IP)", 'callback_data' => "NetFreedomVPN"]] : []),
            ($pd['inbound_id'] != 0 && $pd['type'] != 'agent_quota' ? [['text' => $pd['inbound_id'], 'callback_data' => "wizwizplansinobundid$id"], ['text' => "🚪 سطر کانفیگ", 'callback_data' => "NetFreedomVPN"]] : []),
            [['text' => "✏️ ویرایش توضیحات", 'callback_data' => "wizwizplaneditdes$id"]],
            [['text' => number_format($price) . " تومان", 'callback_data' => "wizwizplanrial$id"], ['text' => "💰 قیمت پلن", 'callback_data' => "NetFreedomVPN"]],
            // افزودن دکمه ویرایش حجم پلن
            [['text' => ($pd['volume'] ?? "0") . " GB", 'callback_data' => "editAgentPlanVolume$id"], ['text' => "📦 حجم پلن", 'callback_data' => "NetFreedomVPN"]],
            [['text' => "♻️ دریافت لیست اکانت ها", 'callback_data' => "wizwizplanacclist$id"]],
            ($server_info['type'] == "marzban" ? [['text' => "انتخاب Host", 'callback_data' => "marzbanHostSettings" . $id]] : []),
            [['text' => "✂️ حذف", 'callback_data' => "wizwizplandelete$id"]],
            [['text' => $buttonValues['back_button'], 'callback_data' => "plansList$srvid"]]
        ];
        return json_encode(['inline_keyboard' => $keyboard]);
    }
}

// --- Function getUserOrderDetailKeys ---
function getUserOrderDetailKeys($id, $offset = 0)
{
    global $connection, $botState, $mainValues, $buttonValues, $botUrl;
    $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `id`=?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $order_res = $stmt->get_result();
    $stmt->close();

    if ($order_res->num_rows == 0) return null;
    $order = $order_res->fetch_assoc();
    $userId = $order['userid'];
    $firstName = bot('getChat', ['chat_id' => $userId])->result->first_name ?? " ";
    $fid = $order['fileid'];
    $rahgozar = $order['rahgozar'];
    $agentBought = $order['agent_bought'];
    $isAgentBought = $agentBought == true ? "بله" : "خیر";

    $date = jdate("Y-m-d H:i", $order['date']);
    $expire_date = $order['expire_date'];
    $remark = $order['remark'];
    $uuid = $order['uuid'] ?? "0";
    
    $acc_link = json_decode($order['link'], true);
    if (!is_array($acc_link)) $acc_link = [];
    
    $token = $order['token'];
    $server_id = $order['server_id'];
    $inbound_id = $order['inbound_id'];

    $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();

    if (!$serverConfig) return null;
    $serverType = $serverConfig['type'];
    $panelUrl = rtrim($serverConfig['panel_url'] ?? '', '/');

    $found = false; $enable = true; 
    $total = 0; $up = 0; $down = 0;

    if ($serverType == "marzban") {
        $info = getMarzbanUser($server_id, $remark);
        if (isset($info->username)) {
            $found = true;
            $enable = $info->status == "active" ? true : false;
            $total = $info->data_limit ?? 0;
            $up = $info->used_traffic ?? 0;
        }
    } else {
        $response = getJson($server_id);
        if ($response && isset($response->obj)) {
            $response = $response->obj;
            if ($inbound_id == 0) {
                foreach ($response as $row) {
                    $settings = json_decode($row->settings ?? '{}');
                    if (isset($settings->clients) && is_array($settings->clients)) {
                        $client = $settings->clients[0];
                        $clientId = $client->id ?? ($client->password ?? '');
                        $cleanEmail = str_replace('@tg.com', '', $client->email ?? '');
                        $cleanUuid = str_replace('@tg.com', '', $uuid);
                        $cleanRemark = str_replace('@tg.com', '', $remark);
                        if ($clientId == $uuid || $cleanEmail == $cleanUuid || $cleanEmail == $cleanRemark) {
                            $found = true;
                            $total = $row->total ?? 0;
                            $up = $row->up ?? 0;
                            $down = $row->down ?? 0;
                            $enable = $row->enable ?? true;
                            break;
                        }
                    }
                }
            } else {
                foreach ($response as $row) {
                    if ($row->id == $inbound_id) {
                        $clientsStates = $row->clientStats ?? [];
                        $settings = json_decode($row->settings ?? '{}');
                        if (isset($settings->clients) && is_array($settings->clients)) {
                            foreach ($settings->clients as $client) {
                                $clientId = $client->id ?? ($client->password ?? '');
                                $cleanEmail = str_replace('@tg.com', '', $client->email ?? '');
                                $cleanUuid = str_replace('@tg.com', '', $uuid);
                                $cleanRemark = str_replace('@tg.com', '', $remark);
                                if ($clientId == $uuid || $cleanEmail == $cleanUuid || $cleanEmail == $cleanRemark) {
                                    $found = true;
                                    $email = $client->email ?? '';
                                    $emails = array_column($clientsStates, 'email');
                                    $emailKey = array_search($email, $emails);
                                    if ($emailKey !== false && isset($clientsStates[$emailKey])) {
                                        $total = $client->totalGB ?? 0;
                                        $up = $clientsStates[$emailKey]->up ?? 0;
                                        $down = $clientsStates[$emailKey]->down ?? 0;
                                        $enable = $clientsStates[$emailKey]->enable ?? true;
                                        if (isset($client->enable) && !$client->enable) $enable = false;
                                    }
                                    break;
                                }
                            }
                        }
                        break;
                    }
                }
            }
        }
    }

    $totalUsedGb = round(((float)$up + (float)$down) / 1073741824, 2);
    $totalTxt = ((float)$total == 0) ? "نامحدود" : round((float)$total / 1073741824, 2) . " GB";

    $daysLeft = round(((float)$expire_date - time()) / 86400, 1);
    if ($daysLeft < 0) $daysLeft = 0;
    $daysTxt = ($expire_date == 0) ? "نامحدود" : $daysLeft . " روز";

    $isExpired = ($expire_date != 0 && $expire_date < time());
    $isTrafficFinished = ((float)$total > 0 && ((float)$up + (float)$down) >= (float)$total);
    $stateIcon = ($enable && !$isExpired && !$isTrafficFinished) ? "فعال 🟢" : "غیرفعال/پایان 🔴";

    $configLinesTxt = "";
    $configLinkState = $botState['configLinkState'] ?? 'off';
    $limit = 5; $count = 0;
    foreach ($acc_link as $singleLink) {
        $count++;
        if ($count <= $offset) continue;
        if (is_array($singleLink)) {
            foreach ($singleLink as $sl) {
                if (is_string($sl)) {
                    $safeLink = htmlspecialchars($sl, ENT_QUOTES, 'UTF-8');
                    $configLinesTxt .= "💝 <b>config $count :</b> <code>{$safeLink}</code>\n\n";
                }
            }
        } elseif (is_string($singleLink)) {
            $safeLink = htmlspecialchars($singleLink, ENT_QUOTES, 'UTF-8');
            $configLinesTxt .= "💝 <b>config $count :</b> <code>{$safeLink}</code>\n\n";
        }
        if ($count >= $offset + $limit) break;
    }

    $parsedPanelUrl = parse_url($panelUrl);
    $panelHost = $parsedPanelUrl['host'] ?? '';
    $panelScheme = $parsedPanelUrl['scheme'] ?? 'https';
    $directSubLink = "{$panelScheme}://{$panelHost}:2096/sub/{$uuid}";
    
    $subLinkState = $botState['subLinkState'] ?? 'off';
    if ($serverType == "marzban") {
        $directSubLink = $panelUrl . "/sub/" . $token;
    }

    $msg = "👨‍💻 <b>اطلاعات کانفیگ کاربر (پنل مدیریت)</b>\n\n" .
           "👤 نام کاربر: <code>{$firstName}</code>\n" .
           "🆔 آیدی عددی: <code>{$userId}</code>\n" .
           "👥 خرید نماینده: <b>{$isAgentBought}</b>\n" .
           "---------------------------------------\n" .
           "🔮 نام سرویس: <code>{$remark}</code>\n" .
           "⚡️ وضعیت اشتراک: <b>{$stateIcon}</b>\n" .
           "🔋 حجم مصرفی: <code>{$totalUsedGb} GB از {$totalTxt}</code>\n" .
           "⏰ زمان باقی‌مانده: <code>{$daysTxt}</code>\n\n" .
           "---------------------------------------\n\n" .
           $configLinesTxt .
           "🔋 <b>Volume web :</b> {$botUrl}search.php?id={$uuid}\n\n" .
           ($subLinkState == "on" ? "🌐 <b>subscription :</b> <code>{$directSubLink}</code>" : "");

    $keyboard = [];
    $configKeys = [];

    if (count($acc_link) > $limit) {
        if ($offset == 0) {
            $configKeys = [['text' => "«", 'callback_data' => "userOrderDetails{$id}_" . ($offset + $limit)]];
        } elseif (count($acc_link) >= $offset + $limit) {
            $configKeys = [
                ['text' => "«", 'callback_data' => "userOrderDetails{$id}_" . ($offset + $limit)],
                ['text' => "»", 'callback_data' => "userOrderDetails{$id}_" . ($offset - $limit)]
            ];
        } elseif ($offset != 0) {
            $configKeys = [['text' => "»", 'callback_data' => "userOrderDetails{$id}_" . ($offset - $limit)]];
        }
    }
    if (!empty($configKeys)) $keyboard[] = $configKeys;

    // دکمه‌های مدیریتی (بدون پروتکل‌های اضافه)
    $keyboard[] = [
        ['text' => ($enable == true ? $buttonValues['disable_config'] : $buttonValues['enable_config']), 'callback_data' => "changeUserConfigState" . $order['id']],
        ['text' => $buttonValues['delete_config'], 'callback_data' => "delUserConfig" . $order['id']],
    ];
    $keyboard[] = [['text' => $buttonValues['back_button'], 'callback_data' => "managePanel"]];

    return [
        "keyboard" => json_encode(['inline_keyboard' => $keyboard]),
        "msg" => $msg
    ];
}

// --- Function getOrderDetailKeys ---
function getOrderDetailKeys($from_id, $id, $offset = 0)
{
    global $connection, $botState, $mainValues, $buttonValues, $botUrl;
    $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `userid`=? AND `id`=?");
    $stmt->bind_param("ii", $from_id, $id);
    $stmt->execute();
    $order_res = $stmt->get_result();
    $stmt->close();

    if ($order_res->num_rows == 0) return null;
    $order = $order_res->fetch_assoc();
    $fid = $order['fileid'];
    $rahgozar = $order['rahgozar'];
    $agentBought = $order['agent_bought'];

    $date = jdate("Y-m-d H:i", $order['date']);
    $expire_date = $order['expire_date'];
    $remark = $order['remark'];
    $uuid = $order['uuid'] ?? "0";
    
    $acc_link = json_decode($order['link'], true);
    if (!is_array($acc_link)) $acc_link = [];

    $token = $order['token'];
    $server_id = $order['server_id'];
    $inbound_id = $order['inbound_id'];
    $price = $order['amount'];

    $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();

    if (!$serverConfig) return null;

    $serverType = $serverConfig['type'];
    $panel_url = rtrim($serverConfig['panel_url'] ?? '', '/');

    $found = false;
    $enable = true; 
    $total = 0; $up = 0; $down = 0;

    if ($serverType == "marzban") {
        $info = getMarzbanUser($server_id, $remark);
        if (isset($info->username)) {
            $found = true;
            $enable = $info->status == "active" ? true : false;
            $total = $info->data_limit ?? 0;
            $up = $info->used_traffic ?? 0;

            if (isset($info->expire) && $info->expire > 0) {
                $expire_date = $info->expire;
                $connection->query("UPDATE `orders_list` SET `expire_date` = $expire_date WHERE `id` = $id");
            } else {
                $expire_date = 0;
                $connection->query("UPDATE `orders_list` SET `expire_date` = 0 WHERE `id` = $id");
            }
        }
    } else {
        // 1. Try `/panel/api/clients/list` first
        include_once __DIR__ . '/config_xui_api.php';
        $clientsListRes = callXuiApi($serverConfig, '/panel/api/clients/list');
        if ($clientsListRes && isset($clientsListRes->success) && $clientsListRes->success && is_array($clientsListRes->obj)) {
            foreach ($clientsListRes->obj as $c) {
                $clientId = $c->uuid ?? ($c->id ?? ($c->password ?? ''));
                $clientEmail = $c->email ?? '';
                $clientSubId = $c->subId ?? '';
                
                $cleanEmail = str_replace('@tg.com', '', $clientEmail);
                $cleanUuid = str_replace('@tg.com', '', $uuid);
                $cleanRemark = str_replace('@tg.com', '', $remark);
                
                if ($clientId == $uuid || $clientEmail == $uuid || $clientSubId == $uuid ||
                    $cleanEmail == $cleanUuid || $cleanEmail == $cleanRemark) {
                    
                    $found = true;
                    $traffic = $c->traffic ?? null;
                    
                    $up = $traffic ? ($traffic->up ?? 0) : ($c->up ?? 0);
                    $down = $traffic ? ($traffic->down ?? 0) : ($c->down ?? 0);
                    $total = $c->totalGB ?? ($traffic->total ?? 0);
                    $enable = ($c->enable ?? ($traffic->enable ?? true));
                    
                    $expiryTimeMs = $c->expiryTime ?? ($traffic->expiryTime ?? 0);
                    if ($expiryTimeMs > 0) {
                        $expire_date = (int)substr($expiryTimeMs, 0, -3);
                        $connection->query("UPDATE `orders_list` SET `expire_date` = $expire_date WHERE `id` = $id");
                    } else {
                        $expire_date = 0;
                        $connection->query("UPDATE `orders_list` SET `expire_date` = 0 WHERE `id` = $id");
                    }
                    break;
                }
            }
        }
        
        // 2. Fallback to `/panel/api/inbounds/list`
        if (!$found) {
            $response = getJson($server_id);
            if ($response && isset($response->obj)) {
                $response = $response->obj;
                if ($inbound_id == 0) {
                    foreach ($response as $row) {
                        $settings = json_decode($row->settings ?? '{}');
                        if (isset($settings->clients) && is_array($settings->clients)) {
                            $client = $settings->clients[0];
                            $clientId = $client->id ?? ($client->password ?? '');
                            $cleanEmail = str_replace('@tg.com', '', $client->email ?? '');
                            $cleanUuid = str_replace('@tg.com', '', $uuid);
                            $cleanRemark = str_replace('@tg.com', '', $remark);
                            if ($clientId == $uuid || $cleanEmail == $cleanUuid || $cleanEmail == $cleanRemark) {
                                $found = true;
                                $total = $row->total ?? 0;
                                $up = $row->up ?? 0;
                                $down = $row->down ?? 0;
                                $enable = $row->enable ?? true;

                                $expiryTimeMs = $client->expiryTime ?? ($row->expiryTime ?? 0);
                                if ($expiryTimeMs > 0) {
                                    $expire_date = (int)substr($expiryTimeMs, 0, -3);
                                    $connection->query("UPDATE `orders_list` SET `expire_date` = $expire_date WHERE `id` = $id");
                                } else {
                                    $expire_date = 0;
                                    $connection->query("UPDATE `orders_list` SET `expire_date` = 0 WHERE `id` = $id");
                                }
                                break;
                            }
                        }
                    }
                } else {
                    foreach ($response as $row) {
                        if ($row->id == $inbound_id) {
                            $clientsStates = $row->clientStats ?? [];
                            $settings = json_decode($row->settings ?? '{}');
                            if (isset($settings->clients) && is_array($settings->clients)) {
                                foreach ($settings->clients as $client) {
                                    $clientId = $client->id ?? ($client->password ?? '');
                                    $cleanEmail = str_replace('@tg.com', '', $client->email ?? '');
                                    $cleanUuid = str_replace('@tg.com', '', $uuid);
                                    $cleanRemark = str_replace('@tg.com', '', $remark);
                                    if ($clientId == $uuid || $cleanEmail == $cleanUuid || $cleanEmail == $cleanRemark) {
                                        $found = true;
                                        $email = $client->email ?? '';
                                        $emails = array_column($clientsStates, 'email');
                                        $emailKey = array_search($email, $emails);

                                        if ($emailKey !== false && isset($clientsStates[$emailKey])) {
                                            $total = $client->totalGB ?? 0;
                                            if ($total == 0 && isset($clientsStates[$emailKey]->total)) {
                                                $total = $clientsStates[$emailKey]->total;
                                            }
                                            $up = $clientsStates[$emailKey]->up ?? 0;
                                            $down = $clientsStates[$emailKey]->down ?? 0;
                                            $enable = $clientsStates[$emailKey]->enable ?? true;
                                            if (isset($client->enable) && !$client->enable) $enable = false;
                                            
                                            $expiryTimeMs = $client->expiryTime ?? ($clientsStates[$emailKey]->expiryTime ?? 0);
                                            if ($expiryTimeMs > 0) {
                                                $expire_date = (int)substr($expiryTimeMs, 0, -3);
                                                $connection->query("UPDATE `orders_list` SET `expire_date` = $expire_date WHERE `id` = $id");
                                            } else {
                                                $expire_date = 0;
                                                $connection->query("UPDATE `orders_list` SET `expire_date` = 0 WHERE `id` = $id");
                                            }
                                        }
                                        break;
                                    }
                                }
                            }
                            break;
                        }
                    }
                }
            }
        }
    }

    $totalUsedGb = round(((float)$up + (float)$down) / 1073741824, 2);
    $totalTxt = ((float)$total == 0) ? "نامحدود" : round((float)$total / 1073741824, 2) . " GB";

    $daysLeft = (int)round(((float)$expire_date - time()) / 86400);
    if ($daysLeft < 0) $daysLeft = 0;
    $daysTxt = ($expire_date == 0) ? "نامحدود" : $daysLeft . " روز";

    $isExpired = ($expire_date != 0 && $expire_date < time());
    $isTrafficFinished = ((float)$total > 0 && ((float)$up + (float)$down) >= (float)$total);
    $stateIcon = ($enable && !$isExpired && !$isTrafficFinished) ? "فعال 🟢" : "غیرفعال/پایان 🔴";

    // ✨ ضد کرش HTML تلگرام
    $configLinesTxt = "";
    $configLinkState = $botState['configLinkState'] ?? 'off';
    $limit = 5; $count = 0;
    
    foreach ($acc_link as $singleLink) {
        $count++;
        if ($count <= $offset) continue;
        if (is_array($singleLink)) {
            foreach ($singleLink as $sl) {
                if (is_string($sl)) {
                    $safeLink = htmlspecialchars($sl, ENT_QUOTES, 'UTF-8');
                    $configLinesTxt .= "💝 <b>config $count :</b> <code>{$safeLink}</code>\n\n";
                }
            }
        } elseif (is_string($singleLink)) {
            $safeLink = htmlspecialchars($singleLink, ENT_QUOTES, 'UTF-8');
            $configLinesTxt .= "💝 <b>config $count :</b> <code>{$safeLink}</code>\n\n";
        }
        if ($count >= $offset + $limit) break;
    }

    $parsedPanelUrl = parse_url($panel_url);
    $panelHost = $parsedPanelUrl['host'] ?? '';
    $panelScheme = $parsedPanelUrl['scheme'] ?? 'https';
    $directSubLink = "{$panelScheme}://{$panelHost}:2096/sub/{$uuid}";
    
    $subLinkState = $botState['subLinkState'] ?? 'off';
    if ($serverType == "marzban") {
        $directSubLink = $panel_url . "/sub/" . $token;
    }

    $msg = "😍 <b>مشخصات و اطلاعات مدیریت سرویس شما</b>\n\n" .
           "🔮 نام سرویس: <code>{$remark}</code>\n" .
           "⚡️ وضعیت اشتراک: <b>{$stateIcon}</b>\n" .
           "🔋 حجم مصرفی: <code>{$totalUsedGb} GB از {$totalTxt}</code>\n" .
           "⏰ زمان باقی‌مانده: <code>{$daysTxt}</code>\n\n" .
           "---------------------------------------\n\n" .
           $configLinesTxt .
           "🔋 <b>Volume web :</b> {$botUrl}search.php?id={$uuid}\n\n" .
           ($subLinkState == "on" ? "🌐 <b>subscription :</b> <code>{$directSubLink}</code>" : "");

    $keyboard = [];
    $configKeys = [];

    if (count($acc_link) > $limit) {
        if ($offset == 0) {
            $configKeys = [['text' => "«", 'callback_data' => "orderDetails{$id}_" . ($offset + $limit)]];
        } elseif (count($acc_link) >= $offset + $limit) {
            $configKeys = [
                ['text' => "«", 'callback_data' => "orderDetails{$id}_" . ($offset + $limit)],
                ['text' => "»", 'callback_data' => "orderDetails{$id}_" . ($offset - $limit)]
            ];
        } elseif ($offset != 0) {
            $configKeys = [['text' => "»", 'callback_data' => "orderDetails{$id}_" . ($offset - $limit)]];
        }
    }
    if (!empty($configKeys)) $keyboard[] = $configKeys;

    $isGift = (strpos($remark, 'Gift') !== false);
    $renewAccountState = $botState['renewAccountState'] ?? 'off';
    $switchLocationState = $botState['switchLocationState'] ?? 'off';
    if ($found) {
        $temp = [];
        if (!$isGift) {
            if ($renewAccountState == "on") $temp[] = getBtn('renew_config', "renewAccount$id");
            if ($switchLocationState == "on" && $rahgozar != true) $temp[] = getBtn('change_config_location', "switchLocation{$id}_{$server_id}_-1_" . $expire_date);
        }
        if (!empty($temp)) $keyboard[] = $temp;

        $extrakey = [];
        $increaseVolumeState = $botState['increaseVolumeState'] ?? 'off';
        $increaseTimeState = $botState['increaseTimeState'] ?? 'off';

        if (!$isGift && $increaseVolumeState == "on")
            $extrakey[] = getBtn('increase_config_volume', "increaseAVolume{$id}");
        if (!$isGift && $increaseTimeState == "on")
            $extrakey[] = getBtn('increase_config_days', "increaseADay{$id}");
        if(!empty($extrakey)) $keyboard[] = $extrakey;

        $renewConfigLinkState = $botState['renewConfigLinkState'] ?? 'off';
        $updateConfigLinkState = $botState['updateConfigLinkState'] ?? 'off';

        if ($renewConfigLinkState == "on" && $updateConfigLinkState == "on")
            $keyboard[] = [getBtn('renew_connection_link', 'changAccountConnectionLink' . $id), getBtn('update_config_connection', 'updateConfigConnectionLink' . $id)];
        elseif ($renewConfigLinkState == "on")
            $keyboard[] = [getBtn('renew_connection_link', 'changAccountConnectionLink' . $id)];
        elseif ($updateConfigLinkState == "on")
            $keyboard[] = [getBtn('update_config_connection', 'updateConfigConnectionLink' . $id)];

        $temp = [];
        $qrConfigState = $botState['qrConfigState'] ?? 'off';
        $qrSubState = $botState['qrSubState'] ?? 'off';

        if ($qrConfigState == "on") $temp[] = getBtn('qr_config', "showQrConfig" . $id);
        if ($qrSubState == "on") $temp[] = getBtn('qr_sub', "showQrSub" . $id);
        if(!empty($temp)) $keyboard[] = $temp;
    } else {
        $temp = [];
        if (!$isGift) {
            if ($renewAccountState == "on") $temp[] = getBtn('renew_config', "renewAccount$id");
            if ($switchLocationState == "on" && $rahgozar != true) $temp[] = getBtn('change_config_location', "switchLocation{$id}_{$server_id}_-1_" . $expire_date);
        }
        if (!empty($temp)) $keyboard[] = $temp;
    }
    
    $keyboard[] = [['text' => 'دریافت فایل کانفیگ‌ها 📄', 'callback_data' => "getNpvtFile" . $id]];
    $keyboard[] = [getBtn('delete_config', "deleteMyConfig" . $id)];
    $keyboard[] = [getBtn('back_button', ($agentBought == true ? "agentConfigsList" : "mySubscriptions"))];

    return [
        "keyboard" => json_encode(['inline_keyboard' => $keyboard]),
        "msg" => $msg
    ];
}
