<?php
include_once dirname(__DIR__) . '/settings/config_xui_api.php';
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;


// --- Start of Range 815 to 845 ---
if (($data == "agentOneBuy" || $data == 'buySubscription' || $data == "agentMuchBuy") && ($botState['sellState'] == "on" || ($from_id == $admin || $userInfo['isAdmin'] == true))) {
    if ($botState['cartToCartState'] == "off" && $botState['walletState'] == "off") {
        alert($mainValues['selling_is_off']);
        exit();
    }
    if ($data == "buySubscription")
        $buyType = "none";
    elseif ($data == "agentOneBuy")
        $buyType = "one";
    else
        $buyType = "much";

    $stmt = $connection->prepare("SELECT * FROM `server_info` WHERE `active`=1 and `state` = 1 and `ucount` > 0 ORDER BY `id` ASC");
    $stmt->execute();
    $respd = $stmt->get_result();
    $stmt->close();
    if ($respd->num_rows == 0) {
        alert($mainValues['no_server_available']);
        exit;
    }
    $keyboard = [];
    while ($cat = $respd->fetch_assoc()) {
        $id = $cat['id'];
        $name = $cat['title'];
        $flag = $cat['flag'];
        $keyboard[] = ['text' => "$flag $name", 'callback_data' => "selectServer{$id}_{$buyType}"];
    }
    $keyboard = array_chunk($keyboard, 1);
    $keyboard[] = [getMiniAppBtn(" خرید کانفیگ جدید در مینی‌اپ 📱", "buy-plans")];
    $keyboard[] = [getBtn('back_to_main', 'mainMenu')];
    $msgText = "📍 <b>خرید کانفیگ جدید ➔ ➊ انتخاب سرور (لوکیشن)</b>\n" .
               "-----------------------------------------\n\n" .
               $mainValues['buy_sub_select_location'];
    editText($message_id, $msgText, json_encode(['inline_keyboard' => $keyboard]), "HTML");
}

// --- Start of Range 1312 to 1661 ---
if (preg_match('/selectServer(?<serverId>\d+)_(?<buyType>\w+)/', (string)$data, $match) && ($botState['sellState'] == "on" || ($from_id == $admin || $userInfo['isAdmin'] == true))) {
    $sid = $match['serverId'];

    $stmt = $connection->prepare("SELECT * FROM `server_categories` WHERE `parent`=0 order by `id` asc");
    $stmt->execute();
    $respd = $stmt->get_result();
    $stmt->close();
    if ($respd->num_rows == 0) {
        alert($mainValues['category_not_avilable']);
    } else {

        $keyboard = [];
        while ($file = $respd->fetch_assoc()) {
            $id = $file['id'];
            $name = $file['title'];
            if (($userInfo['is_agent'] ?? 0) == 0 && (mb_strpos($name, 'نمایند') !== false || stripos($name, 'agent') !== false)) {
                continue;
            }
            $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `server_id`=? and `catid`=? and `active`=1 and `type` != 'agent_quota'");
            $stmt->bind_param("ii", $sid, $id);
            $stmt->execute();
            $rowcount = $stmt->get_result()->num_rows;
            $stmt->close();
            if ($rowcount > 0)
                $keyboard[] = ['text' => "$name", 'callback_data' => "selectCategory{$id}_{$sid}_{$match['buyType']}"];
        }
        if (empty($keyboard) && !($match['buyType'] == "much" && $userInfo['is_agent'] == 1)) {
            alert($mainValues['category_not_avilable']);
            exit;
        }
        alert($mainValues['receive_categories']);

        $keyboard = array_chunk($keyboard, 1);
        if ($match['buyType'] == "much" && $userInfo['is_agent'] == 1) {
            array_unshift($keyboard, [['text' => "⚙️ ساخت کانفیگ سفارشی", 'callback_data' => "agentCustomConfigPanel_{$sid}", 'style' => 'primary']]);
        }
        $keyboard[] = [
            getBtn('back_button', ($match['buyType'] == "one" ? "agentOneBuy" : ($match['buyType'] == "much" ? "agentMuchBuy" : "buySubscription"))),
            getBtn('back_to_main', 'mainMenu')
        ];
        $msgText = "📍 <b>خرید کانفیگ جدید ➔ ➊ انتخاب سرور ➔ ➋ انتخاب دسته‌بندی</b>\n" .
                   "---------------------------------------------------\n\n" .
                   $mainValues['buy_sub_select_category'];
        editText($message_id, $msgText, json_encode(['inline_keyboard' => $keyboard]), "HTML");
    }
}
if (preg_match('/selectCategory(?<categoryId>\d+)_(?<serverId>\d+)_(?<buyType>\w+)/', (string)$data, $match) && ($botState['sellState'] == "on" || $from_id == $admin || $userInfo['isAdmin'] == true)) {
    $call_id = $match['categoryId'];
    $sid = $match['serverId'];

    $catStmt = $connection->prepare("SELECT `title` FROM `server_categories` WHERE `id` = ?");
    $catStmt->bind_param("i", $call_id);
    $catStmt->execute();
    $catRes = $catStmt->get_result()->fetch_assoc();
    $catStmt->close();
    if ($catRes) {
        $catName = $catRes['title'];
        if ((($userInfo['is_agent'] ?? 0) == 0) && (mb_strpos($catName, 'نمایند') !== false || stripos($catName, 'agent') !== false)) {
            alert("⚠️ این دسته‌بندی مخصوص نمایندگان است.");
            exit();
        }
    }

    $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `server_id`=? and `price` != 0 and `catid`=? and `active`=1 and `type` != 'agent_quota' order by `id` asc");
    $stmt->bind_param("ii", $sid, $call_id);
    $stmt->execute();
    $respd = $stmt->get_result();
    $stmt->close();
    if ($respd->num_rows == 0) {
        alert($mainValues['no_plan_available']);
    } else {
        alert($mainValues['receive_plans']);
        $keyboard = [];
        while ($file = $respd->fetch_assoc()) {
            $id = $file['id'];
            $name = $file['title'];
            $price = $file['price'];
            if ($userInfo['is_agent'] == true && ($match['buyType'] == "one" || $match['buyType'] == "much")) {
                $discounts = json_decode($userInfo['discount_percent'], true);
                if ($botState['agencyPlanDiscount'] == "on")
                    $discount = $discounts['plans'][$id] ?? $discounts['normal'];
                else
                    $discount = $discounts['servers'][$sid] ?? $discounts['normal'];

                $price -= floor($price * $discount / 100);
            }
            $price = ($price == 0) ? 'رایگان' : number_format($price) . ' تومان ';
            $keyboard[] = ['text' => "$name - $price", 'callback_data' => "selectPlan{$id}_{$call_id}_{$match['buyType']}"];
        }
        $keyboardChunks = array_chunk($keyboard, 1);
        if ($botState['plandelkhahState'] == "on" && $match['buyType'] != "much") {
            $keyboardChunks[] = [['text' => $mainValues['buy_custom_plan'], 'callback_data' => "selectCustomPlan{$call_id}_{$sid}_{$match['buyType']}"]];
        }
        $keyboardChunks[] = [
            getBtn('back_button', "selectServer{$sid}_{$match['buyType']}"),
            getBtn('back_to_main', 'mainMenu')
        ];
        $msgText = "📍 <b>خرید کانفیگ جدید ➔ ➊ انتخاب سرور ➔ ➋ انتخاب دسته‌بندی ➔ ➌ انتخاب پلن</b>\n" .
                   "----------------------------------------------------------------------\n\n" .
                   $mainValues['buy_sub_select_plan'];
        editText($message_id, $msgText, json_encode(['inline_keyboard' => $keyboardChunks]), "HTML");
    }
}
if (preg_match('/selectCustomPlan(?<categoryId>\d+)_(?<serverId>\d+)_(?<buyType>\w+)/', (string)$data, $match) && ($botState['sellState'] == "on" || $from_id == $admin || $userInfo['isAdmin'] == true)) {
    $call_id = $match['categoryId'];
    $sid = $match['serverId'];
    $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `server_id`=? and `catid`=? and `active`=1 order by `id` asc");
    $stmt->bind_param("ii", $sid, $call_id);
    $stmt->execute();
    $respd = $stmt->get_result();
    $stmt->close();
    alert($mainValues['receive_plans']);
    $keyboard = [];
    while ($file = $respd->fetch_assoc()) {
        $id = $file['id'];
        $name = preg_replace("/پلن\s(\d+)\sگیگ\s/", "", $file['title']);
        $keyboard[] = ['text' => "$name", 'callback_data' => "selectCustomePlan{$id}_{$call_id}_{$match['buyType']}"];
    }
    $keyboardChunks = array_chunk($keyboard, 1);
    $keyboardChunks[] = [
        getBtn('back_button', "selectServer{$sid}_{$match['buyType']}"),
        getBtn('back_to_main', 'mainMenu')
    ];
    $msgText = "📍 <b>خرید کانفیگ جدید ➔ ➊ انتخاب سرور ➔ ➋ انتخاب دسته‌بندی ➔ ➌ انتخاب پلن دلخواه</b>\n" .
               "-----------------------------------------------------------------------------\n\n" .
               $mainValues['select_one_plan_to_edit'];
    editText($message_id, $msgText, json_encode(['inline_keyboard' => $keyboardChunks]), "HTML");
}
if (preg_match('/selectCustomePlan(?<planId>\d+)_(?<categoryId>\d+)_(?<buyType>\w+)/', (string)$data, $match) && ($botState['sellState'] == "on" || $from_id == $admin)) {
    $price = $botState['gbPrice'];
    if ($match['buyType'] == "one" && $userInfo['is_agent'] == true) {
        $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `id` = ?");
        $stmt->bind_param("i", $match['planId']);
        $stmt->execute();
        $serverId = $stmt->get_result()->fetch_assoc()['server_id'];
        $stmt->close();

        $discounts = json_decode($userInfo['discount_percent'], true);
        if ($botState['agencyPlanDiscount'] == "on")
            $discount = $discounts['plans'][$match['planId']] ?? $discounts['normal'];
        else
            $discount = $discounts['servers'][$serverId] ?? $discounts['normal'];
        $price -= floor($price * $discount / 100);
    }

    $prompt_id = $message_id;
    $keyboard = json_encode(['inline_keyboard' => [[['text' => "❌ انصراف", 'callback_data' => "mainMenu"]]]]);
    editText($message_id, str_replace("VOLUME-PRICE", $price, $mainValues['customer_custome_plan_volume']), $keyboard, "HTML");

    setUser("selectCustomPlanGB" . json_encode([
        'planId' => $match['planId'],
        'categoryId' => $match['categoryId'],
        'buyType' => $match['buyType'],
        'prompt_id' => $prompt_id
    ], JSON_UNESCAPED_UNICODE));
}

if (preg_match('/^selectCustomPlanGB(?<json>.*)/', (string)$userInfo['step'], $match) && ($botState['sellState'] == "on" || $from_id == $admin) && $text != $buttonValues['cancel']) {
    $d = json_decode($match['json'], true);
    bot('deleteMessage', ['chat_id' => $from_id, 'message_id' => $message_id]);

    $price_gb = $botState['gbPrice'];
    if ($d['buyType'] == "one" && $userInfo['is_agent'] == true) {
        $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `id` = ?");
        $stmt->bind_param("i", $d['planId']);
        $stmt->execute();
        $serverId = $stmt->get_result()->fetch_assoc()['server_id'];
        $stmt->close();

        $discounts = json_decode($userInfo['discount_percent'], true);
        if ($botState['agencyPlanDiscount'] == "on")
            $discount = $discounts['plans'][$d['planId']] ?? $discounts['normal'];
        else
            $discount = $discounts['servers'][$serverId] ?? $discounts['normal'];
        $price_gb -= floor($price_gb * $discount / 100);
    }

    if (!is_numeric($text)) {
        $keyboard = json_encode(['inline_keyboard' => [[['text' => "❌ انصراف", 'callback_data' => "mainMenu"]]]]);
        editText($d['prompt_id'], "😡|لطفا فقط عدد ارسال کن\n\n" . str_replace("VOLUME-PRICE", $price_gb, $mainValues['customer_custome_plan_volume']), $keyboard, "HTML");
        exit();
    } elseif ($text < 1) {
        $keyboard = json_encode(['inline_keyboard' => [[['text' => "❌ انصراف", 'callback_data' => "mainMenu"]]]]);
        editText($d['prompt_id'], "لطفا عددی بزرگتر از 0 وارد کن\n\n" . str_replace("VOLUME-PRICE", $price_gb, $mainValues['customer_custome_plan_volume']), $keyboard, "HTML");
        exit();
    } elseif (strstr($text, ".")) {
        $keyboard = json_encode(['inline_keyboard' => [[['text' => "❌ انصراف", 'callback_data' => "mainMenu"]]]]);
        editText($d['prompt_id'], "عدد وارد شده نمیتواند اعشاری باشد!\n\n" . str_replace("VOLUME-PRICE", $price_gb, $mainValues['customer_custome_plan_volume']), $keyboard, "HTML");
        exit();
    } elseif (substr($text, 0, 1) == '0') {
        $keyboard = json_encode(['inline_keyboard' => [[['text' => "❌ انصراف", 'callback_data' => "mainMenu"]]]]);
        editText($d['prompt_id'], "❌عدد وارد شده نمیتواند با 0 شروع شود!\n\n" . str_replace("VOLUME-PRICE", $price_gb, $mainValues['customer_custome_plan_volume']), $keyboard, "HTML");
        exit();
    }

    $d['volume'] = intval($text);

    $price_day = $botState['dayPrice'];
    if ($d['buyType'] == "one" && $userInfo['is_agent'] == true) {
        $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `id` = ?");
        $stmt->bind_param("i", $d['planId']);
        $stmt->execute();
        $serverId = $stmt->get_result()->fetch_assoc()['server_id'];
        $stmt->close();

        $discounts = json_decode($userInfo['discount_percent'], true);
        if ($botState['agencyPlanDiscount'] == "on")
            $discount = $discounts['plans'][$d['planId']] ?? $discounts['normal'];
        else
            $discount = $discounts['servers'][$serverId] ?? $discounts['normal'];
        $price_day -= floor($price_day * $discount / 100);
    }

    $keyboard = json_encode(['inline_keyboard' => [[['text' => "❌ انصراف", 'callback_data' => "mainMenu"]]]]);
    editText($d['prompt_id'], str_replace("DAY-PRICE", $price_day, $mainValues['customer_custome_plan_day']), $keyboard, "HTML");

    setUser("selectCustomPlanDay" . json_encode($d, JSON_UNESCAPED_UNICODE));
}

if (preg_match('/^selectCustomPlanDay(?<json>.*)/', (string)$userInfo['step'], $match) && ($botState['sellState'] == "on" || $from_id == $admin) && $text != $buttonValues['cancel']) {
    $d = json_decode($match['json'], true);
    bot('deleteMessage', ['chat_id' => $from_id, 'message_id' => $message_id]);

    $price_day = $botState['dayPrice'];
    if ($d['buyType'] == "one" && $userInfo['is_agent'] == true) {
        $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `id` = ?");
        $stmt->bind_param("i", $d['planId']);
        $stmt->execute();
        $serverId = $stmt->get_result()->fetch_assoc()['server_id'];
        $stmt->close();

        $discounts = json_decode($userInfo['discount_percent'], true);
        if ($botState['agencyPlanDiscount'] == "on")
            $discount = $discounts['plans'][$d['planId']] ?? $discounts['normal'];
        else
            $discount = $discounts['servers'][$serverId] ?? $discounts['normal'];
        $price_day -= floor($price_day * $discount / 100);
    }

    if (!is_numeric($text)) {
        $keyboard = json_encode(['inline_keyboard' => [[['text' => "❌ انصراف", 'callback_data' => "mainMenu"]]]]);
        editText($d['prompt_id'], "😡|لطفا فقط عدد ارسال کن\n\n" . str_replace("DAY-PRICE", $price_day, $mainValues['customer_custome_plan_day']), $keyboard, "HTML");
        exit();
    } elseif ($text < 1) {
        $keyboard = json_encode(['inline_keyboard' => [[['text' => "❌ انصراف", 'callback_data' => "mainMenu"]]]]);
        editText($d['prompt_id'], "لطفا عددی بزرگتر از 0 وارد کن\n\n" . str_replace("DAY-PRICE", $price_day, $mainValues['customer_custome_plan_day']), $keyboard, "HTML");
        exit();
    } elseif (strstr($text, ".")) {
        $keyboard = json_encode(['inline_keyboard' => [[['text' => "❌ انصراف", 'callback_data' => "mainMenu"]]]]);
        editText($d['prompt_id'], "عدد وارد شده نمیتواند اعشاری باشد!\n\n" . str_replace("DAY-PRICE", $price_day, $mainValues['customer_custome_plan_day']), $keyboard, "HTML");
        exit();
    } elseif (substr($text, 0, 1) == '0') {
        $keyboard = json_encode(['inline_keyboard' => [[['text' => "❌ انصراف", 'callback_data' => "mainMenu"]]]]);
        editText($d['prompt_id'], "❌عدد وارد شده نمیتواند با 0 شروع شود!\n\n" . str_replace("DAY-PRICE", $price_day, $mainValues['customer_custome_plan_day']), $keyboard, "HTML");
        exit();
    }

    $d['days'] = intval($text);

    $keyboard = json_encode(['inline_keyboard' => [[['text' => "❌ انصراف", 'callback_data' => "mainMenu"]]]]);
    editText($d['prompt_id'], $mainValues['customer_custome_plan_name'], $keyboard, "HTML");

    setUser("enterCustomPlanName" . json_encode($d, JSON_UNESCAPED_UNICODE));
}

if ((preg_match('/^discountCustomPlanDay(\d+)/', (string)$userInfo['step'], $match) || preg_match('/^enterCustomPlanName(?<json>.*)/', (string)$userInfo['step'], $match)) && ($botState['sellState'] == "on" || $from_id == $admin) && $text != $buttonValues['cancel']) {

    if (preg_match('/^discountCustomPlanDay/', (string)$userInfo['step'])) {
        $rowId = $match[1];

        $time = time();
        $stmt = $connection->prepare("SELECT * FROM `discounts` WHERE (`expire_date` > $time OR `expire_date` = 0) AND (`expire_count` > 0 OR `expire_count` = -1) AND `hash_id` = ?");
        $stmt->bind_param("s", $text);
        $stmt->execute();
        $list = $stmt->get_result();
        $stmt->close();

        $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `id` = ?");
        $stmt->bind_param("i", $rowId);
        $stmt->execute();
        $payInfo = $stmt->get_result()->fetch_assoc();
        $hash_id = $payInfo['hash_id'];
        $price = $payInfo['price'];
        $id = $payInfo['type'];
        $volume = $payInfo['volume'];
        $days = $payInfo['day'];
        $stmt->close();

        // Find prompt_id if possible
        $d = ['prompt_id' => $message_id]; // Fallback

        if ($list->num_rows > 0) {
            $discountInfo = $list->fetch_assoc();
            $amount = $discountInfo['amount'];
            $type = $discountInfo['type'];
            $count = $discountInfo['expire_count'];
            $usedBy = !is_null($discountInfo['used_by']) ? json_decode($discountInfo['used_by'], true) : array();

            $canUse = $discountInfo['can_use'];
            $userUsedCount = array_count_values($usedBy)[$from_id] ?? 0;
            if ($canUse > $userUsedCount) {
                $usedBy[] = $from_id;
                $encodeUsedBy = json_encode($usedBy);

                if ($count != -1)
                    $query = "UPDATE `discounts` SET `expire_count` = `expire_count` - 1, `used_by` = ? WHERE `id` = ?";
                else
                    $query = "UPDATE `discounts` SET `used_by` = ? WHERE `id` = ?";

                $stmt = $connection->prepare($query);
                $stmt->bind_param("si", $encodeUsedBy, $discountInfo['id']);
                $stmt->execute();
                $stmt->close();

                if ($type == "percent") {
                    $discount = $price * $amount / 100;
                    $price -= $discount;
                    $discount = number_format($discount) . " تومان";
                } else {
                    $price -= $amount;
                    $discount = number_format($amount) . " تومان";
                }
                if ($price < 0)
                    $price = 0;

                $stmt = $connection->prepare("UPDATE `pays` SET `price` = ? WHERE `id` = ?");
                $stmt->bind_param("ii", $price, $rowId);
                $stmt->execute();
                $stmt->close();
                alert(str_replace("AMOUNT", $discount, $mainValues['valid_discount_code']), true);
                $keys = json_encode(['inline_keyboard' => [
                    [
                        ['text' => "❤️", "callback_data" => "NetFreedomVPN"]
                    ],
                ]]);
                sendMessage(
                    str_replace(['USERID', 'USERNAME', "NAME", "AMOUNT", "DISCOUNTCODE"], [$from_id, $username, $first_name, $discount, $text], $mainValues['used_discount_code']),
                    $keys,
                    null,
                    $admin
                );
            } else
                alert($mainValues['not_valid_discount_code']);
        } else
            alert($mainValues['not_valid_discount_code']);
    } else {
        $d = json_decode($match['json'], true);
        bot('deleteMessage', ['chat_id' => $from_id, 'message_id' => $message_id]);

        $id = $d['planId'];
        $call_id = $d['categoryId'];
        $volume = $d['volume'];
        $days = $d['days'];

        if ($d['buyType'] != "much") {
            if (preg_match('/^[a-z]+[0-9]+$/', (string)$text)) {
            } else {
                $keyboard = json_encode(['inline_keyboard' => [[['text' => "❌ انصراف", 'callback_data' => "mainMenu"]]]]);
                editText($d['prompt_id'], "⚠️ " . $mainValues['incorrect_config_name'] . "\n\n" . $mainValues['customer_custome_plan_name'], $keyboard, "HTML");
                exit();
            }
        }
    }

    $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 `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();
    $token = base64_encode("{$from_id}.{$id}");

    if (!preg_match('/^discountCustomPlanDay/', (string)$userInfo['step'])) {
        $discountPrice = 0;
        $gbPrice = $botState['gbPrice'];
        $dayPrice = $botState['dayPrice'];

        if ($userInfo['is_agent'] == true && $d['buyType'] == "one") {
            $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `id` = ?");
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $serverId = $stmt->get_result()->fetch_assoc()['server_id'];
            $stmt->close();

            $discounts = json_decode($userInfo['discount_percent'], true);
            if ($botState['agencyPlanDiscount'] == "on")
                $discount = $discounts['plans'][$id] ?? $discounts['normal'];
            else
                $discount = $discounts['servers'][$serverId] ?? $discounts['normal'];

            $gbPrice -= floor($gbPrice * $discount / 100);
            $dayPrice -= floor($dayPrice * $discount / 100);
        }

        $agentBought = false;
        if ($userInfo['is_agent'] == 1 && ($d['buyType'] == "one" || $d['buyType'] == "much")) {
            $agentBought = true;
        }

        $price = ($volume * $gbPrice) + ($days * $dayPrice);
        $hash_id = RandomString();
        $stmt = $connection->prepare("DELETE FROM `pays` WHERE `user_id` = ? AND `type` = 'BUY_SUB' AND `state` = 'pending'");
        $stmt->bind_param("i", $from_id);
        $stmt->execute();
        $stmt->close();

        $time = time();
        $stmt = $connection->prepare("INSERT INTO `pays` (`hash_id`, `description`, `user_id`, `type`, `plan_id`, `volume`, `day`, `price`, `request_date`, `state`, `agent_bought`)
                                    VALUES (?, ?, ?, 'BUY_SUB', ?, ?, ?, ?, ?, 'pending', ?)");
        $stmt->bind_param("ssiiiiiii", $hash_id, $text, $from_id, $id, $volume, $days, $price, $time, $agentBought);
        $stmt->execute();
        $rowId = $stmt->insert_id;
        $stmt->close();
    }

    if ($botState['cartToCartState'] == "on")
        $keyboard[] = [getBtn('cart_to_cart', "payCustomWithCartToCart$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[] = [getBtn('weswap_gateway', "payWithWeSwap" . $hash_id)];
    if ($botState['walletState'] == "on")
        $keyboard[] = [getBtn('pay_with_wallet', "payCustomWithWallet$hash_id")];
    if ($botState['tronWallet'] == "on")
        $keyboard[] = [getBtn('tron_gateway', "payWithTronWallet" . $hash_id)];

    if (!preg_match('/^discountCustomPlanDay/', (string)$userInfo['step']))
        $keyboard[] = [['text' => " 🎁 نکنه کد تخفیف داری؟ ", 'callback_data' => "haveDiscountCustom_" . $rowId]];
    $keyboard[] = [getBtn('cancel', "mainMenu")];
    $price = ($price == 0) ? 'رایگان' : number_format($price) . ' تومان ';

    editText($d['prompt_id'], str_replace(['VOLUME', 'DAYS', 'PLAN-NAME', 'PRICE', 'DESCRIPTION'], [$volume, $days, $name, $price, $desc], $mainValues['buy_subscription_detail']), json_encode(['inline_keyboard' => $keyboard]), "HTML");
    setUser();
}

// --- Start of Range 1662 to 1675 ---
if (preg_match('/^haveDiscount(.+?)_(.*)/', (string)$data, $match)) {
    delMessage();
    sendMessage($mainValues['insert_discount_code'], $cancelKey);
    if ($match[1] == "Custom")
        setUser('discountCustomPlanDay' . $match[2]);
    elseif ($match[1] == "SelectPlan")
        setUser('discountSelectPlan' . $match[2]);
    elseif ($match[1] == "Renew")
        setUser('discountRenew' . $match[2]);
}

// -------------------------------------------------------------------------
// ۱. مدیریت و نمایش موجودی پلن‌های اشتراکی و اختصاصی (v3.1.0 کلاینت‌محور)
// -------------------------------------------------------------------------

// --- Start of Range 1746 to 1813 ---
if ($data == "agencySettings" && $userInfo['is_agent'] == 1) {
    bot('editMessageText', ['chat_id' => $from_id, 'message_id' => $message_id, 'text' => $mainValues['agent_setting_message'], 'reply_markup' => getAgentKeys(), 'parse_mode' => "HTML"]);
    exit();
}

if ($data == "requestAgency") {
    if ($userInfo['is_agent'] == 2) {
        alert($mainValues['agency_request_already_sent']);
    } elseif ($userInfo['is_agent'] == 0) {
        // نمایش قوانین نمایندگی به کاربر
        $rules_text = "📜 <b>قوانین و شرایط دریافت نمایندگی:</b>\n\n" .
                      "۱. برای دریافت نمایندگی باید حداقل <b>یک خرید موفق</b> از ربات داشته باشید.\n" .
                      "۲. باید حداقل <b>۱۰ مخاطب فعال</b> برای فروش داشته باشید.\n\n" .
                      "💡 در صورت موافقت با قوانین بالا، روی دکمه سبز رنگ زیر کلیک کنید تا درخواست شما برای مدیریت ارسال شود.";
                      
        $keys = json_encode(['inline_keyboard' => [
            [['text' => "✅ موافقم و ارسال درخواست", 'callback_data' => "sendAgencyRequest", 'style' => 'success', 'icon_custom_emoji_id' => '5208880351690112495']],
            [['text' => "🔙 انصراف", 'callback_data' => "mainMenu", 'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']]
        ]]);
        
        bot('editMessageText', ['chat_id' => $from_id, 'message_id' => $message_id, 'text' => $rules_text, 'reply_markup' => $keys, 'parse_mode' => "HTML"]);
    } elseif ($userInfo['is_agent'] == -1) {
        alert($mainValues['agency_request_declined']);
    } elseif ($userInfo['is_agent'] == 1) {
        bot('editMessageText', ['chat_id' => $from_id, 'message_id' => $message_id, 'text' => "لطفاً یکی از کلیدهای زیر را انتخاب کنید:", 'reply_markup' => getMainKeys()]);
    }
    exit();
}

if ($data == "sendAgencyRequest") {
    // بررسی حداقل ۱ خرید موفق
    $stmt = $connection->prepare("SELECT COUNT(*) as buy_count FROM `orders_list` WHERE `userid` = ? AND `status` = 1");
    $stmt->bind_param("i", $from_id);
    $stmt->execute();
    $buyCount = $stmt->get_result()->fetch_assoc()['buy_count'] ?? 0;
    $stmt->close();
    
    if ($buyCount < 1) {
        alert("⚠️ برای درخواست نمایندگی، باید حداقل یک خرید موفق از ربات داشته باشید.");
        exit();
    }
    
    // ارسال به ادمین با دکمه‌های شکیل و کاستوم ایموجی
    $user_name_display = !empty($first_name) ? $first_name : (!empty($userInfo['name']) ? $userInfo['name'] : 'کاربر');
    $user_username_display = !empty($username) && $username !== 'ندارد' ? "@$username" : (!empty($userInfo['username']) && $userInfo['username'] !== 'ندارد' ? "@" . $userInfo['username'] : 'بدون یوزرنیم');
    
    $msg = "📥 <b>درخواست جدید نمایندگی:</b>\n\n" .
           "👤 <b>نام کاربر:</b> $user_name_display\n" .
           "⚡️ <b>نام کاربری:</b> $user_username_display\n" .
           "🆔 <b>آیدی عددی:</b> <code>$from_id</code>\n\n" .
           "📌 کاربر قوانین را مطالعه کرده و با شرایط نمایندگی موافقت نموده است.";
           
    $keys = json_encode(['inline_keyboard' => [
        [
            ['text' => $buttonValues['approve'], 'callback_data' => "agencyApprove" . $from_id, 'style' => 'success', 'icon_custom_emoji_id' => '5208880351690112495'],
            ['text' => $buttonValues['decline'], 'callback_data' => "agencyDecline" . $from_id, 'style' => 'danger', 'icon_custom_emoji_id' => '5215680783863261658']
        ]
    ]]);
    
    sendMessage($msg, $keys, "HTML", $admin);
    setUser(2, 'is_agent');
    
    bot('editMessageText', [
        'chat_id' => $from_id,
        'message_id' => $message_id,
        'text' => "✅ درخواست شما با موفقیت ارسال شد و در صف بررسی توسط مدیریت قرار گرفت.",
        'reply_markup' => json_encode(['inline_keyboard' => [[['text' => "🔙 بازگشت به منوی اصلی", 'callback_data' => "mainMenu", 'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']]]]),
        'parse_mode' => "HTML"
    ]);
    exit();
}

if (preg_match('/^agencyDecline(\d+)/', (string)$data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    editKeys(json_encode(['inline_keyboard' => [[['text' => $buttonValues['declined'], 'callback_data' => "NetFreedomVPN"]]]]));
    sendMessage($mainValues['agency_request_declined'], null, "HTML", $match[1]);

    $stmt = $connection->prepare("UPDATE `users` SET `is_agent` = -1 WHERE `userid` = ?");
    $stmt->bind_param("i", $match[1]);
    $stmt->execute();
    $stmt->close();
    exit();
}

if (preg_match('/^agencyApprove(\d+)/', (string)$data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    setUser($data . "_" . $message_id);
    delMessage();
    sendMessage($mainValues['send_agent_discount_percent'], $cancelKey, "HTML");
    exit();
}

if (preg_match('/^agencyApprove(\d+)_(\d+)/', (string)$userInfo['step'], $match) && $text != $buttonValues['cancel'] && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    bot('deleteMessage', ['chat_id' => $from_id, 'message_id' => $message_id]);
    if (is_numeric($text)) {
        editKeys(json_encode(['inline_keyboard' => [[['text' => $buttonValues['approved'], 'callback_data' => "NetFreedomVPN"]]]]), $match[2]);
        sendMessage($mainValues['saved_successfuly'], getAdminKeys());

        // ✨ فیکس تعریف زمان جاری برای جلوگیری از خالی ماندن فیلد دیتابیس
        $currentTime = time();
        $discount = json_encode(['normal' => $text]);

        $stmt = $connection->prepare("UPDATE `users` SET `is_agent` = 1, `discount_percent` = ?, `agent_date` = ? WHERE `userid` = ?");
        $stmt->bind_param("sii", $discount, $currentTime, $match[1]);
        $stmt->execute();
        $stmt->close();

        sendMessage($mainValues['agency_request_approved'], null, "HTML", $match[1]);

        // ✨ فیکس حیاتی: خالی کردن استپ ادمین در آخرین مرحله پس از اتمام کامل عملیات دیتابیس جهت جلوگیری از نشت دیتا به کدهای پایین‌تر
        setUser();
    } else {
        sendMessage($mainValues['send_only_number'], $cancelKey);
    }
    exit();
}

// -------------------------------------------------------------------------
// ۳. گام نهایی ادمین: تایید فاکتور تراکنش‌های مالی و صدور کلاینت (v3.1.0 نهایی شاهکار)
// -------------------------------------------------------------------------

// --- Start of Range 1814 to 2119 ---
if (preg_match('/accept(.*)/', (string)$data, $match) && $text != $buttonValues['cancel'] && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    // 🌟 فیکس ارور VSCode: بارگذاری لود عمومی متغیرها در ابتدای اسکوپ تابع
    global $mainValues, $removeKeyboard, $buttonProps, $markup, $botState, $connection, $buttonValues, $botUrl, $admin;

    setUser();

    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]);
    $stmt->execute();
    $payInfo = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if (!$payInfo || $payInfo['state'] == "approved") exit();

    $fid = $payInfo['plan_id'];
    $uid = $payInfo['user_id'];
    $price = $payInfo['price'];

    // واکشی کامل دیتای پلن از دیتابیس ربات
    $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();

    $server_id = $file_detail['server_id'];
    $days = intval($file_detail['days']);
    $volume = intval($file_detail['volume']);
    $inbound_id_raw = $file_detail['inbound_id'];
    $limitip = intval($file_detail['limitip']);
    $rahgozar = $file_detail['rahgozar'];

    // واکشی تنظیمات اختصاصی اتصال به API سرور سنایی
    $stmt = $connection->prepare("SELECT * FROM `server_info` WHERE `id` = ?");
    $stmt->bind_param("i", $server_id);
    $stmt->execute();
    $serverInfo = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    $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'];
    $panelUrl = rtrim($serverConfig['panel_url'], '/');
    $apiToken = trim($serverConfig['password']);

    alert($mainValues['sending_config_to_user']); // آلارم انتظار اولیه برای ادمین

    // تغییر وضعیت پرداخت فاکتور به تایید شده
    $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'approved' WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]);
    $stmt->execute();
    $stmt->close();

    $date = time();
    $expire_date = ($days > 0) ? $date + (86400 * $days) : 0;
    $flag = $serverInfo['flag'] ?? "🇩🇪❤️"; // پرچم سرور

    // -------------------------------------------------------------------------
    // 💥 الف) بخش هوشمند سازگاری با تمدید سرویس (Renew Logic Integration)
    // -------------------------------------------------------------------------
    if ($payInfo['type'] == 'RENEW_SCONFIG') {
        // باز کردن بسته آرایه توضیحات موقت جهت استخراج UUID و ری‌آیدی اصلی سرویس
        $renewData = json_decode($payInfo['description'], true);
        $clientUuid = $renewData['uuid'];
        $remark = $renewData['remark'];
        $isMarzban = isset($renewData['marzban']) ? $renewData['marzban'] : false;

        // آپدیت و افزایش زمان انقضای اکانت کلاینت در دیتابیس ربات (جدول orders_list)
        $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `uuid` = ? AND `server_id` = ?");
        $stmt->bind_param("si", $clientUuid, $server_id);
        $stmt->execute();
        $currentOrder = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if ($currentOrder) {
            $baseExpire = ($currentOrder['expire_date'] > $date) ? $currentOrder['expire_date'] : $date;
            $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, $clientUuid, $server_id);
            $stmt->execute();
            $stmt->close();
        }

        // ارتباط مستقیم با API رسمی پنل سنایی v3.1.0 جهت اعمال سریع حجم و روز بدون خطا
        if (!$isMarzban) {
            editClientTraffic($server_id, 0, $clientUuid, $volume, $days, "renew");
        } else {
            editMarzbanConfig($server_id, ['remark' => $remark, 'plus_volume' => $volume, 'days' => $days]);
        }

        // ثبت تراکنش تمدید در ربات
        $inbound_id_renew = $payInfo['volume'];
        $stmt = $connection->prepare("INSERT INTO `increase_order` VALUES (NULL, ?, ?, ?, ?, ?, ?);");
        $stmt->bind_param("iiisii", $uid, $server_id, $inbound_id_renew, $remark, $price, $date);
        $stmt->execute();
        $stmt->close();

        // ارسال پیام تایید و مشخصات تمدید جدید به ادمین و مشتری
        $volumeTxt = ($volume == 0) ? "نامحدود" : $volume . " گیگ";
        $acc_text = "🎉 <b>سرویس شما با موفقیت تمدید شد!</b>\n\n" .
            "🔮 نام سرویس: <code>{$remark}</code>\n" .
            "🔋 حجم افزوده شده: <code>{$volumeTxt}</code>\n" .
            "⏰ اعتبار تمدید: <code>{$days} روز</code>\n" .
            "📎 وضعیت: اکانت متصل شد. نیاز به تغییر لینک نیست.";

        // ارسال پیام قطعی به خریدار کلاینت و ادمین
        sendMessage($acc_text, getMainKeys(), "HTML", $uid);
        sendMessage("✅ تمدید فاکتور کارت به کارت با موفقیت در پنل اعمال و به کاربر تحویل داده شد.", null, "HTML", $admin);
    }
    // ---------------------------------------------------------
    // 🛒 ب) عملیات ساخت و صدور کلاینت جدید (New Buy)
    // ---------------------------------------------------------
    else {
        $accountCount = $payInfo['agent_count'] != 0 ? intval($payInfo['agent_count']) : 1;
        $eachPrice = $price / $accountCount;

        sendMessage("⏳ پرداخت تایید شد؛ در حال صدور و ارسال کانفیگ‌های اختصاصی شما... لطفاً صبور باشید.", null, null, $uid);
        include_once 'phpqrcode/qrlib.php';

        if (strpos($inbound_id_raw, '[') !== false || strpos($inbound_id_raw, ',') !== false) {
            $inboundIdsArray = array_map('intval', explode(',', str_replace(['[', ']'], '', $inbound_id_raw)));
        } else {
            $inboundIdsArray = [intval($inbound_id_raw)];
        }
        if (empty($inboundIdsArray) || $inboundIdsArray[0] == 0) $inboundIdsArray = [1];

        define('IMAGE_WIDTH', 540);
        define('IMAGE_HEIGHT', 540);

        for ($i = 1; $i <= $accountCount; $i++) {
            if (!empty($payInfo['description'])) {
                $remark = $payInfo['description'] . ($accountCount > 1 ? "-$i" : "");
            } else {
                $inbound_id_raw_clean = strval($inbound_id_raw);
                $isProxyInbound = (strpos($inbound_id_raw_clean, '7') !== false);
                if ($isProxyInbound) {
                    $remark = "Proxy-{$uid}-" . rand(1111, 9999);
                } else {
                    $remark = "Client-{$uid}-" . rand(1111, 9999);
                }
            }
            $finalEmail = $remark . "@tg.com";

            $volumeBytes = $volume * 1073741824;
            $expiryTimestamp = ($days > 0) ? (time() + ($days * 86400)) * 1000 : 0;
            $configLinks = [];
            $clientSubId = "";
            $clientUuid = "";

            if ($serverType == "marzban") {
                $response = addMarzbanUser($server_id, $remark, $volume, $days, $fid);
                if (is_object($response) && isset($response->sub_link)) {
                    $directSubUrl = $panelUrl . $response->sub_link;
                    $configLinks[] = $directSubUrl;
                    $clientSubId = $clientUuid = str_replace("/sub/", "", $response->sub_link);
                }
            } else {
                $postData = [
                    "client" => [
                        "email" => $finalEmail,
                        "totalGB" => $volumeBytes,
                        "expiryTime" => $expiryTimestamp,
                        "tgId" => intval($uid),
                        "limitIp" => $limitip,
                        "enable" => true
                    ],
                    "inboundIds" => $inboundIdsArray
                ];

                $clientUuid = ($clientUuid != "") ? $clientUuid : generateUID();
                $response = addInboundAccount($server_id, $clientUuid, $inboundIdsArray[0], $expiryTimestamp, $remark, $volume, $limitip, null, $fid);
                if (is_object($response) && $response->success) {
                    $clientSubId = basename($response->subLink);
                    $stmt = $connection->prepare("SELECT * FROM server_config WHERE id=?");
                    $stmt->bind_param("i", $server_id);
                    $stmt->execute();
                    $srvConf = $stmt->get_result()->fetch_assoc();
                    $stmt->close();
                    
                    $subDec = callXuiApi($srvConf, '/panel/api/clients/links/' . urlencode($remark));
                    if ($subDec && isset($subDec->success) && $subDec->success && is_array($subDec->obj)) {
                        $configLinks = $subDec->obj;
                    }
                }
            }

            $parsedPanelUrl = parse_url($panelUrl);
            $panelHost = $parsedPanelUrl['host'] ?? '';
            $panelScheme = $parsedPanelUrl['scheme'] ?? 'https';
            $directSubLink = "{$panelScheme}://{$panelHost}:2096/sub/{$clientSubId}";

            if (!empty($configLinks)) {
                $configLinesTxt .= "💝 <b>config 1 :</b> <code>{$configLinks[0]}</code>\n\n";
            } else {
                $fallbackConfig = "vless://{$clientUuid}@{$panelHost}:2096?type=tcp&security=none#{$remark}{$flag}";
                $configLinesTxt .= "💝 <b>config 1 :</b> <code>{$fallbackConfig}</code>\n\n";
            }

            $acc_text = "🎉 <b>سفارش جدید شما با موفقیت صادر شد!</b>\n" .
                "🔮 نام سرویس: <code>{$remark}</code>\n" .
                "🔋 حجم ترافیک مجاز: <code>" . ($volume == 0 ? "نامحدود" : $volume . " گیگ") . "</code>\n" .
                "⏰ مدت اعتبار اکانت: <code>{$days} روز</code>\n\n" .
                "---------------------------------------\n\n" .
                $configLinesTxt .
                "🔋 <b>Volume web :</b> {$botUrl}search.php?id={$clientSubId}\n\n" .
                "🌐 <b>subscription :</b> <code>{$directSubLink}</code>";

            $file = RandomString(10) . ".png";
            @QRcode::png($directSubLink, $file, 'L', 10, 2);
            if (function_exists('addBorderImage')) addBorderImage($file);

            if (file_exists($file) && file_exists(dirname(__DIR__) . "/settings/QRCode.jpg")) {
                $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);
            }

            $photoSent = false;
            if (file_exists($file)) {
                $resPhoto = sendPhoto($file, $acc_text, json_encode(['inline_keyboard' => [
                    [['text' => 'مدیریت سرویس در مینی‌اپ 📱', 'web_app' => ['url' => "https://wizwiz.villux.ir:8443/Netfreedom/mini-app/#subscriptions"]]],
                    [['text' => $buttonValues['back_to_main'], 'callback_data' => "mainMenu", 'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']]
                ]]), "HTML", $uid);
                if ($resPhoto && isset($resPhoto->ok) && $resPhoto->ok) {
                    $photoSent = true;
                }
                @unlink($file);
            }
            if (!$photoSent) {
                sendMessage($acc_text, json_encode(['inline_keyboard' => [
                    [['text' => 'مدیریت سرویس در مینی‌اپ 📱', 'web_app' => ['url' => "https://wizwiz.villux.ir:8443/Netfreedom/mini-app/#subscriptions"]]],
                    [['text' => $buttonValues['back_to_main'], 'callback_data' => "mainMenu", 'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']]
                ]]), "HTML", $uid);
            }

            // ارسال فایل .npvt برای NapsternetV
            sendNpvtDocument($configLinks, $remark, $uid, $directSubLink);

            $linkForDb = json_encode($configLinks, JSON_UNESCAPED_UNICODE);
            $inbound_id_db = $inboundIdsArray[0];
            $stmt = $connection->prepare("INSERT INTO `orders_list` (`userid`, `token`, `transid`, `fileid`, `server_id`, `inbound_id`, `remark`, `uuid`, `protocol`, `expire_date`, `link`, `amount`, `status`, `date`, `notif`, `rahgozar`, `agent_bought`) VALUES (?, ?, '', ?, ?, ?, ?, ?, 'vless/vmess/trojan', ?, ?, ?, 1, ?, 0, ?, ?);");
            $stmt->bind_param("isiiissisiiii", $uid, $clientSubId, $fid, $server_id, $inbound_id_db, $remark, $clientSubId, $expire_date, $linkForDb, $eachPrice, $date, $rahgozar, $payInfo['agent_bought']);
            $stmt->execute();
            $stmt->close();
        }

        sendMessage(str_replace(["REMARK", "VOLUME", "DAYS"], [$remark, $volume, $days], $mainValues['sent_config_to_user']), getMainKeys());

        // کسر از ظرفیت اتمی سرورها
        $stmt = $connection->prepare("UPDATE `server_info` SET `ucount` = `ucount` - ? WHERE `id` = ?");
        $stmt->bind_param("ii", $accountCount, $server_id);
        $stmt->execute();
        $stmt->close();

        if ($file_detail['type'] != 'client_centric') {
            $stmt = $connection->prepare("UPDATE `server_plans` SET `acount` = `acount` - ? WHERE `id` = ?");
            $stmt->bind_param("ii", $accountCount, $fid);
            $stmt->execute();
            $stmt->close();
        }
    }

    // تغییر دکمه فاکتور ادمین به تیک سبز تایید
    $keys = json_encode(['inline_keyboard' => [[['text' => "تمدید با موفقیت صادر شد کلاینت ✅", 'callback_data' => "NetFreedomVPN"]]]]);
    editKeys($keys);

    // محاسبه پورسانت معرف
    if ($payInfo['type'] != "RENEW_SCONFIG") {
        $stmt = $connection->prepare("SELECT `refered_by` FROM `users` WHERE `userid` = ?");
        $stmt->bind_param("i", $uid);
        $stmt->execute();
        $user_detail = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if (!empty($user_detail['refered_by'])) {
            $stmt = $connection->prepare("SELECT `value` FROM `setting` WHERE `type` = 'INVITE_BANNER_AMOUNT'");
            $stmt->execute();
            $inviteAmount = $stmt->get_result()->fetch_assoc()['value'] ?? 0;
            $stmt->close();
            $inviterId = $user_detail['refered_by'];

            $stmt = $connection->prepare("UPDATE `users` SET `wallet` = `wallet` + ? WHERE `userid` = ?");
            $stmt->bind_param("ii", $inviteAmount, $inviterId);
            $stmt->execute();
            $stmt->close();
            sendMessage("🎉 پورسانت زیرمجموعه‌گیری به مبلغ " . number_format($inviteAmount) . " تومان به حساب شما واریز شد.", null, null, $inviterId);
        }
    }
    exit();
}

// -------------------------------------------------------------------------
// ۴. منطق رد درخواست پرداخت یا سفارش (Decline) همراه با ثبت دلیل
// -------------------------------------------------------------------------
if (strpos($data, 'decline') === 0 && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    setUser($data . "_" . $message_id);
    delMessage();
    sendMessage('😔 دلیلت از عدم تایید چیست؟ (جهت ارسال خودکار به کاربر تایپ کنید):', $cancelKey, "HTML");
    exit();
}

if (preg_match('/decline(\d+)_([a-zA-Z0-9]+)_(\d+)/', (string)$userInfo['step'], $match) && ($from_id == $admin || $userInfo['isAdmin'] == true) && $text != $buttonValues['cancel']) {
    bot('deleteMessage', ['chat_id' => $from_id, 'message_id' => $message_id]);
    if (empty($text)) {
        sendMessage("❌ لطفاً یک متن معتبر ارسال کنید.");
        exit;
    }

    setUser();
    $uid = $match[1];
    $hashId = $match[2];
    $msgId = $match[3];

    // به روز رسانی وضعیت تراکنش به رد شده
    $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'declined' WHERE `hash_id` = ?");
    $stmt->bind_param("s", $hashId);
    $stmt->execute();
    $stmt->close();

    // ادیت ظاهر دکمه فاکتور ادمین به لغو شد
    editKeys(json_encode(['inline_keyboard' => [[['text' => "لغو شد ❌", 'callback_data' => "NetFreedomVPN"]]]]), $msgId);

    sendMessage('✅ پیام عدم تایید به همراه دلیل برای کاربر با موفقیت ارسال شد.', $removeKeyboard);
    sendMessage($mainValues['reached_main_menu'], getMainKeys());

    $msgToUser = "❌ <b>درخواست خرید/تمدید شما تایید نشد</b>\n\n👤 کاربر گرامی، فاکتور یا رسید ارسالی شما توسط مدیریت رد شد.\n📝 <b>دلیل عدم تایید:</b> <i>$text</i>";
    sendMessage($msgToUser, null, "HTML", $uid);
    exit();
}

if (preg_match('/^selectRenewPlan_(\d+)_(\d+)/', (string)$data, $match)) {
    $oid = $match[1];
    $planId = $match[2];
    
    // Fetch order/config details
    $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) {
        alert("سرویس یافت نشد");
        exit;
    }
    
    // Fetch selected plan details
    $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `id` = ? AND `active` = 1");
    $stmt->bind_param("i", $planId);
    $stmt->execute();
    $respd = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if (!$respd) {
        alert("طرح انتخاب شده معتبر نیست");
        exit;
    }
    
    $price = $respd['price'];
    $serverId = $order['server_id'];
    $agentBought = $order['agent_bought'];
    $remark = $order['remark'];
    
    if ($agentBought == true) {
        $discounts = json_decode($userInfo['discount_percent'], true);
        if ($botState['agencyPlanDiscount'] == "on")
            $discount = $discounts['plans'][$planId] ?? $discounts['normal'];
        else
            $discount = $discounts['servers'][$serverId] ?? $discounts['normal'];
        $price -= floor($price * $discount / 100);
    }
    
    // Early renewal check (5 days or more remaining)
    $remainingDays = 0;
    $hasEarlyDiscount = false;
    $earlyDiscountCode = '';
    $earlyDiscountPercent = 10;

    if ($order['expire_date'] > time()) {
        $remainingDays = ($order['expire_date'] - time()) / 86400;
        if ($remainingDays >= 5) {
            $hasEarlyDiscount = true;
            $earlyDiscountCode = "EARLY_" . strtoupper(RandomString(5));
            $expiryTime = time() + 2 * 86400;
            
            $stmt = $connection->prepare("INSERT INTO `discounts` (`hash_id`, `amount`, `type`, `expire_count`, `expire_date`, `can_use`, `used_by`) VALUES (?, ?, 'percent', 1, ?, ?, '[]')");
            $canUseStr = strval($from_id);
            $stmt->bind_param("siii", $earlyDiscountCode, $earlyDiscountPercent, $expiryTime, $canUseStr);
            $stmt->execute();
            $stmt->close();
        }
    }

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

    $time = time();
    $descPayload = $hasEarlyDiscount ? "EARLY_CODE:" . $earlyDiscountCode : "";
    
    // We store the selected plan ID in the `volume` column!
    $stmt = $connection->prepare("INSERT INTO `pays` (`hash_id`, `user_id`, `type`, `plan_id`, `volume`, `day`, `price`, `request_date`, `state`, `description`)
                                VALUES (?, ?, 'RENEW_ACCOUNT', ?, ?, '0', ?, ?, 'pending', ?)");
    $stmt->bind_param("siiiis", $hash_id, $from_id, $oid, $planId, $price, $time, $descPayload);
    $stmt->execute();
    $rowId = $stmt->insert_id;
    $stmt->close();
    
    // Now render the invoice!
    $priceNumeric = intval($price);
    $priceFormatted = ($price == 0) ? "رایگان" : number_format($priceNumeric) . " تومان";
    
    $keyboard = array();
    if ($botState['cartToCartState'] == "on")
        $keyboard[] = [['text' => "💳 کارت به کارت مبلغ $priceFormatted", 'callback_data' => "payRenewWithCartToCart$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' => "پرداخت با موجودی مبلغ $priceFormatted", 'callback_data' => "payRenewWithWallet$hash_id"]];
    if ($botState['tronWallet'] == "on")
        $keyboard[] = [['text' => $buttonValues['tron_gateway'], 'callback_data' => "payWithTronWallet" . $hash_id]];

    $keyboard[] = [['text' => " 🎁 اعمال کد تخفیف ", 'callback_data' => "haveDiscountRenew_" . $oid . "_" . $rowId]];
    $keyboard[] = [['text' => $buttonValues['cancel'], 'callback_data' => "mainMenu"]];

    $planTitle = $respd['title'];
    $planVol = ($respd['volume'] == 0) ? "نامحدود" : $respd['volume'] . " گیگابایت";
    $planDays = ($respd['days'] == 0) ? "نامحدود" : $respd['days'] . " روز";

    $originalPrice = $respd['price'];
    if ($agentBought == true) {
        $discounts = json_decode($userInfo['discount_percent'], true);
        if ($botState['agencyPlanDiscount'] == "on")
            $discount = $discounts['plans'][$planId] ?? $discounts['normal'];
        else
            $discount = $discounts['servers'][$serverId] ?? $discounts['normal'];
        $originalPrice -= floor($originalPrice * $discount / 100);
    }
    
    $msg = "🧾 <b>فاکتور تمدید سرویس</b>\n\n";
    $msg .= "👤 نام سرویس: <code>$remark</code>\n";
    $msg .= "📦 پلن تمدید: <b>$planTitle</b>\n";
    $msg .= "🔋 حجم ترافیک: <b>$planVol</b>\n";
    $msg .= "⏳ مدت اعتبار: <b>$planDays</b>\n";
    
    if ($priceNumeric != $originalPrice) {
        $msg .= "💰 مبلغ اصلی: <del>" . number_format($originalPrice) . " تومان</del>\n";
        $msg .= "🎉 مبلغ قابل پرداخت (با تخفیف): <b>$priceFormatted</b>\n\n";
    } else {
        $msg .= "💰 مبلغ قابل پرداخت: <b>$priceFormatted</b>\n\n";
    }

    if ($hasEarlyDiscount) {
        $msg .= "🎉 <b>هدیه تمدید زودهنگام نت‌فریدوم:</b>\n";
        $msg .= "به دلیل اینکه بیش از ۵ روز زودتر اقدام به تمدید کردید، یک کد تخفیف ۱۰ درصدی برای شما ساخته شد!\n";
        $msg .= "🔑 کد تخفیف: <code>$earlyDiscountCode</code>\n";
        $msg .= "👇 جهت اعمال تخفیف، دکمه «🎁 اعمال کد تخفیف» را زده و کد فوق را ارسال نمایید.\n\n";
    }

    $msg .= "لطفا با یکی از روش های زیر اقدام به پرداخت و تمدید نمایید :";

    delMessage();
    sendMessage($msg, json_encode([
        'inline_keyboard' => $keyboard
    ]), "HTML");
    exit();
}

// --- Start of Range 5345 to 5504 ---
if (preg_match('/^discountRenew(\d+)_(\d+)/', (string)$userInfo['step'], $match) || preg_match('/renewAccount(\d+)/', (string)$data, $match) && $text != $buttonValues['cancel']) {
    if (preg_match('/^discountRenew/', (string)$userInfo['step'])) {
        $rowId = $match[2];

        $time = time();
        $stmt = $connection->prepare("SELECT * FROM `discounts` WHERE (`expire_date` > $time OR `expire_date` = 0) AND (`expire_count` > 0 OR `expire_count` = -1) AND `hash_id` = ?");
        $stmt->bind_param("s", $text);
        $stmt->execute();
        $list = $stmt->get_result();
        $stmt->close();

        $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `id` = ?");
        $stmt->bind_param("i", $rowId);
        $stmt->execute();
        $payInfo = $stmt->get_result()->fetch_assoc();
        $hash_id = $payInfo['hash_id'];
        $afterDiscount = $payInfo['price'];
        $stmt->close();

        if ($list->num_rows > 0) {
            $discountInfo = $list->fetch_assoc();
            $amount = $discountInfo['amount'];
            $type = $discountInfo['type'];
            $count = $discountInfo['expire_count'];
            $usedBy = !is_null($discountInfo['used_by']) ? json_decode($discountInfo['used_by'], true) : array();

            $canUse = $discountInfo['can_use'];
            $userUsedCount = array_count_values($usedBy)[$from_id];
            if ($canUse > $userUsedCount) {
                $usedBy[] = $from_id;
                $encodeUsedBy = json_encode($usedBy);

                if ($count != -1)
                    $query = "UPDATE `discounts` SET `expire_count` = `expire_count` - 1, `used_by` = ? WHERE `id` = ?";
                else
                    $query = "UPDATE `discounts` SET `used_by` = ? WHERE `id` = ?";

                $stmt = $connection->prepare($query);
                $stmt->bind_param("si", $encodeUsedBy, $discountInfo['id']);
                $stmt->execute();
                $stmt->close();

                if ($type == "percent") {
                    $discount = $afterDiscount * $amount / 100;
                    $afterDiscount -= $discount;
                    $discount = number_format($discount) . " تومان";
                } else {
                    $afterDiscount -= $amount;
                    $discount = number_format($amount) . " تومان";
                }
                if ($afterDiscount < 0)
                    $afterDiscount = 0;

                $stmt = $connection->prepare("UPDATE `pays` SET `price` = ?, `description` = ? WHERE `id` = ?");
                $newDesc = "Discount Code: " . $text;
                $stmt->bind_param("isi", $afterDiscount, $newDesc, $rowId);
                $stmt->execute();
                $stmt->close();
                sendMessage(str_replace("AMOUNT", $discount, $mainValues['valid_discount_code']));
                $keys = json_encode(['inline_keyboard' => [
                    [
                        ['text' => "❤️", "callback_data" => "NetFreedomVPN"]
                    ],
                ]]);
                sendMessage(
                    str_replace(['USERID', 'USERNAME', "NAME", "AMOUNT", "DISCOUNTCODE"], [$from_id, $username, $first_name, $discount, $text], $mainValues['used_discount_code']),
                    $keys,
                    null,
                    $admin
                );
            } else
                sendMessage($mainValues['not_valid_discount_code']);
        } else
            sendMessage($mainValues['not_valid_discount_code']);
        setUser();
    } else
        delMessage();

    $oid = $match[1];

    $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `id` = ?");
    $stmt->bind_param("i", $oid);
    $stmt->execute();
    $order = $stmt->get_result();
    $stmt->close();
    if ($order->num_rows == 0) {
        delMessage();
        sendMessage($mainValues['config_not_found'], getMainKeys());
        exit();
    }
    $order = $order->fetch_assoc();
    $serverId = $order['server_id'];
    $agentBought = $order['agent_bought'];
    $remark = $order['remark'];

    // Check if there is an active custom plan selected in pays
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `plan_id` = ? AND `user_id` = ? AND `type` = 'RENEW_ACCOUNT' AND `state` = 'pending' ORDER BY `id` DESC LIMIT 1");
    $stmt->bind_param("ii", $oid, $from_id);
    $stmt->execute();
    $payRecord = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    $uuid = $order['uuid'] ?? "0";

    // Fetch live server config
    $stmt = $connection->prepare("SELECT * FROM `server_config` WHERE `id` = ?");
    $stmt->bind_param("i", $serverId);
    $stmt->execute();
    $serverConfig = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    $liveTotalGb = 0;
    if ($serverConfig) {
        $serverType = $serverConfig['type'];
        $panelUrl = rtrim($serverConfig['panel_url'] ?? '', '/');
        
        if ($serverType == "marzban") {
            $info = getMarzbanUser($serverId, $remark);
            if (isset($info->username)) {
                $total = $info->data_limit ?? 0;
                $liveTotalGb = round((float)$total / 1073741824);
            }
        } else {
            include_once __DIR__ . '/config_xui_api.php';
            $apiToken = trim($serverConfig['password']);
            $finalEmail = $remark . "@tg.com";
            
            $getClientUrl = $panelUrl . "/panel/api/clients/get/" . urlencode($finalEmail);
            $ch = curl_init(); 
            curl_setopt($ch, CURLOPT_URL, $getClientUrl); 
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json', 'Authorization: Bearer ' . $apiToken]);
            $clientRes = curl_exec($ch); 
            curl_close($ch);
            
            $clientDecoded = json_decode($clientRes, true);
            if (isset($clientDecoded['success']) && $clientDecoded['success'] && isset($clientDecoded['obj']['client'])) {
                $total = $clientDecoded['obj']['client']['totalGB'] ?? 0;
                $liveTotalGb = round((float)$total / 1073741824);
            } else {
                $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) {
                            $total = $c->totalGB ?? ($c->traffic->total ?? 0);
                            $liveTotalGb = round((float)$total / 1073741824);
                            break;
                        }
                    }
                }
            }
        }
    }

    $fid = $order['fileid'];
    if ($liveTotalGb > 0) {
        $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `server_id` = ? AND `volume` = ? LIMIT 1");
        $stmt->bind_param("ii", $serverId, $liveTotalGb);
        $stmt->execute();
        $matchedPlan = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        if ($matchedPlan) {
            $fid = $matchedPlan['id'];
            // Update orders_list with the corrected fileid
            $stmt = $connection->prepare("UPDATE `orders_list` SET `fileid` = ? WHERE `id` = ?");
            $stmt->bind_param("ii", $fid, $oid);
            $stmt->execute();
            $stmt->close();
        }
    }

    if ($payRecord && intval($payRecord['volume']) > 0) {
        $fid = intval($payRecord['volume']);
    }

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

    $isTrial = false;
    if (!$respd || $respd['price'] == 0 || strpos($respd['title'], 'تست') !== false || stripos($respd['title'], 'test') !== false || stripos($respd['title'], 'trial') !== false) {
        $isTrial = true;
    }

    if ($isTrial) {
        // If it has <= 2GB, it is a test config (not allowed to renew)
        if ($liveTotalGb <= 2 && $order['amount'] == 0 && (strpos($remark, 'Gift') !== false || strpos($remark, 'test') !== false || strpos($remark, 'trial') !== false || $fid == 1)) {
            delMessage();
            sendMessage("❌ <b>خطا: اکانت‌های تست قابل تمدید نیستند.</b>\n\nسرویس شما یک اکانت تست موقت است و امکان تمدید آن وجود ندارد. لطفاً یک سرویس تجاری جدید خریداری نمایید.", getMainKeys(), "HTML");
            exit();
        }
    }

    $price = $respd['price'];
    if ($agentBought == true) {
        $discounts = json_decode($userInfo['discount_percent'], true);
        if ($botState['agencyPlanDiscount'] == "on")
            $discount = $discounts['plans'][$fid] ?? $discounts['normal'];
        else
            $discount = $discounts['servers'][$serverId] ?? $discounts['normal'];
        $price -= floor($price * $discount / 100);
    }
    $remainingDays = 0;
    $hasEarlyDiscount = false;
    $earlyDiscountCode = '';
    $earlyDiscountPercent = 10;

    if (!preg_match('/^discountRenew/', (string)$userInfo['step'])) {
        if ($order['expire_date'] > time()) {
            $remainingDays = ($order['expire_date'] - time()) / 86400;
            if ($remainingDays >= 5) {
                $hasEarlyDiscount = true;
                $earlyDiscountCode = "EARLY_" . strtoupper(RandomString(5));
                $expiryTime = time() + 2 * 86400;
                
                $stmt = $connection->prepare("INSERT INTO `discounts` (`hash_id`, `amount`, `type`, `expire_count`, `expire_date`, `can_use`, `used_by`) VALUES (?, ?, 'percent', 1, ?, ?, '[]')");
                $canUseStr = strval($from_id);
                $stmt->bind_param("siii", $earlyDiscountCode, $earlyDiscountPercent, $expiryTime, $canUseStr);
                $stmt->execute();
                $stmt->close();
            }
        }

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

        $time = time();
        $descPayload = $hasEarlyDiscount ? "EARLY_CODE:" . $earlyDiscountCode : "";
        $stmt = $connection->prepare("INSERT INTO `pays` (`hash_id`, `user_id`, `type`, `plan_id`, `volume`, `day`, `price`, `request_date`, `state`, `description`)
                                    VALUES (?, ?, 'RENEW_ACCOUNT', ?, '0', '0', ?, ?, 'pending', ?)");
        $stmt->bind_param("siiiis", $hash_id, $from_id, $oid, $price, $time, $descPayload);
        $stmt->execute();
        $rowId = $stmt->insert_id;
        $stmt->close();
    } else {
        $price = $afterDiscount;
        $stmt = $connection->prepare("SELECT `description` FROM `pays` WHERE `id` = ?");
        $stmt->bind_param("i", $rowId);
        $stmt->execute();
        $pDesc = $stmt->get_result()->fetch_assoc()['description'] ?? '';
        $stmt->close();
        
        if (preg_match('/^EARLY_CODE:(.*)/', $pDesc, $eMatch)) {
            $hasEarlyDiscount = true;
            $earlyDiscountCode = $eMatch[1];
        }
    }

    $priceNumeric = intval($price);
    if ($price == 0)
        $price = "رایگان";
    else
        $price = number_format($priceNumeric) . " تومان";
        
    $keyboard = array();
    if ($botState['cartToCartState'] == "on")
        $keyboard[] = [['text' => "💳 کارت به کارت مبلغ $price", 'callback_data' => "payRenewWithCartToCart$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' => "پرداخت با موجودی مبلغ $price", 'callback_data' => "payRenewWithWallet$hash_id"]];
    if ($botState['tronWallet'] == "on")
        $keyboard[] = [['text' => $buttonValues['tron_gateway'], 'callback_data' => "payWithTronWallet" . $hash_id]];

    if (!preg_match('/^discountRenew/', (string)$userInfo['step']))
        $keyboard[] = [['text' => " 🎁 اعمال کد تخفیف ", 'callback_data' => "haveDiscountRenew_" . $match[1] . "_" . $rowId]];

    $keyboard[] = [['text' => $buttonValues['cancel'], 'callback_data' => "mainMenu"]];

    $planTitle = $respd['title'];
    $planVol = ($respd['volume'] == 0) ? "نامحدود" : $respd['volume'] . " گیگابایت";
    $planDays = ($respd['days'] == 0) ? "نامحدود" : $respd['days'] . " روز";

    $originalPrice = $respd['price'];
    if ($agentBought == true) {
        $discounts = json_decode($userInfo['discount_percent'], true);
        if ($botState['agencyPlanDiscount'] == "on")
            $discount = $discounts['plans'][$fid] ?? $discounts['normal'];
        else
            $discount = $discounts['servers'][$serverId] ?? $discounts['normal'];
        $originalPrice -= floor($originalPrice * $discount / 100);
    }
    
    $discountAppliedMsg = "";
    if (preg_match('/^discountRenew/', (string)$userInfo['step'])) {
        $discountAppliedMsg = "🎁 <b>کد تخفیف با موفقیت اعمال شد!</b>\n\n";
    }

    $msg = "🧾 <b>فاکتور تمدید سرویس</b>\n\n";
    $msg .= $discountAppliedMsg;
    $msg .= "👤 نام سرویس: <code>$remark</code>\n";
    $msg .= "📦 پلن تمدید: <b>$planTitle</b>\n";
    $msg .= "🔋 حجم ترافیک: <b>$planVol</b>\n";
    $msg .= "⏳ مدت اعتبار: <b>$planDays</b>\n";
    
    if ($priceNumeric != $originalPrice) {
        $msg .= "💰 مبلغ اصلی: <del>" . number_format($originalPrice) . " تومان</del>\n";
        $msg .= "🎉 مبلغ قابل پرداخت (با تخفیف): <b>$price</b>\n\n";
    } else {
        $msg .= "💰 مبلغ قابل پرداخت: <b>$price</b>\n\n";
    }

    if ($hasEarlyDiscount) {
        $msg .= "🎉 <b>هدیه تمدید زودهنگام نت‌فریدوم:</b>\n";
        $msg .= "به دلیل اینکه بیش از ۵ روز زودتر اقدام به تمدید کردید، یک کد تخفیف ۱۰ درصدی برای شما ساخته شد!\n";
        $msg .= "🔑 کد تخفیف: <code>$earlyDiscountCode</code>\n";
        $msg .= "👇 جهت اعمال تخفیف، دکمه «🎁 اعمال کد تخفیف» را زده و کد فوق را ارسال نمایید.\n\n";
    }

    $msg .= "لطفا با یکی از روش های زیر اقدام به پرداخت و تمدید نمایید :";

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


// --- Start of Range 6059 to 6101 ---
if (preg_match('/increaseADay(.*)/', (string)$data, $match)) {
    $stmt = $connection->prepare("SELECT * FROM `increase_day`");
    $stmt->execute();
    $res = $stmt->get_result();
    $stmt->close();

    $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `id` = ?");
    $stmt->bind_param("i", $match[1]);
    $stmt->execute();
    $orderInfo = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $agentBought = $orderInfo['agent_bought'];

    if ($res->num_rows == 0) {
        alert("در حال حاضر هیچ پلنی برای افزایش مدت زمان سرویس وجود ندارد");
        exit;
    }
    $keyboard = [];
    while ($cat = $res->fetch_assoc()) {
        $id = $cat['id'];
        $title = $cat['volume'];
        $price = $cat['price'];
        if ($agentBought == true) {
            $discounts = json_decode($userInfo['discount_percent'], true);
            if ($botState['agencyPlanDiscount'] == "on")
                $discount = $discounts['plans'][$orderInfo['fileid']] ?? $discounts['normal'];
            else
                $discount = $discounts['servers'][$orderInfo['server_id']] ?? $discounts['normal'];
            $price -= floor($price * $discount / 100);
        }
        if ($price == 0)
            $price = "رایگان";
        else
            $price = number_format($price) . " تومان";
        $keyboard[] = ['text' => "$title روز $price", 'callback_data' => "selectPlanDayIncrease{$match[1]}_$id"];
    }
    $keyboard = array_chunk($keyboard, 2);
    $keyboard[] = [['text' => $buttonValues['back_to_main'], 'callback_data' => "mainMenu", 'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']];
    editText($message_id, "لطفا یکی از پلن های افزایشی را انتخاب کنید :", json_encode([
        'inline_keyboard' => $keyboard
    ]));
}

// =========================================================================
// سیستم جدید سهمیه نمایندگی: خرید سهمیه و ساخت کانفیگ از سهمیه (v3.1.0)
// =========================================================================

if ($text == $buttonValues['cancel'] && (preg_match('/^agentBuyQuota_/', (string)$userInfo['step']) || preg_match('/^agentCreateConfig_/', (string)$userInfo['step']))) {
    setUser();
    sendMessage("عملیات لغو شد ❌", $removeKeyboard);
    exit();
}

// -------------------------------------------------------------------------
// مدیریت کال‌بک‌های دکمه‌های پنل همکاری نمایندگان (خرید سهمیه و ساخت کانفیگ)
// -------------------------------------------------------------------------
if ($data == "agentCreateConfig_selectServer" && $userInfo['is_agent'] == 1) {
    $stmt = $connection->prepare("SELECT * FROM `server_info` WHERE `active`=1 and `state` = 1 and `ucount` > 0 ORDER BY `id` ASC");
    $stmt->execute();
    $respd = $stmt->get_result();
    $stmt->close();
    
    $keyboard = [];
    while ($cat = $respd->fetch_assoc()) {
        $id = $cat['id'];
        $name = $cat['title'];
        $flag = $cat['flag'];
        $keyboard[] = ['text' => "$flag $name", 'callback_data' => "agentCustomConfigPanel_$id"];
    }
    $keyboard = array_chunk($keyboard, 1);
    $keyboard[] = [['text' => "🔙 بازگشت به پنل همکاری", 'callback_data' => "agencySettings"]];
    
    editText($message_id, "🖥 <b>لطفاً سرور مورد نظر خود را برای ساخت کانفیگ انتخاب کنید:</b>", json_encode(['inline_keyboard' => $keyboard]), "HTML");
    exit();
}

if ($data == "agentBuyQuota_stepVolume" && $userInfo['is_agent'] == 1) {
    $stmt = $connection->prepare("SELECT * FROM `server_info` WHERE `active`=1 and `state` = 1 and `ucount` > 0 ORDER BY `id` ASC");
    $stmt->execute();
    $respd = $stmt->get_result();
    $stmt->close();
    
    $keyboard = [];
    while ($cat = $respd->fetch_assoc()) {
        $id = $cat['id'];
        $name = $cat['title'];
        $flag = $cat['flag'];
        $keyboard[] = ['text' => "$flag $name", 'callback_data' => "agentBuyQuotaPlans_$id"];
    }
    $keyboard = array_chunk($keyboard, 1);
    $keyboard[] = [['text' => "🔙 بازگشت به پنل همکاری", 'callback_data' => "agencySettings"]];
    
    editText($message_id, "🖥 <b>لطفاً سرور مورد نظر خود را برای خرید سهمیه انتخاب کنید:</b>", json_encode(['inline_keyboard' => $keyboard]), "HTML");
    exit();
}

// ----------------------------------------
// ۱. پنل آمار و مدیریت کانفیگ‌های سفارشی نماینده
// ----------------------------------------
if (preg_match('/^agentCustomConfigPanel_(?<sid>\d+)/', (string)$data, $match) && $userInfo['is_agent'] == 1) {
    $sid = $match['sid'];
    setUser();
    
    $stmt = $connection->prepare("SELECT * FROM `server_info` WHERE `id` = ?");
    $stmt->bind_param("i", $sid);
    $stmt->execute();
    $serverInfo = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    $stmt = $connection->prepare("SELECT COUNT(*) as cnt FROM `orders_list` WHERE `userid` = ? AND `server_id` = ? AND `agent_bought` = 1");
    $stmt->bind_param("ii", $from_id, $sid);
    $stmt->execute();
    $totalConfigs = $stmt->get_result()->fetch_assoc()['cnt'] ?? 0;
    $stmt->close();
    
    $stmt = $connection->prepare("SELECT SUM(fileid) as vol FROM `orders_list` WHERE `userid` = ? AND `server_id` = ? AND `agent_bought` = 1");
    $stmt->bind_param("ii", $from_id, $sid);
    $stmt->execute();
    $totalAllocatedVolume = $stmt->get_result()->fetch_assoc()['vol'] ?? 0;
    $stmt->close();

    $stmt = $connection->prepare("SELECT SUM(price) as prc, SUM(volume) as vls, SUM(day) as lims FROM `pays` WHERE `user_id` = ? AND `type` = 'BUY_AGENT_QUOTA' AND `state` = 'approved'");
    $stmt->bind_param("i", $from_id);
    $stmt->execute();
    $quotaStats = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    $totalPaid = number_format($quotaStats['prc'] ?? 0) . " تومان";
    $totalVolsBought = number_format($quotaStats['vls'] ?? 0, 1) . " GB";
    $totalLimitsBought = intval($quotaStats['lims'] ?? 0) . " عدد";
    
    $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 . " عدد";
    $agent_test_lim = intval($userInfo['agent_test_limit'] ?? 0);
    
    $panelMsg = "🛠 <b>پنل مدیریت کانفیگ سفارشی نمایندگی</b>\n\n"
              . "🖥 <b>سرور میزبان:</b> {$serverInfo['title']}\n"
              . "━━━━━━━━━━━━━━\n"
              . "📊 <b>آمار سهمیه فعلی شما:</b>\n"
              . "🔋 حجم باقی‌مانده سهمیه: <code>$agent_vol_txt</code>\n"
              . "👤 تعداد اکانت قابل ساخت: <code>$agent_lim_txt</code>\n"
              . "🎁 تعداد اکانت تست (۱ گیگ): <code>$agent_test_lim عدد</code>\n"
              . "━━━━━━━━━━━━━━\n"
              . "📈 <b>آمار کلی فعالیت شما:</b>\n"
              . "📝 اکانت‌های ساخته شده روی این سرور: <code>$totalConfigs عدد</code>\n"
              . "📉 ترافیک مصرف شده روی این سرور: <code>$totalAllocatedVolume GB</code>\n"
              . "💳 کل حجم خریداری شده شما: <code>$totalVolsBought</code>\n"
              . "👤 کل اکانت‌های سهمیه خریداری شده: <code>$totalLimitsBought</code>\n"
              . "💰 کل مبلغ پرداختی بابت سهمیه: <code>$totalPaid</code>\n\n"
              . "👇 لطفاً یکی از گزینه‌های زیر را انتخاب کنید:";
              
    $keyboard = [
        [['text' => "➕ ساخت کانفیگ جدید (کسر از سهمیه)", 'callback_data' => "agentCreateConfig_start_{$sid}"]],
        [['text' => "🎁 دریافت اکانت تست (۱ گیگ رایگان)", 'callback_data' => "agentCreateTestConfig_start_{$sid}"]],
        [['text' => "🛍 خرید سهمیه جدید (خرید کانفیگ سفارشی)", 'callback_data' => "agentBuyQuotaPlans_{$sid}"]],
        [['text' => "🔙 بازگشت", 'callback_data' => "selectServer{$sid}_much", 'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']]
    ];
    
    $res = editText($message_id, $panelMsg, json_encode(['inline_keyboard' => $keyboard]), "HTML");
    if (!isset($res->ok) || !$res->ok) {
        sendMessage($panelMsg, json_encode(['inline_keyboard' => $keyboard]), "HTML", $from_id);
    }
    exit();
}

// ----------------------------------------
// ۲. خرید سهمیه جدید (بر اساس دسته‌بندی اکانت نمایندگان)
// ----------------------------------------
if (preg_match('/^agentBuyQuotaPlans_(?<sid>\d+)/', (string)$data, $match) && $userInfo['is_agent'] == 1) {
    $sid = $match['sid'];
    
    $planStmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `server_id` = ? AND `active` = 1 AND `type` = 'agent_quota' ORDER BY `id` ASC");
    $planStmt->bind_param("i", $sid);
    $planStmt->execute();
    $plans = $planStmt->get_result();
    $planStmt->close();
    
    if ($plans->num_rows == 0) {
        alert("⚠️ در حال حاضر هیچ پلنی برای خرید سهمیه نمایندگی روی این سرور تعریف نشده است.");
        exit();
    }
    
    $keyboard = [];
    while ($plan = $plans->fetch_assoc()) {
        $pId = $plan['id'];
        $title = $plan['title'];
        $keyboard[] = [['text' => "$title", 'callback_data' => "agentBuyQuotaConfirm_{$sid}_{$pId}"]];
    }
    $keyboard[] = [['text' => "🔙 بازگشت به پنل نمایندگی", 'callback_data' => "agentCustomConfigPanel_{$sid}", 'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']];
    
    editText($message_id, "🛍 <b>لطفاً یکی از پلن‌های سهمیه نمایندگی زیر را انتخاب کنید:</b>", json_encode(['inline_keyboard' => $keyboard]), "HTML");
    exit();
}

if (preg_match('/^agentBuyQuotaConfirm_(?<sid>\d+)_(?<pid>\d+)/', (string)$data, $match) && $userInfo['is_agent'] == 1) {
    $sid = $match['sid'];
    $pid = $match['pid'];
    
    $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `id` = ?");
    $stmt->bind_param("i", $pid);
    $stmt->execute();
    $plan = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if (!$plan) {
        alert("⚠️ پلن انتخابی معتبر نیست.");
        exit();
    }
    
    $totalPrice = $plan['price'];
    $discounts = json_decode($userInfo['discount_percent'], true) ?? [];
    if (($botState['agencyPlanDiscount'] ?? "") == "on") {
        $discount = $discounts['plans'][$pid] ?? ($discounts['normal'] ?? 0);
    } else {
        $discount = $discounts['servers'][$sid] ?? ($discounts['normal'] ?? 0);
    }
    $totalPrice -= floor($totalPrice * $discount / 100);

    $volume = $plan['volume'];
    $limit = $plan['acount'];
    $days = $plan['days'];
    
    $hash_id = RandomString(12);
    
    $timeVal = time();
    $stmt = $connection->prepare("INSERT INTO `pays` (`user_id`, `price`, `volume`, `day`, `type`, `state`, `hash_id`, `plan_id`, `request_date`) VALUES (?, ?, ?, ?, 'BUY_AGENT_QUOTA', 'pending', ?, ?, ?)");
    $stmt->bind_param("iiiisii", $from_id, $totalPrice, $volume, $limit, $hash_id, $pid, $timeVal);
    $stmt->execute();
    $stmt->close();
    
    $totalPriceFa = number_format($totalPrice) . " تومان";
    $discountText = "";
    if ($discount > 0) {
        $discountText = "🎁 تخفیف شما: <code>$discount%</code>\n";
    }
    
    $limitTxt = ($limit == 0) ? "نامحدود" : "$limit عدد";
    $invoiceText = "🛍 <b>فاکتور خرید سهمیه نمایندگی:</b>\n\n"
                 . "📦 پلن انتخابی: <b>{$plan['title']}</b>\n"
                 . "📊 میزان حجم سهمیه: <code>$volume GB</code>\n"
                 . "👤 تعداد اکانت مجاز: <code>$limitTxt</code>\n"
                 . "⏰ تمدید اعتبار نمایندگی: <code>$days روز</code>\n"
                 . $discountText
                 . "━━━━━━━━━━━━━━\n"
                 . "💰 مبلغ قابل پرداخت: <b>$totalPriceFa</b>";
    
    $keyboard = [];
    if ($botState['cartToCartState'] == "on") {
        $keyboard[] = [['text' => "💳 پرداخت کارت به کارت", 'callback_data' => "payAgentQuotaWithCartToCart_{$hash_id}_{$sid}"]];
    }
    $keyboard[] = [['text' => "👛 پرداخت از کیف پول (" . number_format($userInfo['wallet']) . " تومان)", 'callback_data' => "payAgentQuotaWithWallet_{$hash_id}_{$sid}"]];
    if (($botState['stars'] ?? '') == "on") {
        $keyboard[] = [['text' => "⭐ پرداخت با ستاره تلگرام", 'callback_data' => "payAgentQuotaWithStars_{$hash_id}_{$sid}"]];
    }
    $keyboard[] = [['text' => "❌ انصراف", 'callback_data' => "agentCustomConfigPanel_{$sid}"]];
    
    editText($message_id, $invoiceText, json_encode(['inline_keyboard' => $keyboard]), "HTML");
    exit();
}

if (preg_match('/^payAgentQuotaWithWallet_(?<hash>[a-zA-Z0-9]+)_(?<sid>\d+)/', (string)$data, $match) && $userInfo['is_agent'] == 1) {
    $hash = $match['hash'];
    $sid = $match['sid'];
    
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ? AND `state` = 'pending'");
    $stmt->bind_param("s", $hash);
    $stmt->execute();
    $pay_info = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if (!$pay_info) {
        alert("⚠️ فاکتور یافت نشد یا قبلاً پرداخت شده است.");
        exit();
    }
    
    $totalPrice = $pay_info['price'];
    if ($userInfo['wallet'] < $totalPrice) {
        alert("⚠️ موجودی کیف پول شما کافی نیست.");
        exit();
    }
    
    $stmt = $connection->prepare("UPDATE `users` SET `wallet` = `wallet` - ? WHERE `userid` = ?");
    $stmt->bind_param("ii", $totalPrice, $from_id);
    $stmt->execute();
    $stmt->close();
    
    $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'approved' WHERE `hash_id` = ?");
    $stmt->bind_param("s", $hash);
    $stmt->execute();
    $stmt->close();
    
    $vol_added = $pay_info['volume'];
    $lim_added = $pay_info['day'];
    
    $pid = $pay_info['plan_id'];
    $stmt = $connection->prepare("SELECT days FROM `server_plans` WHERE `id` = ?");
    $stmt->bind_param("i", $pid);
    $stmt->execute();
    $pDays = $stmt->get_result()->fetch_assoc()['days'] ?? 30;
    $stmt->close();
    
    $extend_seconds = $pDays * 86400;
    $current_agent_date = intval($userInfo['agent_date']);
    $new_agent_date = ($current_agent_date > time()) ? ($current_agent_date + $extend_seconds) : (time() + $extend_seconds);
    
    $stmt = $connection->prepare("UPDATE `users` SET `agent_volume` = `agent_volume` + ?, `agent_limit` = `agent_limit` + ?, `agent_date` = ? WHERE `userid` = ?");
    $stmt->bind_param("diii", $vol_added, $lim_added, $new_agent_date, $from_id);
    $stmt->execute();
    $stmt->close();
    
    $limAddedTxt = ($lim_added == 0) ? "نامحدود" : "$lim_added عدد";
    $msgAdmin = "📢 <b>خرید سهمیه نمایندگی (کیف پول):</b>\n\n"
              . "👤 نماینده: {$first_name} (@{$username})\n"
              . "🆔 آیدی: <code>$from_id</code>\n"
              . "📊 حجم: <code>$vol_added GB</code>\n"
              . "👤 تعداد اکانت: <code>$limAddedTxt</code>\n"
              . "💰 مبلغ پرداخت شده: <code>" . number_format($totalPrice) . " تومان</code>\n"
              . "✅ سهمیه به‌طور خودکار شارژ شد.";
    sendMessage($msgAdmin, null, "HTML", $admin);
    
    alert("✅ پرداخت با موفقیت انجام شد و سهمیه نمایندگی شما فعال گردید.");
    
    $userInfo['agent_volume'] += $vol_added;
    $userInfo['agent_limit'] += $lim_added;
    $userInfo['agent_date'] = $new_agent_date;
    
    $data = "agentCustomConfigPanel_{$sid}";
}

if (preg_match('/^payAgentQuotaWithStars_(?<hash>[a-zA-Z0-9]+)_(?<sid>\d+)/', (string)$data, $match) && $userInfo['is_agent'] == 1) {
    $hash = $match['hash'];
    $sid = $match['sid'];
    
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ? AND `state` = 'pending'");
    $stmt->bind_param("s", $hash);
    $stmt->execute();
    $payInfo = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if (!$payInfo) {
        alert("⚠️ فاکتور یافت نشد یا قبلاً پرداخت شده است.");
        exit();
    }
    
    $price_toman = $payInfo['price'];
    $star_rate = 2210;
    $stars_amount = ceil($price_toman / $star_rate);
    if ($stars_amount < 1) $stars_amount = 1;

    $invoice_payload = [
        'chat_id' => $from_id,
        'title' => 'خرید سهمیه نمایندگی',
        'description' => "فاکتور خرید سهمیه نمایندگی\nمبلغ تومانی: " . number_format($price_toman) . " تومان",
        'payload' => "agentstars_" . $hash . "_" . $sid,
        'provider_token' => "", 
        'currency' => 'XTR',
        'prices' => json_encode([['label' => 'پرداخت با ستاره', 'amount' => $stars_amount]])
    ];
    
    bot('sendInvoice', $invoice_payload);
    exit();
}

if (preg_match('/^payAgentQuotaWithCartToCart_(?<hash>[a-zA-Z0-9]+)_(?<sid>\d+)/', (string)$data, $match) && $userInfo['is_agent'] == 1) {
    $hash = $match['hash'];
    $sid = $match['sid'];
    
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ? AND `state` = 'pending'");
    $stmt->bind_param("s", $hash);
    $stmt->execute();
    $pay_info = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if (!$pay_info) {
        alert("⚠️ فاکتور یافت نشد یا قبلاً پرداخت شده است.");
        exit();
    }
    
    $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'CARD_INFO'");
    $stmt->execute();
    $card_info = $stmt->get_result()->fetch_assoc()['value'] ?? "";
    $stmt->close();
    
    $card_text = "💳 لطفاً مبلغ <b>" . number_format($pay_info['price']) . " تومان</b> را به شماره کارت زیر واریز کرده و <b>عکس فیش واریزی</b> را در قالب تصویر برای من ارسال کنید:\n\n" . $card_info;
    
    $kb = json_encode(['inline_keyboard' => [[['text' => "❌ انصراف", 'callback_data' => "agentCustomConfigPanel_{$sid}"]]]]);
    editText($message_id, $card_text, $kb, "HTML");
    setUser("enterAgentQuotaReceipt_" . json_encode(['hash' => $hash, 'sid' => $sid, 'prompt_id' => $message_id], JSON_UNESCAPED_UNICODE));
    exit();
}

if (preg_match('/^enterAgentQuotaReceipt_(?<json>.*)/', (string)$userInfo['step'], $match) && $text != $buttonValues['cancel']) {
    $d = json_decode($match['json'], true);
    $hash = $d['hash'];
    $sid = $d['sid'];
    $prompt_id = $d['prompt_id'];
    
    if (isset($fileid)) {
        bot('deleteMessage', ['chat_id' => $from_id, 'message_id' => $message_id]);
        
        $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
        $stmt->bind_param("s", $hash);
        $stmt->execute();
        $pay_info = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        
        $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'send', `description` = ? WHERE `hash_id` = ?");
        $stmt->bind_param("ss", $fileid, $hash);
        $stmt->execute();
        $stmt->close();
        
        $admin_keys = json_encode(['inline_keyboard' => [
            [
                ['text' => "✅ تایید پرداخت", 'callback_data' => "approveAgentQuota_{$hash}_{$sid}"],
                ['text' => "❌ رد پرداخت", 'callback_data' => "declineAgentQuota_{$hash}_{$sid}"]
            ]
        ]]);
        
        $acountTxt = ($pay_info['day'] == 0) ? "نامحدود" : $pay_info['day'] . " عدد";
        $admin_msg = "📥 <b>درخواست خرید سهمیه نمایندگی (کارت به کارت):</b>\n\n"
                     . "👤 نماینده: {$first_name} (@{$username})\n"
                     . "🆔 آیدی: <code>$from_id</code>\n"
                     . "📊 حجم درخواستی: <code>" . $pay_info['volume'] . " GB</code>\n"
                     . "👤 تعداد اکانت: <code>$acountTxt</code>\n"
                     . "💰 مبلغ واریزی: <code>" . number_format($pay_info['price']) . " تومان</code>\n";
        
        sendPhoto($fileid, $admin_msg, $admin_keys, "HTML", $admin);
        
        bot('editMessageText', [
            'chat_id' => $from_id,
            'message_id' => $prompt_id,
            'text' => "⏳ رسید شما با موفقیت ارسال شد و در انتظار تایید مدیریت است.",
            'reply_markup' => json_encode(['inline_keyboard' => [[['text' => "ورود به پنل نمایندگی", 'callback_data' => "agentCustomConfigPanel_{$sid}"]]]]),
            'parse_mode' => "HTML"
        ]);
        setUser("none");
        exit();
    } else {
        bot('deleteMessage', ['chat_id' => $from_id, 'message_id' => $message_id]);
        $kb = json_encode(['inline_keyboard' => [[['text' => "❌ انصراف", 'callback_data' => "agentCustomConfigPanel_{$sid}"]]]]);
        bot('editMessageText', [
            'chat_id' => $from_id,
            'message_id' => $prompt_id,
            'text' => "⚠️ لطفا فقط فیش واریزی را به صورت <b>تصویر</b> ارسال کنید.",
            'reply_markup' => $kb,
            'parse_mode' => "HTML"
        ]);
        exit();
    }
}

if (preg_match('/^approveAgentQuota_(?<hash>[a-zA-Z0-9]+)_(?<sid>\d+)/', (string)$data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $hash = $match['hash'];
    $sid = $match['sid'];
    
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ? AND `state` = 'send'");
    $stmt->bind_param("s", $hash);
    $stmt->execute();
    $pay_info = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if (!$pay_info) {
        alert("⚠️ این درخواست قبلاً پردازش شده یا یافت نشد.");
        exit();
    }
    
    $agent_id = $pay_info['user_id'];
    $vol_added = $pay_info['volume'];
    $lim_added = $pay_info['day'];
    
    $pid = $pay_info['plan_id'];
    $stmt = $connection->prepare("SELECT days FROM `server_plans` WHERE `id` = ?");
    $stmt->bind_param("i", $pid);
    $stmt->execute();
    $pDays = $stmt->get_result()->fetch_assoc()['days'] ?? 30;
    $stmt->close();
    
    $stmt = $connection->prepare("SELECT * FROM `users` WHERE `userid` = ?");
    $stmt->bind_param("i", $agent_id);
    $stmt->execute();
    $agentInfo = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    $extend_seconds = $pDays * 86400;
    $current_agent_date = intval($agentInfo['agent_date']);
    $new_agent_date = ($current_agent_date > time()) ? ($current_agent_date + $extend_seconds) : (time() + $extend_seconds);
    
    $stmt = $connection->prepare("UPDATE `users` SET `agent_volume` = `agent_volume` + ?, `agent_limit` = `agent_limit` + ?, `agent_date` = ? WHERE `userid` = ?");
    $stmt->bind_param("diii", $vol_added, $lim_added, $new_agent_date, $agent_id);
    $stmt->execute();
    $stmt->close();
    
    $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'approved' WHERE `hash_id` = ?");
    $stmt->bind_param("s", $hash);
    $stmt->execute();
    $stmt->close();
    
    editKeys(json_encode(['inline_keyboard' => [[['text' => "پرداخت تایید شد ✅", 'callback_data' => "NetFreedomVPN"]]]]));
    
    $limAddedTxt = ($lim_added == 0) ? "نامحدود" : "$lim_added عدد";
    $notify_msg = "🎉 <b>سهمیه نمایندگی شما فعال شد!</b>\n\n"
                . "📊 میزان حجم افزوده شده: <code>$vol_added GB</code>\n"
                . "👤 اکانت‌های قابل ساخت افزوده شده: <code>$limAddedTxt</code>\n"
                . "⏰ تاریخ انقضا نمایندگی تمدید شد.\n\n"
                . "🔋 سهمیه شما با موفقیت شارژ شد.";
    sendMessage($notify_msg, json_encode(['inline_keyboard' => [[['text' => "ورود به بخش نمایندگی", 'callback_data' => "agentCustomConfigPanel_{$sid}"]]]]), "HTML", $agent_id);
    exit();
}

if (preg_match('/^declineAgentQuota_(?<hash>[a-zA-Z0-9]+)_(?<sid>\d+)/', (string)$data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $hash = $match['hash'];
    $sid = $match['sid'];
    
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ? AND `state` = 'send'");
    $stmt->bind_param("s", $hash);
    $stmt->execute();
    $pay_info = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if (!$pay_info) {
        alert("⚠️ این درخواست قبلاً پردازش شده یا یافت نشد.");
        exit();
    }
    
    $agent_id = $pay_info['user_id'];
    
    $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'declined' WHERE `hash_id` = ?");
    $stmt->bind_param("s", $hash);
    $stmt->close();
    
    editKeys(json_encode(['inline_keyboard' => [[['text' => "پرداخت رد شد ❌", 'callback_data' => "NetFreedomVPN"]]]]));
    
    sendMessage("⚠️ فیش واریزی شما برای خرید سهمیه نمایندگی توسط مدیریت رد شد.", null, "HTML", $agent_id);
    exit();
}

// ----------------------------------------
// ۳. شروع فرآیند ساخت کانفیگ جدید (کسر از سهمیه)
// ترتیب: نام کانفیگ → حجم → روز → IP Limit → ساخت
// ----------------------------------------
if (preg_match('/^agentCreateConfig_start_(?<sid>\d+)/', (string)$data, $match) && $userInfo['is_agent'] == 1) {
    $sid = $match['sid'];

    if (intval($userInfo['agent_limit'] ?? 0) < 0) {
        alert("⚠️ سهمیه تعداد اکانت‌های قابل ساخت شما به پایان رسیده است. لطفا سهمیه جدید خریداری کنید.");
        exit();
    }
    if (floatval($userInfo['agent_volume'] ?? 0) < 0) {
        alert("⚠️ سهمیه حجم باقی‌مانده شما به پایان رسیده است. لطفا سهمیه جدید خریداری کنید.");
        exit();
    }

    // مرحله اول: نام کانفیگ خودکار ساخته شده و از مراحل حذف می‌شود.
    $remark = "agency-{$from_id}-" . rand(10000, 99999);
    $agentVol = floatval($userInfo['agent_volume'] ?? 0);
    $volHint  = ($agentVol > 0) ? " (سهمیه شما: " . number_format($agentVol, 1) . " GB)" : " (نامحدود)";
    $kb = json_encode(['inline_keyboard' => [[['text' => "❌ انصراف", 'callback_data' => "agentCustomConfigPanel_{$sid}"]]]]);
    
    editText($message_id,
        "🔋 <b>مرحله ۱ از ۳ - حجم کانفیگ:</b>{$volHint}\n\nلطفاً حجم را به <b>گیگابایت (GB)</b> وارد کنید:",
        $kb, "HTML");
    setUser("agentCfg2_vol_{$sid}_{$remark}_{$message_id}");
    exit();
}

// مرحله ۲: دریافت حجم
if (preg_match('/^agentCfg2_vol_(\d+)_([a-zA-Z0-9\-]+)_(\d+)$/', (string)$userInfo['step'], $match) && $text != $buttonValues['cancel']) {
    $sid       = $match[1];
    $remark    = $match[2];
    $prompt_id = intval($match[3]);
    bot('deleteMessage', ['chat_id' => $from_id, 'message_id' => $message_id]);

    $agentVolume   = floatval($userInfo['agent_volume'] ?? 0);
    $enteredVolume = intval($text);
    $volumeInvalid = !is_numeric($text) || $enteredVolume <= 0 || ($agentVolume > 0 && $enteredVolume > $agentVolume);

    if ($volumeInvalid) {
        $volHint = ($agentVolume > 0) ? " (سهمیه: " . number_format($agentVolume, 1) . " GB)" : " (نامحدود)";
        $kb = json_encode(['inline_keyboard' => [[['text' => "❌ انصراف", 'callback_data' => "agentCustomConfigPanel_{$sid}"]]]]);
        bot('editMessageText', [
            'chat_id' => $from_id, 'message_id' => $prompt_id,
            'text' => "⚠️ حجم نامعتبر است{$volHint}!\n\n🔋 <b>حجم کانفیگ (GB):</b>",
            'reply_markup' => $kb, 'parse_mode' => "HTML"
        ]);
        exit();
    }

    $kb = json_encode(['inline_keyboard' => [[['text' => "❌ انصراف", 'callback_data' => "agentCustomConfigPanel_{$sid}"]]]]);
    bot('editMessageText', [
        'chat_id' => $from_id, 'message_id' => $prompt_id,
        'text' => "⏰ <b>مرحله ۳ از ۴ - مدت اعتبار:</b>\n\nلطفاً تعداد روز اعتبار کانفیگ را وارد کنید (مثال: <code>30</code>):",
        'reply_markup' => $kb, 'parse_mode' => "HTML"
    ]);
    setUser("agentCfg3_days_{$sid}_{$remark}_{$enteredVolume}_{$prompt_id}");
    exit();
}

// مرحله ۳: دریافت تعداد روز
if (preg_match('/^agentCfg3_days_(\d+)_([a-zA-Z0-9\-]+)_(\d+)_(\d+)$/', (string)$userInfo['step'], $match) && $text != $buttonValues['cancel']) {
    $sid       = $match[1];
    $remark    = $match[2];
    $volume    = intval($match[3]);
    $prompt_id = intval($match[4]);
    bot('deleteMessage', ['chat_id' => $from_id, 'message_id' => $message_id]);

    if (!is_numeric($text) || intval($text) <= 0) {
        $kb = json_encode(['inline_keyboard' => [[['text' => "❌ انصراف", 'callback_data' => "agentCustomConfigPanel_{$sid}"]]]]);
        bot('editMessageText', [
            'chat_id' => $from_id, 'message_id' => $prompt_id,
            'text' => "⚠️ لطفاً یک عدد بزرگتر از صفر وارد کنید:\n\n⏰ <b>مدت اعتبار (روز):</b>",
            'reply_markup' => $kb, 'parse_mode' => "HTML"
        ]);
        exit();
    }

    $days = intval($text);
    $kb = json_encode(['inline_keyboard' => [
        [['text' => "♾️ بدون محدودیت (0)", 'callback_data' => "agentCfg4ip_{$sid}_{$remark}_{$volume}_{$days}_{$prompt_id}_0"]],
        [['text' => "❌ انصراف", 'callback_data' => "agentCustomConfigPanel_{$sid}"]]
    ]]);
    bot('editMessageText', [
        'chat_id' => $from_id, 'message_id' => $prompt_id,
        'text' => "🧲 <b>مرحله ۴ از ۴ - IP Limit:</b>\n\nتعداد اتصال هم‌زمان (0 = نامحدود):\nمثال: <code>1</code> یا <code>2</code>",
        'reply_markup' => $kb, 'parse_mode' => "HTML"
    ]);
    setUser("agentCfg4_ip_{$sid}_{$remark}_{$volume}_{$days}_{$prompt_id}");
    exit();
}

// مرحله ۴ الف: IP Limit از دکمه
if (preg_match('/^agentCfg4ip_(\d+)_([a-zA-Z0-9\-]+)_(\d+)_(\d+)_(\d+)_(\d+)$/', (string)$data, $match) && $userInfo['is_agent'] == 1) {
    $sid       = $match[1];
    $remark    = $match[2];
    $volume    = intval($match[3]);
    $days      = intval($match[4]);
    $prompt_id = intval($match[5]);
    $limitip   = intval($match[6]);
    goto agentBuildConfig;
}

// مرحله ۴ ب: IP Limit دستی
if (preg_match('/^agentCfg4_ip_(\d+)_([a-zA-Z0-9\-]+)_(\d+)_(\d+)_(\d+)$/', (string)$userInfo['step'], $match) && $text != $buttonValues['cancel']) {
    $sid       = $match[1];
    $remark    = $match[2];
    $volume    = intval($match[3]);
    $days      = intval($match[4]);
    $prompt_id = intval($match[5]);
    bot('deleteMessage', ['chat_id' => $from_id, 'message_id' => $message_id]);

    if (!is_numeric($text) || intval($text) < 0) {
        $kb = json_encode(['inline_keyboard' => [
            [['text' => "♾️ بدون محدودیت (0)", 'callback_data' => "agentCfg4ip_{$sid}_{$remark}_{$volume}_{$days}_{$prompt_id}_0"]],
            [['text' => "❌ انصراف", 'callback_data' => "agentCustomConfigPanel_{$sid}"]]
        ]]);
        bot('editMessageText', [
            'chat_id' => $from_id, 'message_id' => $prompt_id,
            'text' => "⚠️ لطفاً یک عدد معتبر (0 یا بیشتر) وارد کنید:\n\n🧲 <b>IP Limit:</b>",
            'reply_markup' => $kb, 'parse_mode' => "HTML"
        ]);
        exit();
    }

    $limitip = intval($text);
    goto agentBuildConfig;
}

// ---- ساخت نهایی کانفیگ ----
agentBuildConfig:
if (isset($sid) && isset($remark) && isset($volume) && isset($days) && isset($limitip) && isset($prompt_id) && $userInfo['is_agent'] == 1) {
    $server_id = $sid;

    $agentVolume = floatval($userInfo['agent_volume'] ?? 0);
    $agentLimit  = intval($userInfo['agent_limit'] ?? 0);

    $volumeExceeded = ($agentVolume > 0) && ($agentVolume < $volume);
    $limitExceeded  = ($agentLimit > 0) && ($agentLimit < 1);
    if ($volumeExceeded || $limitExceeded) {
        bot('editMessageText', [
            'chat_id' => $from_id, 'message_id' => $prompt_id,
            'text' => "❌ خطا: موجودی سهمیه شما برای ساخت این کانفیگ کافی نیست.",
            'reply_markup' => json_encode(['inline_keyboard' => [[['text' => "بازگشت به نمایندگی", 'callback_data' => "agentCustomConfigPanel_{$sid}"]]]]),
            'parse_mode' => "HTML"
        ]);
        setUser("none");
        exit();
    }

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

    $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'];
    $panelUrl    = rtrim($serverConfig['panel_url'], '/');
    $apiToken    = trim($serverConfig['password']);
    $parsedUrl   = parse_url($panelUrl);
    $panelHost   = $parsedUrl['host'] ?? '';
    $panelScheme = $parsedUrl['scheme'] ?? 'https';

    $configLinks = [];
    $clientSubId = "";
    $clientUuid  = "";

    bot('editMessageText', [
        'chat_id' => $from_id, 'message_id' => $prompt_id,
        'text' => "⏳ در حال ساخت کانفیگ و ارتباط با سرور... لطفاً شکیبا باشید.",
        'reply_markup' => null, 'parse_mode' => "HTML"
    ]);

    $finalEmail   = $remark . "@tg.com";
    $volumeBytes  = intval($volume) * 1073741824;
    $expiryTimeMs = $days > 0 ? (time() + ($days * 86400)) * 1000 : 0;

    if ($serverType == "marzban") {
        $response = addMarzbanUser($server_id, $remark, $volume, $days, 0);
        if (is_object($response) && isset($response->sub_link)) {
            $configLinks[] = $panelUrl . $response->sub_link;
            $clientSubId = $clientUuid = str_replace("/sub/", "", $response->sub_link);
        }
    } else {
        $allInboundIds = [];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $panelUrl . '/panel/api/inbounds/list');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json', 'Authorization: Bearer ' . $apiToken]);
        $listRes = curl_exec($ch);
        curl_close($ch);
        $listDec = json_decode($listRes, true);
        if (isset($listDec['success']) && $listDec['success'] && is_array($listDec['obj'])) {
            foreach ($listDec['obj'] as $inb) {
                if (isset($inb['enable']) && $inb['enable'] == true) {
                    $allInboundIds[] = intval($inb['id']);
                }
            }
        }
        if (empty($allInboundIds)) {
            $allInboundIds = [1];
        }

        $clientUuid = generateUID();
        $postData = [
            "client" => [
                "email"      => $finalEmail,
                "totalGB"    => $volumeBytes,
                "expiryTime" => $expiryTimeMs,
                "tgId"       => intval($from_id),
                "limitIp"    => intval($limitip),
                "enable"     => true
            ],
            "inboundIds" => $allInboundIds
        ];$response = addInboundAccount($server_id, $clientUuid, $allInboundIds[0], $expiryTimeMs, $remark, $volume, $limitip, null, $fid);
        if (is_object($response) && $response->success) {
            $clientSubId = basename($response->subLink);
            $subDec = callXuiApi($serverConfig, '/panel/api/clients/links/' . urlencode($remark));
            if ($subDec && isset($subDec->success) && $subDec->success && is_array($subDec->obj)) {
                $configLinks = $subDec->obj;
            }
        }
    }

    if (empty($clientSubId) && !empty($clientUuid)) {
        $clientSubId = $clientUuid;
    }

    if (empty($configLinks) && $clientUuid != "") {
        $configLinks[] = "vless://{$clientUuid}@{$panelHost}:2096?type=tcp&security=none#{$remark}";
    }

    if (empty($configLinks)) {
        bot('editMessageText', [
            'chat_id' => $from_id, 'message_id' => $prompt_id,
            'text' => "❌ متاسفانه ارتباط با سرور برقرار نشد یا اکانتی با این ریمارک از قبل وجود دارد.",
            'reply_markup' => json_encode(['inline_keyboard' => [[['text' => "بازگشت به نمایندگی", 'callback_data' => "agentCustomConfigPanel_{$sid}"]]]]),
            'parse_mode' => "HTML"
        ]);
        setUser("none");
        exit();
    }

    $filteredLinks = [];
    if ($serverType != "marzban") {
        $inbound1Port = null;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $panelUrl . '/panel/api/inbounds/get/1');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json', 'Authorization: Bearer ' . $apiToken]);
        $inb1Res = curl_exec($ch);
        curl_close($ch);
        $inb1Dec = json_decode($inb1Res, true);
        if (isset($inb1Dec['success']) && $inb1Dec['success'] && isset($inb1Dec['obj']['port'])) {
            $inbound1Port = intval($inb1Dec['obj']['port']);
        }

        if ($inbound1Port !== null && !empty($configLinks)) {
            foreach ($configLinks as $link) {
                if (strpos($link, 'vmess://') === 0) {
                    $base64Part = substr($link, 8);
                    $decoded = json_decode(base64_decode($base64Part), true);
                    if (isset($decoded['port']) && intval($decoded['port']) == $inbound1Port) {
                        $filteredLinks[] = $link;
                    }
                } else {
                    if (strpos($link, ":" . $inbound1Port) !== false) {
                        $filteredLinks[] = $link;
                    }
                }
            }
        }
    }

    if (empty($filteredLinks) && !empty($configLinks)) {
        $filteredLinks = [$configLinks[0]];
    }

    $directSubLink = "{$panelScheme}://{$panelHost}:2096/sub/{$clientSubId}";

    if ($agentVolume > 0 && $agentLimit > 0) {
        $stmt = $connection->prepare("UPDATE `users` SET `agent_volume` = `agent_volume` - ?, `agent_limit` = `agent_limit` - 1, `agent_test_limit` = `agent_test_limit` + 1 WHERE `userid` = ?");
        $stmt->bind_param("di", $volume, $from_id);
    } elseif ($agentVolume > 0) {
        $stmt = $connection->prepare("UPDATE `users` SET `agent_volume` = `agent_volume` - ?, `agent_test_limit` = `agent_test_limit` + 1 WHERE `userid` = ?");
        $stmt->bind_param("di", $volume, $from_id);
    } elseif ($agentLimit > 0) {
        $stmt = $connection->prepare("UPDATE `users` SET `agent_limit` = `agent_limit` - 1, `agent_test_limit` = `agent_test_limit` + 1 WHERE `userid` = ?");
        $stmt->bind_param("i", $from_id);
    } else {
        $stmt = $connection->prepare("UPDATE `users` SET `agent_test_limit` = `agent_test_limit` + 1 WHERE `userid` = ?");
        $stmt->bind_param("i", $from_id);
    }
    $stmt->execute();
    $stmt->close();

    $date        = time();
    $expire_date = ($days > 0) ? $date + (86400 * $days) : 0;
    $linkForDb   = json_encode($filteredLinks, JSON_UNESCAPED_UNICODE);
    $eachPrice   = 0;

    $stmt = $connection->prepare("INSERT INTO `orders_list`
        (`userid`, `token`, `transid`, `fileid`, `server_id`, `inbound_id`, `remark`, `uuid`, `protocol`, `expire_date`, `link`, `amount`, `status`, `date`, `notif`, `rahgozar`, `agent_bought`)
        VALUES (?, ?, '', 0, ?, 0, ?, ?, 'vless/vmess/trojan', ?, ?, ?, 1, ?, 0, 0, 1);");
    $stmt->bind_param("isissisii", $from_id, $clientSubId, $server_id, $remark, $clientSubId, $expire_date, $linkForDb, $eachPrice, $date);
    $stmt->execute();
    $stmt->close();

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

    $configLinesTxt = "";
    if (!empty($filteredLinks)) {
        $configLinesTxt = "💝 <b>config 1 :</b> <code>{$filteredLinks[0]}</code>\n\n";
    }

    $botUrl    = rtrim($botUrl, '/') . '/';
    $volumeTxt = ($volume == 0) ? "نامحدود" : $volume . " گیگ";
    $limitipTxt = ($limitip == 0) ? "نامحدود" : $limitip;
    $limitTxt  = ($agentLimit == 0) ? "نامحدود" : max(0, $agentLimit - 1) . " اکانت باقی‌مانده";

    $acc_text = "🎉 <b>سفارش جدید شما با موفقیت صادر شد!</b>\n"
              . "🔮 نام سرویس: <code>{$remark}</code>\n"
              . "🔋 حجم ترافیک مجاز: <code>{$volumeTxt}</code>\n"
              . "⏰ مدت اعتبار اکانت: <code>{$days} روز</code>\n\n"
              . "---------------------------------------\n\n"
              . $configLinesTxt
              . "🔋 <b>Volume web :</b> {$botUrl}search.php?id={$clientSubId}\n\n"
              . "🌐 <b>subscription :</b> <code>{$directSubLink}</code>";

    bot('deleteMessage', ['chat_id' => $from_id, 'message_id' => $prompt_id]);

    include_once 'phpqrcode/qrlib.php';
    $file = sys_get_temp_dir() . '/' . RandomString(10) . ".png";
    QRcode::png($directSubLink, $file, 'L', 10, 2);
    if (function_exists('addBorderImage')) addBorderImage($file);

    if (file_exists(dirname(__DIR__) . "/settings/QRCode.jpg")) {
        $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);
    }

    $photoResult = sendPhoto($file, $acc_text, json_encode(['inline_keyboard' => [[['text' => "ورود به بخش نمایندگی", 'callback_data' => "agentCustomConfigPanel_{$sid}"]]]]), "HTML", $from_id);
    error_log("[AGENT_CONFIG] sendPhoto result for user=$from_id: " . json_encode($photoResult) . " | file_exists=" . (file_exists($file) ? "yes" : "no") . " | caption_len=" . strlen($acc_text) . " | filteredLinks=" . count($filteredLinks));
    if (!isset($photoResult->ok) || !$photoResult->ok) {
        // اگر عکس ارسال نشد، فاکتور رو به صورت متنی بفرست
        sendMessage($acc_text, json_encode(['inline_keyboard' => [[['text' => "ورود به بخش نمایندگی", 'callback_data' => "agentCustomConfigPanel_{$sid}"]]]]), "HTML", $from_id);
    }
    if (file_exists($file)) unlink($file);

    // ارسال فایل .npvt برای NapsternetV
    sendNpvtDocument($filteredLinks, $remark, $from_id, $directSubLink);

    $msgAdmin = "📢 <b>ساخت کانفیگ جدید از سهمیه نمایندگی:</b>\n\n"
              . "👤 نماینده: {$first_name} (@{$username})\n"
              . "🆔 آیدی: <code>$from_id</code>\n"
              . "🖥 سرور میزبان: {$serverInfo['title']}\n"
              . "🎈 نام کانفیگ: <code>$remark</code>\n"
              . "🔋 حجم: <code>$volume GB</code>\n"
              . "⏰ مدت: <code>$days روز</code>\n"
              . "🧲 IP Limit: <code>{$limitipTxt}</code>\n"
              . "🔑 SubId: <code>{$clientSubId}</code>";
    sendMessage($msgAdmin, null, "HTML", $admin);

    setUser("none");
    exit();
}
// ----------------------------------------
// ۴. فرآیند ساخت اکانت تست ۱ گیگابایتی رایگان
// ----------------------------------------
// ۴. فرآیند ساخت اکانت تست ۱ گیگابایتی رایگان
// ----------------------------------------
if (preg_match('/^agentCreateTestConfig_start_(?<sid>\d+)/', (string)$data, $match) && $userInfo['is_agent'] == 1) {
    $sid = $match['sid'];
    
    if (($userInfo['agent_test_limit'] ?? 0) <= 0) {
        alert("⚠️ شما اکانت تست فعالی ندارید. با ساخت هر کانفیگ معمولی، یک عدد سهمیه اکانت تست رایگان کسب خواهید کرد.");
        exit();
    }
    
    $remark = "agency(Gift)-{$from_id}-" . rand(10000, 99999);
    createAgentTestConfig($sid, $remark, $message_id);
    exit();
}

// ۵. تابع ساخت اکانت تست نمایندگی با ساختار مشابه گیفت
function createAgentTestConfig($server_id, $remark, $prompt_id) {
    global $connection, $from_id, $first_name, $username, $admin, $botUrl, $userInfo, $buttonValues;
    
    // ۱. دریافت اطلاعات سرور
    $stmt = $connection->prepare("SELECT * FROM `server_info` WHERE `id` = ?");
    $stmt->bind_param("i", $server_id);
    $stmt->execute();
    $serverInfo = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if (!$serverInfo) {
        alert("❌ سرور مورد نظر یافت نشد.");
        exit;
    }
    
    $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'];
    $panelUrl = rtrim($serverConfig['panel_url'], '/');
    $apiToken = trim($serverConfig['password']);
    
    bot('editMessageText', [
        'chat_id' => $from_id,
        'message_id' => $prompt_id,
        'text' => "⏳ در حال ساخت اکانت تست روی سرور... لطفاً شکیبا باشید.",
        'reply_markup' => null,
        'parse_mode' => "HTML"
    ]);
    
    $volume = 1; // 1 GB
    $days = 1;   // 1 day
    $limitip = 1;
    
    $configLinks = [];
    $clientSubId = "";
    $clientUuid = "";
    
    if ($serverType == "marzban") {
        $response = addMarzbanUser($server_id, $remark, $volume, $days, 0);
        if (is_object($response) && isset($response->sub_link)) {
            $configLinks[] = $panelUrl . $response->sub_link;
            $clientSubId = $clientUuid = str_replace("/sub/", "", $response->sub_link);
        }
    } else {
        $clientUuid = generateUID();
        $expiryTimeMs = (time() + 86400) * 1000;
        $response = addInboundAccount($server_id, $clientUuid, 1, $expiryTimeMs, $remark, $volume, $limitip, null, 0);
        
        if (is_null($response) || !$response->success) {
            $errorDetails = isset($response->msg) ? $response->msg : "عدم پاسخگویی یا خطا در ارتباط با سرور";
            bot('editMessageText', [
                'chat_id' => $from_id,
                'message_id' => $prompt_id,
                'text' => "❌ خطا در صدور از سمت پنل سرور:\n$errorDetails",
                'reply_markup' => json_encode(['inline_keyboard' => [[['text' => "بازگشت به پنل نمایندگی", 'callback_data' => "agentCustomConfigPanel_{$server_id}"]]]]),
                'parse_mode' => "HTML"
            ]);
            setUser("none");
            exit;
        }
        
        $clientSubId = basename($response->subLink);
        
        // واکشی آنی تمام کانفیگ‌های اتصال متصل به این کاربر
        $subDecodedObj = callXuiApi($serverConfig, '/panel/api/clients/links/' . urlencode($remark));
        if ($subDecodedObj && isset($subDecodedObj->success) && $subDecodedObj->success && is_array($subDecodedObj->obj)) {
            $configLinks = $subDecodedObj->obj;
        }
    }
    
    // تولید مستقیم لینک سابسکریپشن رسمی خود پنل سنایی روی پورت ۲۰۹۶
    $parsedPanelUrl = parse_url($panelUrl);
    $panelHost = $parsedPanelUrl['host'] ?? '';
    $panelScheme = $parsedPanelUrl['scheme'] ?? 'https';
    $directSubLink = "{$panelScheme}://{$panelHost}:2096/sub/{$clientSubId}";
    
    // ساختار پیام
    $configLinesTxt = "";
    if (!empty($configLinks)) {
        $configLinesTxt = "💝 <b>config 1 :</b> <code>{$configLinks[0]}</code>\n\n";
    } else {
        $fallbackConfig = "vless://{$clientUuid}@{$panelHost}:2096?type=tcp&security=none#{$remark}";
        $configLinesTxt = "💝 <b>config 1 :</b> <code>{$fallbackConfig}</code>\n\n";
    }
    
    $acc_text = "🎉 <b>سفارش جدید شما با موفقیت صادر شد!</b>\n"
              . "🔮 نام سرویس: <code>{$remark}</code>\n"
              . "🔋 حجم ترافیک مجاز: <code>1 گیگ</code>\n"
              . "⏰ مدت اعتبار اکانت: <code>1 روز</code>\n\n"
              . "---------------------------------------\n\n"
              . $configLinesTxt
              . "🔋 <b>Volume web :</b> {$botUrl}search.php?id={$clientSubId}\n\n"
              . "🌐 <b>subscription :</b> <code>{$directSubLink}</code>";
              
    bot('deleteMessage', ['chat_id' => $from_id, 'message_id' => $prompt_id]);
    
    // تولید QR Code
    include_once 'phpqrcode/qrlib.php';
    $file = sys_get_temp_dir() . '/' . RandomString(10) . ".png";
    @QRcode::png($directSubLink, $file, 'L', 10, 2);
    
    if (file_exists($file) && file_exists(dirname(__DIR__) . "/settings/QRCode.jpg") && function_exists('imagecreatefromjpeg') && function_exists('imagecreatefrompng')) {
        try {
            $backgroundImage = @imagecreatefromjpeg(dirname(__DIR__) . "/settings/QRCode.jpg");
            $qrImage = @imagecreatefrompng($file);
            if ($backgroundImage && $qrImage) {
                $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);
            }
        } catch (Exception $e) {
            # ignore image errors
        }
    }
    
    $photoSent = false;
    if (file_exists($file)) {
        $resPhoto = sendPhoto($file, $acc_text, json_encode(['inline_keyboard' => [[['text' => "ورود به بخش نمایندگی", 'callback_data' => "agentCustomConfigPanel_{$server_id}"]]]]), "HTML", $from_id);
        if ($resPhoto && isset($resPhoto->ok) && $resPhoto->ok) {
            $photoSent = true;
        }
        @unlink($file);
    }
    
    if (!$photoSent) {
        sendMessage($acc_text, json_encode(['inline_keyboard' => [[['text' => "ورود به بخش نمایندگی", 'callback_data' => "agentCustomConfigPanel_{$server_id}"]]]]), "HTML", $from_id);
    }

    // ارسال فایل .npvt برای NapsternetV
    sendNpvtDocument($configLinks, $remark, $from_id, $directSubLink);
    
    // ثبت در دیتابیس
    $linkForDb = json_encode($configLinks, JSON_UNESCAPED_UNICODE);
    $eachPrice = 0;
    $date = time();
    $expire_date = $date + 86400;
    
    $stmt = $connection->prepare("INSERT INTO `orders_list` 
        (`userid`, `token`, `transid`, `fileid`, `server_id`, `inbound_id`, `remark`, `uuid`, `protocol`, `expire_date`, `link`, `amount`, `status`, `date`, `notif`, `rahgozar`, `agent_bought`)
        VALUES (?, ?, '', 1, ?, 0, ?, ?, 'vless', ?, ?, ?, 1, ?, 0, 0, 1);");
    $stmt->bind_param("isissisiii", $from_id, $clientSubId, $server_id, $remark, $clientUuid, $expire_date, $linkForDb, $eachPrice, $date);
    $stmt->execute();
    $stmt->close();
    
    // بروزرسانی موجودی سرور
    $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 `users` SET `agent_test_limit` = `agent_test_limit` - 1 WHERE `userid` = ?");
    $stmt->bind_param("i", $from_id);
    $stmt->execute();
    $stmt->close();
    
    $userInfo['agent_test_limit'] -= 1;
    
    $msgAdmin = "📢 <b>ساخت اکانت تست جدید توسط نماینده:</b>\n\n"
              . "👤 نماینده: {$first_name} (@{$username})\n"
              . "🆔 آیدی: <code>$from_id</code>\n"
              . "🖥 سرور میزبان: {$serverInfo['title']}\n"
              . "🎈 نام تست: <code>$remark</code>";
    sendMessage($msgAdmin, null, "HTML", $admin);
    
    setUser("none");
    exit();
}
