<?php
include_once __DIR__ . '/settings/config_xui_api.php';
include_once __DIR__ . '/settings/config_utils.php';
global $mainValues, $removeKeyboard, $buttonProps, $markup, $botState, $connection, $buttonValues, $botUrl, $admin, $userInfo,
 $from_id, $text, $data, $message_id, $cancelKey, $fullName, $fileid, $chat_id, $apiToken,$panelUrl, $limitip, $days, $volume, $inbound_id_raw,
 $serverType, $expire_date, $first_name, $rahgozar, $date, $directSubUrl;
$data = $data ?? '';
$text = $text ?? '';
$userInfo = $userInfo ?? [];

if (preg_match('/^changePaymentKeys(\w+)/', (string)$data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    delMessage();
    $gate = '';
    switch ($match[1]) {
        case "nextpay":
            $gate = "کد جدید درگاه نکست پی";
            break;
        case "nowpayment":
            $gate = "کد جدید درگاه nowPayment";
            break;
        case "zarinpal":
            $gate = "کد جدید درگاه زرین پال";
            break;
        case "bankAccount":
            $gate = "شماره حساب جدید";
            break;
        case "holderName":
            $gate = "اسم دارنده حساب";
            break;
        case "tronwallet":
            $gate = "آدرس والت ترون";
            break;
    }
    sendMessage("🔘|لطفا $gate را وارد کنید", $cancelKey);
    setUser($data);
}
if (preg_match('/^changePaymentKeys(\w+)/', (string)$userInfo['step'], $match) && $text != $buttonValues['cancel'] && ($from_id == $admin || $userInfo['isAdmin'] == true)) {

    $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'PAYMENT_KEYS'");
    $stmt->execute();
    $paymentInfo = $stmt->get_result();
    $stmt->close();
    $paymentKeys = json_decode($paymentInfo->fetch_assoc()['value'], true) ?? array();
    $paymentKeys[$match[1]] = $text;
    $paymentKeys = json_encode($paymentKeys);

    if ($paymentInfo->num_rows > 0)
        $stmt = $connection->prepare("UPDATE `setting` SET `value` = ? WHERE `type` = 'PAYMENT_KEYS'");
    else
        $stmt = $connection->prepare("INSERT INTO `setting` (`type`, `value`) VALUES ('PAYMENT_KEYS', ?)");
    $stmt->bind_param("s", $paymentKeys);
    $stmt->execute();
    $stmt->close();


    sendMessage($mainValues['saved_successfuly'], $removeKeyboard);
    sendMessage($mainValues['change_bot_settings_message'], getGateWaysKeys());
    setUser();
}

if (preg_match('/^edit(RewaredTime|cartToCartAutoAcceptTime)/', (string)$data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    delMessage();
    if ($match[1] == "RewaredTime")
        $txt = "🙃 | لطفا زمان تأخیر در ارسال گزارش رو به ساعت وارد کن\n\nنکته: هر n ساعت گزارش به ربات ارسال میشه! ";
    else
        $txt = "لطفا زمان مورد نظر را به دقیقه وارد کنید";

    sendMessage($txt, $cancelKey);
    setUser($data);
}
if ($data == "userReports" && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    delMessage();
    sendMessage("🙃 | لطفا آیدی عددی کاربر رو وارد کن", $cancelKey);
    setUser($data);
}
if ($userInfo['step'] == "userReports" && $text != $buttonValues['cancel'] && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    if (is_numeric($text)) {
        sendMessage($mainValues['please_wait_message'], $removeKeyboard);
        $keys = getUserInfoKeys($text);
        if ($keys != null) {
            sendMessage("اطلاعات کاربر <a href='tg://user?id=$text'>$fullName</a>", $keys, "html");
            setUser();
        }
        else
            sendMessage("کاربری با این آیدی یافت نشد");
    }
    else {
        sendMessage("😡|لطفا فقط عدد ارسال کن");
    }
}
if (preg_match('/^edit(RewaredTime|cartToCartAutoAcceptTime)/', (string)$userInfo['step'], $match) && ($from_id == $admin || $userInfo['isAdmin'] == true) && $text != $buttonValues['cancel']) {
    if (!is_numeric($text)) {
        sendMessage("لطفا عدد بفرستید");
        exit();
    }
    elseif ($text < 0) {
        sendMessage("مقدار وارد شده معتبر نیست");
        exit();
    }

    setSettings(lcfirst($match[1]), $text);
    sendMessage($mainValues['change_bot_settings_message'], getBotSettingKeys());
    setUser();
    exit();
}
if ($userInfo['step'] == "increaseMyWallet" && $text != $buttonValues['cancel']) {
    if (!is_numeric($text)) {
        sendMessage($mainValues['send_only_number']);
        exit();
    }
    elseif ($text < 5000) {
        sendMessage("لطفا مقداری بیشتر از 5000 وارد کن");
        exit();
    }
    sendMessage("🪄 لطفا صبور باشید ...", $removeKeyboard);
    $hash_id = RandomString();
    $stmt = $connection->prepare("DELETE FROM `pays` WHERE `user_id` = ? AND `type` = 'INCREASE_WALLET' AND `state` = 'pending'");
    $stmt->bind_param("i", $from_id);
    $stmt->execute();
    $stmt->close();

    $time = time();
    $stmt = $connection->prepare("INSERT INTO `pays` (`hash_id`, `user_id`, `type`, `plan_id`, `volume`, `day`, `price`, `request_date`, `state`)
                                VALUES (?, ?, 'INCREASE_WALLET', '0', '0', '0', ?, ?, 'pending')");
    $stmt->bind_param("siii", $hash_id, $from_id, $text, $time);
    $stmt->execute();
    $stmt->close();


    $keyboard = array();
    if ($botState['cartToCartState'] == "on")
        $keyboard[] = [['text' => $buttonValues['cart_to_cart'], 'callback_data' => "increaseWalletWithCartToCart" . $hash_id]];
    if ($botState['nowPaymentWallet'] == "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['tronWallet'] == "on")
        $keyboard[] = [['text' => $buttonValues['tron_gateway'], 'callback_data' => "payWithTronWallet" . $hash_id]];
    if ($botState['stars'] == "on")
        $keyboard[] = [['text' => $buttonValues['stars_gateway'], 'callback_data' => "payWithStars" . $hash_id]];

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


    $keys = json_encode(['inline_keyboard' => $keyboard]);
    sendMessage("اطلاعات شارژ:\nمبلغ " . number_format($text) . " تومان\n\nلطفا روش پرداخت را انتخاب کنید", $keys);
    setUser();
}
if (preg_match('/increaseWalletWithCartToCart(?<hashId>.*)/', (string)$data, $match)) {
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
    $stmt->bind_param('s', $match['hashId']);
    $stmt->execute();
    $payInfo = $stmt->get_result();
    $stmt->close();
    if ($payInfo->num_rows == 0) {
        $text = "/start";
        $data = "";
        delMessage();
    // goto GOTOSTART;
    }

    delMessage();
    setUser($data);

    sendMessage(str_replace(["ACCOUNT-NUMBER", "HOLDER-NAME"], [$paymentKeys['bankAccount'], $paymentKeys['holderName']], $mainValues['increase_wallet_cart_to_cart']), $cancelKey, "HTML");
    exit;
}
if (preg_match('/increaseWalletWithCartToCart(.*)/', (string)$userInfo['step'], $match) and $text != $buttonValues['cancel']) {
    // بررسی اینکه آیا فایلی دریافت شده است
    if ($fileid !== null) {
        setUser();
        $uid = $userInfo['userid'];
        $name = $userInfo['name'];
        $username = $userInfo['username'];

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

        $price = number_format($payInfo['price']);

        @bot('deleteMessage', ['chat_id' => $from_id, 'message_id' => $message_id]);
        @bot('deleteMessage', ['chat_id' => $from_id, 'message_id' => $message_id - 1]);
        sendMessage("✅ <b>رسید شما برای ادمین ارسال شد. منتظر تایید و صدور بمانید.</b>", getMainKeys(), "HTML");

        $msg = str_replace(['PRICE', 'USERNAME', 'NAME', 'USER-ID'], [$price, $username, $name, $from_id], $mainValues['increase_wallet_request_message']);

        // اگر کپشن داشت اضافه کن
        if (!empty($caption)) {
            $msg .= "\n\n📝 توضیحات: " . $caption;
        }

        $keyboard = json_encode([
            'inline_keyboard' => [
                [
                    [
                        'text' => $buttonValues['approve'], 
                        'callback_data' => "approvePayment{$match[1]}",
                        'style' => $buttonProps['approve']['style'] ?? 'success',
                        'icon_custom_emoji_id' => $buttonProps['approve']['icon_custom_emoji_id'] ?? null
                    ],
                    [
                        'text' => $buttonValues['decline'], 
                        'callback_data' => "decPayment{$match[1]}",
                        'style' => $buttonProps['decline']['style'] ?? 'danger',
                        'icon_custom_emoji_id' => $buttonProps['decline']['icon_custom_emoji_id'] ?? null
                    ]
                ]
            ]
        ]);

        // ارسال به ادمین اصلی
        $res = sendPhoto($fileid, $msg, $keyboard, "HTML", $admin);

        if (isset($res->result)) {
            $msgId = $res->result->message_id;
            $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'have_sent', `message_id` = ?, `chat_id` = ? WHERE `hash_id` = ?");
            $stmt->bind_param("iis", $msgId, $admin, $match[1]);
            $stmt->execute();
            $stmt->close();
        }

        // ارسال به سایر ادمین‌ها
        $stmt_admins = $connection->prepare("SELECT `userid` FROM `users` WHERE `isAdmin` = 1 AND `userid` != ?");
        $stmt_admins->bind_param("i", $admin);
        $stmt_admins->execute();
        $admins_result = $stmt_admins->get_result();

        while ($admin_row = $admins_result->fetch_assoc()) {
            sendPhoto($fileid, $msg, $keyboard, "HTML", $admin_row['userid']);
        }
        $stmt_admins->close();

    }
    else {
        sendMessage($mainValues['please_send_only_image']);
    }
}
// -----------------------------------------------------------------------
// 1. بخش تایید پرداخت (زمانی که دکمه تایید زده می‌شود)
// -----------------------------------------------------------------------
if (preg_match('/^approvePayment(.*)/', (string)$data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $hash_id = $match[1];

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

    if ($payInfo) {
        $price = $payInfo['price'];
        $userId = $payInfo['user_id'];

        // فقط اگر قبلاً تایید نشده باشد انجام بده
        if ($payInfo['state'] != "approved") {
            // آپدیت وضعیت پرداخت
            $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'approved' WHERE `hash_id` = ?");
            $stmt->bind_param("s", $hash_id);
            $stmt->execute();
            $stmt->close();

            // افزایش موجودی کاربر
            $stmt = $connection->prepare("UPDATE `users` SET `wallet` = `wallet` + ? WHERE `userid` = ?");
            $stmt->bind_param("ii", $price, $userId);
            $stmt->execute();
            $stmt->close();

            // پیام به کاربر
            sendMessage("✅ افزایش موجودی شما با موفقیت تأیید شد.\n💰 مبلغ " . number_format($price) . " تومان به کیف پول شما اضافه شد.", null, null, $userId);

            // تغییر دکمه پیام ادمین به "تایید شد"
            $doneKey = json_encode(['inline_keyboard' => [[['text' => 'تایید شد', 'callback_data' => "dontsendanymore", 'style' => 'success', 'icon_custom_emoji_id' => '5208880351690112495']]]]);
            bot('editMessageReplyMarkup', [
                'chat_id' => $chat_id,
                'message_id' => $message_id,
                'reply_markup' => $doneKey
            ]);
        }
        else {
            alert("این پرداخت قبلاً تایید شده است!");
        }
    }
}

// --- زمانی که ادمین دکمه عدم تایید را می‌زند ---
if (preg_match('/^decPayment(.*)/', (string)$data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    // ساخت دستی دکمه برای ذخیره در فایل تمپ (چون متغیر markup وجود نداشت)
    $keys = json_encode(['inline_keyboard' => [[['text' => 'رد شد', 'callback_data' => "dontsendanymore", 'style' => 'danger', 'icon_custom_emoji_id' => '5215680783863261658']]]]);
    file_put_contents("temp" . $from_id . ".txt", $keys);

    sendMessage("لطفا دلیل عدم تأیید را بنویسید:\n(یا دکمه برگشت را بزنید)", $cancelKey);
    // ذخیره مرحله به همراه آیدی پیام اصلی و هش تراکنش
    setUser("decPayment" . $message_id . "_" . $match[1]);
}

// --- زمانی که ادمین متن دلیل را می‌فرستد ---
if (preg_match('/^decPayment(\d+)_(.*)/', (string)$userInfo['step'], $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    if ($text != $buttonValues['cancel'] && !empty($text)) {
        $originalMsgId = $match[1]; // آیدی پیام عکس‌دار
        $hashId = $match[2]; // هش تراکنش

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

        if ($payInfo) {
            $price = $payInfo['price'];
            $userId = $payInfo['user_id'];

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

            // ارسال پیام به کاربر
            sendMessage("❌ درخواست افزایش موجودی شما به مبلغ " . number_format($price) . " تومان رد شد.\n\n💬 دلیل: $text", null, null, $userId);

            // تغییر دکمه پیام ادمین به "رد شد"
            if (file_exists("temp" . $from_id . ".txt")) {
                $savedKeys = file_get_contents("temp" . $from_id . ".txt");
                bot('editMessageReplyMarkup', [
                    'chat_id' => $chat_id,
                    'message_id' => $originalMsgId,
                    'reply_markup' => $savedKeys
                ]);
                unlink("temp" . $from_id . ".txt");
            }

            setUser();
            sendMessage('✅ پیام رد تراکنش ارسال شد.', $removeKeyboard);
            sendMessage($mainValues['reached_main_menu'], getMainKeys());
        }
        else {
            sendMessage("خطا: اطلاعات پرداخت پیدا نشد.");
            setUser();
        }
    }
}

// --- بخش‌های افزایش و کاهش دستی موجودی (بدون تغییر منطقی، فقط مرتب‌سازی) ---
if ($data == "increaseUserWallet" && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    delMessage();
    sendMessage($mainValues['send_user_id'], $cancelKey);
    setUser($data);
}
if ($userInfo['step'] == "increaseUserWallet" && ($from_id == $admin || $userInfo['isAdmin'] == true) && $text != $buttonValues['cancel']) {
    if (is_numeric($text)) {
        $stmt = $connection->prepare("SELECT * FROM `users` WHERE `userid` = ?");
        $stmt->bind_param("i", $text);
        $stmt->execute();
        $userCount = $stmt->get_result()->num_rows;
        $stmt->close();
        if ($userCount > 0) {
            setUser("increaseWalletUser" . $text);
            sendMessage($mainValues['enter_increase_amount']);
        }
        else {
            setUser();
            sendMessage($mainValues['user_not_found'], $removeKeyboard);
            sendMessage($mainValues['reached_main_menu'], getMainKeys());
        }
    }
    else {
        sendMessage($mainValues['send_only_number']);
    }
}
if (preg_match('/^increaseWalletUser(\d+)/', (string)$userInfo['step'], $match) && $text != $buttonValues['cancel'] && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    if (is_numeric($text)) {
        $stmt = $connection->prepare("UPDATE `users` SET `wallet` = `wallet` + ? WHERE `userid` = ?");
        $stmt->bind_param("ii", $text, $match[1]);
        $stmt->execute();
        $stmt->close();

        sendMessage("✅ مبلغ " . number_format($text) . " تومان به حساب شما اضافه شد", null, null, $match[1]);
        sendMessage("✅ مبلغ " . number_format($text) . " تومان به کیف پول کاربر مورد نظر اضافه شد", $removeKeyboard);
        sendMessage($mainValues['reached_main_menu'], getMainKeys());
        setUser();
    }
    else {
        sendMessage($mainValues['send_only_number']);
    }
}

if ($data == "decreaseUserWallet" && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    delMessage();
    sendMessage($mainValues['send_user_id'], $cancelKey);
    setUser($data);
}
if ($userInfo['step'] == "decreaseUserWallet" && ($from_id == $admin || $userInfo['isAdmin'] == true) && $text != $buttonValues['cancel']) {
    if (is_numeric($text)) {
        $stmt = $connection->prepare("SELECT * FROM `users` WHERE `userid` = ?");
        $stmt->bind_param("i", $text);
        $stmt->execute();
        $userCount = $stmt->get_result()->num_rows;
        $stmt->close();
        if ($userCount > 0) {
            setUser("decreaseWalletUser" . $text);
            sendMessage($mainValues['enter_decrease_amount']);
        }
        else {
            setUser();
            sendMessage($mainValues['user_not_found'], $removeKeyboard);
            sendMessage($mainValues['reached_main_menu'], getMainKeys());
        }
    }
    else {
        sendMessage($mainValues['send_only_number']);
    }
}
if (preg_match('/^decreaseWalletUser(\d+)/', (string)$userInfo['step'], $match) && $text != $buttonValues['cancel'] && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    if (is_numeric($text)) {
        $stmt = $connection->prepare("UPDATE `users` SET `wallet` = `wallet` - ? WHERE `userid` = ?");
        $stmt->bind_param("ii", $text, $match[1]);
        $stmt->execute();
        $stmt->close();

        sendMessage(str_replace("AMOUNT", number_format($text), $mainValues['amount_decreased_from_your_wallet']), null, null, $match[1]);
        sendMessage(str_replace("AMOUNT", number_format($text), $mainValues['amount_decreased_from_user_wallet']), $removeKeyboard);
        sendMessage($mainValues['reached_main_menu'], getMainKeys());
        setUser();
    }
    else {
        sendMessage($mainValues['send_only_number']);
    }
}
if (preg_match('/payWithTronWallet(.*)/', (string)$data, $match)) {
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]);
    $stmt->execute();
    $payInfo = $stmt->get_result();
    $stmt->close();

    if ($payInfo->num_rows == 0) {
        $text = "/start";
        $data = "";
        delMessage();
    //   goto GOTOSTART;
    }
    $payInfo = $payInfo->fetch_assoc();

    $fid = $payInfo['plan_id'];
    $type = $payInfo['type'];

    $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'];
    $acount = $file_detail['acount'];
    $inbound_id = $file_detail['inbound_id'];

    if ($type != "INCREASE_WALLET" && $type != "RENEW_ACCOUNT") {
        if ($acount <= 0 and $inbound_id != 0) {
            alert($mainValues['out_of_connection_capacity']);
            exit;
        }
        if ($inbound_id == 0) {
            $stmt = $connection->prepare("SELECT * FROM `server_info` WHERE `id`=?");
            $stmt->bind_param("i", $server_id);
            $stmt->execute();
            $server_info = $stmt->get_result()->fetch_assoc();
            $stmt->close();

            if ($server_info['ucount'] <= 0) {
                alert($mainValues['out_of_server_capacity']);
                exit;
            }
        }
        else {
            if ($acount <= 0) {
                alert($mainValues['out_of_server_capacity']);
                exit();
            }
        }
    }

    if ($type == "RENEW_ACCOUNT") {
        $oid = $payInfo['plan_id'];

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

    }

    delMessage();

    $price = $payInfo['price'];

    // --- اصلاح: جلوگیری از تقسیم بر صفر ---
    $trxRate = isset($botState['TRXRate']) ? (float)$botState['TRXRate'] : 0;

    if ($trxRate > 0) {
        $priceInTrx = round($price / $trxRate, 2);
    }
    else {
        // اگر نرخ صفر بود، عملیات را متوقف کن و پیام بده
        sendMessage("❌ خطای فنی: نرخ ارز (ترون) در سیستم تنظیم نشده است. لطفاً بعداً تلاش کنید یا به پشتیبانی اطلاع دهید.", getMainKeys());
        exit();
    }
    // -------------------------------------

    $stmt = $connection->prepare("UPDATE `pays` SET `tron_price` = ? WHERE `hash_id` = ?");
    $stmt->bind_param("ds", $priceInTrx, $match[1]);
    $stmt->execute();
    $stmt->close();

    sendMessage(str_replace(["AMOUNT", "TRON-WALLET"], [$priceInTrx, $paymentKeys['tronwallet']], $mainValues['pay_with_tron_wallet']), $cancelKey, "html");
    setUser($data);
}

if (preg_match('/^payWithTronWallet(.*)/', (string)$userInfo['step'], $match) && $text != $buttonValues['cancel']) {
    // تراز داینامیک شناسه فاکتور جهت جلوگیری از تداخل متغیرها
    $safe_hash_id = trim($match[1]);

    // بررسی ساختار استاندارد هش تراکنش رمزارزها (باید دقیقاً یک رشته ۶۴ کاراکتری هگزادسیمال باشد)
    if (!preg_match('/^[0-9a-f]{64}$/i', (string)$text)) {
        sendMessage($mainValues['incorrect_tax_id']);
        exit();
    }
    else {
        // ایمن‌سازی متن هش ورودی برای جلوگیری از باگ‌های تزریق کوئری
        $safe_tax_id = $connection->real_escape_string(trim($text));

        // ۱. بررسی زنده جهت جلوگیری از ثبت هش تکراری در سیستم
        $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `payid` = ?");
        $stmt->bind_param("s", $safe_tax_id); $stmt->execute();
        $checkExist = $stmt->get_result(); $stmt->close();

        if ($checkExist->num_rows == 0) {
            // ۲. آپدیت وضعیت فاکتور به حالت در حال بررسی (state = 0) با متد مستقیم ضد کرش MySQLi
            $safe_hash_db = $connection->real_escape_string($safe_hash_id);
            $updateQuery = "UPDATE `pays` SET `payid` = '{$safe_tax_id}', `state` = '0' WHERE `hash_id` = '{$safe_hash_db}'";
            $connection->query($updateQuery);

            // ارسال پیام تاییدیه ثبت به کلاینت و هدایت به منوی اصلی ربات
            sendMessage($mainValues['in_review_tax_id'], $removeKeyboard);
            setUser(); // ریست فوری استپ کاربر جهت خروج امن از لایه ترون
            sendMessage($mainValues['reached_main_menu'], getMainKeys());
            
            // 🔔 اطلاع‌رسانی خودکار به مدیریت ربات جهت بررسی هش ترون ارسالی جدید
            $keys = json_encode(['inline_keyboard' => [[['text' => "بررسی تراکنش‌های رمز‌ارز 🪙", 'callback_data' => "crypto_verify"]]]]);
            sendMessage("📥 <b>یک درخواست تایید تراکنش ترون جدید ثبت شد!</b>\n\n👤 کاربر: <code>{$from_id}</code>\n🔗 هش تراکنش:\n<code>{$safe_tax_id}</code>", $keys, "HTML", $admin);
        }
        else {
            sendMessage($mainValues['used_tax_id']);
        }
    }
    exit();
}
// -------------------------------------------------------------------------
// گام اول ستاره تلگرام: صدور فاکتور و ارسال به کاربر
// -------------------------------------------------------------------------
if (preg_match('/^payWithStars(.*)/', (string)$data, $match)) {
    $hash_id = trim($match[1]);
    
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
    $stmt->bind_param("s", $hash_id); $stmt->execute();
    $payInfo = $stmt->get_result(); $stmt->close();

    if ($payInfo->num_rows == 0) {
        delMessage(); exit();
    }
    $payInfo = $payInfo->fetch_assoc();
    $price_toman = $payInfo['price'];

    // محاسبه قیمت بر اساس ستاره تلگرام (مثلا هر ستاره 2210 تومان)
    $star_rate = 2210; // نرخ تبدیل تومان به ستاره (مثال: 2210 تومان = 1 ستاره)
    $stars_amount = ceil($price_toman / $star_rate);
    if($stars_amount < 1) $stars_amount = 1; // حداقل قیمت 1 ستاره است

    // ارسال فاکتور تلگرام (Invoice)
    // نکته مهم: برای ارز XTR مقدار provider_token باید دقیقا یک رشته خالی "" باشد
    $invoice_payload = [
        'chat_id' => $from_id,
        'title' => 'خرید اشتراک سرویس',
        'description' => "فاکتور خرید کانفیگ\nمبلغ تومانی: " . number_format($price_toman) . " تومان",
        'payload' => "stars_" . $hash_id, // پی‌لود برای شناسایی در مرحله پرداخت موفق
        'provider_token' => "", 
        'currency' => 'XTR', // ارز ستاره تلگرام
        'prices' => json_encode([['label' => 'پرداخت با ستاره', 'amount' => $stars_amount]])
    ];
    
    bot('sendInvoice', $invoice_payload);
    exit();
}
// -------------------------------------------------------------------------
// گام دوم ستاره تلگرام: تایید تراکنش قبل از کسر از حساب کاربر
// -------------------------------------------------------------------------
if (isset($update->pre_checkout_query)) {
    bot('answerPreCheckoutQuery', [
        'pre_checkout_query_id' => $update->pre_checkout_query->id,
        'ok' => true // تایید می‌کنیم تا کسر ستاره انجام شود
    ]);
    exit();
}
// -------------------------------------------------------------------------
// گام سوم ستاره تلگرام: دریافت تاییدیه قطعی پرداخت و صدور آنی کانفیگ
// -------------------------------------------------------------------------
if (isset($update->message->successful_payment)) {
    $payment_info = $update->message->successful_payment;
    $currency = $payment_info->currency;
    $payload = $payment_info->invoice_payload; // همان stars_{hash_id} که بالا ست کردیم
    
    if ($currency == 'XTR' && strpos($payload, 'agentstars_') !== false) {
        $parts = explode('_', $payload);
        $safe_hash_id = $parts[1] ?? '';
        $sid = $parts[2] ?? '';
        $uid = $update->message->chat->id;

        $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
        $stmt->bind_param("s", $safe_hash_id);
        $stmt->execute();
        $pay_info = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if ($pay_info && $pay_info['state'] != "approved") {
            $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'approved' WHERE `hash_id` = ?");
            $stmt->bind_param("s", $safe_hash_id);
            $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();

            $stmt = $connection->prepare("SELECT * FROM `users` WHERE `userid` = ?");
            $stmt->bind_param("i", $uid);
            $stmt->execute();
            $agentInfo = $stmt->get_result()->fetch_assoc();
            $stmt->close();

            $extend_seconds = $pDays * 86400;
            $current_agent_date = intval($agentInfo['agent_date'] ?? 0);
            $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, $uid);
            $stmt->execute();
            $stmt->close();

            $limAddedTxt = ($lim_added == 0) ? "نامحدود" : "$lim_added عدد";
            $msgAdmin = "📢 <b>خرید سهمیه نمایندگی (ستاره تلگرام):</b>\n\n"
                      . "👤 نماینده: " . ($agentInfo['first_name'] ?? '') . " (@" . ($agentInfo['username'] ?? '') . ")\n"
                      . "🆔 آیدی: <code>$uid</code>\n"
                      . "📊 حجم: <code>$vol_added GB</code>\n"
                      . "👤 تعداد اکانت: <code>$limAddedTxt</code>\n"
                      . "⭐ ستاره‌های پرداخت شده: <code>{$payment_info->total_amount}</code>\n"
                      . "✅ سهمیه به‌طور خودکار شارژ شد.";
            sendMessage($msgAdmin, null, "HTML", $admin);

            sendMessage("🎉 <b>سهمیه نمایندگی شما با موفقیت شارژ شد!</b>\n\n📊 میزان حجم افزوده شده: <code>$vol_added GB</code>\n👤 تعداد اکانت: <code>$limAddedTxt</code>", json_encode(['inline_keyboard' => [[['text' => "ورود به پنل نمایندگی", 'callback_data' => "agentCustomConfigPanel_{$sid}"]]]]), "HTML", $uid);
        }
        exit();
    }
    
    if ($currency == 'XTR' && strpos($payload, 'stars_') !== false) {
        $safe_hash_id = str_replace('stars_', '', $payload);
        $uid = $update->message->chat->id;

        // واکشی فاکتور از دیتابیس
        $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
        $stmt->bind_param("s", $safe_hash_id); $stmt->execute();
        $payInfo = $stmt->get_result()->fetch_assoc(); $stmt->close();

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

        $fid = $payInfo['plan_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();

        if (!$file_detail) exit();

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

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

        if (!$serverConfig) exit();

        $serverType = $serverConfig['type'];
        $panelUrl = rtrim($serverConfig['panel_url'], '/');
        $apiToken = trim($serverConfig['password']);

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

        sendMessage("⏳ پرداخت شما با ستاره تلگرام تایید شد؛ در حال صدور و ارسال کانفیگ اختصاصی شما...", null, null, $uid);

        // ساخت ریمارک کلاینت انگلیسی استاندارد مشابه ماژول هدیه
        $rnd = rand(1111, 9999);
        $inbound_id_raw_clean = strval($inbound_id_raw);
        $isProxyInbound = (strpos($inbound_id_raw_clean, '7') !== false);
        if ($isProxyInbound) {
            $remark = "Proxy-{$uid}-{$rnd}";
        } else {
            $remark = "User-{$uid}-{$rnd}";
        }
        $finalEmail = $remark . "@tg.com";

        $volumeBytes = $volume * 1073741824;
        $expiryTimestamp = ($days > 0) ? (time() + ($days * 86400)) * 1000 : 0;
        $flag = $serverInfo['flag'] ?? "🇩🇪❤️";

        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];

        $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 {
            $groupName = determineClientGroup($finalEmail);
            $postData = [
                "client" => [
                    "email" => $finalEmail, "totalGB" => $volumeBytes, "expiryTime" => $expiryTimestamp,
                    "tgId" => intval($uid), "limitIp" => $limitip, "enable" => true,
                    "group_name" => $groupName, "groupName" => $groupName, "group" => $groupName
                ],
                "inboundIds" => $inboundIdsArray
            ];

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $panelUrl . '/panel/api/clients/add');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData)); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'Accept: application/json', 'Authorization: Bearer ' . $apiToken]);
            $raw_response = curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch);
            
            $resDecoded = json_decode($raw_response, true);

            if ($http_code == 200 || (isset($resDecoded['success']) && $resDecoded['success'] == true)) {
                $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'])) {
                    $clientSubId = $clientDecoded['obj']['client']['subId'] ?? "";
                    $clientUuid = $clientDecoded['obj']['client']['id'] ?? ""; 
                }

                $subUrl = $panelUrl . "/panel/api/clients/links/" . urlencode($finalEmail);
                $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $subUrl); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json', 'Authorization: Bearer ' . $apiToken]);
                $subResponse = curl_exec($ch); curl_close($ch);
                
                $subDecoded = json_decode($subResponse, true);
                if (isset($subDecoded['success']) && $subDecoded['success'] && isset($subDecoded['obj'])) {
                    // ✨ فیکس طلایی چند اینبانده: باز کردن هوشمند لایه‌های چند پروتکله جهت جلوگیری از خطای Array به String
                    $rawObj = $subDecoded['obj'];
                    if (is_array($rawObj)) {
                        foreach ($rawObj as $key => $val) {
                            if (is_array($val)) {
                                foreach ($val as $subVal) {
                                    if (is_string($subVal)) $configLinks[] = $subVal;
                                }
                            } elseif (is_string($val)) {
                                $configLinks[] = $val;
                            }
                        }
                    }
                }
            }
        }

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

        // فیلتر و رندر رشته‌های متنی کانفیگ‌ها
        $firstLink = "";
        $cleanLinksForDb = [];
        if (!empty($configLinks)) {
            $firstLink = $configLinks[0];
            foreach ($configLinks as $singleLink) { $cleanLinksForDb[] = $singleLink; }
        } else {
            $firstLink = "vless://{$clientUuid}@{$panelHost}:2096?type=tcp&security=none#{$remark}{$flag}";
            $cleanLinksForDb[] = $firstLink;
        }

        $ipLimitTxt = ($limitip == 0) ? "بدون محدودیت" : $limitip . " کاربره";

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

        delMessage(); 
        include_once 'phpqrcode/qrlib.php';
        
        $file = RandomString(10) . ".png";
        QRcode::png($firstLink, $file, 'L', 10, 2); 

        if (function_exists('addBorderImage')) addBorderImage($file);

        if (file_exists(__DIR__ . "/settings/QRCode.jpg")) {
            try {
                $backgroundImage = @imagecreatefromjpeg(__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);
            } catch (Exception $e) {}
        }

        sendPhoto($file, $acc_text, json_encode(['inline_keyboard' => [[['text' => $buttonValues['back_to_main'], 'callback_data' => "mainMenu",'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']]]]), "HTML", $uid);
        if(file_exists($file)) @unlink($file);

        if (!empty($userInfo['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 = $userInfo['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);
        }

        $linkForDb = $connection->real_escape_string(json_encode($cleanLinksForDb, JSON_UNESCAPED_UNICODE));
        $agentBought = $payInfo['agent_bought'] ? 1 : 0;
        $inbound_id_db = intval($inboundIdsArray[0]);
        $safe_remark_db = $connection->real_escape_string($remark);
        $safe_clientSubId = $connection->real_escape_string($clientSubId);

        $insertQuery = "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 
            ({$uid}, '{$safe_clientSubId}', '', {$fid}, {$server_id}, {$inbound_id_db}, '{$safe_remark_db}', '{$safe_clientSubId}', 'vless/vmess/trojan', {$expire_date}, '{$linkForDb}', {$price}, 1, {$date}, 0, {$rahgozar}, {$agentBought})";
            
        $connection->query($insertQuery);

        $stmt = $connection->prepare("UPDATE `server_info` SET `ucount` = `ucount` - 1 WHERE `id` = ?");
        $stmt->bind_param("i", $server_id); $stmt->execute(); $stmt->close();
        
        $keys = json_encode(['inline_keyboard' => [[['text' => "بنازم خرید ستاره‌ای ⭐️💸", 'callback_data' => "NetFreedomVPN"]]]]);
        $msgAdmin = "📥 خرید جدید با ستاره تلگرام انجام شد!\nکاربر: $uid\nتعداد ستاره: {$payment_info->total_amount} ⭐️";
        sendMessage($msgAdmin, $keys, "html", $admin);
    }
    exit();
}
if (preg_match('/payWithWeSwap(.*)/', (string)$data, $match)) {
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]);
    $stmt->execute();
    $payInfo = $stmt->get_result();
    $stmt->close();

    if ($payInfo->num_rows == 0) {
        $text = "/start";
        $data = "";
        delMessage();
    //    goto GOTOSTART;
    }
    $payInfo = $payInfo->fetch_assoc();

    $fid = $payInfo['plan_id'];
    $type = $payInfo['type'];

    $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'];
    $acount = $file_detail['acount'];
    $inbound_id = $file_detail['inbound_id'];

    if ($type != "INCREASE_WALLET" && $type != "RENEW_ACCOUNT") {
        if ($acount <= 0 and $inbound_id != 0) {
            alert($mainValues['out_of_connection_capacity']);
            exit;
        }
        if ($inbound_id == 0) {
            $stmt = $connection->prepare("SELECT * FROM `server_info` WHERE `id`=?");
            $stmt->bind_param("i", $server_id);
            $stmt->execute();
            $server_info = $stmt->get_result()->fetch_assoc();
            $stmt->close();

            if ($server_info['ucount'] <= 0) {
                alert($mainValues['out_of_server_capacity']);
                exit;
            }
        }
        else {
            if ($acount <= 0) {
                alert($mainValues['out_of_server_capacity']);
                exit();
            }
        }
    }

    if ($type == "RENEW_ACCOUNT") {
        $oid = $payInfo['plan_id'];

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

    }

    delMessage();
    sendMessage($mainValues['please_wait_message'], $removeKeyboard);


    $price = $payInfo['price'];
    $priceInUSD = round($price / $botState['USDRate'], 2);
    $priceInTrx = round($price / $botState['TRXRate'], 2);
    $pay = NOWPayments('POST', 'payment', [
        'price_amount' => $priceInUSD,
        'price_currency' => 'usd',
        'pay_currency' => 'trx'
    ]);
    if (isset($pay->pay_address)) {
        $payAddress = $pay->pay_address;

        $payId = $pay->payment_id;

        $stmt = $connection->prepare("UPDATE `pays` SET `payid` = ? WHERE `hash_id` = ?");
        $stmt->bind_param("is", $payId, $match[1]);
        $stmt->execute();
        $stmt->close();

        $keys = json_encode(['inline_keyboard' => [
                [['text' => "پرداخت با درگاه ارزی ریالی", 'url' => "https://changeto.technology/quick?amount=$priceInTrx&currency=TRX&address=$payAddress"]],
                [['text' => "پرداخت کردم ✅", 'callback_data' => "havePaiedWeSwap" . $match[1]]]
            ]]);
        sendMessage("
✅ لینک پرداخت با موفقیت ایجاد شد

💰مبلغ : " . $priceInTrx . " ترون

✔️ بعد از پرداخت حدود 1 الی 15 دقیقه صبر کنید تا پرداخت به صورت کامل انجام شود سپس روی پرداخت کردم کلیک کنید
⁮⁮ ⁮⁮
", $keys);
    }
    else {
        if ($pay->statusCode == 400) {
            sendMessage("مقدار انتخاب شده کمتر از حد مجاز است");
        }
        else {
            sendMessage("مشکلی رخ داده است، لطفا به پشتیبانی اطلاع بدهید");
        }
        sendMessage("لطفا یکی از کلید های زیر را انتخاب کنید", getMainKeys());
    }
}
if (preg_match('/havePaiedWeSwap(.*)/', (string)$data, $match)) {
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]);
    $stmt->execute();
    $payInfoResult = $stmt->get_result(); // تغییر نام موقت برای عدم تداخل
    $stmt->close();

    if ($payInfoResult->num_rows == 0) {
        $text = "/start";
        $data = "";
        delMessage();
        exit();
    }
    
    // 🎯 شلیک نهایی و حل ارور VSCode: تبدیل خروجی دیتابیس به آرایه استاندارد
    $payInfo = $payInfoResult->fetch_assoc();

    if ($payInfo['state'] == "pending") {
        $payid = $payInfo['payid'];
        $payType = $payInfo['type'];
        $price = $payInfo['price'];

        // استعلام وضعیت از درگاه
        $request_json = NOWPayments('GET', 'payment', $payid);

        // اگر پرداخت موفق بود
        if ($request_json->payment_status == 'finished' or $request_json->payment_status == 'confirmed' or $request_json->payment_status == 'sending') {

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

            // ======================================================
            // 1. افزایش موجودی (INCREASE_WALLET)
            // ======================================================
            if ($payType == "INCREASE_WALLET") {
                $stmt = $connection->prepare("UPDATE `users` SET `wallet` = `wallet` + ? WHERE `userid` = ?");
                $stmt->bind_param("ii", $price, $from_id);
                $stmt->execute();
                $stmt->close();

                sendMessage("افزایش حساب شما با موفقیت تأیید شد\n✅ مبلغ " . number_format($price) . " تومان به حساب شما اضافه شد");
                sendMessage("✅ مبلغ " . number_format($price) . " تومان به کیف پول کاربر $from_id توسط درگاه ارزی ریالی اضافه شد", null, null, $admin);
            }
            // ======================================================
            // 2. خرید اکانت جدید (BUY_SUB) - نسخه مولتی پورت
            // ======================================================
            elseif ($payType == "BUY_SUB") {
                $uid = $from_id;
                $fid = $payInfo['plan_id'];
                $volume = $payInfo['volume'];
                $days = $payInfo['day'];
                $description = $payInfo['description'];

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

                if ($volume == 0 && $days == 0) {
                    $volume = $file_detail['volume'];
                    $days = $file_detail['days'];
                }

                $date = time();
                $expire_microdate = ($days > 0) ? floor(microtime(true) * 1000) + (864000 * $days * 100) : 0;
                $expire_date = ($days > 0) ? $date + (86400 * $days) : 0;
                $type = $file_detail['type'];
                $protocol = $file_detail['protocol'];
                $price = $payInfo['price'];

                $server_id = $file_detail['server_id'];
                $netType = $file_detail['type'];
                $acount = $file_detail['acount'];
                $inbound_id = $file_detail['inbound_id'];
                $limitip = $file_detail['limitip'];
                $rahgozar = $file_detail['rahgozar'];
                $customPath = $file_detail['custom_path'];
                $customPort = $file_detail['custom_port'];
                $customSni = $file_detail['custom_sni'];

                $accountCount = $payInfo['agent_count'] != 0 ? $payInfo['agent_count'] : 1;
                $eachPrice = $price / $accountCount;

                if ($acount == 0 and $inbound_id != 0) {
                    alert($mainValues['out_of_connection_capacity']);
                    exit;
                }
                if ($inbound_id == 0) {
                    $stmt = $connection->prepare("SELECT * FROM `server_info` WHERE `id`=?");
                    $stmt->bind_param("i", $server_id);
                    $stmt->execute();
                    $server_info = $stmt->get_result()->fetch_assoc();
                    $stmt->close();

                    if ($server_info['ucount'] <= 0) {
                        alert($mainValues['out_of_server_capacity']);
                        exit;
                    }
                }

                $stmt = $connection->prepare("SELECT * FROM `server_info` WHERE `id`=?");
                $stmt->bind_param("i", $server_id);
                $stmt->execute();
                $serverInfo = $stmt->get_result()->fetch_assoc();
                $serverTitle = $serverInfo['title'];
                $srv_remark = $serverInfo['remark'];
                $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();
                $serverType = $serverConfig['type'];
                $portType = $serverConfig['port_type'];
                $panelUrl = $serverConfig['panel_url'];
                $stmt->close();

                // ⏳ پیام انتظار
                sendMessage("⏳ پرداخت تایید شد. در حال آماده‌سازی سرویس... لطفاً چند لحظه صبر کنید.", null, null, $uid);
                alert($mainValues['sending_config_to_user']);

                include_once 'phpqrcode/qrlib.php';
                define('IMAGE_WIDTH', 540);
                define('IMAGE_HEIGHT', 540);

                for ($i = 1; $i <= $accountCount; $i++) {
                    $uniqid = generateRandomString(42, $protocol);

                    $savedinfo = file_get_contents('settings/temp.txt');
                    $savedinfo = explode('-', $savedinfo);
                    $port = $savedinfo[0] + 1;
                    $last_num = $savedinfo[1] + 1;

                    if ($botState['remark'] == "digits") {
                        $rnd = rand(10000, 99999);
                        $remark = "{$srv_remark}-{$rnd}";
                    }
                    elseif ($botState['remark'] == "manual") {
                        $remark = $payInfo['description'];
                        if ($accountCount > 1)
                            $remark .= "-$i";
                    }
                    else {
                        $rnd = rand(1111, 99999);
                        $typePrefix = ($agentBought == 1) ? "Agent" : "Client";
                        $remark = "{$typePrefix}-{$from_id}-{$rnd}";
                    }
                    if (!empty($description))
                        $remark = $description;

                    if ($portType == "auto") {
                        file_put_contents('settings/temp.txt', $port . '-' . $last_num);
                    }
                    else {
                        $port = rand(1111, 65000);
                    }

                    // --- ساخت در پنل ---
                    if ($inbound_id == 0) {
                        if ($serverType == "marzban") {
                            $response = addMarzbanUser($server_id, $remark, $volume, $days, $fid);
                            if (!$response->success && $response->msg == "User already exists") {
                                $remark .= rand(1111, 99999);
                                $response = addMarzbanUser($server_id, $remark, $volume, $days, $fid);
                            }
                        }
                        else {
                            $response = addUser($server_id, $uniqid, $protocol, $port, $expire_microdate, $remark, $volume, $netType, 'none', $rahgozar, $fid);
                            if (!$response->success) {
                                if (strstr($response->msg, "Duplicate email"))
                                    $remark .= RandomString();
                                elseif (strstr($response->msg, "Port already exists"))
                                    $port = rand(1111, 65000);
                                $response = addUser($server_id, $uniqid, $protocol, $port, $expire_microdate, $remark, $volume, $netType, 'none', $rahgozar, $fid);
                            }
                        }
                    }
                    else {
                        // تابع مولتی پورت (با تاخیر)
                        $response = addInboundAccount($server_id, $uniqid, $inbound_id, $expire_microdate, $remark, $volume, $limitip, null, $fid);
                        if (!$response->success) {
                            if (strstr($response->msg, "Duplicate email"))
                                $remark .= RandomString();
                            $response = addInboundAccount($server_id, $uniqid, $inbound_id, $expire_microdate, $remark, $volume, $limitip, null, $fid);
                        }
                    }

                    if (is_null($response)) {
                        sendMessage('❌ | 🥺 گلم ، اتصال به سرور برقرار نیست لطفا مدیر رو در جریان بزار ...');
                        exit;
                    }
                    if ($response == "inbound not Found") {
                        sendMessage("❌ | 🥺 سطر (inbound) با آیدی $inbound_id تو این سرور وجود نداره ، مدیر رو در جریان بزار ...");
                        exit;
                    }
                    if (!$response->success) {
                        sendMessage('❌ | 😮 وای خطا داد لطفا سریع به مدیر بگو ...');
                        sendMessage("خطای سرور {$serverInfo['title']}:\n\n" . ($response->msg), null, null, $admin);
                        exit;
                    }

                    // --- لینک سابسکریپشن ---
                    $subLink = "";
                    $token = "";

                    if ($serverType == "marzban") {
                        $uniqid = $token = str_replace("/sub/", "", $response->sub_link);
                        $subLink = $botState['subLinkState'] == "on" ? $panelUrl . $response->sub_link : "";
                    }
                    else {
                        if (isset($response->subLink) && !empty($response->subLink)) {
                            $subLink = $response->subLink;
                            $token = basename($subLink);
                        // ✅ $uniqid تغییر نمیکند
                        }
                        else {
                            $token = RandomString(30);
                            $subLink = ($botState['subLinkState'] == "on") ? $botUrl . "settings/subLink.php?token=" . $token : "";
                        }
                    }

                    $linkForDb = json_encode([$subLink]);

                    $acc_text = "
😍 سفارش جدید شما
📡 پروتکل: $protocol
🔮 نام سرویس: $remark
🔋حجم سرویس: $volume گیگ
⏰ مدت سرویس: $days روز

🔗 لینک اشتراک هوشمند (همه پروتکل‌ها):
<code>$subLink</code>

⚠️ آموزش: لینک بالا را کپی کرده و در نرم‌افزار (V2RayNG / V2Box) گزینه Update Subscription را بزنید.

🔋 مشاهده آنلاین حجم: 
<code>{$botUrl}search.php?id={$uniqid}</code>
";

                    $file = RandomString() . ".png";
                    $ecc = 'L';
                    $pixel_Size = 10;
                    $frame_Size = 2;

                    QRcode::png($subLink, $file, $ecc, $pixel_Size, $frame_Size);

                    if (function_exists('addBorderImage'))
                        addBorderImage($file);

                    if (file_exists(__DIR__ . "/settings/QRCode.jpg")) {
                        $backgroundImage = imagecreatefromjpeg(__DIR__ . "/settings/QRCode.jpg");
                        $qrImage = imagecreatefrompng($file);
                        $qrWidth = imagesx($qrImage); $qrHeight = imagesy($qrImage);
                        $newWidth = round($qrWidth * 1.5); $newHeight = round($qrHeight * 1.5);
                        $startX = round((imagesx($backgroundImage) - $newWidth) / 2);
                        $startY = round(300 - ($newHeight - $qrHeight) / 2);
                        imagecopyresampled($backgroundImage, $qrImage, $startX, $startY, 0, 0, $newWidth, $newHeight, $qrWidth, $qrHeight);
                        imagepng($backgroundImage, $file);
                        imagedestroy($backgroundImage);
                        imagedestroy($qrImage);
                    }

                    sendPhoto($file, $acc_text, json_encode(['inline_keyboard' => [[['text' => $buttonValues['back_to_main'], 'callback_data' => "mainMenu",'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']]]]), "HTML", $uid);
                    unlink($file);

                    $agentBought = $payInfo['agent_bought'];

                    $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, ?, ?);");
                    $stmt->bind_param("ssiiisssisiiii", $uid, $token, $fid, $server_id, $inbound_id, $remark, $uniqid, $protocol, $expire_date, $linkForDb, $eachPrice, $date, $rahgozar, $agentBought);
                    $stmt->execute();
                    $stmt->close();
                } // پایان حلقه

                if ($userInfo['refered_by'] != null) {
                    $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'INVITE_BANNER_AMOUNT'");
                    $stmt->execute();
                    $inviteAmount = $stmt->get_result()->fetch_assoc()['value'] ?? 0;
                    $stmt->close();
                    $inviterId = $userInfo['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);
                }

                if ($inbound_id == 0) {
                    $stmt = $connection->prepare("UPDATE `server_info` SET `ucount` = `ucount` - ? WHERE `id`=?");
                    $stmt->bind_param("ii", $accountCount, $server_id);
                    $stmt->execute();
                    $stmt->close();
                }
                else {
                    $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"]]]]);

                $msg = str_replace(['SERVERNAME', 'TYPE', 'USER-ID', 'USERNAME', 'NAME', 'PRICE', 'REMARK', 'VOLUME', 'DAYS'],
                [$serverTitle, 'ارزی ریالی', $from_id, $username, $first_name, $price, $remark, $volume, $days], $mainValues['buy_new_account_request']);

                sendMessage($msg, $keys, "html", $admin);
            }
            // ======================================================
            // 3. تمدید اکانت (RENEW_ACCOUNT)
            // ======================================================
            elseif ($payType == "RENEW_ACCOUNT") {
                $oid = $payInfo['plan_id'];
                $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `id` = ?");
                $stmt->bind_param("i", $oid);
                $stmt->execute();
                $order = $stmt->get_result()->fetch_assoc();
                $stmt->close();
                $fid = $order['fileid'];
                $remark = $order['remark'];
                $uuid = $order['uuid'] ?? "0";
                $server_id = $order['server_id'];
                $inbound_id = $order['inbound_id'];
                $expire_date = $order['expire_date'];
                $expire_date = ($expire_date > $time) ? $expire_date : $time;

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

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

                if ($serverType == "marzban") {
                    $response = editMarzbanConfig($server_id, ['remark' => $remark, 'days' => $days, 'volume' => $volume]);
                }
                else {
                    if ($inbound_id > 0)
                        $response = editClientTraffic($server_id, $inbound_id, $uuid, $volume, $days, "renew");
                    else
                        $response = editInboundTraffic($server_id, $uuid, $volume, $days, "renew");
                }

                if (is_null($response)) {
                    alert('🔻مشکل فنی در اتصال به سرور. لطفا به مدیریت اطلاع بدید', true);
                    exit;
                }
                $stmt = $connection->prepare("UPDATE `orders_list` SET `expire_date` = ?, `notif` = 0 WHERE `id` = ?");
                $newExpire = $time + $days * 86400;
                $stmt->bind_param("ii", $newExpire, $oid);
                $stmt->execute();
                $stmt->close();
                $stmt = $connection->prepare("INSERT INTO `increase_order` VALUES (NULL, ?, ?, ?, ?, ?, ?);");
                $stmt->bind_param("iiisii", $uid, $server_id, $inbound_id, $remark, $price, $time);
                $stmt->execute();
                $stmt->close();

                sendMessage("✅سرویس $remark با موفقیت تمدید شد", getMainKeys());
                $keys = json_encode(['inline_keyboard' => [[['text' => "به به تمدید 😍", 'callback_data' => "NetFreedomVPN"]]]]);

                $msg = str_replace(['TYPE', "USER-ID", "USERNAME", "NAME", "PRICE", "REMARK", "VOLUME", "DAYS"], ['کیف پول', $from_id, $username, $first_name, $price, $remark, $volume, $days], $mainValues['renew_account_request_message']);

                sendMessage($msg, $keys, "html", $admin);
            }
            // ======================================================
            // 4. افزایش زمان (INCREASE_DAY)
            // ======================================================
            elseif (preg_match('/^INCREASE_DAY_(\d+)_(\d+)/', $payType, $increaseInfo)) {
                $orderId = $increaseInfo[1];

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

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

                $planid = $increaseInfo[2];

                $stmt = $connection->prepare("SELECT * FROM `increase_day` WHERE `id` = ?");
                $stmt->bind_param("i", $planid);
                $stmt->execute();
                $res = $stmt->get_result()->fetch_assoc();
                $stmt->close();
                $price = $payInfo['price'];
                $volume = $res['volume']; // این volume در اینجا به معنی تعداد روز است

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

                if ($serverType == "marzban") {
                    $response = editMarzbanConfig($server_id, ['remark' => $remark, 'plus_day' => $volume]);
                }
                else {
                    if ($inbound_id > 0)
                        $response = editClientTraffic($server_id, $inbound_id, $uuid, 0, $volume);
                    else
                        $response = editInboundTraffic($server_id, $uuid, 0, $volume);
                }

                if ($response->success) {
                    $stmt = $connection->prepare("UPDATE `orders_list` SET `expire_date` = `expire_date` + ?, `notif` = 0 WHERE `uuid` = ?");
                    $newVolume = $volume * 86400;
                    $stmt->bind_param("is", $newVolume, $uuid);
                    $stmt->execute();
                    $stmt->close();

                    $stmt = $connection->prepare("INSERT INTO `increase_order` VALUES (NULL, ?, ?, ?, ?, ?, ?);");
                    $stmt->bind_param("iiisii", $from_id, $server_id, $inbound_id, $remark, $price, $time);
                    $stmt->execute();
                    $stmt->close();

                    sendMessage("✅$volume روز به مدت زمان سرویس شما اضافه شد", getMainKeys());

                    $keys = json_encode(['inline_keyboard' => [[['text' => "اخیش یکی زمان زد 😁", 'callback_data' => "NetFreedomVPN"]]]]);
                    sendMessage("🔋|💰 افزایش زمان با ( درگاه ) \n ▫️آیدی کاربر: $from_id \n 👨‍💼اسم کاربر: $first_name \n ⚡️ نام کاربری: $username \n 🎈 نام سرویس: $remark \n ⏰ مدت افزایش: $volume روز \n 💰قیمت: $price تومان", $keys, "html", $admin);

                    exit;
                }
                else {
                    alert("به دلیل مشکل فنی امکان افزایش زمان نیست. لطفا به مدیریت اطلاع بدید", true);
                    exit;
                }
            }
            // ======================================================
            // 5. افزایش حجم (INCREASE_VOLUME)
            // ======================================================
            elseif (preg_match('/^INCREASE_VOLUME_(\d+)_(\d+)/', $payType, $increaseInfo)) {
                $orderId = $increaseInfo[1];

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

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

                $planid = $increaseInfo[2];

                $stmt = $connection->prepare("SELECT * FROM `increase_plan` WHERE `id` = ?");
                $stmt->bind_param("i", $planid);
                $stmt->execute();
                $res = $stmt->get_result()->fetch_assoc();
                $stmt->close();
                $price = $payInfo['price'];
                $volume = $res['volume'];

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

                if ($serverType == "marzban") {
                    $response = editMarzbanConfig($server_id, ['remark' => $remark, 'plus_volume' => $volume]);
                }
                else {
                    if ($inbound_id > 0)
                        $response = editClientTraffic($server_id, $inbound_id, $uuid, $volume, 0);
                    else
                        $response = editInboundTraffic($server_id, $uuid, $volume, 0);
                }

                if ($response->success) {
                    $stmt = $connection->prepare("UPDATE `orders_list` SET `notif` = 0 WHERE `uuid` = ?");
                    $stmt->bind_param("s", $uuid);
                    $stmt->execute();
                    $stmt->close();

                    $keys = json_encode(['inline_keyboard' => [[['text' => "اخیش یکی حجم زد 😁", 'callback_data' => "NetFreedomVPN"]]]]);
                    sendMessage("🔋|💰 افزایش حجم با ( درگاه ) \n ▫️آیدی کاربر: $from_id \n 👨‍💼اسم کاربر: $first_name \n ⚡️ نام کاربری: $username \n 🎈 نام سرویس: $remark \n ⏰ مقدار افزایش: $volume گیگ \n 💰قیمت: $price تومان", $keys, "html", $admin);
                    sendMessage("✅$volume گیگ به حجم سرویس شما اضافه شد", getMainKeys());
                    exit;
                }
                else {
                    alert("به دلیل مشکل فنی امکان افزایش حجم نیست.", true);
                    exit;
                }
            }
            // ======================================================
            // 6. تمدید مشخصات کانفیگ (RENEW_SCONFIG) - نسخه اصلاح شده و قطعی
            // ======================================================
            elseif ($payType == "RENEW_SCONFIG") {
                $uid = $from_id;
                $fid = $payInfo['plan_id'];
                $time = time(); // ✨ فیکس: تعریف متغیر زمان زنده

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

                $volume = $file_detail['volume'];
                $days = $file_detail['days'];

                $price = $payInfo['price'];
                $server_id = $file_detail['server_id'];

                $configInfo = json_decode($payInfo['description'], true);
                $uuid = $configInfo['uuid'];
                $isMarzban = $configInfo['marzban'];
                $remark = $configInfo['remark'];

                $inbound_id = $payInfo['volume'];

                // ارتباط با API هسته سرور جهت اعمال ترافیک و روز
                if ($isMarzban) {
                    $response = editMarzbanConfig($server_id, ['remark' => $remark, 'days' => $days, 'volume' => $volume]);
                }
                else {
                    if ($inbound_id > 0)
                        $response = editClientTraffic($server_id, $inbound_id, $uuid, $volume, $days, "renew");
                    else
                        $response = editInboundTraffic($server_id, $uuid, $volume, $days, "renew");
                }

                if (is_null($response) || (isset($response->success) && !$response->success)) {
                    alert('🔻مشکل فنی در اتصال به سرور. لطفا به مدیریت اطلاع بدید', true);
                    exit;
                }

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

                if ($currentOrder) {
                    $baseExpire = ($currentOrder['expire_date'] > $time) ? $currentOrder['expire_date'] : $time;
                    $new_expire_date = $baseExpire + (86400 * $days);

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

                // درج در آرشیو افزایش دوره و تمدید
                $stmt = $connection->prepare("INSERT INTO `increase_order` VALUES (NULL, ?, ?, ?, ?, ?, ?);");
                $stmt->bind_param("iiisii", $uid, $server_id, $inbound_id, $remark, $price, $time);
                $stmt->execute();
                $stmt->close();

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

                $keys = json_encode(['inline_keyboard' => [[['text' => "پرداخت انجام شد", 'callback_data' => "NetFreedomVPN"]]]]);
                sendMessage("🔋|💰 تمدید مشخصات کانفیگ با ( درگاه ) \n ▫️آیدی کاربر: $from_id \n 👨‍💼اسم کاربر: $first_name \n ⚡️ نام کاربری: $username \n 🎈 نام سرویس: $remark \n ⏰ مدت: $days روز \n حجم: $volume گیگ \n 💰قیمت: $price تومان", $keys, "html", $admin);

                editKeys($keys);
            }

        }
        else {
            // پرداخت ناموفق یا ناقص
            if ($request_json->payment_status == 'partially_paid') {
                $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'partiallyPaied' WHERE `hash_id` = ?");
                $stmt->bind_param("s", $match[1]);
                $stmt->execute();
                $stmt->close();
                alert("شما هزینه کمتری پرداخت کردید، لطفا به پشتیبانی پیام بدهید");
            }
            else {
                alert("پرداخت مورد نظر هنوز تکمیل نشده!");
            }
        }
    }
    else {
        alert("این لینک پرداخت منقضی شده است");
    }
}
if ($data == "getTestAccount") {
    // ایمن‌سازی بررسی سابقه کاربر
    if (isset($userInfo['freetrial']) && $userInfo['freetrial'] != null && $from_id != $admin && empty($userInfo['isAdmin'])) {
        alert("شما اکانت تست را قبلا استفاده کرده اید");
        exit();
    }
    
    $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `price`=0");
    $stmt->execute();
    $respd = $stmt->get_result();
    $stmt->close();

    if ($respd->num_rows > 0) {
        // ایمن‌سازی در صورت خالی بودن متن پیش‌فرض
        $infoMsg = isset($mainValues['receving_information']) ? $mainValues['receving_information'] : "در حال دریافت اطلاعات...";
        alert($infoMsg);
        
        $keyboard = array();
        while ($row = $respd->fetch_assoc()) {
            $id = $row['id'];
            
            // دریافت اطلاعات دسته بندی به صورت ایمن
            $catInfo = $connection->prepare("SELECT * FROM `server_categories` WHERE `id`=?");
            $catInfo->bind_param("i", $row['catid']);
            $catInfo->execute();
            $catResult = $catInfo->get_result()->fetch_assoc();
            
            // اگر دسته بندی پاک شده بود، ارور نده و یک نام پیش‌فرض بذار
            $catname = isset($catResult['title']) ? $catResult['title'] : "دسته نامشخص";
            $catInfo->close();

            $name = $catname . " " . $row['title'];
            $price = $row['price'];
            $desc = $row['descr'];
            $sid = $row['server_id'];

            $keyboard[] = [['text' => $name, 'callback_data' => "freeTrial{$id}_normal"]];
        }
        $keyboard[] = [['text' => $buttonValues['back_to_main'], 'callback_data' => "mainMenu",'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']];
        editText($message_id, "لطفا یکی از کلید های زیر را انتخاب کنید", json_encode(['inline_keyboard' => $keyboard]), "HTML");
    }
    else {
        alert("این بخش موقتا غیر فعال است");
    }
}
// -------------------------------------------------------------------------
// بخش اول: پردازش گام‌های قبل از پرداخت (پیش‌فاکتور خرید) - نسخه نهایی بدون تداخل
// -------------------------------------------------------------------------
if ((preg_match('/^discountSelectPlan(\d+)_(\d+)_(\d+)/', (string)$userInfo['step'], $match) ||
preg_match('/selectPlan(\d+)_(\d+)_(?<buyType>\w+)/', (string)$userInfo['step'], $match) ||
preg_match('/enterAccountName(\d+)_(\d+)_(?<buyType>\w+)/', (string)$userInfo['step'], $match) ||
preg_match('/selectPlan(\d+)_(\d+)_(?<buyType>\w+)/', (string)$data, $match)) &&
($botState['sellState'] == "on" || $from_id == $admin) &&
$text != $buttonValues['cancel']) {

    // ✨ فیکس نهایی و فوق هوشمند: اگر دکمه صدور با کیف پول/مدیریت یا کارت به کارت زده شده، فورا خارج شو تا فاکتور دلیت نشود!
    if (strpos((string)$data, 'payCustomWithWallet') !== false || strpos((string)$data, 'payCustomWithCartToCart') !== false || strpos((string)$userInfo['step'], 'payCustomWithCartToCart') !== false) {
        return; 
    }

    if (preg_match('/^discountSelectPlan/', (string)$userInfo['step'])) {
        $rowId = $match[3];
        $timeNow = time();
        
        $stmt = $connection->prepare("SELECT * FROM `discounts` WHERE (`expire_date` > ? OR `expire_date` = 0) AND (`expire_count` > 0 OR `expire_count` = -1) AND `hash_id` = ?");
        $stmt->bind_param("is", $timeNow, $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'];
            $canUse = $discountInfo['can_use'];
            $usedBy = !is_null($discountInfo['used_by']) ? json_decode($discountInfo['used_by'], true) : array();
            $userUsedCount = isset(array_count_values($usedBy)[$from_id]) ? 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 = $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` = ? WHERE `id` = ?");
                $stmt->bind_param("ii", $afterDiscount, $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();
    } elseif (isset($data)) {
        delMessage();
    }

    if ($botState['remark'] == "manual" && preg_match('/^selectPlan/', (string)$data) && $match['buyType'] != "much") {
        sendMessage($mainValues['customer_custome_plan_name'], $cancelKey);
        setUser('enterAccountName' . $match[1] . "_" . $match[2] . "_" . $match['buyType']);
        exit();
    }

    $remark = "";
    $bType = isset($match['buyType']) ? $match['buyType'] : "one";

    if (preg_match("/selectPlan(\d+)_(\d+)_(\w+)/", (string)$userInfo['step'])) {
        if ($bType == "much") {
            if (is_numeric($text) && $text > 0) {
                $accountCount = intval($text); setUser();
            } else {
                sendMessage("❌ لطفاً یک عدد مثبت بزرگتر از صفر وارد کنید."); exit();
            }
        }
    } elseif (preg_match("/enterAccountName(\d+)_(\d+)/", (string)$userInfo['step'])) {
        if (preg_match('/^[a-z0-9]+$/i', (string)$text)) {
            $remark = $text; setUser();
        } else {
            sendMessage($mainValues['incorrect_config_name']); exit();
        }
    } else {
        if ($bType == "much") {
            setUser($data); sendMessage($mainValues['enter_account_amount'], $cancelKey); exit();
        }
    }

    $id = $match[1];
    $call_id = $match[2];
    alert($mainValues['receving_information']);
    
    $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();
    $price = $respd['price'];
    if (isset($accountCount)) $price *= $accountCount;

    $agentBought = false;
    if ($userInfo['is_agent'] == true && ($bType == "one" || $bType == "much")) {
        $discounts = json_decode($userInfo['discount_percent'], true);
        if ($botState['agencyPlanDiscount'] == "on")
            $discount = $discounts['plans'][$id] ?? $discounts['normal'] ?? 0;
        else
            $discount = $discounts['servers'][$sid] ?? $discounts['normal'] ?? 0;
        $price -= floor($price * $discount / 100);
        $agentBought = true;
    }
    
    $hash_id = RandomString(15);
    $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();

    $timeNow = time();
    $accCountPayload = isset($accountCount) ? intval($accountCount) : 1;
    $agentBoughtVal = $agentBought ? 1 : 0;
    
    $finalDBPrice = ($from_id == $admin) ? 0 : $price; 

    $safe_remark = $connection->real_escape_string($remark);
    $query = "INSERT INTO `pays` 
              (`hash_id`, `description`, `user_id`, `type`, `plan_id`, `volume`, `day`, `price`, `request_date`, `state`, `agent_bought`, `agent_count`) 
              VALUES 
              ('{$hash_id}', '{$safe_remark}', {$from_id}, 'BUY_SUB', {$id}, '0', '0', {$finalDBPrice}, {$timeNow}, 'pending', {$agentBoughtVal}, {$accCountPayload})";
              
    $connection->query($query);
    $rowId = $connection->insert_id;

    if ($from_id == $admin) {
        $keyboard[] = [['text' => '📥 تایید و صدور آنی کانفیگ (ویژه مدیریت)', 'callback_data' => "payCustomWithWallet$hash_id"]];
    } else {
        if (($botState['cartToCartState'] ?? '') == "on") $keyboard[] = [['text' => $buttonValues['cart_to_cart'], 'callback_data' => "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['walletState'] ?? '') == "on") $keyboard[] = [['text' => $buttonValues['pay_with_wallet'], 'callback_data' => "payCustomWithWallet$hash_id"]];
        if (($botState['stars'] ?? '') == "on") $keyboard[] = [['text' => $buttonValues['stars_gateway'], 'callback_data' => "payWithStars" . $hash_id]];
        if (!preg_match('/^discountSelectPlan/', (string)$userInfo['step']))
            $keyboard[] = [['text' => "🎁 کد تخفیف داری؟ اعمال کد تخفیف", 'callback_data' => "haveDiscountSelectPlan_" . $match[1] . "_" . $match[2] . "_" . $rowId]];
    }
    
    $keyboard[] = [['text' => $buttonValues['back_to_main'], 'callback_data' => "selectCategory{$call_id}_{$sid}_{$bType}"]];
    $priceC = ($from_id == $admin) ? 'رایگان (مدیریت)' : number_format($price) . ' تومان ';
    
    if (isset($accountCount)) {
        $eachPrice = number_format($price / $accountCount) . " تومان";
        $msg = str_replace(['ACCOUNT-COUNT', 'TOTAL-PRICE', 'PLAN-NAME', 'PRICE', 'DESCRIPTION'], [$accCountPayload, $priceC, $name, $eachPrice, $desc], $mainValues['buy_much_subscription_detail']);
    } else {
        $msg = str_replace(['PLAN-NAME', 'PRICE', 'DESCRIPTION'], [$name, $priceC, $desc], $mainValues['buy_subscription_detail']);
    }
    sendMessage($msg, json_encode(['inline_keyboard' => $keyboard]), "HTML");
    exit();
}

// -------------------------------------------------------------------------
// بخش دوم: تحویل اکانت پس از پرداخت موفقیت‌آمیز از طریق کیف پول / صدور آنی مدیریت (نسخه ۱۰۰٪ فیکس و لوکس چند اینبانده)
// -------------------------------------------------------------------------
if (preg_match('/payCustomWithWallet(.*)/', (string)$data, $match)) {
    setUser();

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

    if ($payInfo->num_rows == 0) {
        $text = "/start"; $data = ""; delMessage(); exit();
    }
    $payInfo = $payInfo->fetch_assoc();

    if ($payInfo['state'] == "paid_with_wallet") exit();

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

    // هک طلایی موجودی مدیریت
    if ($from_id != $admin && $userInfo['wallet'] < $price) {
        alert("❌ موجودی حساب شما کافی نیست! لطفاً ابتدا کیف پول خود را شارژ کنید.");
        exit();
    }

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

    if (!$file_detail) {
        alert("❌ پلن مورد نظر یافت نشد.");
        exit();
    }

    $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'];
    $plan_title = $connection->real_escape_string($file_detail['title']);

    $date = time();
    $expire_date = ($days > 0) ? $date + (86400 * $days) : 0;

    // واکشی مشخصات سرور میزبان جهت دریافت توکن 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']);

    // کسر موجودی کیف پول کاربر خریدار (فقط در صورتی که خریدار ادمین نباشد)
    if ($from_id != $admin) {
        $stmt = $connection->prepare("UPDATE `users` SET `wallet` = `wallet` - ? WHERE `userid` = ?");
        $stmt->bind_param("ii", $price, $uid); $stmt->execute(); $stmt->close();
    }

    $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'paid_with_wallet' WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]); $stmt->execute(); $stmt->close();

    sendMessage("⏳ پرداخت موفقیت‌آمیز بود؛ در حال کانفیگ و صدور لایسنس اختصاصی شما... لطفاً صبور باشید.", null, null, $uid);

    // ساخت ریمارک کلاینت انگلیسی استاندارد مشابه ماژول هدیه
    $rnd = rand(1111, 9999);
    $inbound_id_raw_clean = strval($inbound_id_raw);
    $isProxyInbound = (strpos($inbound_id_raw_clean, '7') !== false);
    if ($isProxyInbound) {
        $remark = "Proxy-{$uid}-{$rnd}";
    } else {
        $remark = "User-{$uid}-{$rnd}";
    }
    $finalEmail = $remark . "@tg.com";

    $volumeBytes = $volume * 1073741824;
    $expiryTimestamp = ($days > 0) ? (time() + ($days * 86400)) * 1000 : 0;
    $flag = $serverInfo['flag'] ?? "🇩🇪❤️";

    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];

    $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 {
        $groupName = determineClientGroup($finalEmail);
        $postData = [
            "client" => [
                "email" => $finalEmail, "totalGB" => $volumeBytes, "expiryTime" => $expiryTimestamp,
                "tgId" => intval($uid), "limitIp" => $limitip, "enable" => true,
                "group_name" => $groupName, "groupName" => $groupName, "group" => $groupName
            ],
            "inboundIds" => $inboundIdsArray
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $panelUrl . '/panel/api/clients/add');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData)); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'Accept: application/json', 'Authorization: Bearer ' . $apiToken]);
        $raw_response = curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch);
        
        $resDecoded = json_decode($raw_response, true);

        if ($http_code == 200 || (isset($resDecoded['success']) && $resDecoded['success'] == true)) {
            $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'])) {
                $clientSubId = $clientDecoded['obj']['client']['subId'] ?? "";
                $clientUuid = $clientDecoded['obj']['client']['id'] ?? ""; 
            }

            $subUrl = $panelUrl . "/panel/api/clients/links/" . urlencode($finalEmail);
            $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $subUrl); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json', 'Authorization: Bearer ' . $apiToken]);
            $subResponse = curl_exec($ch); curl_close($ch);
            
            $subDecoded = json_decode($subResponse, true);
            if (isset($subDecoded['success']) && $subDecoded['success'] && isset($subDecoded['obj'])) {
                $rawObj = $subDecoded['obj'];
                if (is_array($rawObj)) {
                    foreach ($rawObj as $key => $val) {
                        if (is_array($val)) {
                            foreach ($val as $subVal) {
                                if (is_string($subVal)) $configLinks[] = $subVal;
                            }
                        } elseif (is_string($val)) {
                            $configLinks[] = $val;
                        }
                    }
                }
            }
        }
    }

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

    $firstLink = "";
    $cleanLinksForDb = [];
    if (!empty($configLinks)) {
        $firstLink = $configLinks[0];
        foreach ($configLinks as $singleLink) { $cleanLinksForDb[] = $singleLink; }
    } else {
        $firstLink = "vless://{$clientUuid}@{$panelHost}:2096?type=tcp&security=none#{$remark}{$flag}";
        $cleanLinksForDb[] = $firstLink;
    }

    $ipLimitTxt = ($limitip == 0) ? "بدون محدودیت" : $limitip . " کاربره";

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

    delMessage(); 
    include_once 'phpqrcode/qrlib.php';
    
    $file = sys_get_temp_dir() . '/' . RandomString(10) . ".png";
    QRcode::png($firstLink, $file, 'L', 10, 2); 

    if (function_exists('addBorderImage')) addBorderImage($file);

    if (file_exists(__DIR__ . "/settings/QRCode.jpg")) {
        try {
            $backgroundImage = @imagecreatefromjpeg(__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);
        } catch (Exception $e) {}
    }

    $resUser = sendPhoto($file, $acc_text, json_encode(['inline_keyboard' => [[['text' => $buttonValues['back_to_main'], 'callback_data' => "mainMenu",'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']]]]), "HTML", $uid);
    if (!isset($resUser->ok) || !$resUser->ok) {
        sendMessage($acc_text, json_encode(['inline_keyboard' => [[['text' => $buttonValues['back_to_main'], 'callback_data' => "mainMenu",'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']]]]), "HTML", $uid);
    }

    $resAdmin = sendPhoto($file, "✅ نسخه کپی مدیریت:\n\n" . $acc_text, null, "HTML", $admin);
    if (!isset($resAdmin->ok) || !$resAdmin->ok) {
        sendMessage("✅ نسخه کپی مدیریت:\n\n" . $acc_text, null, "HTML", $admin);
    }
    if(file_exists($file)) @unlink($file);

    if (!empty($userInfo['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 = $userInfo['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);
    }

    $linkForDb = $connection->real_escape_string(json_encode($cleanLinksForDb, JSON_UNESCAPED_UNICODE));
    $agentBought = $payInfo['agent_bought'] ? 1 : 0;
    $inbound_id_db = intval($inboundIdsArray[0]);
    $safe_remark_db = $connection->real_escape_string($remark);
    $safe_clientSubId = $connection->real_escape_string($clientSubId);

    $insertQuery = "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 
        ({$uid}, '{$safe_clientSubId}', '', {$fid}, {$server_id}, {$inbound_id_db}, '{$safe_remark_db}', '{$safe_clientSubId}', 'vless/vmess/trojan', {$expire_date}, '{$linkForDb}', {$price}, 1, {$date}, 0, {$rahgozar}, {$agentBought})";
        
    $connection->query($insertQuery);

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

    $keys = json_encode(['inline_keyboard' => [[['text' => "بنازم خرید جدید 💸❤️", 'callback_data' => "NetFreedomVPN"]]]]);
    $msgAdmin = str_replace(['SERVERNAME', 'TYPE', 'USER-ID', 'USERNAME', 'NAME', 'PRICE', 'REMARK', 'VOLUME', 'DAYS'], [$plan_title, 'کیف پول', $uid, $username, $first_name, $price, $remark, $volume, $days], $mainValues['buy_new_account_request']);
    sendMessage($msgAdmin, $keys, "html", $admin);
    exit();
}

// -------------------------------------------------------------------------
// بخش سوم: دریافت مجدد بارکد QR، وضعیت لایو و لینک‌ها از بخش کانفیگ‌های من (v3.1.0 لوکس)
// -------------------------------------------------------------------------
if (preg_match('/^showQr(Sub|Config)(\d+)/', (string)$data, $match)) {
    $order_id = intval($match[2]);
    
    $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `userid` = ? AND `id` = ?");
    $stmt->bind_param("ii", $from_id, $order_id); $stmt->execute();
    $order = $stmt->get_result()->fetch_assoc(); $stmt->close();

    if (!$order) { alert("❌ سفارش مورد نظر یافت نشد."); exit(); }

    $remark = $order['remark'];
    $server_id = $order['server_id'];
    $clientSubId = $order['uuid'] ?? $order['token'];

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

    $panelUrl = rtrim($serverConfig['panel_url'], '/');
    $apiToken = trim($serverConfig['password']);
    $flag = $serverInfo['flag'] ?? "🇩🇪❤️";

    $cleanRemark = preg_replace("/\(📊.+-.+\|📅.+\)/", "", $remark);
    
    // واکشی مشخصات ترافیک با سیستم جدید و ایمن کوکی/توکن
    $cookie_file = getCookieFilePath($server_id);
    $trafficApiUrl = $panelUrl . '/panel/api/clients/traffic/' . urlencode($cleanRemark);
    
    $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $trafficApiUrl); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
    $trafficRes = curl_exec($ch); curl_close($ch);

    $trafficDecoded = json_decode($trafficRes, true);
    
    $up = 0; $down = 0; $totalBytes = 0; $state = "فعال 🟢";
    if (isset($trafficDecoded['success']) && $trafficDecoded['success'] == true) {
        $clientData = $trafficDecoded['obj'];
        $up = $clientData['up']; $down = $clientData['down']; $totalBytes = $clientData['total'];
        
        if ($totalBytes != 0 && ($up + $down) >= $totalBytes) $state = "پایان حجم 🔴";
        elseif ($clientData['expiryTime'] != 0 && substr($clientData['expiryTime'], 0, -3) < time()) $state = "منقضی شده 🔴";
    }

    $configLinks = [];
    $subUrl = $panelUrl . "/panel/api/clients/links/" . urlencode($cleanRemark);
    $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $subUrl); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
    $subResponse = curl_exec($ch); curl_close($ch);
    $subDecoded = json_decode($subResponse, true);
    if (isset($subDecoded['success']) && $subDecoded['success'] && is_array($subDecoded['obj'])) $configLinks = $subDecoded['obj'];

    $totalUsedGb = round(($up + $down) / 1073741824, 2);
    $totalGb = $totalBytes != 0 ? round($totalBytes / 1073741824, 2) : 0;
    $daysLeft = round(($order['expire_date'] - time()) / 86400, 1);
    if($daysLeft < 0) $daysLeft = 0;

    $totalUsedTxt = $totalUsedGb . " GB";
    $totalTxt = $totalBytes != 0 ? $totalGb . " GB" : "نامحدود";
    $daysTxt = $daysLeft . " روز";

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

    include_once 'phpqrcode/qrlib.php';
    define('IMAGE_WIDTH', 540); define('IMAGE_HEIGHT', 540);
    delMessage();

    if ($match[1] == "Sub") {
        $configLinksTxt = "";
        if (!empty($configLinks)) {
            foreach ($configLinks as $singleLink) {
                if (is_array($singleLink)) {
                    foreach ($singleLink as $subLnk) {
                        if (is_string($subLnk)) $configLinksTxt .= "💝 <b>config :</b> <code>{$subLnk}</code>\n\n";
                    }
                } elseif (is_string($singleLink)) {
                    $configLinksTxt .= "💝 <b>config :</b> <code>{$singleLink}</code>\n\n";
                }
            }
        } else {
            $configLinksTxt .= "💝 <b>config :</b> <code>vless://{$clientSubId}@{$panelHost}:2096?type=tcp#{$cleanRemark}{$flag}</code>\n\n";
        }

        $acc_text = "😍 <b>مشخصات و اطلاعات مدیریت سرویس شما</b>\n\n" .
                     "🔮 نام سرویس: <code>{$cleanRemark}</code>\n" .
                     "⚡️ وضعیت اشتراک: <b>{$state}</b>\n" .
                     "🔋 حجم مصرفی: <code>{$totalUsedTxt} از {$totalTxt}</code>\n" .
                     "⏰ مدت زمان باقی‌مانده: <code>{$daysTxt}</code>\n\n" .
                     "---------------------------------------\n\n" .
                     $configLinksTxt .
                     "🔋 <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(__DIR__ . "/settings/QRCode.jpg") && function_exists('imagecreatefromjpeg') && function_exists('imagecreatefrompng')) {
            try {
                $backgroundImage = @imagecreatefromjpeg(__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) {}
        }

        $inline_keyboard = [
            [['text' => "📊 مصرف: {$totalUsedTxt} / {$totalTxt}", 'callback_data' => "NetFreedomVPN"]],
            [['text' => "📅 زمان باقی‌مانده: {$daysTxt}", 'callback_data' => "NetFreedomVPN"]],
            [['text' => $buttonValues['back_to_main'], 'callback_data' => "mainMenu",'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']]
        ];

        sendPhoto($file, $acc_text, json_encode(['inline_keyboard' => $inline_keyboard]), "HTML", $from_id);
        if(file_exists($file)) @unlink($file);
        
        // ارسال فایل .npvt برای NapsternetV
        sendNpvtDocument(!empty($configLinks) ? $configLinks : [], $cleanRemark, $from_id, $directSubLink);
        exit();
    }
    elseif ($match[1] == "Config") {
        if (empty($configLinks)) {
            $configLinks[] = "vless://{$clientSubId}@{$panelHost}:2096?type=tcp#{$cleanRemark}{$flag}";
        }
        
        foreach ($configLinks as $index => $vray_link) {
            $file = RandomString(10) . ".png";
            QRcode::png($vray_link, $file, 'L', 10, 2);
            if (function_exists('addBorderImage')) addBorderImage($file);

            if (file_exists(__DIR__ . "/settings/QRCode.jpg") && function_exists('imagecreatefromjpeg') && function_exists('imagecreatefrompng')) {
                try {
                    $backgroundImage = @imagecreatefromjpeg(__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) {}
            }

            $capText = "🔮 <b>کانفیگ اتصال اختصاصی شما (شماره " . ($index + 1) . "):</b>\n\n<code>" . htmlspecialchars($vray_link) . "</code>\n\n" .
                       "📊 حجم سرویس: <code>{$totalUsedTxt} / {$totalTxt}</code>\n" .
                       "⏰ وضعیت اعتبار: <code>{$daysTxt}</code>";
                       
            sendPhoto($file, $capText, json_encode(['inline_keyboard' => [[['text' => $buttonValues['back_to_main'], 'callback_data' => "mainMenu",'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']]]]), "HTML", $from_id);
            if(file_exists($file)) @unlink($file);
        }
        exit();
    }
}

// -------------------------------------------------------------------------
// گام اول: نمایش اطلاعات حساب بانکی به کاربر جهت کارت به کارت
// -------------------------------------------------------------------------
if (preg_match('/payCustomWithCartToCart(.*)/', (string)$data, $match)) {
    $hash_id_cart = trim($match[1]);

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

    if ($payInfo->num_rows == 0) {
        $text = "/start"; $data = ""; delMessage(); exit();
    }
    $payInfo = $payInfo->fetch_assoc();
    $fid = $payInfo['plan_id'];

    $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'];
    $acount = $file_detail['acount'];

    if ($payInfo['type'] != "RENEW_SCONFIG") {
        if ($acount == 0 && $file_detail['type'] != 'client_centric') {
            alert($mainValues['out_of_connection_capacity']); exit;
        }
        
        $stmt = $connection->prepare("SELECT `ucount` FROM `server_info` WHERE `id` = ?");
        $stmt->bind_param("i", $server_id); $stmt->execute();
        $ucnt = $stmt->get_result()->fetch_assoc()['ucount'] ?? 0; $stmt->close();
        if ($ucnt <= 0) { alert($mainValues['out_of_server_capacity']); exit; }
    }

    setUser('payCustomWithCartToCart' . $hash_id_cart); 
    delMessage();
    
    $msg = str_replace(["ACCOUNT-NUMBER", "HOLDER-NAME"], [$paymentKeys['bankAccount'], $paymentKeys['holderName']], $mainValues['buy_account_cart_to_cart']);
    $resMsg = sendMessage($msg, $cancelKey, "HTML");
    if ($resMsg && isset($resMsg->result->message_id)) {
        setUser($resMsg->result->message_id, 'temp');
    }
    exit;
}

// -------------------------------------------------------------------------
// گام دوم: دریافت عکس رسید کارت به کارت از کاربر و ارسال برای ادمین (نسخه لوکس و فیکس شده)
// -------------------------------------------------------------------------
if (preg_match('/payCustomWithCartToCart(.*)/', (string)$userInfo['step'], $match) && $text != $buttonValues['cancel']) {
    if (isset($update->message->photo)) {
        $safe_hash_id = trim($match[1]);

        $photoArray = $update->message->photo;
        $fileid = $photoArray[count($photoArray) - 1]->file_id;

        // واکشی فاکتور موقت
        $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
        $stmt->bind_param("s", $safe_hash_id); $stmt->execute();
        $payInfo = $stmt->get_result()->fetch_assoc(); $stmt->close();

        $fid = $payInfo['plan_id'];
        $fileprice = number_format($payInfo['price']);
        
        setUser(); 
        $uid = $userInfo['userid'];
        $username = isset($userInfo['username']) ? $userInfo['username'] : "ندارد";
        $first_name_user = isset($update->message->from->first_name) ? $update->message->from->first_name : "کاربر";

        // واکشی اطلاعات واقعی و دقیق پلن از دیتابیس
        $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `id` = ?");
        $stmt->bind_param("i", $fid); $stmt->execute();
        $res = $stmt->get_result()->fetch_assoc(); $stmt->close();

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

        // استخراج مقادیر اصلی
        $plan_title = $catname . " " . $res['title'];
        $volume = $res['volume'];
        $days = $res['days'];
        $limitip = intval($res['limitip']);

        // قالب‌بندی متون برای نمایش زیبا
        $volumeTxt = ($volume == 0) ? "نامحدود" : $volume . " گیگ";
        $daysTxt = ($days == 0) ? "نامحدود" : $days . " روز";
        $ipLimitTxt = ($limitip == 0) ? "بدون محدودیت" : $limitip . " کاربره";
        
        // اگر کاربر نام دلخواه نداده بود، نام پلن را به عنوان نام سرویس نمایش بده
        $remark = !empty($payInfo['description']) ? $payInfo['description'] : $plan_title . " (تولید خودکار)";

        setUser(); 
        $msgToDelete = intval($userInfo['temp'] ?? 0);
        if ($msgToDelete > 0) {
            @bot('deleteMessage', ['chat_id' => $from_id, 'message_id' => $msgToDelete]);
            setUser(null, 'temp');
        }
        @bot('deleteMessage', ['chat_id' => $from_id, 'message_id' => $message_id]);
        sendMessage("✅ <b>رسید شما برای ادمین ارسال شد. منتظر تایید و صدور بمانید.</b>", getMainKeys(), "HTML");

        // ساخت دستی و بسیار شیک کپشن رسید برای ادمین (جایگزین متن ناقص قبلی)
        $msgAdmin = "📥 <b>رسید جدید (کارت به کارت)</b>\n\n" .
                    "👤 خریدار: <a href='tg://user?id={$uid}'>{$first_name_user}</a>\n" .
                    "🆔 آیدی عددی: <code>{$uid}</code>\n" .
                    "💬 یوزرنیم: @{$username}\n" .
                    "💵 مبلغ پرداختی: <code>{$fileprice} تومان</code>\n" .
                    "---------------------------------------\n" .
                    "🔮 پلن انتخابی: <code>{$plan_title}</code>\n" .
                    "✏️ نام سرویس: <code>{$remark}</code>\n" .
                    "🔋 حجم سرویس: <code>{$volumeTxt}</code>\n" .
                    "⏰ مدت سرویس: <code>{$daysTxt}</code>\n" .
                    "👥 کاربر مجاز: <code>{$ipLimitTxt}</code>";
        
        $keyboard = json_encode([
            'inline_keyboard' => [
                [
                    [
                    'text' => "تایید",
                    'callback_data' => "accCustom" . $safe_hash_id,
                    'style' => $buttonProps['approve']['style'],
                    'icon_custom_emoji_id' => $buttonProps['approve']['icon_custom_emoji_id']
                    ],

                    [
                    'text' => "عدم تایید",
                    'callback_data' => "decline" . $uid . "_" . $safe_hash_id,
                    'style' => $buttonProps['decline']['style'],
                    'icon_custom_emoji_id' => $buttonProps['decline']['icon_custom_emoji_id']
                    ]
                ]
            ]
        ]);
        
        $resAdminMsg = sendPhoto($fileid, $msgAdmin, $keyboard, "HTML", $admin);
        
        $msgId = 0;
        if (is_object($resAdminMsg) && isset($resAdminMsg->result->message_id)) $msgId = $resAdminMsg->result->message_id;
        elseif (is_array($resAdminMsg) && isset($resAdminMsg['result']['message_id'])) $msgId = $resAdminMsg['result']['message_id'];

        $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'have_sent', `message_id` = ?, `chat_id` = ? WHERE `hash_id` = ?");
        $stmt->bind_param("iis", $msgId, $admin, $safe_hash_id);
        $stmt->execute(); $stmt->close();
    } else {
        sendMessage($mainValues['please_send_only_image']);
    }
    exit();
}

// -------------------------------------------------------------------------
// گام سوم: کلیک ادمین روی دکمه تایید (Approve) و صدور مستقیم کلاینت در پنل
// -------------------------------------------------------------------------
if (preg_match('/accCustom(.*)/', (string)$data, $match) && $text != $buttonValues['cancel']) {
    setUser();

    $safe_hash_id = trim($match[1]);

    // ۱. واکشی دقیق فاکتور از دیتابیس
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
    $stmt->bind_param("s", $safe_hash_id); $stmt->execute();
    $payInfo = $stmt->get_result()->fetch_assoc(); $stmt->close();

    if (!$payInfo) {
        alert("❌ فاکتور مورد نظر در دیتابیس یافت نشد.");
        exit();
    }

    if ($payInfo['state'] == "approved") {
        alert("ℹ️ این فاکتور قبلاً تایید و صادر شده است.");
        exit();
    }

    $fid = $payInfo['plan_id'];
    $client_telegram_id = intval($payInfo['user_id']); // آیدی عددی خریدار واقعی
    $price = $payInfo['price'];

    // ✨ هک طلایی ضد گم‌شدن متغیر: واکشی مستقیم و زنده مشخصات خریدار از دیتابیس جهت رفع تداخل با دیتای ادمین
    $stmt = $connection->prepare("SELECT * FROM `users` WHERE `userid` = ?");
    $stmt->bind_param("i", $client_telegram_id); $stmt->execute();
    $buyer_profile = $stmt->get_result()->fetch_assoc(); $stmt->close();

    $buyer_username = isset($buyer_profile['username']) ? $buyer_profile['username'] : "بدون یوزرنیم";
    $buyer_first_name = isset($buyer_profile['name']) ? $buyer_profile['name'] : "کاربر";

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

    if (!$file_detail) {
        alert("❌ پلن مورد نظر یافت نشد.");
        exit();
    }

    $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'];
    $plan_title = $connection->real_escape_string($file_detail['title']);

    // محاسبه زمان انقضا
    $date = time();
    $expire_date = ($days > 0) ? $date + (86400 * $days) : 0;

    // ۳. واکشی مشخصات سرور میزبان جهت دریافت توکن 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']); 
    $flag = $serverInfo['flag'] ?? "🇩🇪❤️";

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

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

    // ساخت ریمارک کلاینت انگلیسی استاندارد بدون کاراکترهای مخرب فارسی
    $rnd = rand(1111, 9999);
    $inbound_id_raw_clean = strval($inbound_id_raw);
    $isProxyInbound = (strpos($inbound_id_raw_clean, '7') !== false);
    if ($isProxyInbound) {
        $remark = "Proxy-{$client_telegram_id}-{$rnd}";
    } else {
        $remark = "Client-{$client_telegram_id}-{$rnd}";
    }
    $finalEmail = $remark . "@tg.com";

    $volumeBytes = $volume * 1073741824;
    $expiryTimestamp = ($days > 0) ? (time() + ($days * 86400)) * 1000 : 0;

    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];

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

    if ($serverType == "marzban") {
        $response = addMarzbanUser($server_id, $remark, $volume, $days, $fid);
        if (is_object($response) && isset($response->sub_link)) {
            $subLink = $panelUrl . $response->sub_link; $configLinks[] = $subLink;
            $clientSubId = $clientUuid = str_replace("/sub/", "", $response->sub_link);
        }
    } 
    else {
        // ساخت مستقیم کلاینت در درگاه جدید سنایی نسخه 3.1.0
        $groupName = determineClientGroup($finalEmail);
        $postData = [
            "client" => [
                "email" => $finalEmail, "totalGB" => $volumeBytes, "expiryTime" => $expiryTimestamp,
                "tgId" => intval($client_telegram_id), "limitIp" => $limitip, "enable" => true,
                "group_name" => $groupName, "groupName" => $groupName, "group" => $groupName
            ],
            "inboundIds" => $inboundIdsArray
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $panelUrl . '/panel/api/clients/add');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData)); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'Accept: application/json', 'Authorization: Bearer ' . $apiToken]);
        $raw_response = curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch);
        
        $resDecoded = json_decode($raw_response, true);

        if ($http_code == 200 || (isset($resDecoded['success']) && $resDecoded['success'] == true)) {
            // واکشی مشخصات کلاینت صادر شده جهت استخراج SubId واقعی
            $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'])) {
                $clientSubId = $clientDecoded['obj']['client']['subId'] ?? "";
                $clientUuid = $clientDecoded['obj']['client']['id'] ?? ""; 
            }

            // دریافت خودکار سابسکریپشن کامل از پنل
            $subUrl = $panelUrl . "/panel/api/clients/links/" . urlencode($finalEmail);
            $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $subUrl); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json', 'Authorization: Bearer ' . $apiToken]);
            $subResponse = curl_exec($ch); curl_close($ch);
            
            $subDecoded = json_decode($subResponse, true);
            if (isset($subDecoded['success']) && $subDecoded['success'] && isset($subDecoded['obj'])) {
                $rawObj = $subDecoded['obj'];
                if (is_array($rawObj)) {
                    foreach ($rawObj as $key => $val) {
                        if (is_array($val)) {
                            foreach ($val as $subVal) {
                                if (is_string($subVal)) $configLinks[] = $subVal;
                            }
                        } elseif (is_string($val)) {
                            $configLinks[] = $val;
                        }
                    }
                }
            }
        }
    }

    // تولید مستقیم لینک سابسکریپشن رسمی خود پنل سنایی روی پورت ۲۰۹۶
    $parsedPanelUrl = parse_url($panelUrl);
    $panelHost = $parsedPanelUrl['host'] ?? '';
    $panelScheme = $parsedPanelUrl['scheme'] ?? 'https';
    $directSubLink = "{$panelScheme}://{$panelHost}:2096/sub/{$clientSubId}";

    // استخراج و فیلتر نهایی لینک‌ها به صورت رشته متنی ۱۰۰٪ ایمن ضد کرش
    $firstLink = "";
    $cleanLinksForDb = [];
    if (!empty($configLinks)) {
        $firstLink = $configLinks[0];
        foreach ($configLinks as $singleLink) { $cleanLinksForDb[] = $singleLink; }
    } else {
        $firstLink = "vless://{$clientUuid}@{$panelHost}:2096?type=tcp&security=none#{$remark}{$flag}";
        $cleanLinksForDb[] = $firstLink;
    }

    $ipLimitTxt = ($limitip == 0) ? "بدون محدودیت" : $limitip . " کاربره";

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

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

    if (function_exists('addBorderImage')) addBorderImage($file);

    if (file_exists(__DIR__ . "/settings/QRCode.jpg")) {
        try {
            $backgroundImage = @imagecreatefromjpeg(__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);
        } catch (Exception $e) {}
    }

    $resUser = sendPhoto($file, $acc_text, json_encode(['inline_keyboard' => [[['text' => $buttonValues['back_to_main'], 'callback_data' => "mainMenu",'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']]]]), "HTML", $client_telegram_id);
    if (!isset($resUser->ok) || !$resUser->ok) {
        sendMessage($acc_text, json_encode(['inline_keyboard' => [[['text' => $buttonValues['back_to_main'], 'callback_data' => "mainMenu",'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']]]]), "HTML", $client_telegram_id);
    }
    
    $resAdmin = sendPhoto($file, "✅ نسخه کپی مدیریت:\n\n" . $acc_text, null, "HTML", $admin);
    if (!isset($resAdmin->ok) || !$resAdmin->ok) {
        sendMessage("✅ نسخه کپی مدیریت:\n\n" . $acc_text, null, "HTML", $admin);
    }
    if(file_exists($file)) @unlink($file);

    sendMessage('✅ فاکتور با موفقیت تایید و کانفیگ‌ها با قالب لوکس برای کاربر ارسال گردید.', getMainKeys());

    if ($buyer_profile['refered_by'] != null) {
        $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 = $buyer_profile['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);
    }

    $linkForDb = $connection->real_escape_string(json_encode($cleanLinksForDb, JSON_UNESCAPED_UNICODE));
    $agentBought = $payInfo['agent_bought'] ? 1 : 0;
    $inbound_id_db = intval($inboundIdsArray[0]);
    $safe_remark_db = $connection->real_escape_string($remark);
    $safe_clientSubId = $connection->real_escape_string($clientSubId);

    $insertQuery = "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 
        ({$client_telegram_id}, '{$safe_clientSubId}', '', {$fid}, {$server_id}, {$inbound_id_db}, '{$safe_remark_db}', '{$safe_clientSubId}', 'vless/vmess/trojan', {$expire_date}, '{$linkForDb}', {$price}, 1, {$date}, 0, {$rahgozar}, {$agentBought})";
        
    $connection->query($insertQuery);

    if (isset($markup) && is_array($markup)) {
        unset($markup[count($markup) - 1]);
        $markup[] = [['text' => "تایید شده و صادر شد کلاینت", 'callback_data' => "NetFreedomVPN",'style' => 'success', 'icon_custom_emoji_id' => '5208880351690112495']];
        $keys = json_encode(['inline_keyboard' => array_values($markup)]);
        editKeys($keys);
    }

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

    if ($file_detail['type'] != 'client_centric') {
        $stmt = $connection->prepare("UPDATE `server_plans` SET `acount` = `acount` - 1 WHERE `id` = ?");
        $stmt->bind_param("i", $fid); $stmt->execute(); $stmt->close();
    }
    exit();
}
// -------------------------------------------------------------------------
// ۱. بخش خرید جدید و تمدید سرویس‌ها از طریق کیف پول (Wallet) - نسخه مدرن و لوکس ضد کرش
// -------------------------------------------------------------------------
if (preg_match('/payWithWallet(.*)/', (string)$data, $match)) {
    setUser();

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

    if ($payInfo->num_rows == 0) {
        $text = "/start"; $data = ""; delMessage(); exit();
    }
    $payInfo = $payInfo->fetch_assoc();

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

    if ($payInfo['state'] == "paid_with_wallet") exit();

    // هک امنیتی مدیریت: اگر کلیک‌کننده ادمین اصلی ربات بود، بررسی موجودی ولت را کاملا بای‌پَس کن
    if ($from_id != $admin && $userInfo['wallet'] < $price) {
        alert("❌ موجودی حساب شما کافی نیست! لطفاً ابتدا کیف پول خود را شارژ کنید.");
        exit();
    }

    $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'];
    $plan_title = $connection->real_escape_string($file_detail['title']);

    // واکشی مشخصات اتصال سرور
    $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']);

    // تغییر وضعیت فاکتور و کسر پول از کیف پول (کسر پول فقط برای کاربر غیر ادمین انجام می‌شود)
    $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'paid_with_wallet' WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]); $stmt->execute(); $stmt->close();

    if ($from_id != $admin) {
        $stmt = $connection->prepare("UPDATE `users` SET `wallet` = `wallet` - ? WHERE `userid` = ?");
        $stmt->bind_param("ii", $price, $uid); $stmt->execute(); $stmt->close();
    }

    $date = time();
    $expire_date = ($days > 0) ? $date + (86400 * $days) : 0;

    // -------------------------------------------------------------------------
    // 🔄 الف) زیربخش تمدید آنی سرویس موجود (Renewal) از طریق کیف پول
    // -------------------------------------------------------------------------
    if ($payInfo['type'] == "RENEW_SCONFIG") {
        $configInfo = json_decode($payInfo['description'], true);
        $remark = $configInfo['remark'];
        $finalEmail = $remark . "@tg.com"; 

        sendMessage("⏳ در حال پردازش و تمدید دوره سرویس شما در پنل سرور... لطفاً کمی صبر کنید.", null, null, $uid);

        $successRenew = false;
        if ($serverType == "marzban") {
            $response = editMarzbanConfig($server_id, ['remark' => $remark, 'days' => $days, 'volume' => $volume]);
            if (is_object($response) && $response->success) $successRenew = true;
        } 
        else {
            $inbound_id = isset($configInfo['inbound_id']) ? (int)$configInfo['inbound_id'] : 0;
            $uuid = isset($configInfo['uuid']) ? $configInfo['uuid'] : $remark;

            if ($inbound_id > 0) {
                $response = editClientTraffic($server_id, $inbound_id, $uuid, $volume, $days, "renew");
            } else {
                $response = editInboundTraffic($server_id, $uuid, $volume, $days, "renew");
            }
            if ($response) {
                $successRenew = true;
            }
        }

        if (!$successRenew) {
            alert('🔻 مشکل فنی در ارتباط با هسته سرور جهت تمدید. به مدیریت گزارش دهید.');
            exit;
        }

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

        $keys = json_encode(['inline_keyboard' => [[['text' => $buttonValues['back_to_main'], 'callback_data' => "mainMenu",'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']]]]);
        bot('deleteMessage', ['chat_id' => $from_id, 'message_id' => $message_id]);
        sendMessage("✅ <b>سرویس اکانت <code>$remark</code> با موفقیت تمدید و ترافیک آن شارژ شد.</b>\n\nنرم‌افزار خود را بروزرسانی کنید.", $keys, "HTML");

        $msgAdmin = str_replace(['TYPE', 'USER-ID', 'USERNAME', 'NAME', 'PRICE', 'REMARK', 'VOLUME', 'DAYS'], ['کیف پول', $uid, $username, $first_name, $price, $remark, $volume, $days], $mainValues['renew_account_request_message']);
        sendMessage($msgAdmin, $keys, "html", $admin);
        exit();
    }
    // -------------------------------------------------------------------------
    // 🛒 ب) زیربخش صدور اکانت خرید جدید (New Buy) از روی کیف پول (فیکس فوق پیشرفته چند اینبانده)
    // -------------------------------------------------------------------------
    else {
        $accountCount = $payInfo['agent_count'] != 0 ? intval($payInfo['agent_count']) : 1;
        $stmt = $connection->prepare("SELECT `title`, `remark`, `flag` FROM `server_info` WHERE `id` = ?");
        $stmt->bind_param("i", $server_id); $stmt->execute();
        $srvData = $stmt->get_result()->fetch_assoc(); 
        $serverTitle = $srvData['title']; 
        $srv_remark = $srvData['remark']; 
        $flag = $srvData['flag'] ?? "🇩🇪❤️"; 
        $stmt->close();

        include_once 'phpqrcode/qrlib.php';
        $agent_bought = $payInfo['agent_bought'];
        $eachPrice = $price / $accountCount;

        sendMessage("⏳ پرداخت موفقیت‌آمیز بود؛ در حال صدور و ارسال کانفیگ‌های اختصاصی شما... لطفاً صبور باشید.", null, null, $uid);
        alert($mainValues['sending_config_to_user']);

        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++) {
            // ایجاد ریمارک انگلیسی استاندارد جهت مهار کامل باگ کرش Reality در ۵ اینباند به بالا
            $rnd = rand(1111, 9999);
            $inbound_id_raw_clean = strval($inbound_id_raw);
            $isProxyInbound = (strpos($inbound_id_raw_clean, '7') !== false);
            if ($isProxyInbound) {
                $remark = "Proxy-{$uid}-{$rnd}" . ($accountCount > 1 ? "-$i" : "");
            } else {
                $remark = "User-{$uid}-{$rnd}" . ($accountCount > 1 ? "-$i" : "");
            }
            $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 {
                $groupName = determineClientGroup($finalEmail);
                $postData = [
                    "client" => [
                        "email" => $finalEmail, "totalGB" => $volumeBytes, "expiryTime" => $expiryTimestamp,
                        "tgId" => intval($uid), "limitIp" => $limitip, "enable" => true,
                        "group_name" => $groupName, "groupName" => $groupName, "group" => $groupName
                    ],
                    "inboundIds" => $inboundIdsArray
                ];

                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $panelUrl . '/panel/api/clients/add');
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData)); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'Accept: application/json', 'Authorization: Bearer ' . $apiToken]);
                $raw_res = curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch);
                
                $resDec = json_decode($raw_res, true);

                if ($http_code == 200 || (isset($resDec['success']) && $resDec['success'] == true)) {
                    $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'])) {
                        $clientSubId = $clientDecoded['obj']['client']['subId'] ?? "";
                        $clientUuid = $clientDecoded['obj']['client']['id'] ?? ""; 
                    }

                    $subUrl = $panelUrl . "/panel/api/clients/links/" . urlencode($finalEmail);
                    $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $subUrl); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json', 'Authorization: Bearer ' . $apiToken]);
                    $subRes = curl_exec($ch); curl_close($ch);
                    $subDec = json_decode($subRes, true);
                    
                    if (isset($subDec['success']) && $subDec['success'] && isset($subDec['obj'])) {
                        $rawObj = $subDec['obj'];
                        if (is_array($rawObj)) {
                            foreach ($rawObj as $key => $val) {
                                if (is_array($val)) {
                                    foreach ($val as $subVal) {
                                        if (is_string($subVal)) $configLinks[] = $subVal;
                                    }
                                } elseif (is_string($val)) {
                                    $configLinks[] = $val;
                                }
                            }
                        }
                    }
                }
            }

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

            $configLinesTxt = "";
            $cleanLinksForDb = [];
            if (!empty($configLinks)) {
                $linkCounter = 1;
                foreach ($configLinks as $singleLink) {
                    if (is_string($singleLink) && (strpos($singleLink, 'vless://') !== false || strpos($singleLink, 'vmess://') !== false || strpos($singleLink, 'trojan://') !== false)) {
                        if ($linkCounter === 1) {
                            $configLinesTxt .= "💝 <b>config 1 :</b> <code>{$singleLink}</code>\n\n";
                        }
                        $cleanLinksForDb[] = $singleLink;
                        $linkCounter++;
                    }
                }
            } 
            
            if (empty($configLinesTxt)) {
                $fallbackConfig = "vless://{$clientUuid}@{$panelHost}:2096?type=tcp&security=none#{$remark}{$flag}";
                $configLinesTxt .= "💝 <b>config :</b> <code>{$fallbackConfig}</code>\n\n";
                $cleanLinksForDb[] = $fallbackConfig;
            }

            $ipLimitTxt = ($limitip == 0) ? "بدون محدودیت" : $limitip . " کاربره";

            $acc_text = "🎉 <b>سفارش جدید شما با موفقیت صادر شد!</b>\n" .
                         "🔮 نام سرویس: <code>{$remark}</code>\n" .
                         "🔋 حجم ترافیک مجاز: <code>" . ($volume == 0 ? "نامحدود" : $volume . " گیگ") . "</code>\n" .
                         "⏰ مدت اعتبار اکانت: <code>{$days} روز</code>\n" .
                         "👥 کاربر مجاز (Limit IP): <code>{$ipLimitTxt}</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(__DIR__ . "/settings/QRCode.jpg") && function_exists('imagecreatefromjpeg') && function_exists('imagecreatefrompng')) {
                try {
                    $backgroundImage = @imagecreatefromjpeg(__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) {}
            }

            sendPhoto($file, $acc_text, json_encode(['inline_keyboard' => [[['text' => $buttonValues['back_to_main'], 'callback_data' => "mainMenu",'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']]]]), "HTML", $uid);
            if(file_exists($file)) @unlink($file);

            $linkForDb = json_encode($cleanLinksForDb, 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("isiiisssisiiii", $uid, $clientSubId, $fid, $server_id, $inbound_id_db, $remark, $clientSubId, $expire_date, $linkForDb, $eachPrice, $date, $rahgozar, $agent_bought);
            $stmt->execute(); $stmt->close();
        }

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

        if (!empty($userInfo['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 = $userInfo['refered_by'];

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

        $keys = json_encode(['inline_keyboard' => [[['text' => "بنازم خرید جدید 💸❤️", 'callback_data' => "NetFreedomVPN"]]]]);
        $msgAdmin = str_replace(['SERVERNAME', 'TYPE', 'USER-ID', 'USERNAME', 'NAME', 'PRICE', 'REMARK', 'VOLUME', 'DAYS'], [$serverTitle, 'کیف پول', $uid, $username, $first_name, $price, $remark, $volume, $days], $mainValues['buy_new_account_request']);
        sendMessage($msgAdmin, $keys, "html", $admin);
    }
    exit();
}
// -------------------------------------------------------------------
// بخش دریافت تست رایگان / سرویس هدیه (نسخه نهایی و ۱۰۰٪ پایدار با ساب‌لینک مستقیم پنل)
// -------------------------------------------------------------------
if (preg_match('/freeTrial(\d+)_(?<buyType>\w+)/', (string)$data, $match)) {
    $id = $match[1];

    if ($userInfo['freetrial'] == 'used' && !($from_id == $admin) && isset(json_decode($userInfo['discount_percent'], true)['normal']) && json_decode($userInfo['discount_percent'], true)['normal'] != "100") {
        alert('⚠️ شما قبلاً هدیه رایگان خود را دریافت کرده‌اید.');
        exit;
    }
    delMessage();

    // ۱. دریافت اطلاعات کامل پلن از دیتابیس ربات
    $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `id` = ?");
    $stmt->bind_param("i", $id); $stmt->execute();
    $file_detail = $stmt->get_result()->fetch_assoc(); $stmt->close();

    if (!$file_detail) {
        alert("❌ پلن مورد نظر یافت نشد.");
        exit;
    }

    $days = intval($file_detail['days']);
    $date = time();
    $expire_date = ($days > 0) ? $date + (86400 * $days) : 0;
    $volume = intval($file_detail['volume']);
    $price = $file_detail['price'];
    $server_id = $file_detail['server_id'];
    $acount = $file_detail['acount'];
    $inbound_id_raw = $file_detail['inbound_id']; 
    $limitip = intval($file_detail['limitip']);
    $rahgozar = $file_detail['rahgozar'];

    $agentBought = false;
    if (isset($match['buyType']) && ($match['buyType'] == "one" || $match['buyType'] == "much")) {
        $agentBought = true;
        $discounts = json_decode($userInfo['discount_percent'], true);
        if ($botState['agencyPlanDiscount'] == "on")
            $discount = $discounts['plans'][$id] ?? $discounts['normal'] ?? 0;
        else
            $discount = $discounts['servers'][$server_id] ?? $discounts['normal'] ?? 0;
        $price -= floor($price * $discount / 100);
    }

    if ($acount == 0 && $file_detail['type'] != 'client_centric') {
        alert($mainValues['out_of_connection_capacity']);
        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();

    if (!$serverInfo) { alert("❌ سرور مورد نظر پیدا نشد."); exit; }
    if ($serverInfo['ucount'] <= 0) { alert($mainValues['out_of_server_capacity']); 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']); 

    sendMessage("⏳ در حال آماده‌سازی و صدور سرویس هدیه شما... لطفاً چند لحظه صبر کنید.", null, null, $from_id);

    $srv_remark = $serverInfo['remark'];
    $flag = $serverInfo['flag'] ?? "🇩🇪❤️"; // پرچم سرور

    $rnd = rand(1111, 9999);
    $remark = "Gift-{$from_id}-{$rnd}";
    if ($from_id == $admin && !empty($userInfo['temp']) && strpos((string)$userInfo['temp'], 'session:') !== 0) {
        $remark = $userInfo['temp'];
        setUser('', 'temp');
    }
    $finalEmail = $remark . "@tg.com"; 

    $volumeBytes = $volume * 1073741824; 
    $expiryTimestamp = ($days > 0) ? (time() + ($days * 86400)) * 1000 : 0;

    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]; 

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

    // ۳. ارسال درخواست به سرور بر اساس ساختار کلاینت‌محور جدید سنایی
    if ($serverType == "marzban") {
        $response = addMarzbanUser($server_id, $remark, $volume, $days, $id);
        if (is_object($response) && isset($response->sub_link)) {
            $directSubLink = $panelUrl . $response->sub_link;
            $configLinks[] = $directSubLink;
            $clientSubId = $clientUuid = str_replace("/sub/", "", $response->sub_link);
        }
    } 
    else {
        $clientUuid = generateUID();
        $response = addInboundAccount($server_id, $clientUuid, $inboundIdsArray[0], $expiryTimestamp, $remark, $volume, $limitip, null, $id);
        
        if (is_null($response) || !$response->success) {
            $errorDetails = isset($response->msg) ? $response->msg : "عدم پاسخگویی یا خطا در ارتباط با سرور";
            alert("❌ خطا در صدور از سمت پنل سرور:\n$errorDetails", true);
            exit;
        }
        
        $clientSubId = basename($response->subLink);
        
        // واکشی آنی تمام کانفیگ‌های اتصال متصل به این کاربر با استفاده از API Token
        $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}";

    // ۴. ساخت فرمت و قالب فوق‌العاده جذاب و لوکس قدیمی برای ادمین/کاربر
    alert($mainValues['sending_config_to_user']);
    include_once 'phpqrcode/qrlib.php';
    define('IMAGE_WIDTH', 540); define('IMAGE_HEIGHT', 540);

    $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}{$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 = "pay/" . RandomString(10) . ".png";
    @QRcode::png($directSubLink, $file, 'L', 10, 2);

    // بررسی امن جهت اعمال بک‌گراند بدون ریسک قفل شدن کل اسکریپت ربات
    if (file_exists($file) && file_exists(__DIR__ . "/settings/QRCode.jpg") && function_exists('imagecreatefromjpeg') && function_exists('imagecreatefrompng')) {
        try {
            $backgroundImage = @imagecreatefromjpeg(__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) {
            // در صورت هرگونه تداخل در لایبرری عکس، بدون خطا ریکاور شود
        }
    }

    // تحویل فوری پکت خروجی لایسنس به صورت عکس، یا متن پشتیبان در صورت خطا
    $photoSent = false;
    if (file_exists($file)) {
        $res = sendPhoto($file, $acc_text, json_encode(['inline_keyboard' => [[['text' => $buttonValues['back_to_main'], 'callback_data' => "mainMenu",'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']]]]), "HTML", $from_id);
        if ($res && isset($res->ok) && $res->ok) {
            $photoSent = true;
        }
        @unlink($file);
    }

    if (!$photoSent) {
        sendMessage($acc_text, json_encode(['inline_keyboard' => [[['text' => $buttonValues['back_to_main'], 'callback_data' => "mainMenu",'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']]]]), "HTML", $from_id);
    }

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

    // ۵. ثبت دقیق سوابق در Orders List ربات (ذخیره ساب‌آیدی واقعی در فیلد token و uuid)
    $localToken = substr(md5(time() . rand(1111, 9999)), 0, 30);
    $linkForDb = json_encode($configLinks, JSON_UNESCAPED_UNICODE);
    $inbound_id_db = $inboundIdsArray[0];
    $protocol_placeholder = "vless/vmess/trojan";

    $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, ?, ?)");

    $stmt->bind_param("isiiisssisiiii", $from_id, $clientSubId, $id, $server_id, $inbound_id_db, $remark, $clientSubId, $protocol_placeholder, $expire_date, $linkForDb, $price, $date, $rahgozar, $agentBought);
    $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();

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

    setUser('used', 'freetrial');
    exit();
}
if (preg_match('/payRenewWithCartToCart(.*)/', (string)$data, $match)) {
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]);
    $stmt->execute();
    $payInfo = $stmt->get_result();
    $stmt->close();

    if ($payInfo->num_rows == 0) {
        $text = "/start";
        $data = "";
        delMessage();
    //   goto GOTOSTART;
    }
    $payInfo = $payInfo->fetch_assoc();

    $oid = $payInfo['plan_id'];

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

    setUser($data);
    delMessage();

    $resMsg = sendMessage(str_replace(['ACCOUNT-NUMBER', 'HOLDER-NAME'], [$paymentKeys['bankAccount'], $paymentKeys['holderName']], $mainValues['renew_ccount_cart_to_cart']), $cancelKey, "html");
    if ($resMsg && isset($resMsg->result->message_id)) {
        setUser($resMsg->result->message_id, 'temp');
    }
    exit;
}
// -------------------------------------------------------------------------
// بخش تمدید سرویس کارت به کارت - نسخه فوق ایمن و ۱۰۰٪ فیکس شده
// -------------------------------------------------------------------------
if (preg_match('/payRenewWithCartToCart(.*)/', (string)$userInfo['step'], $match) && $text != $buttonValues['cancel']) {
    if (isset($update->message->photo)) {
        global $connection, $admin, $buttonValues, $mainValues, $botUrl, $from_id, $username, $first_name, $removeKeyboard;
        
        $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
        $stmt->bind_param("s", $match[1]);
        $stmt->execute();
        $payInfo = $stmt->get_result()->fetch_assoc();
        $hash_id = $payInfo['hash_id'] ?? '';
        $stmt->close();

        if (empty($hash_id)) exit();

        $oid = $payInfo['plan_id'];

        $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `id` = ?");
        $stmt->bind_param("i", $oid);
        $stmt->execute();
        $order = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        
        $fid = $order['fileid'];
        $remark = $order['remark'];
        $uid = $order['userid'];

        $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `id` = ?");
        $stmt->bind_param("i", $fid);
        $stmt->execute();
        $respd = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        
        $price = $payInfo['price'];
        $fileprice = number_format($price);
        $volume = $respd['volume'] ?? 0;
        $days = $respd['days'] ?? 0;
        
        $volumeTxt = ($volume == 0) ? "نامحدود" : $volume . " گیگ";
        $daysTxt = ($days == 0) ? "نامحدود" : $days . " روز";

        $photoArray = $update->message->photo;
        $fileid = $photoArray[count($photoArray) - 1]->file_id;

        setUser();
        $msgToDelete = intval($userInfo['temp'] ?? 0);
        if ($msgToDelete > 0) {
            @bot('deleteMessage', ['chat_id' => $from_id, 'message_id' => $msgToDelete]);
            setUser(null, 'temp');
        }
        @bot('deleteMessage', ['chat_id' => $from_id, 'message_id' => $message_id]);
        sendMessage("✅ <b>رسید شما برای ادمین ارسال شد. منتظر تایید و صدور بمانید.</b>", getMainKeys(), "HTML");

        $discountUsedText = "";
        if (preg_match('/^Discount Code: (.*)/', (string)($payInfo['description'] ?? ''), $dMatch)) {
            $discountUsedText = "\n🔑 کد تخفیف اعمال شده: <code>" . $dMatch[1] . "</code>";
        }
        $originalPlanPrice = $respd['price'] ?? 0;
        if ($originalPlanPrice > 0 && $price < $originalPlanPrice) {
            $discountUsedText .= "\n🎁 تخفیف اعمال شده: بله (مبلغ اصلی: " . number_format($originalPlanPrice) . " تومان)";
        }

        // متن لوکس، خوانا و بدون شکستگی تگ‌های ساختار متن تلگرام
        $msg = "♻️ <b>درخواست تمدید سرویس (کارت به کارت)</b>\n\n" .
               "👤 خریدار: <a href='tg://user?id={$from_id}'>{$first_name}</a>\n" .
               "🆔 آیدی عددی: <code>{$from_id}</code>\n" .
               "💬 یوزرنیم: @{$username}\n" .
               "💵 مبلغ پرداختی: <code>{$fileprice} تومان</code>" . $discountUsedText . "\n" .
               "---------------------------------------\n" .
               "🔮 نام سرویس: <code>{$remark}</code>\n" .
               "🔋 حجم تمدید: <code>{$volumeTxt}</code>\n" .
               "⏰ زمان تمدید: <code>{$daysTxt}</code>";

        // فیکس دکمه‌ها با پاس دادن دقیق استیکرهای متنی فابریک و معتبر
        $keyboard = json_encode([
            'inline_keyboard' => [
                [
                    ['text' => "تایید تمدید سرویس", 'callback_data' => "approveRenewAcc" . $hash_id, 'style' => 'success', 'icon_custom_emoji_id' => '5208880351690112495'],
                    ['text' => "عدم تایید", 'callback_data' => "decRenewAcc" . $hash_id, 'style' => 'danger', 'icon_custom_emoji_id' => '5215680783863261658']
                ]
            ]
        ]);

        $res = sendPhoto($fileid, $msg, $keyboard, "HTML", $admin);
        
        // ✨ فیکس قطعی ارور لاگ خط ۳۱۵۱ (تشخیص داینامیک خروجی آرایه‌ای یا آبجکتی)
        $msgId = 0;
        if (is_object($res) && isset($res->result->message_id)) $msgId = $res->result->message_id;
        elseif (is_array($res) && isset($res['result']['message_id'])) $msgId = $res['result']['message_id'];

        setUser();

        $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'have_sent', `message_id` = ?, `chat_id` = ? WHERE `hash_id` = ?");
        $stmt->bind_param("iis", $msgId, $admin, $hash_id);
        $stmt->execute();
        $stmt->close();
    }
    else {
        sendMessage($mainValues['please_send_only_image']);
    }
    exit();
}

// -------------------------------------------------------------------------
// بخش تایید تمدید سرویس توسط ادمین
// -------------------------------------------------------------------------
if (preg_match('/^approveRenewAcc(.*)/', (string)$data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    global $connection, $admin, $mainValues;
    $time = time(); // ✨ فیکس: تعریف متغیر زمان زنده جاری
    $hash_id_key = trim($match[1]);

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

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

    $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'approved' WHERE `hash_id` = ?");
    $stmt->bind_param("s", $hash_id_key);
    $stmt->execute();
    $stmt->close();

    $uid = $payInfo['user_id'];
    $oid = $payInfo['plan_id'];
    
    $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `id` = ?");
    $stmt->bind_param("i", $oid);
    $stmt->execute();
    $order = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    $fid = $order['fileid'];
    $remark = $order['remark'];
    $uuid = $order['uuid'] ?? "0";
    $server_id = $order['server_id'];
    $inbound_id = $order['inbound_id'];

    $plan_id_to_fetch = (isset($payInfo['volume']) && $payInfo['volume'] > 0) ? $payInfo['volume'] : $fid;

    $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `id` = ?");
    $stmt->bind_param("i", $plan_id_to_fetch);
    $stmt->execute();
    $respd = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    $days = intval($respd['days']);
    $volume = intval($respd['volume']);
    $price = $payInfo['price'];

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

    if ($serverType == "marzban") {
        $response = editMarzbanConfig($server_id, ['remark' => $remark, 'days' => $days, 'volume' => $volume]);
    }
    else {
        if ($serverType == "sanaei" || $inbound_id > 0) {
            $response = editClientTraffic($server_id, $inbound_id, $uuid, $volume, $days, "renew");
        } else {
            $response = editInboundTraffic($server_id, $uuid, $volume, $days, "renew");
        }
    }

    if (is_null($response) || (isset($response->success) && !$response->success)) {
        alert('🔻مشکل فنی در اتصال به سرور. لطفا به مدیریت اطلاع بدید', true);
        exit();
    }

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

    // اتصال زمان انقضای جدید به انتهای زمان معتبر باقیمانده قبلی مشتری
    $baseExpire = ($order['expire_date'] > $time) ? $order['expire_date'] : $time;
    $newExpire = $baseExpire + ($days * 86400);

    $stmt = $connection->prepare("UPDATE `orders_list` SET `expire_date` = ?, `status` = 1, `notif` = 0 WHERE `id` = ?");
    $stmt->bind_param("ii", $newExpire, $oid);
    $stmt->execute();
    $stmt->close();
    
    $stmt = $connection->prepare("INSERT INTO `increase_order` VALUES (NULL, ?, ?, ?, ?, ?, ?);");
    $stmt->bind_param("iiisii", $uid, $server_id, $inbound_id, $remark, $price, $time);
    $stmt->execute();
    $stmt->close();
    
    $volumeTxt = ($volume == 0) ? "نامحدود" : $volume . " گیگ";
    $acc_text = "🎉 <b>سرویس شما با موفقیت تمدید شد!</b>\n" .
                 "🔮 نام سرویس: <code>{$remark}</code>\n" .
                 "🔋 حجم افزوده شده: <code>{$volumeTxt}</code>\n" .
                 "⏰ اعتبار تمدید: <code>{$days} روز</code>\n";

    sendMessage($acc_text, getMainKeys(), "HTML", $uid);
    sendMessage("✅ تمدید فاکتور کارت به کارت با موفقیت در پنل اعمال و به کاربر تحویل داده شد.", null, "HTML", $admin);
    exit();
}

// -------------------------------------------------------------------------
// بخش لغو یا رد درخواست تمدید توسط ادمین
// -------------------------------------------------------------------------
if (preg_match('/^decRenewAcc(.*)/', (string)$data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    global $connection, $admin;
    $hash_id_key = trim($match[1]);

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

    if (!$payInfo) exit();
    
    $uid = $payInfo['user_id'];
    $oid = $payInfo['plan_id'];

    $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `id` = ?");
    $stmt->bind_param("i", $oid);
    $stmt->execute();
    $order = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $remark = $order['remark'] ?? 'سرویس متوقف شده';

    $keys = json_encode(['inline_keyboard' => [[['text' => 'درخواست تمدید لغو و رد شد', 'callback_data' => "NetFreedomVPN", 'style' => 'danger', 'icon_custom_emoji_id' => '5215680783863261658']]]]);
    editKeys($keys);
    
    sendMessage("😖|درخواست تمدید سرویس <code>$remark</code> توسط مدیریت لغو و رد شد.", null, "HTML", $uid);
    exit();
}

if (preg_match('/payRenewWithWallet(.*)/', (string)$data, $match)) {
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]);
    $stmt->execute();
    $payInfo = $stmt->get_result();
    $stmt->close();

    if ($payInfo->num_rows == 0) {
        $text = "/start";
        $data = "";
        delMessage();
    //  goto GOTOSTART;
    }
    $payInfo = $payInfo->fetch_assoc();
    $hash_id = $payInfo['hash_id'];

    if ($payInfo['state'] == "paid_with_wallet")
        exit();

    $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'paid_with_wallet' WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]);
    $stmt->execute();
    $stmt->close();

    $oid = $payInfo['plan_id'];
    $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();

    $fid = $order['fileid'];
    $remark = $order['remark'];
    $uuid = $order['uuid'] ?? "0";
    $server_id = $order['server_id'];
    $inbound_id = $order['inbound_id'];
    $expire_date = $order['expire_date'];
    $expire_date = ($expire_date > $time) ? $expire_date : $time;

    $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `id` = ?");
    $stmt->bind_param("i", $fid);
    $stmt->execute();
    $respd = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $name = $respd['title'];
    $days = $respd['days'];
    $volume = $respd['volume'];
    $price = $payInfo['price'];

    $userwallet = $userInfo['wallet'];

    if ($userwallet < $price) {
        $needamount = $price - $userwallet;
        alert("💡موجودی کیف پول (" . number_format($userwallet) . " تومان) کافی نیست لطفا به مقدار " . number_format($needamount) . " تومان شارژ کنید ", true);
        exit;
    }


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

    if ($serverType == "marzban") {
        $response = editMarzbanConfig($server_id, ['remark' => $remark, 'days' => $days, 'volume' => $volume]);
    }
    else {
        if ($inbound_id > 0)
            $response = editClientTraffic($server_id, $inbound_id, $uuid, $volume, $days, "renew");
        else
            $response = editInboundTraffic($server_id, $uuid, $volume, $days, "renew");
    }

    if (is_null($response)) {
        alert('🔻مشکل فنی در اتصال به سرور. لطفا به مدیریت اطلاع بدید', true);
        exit;
    }
    $stmt = $connection->prepare("UPDATE `orders_list` SET `expire_date` = ?, `notif` = 0 WHERE `id` = ?");
    $newExpire = $time + $days * 86400;
    $stmt->bind_param("ii", $newExpire, $oid);
    $stmt->execute();
    $stmt->close();
    $stmt = $connection->prepare("INSERT INTO `increase_order` VALUES (NULL, ?, ?, ?, ?, ?, ?);");
    $stmt->bind_param("iiisii", $from_id, $server_id, $inbound_id, $remark, $price, $time);
    $stmt->execute();
    $stmt->close();

    $stmt = $connection->prepare("UPDATE `users` SET `wallet` = `wallet` - ? WHERE `userid` = ?");
    $stmt->bind_param("ii", $price, $from_id);
    $stmt->execute();
    $stmt->close();
    editText($message_id, "✅سرویس $remark با موفقیت تمدید شد", getMainKeys());
    $keys = json_encode(['inline_keyboard' => [
            [
                ['text' => "به به تمدید 😍", 'callback_data' => "NetFreedomVPN"]
            ],
        ]]);
    $msg = str_replace(['TYPE', "USER-ID", "USERNAME", "NAME", "PRICE", "REMARK", "VOLUME", "DAYS"], ['کیف پول', $from_id, $username, $first_name, $price, $remark, $volume, $days], $mainValues['renew_account_request_message']);

    sendMessage($msg, $keys, "html", $admin);
    exit;
}
if (preg_match('/selectPlanDayIncrease(?<orderId>.+)_(?<dayId>.+)/', (string)$data, $match)) {
    $data = str_replace('selectPlanDayIncrease', '', $data);
    $pid = $match['dayId'];
    $stmt = $connection->prepare("SELECT * FROM `increase_day` WHERE `id` = ?");
    $stmt->bind_param("i", $pid);
    $stmt->execute();
    $res = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $planprice = $res['price'];

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

    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'];

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


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

    $time = time();
    $stmt = $connection->prepare("INSERT INTO `pays` (`hash_id`, `user_id`, `type`, `plan_id`, `volume`, `day`, `price`, `request_date`, `state`)
                                VALUES (?, ?, ?, '0', '0', '0', ?, ?, 'pending')");
    $type = "INCREASE_DAY_$data";
    $stmt->bind_param("sisii", $hash_id, $from_id, $type, $planprice, $time);
    $stmt->execute();
    $stmt->close();


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

    $keyboard[] = [['text' => $buttonValues['cancel'], 'callback_data' => "mainMenu",'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']];
    editText($message_id, "لطفا با یکی از روش های زیر پرداخت خود را تکمیل کنید :", json_encode(['inline_keyboard' => $keyboard]));
}
if (preg_match('/payIncreaseDayWithCartToCart(.*)/', (string)$data, $match)) {
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]);
    $stmt->execute();
    $payInfo = $stmt->get_result();
    $stmt->close();
    if ($payInfo->num_rows == 0) {
        $text = "/start";
        $data = "";
        delMessage();
    //   goto GOTOSTART;
    }

    delMessage();
    setUser($data);
    sendMessage(str_replace(['ACCOUNT-NUMBER', 'HOLDER-NAME'], [$paymentKeys['bankAccount'], $paymentKeys['holderName']], $mainValues['renew_ccount_cart_to_cart']), $cancelKey, "html");

    exit;
}
if (preg_match('/payIncreaseDayWithCartToCart(.*)/', (string)$userInfo['step'], $match) and $text != $buttonValues['cancel']) {
    if (isset($update->message->photo)) {
        $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
        $stmt->bind_param("s", $match[1]);
        $stmt->execute();
        $payInfo = $stmt->get_result();
        $stmt->close();

        $payParam = $payInfo->fetch_assoc();
        $payType = $payParam['type'];


        preg_match('/^INCREASE_DAY_(\d+)_(\d+)/', $payType, $increaseInfo);
        $orderId = $increaseInfo[1];

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

        $server_id = $orderInfo['server_id'];
        $inbound_id = $orderInfo['inbound_id'];
        $remark = $orderInfo['remark'];

        $planid = $increaseInfo[2];

        $stmt = $connection->prepare("SELECT * FROM `increase_day` WHERE `id` = ?");
        $stmt->bind_param("i", $planid);
        $stmt->execute();
        $res = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        $price = $payParam['price'];
        $volume = $res['volume'];

        @bot('deleteMessage', ['chat_id' => $from_id, 'message_id' => $message_id]);
        @bot('deleteMessage', ['chat_id' => $from_id, 'message_id' => $message_id - 1]);
        sendMessage("✅ <b>رسید شما برای ادمین ارسال شد. منتظر تایید و صدور بمانید.</b>", getMainKeys(), "HTML");

        // notify admin   
        $msg = str_replace(['INCREASE', 'TYPE', "USER-ID", "USERNAME", "NAME", "PRICE", "REMARK"], [$volume, 'زمان', $from_id, $username, $first_name, $price, $remark], $mainValues['increase_account_request_message']);

        $keyboard = json_encode([
            'inline_keyboard' => [
                [
                    [
                        'text' => $buttonValues['approve'], 
                        'callback_data' => "approveIncreaseDay{$match[1]}",
                        'style' => $buttonProps['approve']['style'] ?? 'success',
                        'icon_custom_emoji_id' => $buttonProps['approve']['icon_custom_emoji_id'] ?? null
                    ],
                    [
                        'text' => $buttonValues['decline'], 
                        'callback_data' => "decIncreaseDay{$match[1]}",
                        'style' => $buttonProps['decline']['style'] ?? 'danger',
                        'icon_custom_emoji_id' => $buttonProps['decline']['icon_custom_emoji_id'] ?? null
                    ]
                ]
            ]
        ]);


        $res = sendPhoto($fileid, $msg, $keyboard, "HTML", $admin);
        $msgId = $res->result->message_id;
        setUser();

        $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'have_sent', `message_id` = ?, `chat_id` = ? WHERE `hash_id` = ?");
        $stmt->bind_param("iis", $msgId, $admin, $match[1]);
        $stmt->execute();
        $stmt->close();
    }
    else {
        sendMessage($mainValues['please_send_only_image']);
    }

}
if (preg_match('/approveIncreaseDay(.*)/', (string)$data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]);
    $stmt->execute();
    $payInfo = $stmt->get_result();
    $stmt->close();
    $payParam = $payInfo->fetch_assoc();
    $payType = $payParam['type'];

    if ($payParam['state'] == "approved")
        exit();

    $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'approved' WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]);
    $stmt->execute();
    $stmt->close();



    preg_match('/^INCREASE_DAY_(\d+)_(\d+)/', $payType, $increaseInfo);
    $orderId = $increaseInfo[1];

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

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

    $planid = $increaseInfo[2];


    $uid = $payParam['user_id'];

    $stmt = $connection->prepare("SELECT * FROM `increase_day` WHERE `id` = ?");
    $stmt->bind_param("i", $planid);
    $stmt->execute();
    $res = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $price = $res['price'];
    $volume = $res['volume'];

    $acctxt = '';

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

    unset($markup[count($markup) - 1]);

    if ($serverType == "marzban") {
        $response = editMarzbanConfig($server_id, ['remark' => $remark, 'plus_day' => $volume]);
    }
    else {
        if ($inbound_id > 0)
            $response = editClientTraffic($server_id, $inbound_id, $uuid, 0, $volume);
        else
            $response = editInboundTraffic($server_id, $uuid, 0, $volume);
    }

    if ($response->success) {
        $stmt = $connection->prepare("UPDATE `orders_list` SET `expire_date` = `expire_date` + ?, `notif` = 0 WHERE `uuid` = ?");
        $newVolume = $volume * 86400;
        $stmt->bind_param("is", $newVolume, $uuid);
        $stmt->execute();
        $stmt->close();

        $stmt = $connection->prepare("INSERT INTO `increase_order` VALUES (NULL, ?, ?, ?, ?, ?, ?);");
        $newVolume = $volume * 86400;
        $stmt->bind_param("iiisii", $uid, $server_id, $inbound_id, $remark, $price, $time);
        $stmt->execute();
        $stmt->close();
        $markup[] = [['text' => '✅', 'callback_data' => "dontsendanymore"]];
        $keys = json_encode(['inline_keyboard' => array_values($markup)], 488);

        editKeys($keys);
        sendMessage("✅$volume روز به مدت زمان سرویس شما اضافه شد", null, null, $uid);
    }
    else {
        alert("مشکل فنی در ارتباط با سرور. لطفا سلامت سرور را بررسی کنید", true);
        exit;
    }
}
if (preg_match('/payIncraseDayWithWallet(.*)/', (string)$data, $match)) {
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]);
    $stmt->execute();
    $payInfo = $stmt->get_result();
    $stmt->close();

    if ($payInfo->num_rows == 0) {
        $text = "/start";
        $data = "";
        delMessage();
    //  goto GOTOSTART;
    }
    $payParam = $payInfo->fetch_assoc();
    $payType = $payParam['type'];

    $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'paid_with_wallet' WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]);
    $stmt->execute();
    $stmt->close();

    preg_match('/^INCREASE_DAY_(\d+)_(\d+)/', $payType, $increaseInfo);
    $orderId = $increaseInfo[1];

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

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

    $planid = $increaseInfo[2];

    $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'];


    $stmt = $connection->prepare("SELECT * FROM `increase_day` WHERE `id` = ?");
    $stmt->bind_param("i", $planid);
    $stmt->execute();
    $res = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $price = $payParam['price'];
    $volume = $res['volume'];

    $userwallet = $userInfo['wallet'];

    if ($userwallet < $price) {
        $needamount = $price - $userwallet;
        alert("💡موجودی کیف پول (" . number_format($userwallet) . " تومان) کافی نیست لطفا به مقدار " . number_format($needamount) . " تومان شارژ کنید ", true);
        exit;
    }



    if ($serverType == "marzban") {
        $response = editMarzbanConfig($server_id, ['remark' => $remark, 'plus_day' => $volume]);
    }
    else {
        if ($inbound_id > 0)
            $response = editClientTraffic($server_id, $inbound_id, $uuid, 0, $volume);
        else
            $response = editInboundTraffic($server_id, $uuid, 0, $volume);
    }

    if ($response->success) {
        $stmt = $connection->prepare("UPDATE `orders_list` SET `expire_date` = `expire_date` + ?, `notif` = 0 WHERE `uuid` = ?");
        $newVolume = $volume * 86400;
        $stmt->bind_param("is", $newVolume, $uuid);
        $stmt->execute();
        $stmt->close();

        $stmt = $connection->prepare("INSERT INTO `increase_order` VALUES (NULL, ?, ?, ?, ?, ?, ?);");
        $newVolume = $volume * 86400;
        $stmt->bind_param("iiisii", $from_id, $server_id, $inbound_id, $remark, $price, $time);
        $stmt->execute();
        $stmt->close();

        $stmt = $connection->prepare("UPDATE `users` SET `wallet` = `wallet` - ? WHERE `userid` = ?");
        $stmt->bind_param("ii", $price, $from_id);
        $stmt->execute();
        $stmt->close();
        editText($message_id, "✅$volume روز به مدت زمان سرویس شما اضافه شد", getMainKeys());

        $keys = json_encode(['inline_keyboard' => [
                [
                    ['text' => "اخیش یکی زمان زد 😁", 'callback_data' => "NetFreedomVPN"]
                ],
            ]]);
        sendMessage("
🔋|💰 افزایش زمان با ( کیف پول )

▫️آیدی کاربر: $from_id
👨‍💼اسم کاربر: $first_name
⚡️ نام کاربری: $username
🎈 نام سرویس: $remark
⏰ مدت افزایش: $volume روز
💰قیمت: $price تومان
⁮⁮ ⁮⁮
        ", $keys, "html", $admin);

        exit;
    }
    else {
        alert("به دلیل مشکل فنی امکان افزایش حجم نیست. لطفا به مدیریت اطلاع بدید یا 5دقیقه دیگر دوباره تست کنید", true);
        exit;
    }
}
if (preg_match('/^increaseAVolume(.*)/', (string)$data, $match)) {
    $stmt = $connection->prepare("SELECT * FROM `increase_plan`");
    $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' => "increaseVolumePlan{$match[1]}_{$id}"];
    }
    $keyboard = array_chunk($keyboard, 2);
    $keyboard[] = [getBtn('back_to_main', 'mainMenu')];
    $res = editText($message_id, "لطفا یکی از پلن های حجمی را انتخاب کنید :", json_encode([
        'inline_keyboard' => $keyboard
    ]));
}
if (preg_match('/increaseVolumePlan(?<orderId>.+)_(?<volumeId>.+)/', (string)$data, $match)) {
    $data = str_replace('increaseVolumePlan', '', $data);
    $stmt = $connection->prepare("SELECT * FROM `increase_plan` WHERE `id` = ?");
    $stmt->bind_param("i", $match['volumeId']);
    $stmt->execute();
    $res = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $planprice = $res['price'];
    $plangb = $res['volume'];

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

    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'];

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

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

    $time = time();
    $stmt = $connection->prepare("INSERT INTO `pays` (`hash_id`, `user_id`, `type`, `plan_id`, `volume`, `day`, `price`, `request_date`, `state`)
                                VALUES (?, ?, ?, '0', '0', '0', ?, ?, 'pending')");
    $type = "INCREASE_VOLUME_$data";
    $stmt->bind_param("sisii", $hash_id, $from_id, $type, $planprice, $time);
    $stmt->execute();
    $stmt->close();

    $keyboard = array();

    if ($planprice == 0)
        $planprice = ' رایگان';
    else
        $planprice = " " . number_format($planprice) . " تومان";


    if ($botState['cartToCartState'] == "on")
        $keyboard[] = [['text' => $buttonValues['cart_to_cart'] . $planprice, 'callback_data' => "payIncreaseWithCartToCart$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' => "💰پرداخت با موجودی  " . $planprice, 'callback_data' => "payIncraseWithWallet$hash_id"]];
    if ($botState['tronWallet'] == "on")
        $keyboard[] = [['text' => $buttonValues['tron_gateway'], 'callback_data' => "payWithTronWallet" . $hash_id]];
    if ($botState['stars'] == "on")
        $keyboard[] = [['text' => $buttonValues['stars_gateway'], 'callback_data' => "payWithStars" . $hash_id]];    

    $keyboard[] = [getBtn('cancel', 'mainMenu')];
    editText($message_id, "لطفا با یکی از روش های زیر پرداخت خود را تکمیل کنید :", json_encode(['inline_keyboard' => $keyboard]));
}
if (preg_match('/payIncreaseWithCartToCart(.*)/', (string)$data, $match)) {
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]);
    $stmt->execute();
    $payInfo = $stmt->get_result();
    $stmt->close();
    if ($payInfo->num_rows == 0) {
        $text = "/start";
        $data = "";
        delMessage();
    //   goto GOTOSTART;
    }

    setUser($data);
    delMessage();

    sendMessage(str_replace(['ACCOUNT-NUMBER', 'HOLDER-NAME'], [$paymentKeys['bankAccount'], $paymentKeys['holderName']], $mainValues['renew_ccount_cart_to_cart']), $cancelKey, "html");
    exit;
}
if (preg_match('/payIncreaseWithCartToCart(.*)/', (string)$userInfo['step'], $match) and $text != $buttonValues['cancel']) {
    if (isset($update->message->photo)) {
        $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
        $stmt->bind_param("s", $match[1]);
        $stmt->execute();
        $payInfo = $stmt->get_result();
        $stmt->close();

        $payParam = $payInfo->fetch_assoc();
        $payType = $payParam['type'];


        preg_match('/^INCREASE_VOLUME_(\d+)_(\d+)/', $payType, $increaseInfo);
        $orderId = $increaseInfo[1];

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

        $server_id = $orderInfo['server_id'];
        $inbound_id = $orderInfo['inbound_id'];
        $remark = $orderInfo['remark'];

        $planid = $increaseInfo[2];

        $stmt = $connection->prepare("SELECT * FROM `increase_plan` WHERE `id` = ?");
        $stmt->bind_param("i", $planid);
        $stmt->execute();
        $res = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        $price = $payParam['price'];
        $volume = $res['volume'];
        $state = str_replace('payIncreaseWithCartToCart', '', $userInfo['step']);
        @bot('deleteMessage', ['chat_id' => $from_id, 'message_id' => $message_id]);
        @bot('deleteMessage', ['chat_id' => $from_id, 'message_id' => $message_id - 1]);
        sendMessage("✅ <b>رسید شما برای ادمین ارسال شد. منتظر تایید و صدور بمانید.</b>", getMainKeys(), "HTML");

        // notify admin

        $msg = str_replace(['INCREASE', 'TYPE', "USER-ID", "USERNAME", "NAME", "PRICE", "REMARK"], [$volume, 'حجم', $from_id, $username, $first_name, $price, $remark], $mainValues['increase_account_request_message']);

        $keyboard = json_encode([
            'inline_keyboard' => [
                [
                    [
                        'text' => $buttonValues['approve'], 
                        'callback_data' => "approveIncreaseVolume{$match[1]}",
                        'style' => $buttonProps['approve']['style'] ?? 'success',
                        'icon_custom_emoji_id' => $buttonProps['approve']['icon_custom_emoji_id'] ?? null
                    ],
                    [
                        'text' => $buttonValues['decline'], 
                        'callback_data' => "decIncreaseVolume{$match[1]}",
                        'style' => $buttonProps['decline']['style'] ?? 'danger',
                        'icon_custom_emoji_id' => $buttonProps['decline']['icon_custom_emoji_id'] ?? null
                    ]
                ]
            ]
        ]);

        $res = sendPhoto($fileid, $msg, $keyboard, "HTML", $admin);
        $msgId = $res->result->message_id;
        setUser();

        $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'have_sent', `message_id` = ?, `chat_id` = ? WHERE `hash_id` = ?");
        $stmt->bind_param("iis", $msgId, $admin, $match[1]);
        $stmt->execute();
        $stmt->close();
    }
    else {
        sendMessage($mainValues['please_send_only_image']);
    }
}
if (preg_match('/approveIncreaseVolume(.*)/', (string)$data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]);
    $stmt->execute();
    $payInfo = $stmt->get_result();
    $stmt->close();

    $payParam = $payInfo->fetch_assoc();
    $payType = $payParam['type'];

    if ($payParam['state'] == "approved")
        exit();

    $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'approved' WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]);
    $stmt->execute();
    $stmt->close();


    preg_match('/^INCREASE_VOLUME_(\d+)_(\d+)/', $payType, $increaseInfo);
    $orderId = $increaseInfo[1];

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

    $server_id = $orderInfo['server_id'];
    $inbound_id = $orderInfo['inbound_id'];
    $remark = $orderInfo['remark'];
    $uuid = $orderInfo['uuid'] ?? "0";
    $planid = $increaseInfo[2];

    $uid = $payParam['user_id'];
    $stmt = $connection->prepare("SELECT * FROM `increase_plan` WHERE `id` = ?");
    $stmt->bind_param("i", $planid);
    $stmt->execute();
    $res = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $price = $res['price'];
    $volume = $res['volume'];

    $acctxt = '';

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

    if ($serverType == "marzban") {
        $response = editMarzbanConfig($server_id, ['remark' => $remark, 'plus_volume' => $volume]);
    }
    else {
        if ($inbound_id > 0)
            $response = editClientTraffic($server_id, $inbound_id, $uuid, $volume, 0);
        else
            $response = editInboundTraffic($server_id, $uuid, $volume, 0);
    }

    if ($response->success) {
        $stmt = $connection->prepare("UPDATE `orders_list` SET `notif` = 0 WHERE `uuid` = ?");
        $stmt->bind_param("s", $uuid);
        $stmt->execute();
        $stmt->close();
        unset($markup[count($markup) - 1]);
        $markup[] = [['text' => '✅', 'callback_data' => "dontsendanymore"]];
        $keys = json_encode(['inline_keyboard' => array_values($markup)], 488);

        editKeys($keys);
        sendMessage("✅$volume گیگ به حجم سرویس شما اضافه شد", null, null, $uid);
    }
    else {
        alert("مشکل فنی در ارتباط با سرور. لطفا سلامت سرور را بررسی کنید", true);
        exit;
    }
}
if (preg_match('/decIncreaseVolume(.*)/', (string)$data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]);
    $stmt->execute();
    $payInfo = $stmt->get_result();
    $stmt->close();

    $payParam = $payInfo->fetch_assoc();
    $payType = $payParam['type'];


    preg_match('/^INCREASE_VOLUME_(\d+)_(\d+)/', $payType, $increaseInfo);
    $orderId = $increaseInfo[1];

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

    $server_id = $orderInfo['server_id'];
    $inbound_id = $orderInfo['inbound_id'];
    $remark = $orderInfo['remark'];

    $planid = $increaseInfo[2];


    $uid = $payParam['user_id'];
    $stmt = $connection->prepare("SELECT * FROM `increase_plan` WHERE `id` = ?");
    $stmt->bind_param("i", $planid);
    $stmt->execute();
    $res = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $price = $res['price'];
    $volume = $res['volume'];

    $acctxt = '';
    editKeys(json_encode(['inline_keyboard' => [
            [['text' => "لغو شد ❌", 'callback_data' => "NetFreedomVPN"]]
        ]]));

    sendMessage("افزایش حجم $volume گیگ اشتراک $remark لغو شد", null, null, $uid);
}
if (preg_match('/decIncreaseDay(.*)/', (string)$data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]);
    $stmt->execute();
    $payInfo = $stmt->get_result();
    $stmt->close();

    $payParam = $payInfo->fetch_assoc();
    $payType = $payParam['type'];


    preg_match('/^INCREASE_DAY_(\d+)_(\d+)/', $payType, $increaseInfo);
    $orderId = $increaseInfo[1];

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

    $server_id = $orderInfo['server_id'];
    $inbound_id = $orderInfo['inbound_id'];
    $remark = $orderInfo['remark'];

    $planid = $increaseInfo[2];


    $uid = $payParam['user_id'];
    $stmt = $connection->prepare("SELECT * FROM `increase_day` WHERE `id` = ?");
    $stmt->bind_param("i", $planid);
    $stmt->execute();
    $res = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $price = $res['price'];
    $volume = $res['volume'];

    $acctxt = '';
    editKeys(json_encode(['inline_keyboard' => [
            [['text' => "لغو شد ❌", 'callback_data' => "NetFreedomVPN"]]
        ]]));

    sendMessage("افزایش زمان $volume روز اشتراک $remark لغو شد", null, null, $uid);
}
if (preg_match('/payIncraseWithWallet(.*)/', (string)$data, $match)) {
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]);
    $stmt->execute();
    $payInfo = $stmt->get_result();
    $stmt->close();

    if ($payInfo->num_rows == 0) {
        $text = "/start";
        $data = "";
        delMessage();
    //   goto GOTOSTART;
    }

    $payParam = $payInfo->fetch_assoc();
    $payType = $payParam['type'];

    $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'paid_with_wallet' WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]);
    $stmt->execute();
    $stmt->close();


    preg_match('/^INCREASE_VOLUME_(\d+)_(\d+)/', $payType, $increaseInfo);
    $orderId = $increaseInfo[1];

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

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

    $planid = $increaseInfo[2];


    $stmt = $connection->prepare("SELECT * FROM `increase_plan` WHERE `id` = ?");
    $stmt->bind_param("i", $planid);
    $stmt->execute();
    $res = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $price = $payParam['price'];
    $volume = $res['volume'];

    $userwallet = $userInfo['wallet'];

    if ($userwallet < $price) {
        $needamount = $price - $userwallet;
        alert("💡موجودی کیف پول (" . number_format($userwallet) . " تومان) کافی نیست لطفا به مقدار " . number_format($needamount) . " تومان شارژ کنید ", true);
        exit;
    }

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

    if ($serverType == "marzban") {
        $response = editMarzbanConfig($server_id, ['remark' => $remark, 'plus_volume' => $volume]);
    }
    else {
        if ($inbound_id > 0)
            $response = editClientTraffic($server_id, $inbound_id, $uuid, $volume, 0);
        else
            $response = editInboundTraffic($server_id, $uuid, $volume, 0);
    }

    if ($response->success) {
        $stmt = $connection->prepare("UPDATE `users` SET `wallet` = `wallet` - ? WHERE `userid` = ?");
        $stmt->bind_param("ii", $price, $from_id);
        $stmt->execute();
        $stmt->close();
        $stmt = $connection->prepare("UPDATE `orders_list` SET `notif` = 0 WHERE `uuid` = ?");
        $stmt->bind_param("s", $uuid);
        $stmt->execute();
        $stmt->close();
        $keys = json_encode(['inline_keyboard' => [
                [
                    ['text' => "اخیش یکی حجم زد 😁", 'callback_data' => "NetFreedomVPN"]
                ],
            ]]);
        sendMessage("
🔋|💰 افزایش حجم با ( کیف پول )

▫️آیدی کاربر: $from_id
👨‍💼اسم کاربر: $first_name
⚡️ نام کاربری: $username
🎈 نام سرویس: $remark
⏰ مدت افزایش: $volume گیگ
💰قیمت: $price تومان
⁮⁮ ⁮⁮
        ", $keys, "html", $admin);
        editText($message_id, "✅$volume گیگ به حجم سرویس شما اضافه شد", getMainKeys());
        exit;


    }
    else {
        alert("به دلیل مشکل فنی امکان افزایش حجم نیست. لطفا به مدیریت اطلاع بدید یا 5دقیقه دیگر دوباره تست کنید", true);
        exit;
    }
}
?>