<?php
include_once 'config.php';
include_once 'server_manager.php';
include_once 'service_creator.php';
include_once 'trading_plans_handler.php';
include_once 'notification_system.php';
include_once 'discount_system.php';
include_once 'advanced_reports.php';
// check(); // غیرفعال شد برای رفع مشکل IP - اگر نیاز به امنیت بیشتر دارید فعالش کنید
$robotState = $botState['botState']??"on";
if ($userInfo['step'] == "banned" && $from_id != $admin && $userInfo['isAdmin'] != true) {
    sendMessage($mainValues['banned']);
    exit();
}
if(preg_match("/^haveJoined(.*)/",$data,$match)){
    if ($joniedState== "kicked" || $joniedState== "left"){
        alert($mainValues['not_joine_yet']);
        exit();
    }else{
        delMessage();
        $text = $match[1];
    }
}
if (($joniedState== "kicked" || $joniedState== "left") && $from_id != $admin){
    sendMessage(str_replace("CHANNEL-ID", $channelLock, $mainValues['join_channel_message']), json_encode(['inline_keyboard'=>[
        [['text'=>$buttonValues['join_channel'],'url'=>"https://t.me/" . str_replace("@", "", $botState['lockChannel'])]],
        [['text'=>$buttonValues['have_joined'],'callback_data'=>'haveJoined' . $text]],
        ]]),"HTML");
    exit;
}
if($robotState == "off" && $from_id != $admin){
    sendMessage($mainValues['bot_is_updating']);
    exit();
}
if(strpos($text, "/start ") !== false){
    $inviter = str_replace("/start ", "", $text);
    
    if($uinfo->num_rows == 0 && $inviter != $from_id){
        
        $first_name = !empty($first_name)?$first_name:" ";
        $username = !empty($username)?$username:" ";
        if($uinfo->num_rows == 0){
            $sql = "INSERT INTO `users` (`userid`, `name`, `username`, `refcode`, `wallet`, `date`, `refered_by`)
                                VALUES (?,?,?, 0,0,?,?)";
            $stmt = $connection->prepare($sql);
            $time = time();
            $stmt->bind_param("issii", $from_id, $first_name, $username, $time, $inviter);
            $stmt->execute();
            $stmt->close();
        }else{
            $refcode = time();
            $sql = "UPDATE `users` SET `refered_by` = ? WHERE `userid` = ?";
            $stmt = $connection->prepare($sql);
            $stmt->bind_param("si", $inviter, $from_id);
            $stmt->execute();
            $stmt->close();
        }
        $stmt = $connection->prepare("SELECT * FROM `users` WHERE `userid`=?");
        $stmt->bind_param("i", $from_id);
        $stmt->execute();
        $uinfo = $stmt->get_result();
        $userInfo = $uinfo->fetch_assoc();
        $stmt->close();
        
        setUser("referedBy" . $inviter);
        $userInfo['step'] = "referedBy" . $inviter;
        sendMessage($mainValues['invited_user_joined_message'],null,null, $inviter);
    }
    
    $text = "/start";
}
if($data == "agentsList" && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    editText($message_id,$mainValues['agents_list'], getAgentsList());
}
if(preg_match('/^agentDetails(\d+)/',$data,$match) && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $userDetail = bot('getChat',['chat_id'=>$match[1]])->result;
    $userUserName = $userDetail->username;
    $fullName = $userDetail->first_name . " " . $userDetail->last_name;

    editText($message_id,str_replace("AGENT-NAME", $fullName, $mainValues['agent_details']), getAgentDetails($match[1]));
}
if(preg_match('/^removeAgent(\d+)/',$data,$match) && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $stmt = $connection->prepare("UPDATE `users` SET `is_agent` = 0 WHERE `userid` = ?");
    $stmt->bind_param("i", $match[1]);
    $stmt->execute();
    $stmt->close();
    
    alert($mainValues['agent_deleted_successfuly']);
    editKeys(getAgentsList());
}
if(preg_match('/^editAgentDiscount(\d+)/',$data,$match) && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    delMessage();
    sendMessage($mainValues['send_agent_discount_percent'], $cancelKey);
    setUser($data);
}
if(preg_match('/^editAgentDiscount(\d+)/',$userInfo['step'],$match) && ($from_id == $admin || $userInfo['isAdmin'] == true) && $text != $buttonValues['cancel']){
    if(is_numeric($text)){
        sendMessage($mainValues['saved_successfuly'],$removeKeyboard);
        
        $stmt = $connection->prepare("UPDATE `users` SET `discount_percent` = ? WHERE `userid` = ?");
        $stmt->bind_param("ii", $text, $match[1]);
        $stmt->execute();
        $stmt->close();
        
        sendMessage($mainValues['agents_list'], getAgentsList());
        setUser();
    }else sendMessage($mainValues['send_only_number']);
}

if($userInfo['phone'] == null && $from_id != $admin && $userInfo['isAdmin'] != true && $botState['requirePhone'] == "on"){
    if(isset($update->message->contact)){
        $contact = $update->message->contact;
        $phone_number = $contact->phone_number;
        $phone_id = $contact->user_id;
        if($phone_id != $from_id){
            sendMessage($mainValues['please_select_from_below_buttons']);
            exit();
        }else{
            if(!preg_match('/^\+98(\d+)/',$phone_number) && !preg_match('/^98(\d+)/',$phone_number) && !preg_match('/^0098(\d+)/',$phone_number) && $botState['requireIranPhone'] == 'on'){
                sendMessage($mainValues['use_iranian_number_only']);
                exit();
            }
            setUser($phone_number, 'phone');
            
            sendMessage($mainValues['phone_confirmed'],$removeKeyboard);
            $text = "/start";
        }
    }else{
        sendMessage($mainValues['send_your_phone_number'], json_encode([
			'keyboard' => [[[
					'text' => $buttonValues['send_phone_number'],
					'request_contact' => true,
				]]],
			'resize_keyboard' => true
		]));
		exit();
    }
}
if ($data == 'mainMenu1') {
    delMessage();
    setUser();
    setUser("", "temp");
    if ($uinfo->num_rows == 0) {
        $first_name = !empty($first_name)?$first_name:" ";
        $username = !empty($username)?$username:" ";
        $refcode = time();
        $sql = "INSERT INTO `users` VALUES (NULL,?,?,?,?, 0,?)";
        $stmt = $connection->prepare($sql);
        $stmt->bind_param("issii", $from_id, $first_name, $username, $refcode, $time);
        $stmt->execute();
        $stmt->close();
    }
    if(isset($data) and $data == "mainMenu"){
        $res = editText($message_id, $mainValues['start_message'], getMainKeys());
        if(!$res->ok){
            sendMessage($mainValues['start_message'], getMainKeys());
        }
    }else{
        if($from_id != $admin && !isset($userInfo['first_start'])){
            setUser('sent','first_start');
            $keys = json_encode(['inline_keyboard'=>[
                [['text'=>$buttonValues['send_message_to_user'],'callback_data'=>'sendMessageToUser' . $from_id]]
            ]]);

            sendMessage(str_replace(["FULLNAME", "USERNAME", "USERID"], ["<a href='tg://user?id=$from_id'>$first_name</a>", $username, $from_id], $mainValues['new_member_joined'])
                ,$keys, "html",$admin);
        }
        
        // ارسال پوستر در استارت
        $poster_path = __DIR__ . '/poster.png';
        if(file_exists($poster_path)){
            Bot('sendPhoto', [
                'chat_id' => $from_id,
                'photo' => new CURLFile($poster_path),
                'caption' => "🔥 به فروشگاه تحریم‌شکن APN خوش آمدید! 🔥"
            ]);
        }
        
        sendMessage($mainValues['start_message'],getMainKeys());
    }
}
if (preg_match('/^\/([Ss]tart)/', $text) or $text == $buttonValues['back_to_main'] or $data == 'mainMenu') {
    setUser();
    setUser("", "temp");
    if ($uinfo->num_rows == 0) {
        $first_name = !empty($first_name)?$first_name:" ";
        $username = !empty($username)?$username:" ";
        $refcode = time();
        $sql = "INSERT INTO `users` VALUES (NULL,?,?,?,?, 0,?)";
        $stmt = $connection->prepare($sql);
        $stmt->bind_param("issii", $from_id, $first_name, $username, $refcode, $time);
        $stmt->execute();
        $stmt->close();
    }
    if(isset($data) and $data == "mainMenu"){
        $res = editText($message_id, $mainValues['start_message'], getMainKeys());
        if(!$res->ok){
            sendMessage($mainValues['start_message'], getMainKeys());
        }
    }else{
        if($from_id != $admin && !isset($userInfo['first_start'])){
            setUser('sent','first_start');
            $keys = json_encode(['inline_keyboard'=>[
                [['text'=>$buttonValues['send_message_to_user'],'callback_data'=>'sendMessageToUser' . $from_id]]
            ]]);

            sendMessage(str_replace(["FULLNAME", "USERNAME", "USERID"], ["<a href='tg://user?id=$from_id'>$first_name</a>", $username, $from_id], $mainValues['new_member_joined'])
                ,$keys, "html",$admin);
        }
        sendMessage($mainValues['start_message'],getMainKeys());
    }
}
if(preg_match('/^sendMessageToUser(\d+)/',$data,$match) && ($from_id == $admin || $userInfo['isAdmin'] == true) && $text != $buttonValues['cancel']){
    editText($message_id,'🔘|لطفا پیامت رو بفرست');
    setUser($data);
}
if(preg_match('/^sendMessageToUser(\d+)/',$userInfo['step'],$match) && ($from_id == $admin || $userInfo['isAdmin'] == true) && $text != $buttonValues['cancel']){
    sendMessage($text,null,null,$match[1]);
    sendMessage("پیامت به کاربر ارسال شد",$removeKeyboard);
    sendMessage($mainValues['reached_main_menu'],getAdminKeys());
    setUser();
}
if($data=='botReports' && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    editText($message_id, "آمار ربات در این لحظه",getBotReportKeys());
}
if($data=="adminsList" && $from_id == $admin){
    editText($message_id, "لیست ادمین ها",getAdminsKeys());
}
if(preg_match('/^delAdmin(\d+)/',$data,$match) && $from_id === $admin){
    $stmt = $connection->prepare("UPDATE `users` SET `isAdmin` = false WHERE `userid` = ?");
    $stmt->bind_param("i", $match[1]);
    $stmt->execute();
    $stmt->close();
    
    editText($message_id, "لیست ادمین ها",getAdminsKeys());

}
if($data=="addNewAdmin" && $from_id === $admin){
    delMessage();
    sendMessage("🧑‍💻| کسی که میخوای ادمین کنی رو آیدی عددیشو بفرست ببینم:",$cancelKey);
    setUser($data);
}
if($userInfo['step'] == "addNewAdmin" && $from_id === $admin && $text != $buttonValues['cancel']){
    if(is_numeric($text)){
        $stmt = $connection->prepare("UPDATE `users` SET `isAdmin` = true WHERE `userid` = ?");
        $stmt->bind_param("i", $text);
        $stmt->execute();
        $stmt->close();
        
        sendMessage("✅ | 🥳 خب کاربر الان ادمین شد تبریک میگم",$removeKeyboard);
        setUser();
        
        sendMessage("لیست ادمین ها",getAdminsKeys());
    }else{
        sendMessage($mainValues['send_only_number']);
    }
}
if(($data=="botSettings" or preg_match("/^changeBot(\w+)/",$data,$match)) && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    if($data!="botSettings"){
        $newValue = $botState[$match[1]]=="on"?"off":"on";
        $botState[$match[1]]= $newValue;
        
        $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'BOT_STATES'");
        $stmt->execute();
        $isExists = $stmt->get_result();
        $stmt->close();
        if($isExists->num_rows>0) $query = "UPDATE `setting` SET `value` = ? WHERE `type` = 'BOT_STATES'";
        else $query = "INSERT INTO `setting` (`type`, `value`) VALUES ('BOT_STATES', ?)";
        $newData = json_encode($botState);
        
        $stmt = $connection->prepare($query);
        $stmt->bind_param("s", $newData);
        $stmt->execute();
        $stmt->close();
        }
    editText($message_id,$mainValues['change_bot_settings_message'],getBotSettingKeys());
}
if(($data=="gateWays_Channels" or preg_match("/^changeGateWays(\w+)/",$data,$match)) && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    if($data!="gateWays_Channels"){
        $newValue = $botState[$match[1]]=="on"?"off":"on";
        $botState[$match[1]]= $newValue;

        $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'BOT_STATES'");
        $stmt->execute();
        $isExists = $stmt->get_result();
        $stmt->close();
        if($isExists->num_rows>0) $query = "UPDATE `setting` SET `value` = ? WHERE `type` = 'BOT_STATES'";
        else $query = "INSERT INTO `setting` (`type`, `value`) VALUES ('BOT_STATES', ?)";
        $newData = json_encode($botState);
        
        $stmt = $connection->prepare($query);
        $stmt->bind_param("s", $newData);
        $stmt->execute();
        $stmt->close();
    }
    editText($message_id,$mainValues['change_bot_settings_message'],getGateWaysKeys());
}
if($data=="changeConfigRemarkType"){
    $newValue = $botState['remark']=="digits"?"idanddigits":"digits";
    $botState['remark']= $newValue;

    $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'BOT_STATES'");
    $stmt->execute();
    $isExists = $stmt->get_result();
    $stmt->close();
    if($isExists->num_rows>0) $query = "UPDATE `setting` SET `value` = ? WHERE `type` = 'BOT_STATES'";
    else $query = "INSERT INTO `setting` (`type`, `value`) VALUES ('BOT_STATES', ?)";
    $newData = json_encode($botState);
    
    $stmt = $connection->prepare($query);
    $stmt->bind_param("s", $newData);
    $stmt->execute();
    $stmt->close();
    editText($message_id,$mainValues['change_bot_settings_message'],getBotSettingKeys());
}
if(preg_match('/^changePaymentKeys(\w+)/',$data,$match)){
    delMessage();
    switch($match[1]){
        case "nextpay":
            $gate = "کد جدید درگاه نکست پی";
            break;
        case "nowpayment":
            $gate = "کد جدید درگاه nowPayment";
            break;
        case "zarinpal":
            $gate = "کد جدید درگاه زرین پال";
            break;
        case "bankAccount":
            $gate = "شماره حساب جدید";
            break;
        case "holderName":
            $gate = "اسم دارنده حساب";
            break;
    }
    sendMessage("🔘|لطفا $gate را وارد کنید", $cancelKey);
    setUser($data);
}
if(preg_match('/^changePaymentKeys(\w+)/',$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($data=="editRewardTime" && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    delMessage();
    sendMessage("🙃 | لطفا زمان تأخیر در ارسال گزارش رو به ساعت وارد کن\n\nنکته: هر n ساعت گزارش به ربات ارسال میشه! ",$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(($data == 'allUsersList' || preg_match('/^changeUsersPage(\d+)$/', $data, $match)) && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $results_per_page = 20;
    
    // شمارش کل کاربران
    $stmt = $connection->prepare("SELECT COUNT(*) as total FROM `users`");
    $stmt->execute();
    $number_of_result = $stmt->get_result()->fetch_assoc()['total'];
    $stmt->close();
    
    $number_of_page = ceil($number_of_result / $results_per_page);
    $page = $match[1] ?? 1;
    $page_first_result = ($page - 1) * $results_per_page;
    
    // دریافت کاربران با صفحه‌بندی
    $stmt = $connection->prepare("SELECT `userid`, `name`, `username`, `date` FROM `users` ORDER BY `id` DESC LIMIT ?, ?");
    $stmt->bind_param("ii", $page_first_result, $results_per_page);
    $stmt->execute();
    $users = $stmt->get_result();
    $stmt->close();
    
    if($users->num_rows == 0){
        alert("کاربری یافت نشد!");
        exit;
    }
    
    $message = "👥 <b>لیست کامل کاربران</b>\n\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━━━\n\n";
    $message .= "📊 تعداد کل: <b>" . number_format($number_of_result) . "</b> کاربر\n";
    $message .= "📄 صفحه: <b>{$page}</b> از <b>{$number_of_page}</b>\n\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━━━\n\n";
    
    $num = $page_first_result + 1;
    while($user = $users->fetch_assoc()){
        $userid = $user['userid'];
        $name = $user['name'];
        $username = $user['username'] ? "@" . $user['username'] : "❌ ندارد";
        $date = jdate('Y/m/d', $user['date']);
        
        $message .= "{$num}. 👤 {$name}\n";
        $message .= "   🆔 <code>{$userid}</code>\n";
        $message .= "   📱 {$username}\n";
        $message .= "   📅 {$date}\n\n";
        
        $num++;
    }
    
    $message .= "━━━━━━━━━━━━━━━━━━━━━━\n\n";
    $message .= "💡 برای کپی آیدی عددی، روی آن کلیک کنید.";
    
    // دکمه‌های صفحه‌بندی
    $keyboard = [];
    $prev = $page - 1;
    $next = $page + 1;
    
    $buttons = [];
    if($prev > 0) {
        $buttons[] = ['text' => "◀️ قبلی", 'callback_data' => "changeUsersPage{$prev}"];
    }
    if($next <= $number_of_page) {
        $buttons[] = ['text' => "بعدی ▶️", 'callback_data' => "changeUsersPage{$next}"];
    }
    
    if(!empty($buttons)) {
        $keyboard[] = $buttons;
    }
    
    // دکمه‌های اضافی
    $keyboard[] = [
        ['text' => '🔍 جستجوی کاربر', 'callback_data' => 'userReports'],
        ['text' => '📊 آمار ربات', 'callback_data' => 'botReports']
    ];
    $keyboard[] = [['text' => '🔙 بازگشت', 'callback_data' => 'adminSection']];
    
    if(isset($data)) {
        editText($message_id, $message, json_encode(['inline_keyboard' => $keyboard]), 'HTML');
    } else {
        sendMessage($message, json_encode(['inline_keyboard' => $keyboard]), 'HTML');
    }
    exit;
}

if($data=="inviteSetting" && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'INVITE_BANNER_AMOUNT'");
    $stmt->execute();
    $inviteAmount = number_format($stmt->get_result()->fetch_assoc()['value']??0) . " تومان";
    $stmt->close();
    setUser();
    $keys = json_encode(['inline_keyboard'=>[
        [['text'=>"❗️بنر دعوت",'callback_data'=>"inviteBanner"]],
        [
            ['text'=>$inviteAmount,'callback_data'=>"editInviteAmount"],
            ['text'=>"مقدار پورسانت",'callback_data'=>"wizwizch"]
            ],
        [
            ['text'=>$buttonValues['back_button'],'callback_data'=>"botSettings"]
            ],
        ]]); 
    $res = editText($message_id,"✅ تنظیمات بازاریابی",$keys);
    if(!$res->ok){
        delMessage();
        sendMessage("✅ تنظیمات بازاریابی",$keys);
    }
} 
if($data=="inviteBanner" && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'INVITE_BANNER_TEXT'");
    $stmt->execute();
    $inviteText = $stmt->get_result()->fetch_assoc()['value'];
    $inviteText = $inviteText != null?json_decode($inviteText,true):array('type'=>'text');
    $stmt->close();
    $keys = json_encode(['inline_keyboard'=>[
        [['text'=>"ویرایش",'callback_data'=>'editInviteBannerText']],
        [['text'=>$buttonValues['back_button'],'callback_data'=>'inviteSetting']]
        ]]);
    if($inviteText['type'] == "text"){
        editText($message_id,"بنر فعلی: \n" . $inviteText['text'],$keys);
    }else{
        delMessage();
        $res = sendPhoto($inviteText['file_id'], $inviteText['caption'], $keys,null);
        if(!$res->ok){
            sendMessage("تصویر فعلی یافت نشد، لطفا اقدام به ویرایش بنر کنید",$keys);
        }
    }
    setUser();
}
if($data=="editInviteBannerText" && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    delMessage();
    sendMessage("🤖 | لطفا بنر جدید را بفرستید از متن  LINK برای نمایش لینک دعوت استفاده کنید)",$cancelKey);
    setUser($data);
}
if($userInfo['step']=="editInviteBannerText" && ($from_id == $admin || $userInfo['isAdmin'] == true) && $text != $buttonValues['cancel']){
    $data = array();
    if(isset($update->message->photo)){
        $data['type'] = 'photo';
        $data['caption'] = $caption;
        $data['file_id'] = $fileid;
    }
    elseif(isset($update->message->text)){
        $data['type'] = 'text';
        $data['text'] = $text;
    }else{
        sendMessage("🥺 | بنر ارسال شده پشتیبانی نمی شود");
        exit();
    }
    
    $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'INVITE_BANNER_TEXT'");
    $stmt->execute();
    $checkExist = $stmt->get_result();
    $stmt->close();
    $data = json_encode($data);
    if($checkExist->num_rows > 0){
        $stmt = $connection->prepare("UPDATE `setting` SET `value` = ? WHERE `type` = 'INVITE_BANNER_TEXT'");
        $stmt->bind_param("s", $data);
        $stmt->execute();
        $checkExist = $stmt->get_result();
        $stmt->close();
    }else{
        $stmt = $connection->prepare("INSERT INTO `setting` (`value`, `type`) VALUES (?, 'INVITE_BANNER_TEXT')");
        $stmt->bind_param("s", $data);
        $stmt->execute();
        $checkExist = $stmt->get_result();
        $stmt->close();
    }
    
    sendMessage($mainValues['saved_successfuly'],$removeKeyboard);
    $keys = json_encode(['inline_keyboard'=>[
        [['text'=>"ویرایش",'callback_data'=>'editInviteBannerText']],
        [['text'=>$buttonValues['back_button'],'callback_data'=>'inviteSetting']]
        ]]);
    if(isset($update->message->text)){
        sendMessage("بنر فعلی: \n" . $text,$keys);
    }else{
        sendPhoto($fileid, $caption, $keys);
    }
    setUser();
}
if($data=="editInviteAmount" && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    delMessage();
    sendMessage("لطفا مبلغ پورسانت رو به تومان وارد کن",$cancelKey);
    setUser($data);
} 
if($userInfo['step'] == "editInviteAmount"){
    if(is_numeric($text)){
        $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'INVITE_BANNER_AMOUNT'");
        $stmt->execute();
        $checkExist = $stmt->get_result();
        $stmt->close();
        
        if($checkExist->num_rows > 0){
            $stmt = $connection->prepare("UPDATE `setting` SET `value` = ? WHERE `type` = 'INVITE_BANNER_AMOUNT'");
            $stmt->bind_param("s", $text);
            $stmt->execute();
            $checkExist = $stmt->get_result();
            $stmt->close();
        }else{
            $stmt = $connection->prepare("INSERT INTO `setting` (`value`, `type`) VALUES (?, 'INVITE_BANNER_AMOUNT')");
            $stmt->bind_param("s", $text);
            $stmt->execute();
            $checkExist = $stmt->get_result();
            $stmt->close();
        }
        sendMessage($mainValues['saved_successfuly'],$removeKeyboard);
        
        $keys = json_encode(['inline_keyboard'=>[
            [['text'=>"❗️بنر دعوت",'callback_data'=>"inviteBanner"]],
            [
                ['text'=>number_format($text) . " تومان",'callback_data'=>"editInviteAmount"],
                ['text'=>"مقدار پورسانت",'callback_data'=>"wizwizch"]
                ], 
            [
                ['text'=>$buttonValues['back_button'],'callback_data'=>"botSettings"]
                ],
            ]]); 
        sendMessage("✅ تنظیمات بازاریابی",$keys);
        setUser();
    }else sendMessage($mainValues['send_only_number']);
}
if($userInfo['step'] == "editRewardTime" && ($from_id == $admin || $userInfo['isAdmin'] == true) && $text != $buttonValues['cancel']){
    if(!is_numeric($text)){
        sendMessage("لطفا عدد بفرستید");
        exit();
    }
    elseif($text <0 ){
        sendMessage("مقدار وارد شده معتبر نیست");
        exit();
    }
    $botState['rewaredTime'] = $text;

    $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'BOT_STATES'");
    $stmt->execute();
    $isExist = $stmt->get_result();
    $stmt->close();
    if($isExist->num_rows>0) $query = "UPDATE `setting` SET `value` = ? WHERE `type` = 'BOT_STATES'";
    else $query = "INSERT INTO `setting` (`type`, `value`) VALUES ('BOT_STATES', ?)";
    $newData = json_encode($botState);
    
    $stmt = $connection->prepare($query);
    $stmt->bind_param("s", $newData);
    $stmt->execute();
    $stmt->close();


    sendMessage($mainValues['change_bot_settings_message'],getBotSettingKeys());
    setUser();
    exit();
}
if($data=="listgheymat"){
    delMessage();    
    $txt = "📋 <b>لیست تعرفه‌های فروشگاه APN</b> 📋

━━━━━━━━━━━━━━━━━━━━━━
💎 <b>پلن‌های VIP - تک کاربره یک ماهه</b>
━━━━━━━━━━━━━━━━━━━━━━

⚡️ 20 گیگ - 40,000 تومان
⚡️ 35 گیگ - 55,000 تومان
⚡️ 70 گیگ - 85,000 تومان
⚡️ 90 گیگ - 100,000 تومان
⚡️ 200 گیگ - 180,000 تومان
⚡️ 300 گیگ - 250,000 تومان
♾️ نامحدود - 120,000 تومان

━━━━━━━━━━━━━━━━━━━━━━
👥 <b>پلن‌های VIP - دو کاربره یک ماهه</b>
━━━━━━━━━━━━━━━━━━━━━━

💫 100 گیگ - 160,000 تومان
🌟 150 گیگ - 220,000 تومان
👑 نامحدود - 280,000 تومان

━━━━━━━━━━━━━━━━━━━━━━
👥 <b>پلن‌های VIP - دو کاربره سه ماهه</b>
━━━━━━━━━━━━━━━━━━━━━━

🔥 200 گیگ - 450,000 تومان (15% تخفیف 🎁)
💎 نامحدود - 700,000 تومان (17% تخفیف 🎁)

━━━━━━━━━━━━━━━━━━━━━━
📈 <b>پلن‌های Trading</b>
━━━━━━━━━━━━━━━━━━━━━━

🔜 <b>به زودی در دسترس</b>
• پینگ فوق پایین
• سرور اختصاصی ترید
• مناسب Binance، Bybit، OKX

━━━━━━━━━━━━━━━━━━━━━━

✨ <b>مشخصات عمومی:</b>

🌍 لوکیشن: آلمان 🇩🇪
🚀 آپتایم: 99%
📱 سازگار با همه دستگاه‌ها
☎️ پشتیبانی: 24/7
✅ ضمانت بازگشت وجه

━━━━━━━━━━━━━━━━━━━━━━

💎 فروشگاه تحریم‌شکن APN";
    
$inlineKeyboard = json_encode([
    'inline_keyboard' => [
        [
           ['text' => "🛍 خرید سرویس",'callback_data' => "buyService"],
           ['text' => "🏘 صفحه اصلی",'callback_data' => "mainMenu"]
        ]
    ]
]);
    
sendMessage($txt, $inlineKeyboard, 'HTML');
}    
if($data=="inviteFriends"){
    $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'INVITE_BANNER_TEXT'");
    $stmt->execute();
    $inviteText = $stmt->get_result()->fetch_assoc()['value'];
    if($inviteText != null){
        $inviteText = json_decode($inviteText,true);
    
        $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'INVITE_BANNER_AMOUNT'");
        $stmt->execute();
        $inviteAmount = number_format($stmt->get_result()->fetch_assoc()['value']??0) . " تومان";
        $stmt->close();
        
        $getBotInfo = json_decode(file_get_contents("http://api.telegram.org/bot" . $botToken . "/getMe"),true);
        $botId = $getBotInfo['result']['username'];
        
        $link = "t.me/$botId?start=" . $from_id;
        if($inviteText['type'] == "text"){
            $txt = str_replace('LINK',"<code>$link</code>",$inviteText['text']);
            $res = sendMessage($txt,null,"HTML");
        } 
        else{
            $txt = str_replace('LINK',"$link",$inviteText['caption']);
            $res = sendPhoto($inviteText['file_id'],$txt,null,"HTML");
        }
        $msgId = $res->result->message_id;
        sendMessage("با لینک بالا دوستاتو به ربات دعوت کن و با هر خرید $inviteAmount بدست بیار",null,null,null,$msgId);
    }
    else alert("این قسمت غیر فعال است");
}
if($data=="myInfo"){
    $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `userid` = ?");
    $stmt->bind_param("i", $from_id);
    $stmt->execute();
    $totalBuys = $stmt->get_result()->num_rows;
    $stmt->close();
    
    $myWallet = number_format($userInfo['wallet']) . " تومان";
    
    $keys = json_encode(['inline_keyboard'=>[
        [
            ['text'=>$from_id,'callback_data'=>"wizwizch"],
            ['text'=>"آیدی عددی",'callback_data'=>"wizwizch"]
        ],
        [
            ['text'=>"@$username",'callback_data'=>"wizwizch"],
            ['text'=>"یوزرنیم",'callback_data'=>"wizwizch"]
        ],
        [
            ['text'=>$first_name,'callback_data'=>"wizwizch"],
            ['text'=>"اسم",'callback_data'=>"wizwizch"]
        ],
        [
            ['text'=>$totalBuys,'callback_data'=>"wizwizch"],
            ['text'=>"تعداد خرید ها",'callback_data'=>"wizwizch"]
        ],
        [
            ['text'=>$myWallet,'callback_data'=>"wizwizch"],
            ['text'=>"موجودی کیف پول",'callback_data'=>"wizwizch"]
        ],
        [
            ['text'=>"🔻🔻🔻🔻",'callback_data'=>"wizwizch"],
        ],
        [
            ['text'=>"شارژ کیف پول 💰",'callback_data'=>"increaseMyWallet"],
            ['text'=>"انتقال موجودی",'callback_data'=>"transferMyWallet"]
        ],
        [
            ['text'=>$buttonValues['back_button'],'callback_data'=>"mainMenu"]
            ]
        ]]);
    delMessage();
    sendMessage("💞 اطلاعات حساب شما:",
            $keys,"html");
}
if($data=="transferMyWallet"){
    delMessage();
    sendMessage("لطفا آیدی عددی کاربر مورد نظر رو وارد کن",$cancelKey);
    setUser($data);
}
if($userInfo['step'] =="transferMyWallet" && $text != $buttonValues['cancel']){
    if(is_numeric($text)){
        if($text != $from_id){
            $stmt= $connection->prepare("SELECT * FROM `users` WHERE `userid` = ?");
            $stmt->bind_param("i", $text);
            $stmt->execute();
            $checkExist = $stmt->get_result();
            $stmt->close();
            
            if($checkExist->num_rows > 0){
                setUser("tranfserUserAmount" . $text);
                sendMessage("لطفا مبلغ مورد نظر رو وارد کن");
            }else sendMessage("کاربری با این آیدی یافت نشد");
        }else sendMessage("میخای به خودت انتقال بدی ؟؟");
    }else sendMessage($mainValues['send_only_number']);
}
if(preg_match('/^tranfserUserAmount(\d+)/',$userInfo['step'],$match) && $text != $buttonValues['cancel']){
    if(is_numeric($text)){
        if($userInfo['wallet'] >= $text){
            $stmt = $connection->prepare("UPDATE `users` SET `wallet` = `wallet` + ? WHERE `userid` = ?");
            $stmt->bind_param("ii", $text, $match[1]);
            $stmt->execute();
            $stmt->close();
            
            $stmt = $connection->prepare("UPDATE `users` SET `wallet` = `wallet` - ? WHERE `userid` = ?");
            $stmt->bind_param("ii", $text, $from_id);
            $stmt->execute();
            $stmt->close();
            
            sendMessage("✅|مبلغ " . number_format($text) . " تومان به کیف پول شما توسط کاربر $from_id انتقال یافت",null,null,$match[1]);
            setUser();
            sendMessage("✅|مبلغ " . number_format($text) . " تومان به کیف پول کاربر مورد نظر شما انتقال یافت",$removeKeyboard);
            sendMessage("لطفا یکی از کلید های زیر را انتخاب کنید",getMainKeys());
        }else sendMessage("موجودی حساب شما کم است");
    }else sendMessage($mainValues['send_only_number']);
}
if($data=="increaseMyWallet"){
    delMessage();
    sendMessage("🙂 عزیزم مقدار شارژ مورد نظر خود را به تومان وارد کن (بیشتر از 5000 تومان)",$cancelKey);
    setUser($data);
}
if($userInfo['step'] == "increaseMyWallet" && $text != $buttonValues['cancel']){
    if(!is_numeric($text)){
        sendMessage($mainValues['send_only_number']);
        exit();
    }
    elseif($text < 5000){
        sendMessage("لطفا مقداری بیشتر از 5000 وارد کن");
        exit();
    }
    
    // دریافت اطلاعات کارت از دیتابیس
    $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'PAYMENT_KEYS'");
    $stmt->execute();
    $paymentKeys_result = $stmt->get_result()->fetch_assoc();
    $paymentKeys = [];
    if($paymentKeys_result && !is_null($paymentKeys_result['value'])){
        $paymentKeys = json_decode($paymentKeys_result['value'], true);
    }
    $stmt->close();
    
    // ثبت درخواست شارژ
    $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();
    
    // نمایش اطلاعات کارت و درخواست فیش
    setUser("uploadReceiptForWallet_{$hash_id}_{$text}", 'step');
    
    $price_text = number_format($text);
    $cardMsg = "💳 <b>شارژ کیف پول</b>\n\n";
    $cardMsg .= "💰 مبلغ شارژ: <b>{$price_text} تومان</b>\n\n";
    
    if(!empty($paymentKeys['bankAccount']) && !empty($paymentKeys['holderName'])){
        $cardMsg .= "📌 لطفا به کارت زیر واریز کنید:\n\n";
        $cardMsg .= "💳 شماره کارت:\n<code>{$paymentKeys['bankAccount']}</code>\n\n";
        $cardMsg .= "👤 نام صاحب حساب:\n<b>{$paymentKeys['holderName']}</b>\n\n";
    }
    
    $cardMsg .= "📤 لطفا تصویر فیش واریزی خود را ارسال کنید:";
    
    sendMessage($cardMsg, $cancelKey, 'HTML');
    exit;
}

// دریافت فیش شارژ کیف پول
if(preg_match('/^uploadReceiptForWallet_([a-zA-Z0-9]+)_(\d+)$/', $userInfo['step'], $match) && $from_id != $admin && !$userInfo['isAdmin']){
    if($text == $buttonValues['cancel']){
        setUser('none', 'step');
        sendMessage("❌ لغو شد", getMainKeys());
        exit;
    }
    
    if(!isset($photo)){
        sendMessage("⚠️ لطفا تصویر فیش را ارسال کنید!", $cancelKey);
        exit;
    }
    
    $hash_id = $match[1];
    $amount = $match[2];
    
    error_log("📸 فیش شارژ کیف پول دریافت شد - User: {$from_id}, Hash: {$hash_id}, Amount: {$amount}");
    
    // به‌روزرسانی عکس در جدول pays
    $stmt = $connection->prepare("UPDATE `pays` SET `photo` = ? WHERE `hash_id` = ? AND `user_id` = ?");
    $stmt->bind_param("ssi", $photo, $hash_id, $from_id);
    $stmt->execute();
    $stmt->close();
    
    setUser('none', 'step');
    
    // ارسال پیام تایید به کاربر
    sendMessage("✅ فیش شارژ کیف پول شما با موفقیت ثبت شد!\n\n⏳ پس از بررسی توسط ادمین، موجودی به کیف پول شما اضافه خواهد شد.\n\n💰 مبلغ: " . number_format($amount) . " تومان\n\n🆔 شناسه پرداخت: <code>{$hash_id}</code>", getMainKeys(), 'HTML');
    
    // اطلاع به ادمین
    $price_text = number_format($amount);
    $user_name = $first_name ?? $userInfo['name'] ?? "کاربر";
    $user_username = $username != " ندارد " ? "@{$username}" : "ندارد";
    
    $adminMsg = "💰 <b>درخواست شارژ کیف پول</b>\n\n";
    $adminMsg .= "👤 کاربر: {$user_name}\n";
    $adminMsg .= "🆔 یوزرنیم: {$user_username}\n";
    $adminMsg .= "🔢 آیدی: <code>{$from_id}</code>\n";
    $adminMsg .= "💵 مبلغ: {$price_text} تومان\n\n";
    $adminMsg .= "🆔 کد پیگیری: <code>{$hash_id}</code>";
    
    $adminKeyboard = [
        [
            ['text' => '✅ تایید شارژ', 'callback_data' => "approveWalletRecharge_{$hash_id}_{$from_id}_{$amount}"],
            ['text' => '❌ رد درخواست', 'callback_data' => "rejectWalletRecharge_{$hash_id}_{$from_id}_{$amount}"]
        ]
    ];
    
    bot('sendPhoto', [
        'chat_id' => $admin,
        'photo' => $photo,
        'caption' => $adminMsg,
        'parse_mode' => 'HTML',
        'reply_markup' => json_encode(['inline_keyboard' => $adminKeyboard])
    ]);
    
    exit;
}

// تایید شارژ کیف پول توسط ادمین
if(preg_match('/^approveWalletRecharge_([a-zA-Z0-9]+)_(\d+)_(\d+)$/', $data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $hash_id = $match[1];
    $user_id = $match[2];
    $amount = $match[3];
    
    // افزایش موجودی کیف پول
    $stmt = $connection->prepare("UPDATE `users` SET `wallet` = `wallet` + ? WHERE `userid` = ?");
    $stmt->bind_param("ii", $amount, $user_id);
    $stmt->execute();
    $stmt->close();
    
    // به‌روزرسانی وضعیت پرداخت
    $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'success' WHERE `hash_id` = ?");
    $stmt->bind_param("s", $hash_id);
    $stmt->execute();
    $stmt->close();
    
    // ارسال پیام به کاربر
    $price_text = number_format($amount);
    bot('sendMessage', [
        'chat_id' => $user_id,
        'text' => "✅ شارژ کیف پول شما تایید شد!\n\n💰 مبلغ {$price_text} تومان به کیف پول شما اضافه شد.\n\n🆔 کد پیگیری: {$hash_id}",
        'parse_mode' => 'HTML'
    ]);
    
    // ویرایش پیام ادمین
    editText($message_id, "✅ شارژ کیف پول تایید شد\n\n" . $message, null, 'HTML');
    
    alert("✅ شارژ کیف پول با موفقیت تایید شد!");
    exit;
}

// رد شارژ کیف پول توسط ادمین
if(preg_match('/^rejectWalletRecharge_([a-zA-Z0-9]+)_(\d+)_(\d+)$/', $data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $hash_id = $match[1];
    $user_id = $match[2];
    $amount = $match[3];
    
    delMessage();
    sendMessage("لطفا دلیل رد شارژ کیف پول را وارد کنید:", $cancelKey);
    setUser("waitingRejectWalletReason_{$hash_id}_{$user_id}_{$amount}_{$message_id}", 'step');
    exit;
}

// دریافت دلیل رد شارژ کیف پول
if(preg_match('/^waitingRejectWalletReason_([a-zA-Z0-9]+)_(\d+)_(\d+)_(\d+)$/', $userInfo['step'], $match) && ($from_id == $admin || $userInfo['isAdmin'] == true) && $text){
    if($text == $buttonValues['cancel']){
        setUser('none', 'step');
        sendMessage("❌ لغو شد", getMainKeys());
        exit;
    }
    
    $hash_id = $match[1];
    $user_id = $match[2];
    $amount = $match[3];
    $admin_message_id = $match[4];
    
    // به‌روزرسانی وضعیت پرداخت
    $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'rejected' WHERE `hash_id` = ?");
    $stmt->bind_param("s", $hash_id);
    $stmt->execute();
    $stmt->close();
    
    setUser('none', 'step');
    
    // ارسال پیام به کاربر
    $price_text = number_format($amount);
    $reject_reason = htmlspecialchars($text);
    bot('sendMessage', [
        'chat_id' => $user_id,
        'text' => "❌ درخواست شارژ کیف پول شما رد شد\n\n💰 مبلغ: {$price_text} تومان\n🆔 کد پیگیری: {$hash_id}\n\n📝 دلیل:\n{$reject_reason}",
        'parse_mode' => 'HTML'
    ]);
    
    // ویرایش پیام ادمین
    editText($admin_message_id, "❌ شارژ کیف پول رد شد\n\nدلیل: {$text}", null, 'HTML');
    
    sendMessage("✅ درخواست شارژ کیف پول رد شد و به کاربر اطلاع داده شد.", getMainKeys());
    exit;
}

if(preg_match('/increaseWalletWithCartToCart/',$data)) {
    $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'PAYMENT_KEYS'");
    $stmt->execute();
    $paymentKeys = $stmt->get_result()->fetch_assoc()['value'];
    if(!is_null($paymentKeys)) $paymentKeys = json_decode($paymentKeys,true);
    else $paymentKeys = array();
    $stmt->close();

    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(\d+)/',$userInfo['step'], $match) and $text != $buttonValues['cancel']){
    if(isset($update->message->photo)){
        $fid = $match[1];
        setUser();
        $uid = $userInfo['userid'];
        $name = $userInfo['name'];
        $username = $userInfo['username'];
    
        sendMessage($mainValues['order_increase_sent'],$removeKeyboard);
        sendMessage($mainValues['reached_main_menu'],getMainKeys());
        $price = number_format($match[1]);
        $msg = str_replace(['PRICE', 'USERNAME', 'NAME', 'USER-ID'],[$price, $username, $name, $from_id], $mainValues['increase_wallet_request_message']);
        
        $keyboard = json_encode([
            'inline_keyboard' => [
                [
                    ['text' => $buttonValues['approve'], 'callback_data' => "approvePayment{$uid}_{$match[1]}"],
                    ['text' => $buttonValues['decline'], 'callback_data' => "decPayment{$uid}_{$match[1]}"]
                ]
            ]
        ]);
        sendPhoto($fileid, $msg,$keyboard, "HTML", $admin);
    }else{
        sendMessage($mainValues['please_send_only_image']);
    }
}
if(preg_match('/^approvePayment(\d+)_(\d+)/',$data,$match) && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $stmt = $connection->prepare("UPDATE `users` SET `wallet` = `wallet` + ? WHERE `userid` = ?");
    $stmt->bind_param("ii", $match[2], $match[1]);
    $stmt->execute();
    $stmt->close();

    sendMessage("افزایش حساب شما با موفقیت تأیید شد\n✅ مبلغ " . number_format($match[2]). " تومان به حساب شما اضافه شد",null,null,$match[1]);
    
    unset($markup[count($markup)-1]);
    $markup[] = [['text' => '✅', 'callback_data' => "dontsendanymore"]];
    $keys = json_encode(['inline_keyboard'=>array_values($markup)],488);

    editKeys($keys);
}
if(preg_match('/^decPayment(\d+)_(\d+)/',$data,$match) && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    unset($markup[count($markup)-1]);
    $markup[] = [['text' => '❌', 'callback_data' => "dontsendanymore"]];
    $keys = json_encode(['inline_keyboard'=>array_values($markup)],488);
    file_put_contents("temp" . $from_id . ".txt", $keys);
    sendMessage("لطفا دلیل عدم تأیید افزایش موجودی را وارد کنید",$cancelKey);
    setUser($data . "_" . $message_id);
}
if(preg_match('/^decPayment(\d+)_(\d+)_(\d+)/',$userInfo['step'],$match) && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    sendMessage("💔 افزایش موجودی شما به مبلغ "  . number_format($match[2]) . " به دلیل زیر رد شد\n\n$text",null,null,$match[1]);
    
    editKeys(file_get_contents("temp" . $from_id . ".txt"), $match[3]);
    setUser();
    sendMessage('پیامت رو براش ارسال کردم ... 🤝',$removeKeyboard);
    unlink("temp" . $from_id . ".txt");
}
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+)/',$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+)/',$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($data=="editRewardChannel" && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    delMessage();
    sendMessage("🤗|لطفا ربات رو در کانال ادمین کن و آیدی کانال رو بفرست",$cancelKey);
    setUser($data);
}
if($userInfo['step'] == "editRewardChannel" && ($from_id == $admin || $userInfo['isAdmin'] == true) && $text != $buttonValues['cancel']){
    $botId = json_decode(file_get_contents("https://api.telegram.org/bot$botToken/getme"))->result->id;
    $result = json_decode(file_get_contents("https://api.telegram.org/bot$botToken/getChatMember?chat_id=$text&user_id=$botId"));
    if($result->ok){
        if($result->result->status == "administrator"){
            $botState['rewardChannel'] = $text;
            
            $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'BOT_STATES'");
            $stmt->execute();
            $isExist = $stmt->get_result();
            $stmt->close();
            if($isExist->num_rows>0) $query = "UPDATE `setting` SET `value` = ? WHERE `type` = 'BOT_STATES'";
            else $query = "INSERT INTO `setting` (`type`, `value`) VALUES ('BOT_STATES', ?)";
            $newData = json_encode($botState);
            
            $stmt = $connection->prepare($query);
            $stmt->bind_param("s", $newData);
            $stmt->execute();
            $stmt->close();
            
            sendMessage($mainValues['change_bot_settings_message'],getGateWaysKeys());
            setUser();
            exit();
        }
    }
    sendMessage("😡|ای بابا ،ربات هنوز تو کانال عضو نشده، اول ربات رو تو کانال ادمین کن و آیدیش رو بفرست");
}
if($data=="editLockChannel" && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    delMessage();
    sendMessage("🤗|لطفا ربات رو در کانال ادمین کن و آیدی کانال رو بفرست",$cancelKey);
    setUser($data);
}
if($userInfo['step'] == "editLockChannel" && ($from_id == $admin || $userInfo['isAdmin'] == true) && $text != $buttonValues['cancel']){
    $botId = json_decode(file_get_contents("https://api.telegram.org/bot$botToken/getme"))->result->id;
    $result = json_decode(file_get_contents("https://api.telegram.org/bot$botToken/getChatMember?chat_id=$text&user_id=$botId"));
    if($result->ok){
        if($result->result->status == "administrator"){
            $botState['lockChannel'] = $text;

            $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'BOT_STATES'");
            $stmt->execute();
            $isExists = $stmt->get_result();
            $stmt->close();
            if($isExists->num_rows>0) $query = "UPDATE `setting` SET `value` = ? WHERE `type` = 'BOT_STATES'";
            else $query = "INSERT INTO `setting` (`type`, `value`) VALUES ('BOT_STATES', ?)";
            $newData = json_encode($botState);
            
            $stmt = $connection->prepare($query);
            $stmt->bind_param("s", $newData);
            $stmt->execute();
            $stmt->close();
            
            sendMessage($mainValues['change_bot_settings_message'],getGateWaysKeys());
            setUser();
            exit();
        }
    }
    sendMessage($mainValues['the_bot_in_not_admin']);
}
if (($data == "agentOneBuy" || $data=='buySubscription' || $data == "agentMuchBuy") && ($botState['sellState']=="on" || ($from_id == $admin || $userInfo['isAdmin'] == true))){
    if($botState['cartToCartState'] == "off" && $botState['walletState'] == "off"){
        alert($mainValues['selling_is_off']);
        exit();
    }
    if($data=="buySubscription") setUser('','temp');
    elseif($data=="agentOneBuy") setUser('agentBuy', 'temp');
    elseif($data== "agentMuchBuy") setUser('agentMuchBuy', 'temp');
    
    $stmt = $connection->prepare("SELECT * FROM `server_info` WHERE `active`=1 and `state` = 1 and `ucount` > 0 ORDER BY `id` ASC");
    $stmt->execute();
    $respd = $stmt->get_result();
    $stmt->close();
    if($respd->num_rows==0){
        alert($mainValues['no_server_available']);
        exit;
    }
    $keyboard = [];
    while($cat = $respd->fetch_assoc()){
        $id = $cat['id'];
        $name = $cat['title'];
        $flag = $cat['flag'];
        $keyboard[] = ['text' => "$flag $name", 'callback_data' => "selectServer$id"];
    }
    $keyboard[] = ['text'=>$buttonValues['back_to_main'],'callback_data'=>"mainMenu"];
    $keyboard = array_chunk($keyboard,1);
    editText($message_id, $mainValues['buy_sub_select_location'], json_encode(['inline_keyboard'=>$keyboard]));
}
if ($data=='createMultipleAccounts' && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $stmt = $connection->prepare("SELECT * FROM `server_info` WHERE `active`=1 and `ucount` > 0 ORDER BY `id` ASC");
    $stmt->execute();
    $respd = $stmt->get_result();
    $stmt->close();
    if($respd->num_rows==0){
        sendMessage($mainValues['no_server_available']);
        exit;
    }
    $keyboard = [];
    while($cat = $respd->fetch_assoc()){
        $id = $cat['id'];
        $name = $cat['title'];
        $flag = $cat['flag'];
        $keyboard[] = ['text' => "$flag $name", 'callback_data' => "createAccServer$id"];
    }
    $keyboard[] = ['text'=>$buttonValues['back_to_main'],'callback_data'=>"managePanel"];
    $keyboard = array_chunk($keyboard,1);
    editText($message_id, $mainValues['buy_sub_select_location'], json_encode(['inline_keyboard'=>$keyboard]));
    

}
if(preg_match('/createAccServer(\d+)/',$data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true) ) {
    $sid = $match[1];
        
    $stmt = $connection->prepare("SELECT * FROM `server_categories` WHERE `parent`=0 order by `id` asc");
    $stmt->execute();
    $respd = $stmt->get_result();
    $stmt->close();
    if($respd->num_rows == 0){
        alert("هیچ دسته بندی برای این سرور وجود ندارد");
    }else{
        
        $keyboard = [];
        while ($file = $respd->fetch_assoc()){
            $id = $file['id'];
            $name = $file['title'];
            $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `server_id`=? and `catid`=? and `active`=1");
            $stmt->bind_param("ii", $sid, $id);
            $stmt->execute();
            $rowcount = $stmt->get_result()->num_rows; 
            $stmt->close();
            if($rowcount>0) $keyboard[] = ['text' => "$name", 'callback_data' => "createAccCategory{$id}_{$sid}"];
        }
        if(empty($keyboard)){
            alert("هیچ دسته بندی برای این سرور وجود ندارد");exit;
        }
        alert("♻️ | دریافت دسته بندی ...");
        $keyboard[] = ['text' => $buttonValues['back_to_main'], 'callback_data' => "createMultipleAccounts"];
        $keyboard = array_chunk($keyboard,1);
        editText($message_id, "2️⃣ مرحله دو:

دسته بندی مورد نظرت رو انتخاب کن 🤭", json_encode(['inline_keyboard'=>$keyboard]));
    }

}
if(preg_match('/createAccCategory(\d+)_(\d+)/',$data,$match) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $call_id = $match[1];
    $sid = $match[2];
    $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `server_id`=? and `catid`=? and `active`=1 order by `id` asc");
    $stmt->bind_param("ii", $sid, $call_id);
    $stmt->execute();
    $respd = $stmt->get_result();
    $stmt->close();
    if($respd->num_rows==0){
        alert("💡پلنی در این دسته بندی وجود ندارد ");
    }else{
        alert("📍در حال دریافت لیست پلن ها");
        $keyboard = [];
        while($file = $respd->fetch_assoc()){
            $id = $file['id'];
            $name = $file['title'];
            $keyboard[] = ['text' => "$name", 'callback_data' => "createAccPlan{$id}"];
        }
        $keyboard[] = ['text' => $buttonValues['back_to_main'], 'callback_data' => "createAccServer$sid"];
        $keyboard = array_chunk($keyboard,1);
        editText($message_id, "3️⃣ مرحله سه:

یکی از پلن هارو انتخاب کن و برو برای پرداختش 🤲 🕋", json_encode(['inline_keyboard'=>$keyboard]));
    }

}
if(preg_match('/^createAccPlan(\d+)/',$data,$match) && $text != $buttonValues['cancel']){
    delMessage();
    sendMessage("❗️لطفا مدت زمان اکانت را به ( روز ) وارد کن:",$cancelKey);
    setUser('createAccDate' . $match[1]);
}
if(preg_match('/^createAccDate(\d+)/',$userInfo['step'],$match) && $text != $buttonValues['cancel']){
    if(is_numeric($text)){
        if($text >0){
            sendMessage("❕حجم اکانت ها رو به گیگابایت ( GB ) وارد کن:");
            setUser('createAccVolume' . $match[1] . "_" . $text);
        }else{
            sendMessage("عدد باید بیشتر از 0 باشه");
        }
    }else{
        sendMessage('😡 | مگه نمیگم فقط عدد بفرس نمیفهمی؟ یا خودتو زدی به نفهمی؟');
    }
}
if(preg_match('/^createAccVolume(\d+)_(\d+)/',$userInfo['step'],$match) && $text != $buttonValues['cancel']){
    if(!is_numeric($text)){
        sendMessage($mainValues['send_only_number']);
        exit();
    }elseif($text <=0){
        sendMessage("مقداری بزرگتر از 0 وارد کن");
        exit();
    }
    sendMessage($mainValues['enter_account_amount']);
    setUser("createAccAmount" . $match[1] . "_" . $match[2] . "_" . $text);
}
if(preg_match('/^createAccAmount(\d+)_(\d+)_(\d+)/',$userInfo['step'], $match) && $text != $buttonValues['cancel']){
    if(!is_numeric($text)){
        sendMessage($mainValues['send_only_number']);
        exit();
    }elseif($text <=0){
        sendMessage("مقداری بزرگتر از 0 وارد کن");
        exit();
    }
    $uid = $from_id;
    $fid = $match[1];
    $acctxt = '';
    
    
    $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();

    $days = $match[2];
    $date = time();
    $expire_microdate = floor(microtime(true) * 1000) + (864000 * $days * 100);
    $expire_date = $date + (86400 * $days);
    $type = $file_detail['type'];
    $volume = $match[3];
    $protocol = $file_detail['protocol'];
    $price = $file_detail['price'];
    $rahgozar = $file_detail['rahgozar'];
    $customPath = $file_detail['custom_path'];
    $customPort = $file_detail['custom_port'];
    $customSni = $file_detail['custom_sni'];
    
    
    
    $server_id = $file_detail['server_id'];
    $netType = $file_detail['type'];
    $acount = $file_detail['acount'];
    $inbound_id = $file_detail['inbound_id'];
    $limitip = $file_detail['limitip'];


    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) {
            $stmt = $connection->prepare("UPDATE `server_info` SET `ucount` = `ucount` - 1 WHERE `id`=?");
            $stmt->bind_param("i", $server_id);
            $stmt->execute();
            $stmt->close();

        } else {
            alert($mainValues['out_of_server_capacity']);
            exit;
        }
    }else{
        if($acount != 0 && $acount >= $text) {
            $stmt = $connection->prepare("UPDATE `server_plans` SET `acount` = `acount` - ? WHERE id=?");
            $stmt->bind_param("ii", $text, $fid);
            $stmt->execute();
            $stmt->close();
        }
        else{
            sendMessage(str_replace("AMOUNT", $acount, $mainValues['can_create_specific_account']));
            exit();
        }
    }

    $stmt = $connection->prepare("SELECT * FROM `server_info` WHERE `id`=?");
    $stmt->bind_param("i", $server_id);
    $stmt->execute();
    $srv_remark = $stmt->get_result()->fetch_assoc()['remark'];
    $stmt->close();
    $savedinfo = file_get_contents('settings/temp.txt');
    $savedinfo = explode('-',$savedinfo);
    $port = $savedinfo[0];
    $last_num = $savedinfo[1];
    include 'phpqrcode/qrlib.php';
    $ecc = 'L';
    $pixel_Size = 10;
    $frame_Size = 10;
    
    $stmt = $connection->prepare("SELECT * FROM `server_config` WHERE `id`=?");
    $stmt->bind_param("i", $server_id);
    $stmt->execute();
    $portType = $stmt->get_result()->fetch_assoc()['port_type'];
    $stmt->close();


	$stmt = $connection->prepare("INSERT INTO `orders_list` 
	    (`userid`, `token`, `transid`, `fileid`, `server_id`, `inbound_id`, `remark`, `protocol`, `expire_date`, `link`, `amount`, `status`, `date`, `notif`, `rahgozar`)
	    VALUES (?, ?, '', ?, ?, ?, ?, ?, ?, ?, ?,1, ?, 0, ?);");
    for($i = 1; $i<= $text; $i++){
        $token = RandomString(30);
        $uniqid = generateRandomString(42,$protocol); 
        if($portType == "auto"){
            $port++;
        }else{
            $port = rand(1111,65000);
        }
        $last_num++;
        
        if($botState['remark'] == "digits"){
            $rnd = rand(10000,99999);
            $remark = "{$srv_remark}-{$rnd}";
        }else{
            $rnd = rand(1111,99999);
            $remark = "{$srv_remark}-{$from_id}-{$rnd}";
        }
    
        if($inbound_id == 0){    
            $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(is_null($response)){
            sendMessage('❌ | 🥺 گلم ، اتصال به سرور برقرار نیست لطفا مدیر رو در جریان بزار ...');
            break;
        }
    	if($response == "inbound not Found"){
            sendMessage("❌ | 🥺 سطر (inbound) با آیدی $inbound_id تو این سرور وجود نداره ، مدیر رو در جریان بزار ...");
            break;
    	}
    	if(!$response->success){
            sendMessage('❌ | 😮 وای خطا داد لطفا سریع به مدیر بگو ...');
            break;
        }
    
        $vraylink = getConnectionLink($server_id, $uniqid, $protocol, $remark, $port, $netType, $inbound_id, $rahgozar, $customPath, $customPort, $customSni);
        $subLink = $botState['subLinkState']=="on"?$botUrl . "settings/subLink.php?token=" . $token:"";
        foreach($vraylink as $vray_link){
            $acc_text = "
    
        🔮 $remark \n <code>$vray_link</code>
            ";
            if($botState['subLinkState'] == "on") $acc_text .= 
            " \n🌐 subscription : <code>$subLink</code>";
        
            $file = RandomString() .".png";
            QRcode::png($vray_link, $file, $ecc, $pixel_Size, $frame_Size);
        	addBorderImage($file);
        	sendPhoto($botUrl . $file, $acc_text,json_encode(['inline_keyboard'=>[[['text'=>"صفحه اصلی 🏘",'callback_data'=>"mainMenu"]]]]),"HTML", $uid);
            unlink($file);
        }
        $vray_link = json_encode($vraylink);
        $stmt->bind_param("ssiiissisiii", $uid, $token, $fid, $server_id, $inbound_id, $remark, $protocol, $expire_date, $vray_link, $price, $date, $rahgozar);
        $stmt->execute();
    }
    $stmt->close();
    if($portType == "auto"){
        file_put_contents('settings/temp.txt',$port.'-'.$last_num);
    }
    sendMessage("☑️|❤️ اکانت های جدید با موفقیت ساخته شد",getMainKeys());
    setUser();
}
if(preg_match('/payWithWeSwap(.*)/',$data,$match)) {
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]);
    $stmt->execute();
    $payInfo = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    $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();
            }
        }
    }
    
    delMessage();
    sendMessage($mainValues['please_wait_message'],$removeKeyboard);
    
    
    $price = $payInfo['price'];
    $rate = json_decode(file_get_contents("https://api.changeto.technology/api/rate"),true)['result'];
    $priceInUSD = round($price / $rate['USD'],2);
    $priceInTrx = round($price / $rate['TRX'],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(.*)/',$data,$match)) {
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]);
    $stmt->execute();
    $payInfo = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    if($payInfo['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();
        
    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);                
    }
    elseif($payType == "BUY_SUB"){
    $uid = $from_id;
    $fid = $payInfo['plan_id']; 
    $volume = $payInfo['volume'];
    $days = $payInfo['day'];
    $description = $payInfo['description'];
    
    
    $acctxt = '';
    
    $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 = floor(microtime(true) * 1000) + (864000 * $days * 100);
    $expire_date = $date + (86400 * $days);
    $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) {
            $stmt = $connection->prepare("UPDATE `server_info` SET `ucount` = `ucount` - ? WHERE `id`=?");
            $stmt->bind_param("ii", $accountCount, $server_id);
            $stmt->execute();
            $stmt->close();
    
        } else {
            alert($mainValues['out_of_server_capacity']);
            exit;
        }
    }else{
        if($acount != 0) {
            $stmt = $connection->prepare("UPDATE `server_plans` SET `acount` = `acount` - ? WHERE id=?");
            $stmt->bind_param("ii", $accountCount, $fid);
            $stmt->execute();
            $stmt->close();
        }
    }

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

    $stmt = $connection->prepare("SELECT * FROM `server_config` WHERE `id`=?");
    $stmt->bind_param("i", $server_id);
    $stmt->execute();
    $portType = $stmt->get_result()->fetch_assoc()['port_type'];
    $stmt->close();
    include 'phpqrcode/qrlib.php';

    alert('🚀 | 😍 در حال ارسال کانفیگ به مشتری ...');
    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}";
        }else{
            $rnd = rand(1111,99999);
            $remark = "{$srv_remark}-{$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){    
            $response = addUser($server_id, $uniqid, $protocol, $port, $expire_microdate, $remark, $volume, $netType, 'none', $rahgozar, $fid); 
            if(! $response->success){
                $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){
                $response = addInboundAccount($server_id, $uniqid, $inbound_id, $expire_microdate, $remark, $volume, $limitip, null, $fid);
            } 
        }
        
        if(is_null($response)){
            alert('❌ | 🥺 گلم ، اتصال به سرور برقرار نیست لطفا مدیر رو در جریان بزار ...');
            exit;
        }
        if($response == "inbound not Found"){
            alert("❌ | 🥺 سطر (inbound) با آیدی $inbound_id تو این سرور وجود نداره ، مدیر رو در جریان بزار ...");
        	exit;
        }
        if(!$response->success){
            alert('❌ | 😮 وای خطا داد لطفا سریع به مدیر بگو ...');
            exit;
        }
        
        $token = RandomString(30);
        $subLink = $botState['subLinkState']=="on"?$botUrl . "settings/subLink.php?token=" . $token:"";

        $vraylink = getConnectionLink($server_id, $uniqid, $protocol, $remark, $port, $netType, $inbound_id, $rahgozar, $customPath, $customPort, $customSni);
        foreach($vraylink as $vray_link){
        $acc_text = "
        
        😍 سفارش جدید شما
        📡 پروتکل: $protocol
        🔮 نام سرویس: $remark
        🔋حجم سرویس: $volume گیگ
        ⏰ مدت سرویس: $days روز
        ⁮⁮ ⁮⁮
        💝 config : <code>$vray_link</code>";
        if($botState['subLinkState'] == "on") $acc_text .= "
        
        🌐 subscription : <code>$subLink</code>
        
        ";
              
            $file = RandomString() .".png";
            $ecc = 'L';
            $pixel_Size = 10;
            $frame_Size = 10;
            
            QRcode::png($vray_link, $file, $ecc, $pixel_Size, $frame_Size);
        	addBorderImage($file);
        	sendPhoto($botUrl . $file, $acc_text,json_encode(['inline_keyboard'=>[[['text'=>"صفحه اصلی 🏘",'callback_data'=>"mainMenu"]]]]),"HTML", $uid);
            unlink($file);
        }
        
        $vray_link = json_encode($vraylink);
        $agentBought = $payInfo['agent_bought'];
        
        $stmt = $connection->prepare("INSERT INTO `orders_list` 
            (`userid`, `token`, `transid`, `fileid`, `server_id`, `inbound_id`, `remark`, `protocol`, `expire_date`, `link`, `amount`, `status`, `date`, `notif`, `rahgozar`, `agent_bought`)
            VALUES (?, ?, '', ?, ?, ?, ?, ?, ?, ?, ?,1, ?, 0, ?, ?);");
        $stmt->bind_param("ssiiissisiiii", $uid, $token, $fid, $server_id, $inbound_id, $remark, $protocol, $expire_date, $vray_link, $eachPrice, $date, $rahgozar, $agentBought);
        $stmt->execute();
        $order = $stmt->get_result(); 
        $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);
    }
    $keys = json_encode(['inline_keyboard'=>[
        [
            ['text'=>"بنازم خرید جدید ❤️",'callback_data'=>"wizwizch"]
        ],
        ]]);
    
    $msg = str_replace(['TYPE', 'USER-ID', 'USERNAME', 'NAME', 'PRICE', 'REMARK', 'VOLUME', 'DAYS'],
                ['ارزی ریالی', $from_id, $username, $first_name, $price, $remark,$volume, $days], $mainValues['buy_custom_account_request']);
    
    sendMessage($msg,$keys,"html", $admin);
}
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'];
    $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` = ? AND `active` = 1");
    $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'];
    
    if($inbound_id > 0)
        $response = editClientTraffic($server_id, $inbound_id, $remark, $volume, $days, "renew");
    else
        $response = editInboundTraffic($server_id, $remark, $volume, $days, "renew");
    
    if(is_null($response)){
    	alert('🔻مشکل فنی در اتصال به سرور. لطفا به مدیریت اطلاع بدید',true);
    	exit;
    }
    $stmt = $connection->prepare("UPDATE `orders_list` SET `expire_date` = ?, `notif` = 0 WHERE `id` = ?");
    $newExpire = $expire_date + $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'=>"wizwizch"]
        ],
    ]]);

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

sendMessage($msg, $keys,"html", $admin);
}
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'];
    
    $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'];


if($inbound_id > 0)
    $response = editClientTraffic($server_id, $inbound_id, $remark, 0, $volume);
else
    $response = editInboundTraffic($server_id, $remark, 0, $volume);
    
if($response->success){
    $stmt = $connection->prepare("UPDATE `orders_list` SET `expire_date` = `expire_date` + ?, `notif` = 0 WHERE `remark` = ?");
    $newVolume = $volume * 86400;
    $stmt->bind_param("is", $newVolume, $remark);
    $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();
    
    sendMessage("✅$volume روز به مدت زمان سرویس شما اضافه شد",getMainKeys());
    
    $keys = json_encode(['inline_keyboard'=>[
        [
            ['text'=>"اخیش یکی زمان زد 😁",'callback_data'=>"wizwizch"]
            ],
        ]]);
sendMessage("
🔋|💰 افزایش زمان با ( کیف پول )

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

    exit;
}else {
    alert("به دلیل مشکل فنی امکان افزایش حجم نیست. لطفا به مدیریت اطلاع بدید یا 5دقیقه دیگر دوباره تست کنید", true);
    exit;
}
}
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'];

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

if($inbound_id > 0)
    $response = editClientTraffic($server_id, $inbound_id, $remark, $volume, 0);
else
    $response = editInboundTraffic($server_id, $remark, $volume, 0);
    
if($response->success){
    $stmt = $connection->prepare("UPDATE `orders_list` SET `notif` = 0 WHERE `remark` = ?");
    $stmt->bind_param("s", $remark);
    $stmt->execute();
    $stmt->close();
    $keys = json_encode(['inline_keyboard'=>[
        [
            ['text'=>"اخیش یکی حجم زد 😁",'callback_data'=>"wizwizch"]
            ],
        ]]);
sendMessage("
🔋|💰 افزایش حجم با ( کیف پول )

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

}else {
    alert("به دلیل مشکل فنی امکان افزایش حجم نیست. لطفا به مدیریت اطلاع بدید یا 5دقیقه دیگر دوباره تست کنید",true);
    exit;
}
}
elseif($payType == "RENEW_SCONFIG"){
    $uid = $from_id;
    $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();
    
    $volume = $file_detail['volume'];
    $days = $file_detail['days'];
    
    $price = $payInfo['price'];   
    $server_id = $file_detail['server_id'];
    $remark = $payInfo['description'];
    $inbound_id = $payInfo['volume']; 
    
    if($inbound_id > 0)
        $response = editClientTraffic($server_id, $inbound_id, $remark, $volume, $days, "renew");
    else
        $response = editInboundTraffic($server_id, $remark, $volume, $days, "renew");
    
	if(is_null($response)){
		alert('🔻مشکل فنی در اتصال به سرور. لطفا به مدیریت اطلاع بدید',true);
		exit;
	}
	$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();

}
    
    editKeys(json_encode(['inline_keyboard'=>[
		    [['text'=>"پرداخت انجام شد",'callback_data'=>"wizwizch"]]
		    ]]));
}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=="messageToSpeceficUser" && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    delMessage();
    sendMessage($mainValues['send_user_id'], $cancelKey);
    setUser($data);
}
if($userInfo['step'] == "messageToSpeceficUser" && $text != $buttonValues['cancel'] && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    if(!is_numeric($text)){
        sendMessage($mainValues['send_only_number']);
        exit();
    }
    $stmt = $connection->prepare("SELECT * FROM `users` WHERE `userid` = ?");
    $stmt->bind_param("i", $text);
    $stmt->execute();
    $usersCount = $stmt->get_result()->num_rows;
    $stmt->close();

    if($usersCount > 0 ){
        sendMessage("👀| خصوصی میخوای بهش پیام بدی شیطون، پیامت رو بفرس تا در گوشش بگم:");
        setUser("sendMessageToUser" . $text);
    }else{
        sendMessage($mainValues['user_not_found']);
    }
}
if ($data == 'message2All' and ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $sendInfo = json_decode(file_get_contents("settings/messagewizwiz.json"),true);
    $offset = $sendInfo['offset'];
    $msg = $sendInfo['text'];
    
    if(strlen($msg) > 1 and $offset != -1) {
        $stmt = $connection->prepare("SELECT * FROM `users`");
        $stmt->execute();
        $usersCount = $stmt->get_result()->num_rows;
        $stmt->close();
        
        $leftMessages = $offset == 0 ? $usersCount - $offset : $usersCount - $offset;
        $offset = $offset == 0 ? $offset : $offset;
        sendMessage("
❗️ یک پیام همگانی در صف انتشار می باشد لطفا صبور باشید ...

🔰 تعداد کاربران : $usersCount
☑️ ارسال شده : $offset
📣 باقیمانده : $leftMessages
⁮⁮ ⁮⁮ ⁮⁮ ⁮⁮
");exit;
    }
    
    delMessage();
    sendMessage("📣 <b>ارسال پیام همگانی</b>\n\n🔹 پیام خود را ارسال کنید\n\n✅ می‌توانید ارسال کنید:\n• متن\n• عکس (با توضیحات)\n• ویدیو (با توضیحات)\n• فایل (با توضیحات)\n\n⚠️ پس از ارسال، از شما تأیید نهایی گرفته می‌شود.", $cancelKey, "HTML");
    setUser('s2a');
    exit;
}
if ($userInfo['step'] == 's2a' and $text != $buttonValues['cancel']){
    setUser();
    
    if($fileid !== null) {
        $value = ['fileid'=>$fileid,'caption'=>$caption];
        $type = $filetype;
    }
    else{
        $type = 'text';
        $value = $text;
    }
    $messageValue = json_encode(['type'=>$type,'value'=> $value]);
    
    $sendInfo = json_decode(file_get_contents("settings/messagewizwiz.json"),true);
    $sendInfo['offset'] = 0;
    $sendInfo['text'] = $messageValue;
    file_put_contents("settings/messagewizwiz.json",json_encode($sendInfo));
    
    sendMessage('✅ پیام دریافت شد!',$removeKeyboard);
    
    // نمایش پیش‌نمایش
    $stmt = $connection->prepare("SELECT COUNT(*) as count FROM `users`");
    $stmt->execute();
    $totalUsers = $stmt->get_result()->fetch_assoc()['count'];
    $stmt->close();
    
    $previewMsg = "📊 <b>پیش‌نمایش ارسال همگانی</b>\n\n";
    $previewMsg .= "👥 تعداد کاربران: <b>" . number_format($totalUsers) . "</b>\n\n";
    $previewMsg .= "📝 نوع پیام: ";
    
    if($type == 'text') $previewMsg .= "متن";
    elseif($type == 'photo') $previewMsg .= "عکس";
    elseif($type == 'video') $previewMsg .= "ویدیو";
    elseif($type == 'document') $previewMsg .= "فایل";
    else $previewMsg .= $type;
    
    $previewMsg .= "\n\n━━━━━━━━━━━━━━━━━━━━━━\n\n";
    $previewMsg .= "⚠️ آیا مطمئن هستید که می‌خواهید این پیام را برای همه ارسال کنید؟";
    
    sendMessage($previewMsg, json_encode(['inline_keyboard'=>[
        [['text'=>'✅ بله، ارسال شود','callback_data'=>'yesSend2All']],
        [['text'=>'❌ خیر، لغو کن','callback_data'=>'noDontSend2all']]
    ]]), "HTML");
}
if($data=="noDontSend2all" and ($from_id == $admin || $userInfo['isAdmin'] == true)){
    delMessage();
    $sendInfo = json_decode(file_get_contents("settings/messagewizwiz.json"),true);
    $sendInfo['offset'] = -1;
    file_put_contents("settings/messagewizwiz.json",json_encode($sendInfo));
    
    sendMessage("❌ ارسال پیام همگانی لغو شد.");
    sendMessage($mainValues['reached_main_menu'],getMainKeys());
}
if($data=="yesSend2All" and ($from_id == $admin || $userInfo['isAdmin'] == true)){
    delMessage();
    sendMessage("🚀 <b>شروع ارسال همگانی...</b>\n\n⏳ لطفاً صبر کنید تا پیام برای همه ارسال شود.", null, "HTML");
    
    $sendInfo = json_decode(file_get_contents("settings/messagewizwiz.json"),true);
    $messageData = json_decode($sendInfo['text'], true);
    $type = $messageData['type'];
    $value = $messageData['value'];
    
    $stmt = $connection->prepare("SELECT `userid` FROM `users`");
    $stmt->execute();
    $users = $stmt->get_result();
    $stmt->close();
    
    $totalUsers = $users->num_rows;
    $successCount = 0;
    $failedCount = 0;
    $failedUsers = [];
    
    $startTime = time();
    $counter = 0;
    $lastMessageId = null;
    
    while($user = $users->fetch_assoc()){
        $userId = $user['userid'];
        $counter++;
        
        try {
            if($type == 'text'){
                $result = sendMessage($value, null, "HTML", $userId);
            }
            elseif($type == 'photo'){
                $result = sendPhoto($value['fileid'], $value['caption'], null, "HTML", $userId);
            }
            elseif($type == 'video'){
                $result = bot('sendVideo', [
                    'chat_id' => $userId,
                    'video' => $value['fileid'],
                    'caption' => $value['caption'],
                    'parse_mode' => 'HTML'
                ]);
            }
            elseif($type == 'document'){
                $result = bot('sendDocument', [
                    'chat_id' => $userId,
                    'document' => $value['fileid'],
                    'caption' => $value['caption'],
                    'parse_mode' => 'HTML'
                ]);
            }
            
            if($result && $result->ok){
                $successCount++;
            } else {
                $failedCount++;
                $failedUsers[] = $userId;
            }
        } catch(Exception $e) {
            $failedCount++;
            $failedUsers[] = $userId;
        }
        
        // هر 50 کاربر یک گزارش میانی
        if($counter % 50 == 0 || $counter == $totalUsers){
            $progress = round(($counter / $totalUsers) * 100, 1);
            $elapsed = time() - $startTime;
            $estimated = $totalUsers > 0 ? round(($elapsed / $counter) * ($totalUsers - $counter)) : 0;
            
            $progressMsg = "📊 <b>در حال ارسال...</b>\n\n";
            $progressMsg .= "✅ ارسال شده: <b>$successCount</b>\n";
            $progressMsg .= "❌ ناموفق: <b>$failedCount</b>\n";
            $progressMsg .= "📈 پیشرفت: <b>$counter</b> از <b>$totalUsers</b> (<b>$progress%</b>)\n\n";
            $progressMsg .= "⏱ زمان سپری شده: <b>" . gmdate('i:s', $elapsed) . "</b>\n";
            $progressMsg .= "⏳ زمان تخمینی باقیمانده: <b>" . gmdate('i:s', $estimated) . "</b>";
            
            if(!$lastMessageId){
                $lastMsg = sendMessage($progressMsg, null, "HTML");
                $lastMessageId = $lastMsg->result->message_id;
            } else {
                editText($lastMessageId, $progressMsg, null, "HTML");
            }
        }
        
        // تأخیر برای جلوگیری از محدودیت API تلگرام
        usleep(50000); // 50 میلی‌ثانیه
    }
    
    $sendInfo['offset'] = -1;
    file_put_contents("settings/messagewizwiz.json", json_encode($sendInfo));
    
    $totalTime = time() - $startTime;
    $minutes = floor($totalTime / 60);
    $seconds = $totalTime % 60;
    
    $finalReport = "✅ <b>ارسال همگانی با موفقیت پایان یافت!</b>\n\n";
    $finalReport .= "━━━━━━━━━━━━━━━━━━━━━━\n\n";
    $finalReport .= "📊 <b>آمار کامل:</b>\n\n";
    $finalReport .= "👥 کل کاربران: <b>" . number_format($totalUsers) . "</b>\n";
    $finalReport .= "✅ ارسال موفق: <b>" . number_format($successCount) . "</b>\n";
    $finalReport .= "❌ ارسال ناموفق: <b>" . number_format($failedCount) . "</b>\n";
    $finalReport .= "📈 نرخ موفقیت: <b>" . round(($successCount / $totalUsers) * 100, 1) . "%</b>\n\n";
    $finalReport .= "⏱ زمان کل: <b>$minutes دقیقه و $seconds ثانیه</b>\n\n";
    $finalReport .= "━━━━━━━━━━━━━━━━━━━━━━";
    
    if($failedCount > 0 && count($failedUsers) <= 10){
        $finalReport .= "\n\n⚠️ <b>کاربران ناموفق:</b>\n";
        foreach($failedUsers as $failedUser){
            $finalReport .= "• <code>$failedUser</code>\n";
        }
    }
    
    editText($lastMessageId, $finalReport, getMainKeys(), "HTML");
}
if(preg_match('/selectServer(\d+)/',$data, $match) && ($botState['sellState']=="on" || ($from_id == $admin || $userInfo['isAdmin'] == true)) ) {
    $sid = $match[1];
        
    $stmt = $connection->prepare("SELECT * FROM `server_categories` WHERE `parent`=0 order by `id` asc");
    $stmt->execute();
    $respd = $stmt->get_result();
    $stmt->close();
    if($respd->num_rows == 0){
        alert($mainValues['category_not_avilable']);
    }else{
        
        $keyboard = [];
        while ($file = $respd->fetch_assoc()){
            $id = $file['id'];
            $name = $file['title'];
            $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `server_id`=? and `catid`=? and `active`=1");
            $stmt->bind_param("ii", $sid, $id);
            $stmt->execute();
            $rowcount = $stmt->get_result()->num_rows; 
            $stmt->close();
            if($rowcount>0) $keyboard[] = ['text' => "$name", 'callback_data' => "selectCategory{$id}_{$sid}"];
        }
        if(empty($keyboard)){
            alert($mainValues['category_not_avilable']);exit;
        }
        alert($mainValues['receive_categories']);
        $keyboard[] = ['text' => $buttonValues['back_to_main'], 'callback_data' => "buySubscription"];
        $keyboard = array_chunk($keyboard,1);
        editText($message_id,$mainValues['buy_sub_select_category'], json_encode(['inline_keyboard'=>$keyboard]));
    }

}
if(preg_match('/selectCategory(\d+)_(\d+)/',$data,$match) && ($botState['sellState']=="on" || $from_id == $admin || $userInfo['isAdmin'] == true)) {
    $call_id = $match[1];
    $sid = $match[2];
    $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `server_id`=? and `price` != 0 and `catid`=? and `active`=1 order by `id` asc");
    $stmt->bind_param("ii", $sid, $call_id);
    $stmt->execute();
    $respd = $stmt->get_result();
    $stmt->close();
    if($respd->num_rows==0){
        alert($mainValues['no_plan_available']); 
    }else{
        alert($mainValues['receive_plans']);
        $keyboard = [];
        while($file = $respd->fetch_assoc()){
            $id = $file['id'];
            $name = $file['title'];
            $price = $file['price'];
            if($userInfo['is_agent'] == true && ($userInfo['temp'] == "agentBuy" || $userInfo['temp'] == "agentMuchBuy")) $price -= floor($price * $userInfo['discount_percent'] / 100);
            $price = ($price == 0) ? 'رایگان' : number_format($price).' تومان ';
            $keyboard[] = ['text' => "$name - $price", 'callback_data' => "selectPlan{$id}_{$call_id}"];
        }
        if($botState['plandelkhahState'] == "on"){
	        $keyboard[] = ['text' => $mainValues['buy_custom_plan'], 'callback_data' => "selectCustomPlan{$call_id}_{$sid}"];
        }
        $keyboard[] = ['text' => $buttonValues['back_to_main'], 'callback_data' => "selectServer$sid"];
        $keyboard = array_chunk($keyboard,1);
        editText($message_id,$mainValues['buy_sub_select_plan'], json_encode(['inline_keyboard'=>$keyboard]));
    }

}
if(preg_match('/selectCustomPlan(\d+)_(\d+)/',$data,$match) && ($botState['sellState']=="on" || $from_id == $admin || $userInfo['isAdmin'] == true)) {
    $call_id = $match[1];
    $sid = $match[2];
    $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `server_id`=? and `catid`=? and `active`=1 order by `id` asc");
    $stmt->bind_param("ii", $sid, $call_id);
    $stmt->execute();
    $respd = $stmt->get_result();
    $stmt->close();
    alert($mainValues['receive_plans']);
    $keyboard = [];
    while($file = $respd->fetch_assoc()){
        $id = $file['id'];
        $name = preg_replace("/پلن\s(\d+)\sگیگ\s/","",$file['title']);
        $keyboard[] = ['text' => "$name", 'callback_data' => "selectCustomePlan{$id}_{$call_id}"];
    }
    $keyboard[] = ['text' => $buttonValues['back_to_main'], 'callback_data' => "selectServer$sid"];
    $keyboard = array_chunk($keyboard,1);
    editText($message_id, $mainValues['select_one_plan_to_edit'], json_encode(['inline_keyboard'=>$keyboard]));

}
if(preg_match('/selectCustomePlan(\d+)_(\d+)/',$data, $match) && ($botState['sellState']=="on" ||$from_id ==$admin)){
	delMessage();
	$price = $botState['gbPrice'];
	if($userInfo['temp'] == "agentBuy" && $userInfo['is_agent'] == true) $price -= ($price * $userInfo['discount_percent'] / 100);
	sendMessage(str_replace("VOLUME-PRICE", $price, $mainValues['customer_custome_plan_volume']),$cancelKey);
	setUser("selectCustomPlanGB" . $match[1] . "_" . $match[2]);
}
if(preg_match('/selectCustomPlanGB(\d+)_(\d+)/',$userInfo['step'], $match) && ($botState['sellState']=="on" ||$from_id ==$admin) && $text != $buttonValues['cancel']){
    if(!is_numeric($text)){
        sendMessage("😡|لطفا فقط عدد ارسال کن");
        exit();
    }
    elseif($text <=0){
        sendMessage("لطفا عددی بزرگتر از 0 وارد کن");
        exit();
    }
    $id = $match[1];
    $price = $botState['dayPrice'];
	if($userInfo['temp'] == "agentBuy" && $userInfo['is_agent'] == true) $price -= ($price * $userInfo['discount_percent'] / 100);
    
	sendMessage(str_replace("DAY-PRICE", $price, $mainValues['customer_custome_plan_day']));
	setUser("selectCustomPlanDay" . $match[1] . "_" . $match[2] . "_" . $text);
}
if((preg_match('/selectCustomPlanDay(\d+)_(\d+)_(\d+)/',$userInfo['step'], $match)) && ($botState['sellState']=="on" ||$from_id ==$admin) && $text != $buttonValues['cancel']){
    if(!is_numeric($text)){
        sendMessage("😡|لطفا فقط عدد ارسال کن");
        exit();
    }
    elseif($text <=0){
        sendMessage("لطفا عددی بزرگتر از 0 وارد کن");
        exit();
    }
    
	sendMessage($mainValues['customer_custome_plan_name']);
	setUser("enterCustomPlanName" . $match[1] . "_" . $match[2] . "_" . $match[3] . "_" . $text);
}
if((preg_match('/^discountCustomPlanDay(\d+)/',$userInfo['step'], $match) || preg_match('/enterCustomPlanName(\d+)_(\d+)_(\d+)_(\d+)/',$userInfo['step'], $match)) && ($botState['sellState']=="on" ||$from_id ==$admin) && $text != $buttonValues['cancel']){
    if(preg_match('/^discountCustomPlanDay/', $userInfo['step'])){
        $rowId = $match[1];

        $time = time();
        $stmt = $connection->prepare("SELECT * FROM `discounts` WHERE (`expire_date` > $time OR `expire_date` = 0) AND (`expire_count` > 0 OR `expire_count` = -1) AND `hash_id` = ?");
        $stmt->bind_param("s", $text);
        $stmt->execute();
        $list = $stmt->get_result();
        $stmt->close();
        
        $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `id` = ?");
        $stmt->bind_param("i", $rowId);
        $stmt->execute();
        $payInfo = $stmt->get_result()->fetch_assoc();
        $hash_id = $payInfo['hash_id'];
        $price = $payInfo['price'];
        $id = $payInfo['type'];
    	$volume = $payInfo['volume'];
        $days = $payInfo['day'];
        $stmt->close();
            
        if($list->num_rows>0){
            $discountInfo = $list->fetch_assoc();
            $amount = $discountInfo['amount'];
            $type = $discountInfo['type'];
            $count = $discountInfo['expire_count'];
            $usedBy = !is_null($discountInfo['used_by'])?json_decode($discountInfo['used_by'],true):array();
            
            $canUse = $discountInfo['can_use'];
            $userUsedCount = array_count_values($usedBy)[$from_id];
            if($canUse > $userUsedCount){
                $usedBy[] = $from_id;
                $encodeUsedBy = json_encode($usedBy);
                
                if ($count != -1) $query = "UPDATE `discounts` SET `expire_count` = `expire_count` - 1, `used_by` = ? WHERE `id` = ?";
                else $query = "UPDATE `discounts` SET `used_by` = ? WHERE `id` = ?";
            
                $stmt = $connection->prepare($query);
                $stmt->bind_param("si", $encodeUsedBy, $discountInfo['id']);
                $stmt->execute();
                $stmt->close();
                
                if($type == "percent"){
                    $discount = $price * $amount / 100;
                    $price -= $discount;
                    $discount = number_format($discount) . " تومان";
                }else{
                    $price -= $amount;
                    $discount = number_format($amount) . " تومان";
                }
                if($price < 0) $price = 0;
                
                $stmt = $connection->prepare("UPDATE `pays` SET `price` = ? WHERE `id` = ?");
                $stmt->bind_param("ii", $price, $rowId);
                $stmt->execute();
                $stmt->close();
                sendMessage(str_replace("AMOUNT", $discount, $mainValues['valid_discount_code']));
                $keys = json_encode(['inline_keyboard'=>[
                    [
                        ['text'=>"❤️", "callback_data"=>"wizwizch"]
                        ],
                    ]]);
            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']);
    }else{
        $id = $match[1];
    	$call_id = $match[2];
    	$volume = $match[3];
        $days = $match[4];
        if(!preg_match("/^[^\W_]+$/",$text)){
            sendMessage("😡|اسم وارد شده معتبر نمی باشد");
            exit();
        }
    }
    $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `id`=? and `active`=1");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $respd = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    $stmt = $connection->prepare("SELECT * FROM `server_categories` WHERE `id`=?");
    $stmt->bind_param("i", $respd['catid']);
    $stmt->execute();
    $catname = $stmt->get_result()->fetch_assoc()['title'];
    $stmt->close();
    
    $name = $catname." ".$respd['title'];
    $desc = $respd['descr'];
	$sid = $respd['server_id'];
	$keyboard = array();
    $token = base64_encode("{$from_id}.{$id}");
    $temp = array();
    
    if(!preg_match('/^discountCustomPlanDay/', $userInfo['step'])){
        $discountPrice = 0;
        $gbPrice = $botState['gbPrice'];
        $dayPrice = $botState['dayPrice'];
        
        if($userInfo['is_agent'] == true && $userInfo['temp'] == "agentBuy") {$gbPrice -= ($gbPrice * $userInfo['discount_percent'] /100); $dayPrice -= ($dayPrice * $userInfo['discount_percent'] / 100);}
        
        $price =  ($volume * $gbPrice) + ($days * $dayPrice);
        $hash_id = RandomString();
        $stmt = $connection->prepare("DELETE FROM `pays` WHERE `user_id` = ? AND `type` = 'BUY_SUB' AND `state` = 'pending'");
        $stmt->bind_param("i", $from_id);
        $stmt->execute();
        $stmt->close();
        
        $time = time();
        $stmt = $connection->prepare("INSERT INTO `pays` (`hash_id`, `description`, `user_id`, `type`, `plan_id`, `volume`, `day`, `price`, `request_date`, `state`)
                                    VALUES (?, ?, ?, 'BUY_SUB', ?, ?, ?, ?, ?, 'pending')");
        $stmt->bind_param("ssiiiiii", $hash_id, $text, $from_id, $id, $volume, $days, $price, $time);
        $stmt->execute();
        $rowId = $stmt->insert_id;
        $stmt->close();
    }
    
    
    if($botState['cartToCartState'] == "on"){
	    $temp[] = ['text' => $buttonValues['cart_to_cart'],  'callback_data' => "payCustomWithCartToCart$hash_id"];
    }
    if($botState['nowPaymentOther'] == "on"){
	    $temp[] = ['text' => $buttonValues['now_payment_gateway'],  'url' => $botUrl . "pay/?nowpayment&hash_id=" . $hash_id];
    }
    if(count($temp) == 2){
        array_push($keyboard, $temp);
        $temp = array();
    }
    if($botState['zarinpal'] == "on"){
	    $temp[] = ['text' => $buttonValues['zarinpal_gateway'],  'url' => $botUrl . "pay/?zarinpal&hash_id=" . $hash_id];
    }
    if(count($temp) == 2){
        array_push($keyboard, $temp);
        $temp = array();
    }
    if($botState['nextpay'] == "on"){
	    $temp[] = ['text' => $buttonValues['nextpay_gateway'],  'url' => $botUrl . "pay/?nextpay&hash_id=" . $hash_id];
    }
    if(count($temp) == 2){
        array_push($keyboard, $temp);
        $temp = array();
    }
    if($botState['weSwapState'] == "on"){
	    $temp[] = ['text' => $buttonValues['weswap_gateway'],  'callback_data' => "payWithWeSwap" . $hash_id];
    }
    if(count($temp) == 2){
        array_push($keyboard, $temp);
        $temp = array();
    }
    if($botState['walletState'] == "on"){
	    $temp[] = ['text' => $buttonValues['pay_with_wallet'],  'callback_data' => "payCustomWithWallet$hash_id"];
    }
    array_push($keyboard, $temp);
    if(!preg_match('/^discountCustomPlanDay/', $userInfo['step'])) $keyboard[] = [['text' => " 🎁 نکنه کد تخفیف داری؟ ",  'callback_data' => "haveDiscountCustom_" . $rowId]];
	$keyboard[] = [['text' => $buttonValues['cancel'], 'callback_data' => "mainMenu"]];
    $price = ($price == 0) ? 'رایگان' : number_format($price).' تومان ';
    sendMessage(str_replace(['VOLUME', 'DAYS', 'PLAN-NAME', 'PRICE', 'DESCRIPTION'], [$volume, $days, $name, $price, $desc], $mainValues['buy_subscription_detail']),json_encode(['inline_keyboard'=>$keyboard]), "HTML");
    setUser();
}
if(preg_match('/^haveDiscount(.+?)_(.*)/',$data,$match)){
    delMessage();
    sendMessage($mainValues['insert_discount_code'],$cancelKey);
    if($match[1] == "Custom") setUser('discountCustomPlanDay' . $match[2]);
    elseif($match[1] == "SelectPlan") setUser('discountSelectPlan' . $match[2]);
    elseif($match[1] == "Renew") setUser('discountRenew' . $match[2]);
}
if($data=="getTestAccount"){
    if($userInfo['freetrial'] != null && $from_id != $admin && $userInfo['isAdmin'] != true){
        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){
        alert($mainValues['receving_information']);
    	$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();
            $catname = $catInfo->get_result()->fetch_assoc()['title'];
            $catInfo->close();
            
            $name = $catname." ".$row['title'];
            $price =  $row['price'];
            $desc = $row['descr'];
        	$sid = $row['server_id'];

            $keyboard[] = [['text' => $name, 'callback_data' => "freeTrial$id"]];

        }
    	$keyboard[] = [['text' => $buttonValues['back_to_main'], 'callback_data' => "mainMenu"]];
        editText($message_id,"لطفا یکی از کلید های زیر را انتخاب کنید", json_encode(['inline_keyboard'=>$keyboard]), "HTML");
    }else alert("این بخش موقتا غیر فعال است");
}
if((preg_match('/^discountSelectPlan(\d+)_(\d+)_(\d+)/',$userInfo['step'],$match) || preg_match('/selectPlan(\d+)_(\d+)/',$userInfo['step'], $match) || preg_match('/selectPlan(\d+)_(\d+)/',$data, $match)) && ($botState['sellState']=="on" ||$from_id ==$admin) && $text != $buttonValues['cancel']){
    if(preg_match('/^discountSelectPlan/', $userInfo['step'])){
        $rowId = $match[3];
        
        $time = time();
        $stmt = $connection->prepare("SELECT * FROM `discounts` WHERE (`expire_date` > $time OR `expire_date` = 0) AND (`expire_count` > 0 OR `expire_count` = -1) AND `hash_id` = ?");
        $stmt->bind_param("s", $text);
        $stmt->execute();
        $list = $stmt->get_result();
        $stmt->close();
        
        $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `id` = ?");
        $stmt->bind_param("i", $rowId);
        $stmt->execute();
        $payInfo = $stmt->get_result()->fetch_assoc();
        $hash_id = $payInfo['hash_id'];
        $afterDiscount = $payInfo['price'];
        $stmt->close();
        
        if($list->num_rows>0){
            $discountInfo = $list->fetch_assoc();
            $amount = $discountInfo['amount'];
            $type = $discountInfo['type'];
            $count = $discountInfo['expire_count'];
            $canUse = $discountInfo['can_use'];
            $usedBy = !is_null($discountInfo['used_by'])?json_decode($discountInfo['used_by'],true):array();
            $userUsedCount = array_count_values($usedBy)[$from_id];
            if($canUse > $userUsedCount){
                $usedBy[] = $from_id;
                $encodeUsedBy = json_encode($usedBy);
                
                if ($count != -1) $query = "UPDATE `discounts` SET `expire_count` = `expire_count` - 1, `used_by` = ? WHERE `id` = ?";
                else $query = "UPDATE `discounts` SET `used_by` = ? WHERE `id` = ?";
    
                $stmt = $connection->prepare($query);
                $stmt->bind_param("si", $encodeUsedBy, $discountInfo['id']);
                $stmt->execute();
                $stmt->close();
                
                if($type == "percent"){
                    $discount = $afterDiscount * $amount / 100;
                    $afterDiscount -= $discount;
                    $discount = number_format($discount) . " تومان";
                }else{
                    $afterDiscount -= $amount;
                    $discount = number_format($amount) . " تومان";
                }
                if($afterDiscount < 0) $afterDiscount = 0;
                
                $stmt = $connection->prepare("UPDATE `pays` SET `price` = ? 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"=>"wizwizch"]
                        ],
                    ]]);
                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(preg_match("/selectPlan(\d+)_(\d+)/",$userInfo['step'])){
        if($userInfo['temp'] == "agentMuchBuy"){
            if(is_numeric($text)){
                if($text > 0){
                    $accountCount = $text;
                    setUser();
                }else{sendMessage( $mainValues['send_positive_number']); exit(); }
            }else{ sendMessage($mainValues['send_only_number']); exit(); }
        }        
    }else{
        if($userInfo['temp'] == "agentMuchBuy"){
            setUser($data);
            sendMessage($mainValues['enter_account_amount']);
            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 && ($userInfo['temp'] == "agentBuy" || $userInfo['temp'] == "agentMuchBuy")){
        $price -= ($price * $userInfo['discount_percent'] /100);
        $agentBought = true;
    }
    if($price == 0 or ($from_id == $admin)){
        $keyboard[] = [['text' => '📥 دریافت رایگان', 'callback_data' => "freeTrial$id"]];
    }else{
        $token = base64_encode("{$from_id}.{$id}");
        $temp = array();
        
        
        if(!preg_match('/^discountSelectPlan/', $userInfo['step'])){
            $hash_id = RandomString();
            $stmt = $connection->prepare("DELETE FROM `pays` WHERE `user_id` = ? AND `type` = 'BUY_SUB' AND `state` = 'pending'");
            $stmt->bind_param("i", $from_id);
            $stmt->execute();
            $stmt->close();
            
            $time = time();
            if(isset($accountCount)){
                $stmt = $connection->prepare("INSERT INTO `pays` (`hash_id`, `user_id`, `type`, `plan_id`, `volume`, `day`, `price`, `request_date`, `state`, `agent_bought`, `agent_count`)
                                            VALUES (?, ?, 'BUY_SUB', ?, '0', '0', ?, ?, 'pending', ?, ?)");
                $stmt->bind_param("siiiiii", $hash_id, $from_id, $id, $price, $time, $agentBought, $accountCount);
            }else{
                $stmt = $connection->prepare("INSERT INTO `pays` (`hash_id`, `user_id`, `type`, `plan_id`, `volume`, `day`, `price`, `request_date`, `state`, `agent_bought`)
                                            VALUES (?, ?, 'BUY_SUB', ?, '0', '0', ?, ?, 'pending', ?)");
                $stmt->bind_param("siiiii", $hash_id, $from_id, $id, $price, $time, $agentBought);
            }
            $stmt->execute();
            $rowId = $stmt->insert_id;
            $stmt->close();
        }else{
            $price = $afterDiscount;
        }
        
        if($botState['cartToCartState'] == "on"){
		    $temp[] = ['text' => $buttonValues['cart_to_cart'],  'callback_data' => "payWithCartToCart$hash_id"];
        }
        if($botState['nowPaymentOther'] == "on"){
    	    $temp[] = ['text' => $buttonValues['now_payment_gateway'],  'url' => $botUrl . "pay/?nowpayment&hash_id=" . $hash_id];
        }
        if(count($temp) == 2){
            array_push($keyboard, $temp);
            $temp = array();
        }
        if($botState['zarinpal'] == "on"){
    	    $temp[] = ['text' => $buttonValues['zarinpal_gateway'],  'url' => $botUrl . "pay/?zarinpal&hash_id=" . $hash_id];
        }
        if(count($temp) == 2){
            array_push($keyboard, $temp);
            $temp = array();
        }
        if($botState['nextpay'] == "on"){
    	    $temp[] = ['text' => $buttonValues['nextpay_gateway'],  'url' => $botUrl . "pay/?nextpay&hash_id=" . $hash_id];
        }
        if(count($temp) == 2){
            array_push($keyboard, $temp);
            $temp = array();
        }
        if($botState['weSwapState'] == "on"){
    	    $temp[] = ['text' => $buttonValues['weswap_gateway'],  'callback_data' => "payWithWeSwap" . $hash_id];
        }
        if(count($temp) == 2){
            array_push($keyboard, $temp);
            $temp = array();
        }
        if($botState['walletState'] == "on"){
		    $temp[] = ['text' => $buttonValues['pay_with_wallet'],  'callback_data' => "payWithWallet$hash_id"];
        }
        array_push($keyboard, $temp);
        
        if(!preg_match('/^discountSelectPlan/', $userInfo['step'])) $keyboard[] = [['text' => " 🎁 نکنه کد تخفیف داری؟ ",  'callback_data' => "haveDiscountSelectPlan_" . $match[1] . "_" . $match[2] . "_" . $rowId]];

    }
	$keyboard[] = [['text' => $buttonValues['back_to_main'], 'callback_data' => "selectCategory{$call_id}_{$sid}"]];
    $priceC = ($price == 0) ? 'رایگان' : number_format($price).' تومان ';
    if(isset($accountCount)){
        $eachPrice = number_format($price / $accountCount) . " تومان";
        $msg = str_replace(['ACCOUNT-COUNT', 'TOTAL-PRICE', 'PLAN-NAME', 'PRICE', 'DESCRIPTION'], [$accountCount, $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");
}
if(preg_match('/payCustomWithWallet(.*)/',$data, $match)){
    setUser();
    
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]);
    $stmt->execute();
    $payInfo = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'approved' WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]);
    $stmt->execute();
    $stmt->close();
    
    $uid = $from_id;
    $fid = $payInfo['plan_id']; 
    $volume = $payInfo['volume'];
    $days = $payInfo['day'];
    
    $acctxt = '';
    
    $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();

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

    if($userInfo['wallet'] < $price){
        alert("موجودی حساب شما کم است");
        exit();
    }
    
    
    $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'];


    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) {
            $stmt = $connection->prepare("UPDATE `server_info` SET `ucount` = `ucount` - 1 WHERE `id`=?");
            $stmt->bind_param("i", $server_id);
            $stmt->execute();
            $stmt->close();

        } else {
            alert($mainValues['out_of_server_capacity']);
            exit;
        }
    }else{
        if($acount != 0) {
            $stmt = $connection->prepare("UPDATE `server_plans` SET `acount` = `acount` - 1 WHERE id=?");
            $stmt->bind_param("i", $fid);
            $stmt->execute();
            $stmt->close();
        }
    }

    $uniqid = generateRandomString(42,$protocol); 

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

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

    // $rnd = rand(1111,99999);
    // $remark = "{$srv_remark}-{$from_id}-{$rnd}";
    $remark = $payInfo['description']; 
    
    if($portType == "auto"){
        file_put_contents('settings/temp.txt',$port.'-'.$last_num);
    }else{
        $port = rand(1111,65000);
    }
    
    if($inbound_id == 0){    
        $response = addUser($server_id, $uniqid, $protocol, $port, $expire_microdate, $remark, $volume, $netType, 'none', $rahgozar, $fid); 
        if(! $response->success){
            $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){
            $response = addInboundAccount($server_id, $uniqid, $inbound_id, $expire_microdate, $remark, $volume, $limitip, null, $fid);
        } 
    }
    
    if(is_null($response)){
        alert('❌ | 🥺 گلم ، اتصال به سرور برقرار نیست لطفا مدیر رو در جریان بزار ...');
        exit;
    }
	if($response == "inbound not Found"){
        alert("❌ | 🥺 سطر (inbound) با آیدی $inbound_id تو این سرور وجود نداره ، مدیر رو در جریان بزار ...");
		exit;
	}
	if(!$response->success){
        alert('❌ | 😮 وای خطا داد لطفا سریع به مدیر بگو ...');
        exit;
    }
    alert('🚀 | 😍 در حال ارسال کانفیگ به مشتری ...');
    
    $stmt = $connection->prepare("UPDATE `users` SET `wallet` = `wallet` - ? WHERE `userid` = ?");
    $stmt->bind_param("ii", $price, $uid);
    $stmt->execute();
    include 'phpqrcode/qrlib.php';
    $token = RandomString(30);
    $subLink = $botState['subLinkState']=="on"?$botUrl . "settings/subLink.php?token=" . $token:"";

    $vraylink = getConnectionLink($server_id, $uniqid, $protocol, $remark, $port, $netType, $inbound_id, $rahgozar, $customPath, $customPort, $customSni);
    delMessage();
    foreach($vraylink as $vray_link){
        $acc_text = "
😍 سفارش جدید شما
📡 پروتکل: $protocol
🔮 نام سرویس: $remark
🔋حجم سرویس: $volume گیگ
⏰ مدت سرویس: $days روز
⁮⁮ ⁮⁮
💝 config : <code>$vray_link</code>";
if($botState['subLinkState'] == "on") $acc_text .= "

🌐 subscription : <code>$subLink</code>"; 
    
        $file = RandomString() .".png";
        $ecc = 'L';
        $pixel_Size = 10;
        $frame_Size = 10;
        
        QRcode::png($vray_link, $file, $ecc, $pixel_Size, $frame_Size);
    	addBorderImage($file);
    	sendPhoto($botUrl . $file, $acc_text,json_encode(['inline_keyboard'=>[[['text'=>"صفحه اصلی 🏘",'callback_data'=>"mainMenu"]]]]),"HTML", $uid);
        unlink($file);
    }

    
    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);
    }
    $vray_link = json_encode($vraylink);

	$stmt = $connection->prepare("INSERT INTO `orders_list` 
	    (`userid`, `token`, `transid`, `fileid`, `server_id`, `inbound_id`, `remark`, `protocol`, `expire_date`, `link`, `amount`, `status`, `date`, `notif`, `rahgozar`)
	    VALUES (?, ?, '', ?, ?, ?, ?, ?, ?, ?, ?,1, ?, 0, ?);");
    $stmt->bind_param("ssiiissisiii", $uid, $token, $fid, $server_id, $inbound_id, $remark, $protocol, $expire_date, $vray_link, $price, $date, $rahgozar);
    $stmt->execute();
    $order = $stmt->get_result(); 
    $stmt->close();
    $keys = json_encode(['inline_keyboard'=>[
        [
            ['text'=>"بنازم خرید جدید ❤️",'callback_data'=>"wizwizch"]
        ],
        ]]);
    $msg = str_replace(['TYPE', 'USER-ID', 'USERNAME', 'NAME', 'PRICE', 'REMARK', 'VOLUME', 'DAYS'],
                ['کیف پول', $from_id, $username, $first_name, $price, $remark,$volume, $days], $mainValues['buy_custom_account_request']);
    sendMessage($msg,$keys,"html", $admin);
}
if(preg_match('/payCustomWithCartToCart(.*)/',$data, $match)) {
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]);
    $stmt->execute();
    $payInfo = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    $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'];
    $inbound_id = $file_detail['inbound_id'];


    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 && $acount <= 0){
            sendMessage(str_replace("AMOUNT", $acount, $mainValues['can_create_specific_account']));
            exit();
        }
    }
    
    $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'PAYMENT_KEYS'");
    $stmt->execute();
    $paymentKeys = $stmt->get_result()->fetch_assoc()['value'];
    if(!is_null($paymentKeys)) $paymentKeys = json_decode($paymentKeys,true);
    else $paymentKeys = array();
    $stmt->close();

    
    setUser($data);
    delMessage();
    sendMessage(str_replace(["ACCOUNT-NUMBER", "HOLDER-NAME"],[$paymentKeys['bankAccount'],$paymentKeys['holderName']], $mainValues['buy_account_cart_to_cart']),$cancelKey, "HTML");
    exit;
}
if(preg_match('/payCustomWithCartToCart(.*)/',$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()->fetch_assoc();
        $stmt->close();
        
        $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'sent' WHERE `hash_id` = ?");
        $stmt->bind_param("s", $match[1]);
        $stmt->execute();
        $stmt->execute();
        
        $fid = $payInfo['plan_id'];
        $volume = $payInfo['volume'];
        $days = $payInfo['day'];
        
        setUser();
        $uid = $userInfo['userid'];
        $name = $userInfo['name'];
        $username = $userInfo['username'];
    
        $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 * FROM `server_categories` WHERE `id`=?");
        $stmt->bind_param("i", $res['catid']);
        $stmt->execute();
        $catname = $stmt->get_result()->fetch_assoc()['title'];
        $stmt->close();
        $filename = $catname." ".$res['title']; 
        $fileprice = $payInfo['price'];
    
        sendMessage($mainValues['order_buy_sent'],$removeKeyboard);
        sendMessage($mainValues['reached_main_menu'],getMainKeys());
    
        $msg = str_replace(['TYPE', 'USER-ID', 'USERNAME', 'NAME', 'PRICE', 'REMARK', 'VOLUME', 'DAYS'],
                            ["کارت به کارت", $from_id, $username, $first_name, $fileprice, $remark,$volume, $days], $mainValues['buy_custom_account_request']);
        $keyboard = json_encode([
            'inline_keyboard' => [
                [
                    ['text' => $buttonValues['approve'], 'callback_data' => "accCustom" . $match[1]],
                    ['text' => $buttonValues['decline'], 'callback_data' => "decline$uid"]
                ]
            ]
        ]);
        sendPhoto($fileid, $msg,$keyboard, "HTML", $admin);
    }else{
        sendMessage($mainValues['please_send_only_image']);
    }
}
if(preg_match('/accCustom(.*)/',$data, $match) and $text != $buttonValues['cancel']){
    setUser();

    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]);
    $stmt->execute();
    $payInfo = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'approved' WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]);
    $stmt->execute();
    $stmt->close();
    
    $fid = $payInfo['plan_id'];
    $volume = $payInfo['volume'];
    $days = $payInfo['day'];
    $uid = $payInfo['user_id'];

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

    $date = time();
    $expire_microdate = floor(microtime(true) * 1000) + (864000 * $days * 100);
    $expire_date = $date + (86400 * $days);
    $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'];

    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) {
            $stmt = $connection->prepare("UPDATE `server_info` SET `ucount` = `ucount` - 1 WHERE `id`=?");
            $stmt->bind_param("i", $server_id);
            $stmt->execute();
            $stmt->close();

        } else {
            alert($mainValues['out_of_server_capacity']);
            exit;
        }
    }else{
        if($acount != 0) {
            $stmt = $connection->prepare("UPDATE `server_plans` SET `acount` = `acount` - 1 WHERE id=?");
            $stmt->bind_param("i", $fid);
            $stmt->execute();
            $stmt->close();
        }
    }

    $uniqid = generateRandomString(42,$protocol); 

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

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

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

    // $rnd = rand(1111,99999);
    // $remark = "{$srv_remark}-{$uid}-{$rnd}";
    $remark = $payInfo['description'];
    
    if($portType == "auto"){
        file_put_contents('settings/temp.txt',$port.'-'.$last_num);
    }else{
        $port = rand(1111,65000);
    }
    
    if($inbound_id == 0){    
        $response = addUser($server_id, $uniqid, $protocol, $port, $expire_microdate, $remark, $volume, $netType, 'none', $rahgozar, $fid); 
        if(! $response->success){
            $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){
            $response = addInboundAccount($server_id, $uniqid, $inbound_id, $expire_microdate, $remark, $volume, $limitip, null, $fid);
        } 
    }
    
    if(is_null($response)){
        alert('❌ | 🥺 گلم ، اتصال به سرور برقرار نیست لطفا مدیر رو در جریان بزار ...');
        exit;
    }
	if($response == "inbound not Found"){
        alert("❌ | 🥺 سطر (inbound) با آیدی $inbound_id تو این سرور وجود نداره ، مدیر رو در جریان بزار ...");
		exit;
	}
	if(!$response->success){
        alert('❌ | 😮 وای خطا داد لطفا سریع به مدیر بگو ...');
        exit;
    }
    alert('🚀 | 😍 در حال ارسال کانفیگ به مشتری ...');
    
    include 'phpqrcode/qrlib.php';
    $token = RandomString(30);
    $subLink = $botState['subLinkState']=="on"?$botUrl . "settings/subLink.php?token=" . $token:"";

    $vraylink = getConnectionLink($server_id, $uniqid, $protocol, $remark, $port, $netType, $inbound_id);
    foreach($vraylink as $vray_link){
        $acc_text = "
😍 سفارش جدید شما
📡 پروتکل: $protocol
🔮 نام سرویس: $remark
🔋حجم سرویس: $volume گیگ
⏰ مدت سرویس: $days روز
⁮⁮ ⁮⁮
💝 config : <code>$vray_link</code>";
if($botState['subLinkState'] == "on") $acc_text .= "

\n🌐 subscription : <code>$subLink</code>";
    
        $file = RandomString() .".png";
        $ecc = 'L';
        $pixel_Size = 10;
        $frame_Size = 10;
    
        QRcode::png($vray_link, $file, $ecc, $pixel_Size, $frame_Size);
    	addBorderImage($file);
    	sendPhoto($botUrl . $file, $acc_text,json_encode(['inline_keyboard'=>[[['text'=>"صفحه اصلی 🏘",'callback_data'=>"mainMenu"]]]]),"HTML", $uid);
        unlink($file);
    }
    sendMessage('✅ کانفیگ و براش ارسال کردم', getMainKeys());
    
    $vray_link= json_encode($vraylink);
	$stmt = $connection->prepare("INSERT INTO `orders_list` 
	    (`userid`, `token`, `transid`, `fileid`, `server_id`, `inbound_id`, `remark`, `protocol`, `expire_date`, `link`, `amount`, `status`, `date`, `notif`, `rahgozar`)
	    VALUES (?, ?, '', ?, ?, ?, ?, ?, ?, ?, ?,1, ?, 0, ?);");
    $stmt->bind_param("ssiiissisiii", $uid, $token, $fid, $server_id, $inbound_id, $remark, $protocol, $expire_date, $vray_link, $price, $date, $rahgozar);
    $stmt->execute();
    $order = $stmt->get_result();
    $stmt->close();


    unset($markup[count($markup)-1]);
    $markup[] = [['text'=>"✅",'callback_data'=>"wizwizch"]];
    $keys = json_encode(['inline_keyboard'=>array_values($markup)],488);


    editKeys($keys);
    
    $filename = $file_detail['title'];
    $fileprice = number_format($file_detail['price']);
    $stmt = $connection->prepare("SELECT * FROM `users` WHERE `userid`=?");
    $stmt->bind_param("i", $uid);
    $stmt->execute();
    $user_detail= $stmt->get_result()->fetch_assoc();
    $stmt->close();


    if($user_detail['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 = $user_detail['refered_by'];
        
        $stmt = $connection->prepare("UPDATE `users` SET `wallet` = `wallet` + ? WHERE `userid` = ?");
        $stmt->bind_param("ii", $inviteAmount, $inviterId);
        $stmt->execute();
        $stmt->close();
         
        sendMessage("تبریک یکی از زیر مجموعه های شما خرید انجام داد شما مبلغ " . number_format($inviteAmount) . " تومان جایزه دریافت کردید",null,null,$inviterId);
    }


    $uname = $user_detail['name'];
    $user_name = $user_detail['username'];
    
    if($admin != $from_id){ 
        $keys = json_encode(['inline_keyboard'=>[
            [
                ['text'=>"به به 🛍",'callback_data'=>"wizwizch"]
            ],
            ]]);
        $msg = str_replace(['USER-ID', 'USERNAME', 'NAME', 'PRICE', 'REMARK', 'FILENAME'],
            [$uid, $user_name, $uname, $price, $remark,$filename], $mainValues['invite_buy_new_account']);
        sendMessage($msg,null,null,$admin);
    }
    
}
if(preg_match('/payWithWallet(.*)/',$data, $match)){
    setUser();

    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]);
    $stmt->execute();
    $payInfo = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    
    $uid = $from_id;
    $fid = $payInfo['plan_id'];
    $acctxt = '';
    
    
    $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();

    $days = $file_detail['days'];
    $date = time();
    $expire_microdate = floor(microtime(true) * 1000) + (864000 * $days * 100);
    $expire_date = $date + (86400 * $days);
    $type = $file_detail['type'];
    $volume = $file_detail['volume'];
    $protocol = $file_detail['protocol'];
    $rahgozar = $file_detail['rahgozar'];
    $customPath = $file_detail['custom_path'];
    $price = $payInfo['price'];
    $customPort = $file_detail['custom_port'];
    $customSni = $file_detail['custom_sni'];
    
    if($userInfo['wallet'] < $price){
        alert("موجودی حساب شما کم است");
        exit();
    }

    
    
    $server_id = $file_detail['server_id'];
    $netType = $file_detail['type'];
    $acount = $file_detail['acount'];
    $inbound_id = $file_detail['inbound_id'];
    $limitip = $file_detail['limitip'];


    if($payInfo['type'] == "RENEW_SCONFIG"){
        $remark = $payInfo['description'];
        $inbound_id = $payInfo['volume']; 
        
        if($inbound_id > 0)
            $response = editClientTraffic($server_id, $inbound_id, $remark, $volume, $days, "renew");
        else
            $response = editInboundTraffic($server_id, $remark, $volume, $days, "renew");
        
    	if(is_null($response)){
    		alert('🔻مشکل فنی در اتصال به سرور. لطفا به مدیریت اطلاع بدید',true);
    		exit;
    	}
    	$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();
        $keys = json_encode(['inline_keyboard'=>[
            [
                ['text'=>$buttonValues['back_to_main'],'callback_data'=>"mainMenu"]
            ],
            ]]);
        editText($message_id,"✅سرویس $remark با موفقیت تمدید شد",$keys);
    }else{
        $accountCount = $payInfo['agent_count']!=0?$payInfo['agent_count']:1;
        
        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) {
                $stmt = $connection->prepare("UPDATE `server_info` SET `ucount` = `ucount` - ? WHERE `id`=?");
                $stmt->bind_param("ii", $accountCount, $server_id);
                $stmt->execute();
                $stmt->close();
    
            } else {
                alert($mainValues['out_of_server_capacity']);
                exit;
            }
        }else{
        
            if($acount != 0) {
                $stmt = $connection->prepare("UPDATE `server_plans` SET `acount` = `acount` - ? WHERE id=?");
                $stmt->bind_param("ii", $accountCount, $fid);
                $stmt->execute();
                $stmt->close();
            }
        }
    
        $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'approved' WHERE `hash_id` = ?");
        $stmt->bind_param("s", $match[1]);
        $stmt->execute();
        $stmt->close();

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

        include 'phpqrcode/qrlib.php';
        delMessage();

        $agent_bought = false;
	    $eachPrice = $price / $accountCount;
        if($userInfo['is_agent'] == true && ($userInfo['temp'] == "agentBuy" || $userInfo['temp'] == "agentMuchBuy")) {$agent_bought = true; setUser('', 'temp');}

        alert('🚀 | 😍 در حال ارسال کانفیگ به مشتری ...');
        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}";
            }else{
                $rnd = rand(1111,99999);
                $remark = "{$srv_remark}-{$from_id}-{$rnd}";
            }
        
            if($portType == "auto"){
                file_put_contents('settings/temp.txt',$port.'-'.$last_num);
            }else{
                $port = rand(1111,65000);
            }
        
            if($inbound_id == 0){    
                $response = addUser($server_id, $uniqid, $protocol, $port, $expire_microdate, $remark, $volume, $netType, 'none', $rahgozar, $fid); 
                if(! $response->success){
                    $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){
                    $response = addInboundAccount($server_id, $uniqid, $inbound_id, $expire_microdate, $remark, $volume, $limitip, null, $fid);
                } 
            }
        
            if(is_null($response)){
                alert('❌ | 🥺 گلم ، اتصال به سرور برقرار نیست لطفا مدیر رو در جریان بزار ...');
                exit;
            }
        	if($response == "inbound not Found"){
                alert("❌ | 🥺 سطر (inbound) با آیدی $inbound_id تو این سرور وجود نداره ، مدیر رو در جریان بزار ...");
        		exit;
        	}
        	if(!$response->success){
                alert('❌ | 😮 وای خطا داد لطفا سریع به مدیر بگو ...');
                exit;
            }
        
        
            $token = RandomString(30);
            $subLink = $botState['subLinkState']=="on"?$botUrl . "settings/subLink.php?token=" . $token:"";

            $vraylink = getConnectionLink($server_id, $uniqid, $protocol, $remark, $port, $netType, $inbound_id, $rahgozar, $customPath, $customPort, $customSni);
            foreach($vraylink as $vray_link){
                $acc_text = "
        😍 سفارش جدید شما
        📡 پروتکل: $protocol
        🔮 نام سرویس: $remark
        🔋حجم سرویس: $volume گیگ
        ⏰ مدت سرویس: $days روز
        ⁮⁮ ⁮⁮
        💝 config : <code>$vray_link</code>";
        if($botState['subLinkState'] == "on") $acc_text .= "
        
        \n🌐 subscription : <code>$subLink</code>";
            
                $file = RandomString() .".png";
                $ecc = 'L';
                $pixel_Size = 10;
                $frame_Size = 10;
                
                QRcode::png($vray_link, $file, $ecc, $pixel_Size, $frame_Size);
            	addBorderImage($file);
            	sendPhoto($botUrl . $file, $acc_text,json_encode(['inline_keyboard'=>[[['text'=>"صفحه اصلی 🏘",'callback_data'=>"mainMenu"]]]]),"HTML", $uid);
                unlink($file);
            }
    
            $vray_link= json_encode($vraylink);
            
        	$stmt = $connection->prepare("INSERT INTO `orders_list` 
        	    (`userid`, `token`, `transid`, `fileid`, `server_id`, `inbound_id`, `remark`, `protocol`, `expire_date`, `link`, `amount`, `status`, `date`, `notif`, `rahgozar`, `agent_bought`)
        	    VALUES (?, ?, '', ?, ?, ?, ?, ?, ?, ?, ?,1, ?, 0, ?, ?);");
            $stmt->bind_param("ssiiissisiiii", $uid, $token, $fid, $server_id, $inbound_id, $remark, $protocol, $expire_date, $vray_link, $eachPrice, $date, $rahgozar, $agent_bought);
            $stmt->execute();
            $order = $stmt->get_result(); 
            $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);
        }
        
    }
    $stmt = $connection->prepare("UPDATE `users` SET `wallet` = `wallet` - ? WHERE `userid` = ?");
    $stmt->bind_param("ii", $price, $uid);
    $stmt->execute();
    $stmt->close();
    
    $keys = json_encode(['inline_keyboard'=>[
        [
            ['text'=>"بنازم خرید جدید ❤️",'callback_data'=>"wizwizch"]
        ],
        ]]);
    if($payInfo['type'] == "RENEW_SCONFIG"){$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']);}
    else{$msg = str_replace(['TYPE', 'USER-ID', 'USERNAME', 'NAME', 'PRICE', 'REMARK', 'VOLUME', 'DAYS'],
                ['کیف پول', $from_id, $username, $first_name, $price, $remark,$volume, $days], $mainValues['buy_custom_account_request']);}

    sendMessage($msg,$keys,"html", $admin);
}
if(preg_match('/payWithCartToCart(.*)/',$data,$match)) {
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]);
    $stmt->execute();
    $payInfo = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    $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'];
    $inbound_id = $file_detail['inbound_id'];

    if($payInfo['type'] != "RENEW_SCONFIG"){
        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 && $acount < $text){
                alert(str_replace("AMOUNT", $acount, $mainValues['can_create_specific_account']));
                exit();
            }
        }
    }
    
    
    $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'PAYMENT_KEYS'");
    $stmt->execute();
    $paymentKeys = $stmt->get_result()->fetch_assoc()['value'];
    if(!is_null($paymentKeys)) $paymentKeys = json_decode($paymentKeys,true);
    else $paymentKeys = array();
    $stmt->close();

    
    setUser($data);
    delMessage();
    sendMessage(str_replace(["ACCOUNT-NUMBER", "HOLDER-NAME"],[$paymentKeys['bankAccount'],$paymentKeys['holderName']], $mainValues['buy_account_cart_to_cart']),$cancelKey, "HTML");
    exit;
}
if(preg_match('/payWithCartToCart(.*)/',$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()->fetch_assoc();
        $stmt->close();
        
        $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'approved' WHERE `hash_id` = ?");
        $stmt->bind_param("s", $match[1]);
        $stmt->execute();
        $stmt->close();
    
        
    $fid = $payInfo['plan_id'];
    setUser();
    $uid = $userInfo['userid'];
    $name = $userInfo['name'];
    $username = $userInfo['username'];

    // بررسی اینکه آیا این یک پلن VIP است
    $isVipPlan = ($payInfo['type'] == 'VIP_PLAN');
    
    if($isVipPlan) {
        // برای پلن VIP از description استفاده می‌کنیم
        $filename = $payInfo['description'];
    } else {
        $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `id`=?");
        $stmt->bind_param("i", $fid);
        $stmt->execute();
        $res = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if($payInfo['type'] == "RENEW_SCONFIG"){
            $filename = $payInfo['description'];
        }else{
            $stmt = $connection->prepare("SELECT * FROM `server_categories` WHERE `id`=?");
            $stmt->bind_param("i", $res['catid']);
            $stmt->execute();
            $catname = $stmt->get_result()->fetch_assoc()['title'];
            $stmt->close();
            $filename = $catname." ".$res['title']; 
        }
    }
    
    $fileprice = $payInfo['price'];

    sendMessage($mainValues['order_buy_sent'],$removeKeyboard);
    sendMessage($mainValues['reached_main_menu'],getMainKeys());

    if($payInfo['agent_count'] != 0) $msg = str_replace(['ACCOUNT-COUNT', 'TYPE', 'USER-ID', "USERNAME", "NAME", "PRICE", "REMARK"],[$payInfo['agent_count'], 'کارت به کارت', $from_id, $username, $name, $fileprice, $filename], $mainValues['buy_new_much_account_request']);
    else $msg = str_replace(['TYPE', 'USER-ID', "USERNAME", "NAME", "PRICE", "REMARK"],['کارت به کارت', $from_id, $username, $name, $fileprice, $filename], $mainValues['buy_new_account_request']);        if($isVipPlan) {
            // کیبورد با دکمه تایید و ارسال اتوماتیک برای پلن‌های VIP
            $keyboard = json_encode([
                'inline_keyboard' => [
                    [
                        ['text' => '✅ تایید و ارسال اتوماتیک', 'callback_data' => "acceptAuto" . $match[1]]
                    ],
                    [
                        ['text' => $buttonValues['approve'], 'callback_data' => "accept" . $match[1]],
                        ['text' => $buttonValues['decline'], 'callback_data' => "decline$uid"]
                    ]
                ]
            ]);
        } else {
            // کیبورد معمولی برای پلن‌های غیر VIP
            $keyboard = json_encode([
                'inline_keyboard' => [
                    [
                        ['text' => $buttonValues['approve'], 'callback_data' => "accept" . $match[1]],
                        ['text' => $buttonValues['decline'], 'callback_data' => "decline$uid"]
                    ]
                ]
            ]);
        }
        setUser('', 'temp');
        $res = sendPhoto($fileid, $msg,$keyboard, "HTML", $admin);
    }else{
        sendMessage($mainValues['please_send_only_image']);
    }
}
if($data=="agencySettings" && $userInfo['is_agent'] == 1){
    editText($message_id, $mainValues['agent_setting_message'] ,getAgentKeys());
}
if($data=="requestAgency"){
    if($userInfo['is_agent'] == 2){
        alert($mainValues['agency_request_already_sent']);
    }elseif($userInfo['is_agent'] == 0){
        $msg = str_replace(["USERNAME", "NAME", "USERID"], [$username, $first_name, $from_id], $mainValues['request_agency_message']);
        sendMessage($msg, json_encode(['inline_keyboard'=>[
            [
                ['text' => $buttonValues['approve'], 'callback_data' => "agencyApprove" . $from_id ],
                ['text' => $buttonValues['decline'], 'callback_data' => "agencyDecline" . $from_id]
            ]
            ]]), null, $admin);
        setUser(2, 'is_agent');
        alert($mainValues['agency_request_sent']);
    }elseif($userInfo['is_agent'] == -1) alert($mainValues['agency_request_declined']);
    elseif($userInfo['is_agent'] == 1) editText($message_id,"لطفا یکی از کلید های زیر را انتخاب کنید",getMainKeys());
}
if(preg_match('/^agencyDecline(\d+)/',$data,$match) && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    editKeys(json_encode(['inline_keyboard'=>[
        [['text'=>$buttonValues['declined'],'callback_data'=>"wizwizch"]]
        ]]));
    sendMessage($mainValues['agency_request_declined'], null,null,$match[1]);
    setUser(-1, 'is_agent', $match[1]);
}
if(preg_match('/^agencyApprove(\d+)/',$data,$match) && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    setUser($data . "_" . $message_id);
    sendMessage($mainValues['send_agent_discount_percent'], $cancelKey);
}
if(preg_match('/^agencyApprove(\d+)_(\d+)/',$userInfo['step'],$match) && $text != $buttonValues['cancel'] && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    if(is_numeric($text)){
        editKeys(json_encode(['inline_keyboard'=>[
            [['text'=>$buttonValues['approved'],'callback_data'=>"wizwizch"]]
            ]]), $match[2]);
        sendMessage($mainValues['saved_successfuly']);
        setUser();
        $stmt = $connection->prepare("UPDATE `users` SET `is_agent` = 1, `discount_percent` = ?, `agent_date` = ? WHERE `userid` = ?");
        $stmt->bind_param("iii", $text, $time, $match[1]);
        $stmt->execute();
        $stmt->close();
        sendMessage($mainValues['agency_request_approved'], null,null,$match[1]);
    }else sendMessage($mainValues['send_only_number']);
}

// Handler تایید و ارسال اتوماتیک برای پلن‌های VIP
if(preg_match('/acceptAuto(.*)/',$data, $match) and $text != $buttonValues['cancel']){
    require_once 'auto_account_creator.php';
    
    setUser();
    
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]);
    $stmt->execute();
    $payInfo = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    // بررسی که پرداخت قبلا تایید نشده باشه
    if($payInfo['state'] == 'approved') {
        alert('⚠️ این پرداخت قبلاً تایید شده است!', true);
        exit;
    }
    
    // بررسی که این یک پلن VIP باشه
    if($payInfo['type'] != 'VIP_PLAN') {
        alert('⚠️ این پرداخت برای پلن VIP نیست! از دکمه تایید معمولی استفاده کنید.', true);
        exit;
    }
    
    $uid = $payInfo['user_id'];
    $plan_id = $payInfo['plan_id'];
    $hash_id = $match[1];
    
    // تغییر وضعیت پرداخت به تایید شده
    $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'approved' WHERE `hash_id` = ?");
    $stmt->bind_param("s", $hash_id);
    $stmt->execute();
    $stmt->close();
    
    // ارسال پیام انتظار
    sendMessage("⏳ در حال ساخت اکانت VIP...", null, null, $admin);
    
    // ساخت اکانت
    $result = createVIPAccount($uid, $plan_id, $hash_id);
    
    if($result['success']) {
        // ارسال اکانت به کاربر
        $account_message = formatAccountMessage($result);
        sendMessage($account_message, null, "HTML", $uid);
        
        // اطلاع به ادمین
        editKeys(json_encode(['inline_keyboard'=>[
            [['text'=>'✅ تایید شد و اکانت ارسال شد','callback_data'=>"wizwizch"]]
        ]]), $message_id);
        
        sendMessage("✅ اکانت با موفقیت ساخته شد و به کاربر ارسال شد!\n\n📧 نام اکانت: <code>{$result['account']['email']}</code>", null, "HTML", $admin);
        
        // افزودن کیف پول کاربر
        $price = $payInfo['price'];
        $stmt = $connection->prepare("UPDATE `users` SET `wallet` = `wallet` + ? WHERE `userid` = ?");
        $stmt->bind_param("ii", $price, $uid);
        $stmt->execute();
        $stmt->close();
        
    } else {
        // خطا در ساخت اکانت
        alert($result['message'], true);
        sendMessage("❌ خطا در ساخت اکانت!\n\n" . $result['message'], null, null, $admin);
        
        // برگردوندن وضعیت پرداخت
        $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'pending' WHERE `hash_id` = ?");
        $stmt->bind_param("s", $hash_id);
        $stmt->execute();
        $stmt->close();
    }
}

// تایید دستی پرداخت (برای VIP پلن‌ها)
if(preg_match('/accept(.*)/',$data, $match) and $text != $buttonValues['cancel']){
    setUser();
    
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]);
    $stmt->execute();
    $payInfo = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    // اگر پلن VIP بود، handler جداگانه
    if($payInfo['type'] == 'VIP_PLAN'){
        $hash_id = $match[1];
        $user_id = $payInfo['user_id'];
        
        // تغییر وضعیت به تایید شده
        $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'approved' WHERE `hash_id` = ?");
        $stmt->bind_param("s", $hash_id);
        $stmt->execute();
        $stmt->close();
        
        // حذف پیام قبلی
        delMessage();
        
        // تنظیم step برای دریافت لینک دستی
        $stmt = $connection->prepare("UPDATE `users` SET `step` = ? WHERE `userid` = ?");
        $step_value = "sendVipConfigManual_{$hash_id}";
        $stmt->bind_param("si", $step_value, $from_id);
        $stmt->execute();
        $stmt->close();
        
        $price_formatted = number_format($payInfo['price']);
        $volume = $payInfo['volume'] > 0 ? "{$payInfo['volume']} گیگ" : "نامحدود";
        $days = $payInfo['day'];
        
        $guide_message = "✅ سفارش تایید شد!

📋 اطلاعات سفارش:
👤 کاربر: {$user_id}
🔋 حجم: {$volume}
⏰ مدت: {$days} روز
💰 مبلغ: {$price_formatted} تومان

━━━━━━━━━━━━━━━━━━━━━━
📝 حالا لینک اشتراک (Subscription Link) را ارسال کنید:

📌 مثال صحیح:
<code>http://apn.lotfischool.ir:2096/sub/APN-pro/rnhopbe5mnbyr2f8</code>

یا لینک کانفیگ تکی:
<code>vless://abc123...</code>

⚠️ فقط لینک را بفرستید، بدون متن اضافه!
━━━━━━━━━━━━━━━━━━━━━━

پس از ارسال:
✅ لینک برای کاربر ارسال می‌شود
✅ به 'سرویس‌های من' کاربر اضافه می‌شود
✅ تاریخ انقضا محاسبه می‌شود";
        
        sendMessage($guide_message, $cancelKey, 'html', $from_id);
        exit;
    }
    
    // برای پلن‌های معمولی (غیر VIP) ادامه بده
    $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'approved' WHERE `hash_id` = ?");
    $stmt->bind_param("s", $match[1]);
    $stmt->execute();
    $stmt->close();

    $uid = $payInfo['user_id'];
    $fid = $payInfo['plan_id'];
    $acctxt = '';
    
    
    $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();

    $days = $file_detail['days'];
    $date = time();
    $expire_microdate = floor(microtime(true) * 1000) + (864000 * $days * 100);
    $expire_date = $date + (86400 * $days);
    $type = $file_detail['type'];
    $volume = $file_detail['volume'];
    $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'];

    
    if($payInfo['type'] == "RENEW_SCONFIG"){
        $remark = $payInfo['description'];
        $inbound_id = $payInfo['volume']; 
        
        if($inbound_id > 0)
            $response = editClientTraffic($server_id, $inbound_id, $remark, $volume, $days, "renew");
        else
            $response = editInboundTraffic($server_id, $remark, $volume, $days, "renew");
        
    	if(is_null($response)){
    		alert('🔻مشکل فنی در اتصال به سرور. لطفا به مدیریت اطلاع بدید',true);
    		exit;
    	}
    	$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 با موفقیت تمدید شد",null,null,$uid);
    }else{
        $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) {
                $stmt = $connection->prepare("UPDATE `server_info` SET `ucount` = `ucount` - ? WHERE `id`=?");
                $stmt->bind_param("ii", $accountCount, $server_id);
                $stmt->execute();
                $stmt->close();
    
            } else {
                alert($mainValues['out_of_server_capacity']);
                exit;
            }
        }else{
            if($acount != 0) {
                $stmt = $connection->prepare("UPDATE `server_plans` SET `acount` = `acount` - ? WHERE id=?");
                $stmt->bind_param("ii", $accountCount, $fid);
                $stmt->execute();
                $stmt->close();
            }
        }
        
        $stmt = $connection->prepare("SELECT * FROM `server_info` WHERE `id`=?");
        $stmt->bind_param("i", $server_id);
        $stmt->execute();
        $srv_remark = $stmt->get_result()->fetch_assoc()['remark'];
        $stmt->close();
    
        $stmt = $connection->prepare("SELECT * FROM `server_config` WHERE `id`=?");
        $stmt->bind_param("i", $server_id);
        $stmt->execute();
        $portType = $stmt->get_result()->fetch_assoc()['port_type'];
        $stmt->close();
    
    
        alert('🚀 | 😍 در حال ارسال کانفیگ به مشتری ...');
        include 'phpqrcode/qrlib.php';
        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}";
            }else{
                $rnd = rand(1111,99999);
                $remark = "{$srv_remark}-{$uid}-{$rnd}";
            }
        
            if($portType == "auto"){
                file_put_contents('settings/temp.txt',$port.'-'.$last_num);
            }else{
                $port = rand(1111,65000);
            }
        
            if($inbound_id == 0){    
                $response = addUser($server_id, $uniqid, $protocol, $port, $expire_microdate, $remark, $volume, $netType, 'none', $rahgozar, $fid); 
                if(! $response->success){
                    $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){
                    $response = addInboundAccount($server_id, $uniqid, $inbound_id, $expire_microdate, $remark, $volume, $limitip, null, $fid);
                } 
            }
            if(is_null($response)){
                alert('❌ | 🥺 گلم ، اتصال به سرور برقرار نیست لطفا مدیر رو در جریان بزار ...');
                exit;
            }
        	if($response == "inbound not Found"){
                alert("❌ | 🥺 سطر (inbound) با آیدی $inbound_id تو این سرور وجود نداره ، مدیر رو در جریان بزار ...");
        		exit;
        	}
        	if(!$response->success){
                alert('❌ | 😮 وای خطا داد لطفا سریع به مدیر بگو ...');
                exit;
            }
                
            $token = RandomString(30);
            $subLink = $botState['subLinkState']=="on"?$botUrl . "settings/subLink.php?token=" . $token:"";
    
            $vraylink = getConnectionLink($server_id, $uniqid, $protocol, $remark, $port, $netType, $inbound_id, $rahgozar, $customPath, $customPort, $customSni);
            foreach($vraylink as $vray_link){
                $acc_text = "
        😍 سفارش جدید شما
        📡 پروتکل: $protocol
        🔮 نام سرویس: $remark
        🔋حجم سرویس: $volume گیگ
        ⏰ مدت سرویس: $days روز
        ⁮⁮ ⁮⁮
        💝 config : <code>$vray_link</code>";
        if($botState['subLinkState'] == "on") $acc_text .= "
        
        \n🌐 subscription : <code>$subLink</code>";
            
                $file = RandomString() .".png";
                $ecc = 'L';
                $pixel_Size = 10;
                $frame_Size = 10;
            
                QRcode::png($vray_link, $file, $ecc, $pixel_Size, $frame_Size);
            	addBorderImage($file);
            	sendPhoto($botUrl . $file, $acc_text,json_encode(['inline_keyboard'=>[[['text'=>"صفحه اصلی 🏘",'callback_data'=>"mainMenu"]]]]),"HTML", $uid);
                unlink($file);
            }
            $agent_bought = $payInfo['agent_bought'];
    
            $vray_link = json_encode($vraylink);
        	$stmt = $connection->prepare("INSERT INTO `orders_list` 
        	    (`userid`, `token`, `transid`, `fileid`, `server_id`, `inbound_id`, `remark`, `protocol`, `expire_date`, `link`, `amount`, `status`, `date`, `notif`, `rahgozar`, `agent_bought`)
        	    VALUES (?, ?, '', ?, ?, ?, ?, ?, ?, ?, ?,1, ?, 0, ?, ?);");
            $stmt->bind_param("ssiiissisiiii", $uid, $token, $fid, $server_id, $inbound_id, $remark, $protocol, $expire_date, $vray_link, $eachPrice, $date, $rahgozar, $agent_bought);
            $stmt->execute();
            $order = $stmt->get_result();
            $stmt->close();
        }
        sendMessage('✅ کانفیگ و براش ارسال کردم', getMainKeys());
        
    }

    unset($markup[count($markup)-1]);
    $markup[] = [['text'=>"✅",'callback_data'=>"wizwizch"]];
    $keys = json_encode(['inline_keyboard'=>array_values($markup)],488);

    editKeys($keys);
    if($payInfo['type'] != "RENEW_SCONFIG"){
        $filename = $file_detail['title'];
        $fileprice = number_format($file_detail['price']);
        $stmt = $connection->prepare("SELECT * FROM `users` WHERE `userid`=?");
        $stmt->bind_param("i", $uid);
        $stmt->execute();
        $user_detail= $stmt->get_result()->fetch_assoc();
        $stmt->close();
    
        if($user_detail['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 = $user_detail['refered_by'];
            
            $stmt = $connection->prepare("UPDATE `users` SET `wallet` = `wallet` + ? WHERE `userid` = ?");
            $stmt->bind_param("ii", $inviteAmount, $inviterId);
            $stmt->execute();
            $stmt->close();
             
            sendMessage("تبریک یکی از زیر مجموعه های شما خرید انجام داد شما مبلغ " . number_format($inviteAmount) . " تومان جایزه دریافت کردید",null,null,$inviterId);
        }
    
    
        $uname = $user_detail['name'];
        $user_name = $user_detail['username'];
        
        if($admin != $from_id){
            $keys = json_encode(['inline_keyboard'=>[
                [
                    ['text'=>"به به 🛍",'callback_data'=>"wizwizch"]
                ],
                ]]);
                
        $msg = str_replace(['USER-ID', 'USERNAME', 'NAME', 'PRICE', 'REMARK', 'FILENAME'],
                    [$uid, $user_name, $uname, $price, $remark,$filename], $mainValues['invite_buy_new_account']);
            
            sendMessage($msg,null,null,$admin);
        }
    }
}
if(preg_match('/decline/',$data) and ($from_id == $admin || $userInfo['isAdmin'] == true)){
    setUser($data . "_" . $message_id);
    sendMessage('دلیلت از عدم تایید چیه؟ ( بفرس براش ) 😔 ',$cancelKey);
}
if(preg_match('/decline(\d+)_(\d+)/',$userInfo['step'],$match) and $text != $buttonValues['cancel']){
    setUser();
    $uid = $match[1];
    editKeys(
        json_encode(['inline_keyboard'=>[
	    [['text'=>"لغو شد ❌",'callback_data'=>"wizwizch"]]
	    ]]) ,$match[2]);

    sendMessage('پیامت رو براش ارسال کردم ... 🤝',$removeKeyboard);
    sendMessage($mainValues['reached_main_menu'],getMainKeys());
    
    sendMessage($text, null, null, $uid);
}
if($data=="supportSection"){
    delMessage();
    sendMessage("به بخش پشتیبانی خوش اومدی🛂\nلطفا، یکی از دکمه های زیر را انتخاب نمایید.",
        json_encode(['inline_keyboard'=>[
        [['text'=>"✉️ ثبت تیکت",'callback_data'=>"usersNewTicket"]],
        [['text'=>"تیکت های باز 📨",'callback_data'=>"usersOpenTickets"],['text'=>"📮 لیست تیکت ها", 'callback_data'=>"userAllTickets"]],
        [['text'=>$buttonValues['back_button'],'callback_data'=>"mainMenu"]]
        ]]));
}
if($data== "usersNewTicket"){
    $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'TICKETS_CATEGORY'");
    $stmt->execute();
    $ticketCategory = $stmt->get_result();
    $stmt->close();
    $keys = array();
    $temp = array();
    if($ticketCategory->num_rows >0){
        while($row = $ticketCategory->fetch_assoc()){
            $ticketName = $row['value'];
            $temp[] = ['text'=>$ticketName,'callback_data'=>"supportCat$ticketName"];
            
            if(count($temp) == 2){
                array_push($keys,$temp);
                $temp = null;
            }
        }
        
        if($temp != null){
            if(count($temp)>0){
                array_push($keys,$temp);
                $temp = null;
            }
        }
        $temp[] = ['text'=>$buttonValues['back_button'],'callback_data'=>"supportSection"];
        array_push($keys,$temp);
        delMessage();
        sendMessage("💠لطفا واحد مورد نظر خود را انتخاب نمایید!",json_encode(['inline_keyboard'=>$keys]));
    }else{
        alert("ای وای، ببخشید الان نیستم");
    }
}
if($data == 'dayPlanSettings' and ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $stmt = $connection->prepare("SELECT * FROM `increase_day`");
    $stmt->execute();
    $res = $stmt->get_result();
    $stmt->close();

    if($res->num_rows == 0){
       editText($message_id, 'لیست پلن های زمانی خالی است ',json_encode([
                'inline_keyboard' => [
                    [['text' => "افزودن پلن زمانی جدید", 'callback_data' =>"addNewDayPlan"]],
                    [['text'=>$buttonValues['back_button'],'callback_data'=>"backplan"]]
                ]
            ]));
        exit;
    }
    $keyboard = [];
    $keyboard[] = [['text'=>"حذف",'callback_data'=>"wizwizch"],['text'=>"قیمت",'callback_data'=>"wizwizch"],['text'=>"تعداد روز",'callback_data'=>"wizwizch"]];
    while($cat = $res->fetch_assoc()){
        $id = $cat['id'];
        $title = $cat['volume'];
        $price=number_format($cat['price']) . " تومان";
        $acount =$cat['acount'];

        $keyboard[] = [['text'=>"❌",'callback_data'=>"deleteDayPlan" . $id],['text'=>$price,'callback_data'=>"changeDayPlanPrice" . $id],['text'=>$title,'callback_data'=>"changeDayPlanDay" . $id]];
    }
    $keyboard[] = [['text' => "افزودن پلن زمانی جدید", 'callback_data' =>"addNewDayPlan"]];
    $keyboard[] = [['text' => $buttonValues['back_button'], 'callback_data' => "backplan"]];
    $msg = ' 📍 برای دیدن جزییات پلن زمانی روی آن بزنید👇';
    
    editText($message_id,$msg,json_encode([
            'inline_keyboard' => $keyboard
        ]));

    exit;
}
if($data=='addNewDayPlan' and ($from_id == $admin || $userInfo['isAdmin'] == true)){
    setUser($data);
    delMessage();
    sendMessage("تعداد روز و قیمت آن را بصورت زیر وارد کنید :
10-30000

مقدار اول مدت زمان (10) روز
مقدار دوم قیمت (30000) تومان
 ",$cancelKey);exit;
}
if($userInfo['step'] == "addNewDayPlan" and $text != $buttonValues['cancel']) {
    $input = explode('-',$text); 
    $volume = $input[0];
    $price = $input[1];
    $stmt = $connection->prepare("INSERT INTO `increase_day` VALUES (NULL, ?, ?)");
    $stmt->bind_param("ii", $volume, $price);
    $stmt->execute();
    $stmt->close();
    
    sendMessage("پلن زمانی جدید با موفقیت اضافه شد",$removeKeyboard);
    sendMessage($mainValues['reached_main_menu'],getAdminKeys());
    setUser();
}
if(preg_match('/^deleteDayPlan(\d+)/',$data,$match) and ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $stmt = $connection->prepare("DELETE FROM `increase_day` WHERE `id` = ?");
    $stmt->bind_param("i", $match[1]);
    $stmt->execute();
    $stmt->close();
    alert("پلن موردنظر با موفقیت حذف شد");
    
    
    $stmt = $connection->prepare("SELECT * FROM `increase_day`");
    $stmt->execute();
    $res = $stmt->get_result();
    $stmt->close();

    if($res->num_rows == 0){
       editText($message_id, 'لیست پلن های زمانی خالی است ',json_encode([
                'inline_keyboard' => [
                    [['text' => "افزودن پلن زمانی جدید", 'callback_data' =>"addNewDayPlan"]],
                    [['text'=>$buttonValues['back_button'],'callback_data'=>"managePanel"]]
                ]
            ]));
        exit;
    }
    $keyboard = [];
    $keyboard[] = [['text'=>"حذف",'callback_data'=>"wizwizch"],['text'=>"قیمت",'callback_data'=>"wizwizch"],['text'=>"تعداد روز",'callback_data'=>"wizwizch"]];
    while($cat = $res->fetch_assoc()){
        $id = $cat['id'];
        $title = $cat['volume'];
        $price=number_format($cat['price']) . " تومان";
        $acount =$cat['acount'];

        $keyboard[] = [['text'=>"❌",'callback_data'=>"deleteDayPlan" . $id],['text'=>$price,'callback_data'=>"changeDayPlanPrice" . $id],['text'=>$title,'callback_data'=>"changeDayPlanDay" . $id]];
    }
    $keyboard[] = [['text' => "افزودن پلن زمانی جدید", 'callback_data' =>"addNewDayPlan"]];
    $keyboard[] = [['text' => $buttonValues['back_button'], 'callback_data' => "managePanel"]];
    $msg = ' 📍 برای دیدن جزییات پلن زمانی روی آن بزنید👇';
    
    editText($message_id,$msg,json_encode([
            'inline_keyboard' => $keyboard
        ]));

    exit;
}
if(preg_match('/^changeDayPlanPrice(\d+)/',$data,$match) and ($from_id == $admin || $userInfo['isAdmin'] == true)){
    setUser($data);
    delMessage();
    sendMessage("قیمت جدید را وارد کنید:", $cancelKey);
    exit;
}
if(preg_match('/^changeDayPlanPrice(\d+)/',$userInfo['step'],$match) and $text != $buttonValues['cancel']){
    if(is_numeric($text)){
        setUser();
        $stmt = $connection->prepare("UPDATE `increase_day` SET `price` = ? WHERE `id` = ?");
        $stmt->bind_param("ii", $text, $match[1]);
        $stmt->execute();
        $stmt->close();
        
        sendMessage("✅عملیات با موفقیت انجام شد",$removeKeyboard);
        
        $stmt = $connection->prepare("SELECT * FROM `increase_day`");
        $stmt->execute();
        $res = $stmt->get_result();
        $stmt->close();
    
        if($res->num_rows == 0){
           sendMessage( 'لیست پلن های زمانی خالی است ',json_encode([
                    'inline_keyboard' => [
                        [['text' => "افزودن پلن زمانی جدید", 'callback_data' =>"addNewDayPlan"]],
                        [['text'=>$buttonValues['back_button'],'callback_data'=>"managePanel"]]
                    ]
                ]));
            exit;
        }
        $keyboard = [];
        $keyboard[] = [['text'=>"حذف",'callback_data'=>"wizwizch"],['text'=>"قیمت",'callback_data'=>"wizwizch"],['text'=>"تعداد روز",'callback_data'=>"wizwizch"]];
        while($cat = $res->fetch_assoc()){
            $id = $cat['id'];
            $title = $cat['volume'];
            $price=number_format($cat['price']) . " تومان";
            $acount =$cat['acount'];
    
            $keyboard[] = [['text'=>"❌",'callback_data'=>"deleteDayPlan" . $id],['text'=>$price,'callback_data'=>"changeDayPlanPrice" . $id],['text'=>$title,'callback_data'=>"changeDayPlanDay" . $id]];
        }
        $keyboard[] = [['text' => "افزودن پلن زمانی جدید", 'callback_data' =>"addNewDayPlan"]];
        $keyboard[] = [['text' => $buttonValues['back_button'], 'callback_data' => "managePanel"]];
        $msg = ' 📍 برای دیدن جزییات پلن زمانی روی آن بزنید👇';
        
        sendMessage($msg,json_encode([
                'inline_keyboard' => $keyboard
            ]));
    
        
    }else{
        sendMessage("یک مقدار عددی و صحیح وارد کنید");
    }
}
if(preg_match('/^changeDayPlanDay(\d+)/',$data,$match) and ($from_id == $admin || $userInfo['isAdmin'] == true)){
    setUser($data);
    delMessage();
    sendMessage("روز جدید را وارد کنید:", $cancelKey);
    exit;
}
if(preg_match('/^changeDayPlanDay(\d+)/',$userInfo['step'],$match) and $text != $buttonValues['cancel']) {
    setUser();
    $stmt = $connection->prepare("UPDATE `increase_day` SET `volume` = ? WHERE `id` = ?");
    $stmt->bind_param("ii", $text, $match[1]);
    $stmt->execute();
    $stmt->close();

    sendMessage("✅عملیات با موفقیت انجام شد",$removeKeyboard);
    
    $stmt = $connection->prepare("SELECT * FROM `increase_day`");
    $stmt->execute();
    $res = $stmt->get_result();
    $stmt->close();

    if($res->num_rows == 0){
       sendMessage( 'لیست پلن های زمانی خالی است ',json_encode([
                'inline_keyboard' => [
                    [['text' => "افزودن پلن زمانی جدید", 'callback_data' =>"addNewDayPlan"]],
                    [['text'=>$buttonValues['back_button'],'callback_data'=>"managePanel"]]
                ]
            ]));
        exit;
    }
    $keyboard = [];
    $keyboard[] = [['text'=>"حذف",'callback_data'=>"wizwizch"],['text'=>"قیمت",'callback_data'=>"wizwizch"],['text'=>"تعداد روز",'callback_data'=>"wizwizch"]];
    while($cat = $res->fetch_assoc()){
        $id = $cat['id'];
        $title = $cat['volume'];
        $price=number_format($cat['price']) . " تومان";
        $acount =$cat['acount'];

        $keyboard[] = [['text'=>"❌",'callback_data'=>"deleteDayPlan" . $id],['text'=>$price,'callback_data'=>"changeDayPlanPrice" . $id],['text'=>$title,'callback_data'=>"changeDayPlanDay" . $id]];
    }
    $keyboard[] = [['text' => "افزودن پلن زمانی جدید", 'callback_data' =>"addNewDayPlan"]];
    $keyboard[] = [['text' => $buttonValues['back_button'], 'callback_data' => "managePanel"]];
    $msg = ' 📍 برای دیدن جزییات پلن زمانی روی آن بزنید👇';
    
    sendMessage($msg,json_encode([
            'inline_keyboard' => $keyboard
        ]));

    
}
if($data == 'volumePlanSettings' and ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $stmt = $connection->prepare("SELECT * FROM `increase_plan`");
    $stmt->execute();
    $plans = $stmt->get_result();
    $stmt->close();
    
    if($plans->num_rows == 0){
       editText($message_id, 'لیست پلن های حجمی خالی است ',json_encode([
                'inline_keyboard' => [
                    [['text' => "افزودن پلن حجمی جدید", 'callback_data' =>"addNewVolumePlan"]],
                    [['text' => $buttonValues['back_button'],'callback_data'=>"backplan"]]
                    ]]));
        exit;
    }
    $keyboard = [];
    $keyboard[] = [['text'=>"حذف",'callback_data'=>"wizwizch"],['text'=>"قیمت",'callback_data'=>"wizwizch"],['text'=>"مقدار حجم",'callback_data'=>"wizwizch"]];
    while ($cat = $plans->fetch_assoc()){
        $id = $cat['id'];
        $title = $cat['volume'];
        $price=number_format($cat['price']) . " تومان";
        
        $keyboard[] = [['text'=>"❌",'callback_data'=>"deleteVolumePlan" . $id],['text'=>$price,'callback_data'=>"changeVolumePlanPrice" . $id],['text'=>$title,'callback_data'=>"changeVolumePlanVolume" . $id]];
    }
    $keyboard[] = [['text' => "افزودن پلن حجمی جدید", 'callback_data' =>"addNewVolumePlan"]];
    $keyboard[] = [['text' =>$buttonValues['back_button'], 'callback_data' => "backplan"]];
    $msg = ' 📍 برای دیدن جزییات پلن حجمی روی آن بزنید👇';
    
    $res = editText($message_id, $msg,json_encode([
            'inline_keyboard' => $keyboard
        ]));
    exit;
}
if($data=='addNewVolumePlan' and ($from_id == $admin || $userInfo['isAdmin'] == true)){
    setUser($data);
    delMessage();
    sendMessage("حجم و قیمت آن را بصورت زیر وارد کنید :
10-30000

مقدار اول حجم (10) گیگابایت
مقدار دوم قیمت (30000) تومان
 ",$cancelKey);
 exit;
}
if($userInfo['step'] == "addNewVolumePlan" and $text != $buttonValues['cancel'] && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $input = explode('-',$text); 
    $volume = $input[0];
    $price = $input[1];
    $stmt = $connection->prepare("INSERT INTO `increase_plan` VALUES (NULL, ? ,?)");
    $stmt->bind_param("ii",$volume,$price);
    $stmt->execute();
    $stmt->close();
    
    sendMessage("پلن حجمی جدید با موفقیت اضافه شد",$removeKeyboard);
    sendMessage($mainValues['reached_main_menu'],getAdminKeys());
    setUser();
}
if(preg_match('/^deleteVolumePlan(\d+)/',$data,$match) and ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $stmt = $connection->prepare("DELETE FROM `increase_plan` WHERE `id` = ?");
    $stmt->bind_param("i", $match[1]);
    $stmt->execute();
    $stmt->close();
    alert("پلن موردنظر با موفقیت حذف شد");
    
    
    $stmt = $connection->prepare("SELECT * FROM `increase_plan`");
    $stmt->execute();
    $plans = $stmt->get_result();
    $stmt->close();
    
    if($plans->num_rows == 0){
       editText($message_id, 'لیست پلن های حجمی خالی است ',json_encode([
                'inline_keyboard' => [
                    [['text' => "افزودن پلن حجمی جدید", 'callback_data' =>"addNewVolumePlan"]],
                    [['text' => $buttonValues['back_button'],'callback_data'=>"managePanel"]]
                    ]]));
        exit;
    }
    $keyboard = [];
    $keyboard[] = [['text'=>"حذف",'callback_data'=>"wizwizch"],['text'=>"قیمت",'callback_data'=>"wizwizch"],['text'=>"مقدار حجم",'callback_data'=>"wizwizch"]];
    while ($cat = $plans->fetch_assoc()){
        $id = $cat['id'];
        $title = $cat['volume'];
        $price=number_format($cat['price']) . " تومان";
        
        $keyboard[] = [['text'=>"❌",'callback_data'=>"deleteVolumePlan" . $id],['text'=>$price,'callback_data'=>"changeVolumePlanPrice" . $id],['text'=>$title,'callback_data'=>"changeVolumePlanVolume" . $id]];
    }
    $keyboard[] = [['text' => "افزودن پلن حجمی جدید", 'callback_data' =>"addNewVolumePlan"]];
    $keyboard[] = [['text' =>$buttonValues['back_button'], 'callback_data' => "managePanel"]];
    $msg = ' 📍 برای دیدن جزییات پلن حجمی روی آن بزنید👇';
    
    $res = editText($message_id, $msg,json_encode([
            'inline_keyboard' => $keyboard
        ]));
}
if(preg_match('/^changeVolumePlanPrice(\d+)/',$data,$match) and ($from_id == $admin || $userInfo['isAdmin'] == true)){
    setUser($data);
    delMessage();
    sendMessage("قیمت جدید را وارد کنید:", $cancelKey);
    exit;
}
if(preg_match('/^changeVolumePlanPrice(\d+)/',$userInfo['step'],$match) and $text != $buttonValues['cancel'] and ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $pid=$match[1];
    if(is_numeric($text)){
        $stmt = $connection->prepare("UPDATE `increase_plan` SET `price` = ? WHERE `id` = ?");
        $stmt->bind_param("ii", $text, $pid);
        $stmt->execute();
        $stmt->close();
        sendMessage("عملیات با موفقیت انجام شد",$removeKeyboard);
        
        setUser();
        $stmt = $connection->prepare("SELECT * FROM `increase_plan`");
        $stmt->execute();
        $plans = $stmt->get_result();
        $stmt->close();
        
        if($plans->num_rows == 0){
           sendMessage( 'لیست پلن های حجمی خالی است ',json_encode([
                    'inline_keyboard' => [
                        [['text' => "افزودن پلن حجمی جدید", 'callback_data' =>"addNewVolumePlan"]],
                        [['text' => $buttonValues['back_button'],'callback_data'=>"managePanel"]]
                        ]]));
            exit;
        }
        $keyboard = [];
        $keyboard[] = [['text'=>"حذف",'callback_data'=>"wizwizch"],['text'=>"قیمت",'callback_data'=>"wizwizch"],['text'=>"مقدار حجم",'callback_data'=>"wizwizch"]];
        while ($cat = $plans->fetch_assoc()){
            $id = $cat['id'];
            $title = $cat['volume'];
            $price=number_format($cat['price']) . " تومان";
            
            $keyboard[] = [['text'=>"❌",'callback_data'=>"deleteVolumePlan" . $id],['text'=>$price,'callback_data'=>"changeVolumePlanPrice" . $id],['text'=>$title,'callback_data'=>"changeVolumePlanVolume" . $id]];
        }
        $keyboard[] = [['text' => "افزودن پلن حجمی جدید", 'callback_data' =>"addNewVolumePlan"]];
        $keyboard[] = [['text' =>$buttonValues['back_button'], 'callback_data' => "managePanel"]];
        $msg = ' 📍 برای دیدن جزییات پلن حجمی روی آن بزنید👇';
        
        $res = sendMessage($msg,json_encode([
                'inline_keyboard' => $keyboard
            ]));
    }else{
        sendMessage("یک مقدار عددی و صحیح وارد کنید");
    }
}
if(preg_match('/^changeVolumePlanVolume(\d+)/',$data) and ($from_id == $admin || $userInfo['isAdmin'] == true)){
    setUser($data);
    delMessage();
    sendMessage("حجم جدید را وارد کنید:", $cancelKey);
    exit;
}
if(preg_match('/^changeVolumePlanVolume(\d+)/',$userInfo['step'], $match) and $text != $buttonValues['cancel'] && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $pid=$match[1];
    $stmt = $connection->prepare("UPDATE `increase_plan` SET `volume` = ? WHERE `id` = ?");
    $stmt->bind_param("ii", $text, $pid);
    $stmt->execute();
    $stmt->close();
    sendMessage("✅عملیات با موفقیت انجام شد",$removeKeyboard);
    setUser();

    $stmt = $connection->prepare("SELECT * FROM `increase_plan`");
    $stmt->execute();
    $plans = $stmt->get_result();
    $stmt->close();
    
    if($plans->num_rows == 0){
       sendMessage( 'لیست پلن های حجمی خالی است ',json_encode([
                'inline_keyboard' => [
                    [['text' => "افزودن پلن حجمی جدید", 'callback_data' =>"addNewVolumePlan"]],
                    [['text' => $buttonValues['back_button'],'callback_data'=>"managePanel"]]
                    ]]));
        exit;
    }
    $keyboard = [];
    $keyboard[] = [['text'=>"حذف",'callback_data'=>"wizwizch"],['text'=>"قیمت",'callback_data'=>"wizwizch"],['text'=>"مقدار حجم",'callback_data'=>"wizwizch"]];
    while ($cat = $plans->fetch_assoc()){
        $id = $cat['id'];
        $title = $cat['volume'];
        $price=number_format($cat['price']) . " تومان";
        
        $keyboard[] = [['text'=>"❌",'callback_data'=>"deleteVolumePlan" . $id],['text'=>$price,'callback_data'=>"changeVolumePlanPrice" . $id],['text'=>$title,'callback_data'=>"changeVolumePlanVolume" . $id]];
    }
    $keyboard[] = [['text' => "افزودن پلن حجمی جدید", 'callback_data' =>"addNewVolumePlan"]];
    $keyboard[] = [['text' =>$buttonValues['back_button'], 'callback_data' => "managePanel"]];
    $msg = ' 📍 برای دیدن جزییات پلن حجمی روی آن بزنید👇';
    
    $res = sendMessage( $msg,json_encode([
            'inline_keyboard' => $keyboard
        ]));
    
}
if(preg_match('/^supportCat(.*)/',$data,$match)){
    delMessage();
    sendMessage("💠لطفا موضوع تیکت را ارسال کنید!", $cancelKey);
    setUser("newTicket_" . $match[1]);
}
if(preg_match('/^newTicket_(.*)/',$userInfo['step'],$match)  and $text!=$buttonValues['cancel']){
    file_put_contents("$from_id.txt",$text);
	setUser("sendTicket_" . $match[1]);
    sendMessage("💠لطفا متن تیکت خود را بصورت ساده و مختصر ارسال کنید!");
}
if(preg_match('/^sendTicket_(.*)/',$userInfo['step'],$match)  and $text!=$buttonValues['cancel']){
    $ticketCat = $match[1];
    
    $ticketTitle = file_get_contents("$from_id.txt");
    $time = time();
    $txt = "تیکت جدید:\n\nکاربر: <a href='tg://user?id=$from_id'>$first_name</a>\nنام کاربری: @$username\nآیدی عددی: $from_id\n\nموضوع تیکت: $ticketCat\n\nعنوان تیکت: " .$ticketTitle . "\nمتن تیکت: $text";

    $ticketTitle = str_replace(["/","'","#"],['\/',"\'","\#"],$ticketTitle);
    $text = str_replace(["/","'","#"],['\/',"\'","\#"],$text);
    $stmt = $connection->prepare("INSERT INTO `chats` (`user_id`,`create_date`, `title`,`category`,`state`,`rate`) VALUES 
                        (?,?,?,?,'0','0')");
    $stmt->bind_param("iiss", $from_id, $time, $ticketTitle, $ticketCat);
    $stmt->execute();
    $inserId = $stmt->get_result();
    $chatRowId = $stmt->insert_id;
    $stmt->close();
    
    $stmt = $connection->prepare("INSERT INTO `chats_info` (`chat_id`,`sent_date`,`msg_type`,`text`) VALUES
                (?,?,'USER',?)");
    $stmt->bind_param("iis", $chatRowId, $time, $text);
    $stmt->execute();
    $stmt->close();
    
    $keys = json_encode(['inline_keyboard'=>[
        [['text'=>"پاسخ",'callback_data'=>"reply_{$chatRowId}"]]
        ]]);
    sendMessage($txt,$keys,"html", $admin);
    sendMessage("پیام شما با موفقیت ثبت شد",$removeKeyboard,"HTML");
    sendMessage("لطفا یکی از کلید های زیر را انتخاب کنید",getMainKeys());
        
    unlink("$from_id.txt");
	setUser("none");
}
if($data== "usersOpenTickets" || $data == "userAllTickets"){
    if($data== "usersOpenTickets"){
        $stmt = $connection->prepare("SELECT * FROM `chats` WHERE `state` != 2 AND `user_id` = ? ORDER BY `state` ASC, `create_date` DESC");
        $stmt->bind_param("i", $from_id);
        $stmt->execute();
        $ticketList = $stmt->get_result();
        $stmt->close();
        $type = 2;
    }elseif($data == "userAllTickets"){
        $stmt = $connection->prepare("SELECT * FROM `chats` WHERE `user_id` = ? ORDER BY `state` ASC, `create_date` DESC");
        $stmt->bind_param("i", $from_id);
        $stmt->execute();
        $ticketList = $stmt->get_result();
        $stmt->close();
        $type = "all";
    }
	$allList = $ticketList->num_rows;
	$cont = 5;
	$current = 0;
	$keys = array();
	setUser("none");


	if($allList>0){
        while($row = $ticketList->fetch_assoc()){
		    $current++;
		    
            $rowId = $row['id'];
            $title = $row['title'];
            $category = $row['category'];
	        $state = $row['state'];

            $stmt = $connection->prepare("SELECT * FROM `chats_info` WHERE `chat_id` = ? ORDER BY `sent_date` DESC");
            $stmt->bind_param("i", $rowId);
            $stmt->execute();
            $ticketInfo = $stmt->get_result()->fetch_assoc();
            $stmt->close();
            
            $lastmsg = $ticketInfo['text'];
            $sentType = $ticketInfo['msg_type']=="ADMIN"?"ادمین":"کاربر";
            
            if($state !=2){
                $keys = [
                        [['text'=>"بستن تیکت 🗳",'callback_data'=>"closeTicket_$rowId"],['text'=>"پاسخ به تیکت 📝",'callback_data'=>"replySupport_{$rowId}"]],
                        [['text'=>"آخرین پیام ها 📩",'callback_data'=>"latestMsg_$rowId"]]
                        ];
            }
            else{
                $keys = [
                    [['text'=>"آخرین پیام ها 📩",'callback_data'=>"latestMsg_$rowId"]]
                    ];
            }
                
            sendMessage(" 🔘 موضوع: $title
			💭 دسته بندی:  {$category}
			\n
			$sentType : $lastmsg",json_encode(['inline_keyboard'=>$keys]),"HTML");

			if($current>=$cont){
			    break;
			}
        }
        
		if($allList > $cont){
		    sendmessage("موارد بیشتر",json_encode(['inline_keyboard'=>[
                		        [['text'=>"دریافت",'callback_data'=>"moreTicket_{$type}_{$cont}"]]
                		        ]]),"HTML");
		}
	}else{
	    alert("تیکتی یافت نشد");
        exit();
	}
}
if(preg_match('/^closeTicket_(\d+)/',$data,$match) and  $from_id != $admin){
    $chatRowId = $match[1];
    $stmt = $connection->prepare("SELECT * FROM `chats` WHERE `id` = ?");
    $stmt->bind_param("i", $chatRowId);
    $stmt->execute();
    $ticketInfo = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    $from_id = $ticketInfo['user_id'];
    $title = $ticketInfo['title'];
    $category = $ticketInfo['category'];
        

    $stmt = $connection->prepare("UPDATE `chats` SET `state` = 2 WHERE `id` = ?");
    $stmt->bind_param("i", $chatRowId);
    $stmt->execute();
    $stmt->close();
    
    editKeys();

    $ticketClosed = " $title : $category \n\n" . "این تیکت بسته شد\n به این تیکت رأی بدهید";;
    
    $keys = json_encode(['inline_keyboard'=>[
        [['text'=>"بسیار بد 😠",'callback_data'=>"rate_{$chatRowId}_1"]],
        [['text'=>"بد 🙁",'callback_data'=>"rate_{$chatRowId}_2"]],
        [['text'=>"خوب 😐",'callback_data'=>"rate_{$chatRowId}_3"]],
        [['text'=>"بسیار خوب 😃",'callback_data'=>"rate_{$chatRowId}_4"]],
        [['text'=>"عالی 🤩",'callback_data'=>"rate_{$chatRowId}_5"]]
        ]]);
    sendMessage($ticketClosed,$keys,'html');
    
    $keys = json_encode(['inline_keyboard'=>[
        [
            ['text'=>"$from_id",'callback_data'=>"wizwizch"],
            ['text'=>"آیدی کاربر",'callback_data'=>'wizwizch']
        ],
        [
            ['text'=>$first_name??" ",'callback_data'=>"wizwizch"],
            ['text'=>"اسم کاربر",'callback_data'=>'wizwizch']
        ],
        [
            ['text'=>"$title",'callback_data'=>'wizwizch'],
            ['text'=>"عنوان",'callback_data'=>'wizwizch']
        ],
        [
            ['text'=>"$category",'callback_data'=>'wizwizch'],
            ['text'=>"دسته بندی",'callback_data'=>'wizwizch']
        ],
        ]]);
    sendMessage("☑️| تیکت توسط کاربر بسته شد",$keys,"HTML",$admin);

}
if(preg_match('/^replySupport_(.*)/',$data,$match)){
    delMessage();
    sendMessage("💠لطفا متن پیام خود را بصورت ساده و مختصر ارسال کنید!",$cancelKey);
	setUser("sendMsg_" . $match[1]);
}
if(preg_match('/^sendMsg_(.*)/',$userInfo['step'],$match)  and $text!=$buttonValues['cancel']){
    $ticketRowId = $match[1];

    $stmt = $connection->prepare("SELECT * FROM `chats` WHERE `id` = ?");
    $stmt->bind_param("i", $ticketRowId);
    $stmt->execute();
    $ticketInfo = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $ticketTitle = $ticketInfo['title'];
    $ticketCat = $ticketInfo['category'];

    $time = time();
    $txt = "پیام جدید:\n[$ticketTitle] <i>{$ticketCat}</i>\n\nکاربر: <a href='tg://user?id=$from_id'>$first_name</a>\nنام کاربری: $username\nآیدی عددی: $from_id\n" . "\nمتن پیام: $text";

    $text = str_replace(["/","'","#"],['\/',"\'","\#"],$text);
    $stmt = $connection->prepare("INSERT INTO `chats_info` (`chat_id`,`sent_date`,`msg_type`,`text`) VALUES
                (?,?,'USER',?)");
    $stmt->bind_param("iis",$ticketRowId, $time, $text);
    $stmt->execute();
    $stmt->close();
                
    sendMessage($txt,json_encode(['inline_keyboard'=>[
        [['text'=>"پاسخ",'callback_data'=>"reply_{$ticketRowId}"]]
        ]]),"HTML",$admin);
    sendMessage("پیام شما با موفقیت ثبت شد",getMainKeys(),"HTML");
	setUser("none");
}
if(preg_match("/^rate_+([0-9])+_+([0-9])/",$data,$match)){
    $rowChatId = $match[1];
    $rate = $match[2];
    
    $stmt = $connection->prepare("SELECT * FROM `chats` WHERE `id` = ?");
    $stmt->bind_param("i",$rowChatId);
    $stmt->execute();
    $ticketInfo = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $title = $ticketInfo['title'];
    $category = $ticketInfo['category'];
    
    
    $stmt = $connection->prepare("UPDATE `chats` SET `rate` = $rate WHERE `id` = ?");
    $stmt->bind_param("i", $rowChatId);
    $stmt->execute();
    $stmt->close();
    editText($message_id,"✅");
    
    $keys = json_encode(['inline_keyboard'=>[
        [
            ['text'=>"رای تیکت",'callback_data'=>"wizwizch"]
            ],
        ]]);

    sendMessage("
📨|رأی به تیکت 

👤 آیدی عددی: $from_id
❕نام کاربر: $first_name
❗️نام کاربری: $username
〽️ عنوان: $title
⚜️ دسته بندی: $category
❤️ رای: $rate
 ⁮⁮
    ",$keys,"HTML",$admin);
}
if($data=="ticketsList" and ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $ticketSection = json_encode(['inline_keyboard'=>[
        [
            ['text'=>"تیکت های باز",'callback_data'=>"openTickets"],
            ['text'=>"تیکت های جدید",'callback_data'=>"newTickets"]
            ],
        [
            ['text'=>"همه ی تیکت ها",'callback_data'=>"allTickets"],
            ['text'=>"دسته بندی تیکت ها",'callback_data'=>"ticketsCategory"]
            ],
        [['text' => $buttonValues['back_button'], 'callback_data' => "managePanel"]]
        ]]);
    editText($message_id, "به بخش تیکت ها خوش اومدید، 
    
🚪 /start
    ",$ticketSection);
}
if($data=='ticketsCategory' and ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'TICKETS_CATEGORY'");
    $stmt->execute();
    $ticketCategory = $stmt->get_result();
    $stmt->close();
    $keys = array();
    $keys[] = [['text'=>"حذف",'callback_data'=>"wizwizch"],['text'=>"دسته بندی",'callback_data'=>"wizwizch"]];
    
    if($ticketCategory->num_rows>0){
        while($row = $ticketCategory->fetch_assoc()){
            $rowId = $row['id'];
            $ticketName = $row['value'];
            $keys[] = [['text'=>"❌",'callback_data'=>"delTicketCat_$rowId"],['text'=>$ticketName,'callback_data'=>"wizwizch"]];
        }
    }else{
        $keys[] = [['text'=>"دسته بندی یافت نشد",'callback_data'=>"wizwizch"]];
    }
    $keys[] = [['text'=>"افزودن دسته بندی",'callback_data'=>"addTicketCategory"]];
    $keys[] = [['text'=>$buttonValues['back_button'],'callback_data'=>"ticketsList"]];
    
    $keys =  json_encode(['inline_keyboard'=>$keys]);
    editText($message_id,"دسته بندی تیکت ها",$keys);
}
if($data=="addTicketCategory" and ($from_id == $admin || $userInfo['isAdmin'] == true)){
    setUser('addTicketCategory');
    editText($message_id,"لطفا اسم دسته بندی را وارد کنید");
}
if ($userInfo['step']=="addTicketCategory" and ($from_id == $admin || $userInfo['isAdmin'] == true)){
	$stmt = $connection->prepare("INSERT INTO `setting` (`type`, `value`) VALUES ('TICKETS_CATEGORY', ?)");	
	$stmt->bind_param("s", $text);
	$stmt->execute();
	$stmt->close();
    setUser();
    sendMessage($mainValues['saved_successfuly']);
    $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'TICKETS_CATEGORY'");
    $stmt->execute();
    $ticketCategory = $stmt->get_result();
    $stmt->close();
    
    $keys = array();
    $keys[] = [['text'=>"حذف",'callback_data'=>"wizwizch"],['text'=>"دسته بندی",'callback_data'=>"wizwizch"]];
    
    if($ticketCategory->num_rows>0){
        while ($row = $ticketCategory->fetch_assoc()){
            
            $rowId = $row['id'];
            $ticketName = $row['value'];
            $keys[] = [['text'=>"❌",'callback_data'=>"delTicketCat_$rowId"],['text'=>$ticketName,'callback_data'=>"wizwizch"]];
        }
    }else{
        $keys[] = [['text'=>"دسته بندی یافت نشد",'callback_data'=>"wizwizch"]];
    }
    $keys[] = [['text'=>"افزودن دسته بندی",'callback_data'=>"addTicketCategory"]];
    $keys[] = [['text'=>$buttonValues['back_button'],'callback_data'=>"ticketsList"]];
    
    $keys =  json_encode(['inline_keyboard'=>$keys]);
    sendMessage("دسته بندی تیکت ها",$keys);
}
if(preg_match("/^delTicketCat_(\d+)/",$data,$match) and ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $stmt = $connection->prepare("DELETE FROM `setting` WHERE `id` = ?");
    $stmt->bind_param("i", $match[1]);
    $stmt->execute();
    $stmt->close();
    
    alert("با موفقیت حذف شد");
        

    $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'TICKETS_CATEGORY'");
    $stmt->execute();
    $ticketCategory = $stmt->get_result();
    $stmt->close();
    
    $keys = array();
    $keys[] = [['text'=>"حذف",'callback_data'=>"wizwizch"],['text'=>"دسته بندی",'callback_data'=>"wizwizch"]];
    
    if($ticketCategory->num_rows>0){
        while ($row = $ticketCategory->fetch_assoc()){
            
            $rowId = $row['id'];
            $ticketName = $row['value'];
            $keys[] = [['text'=>"❌",'callback_data'=>"delTicketCat_$rowId"],['text'=>$ticketName,'callback_data'=>"wizwizch"]];
        }
    }else{
        $keys[] = [['text'=>"دسته بندی یافت نشد",'callback_data'=>"wizwizch"]];
    }
    $keys[] = [['text'=>"افزودن دسته بندی",'callback_data'=>"addTicketCategory"]];
    $keys[] = [['text'=>$buttonValues['back_button'],'callback_data'=>"ticketsList"]];
    
    $keys =  json_encode(['inline_keyboard'=>$keys]);
    editText($message_id, "دسته بندی تیکت ها",$keys);
}
if(($data=="openTickets" or $data=="newTickets" or $data == "allTickets")  and  $from_id ==$admin){
    if($data=="openTickets"){
        $stmt = $connection->prepare("SELECT * FROM `chats` WHERE `state` != 2 ORDER BY `state` ASC, `create_date` DESC");
        $type = 2;
    }elseif($data=="newTickets"){
        $stmt = $connection->prepare("SELECT * FROM `chats` WHERE `state` = 0 ORDER BY `create_date` DESC");
        $type = 0;
    }elseif($data=="allTickets"){
        $stmt = $connection->prepare("SELECT * FROM `chats` ORDER BY `state` ASC, `create_date` DESC");
        $type = "all";
    }
    $stmt->execute();
    $ticketList = $stmt->get_result();
    $stmt->close();
	$allList =$ticketList->num_rows;
	$cont = 5;
	$current = 0;
	$keys = array();
	if($allList>0){
        while ($row = $ticketList->fetch_assoc()){
		    $current++;
		    
            $rowId = $row['id'];
            $admin = $row['user_id'];
            $title = $row['title'];
            $category = $row['category'];
	        $state = $row['state'];
	        $username = bot('getChat',['chat_id'=>$admin])->result->first_name ?? " ";

            $stmt = $connection->prepare("SELECT * FROM `chats_info` WHERE `chat_id` = ? ORDER BY `sent_date` DESC");
            $stmt->bind_param("i",$rowId);
            $stmt->execute();
            $ticketInfo = $stmt->get_result()->fetch_assoc();
            $stmt->close();
            $lastmsg = $ticketInfo['text'];
            $sentType = $ticketInfo['msg_type']=="USER"?"کاربر":"ادمین";
            
            if($state !=2){
                $keys = [
                        [['text'=>"بستن تیکت",'callback_data'=>"closeTicket_$rowId"],['text'=>"پاسخ",'callback_data'=>"reply_{$rowId}"]],
                        [['text'=>"آخرین پیام ها",'callback_data'=>"latestMsg_$rowId"]]
                        ];
            }
            else{
                $keys = [[['text'=>"آخرین پیام ها",'callback_data'=>"latestMsg_$rowId"]]];
                $rate = "\nرأی: ". $row['rate'];
            }
            
            sendMessage("آیدی کاربر: $admin\nنام کاربر: $username\nدسته بندی: $category $rate\n\nموضوع: $title\nآخرین پیام:\n[$sentType] $lastmsg",
                json_encode(['inline_keyboard'=>$keys]),"html");

			if($current>=$cont){
			    break;
			}
        }
        
		if($allList > $cont){
		    $keys = json_encode(['inline_keyboard'=>[
		        [['text'=>"دریافت",'callback_data'=>"moreTicket_{$type}_{$cont}"]]
		        ]]);
            sendMessage("موارد بیشتر",$keys,"html");
		}
	}else{
        alert("تیکتی یافت نشد");
	}
}
if(preg_match('/^moreTicket_(.+)_(.+)/',$data, $match) and  ($from_id == $admin || $userInfo['isAdmin'] == true)){
    editText($message_id,$mainValues['please_wait_message']);
    $type = $match[1];
    $offset = $match[2];
    if($type=="2") $stmt = $connection->prepare("SELECT * FROM `chats` WHERE `state` != 2 ORDER BY `state` ASC, `create_date` DESC");
    elseif($type=="0") $stmt = $connection->prepare("SELECT * FROM `chats` WHERE `state` = 0 ORDER BY `create_date` DESC");
    elseif($type=="all") $stmt = $connection->prepare("SELECT * FROM `chats` ORDER BY `state` ASC, `create_date` DESC");
    
    $stmt->execute();
    $ticketList = $stmt->get_result();
    $stmt->close();

	$allList =$ticketList->num_rows;
	$cont = 5 + $offset;
	$current = 0;
	$keys = array();
	$rowCont = 0;
	if($allList>0){
        while ($row = $ticketList->fetch_assoc()){
            $rowCont++;
            if($rowCont>$offset){
    		    $current++;
    		    
                $rowId = $row['id'];
                $admin = $row['user_id'];
                $title = $row['title'];
                $category = $row['category'];
    	        $state = $row['state'];
    	        $username = bot('getChat',['chat_id'=>$admin])->result->first_name ?? " ";
    
                $stmt = $connection->prepare("SELECT * FROM `chats_info` WHERE `chat_id` = ? ORDER BY `sent_date` DESC");
                $stmt->bind_param("i",$rowId);
                $stmt->execute();
                $ticketInfo = $stmt->get_result()->fetch_assoc();
                $stmt->close();
                $lastmsg = $ticketInfo['text'];
                $sentType = $ticketInfo['msg_type']=="USER"?"کاربر":"ادمین";
                
                if($state !=2){
                    $keys = [
                            [['text'=>"بستن تیکت",'callback_data'=>"closeTicket_$rowId"],['text'=>"پاسخ",'callback_data'=>"reply_{$rowId}"]],
                            [['text'=>"آخرین پیام ها",'callback_data'=>"latestMsg_$rowId"]]
                            ];
                }
                else{
                    $keys = [[['text'=>"آخرین پیام ها",'callback_data'=>"latestMsg_$rowId"]]];
                    $rate = "\nرأی: ". $row['rate'];
                }
                
                sendMessage("آیدی کاربر: $admin\nنام کاربر: $username\nدسته بندی: $category $rate\n\nموضوع: $title\nآخرین پیام:\n[$sentType] $lastmsg",
                    json_encode(['inline_keyboard'=>$keys]),"html");


    			if($current>=$cont){
    			    break;
    			}
            }
        }
        
		if($allList > $cont){
		    $keys = json_encode(['inline_keyboard'=>[
		        [['text'=>"دریافت",'callback_data'=>"moreTicket_{$type}_{$cont}"]]
		        ]]);
            sendMessage("موارد بیشتر",$keys);
		}
	}else{
        alert("تیکتی یافت نشد");
	}
}
if(preg_match('/^closeTicket_(\d+)/',$data,$match) and  ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $chatRowId = $match[1];
    $stmt = $connection->prepare("SELECT * FROM `chats` WHERE `id` = ?");
    $stmt->bind_param("i", $chatRowId);
    $stmt->execute();
    $ticketInfo = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    $userId = $ticketInfo['user_id'];
    $title = $ticketInfo['title'];
    $category = $ticketInfo['category'];
        

    $stmt = $connection->prepare("UPDATE `chats` SET `state` = 2 WHERE `id` = ?");
    $stmt->bind_param("i", $chatRowId);
    $stmt->execute();
    $stmt->close();
    
    $ticketClosed = "[$title] <i>$category</i> \n\n" . "این تیکت بسته شد\n به این تیکت رأی بدهید";;
    
    $keys = json_encode(['inline_keyboard'=>[
        [['text'=>"بسیار بد 😠",'callback_data'=>"rate_{$chatRowId}_1"]],
        [['text'=>"بد 🙁",'callback_data'=>"rate_{$chatRowId}_2"]],
        [['text'=>"خوب 😐",'callback_data'=>"rate_{$chatRowId}_3"]],
        [['text'=>"بسیار خوب 😃",'callback_data'=>"rate_{$chatRowId}_4"]],
        [['text'=>"عالی 🤩",'callback_data'=>"rate_{$chatRowId}_5"]]
        ]]);
    sendMessage($ticketClosed,$keys,'html', $userId);
    editKeys(json_encode(['inline_keyboard'=>[
        [['text'=>"تیکت بسته شد",'callback_data'=>"wizwizch"]]
        ]]));

}
if(preg_match('/^latestMsg_(.*)/',$data,$match)){
    $stmt = $connection->prepare("SELECT * FROM `chats_info` WHERE `chat_id` = ? ORDER BY `sent_date` DESC LIMIT 10");
    $stmt->bind_param("i", $match[1]);
    $stmt->execute();
    $chatList = $stmt->get_result();
    $stmt->close();
    $output = "";
    while($row = $chatList->fetch_assoc()){
        $type = $row['msg_type'] == "USER" ?"کاربر":"ادمین";
        $text = $row['text'];

        $output .= "<i>[$type]</i>\n$text\n\n";
    }
    sendMessage($output, null, "html");
}
if($data == "banUser" && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    delMessage();
    sendMessage("😡 | کی باز شلوغی کرده آیدی عددی شو بفرس تا برم ...... آرهههه:", $cancelKey);
    setUser($data);
}
if($data=="unbanUser" && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    delMessage();
    sendMessage("آیدی عددیشو بفرست تا آزادش کنم", $cancelKey);
    setUser($data);
}
if($userInfo['step'] == "banUser" && ($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();
        $usersList = $stmt->get_result();
        $stmt->close();
        
        if($usersList->num_rows >0){
            $userState = $usersList->fetch_assoc();
            if($userState['step'] != "banned"){
                $stmt = $connection->prepare("UPDATE `users` SET `step` = 'banned' WHERE `userid` = ?");
                $stmt->bind_param("i", $text);
                $stmt->execute();
                $stmt->close();
                
                sendMessage("❌ | خب خب برید کنار که مسدودش کردم 😎😂",$removeKeyboard);
            }else{
                sendMessage("☑️ | این کاربر که از قبل مسدود بود چیکارش داری بدبخت و 😂🤣",$removeKeyboard);
            }
        }else sendMessage("کاربری با این آیدی یافت نشد");
        setUser();
        sendMessage($mainValues['reached_main_menu'],getAdminKeys());
    }else{
        sendMessage($mainValues['send_only_number']);
    }
}
if($data=="mainMenuButtons" && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    editText($message_id,"مدیریت دکمه های صفحه اصلی",getMainMenuButtonsKeys());
}
if(preg_match('/^delMainButton(\d+)/',$data,$match) && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $stmt = $connection->prepare("DELETE FROM `setting` WHERE `id` = ?");
    $stmt->bind_param("i", $match[1]);
    $stmt->execute();
    $stmt->close();
    
    alert("با موفقیت حذف شد");
    editText($message_id,"مدیریت دکمه های صفحه اصلی",getMainMenuButtonsKeys());
}
if($data == "addNewMainButton" && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    delMessage();
    sendMessage("لطفا اسم دکمه را وارد کنید",$cancelKey);
    setUser($data);
}
if($userInfo['step'] == "addNewMainButton" && $text != $buttonValues['cancel']){
    if(!isset($update->message->text)){
        sendMessage("لطفا فقط متن بفرستید");
        exit();
    }
    sendMessage("لطفا پاسخ دکمه را وارد کنید");
    setUser("setMainButtonAnswer" . $text);
}
if(preg_match('/^setMainButtonAnswer(.*)/',$userInfo['step'],$match)){
    if(!isset($update->message->text)){
        sendMessage("لطفا فقط متن بفرستید");
        exit();
    }
    setUser();
    
    $stmt = $connection->prepare("INSERT INTO `setting` (`type`, `value`) VALUES (?, ?)");
    $btn = "MAIN_BUTTONS" . $match[1];
    $stmt->bind_param("ss", $btn, $text); 
    $stmt->execute();
    $stmt->close();
    
    sendMessage("مدیریت دکمه های صفحه اصلی",getMainMenuButtonsKeys());
}
if($userInfo['step'] == "unbanUser" && ($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();
        $usersList = $stmt->get_result();
        $stmt->close();

        if($usersList->num_rows >0){
            $userState = $usersList->fetch_assoc();
            if($userState['step'] == "banned"){
                $stmt = $connection->prepare("UPDATE `users` SET `step` = 'none' WHERE `userid` = ?");
                $stmt->bind_param("i", $text);
                $stmt->execute();
                $stmt->close();

                sendMessage("✅ | آزاد شدم خوشحالم ننه ، ایشالا آزادی همه 😂",$removeKeyboard);
            }else{
                sendMessage("☑️ | این کاربری که فرستادی از قبل آزاد بود 🙁",$removeKeyboard);
            }
        }else sendMessage("کاربری با این آیدی یافت نشد");
        setUser();
        sendMessage($mainValues['reached_main_menu'],getAdminKeys());
    }else{
        sendMessage($mainValues['send_only_number']);
    }
}
if(preg_match("/^reply_(.*)/",$data,$match) and  ($from_id == $admin || $userInfo['isAdmin'] == true)){
    setUser("answer_" . $match[1]);
    sendMessage("لطفا پیام خود را ارسال کنید",$cancelKey);
}
if(preg_match('/^answer_(.*)/',$userInfo['step'],$match) and  $from_id ==$admin  and $text!=$buttonValues['cancel']){
    $chatRowId = $match[1];
    $stmt = $connection->prepare("SELECT * FROM `chats` WHERE `id` = ?");
    $stmt->bind_param("i", $chatRowId);
    $stmt->execute();
    $ticketInfo = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    $userId = $ticketInfo['user_id'];
    $ticketTitle = $ticketInfo['title'];
    $ticketCat = $ticketInfo['category'];
    
    sendMessage("\[$ticketTitle] _{$ticketCat}_\n\n" . $text,json_encode(['inline_keyboard'=>[
        [
            ['text'=>'پاسخ به تیکت 📝','callback_data'=>"replySupport_$chatRowId"],
            ['text'=>"بستن تیکت 🗳",'callback_data'=>"closeTicket_$chatRowId"]
            ]
        ]]),"MarkDown", $userId);
    $time = time();

    $ticketTitle = str_replace(["/","'","#"],['\/',"\'","\#"],$ticketTitle);
    $text = str_replace(["/","'","#"],['\/',"\'","\#"],$text);
    $stmt = $connection->prepare("INSERT INTO `chats_info` (`chat_id`,`sent_date`,`msg_type`,`text`) VALUES
                (?,?,'ADMIN',?)");
    $stmt->bind_param("iis", $chatRowId, $time, $text);
    $stmt->execute();
    $stmt->close();
    $stmt = $connection->prepare("UPDATE `chats` SET `state` = 1 WHERE `id` = ?");
    $stmt->bind_param("i", $chatRowId);
    $stmt->execute();
    $stmt->close();
    
    setUser();
    sendMessage("پیام شما با موفقیت ارسال شد ✅",$removeKeyboard);
}
if(preg_match('/freeTrial(\d+)/',$data,$match)) {
    $id = $match[1];
 
    if($userInfo['freetrial'] == 'used' and !($from_id == $admin)){
        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();

    $days = $file_detail['days'];
    $date = time();
    $expire_microdate = floor(microtime(true) * 1000) + (864000 * $days * 100);
    $expire_date = $date + (86400 * $days);
    $type = $file_detail['type'];
    $volume = $file_detail['volume'];
    $protocol = $file_detail['protocol'];
    $price = $file_detail['price'];
    $server_id = $file_detail['server_id'];
    $acount = $file_detail['acount'];
    $inbound_id = $file_detail['inbound_id'];
    $limitip = $file_detail['limitip'];
    $netType = $file_detail['type'];
    $rahgozar = $file_detail['rahgozar'];
    $customPath = $file_detail['custom_path'];
    $customPort = $file_detail['custom_port'];
    $customSni = $file_detail['custom_sni'];
    
    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){ 
            $stmt = $connection->prepare("UPDATE `server_info` SET `ucount` = `ucount` - 1 WHERE `id`=?");
            $stmt->bind_param("i", $server_id);
            $stmt->execute();
            $stmt->close();
        } else {
            alert($mainValues['out_of_server_capacity']);
            exit;
        }
    }else{
        if($acount != 0) {
            $stmt = $connection->prepare("UPDATE `server_plans` SET `acount` = `acount` - 1 WHERE `id`=?");
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $stmt->close();
        }
    }
    
    $uniqid = generateRandomString(42,$protocol); 

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

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

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

    if($botState['remark'] == "digits"){
        $rnd = rand(10000,99999);
        $remark = "{$srv_remark}-{$rnd}";
    }else{
        $rnd = rand(1111,99999);
        $remark = "{$srv_remark}-{$from_id}-{$rnd}";
    }
    
    if($portType == "auto"){
        file_put_contents('settings/temp.txt',$port.'-'.$last_num);
    }else{
        $port = rand(1111,65000);
    }
    if($inbound_id == 0){    
        $response = addUser($server_id, $uniqid, $protocol, $port, $expire_microdate, $remark, $volume, $netType, 'none', $rahgozar, $id); 
        if(! $response->success){
            $response = addUser($server_id, $uniqid, $protocol, $port, $expire_microdate, $remark, $volume, $netType, 'none', $rahgozar, $id);
        } 
    }else {
        $response = addInboundAccount($server_id, $uniqid, $inbound_id, $expire_microdate, $remark, $volume, $limitip, null, $id); 
        if(! $response->success){
            $response = addInboundAccount($server_id, $uniqid, $inbound_id, $expire_microdate, $remark, $volume, $limitip, null, $id);
        }
    }
    if(is_null($response)){
        alert('❌ | 🥺 گلم ، اتصال به سرور برقرار نیست لطفا مدیر رو در جریان بزار ...');
        exit;
    }
	if($response == "inbound not Found"){
        alert("❌ | 🥺 سطر (inbound) با آیدی $inbound_id تو این سرور وجود نداره ، مدیر رو در جریان بزار ...");
		exit;
	}
	if(!$response->success){
        alert('❌ | 😮 وای خطا داد لطفا سریع به مدیر بگو ...');
        exit;
    }
    alert('🚀 | 😍 در حال ارسال کانفیگ به مشتری ...');
    $vraylink = getConnectionLink($server_id, $uniqid, $protocol, $remark, $port, $netType, $inbound_id, $rahgozar, $customPath, $customPort, $customSni);
	include 'phpqrcode/qrlib.php';
    $token = RandomString(30);
    $subLink = $botState['subLinkState']=="on"?$botUrl . "settings/subLink.php?token=" . $token:"";
    
    foreach($vraylink as $vray_link){
        $acc_text = "
😍 سفارش جدید شما
📡 پروتکل: $protocol
🔮 نام سرویس: $remark
🔋حجم سرویس: $volume گیگ
⏰ مدت سرویس: $days روز
⁮⁮ ⁮⁮
💝 config : <code>$vray_link</code>";
if($botState['subLinkState'] == "on") $acc_text .= "

\n🌐 subscription : <code>$subLink</code>";
    
        $file = RandomString().".png";
        $ecc = 'L';
        $pixel_Size = 10;
        $frame_Size = 10;
        QRcode::png($vray_link, $file, $ecc, $pixel_Size, $frame_size);
    	addBorderImage($file);
        sendPhoto($botUrl . $file, $acc_text,json_encode(['inline_keyboard'=>[[['text'=>"صفحه اصلی 🏘",'callback_data'=>"mainMenu"]]]]),"HTML");
        unlink($file);
    }
    
    $vray_link = json_encode($vraylink);
	$stmt = $connection->prepare("INSERT INTO `orders_list` 
	    (`userid`, `token`, `transid`, `fileid`, `server_id`, `inbound_id`, `remark`, `protocol`, `expire_date`, `link`, `amount`, `status`, `date`, `notif`, `rahgozar`)
	    VALUES (?, ?, '', ?, ?, ?, ?, ?, ?, ?, ?,1, ?, 0, ?);");

	$stmt->bind_param("isiiissisiii", $from_id, $token, $id, $server_id, $inbound_id, $remark, $protocol, $expire_date, $vray_link, $price, $date, $rahgozar);
    $stmt->execute();
    $order = $stmt->get_result();
    $stmt->close();

    setUser('used','freetrial');    
}
if(preg_match('/^showMainButtonAns(\d+)/',$data,$match)){
    $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `id` = ?");
    $stmt->bind_param("i", $match[1]);
    $stmt->execute();
    $info = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    editText($message_id,$info['value'],json_encode(['inline_keyboard'=>[
        [['text'=>$buttonValues['back_button'],'callback_data'=>"mainMenu"]]
        ]]));
}
if($data=="rejectedAgentList"){
    $keys = getRejectedAgentList();
    if($keys != null){
        editText($message_id,"لیست کاربران رد شده از نمایندگی",$keys);
    }else alert("کاربری یافت نشد");
}
if(preg_match('/^releaseRejectedAgent(\d+)/',$data,$match)){
    $stmt = $connection->prepare("UPDATE `users` SET `is_agent` = 0 WHERE `userid` = ?");
    $stmt->bind_param("i", $match[1]);
    $stmt->execute();
    $stmt->close();
    
    alert($mainValues['saved_successfuly']);
    $keys = getRejectedAgentList();
    if($keys != null){
        editText($message_id,"لیست کاربران رد شده از نمایندگی",$keys);
    }else editText($message_id,"کاربری یافت نشد",json_encode(['inline_keyboard'=>[[['text'=>$buttonValues['back_to_main'],'callback_data'=>"managePanel"]]]]));
}
if($data=="showUUIDLeft" && ($botState['searchState']=="on" || $from_id== $admin)){
    delMessage();
    sendMessage($mainValues['send_config_uuid'],$cancelKey);
    setUser('showAccount');
}
if($userInfo['step'] == "showAccount" and $text != $buttonValues['cancel']){
    if(preg_match('/^vmess:\/\/(.*)/',$text,$match)){
        $jsonDecode = json_decode(base64_decode($match[1]),true);
        $text = $jsonDecode['id'];
    }elseif(preg_match('/^vless:\/\/(.*?)\@/',$text,$match)){
        $text = $match[1];
    }elseif(preg_match('/^trojan:\/\/(.*?)\@/',$text,$match)){
        $text = $match[1];
    }elseif(!preg_match('/[a-f0-9]{8}\-[a-f0-9]{4}\-4[a-f0-9]{3}\-(8|9|a|b)[a-f0-9]{3}\-[a-f0-9]{12}/', $text)){
        sendMessage($mainValues['not_correct_text']);
        exit();
    }
    
    sendMessage($mainValues['please_wait_message'], $removeKeyboard);
    $stmt = $connection->prepare("SELECT * FROM `server_config`");
    $stmt->execute();
    $serversList = $stmt->get_result();
    $stmt->close();
    $found = false;
    while($row = $serversList->fetch_assoc()){
        $serverId = $row['id'];

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

                        
                        $expiryDay = $packageInfo->expiryTime != 0?
                            floor(
                                (substr($packageInfo->expiryTime,0,-3)-time())/(60 * 60 * 24)
                                ):
                                "نامحدود";    
                        if(is_numeric($expiryDay)){
                            if($expiryDay<0) $expiryDay = 0;
                        }
                    }else{
                        $email = $clientsSettings[$settingKey]['email'];
                        $clientState = $list[$keys]->clientStats;
                        $emails = array_column($clientState,'email');
                        $emailKey = array_search($email,$emails);                    
             
                        if($clientState[$emailKey]->total != 0 || $clientState[$emailKey]->up != 0  ||  $clientState[$emailKey]->down != 0 || $clientState[$emailKey]->expiryTime != 0){
                    	    $configLocation = $list[$keys]->id . "_remark_" . $email;
                            $upload = sumerize($clientState[$emailKey]->up);
                            $download = sumerize($clientState[$emailKey]->down);
                            $total = $clientState[$emailKey]->total==0 && $list[$keys]->total !=0?$list[$keys]->total:$clientState[$emailKey]->total;
                            $leftMb = $total!=0?($total - $clientState[$emailKey]->up - $clientState[$emailKey]->down):"نامحدود";
                            if(is_numeric($leftMb)){
                                if($leftMb<0){
                                    $leftMb = 0;
                                }else{
                                    $leftMb = sumerize($total - $clientState[$emailKey]->up - $clientState[$emailKey]->down);
                                }
                            }
                            $totalUsed = sumerize($clientState[$emailKey]->up + $clientState[$emailKey]->down);
                            $total = $total!=0?sumerize($total):"نامحدود";
                            $expTime = $clientState[$emailKey]->expiryTime == 0 && $list[$keys]->expiryTime?$list[$keys]->expiryTime:$clientState[$emailKey]->expiryTime;
                            $expiryTime = $expTime != 0?jdate("Y-m-d H:i:s",substr($expTime,0,-3)):"نامحدود";
                            $expiryDay = $expTime != 0?
                                floor(
                                    ((substr($expTime,0,-3)-time())/(60 * 60 * 24))
                                    ):
                                    "نامحدود";
                            if(is_numeric($expiryDay)){
                                if($expiryDay<0) $expiryDay = 0;
                            }
                            $state = $clientState[$emailKey]->enable == true?$buttonValues['active']:$buttonValues['deactive'];
                            $remark = $email;
                        }
                        elseif($list[$keys]->total != 0 || $list[$keys]->up != 0  ||  $list[$keys]->down != 0 || $list[$keys]->expiryTime != 0){
                            $upload = sumerize($list[$keys]->up);
                            $download = sumerize($list[$keys]->down);
                            $configLocation = $list[$keys]->remark;
                            $leftMb = $list[$keys]->total!=0?($list[$keys]->total - $list[$keys]->up - $list[$keys]->down):"نامحدود";
                            if(is_numeric($leftMb)){
                                if($leftMb<0){
                                    $leftMb = 0;
                                }else{
                                    $leftMb = sumerize($list[$keys]->total - $list[$keys]->up - $list[$keys]->down);
                                }
                            }
                            $totalUsed = sumerize($list[$keys]->up + $list[$keys]->down);
                            $total = $list[$keys]->total!=0?sumerize($list[$keys]->total):"نامحدود";
                            $expiryTime = $list[$keys]->expiryTime != 0?jdate("Y-m-d H:i:s",substr($list[$keys]->expiryTime,0,-3)):"نامحدود";
                            $expiryDay = $list[$keys]->expiryTime != 0?
                                floor(
                                    ((substr($list[$keys]->expiryTime,0,-3)-time())/(60 * 60 * 24))
                                    ):
                                    "نامحدود";
                            if(is_numeric($expiryDay)){
                                if($expiryDay<0) $expiryDay = 0;
                            }
                            $state = $list[$keys]->enable == true?$buttonValues['active']:$buttonValues['deactive'];
                            $remark = $list[$keys]->remark;
                        }
                    }
                }

                $keys = json_encode(['inline_keyboard'=>[
                [
                    ['text'=>$state??" ",'callback_data'=>"wizwizch"],
                    ['text'=>"🔘 وضعیت اکانت 🔘",'callback_data'=>"wizwizch"],
                    ],
                [
					['text'=>$remark??" ",'callback_data'=>"wizwizch"],
                    ['text'=>"« نام اکانت »",'callback_data'=>"wizwizch"],
                    ],
                [
                    ['text'=>$upload?? " ",'callback_data'=>"wizwizch"],
                    ['text'=>"√ آپلود √",'callback_data'=>"wizwizch"],
                    ],
                [
                    ['text'=>$download??" ",'callback_data'=>"wizwizch"],
                    ['text'=>"√ دانلود √",'callback_data'=>"wizwizch"],
                    ],
                [
                    ['text'=>$total??" ",'callback_data'=>"wizwizch"],
                    ['text'=>"† حجم کلی †",'callback_data'=>"wizwizch"],
                    ],
                [
                    ['text'=>$leftMb??" ",'callback_data'=>"wizwizch"],
                    ['text'=>"~ حجم باقیمانده ~",'callback_data'=>"wizwizch"],
                    ],
                [
                    ['text'=>$expiryTime??" ",'callback_data'=>"wizwizch"],
                    ['text'=>"تاریخ اتمام",'callback_data'=>"wizwizch"],
                    ],
                [
                    ['text'=>$expiryDay??" ",'callback_data'=>"wizwizch"],
                    ['text'=>"تعداد روز باقیمانده",'callback_data'=>"wizwizch"],
                    ],
                (($botState['renewAccountState'] == "on" && $botState['updateConfigLinkState'] == "on")?
                    [
                        ['text'=>$buttonValues['renew_config'],'callback_data'=>"sConfigRenew" . $serverId],
                        ['text'=>$buttonValues['update_config_connection'],'callback_data'=>"sConfigUpdate" . $serverId],
                        ]:[]
                        ),
                (($botState['renewAccountState'] != "on" && $botState['updateConfigLinkState'] == "on")?
                    [
                        ['text'=>$buttonValues['update_config_connection'],'callback_data'=>"sConfigUpdate" . $serverId]
                        ]:[]
                        ),
                (($botState['renewAccountState'] == "on" && $botState['updateConfigLinkState'] != "on")?
                    [
                        ['text'=>$buttonValues['renew_config'],'callback_data'=>"sConfigRenew" . $serverId]
                        ]:[]
                        ),
                [['text'=>"صفحه اصلی",'callback_data'=>"mainMenu"]]
                ]]);
                setUser($configLocation, "temp");
                sendMessage("🔰مشخصات حسابت:",$keys,"MarkDown");
                break;
                

            }
        }
    }
    if(!$found){
         sendMessage("ای وای ، اطلاعاتت اشتباهه 😔",$cancelKey);
    }
}

if(preg_match('/sConfigRenew(\d+)/', $data,$match)){
    if($botState['sellState']=="off" && $from_id !=$admin){ alert($mainValues['bot_is_updating']); exit(); }
    
    alert($mainValues['please_wait_message']);
    $server_id = $match[1];
    if(empty($userInfo['temp'])){delMessage(); exit();}
    
    if(strpos($userInfo['temp'], "_remark_") !== FALSE){
        $param = explode("_remark_", $userInfo['temp']);
        $inboundId = $param[0];
        $remark = $param[1];
    }else{
        $inboundId = 0;
        $remark = $userInfo['temp'];
    }
    setUser($remark, "temp");
    $response = getJson($server_id)->obj;
    if($response == null){delMessage(); exit();}
    
    if($inboundId == 0){
        foreach($response as $row){
            if($row->remark == $remark) {
                $port = $row->port;
                $protocol = $row->protocol;
                $configReality = json_decode($row->streamSettings)->security == "reality"?"true":"false";
                break;
            }
        }
        $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `server_id` = ? AND `inbound_id` = 0 AND `protocol` = ? AND `active` = 1 AND `price` != 0 AND `rahgozar` = 0");
    }else{
        foreach($response as $row){
            if($row->id == $inboundId) {
                $port = $row->port;
                $protocol = $row->protocol;
                $configReality = json_decode($row->streamSettings)->security == "reality"?"true":"false";
                break;
            }
        }
        $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `server_id` = ? AND `inbound_id` != 0 AND `protocol` = ? AND `active` = 1 AND `price` != 0 AND `rahgozar` = 0");
    }
    
    $stmt->bind_param("is", $server_id, $protocol);
    $stmt->execute();
    $plans = $stmt->get_result();
    $stmt->close();
    if($plans->num_rows > 0){
        $keyboard = [];
        while($file = $plans->fetch_assoc()){ 
            $stmt = $connection->prepare("SELECT * FROM `server_config` WHERE `id` = ?");
            $stmt->bind_param("i", $server_id);
            $stmt->execute();
            $isReality = $stmt->get_result()->fetch_assoc()['reality'];
            $stmt->close();
            
            if($isReality == $configReality){
                $id = $file['id'];
                $name = $file['title'];
                $price = $file['price'];
                $price = ($price == 0) ? 'رایگان' : number_format($price).' تومان ';
                $keyboard[] = ['text' => "$name - $price", 'callback_data' => "sConfigRenewPlan{$id}_{$inboundId}"];
            }
        }
        $keyboard[] = ['text' => $buttonValues['back_to_main'], 'callback_data' => "mainMenu"];
        $keyboard = array_chunk($keyboard,1);
        editText($message_id, "3️⃣ مرحله سه:

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

    alert($mainValues['receving_information']);
    delMessage();
    $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `id`=? and `active`=1");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $respd = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    $stmt = $connection->prepare("SELECT * FROM `server_categories` WHERE `id`=?");
    $stmt->bind_param("i", $respd['catid']);
    $stmt->execute();
    $catname = $stmt->get_result()->fetch_assoc()['title'];
    $stmt->close();
    
    $name = $catname." ".$respd['title'];
    $desc = $respd['descr'];
	$sid = $respd['server_id'];
	$keyboard = array();
    $price =  $respd['price'];
    $token = base64_encode("{$from_id}.{$id}");
    $temp = array();
    
    $hash_id = RandomString();
    $stmt = $connection->prepare("DELETE FROM `pays` WHERE `user_id` = ? AND `type` = 'RENEW_SCONFIG' AND `state` = 'pending'");
    $stmt->bind_param("i", $from_id);
    $stmt->execute();
    $stmt->close();
    $remark = $userInfo['temp'];
    setUser('', 'temp');
    
    $time = time();
    $stmt = $connection->prepare("INSERT INTO `pays` (`hash_id`, `description`, `user_id`, `type`, `plan_id`, `volume`, `day`, `price`, `request_date`, `state`)
                                VALUES (?, ?, ?, 'RENEW_SCONFIG', ?, ?, '0', ?, ?, 'pending')");
    $stmt->bind_param("ssiiiii", $hash_id, $remark, $from_id, $id, $inbound_id, $price, $time);
    $stmt->execute();
    $rowId = $stmt->insert_id;
    $stmt->close();

    
    if($botState['cartToCartState'] == "on"){
	    $temp[] = ['text' => $buttonValues['cart_to_cart'],  'callback_data' => "payWithCartToCart$hash_id"];
    }
    if($botState['nowPaymentOther'] == "on"){
	    $temp[] = ['text' => $buttonValues['now_payment_gateway'],  'url' => $botUrl . "pay/?nowpayment&hash_id=" . $hash_id];
    }
    if(count($temp) == 2){
        array_push($keyboard, $temp);
        $temp = array();
    }
    if($botState['zarinpal'] == "on"){
	    $temp[] = ['text' => $buttonValues['zarinpal_gateway'],  'url' => $botUrl . "pay/?zarinpal&hash_id=" . $hash_id];
    }
    if(count($temp) == 2){
        array_push($keyboard, $temp);
        $temp = array();
    }
    if($botState['nextpay'] == "on"){
	    $temp[] = ['text' => $buttonValues['nextpay_gateway'],  'url' => $botUrl . "pay/?nextpay&hash_id=" . $hash_id];
    }
    if(count($temp) == 2){
        array_push($keyboard, $temp);
        $temp = array();
    }
    if($botState['weSwapState'] == "on"){
	    $temp[] = ['text' => $buttonValues['weswap_gateway'],  'callback_data' => "payWithWeSwap" . $hash_id];
    }
    if(count($temp) == 2){
        array_push($keyboard, $temp);
        $temp = array();
    }
    if($botState['walletState'] == "on"){
	    $temp[] = ['text' => $buttonValues['pay_with_wallet'],  'callback_data' => "payWithWallet$hash_id"];
    }
    array_push($keyboard, $temp);

	$keyboard[] = [['text' => $buttonValues['back_to_main'], 'callback_data' => "mainMenu"]];
    sendMessage(str_replace(['PLAN-NAME', 'PRICE', 'DESCRIPTION'], [$name, $price, $desc], $mainValues['buy_subscription_detail']), json_encode(['inline_keyboard'=>$keyboard]), "HTML");
}
if(preg_match('/sConfigUpdate(\d+)/', $data,$match)){
    alert($mainValues['please_wait_message']);
    $server_id = $match[1];
    if(empty($userInfo['temp'])){delMessage(); exit();}
    
    if(strpos($userInfo['temp'], "_remark_") !== FALSE){
        $param = explode("_remark_", $userInfo['temp']);
        $inboundId = $param[0];
        $remark = $param[1];
    }else{
        $inboundId = 0;
        $remark = $userInfo['temp'];
    }
    
    $response = getJson($server_id)->obj;
    if($response == null){delMessage(); exit();}
    
    if($inboundId == 0){
        foreach($response as $row){
            if($row->remark == $remark) {
                $port = $row->port;
                $protocol = $row->protocol;
                $netType = json_decode($row->streamSettings)->network;
                $settings = json_decode($row->settings, true);
                $clients = $settings['clients'];
                $uuid = $clients[0]['id'];
                break;
            }
        }
    }else{
        foreach($response as $row){
            if($row->id == $inboundId) {
                $port = $row->port;
                $protocol = $row->protocol;
                $netType = json_decode($row->streamSettings)->network;
                $settings = json_decode($row->settings, true);
                $clients = $settings['clients'];
                foreach($clients as $key => $client) {
                    if($client['email'] == $remark) {
                        $uuid = $client['id'];
                        break;
                    }
                }
                break;
            }
        }
    }
    
    if($uuid == null){delMessage(); exit();}
    $vraylink = getConnectionLink($server_id, $uuid, $protocol, $remark, $port, $netType, $inboundId);
    
    if($vraylink == null){delMessage(); exit();}
    foreach($vraylink as $vray_link){
        $acc_text = "<code>$vray_link</code>";
    
        $ecc = 'L';
        $pixel_Size = 10;
        $frame_Size = 10;
        
        include 'phpqrcode/qrlib.php';  
        $file = RandomString() .".png";
        QRcode::png($vray_link, $file, $ecc, $pixel_Size, $frame_Size);
    	addBorderImage($file);
        sendPhoto($botUrl . $file, $acc_text,null,"HTML");
        unlink($file);
    }
}

if (($data == 'addNewPlan' || $data=="addNewRahgozarPlan") and (($from_id == $admin || $userInfo['isAdmin'] == true))){
    setUser($data);
    $stmt = $connection->prepare("DELETE FROM `server_plans` WHERE `active`=0");
    $stmt->execute();
    $stmt->close();
    if($data=="addNewPlan"){
        $sql = "INSERT INTO `server_plans` (`fileid`, `catid`, `server_id`, `inbound_id`, `acount`, `limitip`, `title`, `protocol`, `days`, `volume`, `type`, `price`, `descr`, `pic`, `active`, `step`, `date`)
                                            VALUES ('', 0,0,0,0, 1, '', '', 0, 0, '', 0, '', '',0,1, ?);";
    }elseif($data=="addNewRahgozarPlan"){
        $sql = "INSERT INTO `server_plans` (`fileid`, `catid`, `server_id`, `inbound_id`, `acount`, `limitip`, `title`, `protocol`, `days`, `volume`, `type`, `price`, `descr`, `pic`, `active`, `step`, `date`, `rahgozar`)
                    VALUES ('', 0,0,0,0, 1, '', '', 0, 0, '', 0, '', '',0,1, ?, 1);";
    }
    $stmt = $connection->prepare($sql);
    $stmt->bind_param("i", $time);
    $stmt->execute();
    $stmt->close();
    delMessage();
    $msg = '❗️یه عنوان برا پلن انتخاب کن:';
    sendMessage($msg,$cancelKey);
    exit;
}
if(preg_match('/(addNewRahgozarPlan|addNewPlan)/',$userInfo['step']) and $text!=$buttonValues['cancel']){
    $catkey = [];
    $stmt = $connection->prepare("SELECT * FROM `server_categories` WHERE `parent` =0 and `active`=1");
    $stmt->execute();
    $cats = $stmt->get_result();
    $stmt->close();

    while ($cat = $cats->fetch_assoc()){
        $id = $cat['id'];
        $name = $cat['title'];
        $catkey[] = ["$id - $name"];
    }
    $catkey[] = [$buttonValues['cancel']];

    $step = checkStep('server_plans');

    if($step==1 and $text!=$buttonValues['cancel']){
        $msg = '🔰 لطفا قیمت پلن رو به تومان وارد کنید!';
        if(strlen($text)>1){
            $stmt = $connection->prepare("UPDATE `server_plans` SET `title`=?,`step`=2 WHERE `active`=0 and `step`=1");
            $stmt->bind_param("s", $text);
            $stmt->execute();
            $stmt->close();
            sendMessage($msg,$cancelKey);
        }
    } 
    if($step==2 and $text!=$buttonValues['cancel']){
        $msg = '🔰لطفا یه دسته از لیست زیر برا پلن انتخاب کن ';
        if(is_numeric($text)){
            $stmt = $connection->prepare("UPDATE `server_plans` SET `price`=?,`step`=3 WHERE `active`=0");
            $stmt->bind_param("s", $text);
            $stmt->execute();
            $stmt->close();
            sendMessage($msg,json_encode(['keyboard'=>$catkey]));
        }else{
            $msg = '‼️ لطفا یک مقدار عددی وارد کنید';
            sendMessage($msg,$cancelKey);
        }
    } 
    if($step==3 and $text!=$buttonValues['cancel']){
        $srvkey = [];
        $stmt = $connection->prepare("SELECT * FROM `server_info` WHERE `active`=1");
        $stmt->execute();
        $srvs = $stmt->get_result();
        $stmt->close();
        sendMessage($mainValues['please_wait_message'],$cancelKey);
        while($srv = $srvs->fetch_assoc()){
            $id = $srv['id'];
            $title = $srv['title'];
            $srvkey[] = ['text' => "$title", 'callback_data' => "selectNewPlanServer$id"];
        }
        $srvkey = array_chunk($srvkey,2);
        sendMessage("لطفا یکی از سرورها رو انتخاب کن 👇 ", json_encode([
                'inline_keyboard' => $srvkey]), "HTML");
        $inarr = 0;
        foreach ($catkey as $op) {
            if (in_array($text, $op) and $text != $buttonValues['cancel']) {
                $inarr = 1;
            }
        }
        if( $inarr==1 ){
            $input = explode(' - ',$text);
            $catid = $input[0];
            $stmt = $connection->prepare("UPDATE `server_plans` SET `catid`=?,`step`=50 WHERE `active`=0");
            $stmt->bind_param("i", $catid);
            $stmt->execute();
            $stmt->close();

            sendMessage($msg,$cancelKey);
        }else{
            $msg = '‼️ لطفا فقط یکی از گزینه های پیشنهادی زیر را انتخاب کنید';
            sendMessage($msg,$catkey);
        }
    } 
    if($step==50 and $text!=$buttonValues['cancel'] and preg_match('/selectNewPlanServer(\d+)/', $data,$match)){
        $stmt = $connection->prepare("UPDATE `server_plans` SET `server_id`=?,`step`=51 WHERE `active`=0");
        $stmt->bind_param("i", $match[1]);
        $stmt->execute();
        $stmt->close();

        $keys = json_encode(['inline_keyboard'=>[
            [['text'=>"🎖پورت اختصاصی",'callback_data'=>"withSpecificPort"]],
            [['text'=>"🎗پورت اشتراکی",'callback_data'=>"withSharedPort"]]
            ]]);
        editText($message_id, "لطفا نوعیت پورت پنل رو انتخاب کنید", $keys);
    }
    if($step==51 and $text!=$buttonValues['cancel'] and preg_match('/^with(Specific|Shared)Port/',$data,$match)){
        if($userInfo['step'] == "addNewRahgozarPlan") $msg =  "📡 | لطفا پروتکل پلن مورد نظر را وارد کنید (vless | vmess)";
        else $msg =  "📡 | لطفا پروتکل پلن مورد نظر را وارد کنید (vless | vmess | trojan)";
        editText($message_id,$msg);
        if($match[1] == "Shared"){
            $stmt = $connection->prepare("UPDATE `server_plans` SET `step`=60 WHERE `active`=0");
            $stmt->execute();
            $stmt->close();
        }
        elseif($match[1] == "Specific"){
            $stmt = $connection->prepare("UPDATE server_plans SET step=52 WHERE active=0");
            $stmt->execute();
            $stmt->close();
        }
    }
    if($step==60 and $text!=$buttonValues['cancel']){
        if($text != "vless" && $text != "vmess" && $text != "trojan" && $userInfo['step'] == "addNewPlan"){
            sendMessage("لطفا فقط پروتکل های vless و vmess را وارد کنید",$cancelKey);
            exit();
        }
        elseif($text != "vless" && $text != "vmess" && $userInfo['step'] == "addNewRahgozarPlan"){
            sendMessage("لطفا فقط پروتکل های vless و vmess را وارد کنید",$cancelKey);
            exit();
        }
        
        $stmt = $connection->prepare("UPDATE `server_plans` SET `protocol`=?,`step`=61 WHERE `active`=0");
        $stmt->bind_param("s", $text);
        $stmt->execute();
        $stmt->close();
        sendMessage("📅 | لطفا تعداد روز های اعتبار این پلن را وارد کنید:");
    }
    if($step==61 and $text!=$buttonValues['cancel']){
        if(!is_numeric($text)){
            sendMessage($mainValues['send_only_number']);
            exit();
        }
        
        $stmt = $connection->prepare("UPDATE `server_plans` SET `days`=?,`step`=62 WHERE `active`=0");
        $stmt->bind_param("i", $text);
        $stmt->execute();
        $stmt->close();

        sendMessage("🔋 | لطفا مقدار حجم به GB این پلن را وارد کنید:");
    }
    if($step==62 and $text!=$buttonValues['cancel']){
        if(!is_numeric($text)){
            sendMessage($mainValues['send_only_number']);
            exit();
        }
        
        $stmt = $connection->prepare("UPDATE `server_plans` SET `volume`=?,`step`=63 WHERE `active`=0");
        $stmt->bind_param("d", $text);
        $stmt->execute();
        $stmt->close();
        sendMessage("🛡 | لطفا آیدی سطر کانکشن در پنل را وارد کنید:");
    }
    if($step==63 and $text!=$buttonValues['cancel']){
        if(!is_numeric($text)){
            sendMessage($mainValues['send_only_number']);
            exit();
        }
        
        $stmt = $connection->prepare("UPDATE `server_plans` SET `inbound_id`=?,`step`=64 WHERE `active`=0");
        $stmt->bind_param("i", $text);
        $stmt->execute();
        $stmt->close();

        sendMessage("لطفا ظرفیت تعداد اکانت رو پورت مورد نظر را وارد کنید");
    }
    if($step==64 and $text!=$buttonValues['cancel']){
        if(!is_numeric($text)){
            sendMessage($mainValues['send_only_number']);
            exit();
        }
        
        $stmt = $connection->prepare("UPDATE `server_plans` SET `acount`=?,`step`=65 WHERE `active`=0");
        $stmt->bind_param("i", $text);
        $stmt->execute();
        $stmt->close();

        sendMessage("🧲 | لطفا تعداد چند کاربره این پلن را وارد کنید ( 0 نامحدود است )");
    }
    if($step==65 and $text!=$buttonValues['cancel']){
        if(!is_numeric($text)){
            sendMessage($mainValues['send_only_number']);
            exit();
        }
        $stmt = $connection->prepare("UPDATE `server_plans` SET `limitip`=?,`step`=4 WHERE `active`=0");
        $stmt->bind_param("s", $text);
        $stmt->execute();
        $stmt->close();

        $msg = '🔻یه توضیح برای پلن مورد نظرت بنویس:';
        sendMessage($msg,$cancelKey); 
    }
    if($step==52 and $text!=$buttonValues['cancel']){
        if($userInfo['step'] == "addNewPlan" && $text != "vless" && $text != "vmess" && $text != "trojan"){
            sendMessage("لطفا فقط پروتکل های vless و vmess را وارد کنید",$cancelKey);
            exit();
        }elseif($userInfo['step'] == "addNewRahgozarPlan" && $text != "vless" && $text != "vmess"){
            sendMessage("لطفا فقط پروتکل های vless و vmess را وارد کنید",$cancelKey);
            exit();
        }
        
        $stmt = $connection->prepare("UPDATE `server_plans` SET `protocol`=?,`step`=53 WHERE `active`=0");
        $stmt->bind_param("s", $text);
        $stmt->execute();
        $stmt->close();

        sendMessage("📅 | لطفا تعداد روز های اعتبار این پلن را وارد کنید:");
    }
    if($step==53 and $text!=$buttonValues['cancel']){
        if(!is_numeric($text)){
            sendMessage($mainValues['send_only_number']);
            exit();
        }
        
        $stmt = $connection->prepare("UPDATE `server_plans` SET `days`=?,`step`=54 WHERE `active`=0");
        $stmt->bind_param("i", $text);
        $stmt->execute();
        $stmt->close();

        sendMessage("🔋 | لطفا مقدار حجم به GB این پلن را وارد کنید:");
    }
    if($step==54 and $text!=$buttonValues['cancel']){
        if(!is_numeric($text)){
            sendMessage($mainValues['send_only_number']);
            exit();
        }
        
        if($userInfo['step'] == "addNewPlan"){
            $sql = ("UPDATE `server_plans` SET `volume`=?,`step`=55 WHERE `active`=0");
            $msg = "🔉 | لطفا نوع شبکه این پلن را در انتخاب کنید  (ws | tcp | grpc) :";
        }elseif($userInfo['step'] == "addNewRahgozarPlan"){
            $sql = ("UPDATE `server_plans` SET `volume`=?, `type`='ws', `step`=4 WHERE `active`=0");
            $msg = '🔻یه توضیح برای پلن مورد نظرت بنویس:';
        }
        $stmt = $connection->prepare($sql);
        $stmt->bind_param("d", $text);
        $stmt->execute();
        $stmt->close();

        sendMessage($msg);
    }
    if($step==55 and $text!=$buttonValues['cancel']){
        if($text != "tcp" && $text != "ws" && $text != "grpc"){
            sendMessage("لطفا فقط نوع (ws | tcp | grpc) را وارد کنید");
            exit();
        }
        $stmt = $connection->prepare("UPDATE `server_plans` SET `type`=?,`step`=4 WHERE `active`=0");
        $stmt->bind_param("s", $text);
        $stmt->execute();
        $stmt->close();


        $msg = '🔻یه توضیح برای پلن مورد نظرت بنویس:';
        sendMessage($msg,$cancelKey); 
    }
    
    if($step==4 and $text!=$buttonValues['cancel']){
        $imgtxt = '☑️ | پنل با موفقیت ثبت و ایجاد شد ( لذت ببرید ) ';
        $stmt = $connection->prepare("UPDATE `server_plans` SET `descr`=?, `active`=1,`step`=10 WHERE `step`=4");
        $stmt->bind_param("s", $text);
        $stmt->execute();
        $stmt->close();

        sendMessage($imgtxt,$removeKeyboard);
        sendMessage($mainValues['reached_main_menu'],getAdminKeys());
        setUser();
    } 
}
if($data == 'backplan' and ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $stmt = $connection->prepare("SELECT * FROM `server_info` WHERE `active`=1");
    $stmt->execute();
    $res = $stmt->get_result();
    $stmt->close();

    $keyboard = [];
    while($cat = $res->fetch_assoc()){
        $id = $cat['id'];
        $title = $cat['title'];
        $keyboard[] = ['text' => "$title", 'callback_data' => "plansList$id"];
    }
    $keyboard = array_chunk($keyboard,2);
    $keyboard[] = [['text'=>"➖➖➖",'callback_data'=>"wizwizch"]];
    $keyboard[] = [['text'=>'➕ افزودن پلن اختصاصی و اشتراکی','callback_data'=>"addNewPlan"]];
    $keyboard[] = [['text'=>'➕ افزودن پلن رهگذر','callback_data'=>"addNewRahgozarPlan"]];
    $keyboard[] = [['text'=>'➕ افزودن پلن حجمی','callback_data'=>"volumePlanSettings"],['text'=>'➕ افزودن پلن زمانی','callback_data'=>"dayPlanSettings"]];
    $keyboard[] = [['text' => "➕ افزودن پلن دلخواه", 'callback_data' => "editCustomPlan"]];
    $keyboard[] = [['text' => $buttonValues['back_button'], 'callback_data' => "managePanel"]];

    $msg = ' ☑️ مدیریت پلن ها:';
    
    if(isset($data) and $data=='backplan') {
        editText($message_id, $msg, json_encode(['inline_keyboard'=>$keyboard]));
    }else { sendAction('typing');
        sendmessage($msg, json_encode(['inline_keyboard'=>$keyboard]));
    }
    
    
    exit;
}
if(($data=="editCustomPlan" || preg_match('/^editCustom(gbPrice|dayPrice)/',$userInfo['step'],$match)) && ($from_id == $admin || $userInfo['isAdmin'] == true) && $text != $buttonValues['cancel']){
    if(!isset($data)){
        if(is_numeric($text)){
            $botState[$match[1]] = $text;
            
            $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'BOT_STATES'");
            $stmt->execute();
            $isExists = $stmt->get_result();
            $stmt->close();
            if($isExists->num_rows>0) $query = "UPDATE `setting` SET `value` = ? WHERE `type` = 'BOT_STATES'";
            else $query = "INSERT INTO `setting` (`type`, `value`) VALUES ('BOT_STATES', ?)";
            $newData = json_encode($botState);
            
            $stmt = $connection->prepare($query);
            $stmt->bind_param("s", $newData);
            $stmt->execute();
            $stmt->close();
            
            sendMessage($mainValues['saved_successfuly'],$removeKeyboard); 
        }else{
            sendMessage("فقط عدد ارسال کن");
            exit();
        }
    }
    $gbPrice=number_format($botState['gbPrice']??0) . " تومان";
    $dayPrice=number_format($botState['dayPrice']??0) . " تومان";
    
    $keys = json_encode(['inline_keyboard'=>[
        [
            ['text'=>$gbPrice,'callback_data'=>"editCustomgbPrice"],
            ['text'=>"هزینه هر گیگ",'callback_data'=>"wizwizch"]
            ],
        [
            ['text'=>$dayPrice,'callback_data'=>"editCustomdayPrice"],
            ['text'=>"هزینه هر روز",'callback_data'=>"wizwizch"]
            ],
        [
            ['text'=>$buttonValues['back_button'],'callback_data'=>"backplan"]
            ]
            
        ]]);
    if(!isset($data)){
        sendMessage("تنظیمات پلن دلخواه",$keys);
        setUser();
    }else{
        editText($message_id,"تنظیمات پلن دلخواه",$keys);
    }
}
if(preg_match('/^editCustom(gbPrice|dayPrice)/',$data,$match)){
    delMessage();
    $title = $match[1] == "dayPrice"?"هر روز":"هر گیگ";
    sendMessage("لطفا هزینه " . $title . " را به تومان وارد کنید",$cancelKey);
    setUser($data);
}
if(preg_match('/plansList(\d+)/', $data,$match)){
    $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `server_id`=? ORDER BY`id` ASC");
    $stmt->bind_param("i", $match[1]);
    $stmt->execute();
    $res = $stmt->get_result();
    $stmt->close();

    if($res->num_rows==0){
        alert("متاسفانه، هیچ پلنی براش انتخاب نکردی 😑");
        exit;
    }else {
        $keyboard = [];
        while($cat = $res->fetch_assoc()){
            $id = $cat['id'];
            $title = $cat['title'];
            $keyboard[] = ['text' => "#$id $title", 'callback_data' => "planDetails$id"];
        }
        $keyboard = array_chunk($keyboard,2);
        $keyboard[] = [['text' => $buttonValues['back_button'], 'callback_data' => "backplan"],];
        $msg = ' ▫️ یه پلن رو انتخاب کن بریم برای ادیت:';
        editText($message_id, $msg, json_encode(['inline_keyboard'=>$keyboard]), "HTML");
    }
    exit();
}
if(preg_match('/planDetails(\d+)/', $data,$match)){
    $keys = getPlanDetailsKeys($match[1]);
    if($keys == null){
        alert("موردی یافت نشد");
        exit;
    }else editText($message_id, "ویرایش تنظیمات پلن", $keys, "HTML");
}
if(preg_match('/^wizwizplanacclist(\d+)/',$data,$match) and ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `status`=1 AND `fileid`=?");
    $stmt->bind_param("i", $match[1]);
    $stmt->execute();
    $res = $stmt->get_result();
    $stmt->close();

    if($res->num_rows == 0){
        alert('لیست خالی است');
        exit;
    }
    $txt = '';
    while($order = $res->fetch_assoc()){
		$suid = $order['userid'];
		$stmt = $connection->prepare("SELECT * FROM `users` WHERE `userid`=?");
        $stmt->bind_param("i", $suid);
        $stmt->execute();
        $ures = $stmt->get_result()->fetch_assoc();
        $stmt->close();


        $date = $order['date'];
        $remark = $order['remark'];
        $date = jdate('Y-m-d H:i', $date);
        $uname = $ures['name'];
        $sold = " 🚀 ".$uname. " ($date)";
        $accid = $order['id'];
        $orderLink = json_decode($order['link'],true);
        $txt = "$sold \n  ☑️ $remark ";
        foreach($orderLink as $link){
            $txt .= "<code>".$link."</code> \n";
        }
        $txt .= "\n ❗ $channelLock \n";
        sendMessage($txt, null, "HTML");
    }
}
if(preg_match('/^wizwizplandelete(\d+)/',$data,$match) and ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $stmt = $connection->prepare("DELETE FROM `server_plans` WHERE `id`=?");
    $stmt->bind_param("i", $match[1]);
    $stmt->execute();
    $stmt->close();
    alert("پلن رو برات حذفش کردم ☹️☑️");
    
    editText($message_id,"لطفا یکی از کلید های زیر را انتخاب کنید",getMainKeys());
}
if(preg_match('/^wizwizplanname(\d+)/',$data) and ($from_id == $admin || $userInfo['isAdmin'] == true) && $text != $buttonValues['cancel']){
    setUser($data);
    delMessage();
    sendMessage("🔅 یه اسم برا پلن جدید انتخاب کن:",$cancelKey);exit;
}
if(preg_match('/^wizwizplanname(\d+)/',$userInfo['step'], $match) && $text != $buttonValues['cancel']){
    $stmt = $connection->prepare("UPDATE `server_plans` SET `title`=? WHERE `id`=?");
    $stmt->bind_param("si", $text, $match[1]);
    $stmt->execute();
    $stmt->close();

    sendMessage("با موفقیت برات تغییر دادم ☺️☑️");
    setUser();
    
    $keys = getPlanDetailsKeys($match[1]);
    if($keys == null){
        alert("موردی یافت نشد");
        exit;
    }else sendMessage("ویرایش تنظیمات پلن", $keys);
}
if(preg_match('/^wizwizplanslimit(\d+)/',$data) and ($from_id == $admin || $userInfo['isAdmin'] == true) && $text != $buttonValues['cancel']){
    setUser($data);
    delMessage();
    sendMessage("🔅 ظرفیت جدید برای پلن انتخاب کن:",$cancelKey);exit;
}
if(preg_match('/^wizwizplanslimit(\d+)/',$userInfo['step'], $match) && $text != $buttonValues['cancel']){
    $stmt = $connection->prepare("UPDATE `server_plans` SET `acount`=? WHERE `id`=?");
    $stmt->bind_param("ii", $text, $match[1]);
    $stmt->execute();
    $stmt->close();

    sendMessage("با موفقیت برات تغییر دادم ☺️☑️");
    setUser();
    
    $keys = getPlanDetailsKeys($match[1]);
    if($keys == null){
        alert("موردی یافت نشد");
        exit;
    }else sendMessage("ویرایش تنظیمات پلن", $keys, "HTML");
}
if(preg_match('/^wizwizplansinobundid(\d+)/',$data) and ($from_id == $admin || $userInfo['isAdmin'] == true) && $text != $buttonValues['cancel']){
    setUser($data);
    delMessage();
    sendMessage("🔅 سطر جدید برای پلن انتخاب کن:",$cancelKey);exit;
}
if(preg_match('/^wizwizplansinobundid(\d+)/',$userInfo['step'], $match) && $text != $buttonValues['cancel']){
    $stmt = $connection->prepare("UPDATE `server_plans` SET `inbound_id`=? WHERE `id`=?");
    $stmt->bind_param("ii", $text, $match[1]);
    $stmt->execute();
    $stmt->close();

    sendMessage("با موفقیت برات تغییر دادم ☺️☑️");
    setUser();
    
    $keys = getPlanDetailsKeys($match[1]);
    if($keys == null){
        alert("موردی یافت نشد");
        exit;
    }else sendMessage("ویرایش تنظیمات پلن", $keys, "HTML");
}
if(preg_match('/^wizwizplaneditdes(\d+)/',$data) and ($from_id == $admin || $userInfo['isAdmin'] == true) && $text != $buttonValues['cancel']){
    setUser($data);
    delMessage();
    sendMessage("🎯 توضیحاتت رو برام وارد کن:",$cancelKey);exit;
}
if(preg_match('/^wizwizplaneditdes(\d+)/',$userInfo['step'], $match) && $text != $buttonValues['cancel']){
    $stmt = $connection->prepare("UPDATE `server_plans` SET `descr`=? WHERE `id`=?");
    $stmt->bind_param("si", $text, $match[1]);
    $stmt->execute();
    $stmt->close();


    sendMessage("با موفقیت برات تغییر دادم ☺️☑️");
    setUser();
    
    $keys = getPlanDetailsKeys($match[1]);
    if($keys == null){
        alert("موردی یافت نشد");
        exit;
    }else sendMessage("ویرایش تنظیمات پلن", $keys, "HTML");
}
if(preg_match('/^editDestName(\d+)/',$data) and ($from_id == $admin || $userInfo['isAdmin'] == true) && $text != $buttonValues['cancel']){
    setUser($data);
    delMessage();
    sendMessage("🎯 dest رو برام وارد کن:\nبرای حذف کردن متن /empty رو وارد کن",$cancelKey);exit;
}
if(preg_match('/^editDestName(\d+)/',$userInfo['step'], $match) && $text != $buttonValues['cancel']){
    if($text == "/empty"){
        $stmt = $connection->prepare("UPDATE `server_plans` SET `dest` = NULL WHERE `id`=?");
        $stmt->bind_param("i", $match[1]);
    }else{
        $stmt = $connection->prepare("UPDATE `server_plans` SET `dest`=? WHERE `id`=?");
        $stmt->bind_param("si", $text, $match[1]);
    }
    $stmt->execute();
    $stmt->close();


    sendMessage("با موفقیت برات تغییر دادم ☺️☑️");
    setUser();
    
    $keys = getPlanDetailsKeys($match[1]);
    if($keys == null){
        alert("موردی یافت نشد");
        exit;
    }else sendMessage("ویرایش تنظیمات پلن", $keys, "HTML");
}
if(preg_match('/^editSpiderX(\d+)/',$data) and ($from_id == $admin || $userInfo['isAdmin'] == true) && $text != $buttonValues['cancel']){
    setUser($data);
    delMessage();
    sendMessage("🎯 spiderX رو برام وارد کن\nبرای حذف کردن متن /empty رو وارد کن",$cancelKey);exit;
}
if(preg_match('/^editSpiderX(\d+)/',$userInfo['step'], $match) && $text != $buttonValues['cancel']){
    if($text == "/empty"){
        $stmt = $connection->prepare("UPDATE `server_plans` SET `spiderX`=NULL WHERE `id`=?");
        $stmt->bind_param("s", $match[1]);
    }else{
        $stmt = $connection->prepare("UPDATE `server_plans` SET `spiderX`=? WHERE `id`=?");
        $stmt->bind_param("si", $text, $match[1]);
    }
    $stmt->execute();
    $stmt->close();


    sendMessage("با موفقیت برات تغییر دادم ☺️☑️");
    setUser();
    
    $keys = getPlanDetailsKeys($match[1]);
    if($keys == null){
        alert("موردی یافت نشد");
        exit;
    }else sendMessage("ویرایش تنظیمات پلن", $keys, "HTML");
}
if(preg_match('/^editServerNames(\d+)/',$data) and ($from_id == $admin || $userInfo['isAdmin'] == true) && $text != $buttonValues['cancel']){
    setUser($data);
    delMessage();
    sendMessage("🎯 serverNames رو به صورت زیر برام وارد کن:\n
`[
  \"yahoo.com\",
  \"www.yahoo.com\"
]`
    \n\nبرای حذف کردن متن /empty رو وارد کن",$cancelKey);exit;
}
if(preg_match('/^editServerNames(\d+)/',$userInfo['step'], $match) && $text != $buttonValues['cancel']){
    if($text == "/empty"){
        $stmt = $connection->prepare("UPDATE `server_plans` SET `serverNames`=NULL WHERE `id`=?");
        $stmt->bind_param("s", $match[1]);
    }else{
        $stmt = $connection->prepare("UPDATE `server_plans` SET `serverNames`=? WHERE `id`=?");
        $stmt->bind_param("si", $text, $match[1]);
    }
    $stmt->execute();
    $stmt->close();


    sendMessage("با موفقیت برات تغییر دادم ☺️☑️");
    setUser();
    
    $keys = getPlanDetailsKeys($match[1]);
    if($keys == null){
        alert("موردی یافت نشد");
        exit;
    }else sendMessage("ویرایش تنظیمات پلن", $keys, "HTML");
}
if(preg_match('/^editFlow(\d+)/',$data, $match) and ($from_id == $admin || $userInfo['isAdmin'] == true) && $text != $buttonValues['cancel']){
    setUser($data);
    delMessage();
    $keys = json_encode(['inline_keyboard'=>[
        [['text'=>"None", 'callback_data'=>"editPFlow" . $match[1] . "_None"]],
        [['text'=>"xtls-rprx-vision", 'callback_data'=>"editPFlow" . $match[1] . "_xtls-rprx-vision"]],
        ]]);
    sendMessage("🎯 لطفا یکی از موارد زیر رو انتخاب کن",$keys);exit;
}
if(preg_match('/^editPFlow(\d+)_(.*)/',$data, $match) && $text != $buttonValues['cancel']){
    $stmt = $connection->prepare("UPDATE `server_plans` SET `flow`=? WHERE `id`=?");
    $stmt->bind_param("si", $match[2], $match[1]);
    $stmt->execute();
    $stmt->close();

    alert("با موفقیت برات تغییر دادم ☺️☑️");
    setUser();
    
    $keys = getPlanDetailsKeys($match[1]);
    editText($message_id, "ویرایش تنظیمات پلن", $keys, "HTML");
}
if(preg_match('/^wizwizplanrial(\d+)/',$data) and ($from_id == $admin || $userInfo['isAdmin'] == true) && $text != $buttonValues['cancel']){
    setUser($data);
    delMessage();
    sendMessage("🎯 شیطون قیمت و گرون کردی 😂 ، خب قیمت جدید و بزن ببینم :",$cancelKey);exit;
}
if(preg_match('/^wizwizplanrial(\d+)/',$userInfo['step'], $match) && $text != $buttonValues['cancel']){
    if(is_numeric($text)){
        $stmt = $connection->prepare("UPDATE `server_plans` SET `price`=? WHERE `id`=?");
        $stmt->bind_param("ii", $text, $match[1]);
        $stmt->execute();
        $stmt->close();

        sendMessage("با موفقیت برات تغییر دادم ☺️☑️");
        setUser();
        
        $keys = getPlanDetailsKeys($match[1]);
        if($keys == null){
            alert("موردی یافت نشد");
            exit;
        }else sendMessage("ویرایش تنظیمات پلن", $keys, "HTML");
    }else{
        sendMessage("بهت میگم قیمت وارد کن برداشتی یه چیز دیگه نوشتی 🫤 ( عدد وارد کن ) عجبا");
    }
}
if(($data == 'mySubscriptions' || $data == 'myServices' || $data == "agentConfigsList" or preg_match('/(changeAgentOrder|changeOrdersPage)(\d+)/',$data, $match) )&& ($botState['sellState']=="on" || $from_id ==$admin)){
    
    // ========================================
    // صفحه یکپارچه: نمایش همه سرویس‌ها به سبک حساب کاربری
    // ========================================
    
    // 1️⃣ شمارش سرویس‌های قدیمی
    if($data == "agentConfigsList" || $match[1] == "changeAgentOrder") {
        $stmt = $connection->prepare("SELECT COUNT(*) as total FROM `orders_list` WHERE `userid`=? AND `status`=1 AND `agent_bought` = 1");
    } else {
        $stmt = $connection->prepare("SELECT COUNT(*) as total FROM `orders_list` WHERE `userid`=? AND `status`=1 AND `agent_bought` = 0");
    }
    $stmt->bind_param("i", $from_id);
    $stmt->execute();
    $old_count = $stmt->get_result()->fetch_assoc()['total'];
    $stmt->close();
    
    // 2️⃣ شمارش سرویس‌های جدید
    $stmt = $connection->prepare("SELECT COUNT(*) as total FROM `service_orders` WHERE `user_id` = ?");
    $stmt->bind_param("i", $from_id);
    $stmt->execute();
    $new_count = $stmt->get_result()->fetch_assoc()['total'];
    $stmt->close();
    
    $total_services = $old_count + $new_count;
    
    // بررسی خالی بودن
    if($total_services == 0){
        if(isset($data)){
            editText($message_id, "📋 <b>سرویس‌های من</b>\n\n❌ شما هنوز هیچ سرویسی خریداری نکرده‌اید.\n\nبرای خرید سرویس جدید از منوی اصلی استفاده کنید.", json_encode(['inline_keyboard' => [
                [['text' => '🛒 خرید سرویس', 'callback_data' => 'buyService']],
                [['text' => '🏠 منوی اصلی', 'callback_data' => 'mainMenu']]
            ]]), 'HTML');
        } else {
            alert($mainValues['you_dont_have_config']);
        }
        exit;
    }
    
    // 3️⃣ دریافت سرویس‌ها برای نمایش (محدود به 10)
    if($data == "agentConfigsList" || $match[1] == "changeAgentOrder") {
        $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `userid`=? AND `status`=1 AND `agent_bought` = 1 ORDER BY `id` DESC LIMIT 10");
    } else {
        $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `userid`=? AND `status`=1 AND `agent_bought` = 0 ORDER BY `id` DESC LIMIT 10");
    }
    $stmt->bind_param("i", $from_id);
    $stmt->execute();
    $old_orders = $stmt->get_result();
    $stmt->close();
    
    $stmt = $connection->prepare("SELECT so.*, sp.name as plan_name, sp.volume_gb, sp.days 
                                   FROM `service_orders` so
                                   LEFT JOIN `service_plans` sp ON so.plan_id = sp.id
                                   WHERE so.user_id = ? 
                                   ORDER BY so.created_at DESC 
                                   LIMIT 10");
    $stmt->bind_param("i", $from_id);
    $stmt->execute();
    $new_orders = $stmt->get_result();
    $stmt->close();
    
    // 4️⃣ ساخت پیام نمایش
    $msg = "📋 <b>سرویس‌های من</b>\n\n";
    $msg .= "📊 تعداد کل سرویس‌ها: <b>{$total_services}</b>\n";
    $msg .= "━━━━━━━━━━━━━━━━━━\n\n";
    
    $keyboard = [];
    $index = 1;
    
    // نمایش سرویس‌های قدیمی
    if($old_orders->num_rows > 0){
        while($cat = $old_orders->fetch_assoc()){
            $id = $cat['id'];
            $remark = $cat['remark'];
            $fileid = $cat['fileid'];
            
            $displayName = $remark;
            $icon = '📦';
            
            if($fileid == 0) {
                $icon = '💎';
                $transid = $cat['transid'];
                $stmt2 = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ? LIMIT 1");
                $stmt2->bind_param("s", $transid);
                $stmt2->execute();
                $payInfo = $stmt2->get_result()->fetch_assoc();
                $stmt2->close();
                
                if($payInfo) {
                    $volumeGB = $payInfo['volume'] ?? 0;
                    $daysPeriod = $payInfo['day'] ?? 30;
                    $users = $payInfo['agent_count'] ?? 1;
                    $userType = $users == 1 ? "تک کاربره" : "{$users} کاربره";
                    
                    if($volumeGB > 0) {
                        $displayName = "{$volumeGB}GB {$userType}";
                    } else {
                        $displayName = "♾️ نامحدود {$userType}";
                    }
                    
                    if($daysPeriod == 30) {
                        $displayName .= " یک ماهه";
                    } elseif($daysPeriod == 90) {
                        $displayName .= " سه ماهه";
                    } elseif($daysPeriod == 180) {
                        $displayName .= " شش ماهه";
                    }
                }
            }
            
            $msg .= "{$index}. {$icon} <b>{$displayName}</b>\n";
            
            $row = [];
            $row[] = ['text' => "📱 مشاهده #{$id}", 'callback_data' => "orderDetails$id"];
            if($fileid == 0 && !empty($cat['link']) && $cat['link'] != '0'){
                $row[] = ['text' => '🔗 لینک', 'callback_data' => "viewVipLink_{$id}"];
            }
            $keyboard[] = $row;
            $index++;
        }
    }
    
    // نمایش سرویس‌های جدید
    if($new_orders->num_rows > 0){
        while($service = $new_orders->fetch_assoc()){
            $displayName = $service['plan_name'] ?? "سرویس #{$service['id']}";
            $status_icon = $service['status'] == 'active' ? '✅' : '⏸';
            
            $msg .= "{$index}. 🆕 <b>{$displayName}</b> {$status_icon}\n";
            
            $row = [];
            $row[] = ['text' => "📱 مشاهده #{$service['id']}", 'callback_data' => "viewService_{$service['id']}"];
            if(!empty($service['config_link']) || !empty($service['config'])){
                $row[] = ['text' => '🔗 لینک', 'callback_data' => "getConfig_{$service['id']}"];
            }
            $keyboard[] = $row;
            $index++;
        }
    }
    
    $msg .= "\n━━━━━━━━━━━━━━━━━━\n";
    $msg .= "💡 برای مشاهده جزئیات هر سرویس روی دکمه مربوطه کلیک کنید.";
    
    // دکمه‌های پایین
    if($data == "agentConfigsList" || $match[1] == "changeAgentOrder") {
        $keyboard[] = [['text'=>$buttonValues['search_agent_config'],'callback_data'=>"searchAgentConfig"]];
    }
    $keyboard[] = [['text' => '🛒 خرید سرویس جدید', 'callback_data' => 'buyService']];
    $keyboard[] = [['text'=>$buttonValues['back_to_main'],'callback_data'=>"mainMenu"]];
    
    if(isset($data)) {
        editText($message_id, $msg, json_encode(['inline_keyboard'=>$keyboard]), 'HTML');
    } else {
        sendAction('typing');
        sendMessage($msg, json_encode(['inline_keyboard'=>$keyboard]), 'HTML');
    }
    exit;
}
if($data=="searchAgentConfig" || $data=="searchUsersConfig"){
    delMessage();
    sendMessage($mainValues['send_config_remark'],$cancelKey);
    setUser($data);
}
if($userInfo['step'] == "searchAgentConfig" && $text != $buttonValues['cancel']){
    sendMessage($mainValues['please_wait_message']);
    $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `userid` = ? AND `remark` LIKE CONCAT('%', ?, '%') AND `agent_bought` = 1");
    $stmt->bind_param("is", $from_id, $text);
    $stmt->execute();
    $orderId = $stmt->get_result()->fetch_assoc()['id'];
    $stmt->close();
    
    $keys = getOrderDetailKeys($from_id, $orderId);
    if($keys == null) sendMessage($mainValues['no_order_found']); 
    else {
        sendMessage($keys['msg'], $keys['keyboard'], "HTML");
        setUser();
    }
}
if($userInfo['step'] == "searchUsersConfig" && $text != $buttonValues['cancel']){
    sendMessage($mainValues['please_wait_message']);
    $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `remark` LIKE CONCAT('%', ?, '%')");
    $stmt->bind_param("s", $text);
    $stmt->execute();
    $orderId = $stmt->get_result()->fetch_assoc()['id'];
    $stmt->close();
    
    $keys = getUserOrderDetailKeys($orderId);
    if($keys == null) sendMessage($mainValues['no_order_found']); 
    else {
        sendMessage($keys['msg'], $keys['keyboard'], "HTML");
        setUser();
    }
}
if(preg_match('/orderDetails(\d+)/', $data, $match) && ($botState['sellState']=="on" || ($from_id == $admin || $userInfo['isAdmin'] == true))){
    $keys = getOrderDetailKeys($from_id, $match[1]);
    if($keys == null){
        alert($mainValues['no_order_found']);exit;
    }else editText($message_id, $keys['msg'], $keys['keyboard'], "HTML");
}
if($data=="cantEditGrpc"){
    alert("نوعیت این کانفیگ رو تغییر داده نمیتونید!");
    exit();
}
if(preg_match('/^changeCustomPort(\d+)/',$data,$match)){
    delMessage();
    sendMessage("لطفا پورت مورد نظر خود را وارد کنید\nبرای حذف پورت دلخواه عدد 0 را وارد کنید", $cancelKey);
    setUser($data);
}
if(preg_match('/^changeCustomPort(\d+)/',$userInfo['step'],$match) && $text != $buttonValues['cancel']){
    if(is_numeric($text)){
        $stmt = $connection->prepare("UPDATE `server_plans` SET `custom_port`= ? WHERE `id` = ?");
        $stmt->bind_param("ii", $text, $match[1]);
        $stmt->execute();
        $stmt->close();  
        sendMessage($mainValues['saved_successfuly'],$removeKeyboard);
         
        sendMessage("ویرایش تنظیمات پلن", getPlanDetailsKeys($match[1]));
        setUser();
    }else sendMessage($mainValues['send_only_number']);
}
if(preg_match('/^changeCustomSni(\d+)/',$data,$match)){
    delMessage();
    sendMessage("لطفا sni مورد نظر خود را وارد کنید\nبرای حذف متن /empty را وارد کنید", $cancelKey);
    setUser($data);
}
if(preg_match('/^changeCustomSni(\d+)/',$userInfo['step'],$match) && $text != $buttonValues['cancel']){
    if($text == "/empty"){
        $stmt = $connection->prepare("UPDATE `server_plans` SET `custom_sni`= NULL WHERE `id` = ?");
        $stmt->bind_param("i", $match[1]);
    }
    else {
        $stmt = $connection->prepare("UPDATE `server_plans` SET `custom_sni`= ? WHERE `id` = ?");
        $stmt->bind_param("si", $text, $match[1]);
    }
    $stmt->execute();
    $stmt->close();  
    sendMessage($mainValues['saved_successfuly'],$removeKeyboard);
     
    sendMessage("ویرایش تنظیمات پلن", getPlanDetailsKeys($match[1]));
    setUser();
}
if(preg_match('/^changeCustomPath(\d+)/',$data,$match)){
    $stmt = $connection->prepare("UPDATE `server_plans` SET `custom_path` = IF(`custom_path` = 1, 0, 1) WHERE `id` = ?");
    $stmt->bind_param("i", $match[1]);
    $stmt->execute();
    $stmt->close();
    
    editKeys(getPlanDetailsKeys($match[1]));
}
if(preg_match('/changeNetworkType(\d+)_(\d+)/', $data, $match)){
    $fid = $match[1];
    $oid = $match[2];
    
	$stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `id`=? AND `active`=1"); 
    $stmt->bind_param("i", $fid);
    $stmt->execute();
    $respd = $stmt->get_result();
    $stmt->close();


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


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

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


    $date = jdate("Y-m-d H:i",$order['date']);
    $expire_date = jdate("Y-m-d H:i",$order['expire_date']);
    $remark = $order['remark'];
    $acc_link = $order['link'];
    $protocol = $order['protocol'];
    $server_id = $order['server_id'];
    $price = $order['amount'];
    
    $response = getJson($server_id)->obj;
    foreach($response as $row){
        if($row->remark == $remark) {
            $total = $row->total;
            $up = $row->up;
            $down = $row->down;
            $port = $row->port;
            $uniqid = ($protocol == 'trojan') ? json_decode($row->settings)->clients[0]->password : json_decode($row->settings)->clients[0]->id;
            $netType = json_decode($row->streamSettings)->network; 
            $security = json_decode($row->streamSettings)->security;
            $netType = ($netType == 'tcp') ? 'ws' : 'tcp';
        break;
        }
    }

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

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

    $vray_link = json_encode($vraylink);
    $stmt = $connection->prepare("UPDATE `orders_list` SET `protocol`=?,`link`=? WHERE `id`=?");
    $stmt->bind_param("ssi", $protocol, $vray_link, $oid);
    $stmt->execute();
    $stmt->close();
    
    $keys = getOrderDetailKeys($from_id, $oid);
    editText($message_id, $keys['msg'], $keys['keyboard'], "HTML");
}
if($data=="changeProtocolIsDisable"){
    alert("تغییر پروتکل غیر فعال است");
}
if(preg_match('/updateConfigConnectionLink(\d+)/', $data,$match)){
    alert($mainValues['please_wait_message']);
    $oid = $match[1];

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


    $remark = $order['remark'];
    $inboundId = $order['inbound_id'];
    $server_id = $order['server_id'];
    $file_id = $order['fileid'];
    
    $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `id`=?");
    $stmt->bind_param("i", $file_id);
    $stmt->execute();
    $file_detail = $stmt->get_result()->fetch_assoc();

    $rahgozar = $order['rahgozar'];
    $customPath = $file_detail['custom_path'];
    $customPort = $file_detail['custom_port'];
    $customSni = $file_detail['custom_sni'];
    
    $response = getJson($server_id)->obj;
    if($inboundId == 0){
        foreach($response as $row){
            if($row->remark == $remark) {
                $port = $row->port;
                $protocol = $row->protocol;
                $netType = json_decode($row->streamSettings)->network;
                $settings = json_decode($row->settings, true);
                $clients = $settings['clients'];
                $uuid = $clients[0]['id'];
                break;
            }
        }
    }else{
        foreach($response as $row){
            if($row->id == $inboundId) {
                $port = $row->port;
                $protocol = $row->protocol;
                $netType = json_decode($row->streamSettings)->network;
                $settings = json_decode($row->settings, true);
                $clients = $settings['clients'];
                foreach($clients as $key => $client) {
                    if($client['email'] == $remark) {
                        $uuid = $client['id'];
                        break;
                    }
                }
                break;
            }
        }
    }

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

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


    $date = jdate("Y-m-d H:i",$order['date']);
    $expire_date = jdate("Y-m-d H:i",$order['expire_date']);
    $remark = $order['remark'];
    $inboundId = $order['inbound_id'];
    $acc_link = $order['link'];
    $server_id = $order['server_id'];
    $rahgozar = $order['rahgozar'];
    
    $file_id = $order['fileid'];
    
    $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `id`=?");
    $stmt->bind_param("i", $file_id);
    $stmt->execute();
    $file_detail = $stmt->get_result()->fetch_assoc();
    $customPath = $file_detail['custom_path'];
    $customPort = $file_detail['custom_port'];
    $customSni = $file_detail['custom_sni'];
    
    $response = getJson($server_id)->obj;
    if($inboundId == 0){
        foreach($response as $row){
            if($row->remark == $remark) {
                $port = $row->port;
                $protocol = $row->protocol;
                $netType = json_decode($row->streamSettings)->network;
                break;
            }
        }
        
        $update_response = renewInboundUuid($server_id, $remark);
    }else{
        foreach($response as $row){
            if($row->id == $inboundId) {
                $port = $row->port;
                $protocol = $row->protocol;
                $netType = json_decode($row->streamSettings)->network;
                break;
            }
        }
        $update_response = renewClientUuid($server_id, $inboundId, $remark);
    }

    
    $newUuid = $update_response->newUuid;
    $vraylink = getConnectionLink($server_id, $newUuid, $protocol, $remark, $port, $netType, $inboundId, $rahgozar, $customPath, $customPort, $customSni);
    
    $vray_link = json_encode($vraylink);
    $stmt = $connection->prepare("UPDATE `orders_list` SET `link`=? WHERE `id`=?");
    $stmt->bind_param("si", $vray_link, $oid);
    $stmt->execute();
    $stmt->close();
    $keys = getOrderDetailKeys($from_id, $oid);
    editText($message_id, $keys['msg'], $keys['keyboard'],"HTML");
}
if(preg_match('/changeAccProtocol(\d+)_(\d+)_(.*)/', $data,$match)){
    $fid = $match[1];
    $oid = $match[2];
    $protocol = $match[3];

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


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


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

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


    $date = jdate("Y-m-d H:i",$order['date']);
    $expire_date = jdate("Y-m-d H:i",$order['expire_date']);
    $remark = $order['remark'];
    $acc_link = $order['link'];
    $server_id = $order['server_id'];
    $price = $order['amount'];
    $rahgozar = $order['rahgozar'];
    $file_id = $order['fileid'];
    
    $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `id`=?");
    $stmt->bind_param("i", $file_id);
    $stmt->execute();
    $file_detail = $stmt->get_result()->fetch_assoc();
    $customPath = $file_detail['custom_path'];
    $customPort = $file_detail['custom_port'];
    $customSni = $file_detail['custom_sni'];
    
    $response = getJson($server_id)->obj;
    foreach($response as $row){
        if($row->remark == $remark) {
            $total = $row->total;
            $up = $row->up;
            $down = $row->down;
            $port = $row->port;
            $netType = json_decode($row->streamSettings)->network;
            $security = json_decode($row->streamSettings)->security;
            break;
        }
    }
    if($protocol == 'trojan') $netType = 'tcp';
    $uniqid = generateRandomString(42,$protocol); 
    $leftgb = round( ($total - $up - $down) / 1073741824, 2) . " GB"; 
    $update_response = editInbound($server_id, $uniqid, $remark, $protocol, $netType, $security, $rahgozar);
    $vraylink = getConnectionLink($server_id, $uniqid, $protocol, $remark, $port, $netType, 0, $rahgozar, $customPath, $customPort, $customSni);
    
    $vray_link = json_encode($vraylink);
    $stmt = $connection->prepare("UPDATE `orders_list` SET `protocol`=?,`link`=? WHERE `id`=?");
    $stmt->bind_param("ssi", $protocol, $vray_link, $oid);
    $stmt->execute();
    $stmt->close();
    $keys = getOrderDetailKeys($from_id, $oid);
    editText($message_id, $keys['msg'], $keys['keyboard'],"HTML");
}
if(preg_match('/^discountRenew(\d+)_(\d+)/',$userInfo['step'], $match) || preg_match('/renewAccount(\d+)/',$data,$match) && $text != $buttonValues['cancel']){
    if(preg_match('/^discountRenew/', $userInfo['step'])){
        $rowId = $match[2];
        
        $time = time();
        $stmt = $connection->prepare("SELECT * FROM `discounts` WHERE (`expire_date` > $time OR `expire_date` = 0) AND (`expire_count` > 0 OR `expire_count` = -1) AND `hash_id` = ?");
        $stmt->bind_param("s", $text);
        $stmt->execute();
        $list = $stmt->get_result();
        $stmt->close();
        
        $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `id` = ?");
        $stmt->bind_param("i", $rowId);
        $stmt->execute();
        $payInfo = $stmt->get_result()->fetch_assoc();
        $hash_id = $payInfo['hash_id'];
        $afterDiscount = $payInfo['price'];
        $stmt->close();
        
        if($list->num_rows>0){
            $discountInfo = $list->fetch_assoc();
            $amount = $discountInfo['amount'];
            $type = $discountInfo['type'];
            $count = $discountInfo['expire_count'];
            $usedBy = !is_null($discountInfo['used_by'])?json_decode($discountInfo['used_by'],true):array();            
            
            $canUse = $discountInfo['can_use'];
            $userUsedCount = array_count_values($usedBy)[$from_id];
            if($canUse > $userUsedCount){
                $usedBy[] = $from_id;
                $encodeUsedBy = json_encode($usedBy);
                
                if ($count != -1) $query = "UPDATE `discounts` SET `expire_count` = `expire_count` - 1, `used_by` = ? WHERE `id` = ?";
                else $query = "UPDATE `discounts` SET `used_by` = ? WHERE `id` = ?";
    
                $stmt = $connection->prepare($query);
                $stmt->bind_param("si", $encodeUsedBy, $discountInfo['id']);
                $stmt->execute();
                $stmt->close();
                
                if($type == "percent"){
                    $discount = $afterDiscount * $amount / 100;
                    $afterDiscount -= $discount;
                    $discount = number_format($discount) . " تومان";
                }else{
                    $afterDiscount -= $amount;
                    $discount = number_format($amount) . " تومان";
                }
                if($afterDiscount < 0) $afterDiscount = 0;
                
                $stmt = $connection->prepare("UPDATE `pays` SET `price` = ? 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"=>"wizwizch"]
                        ],
                    ]]);
                sendMessage(
                    str_replace(['USERID', 'USERNAME', "NAME", "AMOUNT", "DISCOUNTCODE"], [$from_id, $username, $first_name, $discount, $text], $mainValues['used_discount_code'])
                    ,$keys,null,$admin);
            }else sendMessage($mainValues['not_valid_discount_code']);
        }else sendMessage($mainValues['not_valid_discount_code']);
        setUser();
    }else delMessage();

    $oid = $match[1];
    
    $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `id` = ?");
    $stmt->bind_param("i", $oid);
    $stmt->execute();
    $order = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $fid = $order['fileid'];
    
    $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `id` = ? AND `active` = 1");
    $stmt->bind_param("i", $fid);
    $stmt->execute();
    $respd = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $price = $respd['price'];

    if(!preg_match('/^discountRenew/', $userInfo['step'])){
        $hash_id = RandomString();
        $stmt = $connection->prepare("DELETE FROM `pays` WHERE `user_id` = ? AND `type` = 'RENEW_ACCOUNT' AND `state` = 'pending'");
        $stmt->bind_param("i", $from_id);
        $stmt->execute();
        $stmt->close();
        
        $time = time();
        $stmt = $connection->prepare("INSERT INTO `pays` (`hash_id`, `user_id`, `type`, `plan_id`, `volume`, `day`, `price`, `request_date`, `state`)
                                    VALUES (?, ?, 'RENEW_ACCOUNT', ?, '0', '0', ?, ?, 'pending')");
        $stmt->bind_param("siiii", $hash_id, $from_id, $oid, $price, $time);
        $stmt->execute();
        $rowId = $stmt->insert_id;
        $stmt->close();
    }else $price = $afterDiscount;


    $keyboard = array();
    $temp = array();
    if($botState['cartToCartState'] == "on"){
	    $temp[] = ['text' => "💳 کارت به کارت مبلغ $price تومان ",  'callback_data' => "payRenewWithCartToCart$hash_id"];
    }
    if($botState['nowPaymentOther'] == "on"){
	    $temp[] = ['text' => $buttonValues['now_payment_gateway'],  'url' => $botUrl . "pay/?nowpayment&hash_id=" . $hash_id];
    }
    if(count($temp) == 2){
        array_push($keyboard, $temp);
        $temp = array();
    }
    if($botState['zarinpal'] == "on"){
	    $temp[] = ['text' => $buttonValues['zarinpal_gateway'],  'url' => $botUrl . "pay/?zarinpal&hash_id=" . $hash_id];
    }
    if(count($temp) == 2){
        array_push($keyboard, $temp);
        $temp = array();
    }
    if($botState['nextpay'] == "on"){
	    $temp[] = ['text' => $buttonValues['nextpay_gateway'],  'url' => $botUrl . "pay/?nextpay&hash_id=" . $hash_id];
    }
    if(count($temp) == 2){
        array_push($keyboard, $temp);
        $temp = array();
    }
    if($botState['weSwapState'] == "on"){
	    $temp[] = ['text' => $buttonValues['weswap_gateway'],  'callback_data' => "payWithWeSwap" . $hash_id];
    }

    if(count($temp) == 2){
        array_push($keyboard, $temp);
        $temp = array();
    }
    if($botState['walletState'] == "on"){
	    $temp[] = ['text' => "پرداخت با موجودی مبلغ $price تومان 💰",  'callback_data' => "payRenewWithWallet$hash_id"];
    }
    array_push($keyboard, $temp);
    if(!preg_match('/^discountRenew/', $userInfo['step'])) $keyboard[] = [['text' => " 🎁 نکنه کد تخفیف داری؟ ",  'callback_data' => "haveDiscountRenew_" . $match[1] . "_" . $rowId]];

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



    sendMessage("لطفا با یکی از روش های زیر اکانت خود را تمدید کنید :",json_encode([
            'inline_keyboard' => $keyboard
        ]));
}
if(preg_match('/payRenewWithCartToCart(.*)/',$data,$match)) {
    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('/payRenewWithCartToCart(.*)/',$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()->fetch_assoc();
        $hash_id = $payInfo['hash_id'];
        $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()->fetch_assoc();
        $stmt->close();
        $fid = $order['fileid'];
        $remark = $order['remark'];
        $uid = $order['userid'];
        $userName = $userInfo['username'];
        $uname = $userInfo['name'];
        
        $stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `id` = ? AND `active` = 1");
        $stmt->bind_param("i", $fid);
        $stmt->execute();
        $respd = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        $price = $payInfo['price'];
        sendMessage($mainValues['renew_order_sent'],$removeKeyboard);
        sendMessage($mainValues['reached_main_menu'],getMainKeys());
        // notify admin
        
        $msg = str_replace(['TYPE', "USER-ID", "USERNAME", "NAME", "PRICE", "REMARK"],['کارت به کارت', $from_id, $username, $first_name, $price, $remark], $mainValues['renew_account_request_message']);
    
        $keyboard = json_encode([
            'inline_keyboard' => [
                [
                    ['text' => $buttonValues['approve'], 'callback_data' => "approveRenewAcc$hash_id"],
                    ['text' => $buttonValues['decline'], 'callback_data' => "decRenewAcc$hash_id"]
                ]
            ]
        ]);
    
        sendPhoto($fileid, $msg,$keyboard, "HTML", $admin);
        setUser();
    }else{
        sendMessage($mainValues['please_send_only_image']);
    }
}
if(preg_match('/approveRenewAcc(.*)/',$data,$match)){
    $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();
    
    $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'];
    $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` = ? AND `active` = 1");
    $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'];


    unset($markup[count($markup)-1]);
    $markup[] = [['text'=>"✅",'callback_data'=>"wizwizch"]];
    $keys = json_encode(['inline_keyboard'=>array_values($markup)],488);


    editKeys($keys);

    
    if($inbound_id > 0)
        $response = editClientTraffic($server_id, $inbound_id, $remark, $volume, $days, "renew");
    else
        $response = editInboundTraffic($server_id, $remark, $volume, $days, "renew");
    
	if(is_null($response)){
		alert('🔻مشکل فنی در اتصال به سرور. لطفا به مدیریت اطلاع بدید',true);
		exit;
	}
	$stmt = $connection->prepare("UPDATE `orders_list` SET `expire_date` = ?, `notif` = 0 WHERE `id` = ?");
	$newExpire = $expire_date + $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 با موفقیت تمدید شد",null,null,$uid);
    exit;
}
if(preg_match('/decRenewAcc(.*)/',$data,$match)){
    $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();
    
    $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'];
    $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` = ? AND `active` = 1");
    $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 = $respd['price'];


    unset($markup[count($markup)-1]);
    $markup[] = [['text' => '❌', 'callback_data' => "dontsendanymore"]];
    $keys = json_encode(['inline_keyboard'=>array_values($markup)],488);

    editKeys($keys);
    sendMessage("😖|تمدید سرویس $remark لغو شد",null,null,$uid);
    exit;
}
if(preg_match('/payRenewWithWallet(.*)/', $data,$match)){
    $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();
    
    $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'];
    $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` = ? AND `active` = 1");
    $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;
    }

    if($inbound_id > 0)
        $response = editClientTraffic($server_id, $inbound_id, $remark, $volume, $days, "renew");
    else
        $response = editInboundTraffic($server_id, $remark, $volume, $days, "renew");

	if(is_null($response)){
		alert('🔻مشکل فنی در اتصال به سرور. لطفا به مدیریت اطلاع بدید',true);
		exit;
	}
	$stmt = $connection->prepare("UPDATE `orders_list` SET `expire_date` = ?, `notif` = 0 WHERE `id` = ?");
	$newExpire = $expire_date + $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'=>"wizwizch"]
            ],
        ]]);
    $msg = str_replace(['TYPE', "USER-ID", "USERNAME", "NAME", "PRICE", "REMARK"],['کیف پول', $from_id, $username, $first_name, $price, $remark], $mainValues['renew_account_request_message']);

    sendMessage($msg, $keys,"html", $admin);
    exit;
}
if(preg_match('/switchLocation(.+)_(.+)_(.+)_(.+)/', $data,$match)){
    $order_id = $match[1];
    $server_id = $match[2];
    $leftgp = $match[3];
    $expire = $match[4]; 
    if($expire < time() or $leftgp <= 0) {
        alert("سرویس شما غیرفعال است.لطفا ابتدا آن را تمدید کنید",true);exit;
    }
    $stmt = $connection->prepare("SELECT * FROM `server_info` WHERE `active` = 1 and `state` = 1 and ucount > 0 AND `id` != ?");
    $stmt->bind_param("i", $server_id);
    $stmt->execute();
    $respd = $stmt->get_result();
    $stmt->close();
    if($respd->num_rows == 0){
        alert('در حال حاضر هیچ سرور فعالی برای تغییر لوکیشن وجود ندارد',true);
        exit;
    }
    $keyboard = [];
    while($cat = $respd->fetch_assoc()){
        $sid = $cat['id'];
        $name = $cat['title'];
        $keyboard[] = ['text' => "$name", 'callback_data' => "switchServer{$sid}_{$order_id}"];
    }
    $keyboard = array_chunk($keyboard,2);
    $keyboard[] = [['text' => $buttonValues['back_button'], 'callback_data' => "mainMenu"]];
    editText($message_id, ' 📍 لطفا برای تغییر لوکیشن سرویس فعلی, یکی از سرورها را انتخاب کنید👇',json_encode([
            'inline_keyboard' => $keyboard
        ]));
}
if($data=="giftVolumeAndDay"){
    $stmt = $connection->prepare("SELECT * FROM `server_info` WHERE `active` = 1 and `state` = 1");
    $stmt->execute();
    $respd = $stmt->get_result();
    $stmt->close();
    if($respd->num_rows == 0){
        alert('در حال حاضر هیچ سرور فعالی برای هدیه دادن وجود ندارد',true);
        exit;
    }
    $keyboard = [];
    while($cat = $respd->fetch_assoc()){
        $sid = $cat['id'];
        $name = $cat['title'];
        $keyboard[] = ['text' => "$name", 'callback_data' => "giftToServer{$sid}"];
    }
    $keyboard = array_chunk($keyboard,2);
    $keyboard[] = [['text' => $buttonValues['back_button'], 'callback_data' => "managePanel"]];
    editText($message_id, ' 📍 لطفا برای هدیه دادن, یکی از سرورها را انتخاب کنید👇',json_encode([
            'inline_keyboard' => $keyboard
        ]));
}
if(preg_match('/^giftToServer(\d+)/',$data,$match)){
    delMessage();
    sendMessage("لطفا مدت زمان هدیه را به روز وارد کنید\nبرای اضافه نشدن زمان 0 را وارد کنید", $cancelKey);
    setUser('giftServerDay' . $match[1]);
}
if(preg_match('/^giftServerDay(\d+)/',$userInfo['step'], $match) && $text != $buttonValues['cancel']){
    if(is_numeric($text)){
        if($text >= 0){
            sendMessage("لطفا حجم هدیه را به مگابایت وارد کنید\nبرای اضافه نشدن حجم 0 را وارد کنید");
            setUser('giftServerVolume' . $match[1] . "_" . $text);
        }else sendMessage("عددی بزرگتر و یا مساوی به 0 واردکنید");
    }else sendMessage($mainValues['send_only_number']);
}
if(preg_match('/^giftServerVolume(\d+)_(\d+)/',$userInfo['step'],$match) && $text != $buttonValues['cancel']){
    if(is_numeric($text)){
        if($text >= 0){
            $stmt = $connection->prepare("INSERT INTO `gift_list` (`server_id`, `volume`, `day`) VALUES (?, ?, ?)");
            $stmt->bind_param("iii", $match[1], $text, $match[2]);
            $stmt->execute();
            $stmt->close();
            
            sendMessage($mainValues['saved_successfuly'],$removeKeyboard);
            sendMessage($mainValues['reached_main_menu'],getMainKeys());

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

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


    if($botState['remark'] == "digits"){
        $rnd = rand(10000,99999);
        $newRemark = "{$srv_remark}-{$rnd}";
    }else{
        $rnd = rand(1111,99999);
        $newRemark = "{$srv_remark}-{$from_id}-{$rnd}";
    }
	
    if(preg_match('/vmess/',$link)){
        $link_info = json_decode(base64_decode(str_replace('vmess://','',$link)));
        $uniqid = $link_info->id;
        $port = $link_info->port;
        $netType = $link_info->net;
    }else{
        $link_info = parse_url($link);
        $panel_ip = $link_info['host'];
        $uniqid = $link_info['user'];
        $protocol = $link_info['scheme'];
        $port = $link_info['port'];
        $netType = explode('type=',$link_info['query'])[1]; 
        $netType = explode('&',$netType)[0];
    }

    if($inbound_id > 0) {
        $remove_response = deleteClient($server_id, $inbound_id, $remark);
		if(is_null($remove_response)){
			alert('🔻اتصال به سرور برقرار نیست. لطفا به مدیریت اطلاع بدید',true);
			exit;
		}
        if($remove_response){
            $total = $remove_response['total'];
            $up = $remove_response['up'];
            $down = $remove_response['down'];
			$id_label = $protocol == 'trojan' ? 'password' : 'id';
			if($serverType == "sanaei" || $serverType == "alireza"){
			    if($reality == "true"){
                    $newArr = [
                      "$id_label" => $uniqid,
                      "email" => $newRemark,
                      "enable" => true,
                      "flow" => $flow,
                      "limitIp" => $remove_response['limitIp'],
                      "totalGB" => $total - $up - $down,
                      "expiryTime" => $remove_response['expiryTime'],
                      "subId" => RandomString(16)
                    ];			        
			    }else{
                    $newArr = [
                      "$id_label" => $uniqid,
                      "email" => $newRemark,
                      "enable" => true,
                      "limitIp" => $remove_response['limitIp'],
                      "totalGB" => $total - $up - $down,
                      "expiryTime" => $remove_response['expiryTime'],
                      "subId" => RandomString(16)
                    ];
			    }
			}else{
                $newArr = [
                  "$id_label" => $uniqid,
                  "flow" => $remove_response['flow'],
                  "email" => $newRremark,
                  "limitIp" => $remove_response['limitIp'],
                  "totalGB" => $total - $up - $down,
                  "expiryTime" => $remove_response['expiryTime']
                ];
			}
            
            $response = addInboundAccount($sid, '', $inbound_id, 1, $newRemark, 0, 1, $newArr); 
            if(is_null($response)){
                alert('🔻اتصال به سرور برقرار نیست. لطفا به مدیریت اطلاع بدید',true);
                exit;
            }
			if($response == "inbound not Found"){
                alert("🔻سطر (inbound) با آیدی $inbound_id در این سرور یافت نشد. لطفا به مدیریت اطلاع بدید",true);
                exit;
            }
			if(!$response->success){
				alert('🔻خطا در ساخت کانفیگ. لطفا به مدیریت اطلاع بدید',true);
				exit;
			}
			$vray_link = getConnectionLink($sid, $uniqid, $protocol, $newRemark, $port, $netType, $inbound_id);
			deleteClient($server_id, $inbound_id, $remark, 1);
        }
    }else{
        $response = deleteInbound($server_id, $remark);
		if(is_null($response)){
			alert('🔻اتصال به سرور برقرار نیست. لطفا به مدیریت اطلاع بدید',true);
			exit;
		}
        if($response){
            $res = addUser($sid, $response['uniqid'], $response['protocol'], $response['port'], $response['expiryTime'], $newRemark, $response['volume'] / 1073741824, $response['netType'], $response['security']);
            $vray_link = getConnectionLink($sid, $response['uniqid'], $response['protocol'], $newRemark, $response['port'], $response['netType'], $inbound_id);
            deleteInbound($server_id, $remark, 1);
        }
    }
    $stmt = $connection->prepare("UPDATE `server_info` SET `ucount` = `ucount` + 1 WHERE `id` = ?");
    $stmt->bind_param("i", $server_id);
    $stmt->execute();
    $stmt->close();

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

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

    $stmt = $connection->prepare("SELECT * FROM `server_info` WHERE `id` = ?");
    $stmt->bind_param("i", $sid);
    $stmt->execute();
    $server_title = $stmt->get_result()->fetch_assoc()['title'];
    $stmt->close();
    
    $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `userid` = ? AND `status` = 1 ORDER BY `id` DESC");
    $stmt->bind_param("i", $from_id);
    $stmt->execute();
    $orders = $stmt->get_result();
    $stmt->close();
    
    $keyboard = [];
    while($cat = $orders->fetch_assoc()){
        $id = $cat['id'];
        $cremark = $cat['remark'];
        $keyboard[] = ['text' => "$cremark", 'callback_data' => "orderDetails$id"];
    }
    $keyboard = array_chunk($keyboard,2);
    $keyboard[] = [['text'=>"صفحه اصلی 🏘",'callback_data'=>"mainMenu"]];
    $msg = " 📍لوکیشن سرویس $remark به $server_title با ریمارک $newRemark تغییر یافت.\n لطفا برای مشاهده مشخصات, روی آن بزنید👇";
    
    editText($message_id, $msg,json_encode([
            'inline_keyboard' => $keyboard
        ]));
    exit();
}
elseif(preg_match('/^deleteMyConfig(\d+)/',$data,$match)){
    $oid = $match[1];
    $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `id` = ?");
    $stmt->bind_param("i", $oid);
    $stmt->execute();
    $order = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $remark = $order['remark'];

    editText($message_id, "آیا از حذف کانفیگ $remark مطمئن هستید؟",json_encode([
        'inline_keyboard' => [
            [['text'=>"بلی",'callback_data'=>"yesDeleteConfig" . $match[1]],['text'=>"نخیر",'callback_data'=>"noDontDelete"]]
            ]
    ]));
}
elseif($data=="noDontDelete"){
    editText($message_id, "عملیه مورد نظر لغو شد",json_encode([
        'inline_keyboard' => [
            [['text'=>"صفحه اصلی 🏘",'callback_data'=>"mainMenu"]]
            ]
    ]));
}
elseif(preg_match('/^yesDeleteConfig(\d+)/',$data,$match)){
    $oid = $match[1];
    $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `id` = ?");
    $stmt->bind_param("i", $oid);
    $stmt->execute();
    $order = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $inbound_id = $order['inbound_id'];
    $server_id = $order['server_id'];
    $remark = $order['remark'];
	
    if($inbound_id > 0) deleteClient($server_id, $inbound_id, $remark, 1);
    else deleteInbound($server_id, $remark, 1);
    
    $stmt = $connection->prepare("UPDATE `server_info` SET `ucount` = `ucount` - 1 WHERE `id` = ?");
    $stmt->bind_param("i", $server_id);
    $stmt->execute();
    $stmt->close();

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

    editText($message_id, "کانفیگ $remark با موفقیت حذف شد",json_encode([
            'inline_keyboard' => [
                [['text'=>"صفحه اصلی 🏘",'callback_data'=>"mainMenu"]]
                ]
        ]));
        
sendMessage("
🔋|💰 حذف کانفیگ

▫️آیدی کاربر: $from_id
👨‍💼اسم کاربر: $first_name
⚡️ نام کاربری: $username
🎈 نام سرویس: $remark
⁮⁮ ⁮⁮ ⁮⁮ ⁮⁮
",$keys,"html", $admin);
    exit();
}
if(preg_match('/increaseADay(.*)/', $data, $match)){
    $stmt = $connection->prepare("SELECT * FROM `increase_day`");
    $stmt->execute();
    $res = $stmt->get_result();
    $stmt->close();
    if($res->num_rows == 0){
        alert("در حال حاضر هیچ پلنی برای افزایش مدت زمان سرویس وجود ندارد");
        exit;
    }
    $keyboard = [];
    while ($cat = $res->fetch_assoc()){
        $id = $cat['id'];
        $title = $cat['volume'];
        $price = number_format($cat['price']);
        $keyboard[] = ['text' => "$title روز $price تومان", 'callback_data' => "selectPlanDayIncrease{$match[1]}_$id"];
    }
    $keyboard = array_chunk($keyboard,2);
    $keyboard[] = [['text' => "صفحه اصلی 🏘", 'callback_data' => "mainMenu"]];
    editText($message_id, "لطفا یکی از پلن های افزایشی را انتخاب کنید :", json_encode([
            'inline_keyboard' => $keyboard
        ]));
}
if(preg_match('/selectPlanDayIncrease(?<orderId>.+)_(?<dayId>.+)/',$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'];
    
    
    
    $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();
    $temp = array();
    if($botState['cartToCartState'] == "on"){
	    $temp[] = ['text' => $buttonValues['cart_to_cart'],  'callback_data' => "payIncreaseDayWithCartToCart$hash_id"];
    }
    if($botState['nowPaymentOther'] == "on"){
	    $temp[] = ['text' => $buttonValues['now_payment_gateway'],  'url' => $botUrl . "pay/?nowpayment&hash_id=" . $hash_id];
    }
    if(count($temp) == 2){
        array_push($keyboard, $temp);
        $temp = array();
    }
    if($botState['zarinpal'] == "on"){
	    $temp[] = ['text' => $buttonValues['zarinpal_gateway'],  'url' => $botUrl . "pay/?zarinpal&hash_id=" . $hash_id];
    }
    if(count($temp) == 2){
        array_push($keyboard, $temp);
        $temp = array();
    }
    if($botState['nextpay'] == "on"){
	    $temp[] = ['text' => $buttonValues['nextpay_gateway'],  'url' => $botUrl . "pay/?nextpay&hash_id=" . $hash_id];
    }
    if(count($temp) == 2){
        array_push($keyboard, $temp);
        $temp = array();
    }
    if($botState['weSwapState'] == "on"){
	    $temp[] = ['text' => $buttonValues['weswap_gateway'],  'callback_data' => "payWithWeSwap" . $hash_id];
    }
    if(count($temp) == 2){
        array_push($keyboard, $temp);
        $temp = array();
    }
    if($botState['walletState'] == "on"){
	    $temp[] = ['text' => $buttonValues['pay_with_wallet'],  'callback_data' => "payIncraseDayWithWallet$hash_id"];
    }
    array_push($keyboard, $temp);
    $keyboard[] = [['text'=>$buttonValues['cancel'], 'callback_data'=> "mainMenu"]];
    editText($message_id, "لطفا با یکی از روش های زیر پرداخت خود را تکمیل کنید :",json_encode(['inline_keyboard' => $keyboard]));
}
if(preg_match('/payIncreaseDayWithCartToCart(.*)/',$data,$match)) {
    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(.*)/',$userInfo['step'], $match) and $text != $buttonValues['cancel']){
    if(isset($update->message->photo)){
        $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ? AND `state` = 'pending'");
        $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'];
    
        sendMessage($mainValues['renew_order_sent'],$removeKeyboard);
        sendMessage($mainValues['reached_main_menu'],getMainKeys());
    
        // 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]}"],
                    ['text' => $buttonValues['decline'], 'callback_data' => "decIncreaseDay{$match[1]}"]
                ]
            ]
        ]);


        sendPhoto($fileid, $msg,$keyboard, "HTML", $admin);
        setUser();
    }else{ 
        sendMessage($mainValues['please_send_only_image']);
    }

}
if(preg_match('/approveIncreaseDay(.*)/',$data,$match)){
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ? AND `state` = 'pending'");
    $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 = '';
    
    
    unset($markup[count($markup)-1]);
    $markup[] = [['text' => '✅', 'callback_data' => "dontsendanymore"]];
    $keys = json_encode(['inline_keyboard'=>array_values($markup)],488);

    editKeys($keys);

    
    if($inbound_id > 0)
        $response = editClientTraffic($server_id, $inbound_id, $remark, 0, $volume);
    else
        $response = editInboundTraffic($server_id, $remark, 0, $volume);
    if($response->success){
        $stmt = $connection->prepare("UPDATE `orders_list` SET `expire_date` = `expire_date` + ?, `notif` = 0 WHERE `remark` = ?");
        $newVolume = $volume * 86400;
        $stmt->bind_param("is", $newVolume, $remark);
        $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();
        sendMessage("✅$volume روز به مدت زمان سرویس شما اضافه شد",null,null,$uid);
    }else {
        alert("مشکل فنی در ارتباط با سرور. لطفا سلامت سرور را بررسی کنید",true);
        exit;
    }
}
if(preg_match('/payIncraseDayWithWallet(.*)/', $data,$match)){
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ? AND `state` = 'pending'");
    $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'];
    
    $userwallet = $userInfo['wallet'];

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

    

    if($inbound_id > 0)
        $response = editClientTraffic($server_id, $inbound_id, $remark, 0, $volume);
    else
        $response = editInboundTraffic($server_id, $remark, 0, $volume);
        
    if($response->success){
        $stmt = $connection->prepare("UPDATE `orders_list` SET `expire_date` = `expire_date` + ?, `notif` = 0 WHERE `remark` = ?");
        $newVolume = $volume * 86400;
        $stmt->bind_param("is", $newVolume, $remark);
        $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'=>"wizwizch"]
                ],
            ]]);
        sendMessage("
🔋|💰 افزایش زمان با ( کیف پول )

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

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

    $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();
    $temp = array();
    if($botState['cartToCartState'] == "on"){
	    $temp[] = ['text' => $buttonValues['cart_to_cart'] . number_format($planprice) . " تومان",  'callback_data' => "payIncreaseWithCartToCart$hash_id"];
    }
    if($botState['nowPaymentOther'] == "on"){
	    $temp[] = ['text' => $buttonValues['now_payment_gateway'],  'url' => $botUrl . "pay/?nowpayment&hash_id=" . $hash_id];
    }
    if(count($temp) == 2){
        array_push($keyboard, $temp);
        $temp = array();
    }
    if($botState['zarinpal'] == "on"){
	    $temp[] = ['text' => $buttonValues['zarinpal_gateway'],  'url' => $botUrl . "pay/?zarinpal&hash_id=" . $hash_id];
    }
    if(count($temp) == 2){
        array_push($keyboard, $temp);
        $temp = array();
    }
    if($botState['nextpay'] == "on"){
	    $temp[] = ['text' => $buttonValues['nextpay_gateway'],  'url' => $botUrl . "pay/?nextpay&hash_id=" . $hash_id];
    }
    if(count($temp) == 2){
        array_push($keyboard, $temp);
        $temp = array();
    }
    if($botState['weSwapState'] == "on"){
	    $temp[] = ['text' => $buttonValues['weswap_gateway'],  'callback_data' => "payWithWeSwap" . $hash_id];
    }
    if(count($temp) == 2){
        array_push($keyboard, $temp);
        $temp = array();
    }
    if($botState['walletState'] == "on"){
	    $temp[] = ['text' => "💰پرداخت با موجودی  " . number_format($planprice) . " تومان",  'callback_data' => "payIncraseWithWallet$hash_id"];
    }
    array_push($keyboard, $temp);
    $keyboard[] = [['text'=>$buttonValues['cancel'], 'callback_data'=> "mainMenu"]];
    editText($message_id, "لطفا با یکی از روش های زیر پرداخت خود را تکمیل کنید :",json_encode(['inline_keyboard' => $keyboard]));
}
if(preg_match('/payIncreaseWithCartToCart(.*)/',$data)) {
    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(.*)/',$userInfo['step'],$match) and $text != $buttonValues['cancel']){
    if(isset($update->message->photo)){
        $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ? AND `state` = 'pending'");
        $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']);
        sendMessage($mainValues['renew_order_sent'],$removeKeyboard);
        sendMessage($mainValues['reached_main_menu'],getMainKeys());
    
        // 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]}"],
                    ['text' => $buttonValues['decline'], 'callback_data' => "decIncreaseVolume{$match[1]}"]
                ]
            ]
        ]);

        sendPhoto($fileid, $msg,$keyboard, "HTML", $admin);
        setUser();
    }else{
        sendMessage($mainValues['please_send_only_image']);
    }
}
if(preg_match('/approveIncreaseVolume(.*)/',$data,$match) && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ? AND `state` = 'pending'");
    $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 = '';
    
    unset($markup[count($markup)-1]);
    $markup[] = [['text' => '✅', 'callback_data' => "dontsendanymore"]];
    $keys = json_encode(['inline_keyboard'=>array_values($markup)],488);

    editKeys($keys);

    
    if($inbound_id > 0)
        $response = editClientTraffic($server_id, $inbound_id, $remark, $volume, 0);
    else
        $response = editInboundTraffic($server_id, $remark, $volume, 0);
    if($response->success){
        $stmt = $connection->prepare("UPDATE `orders_list` SET `notif` = 0 WHERE `remark` = ?");
        $stmt->bind_param("s", $remark);
        $stmt->execute();
        $stmt->close();
        sendMessage("✅$volume گیگ به حجم سرویس شما اضافه شد",null,null,$uid);
    }else {
        alert("مشکل فنی در ارتباط با سرور. لطفا سلامت سرور را بررسی کنید",true);
        exit;
    }
}
if(preg_match('/decIncreaseVolume(.*)/',$data,$match) && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ? AND `state` = 'pending'");
    $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'=>"wizwizch"]]
		    ]]));
    
    sendMessage("افزایش حجم $volume گیگ اشتراک $remark لغو شد",null,null,$uid);
}
if(preg_match('/decIncreaseDay(.*)/',$data,$match) && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ? AND `state` = 'pending'");
    $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'=>"wizwizch"]]
		    ]]));
    
    sendMessage("افزایش زمان $volume روز اشتراک $remark لغو شد",null,null,$uid);
}
if(preg_match('/payIncraseWithWallet(.*)/', $data,$match)){
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ? AND `state` = 'pending'");
    $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'];
    
    $userwallet = $userInfo['wallet'];

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

    if($inbound_id > 0)
        $response = editClientTraffic($server_id, $inbound_id, $remark, $volume, 0);
    else
        $response = editInboundTraffic($server_id, $remark, $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 `remark` = ?");
        $stmt->bind_param("s", $remark);
        $stmt->execute();
        $stmt->close();
        $keys = json_encode(['inline_keyboard'=>[
            [
                ['text'=>"اخیش یکی حجم زد 😁",'callback_data'=>"wizwizch"]
                ],
            ]]);
        sendMessage("
🔋|💰 افزایش حجم با ( کیف پول )

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

    }else {
        alert("به دلیل مشکل فنی امکان افزایش حجم نیست. لطفا به مدیریت اطلاع بدید یا 5دقیقه دیگر دوباره تست کنید",true);
        exit;
    }
}
if($data == 'cantEditTrojan'){
    alert("پروتکل تروجان فقط نوع شبکه TCP را دارد");
    exit;
}
if(($data=='categoriesSetting' || preg_match('/^nextCategoryPage(\d+)/',$data,$match)) and ($from_id == $admin || $userInfo['isAdmin'] == true)){
    if(isset($match[1])) $keys = getCategoriesKeys($match[1]);
    else $keys = getCategoriesKeys();
    
    editText($message_id,"☑️ مدیریت دسته ها:", $keys);
}
if($data=='addNewCategory' and (($from_id == $admin || $userInfo['isAdmin'] == true))){
    setUser($data);
    delMessage();
    $stmt = $connection->prepare("DELETE FROM `server_categories` WHERE `active`=0");
    $stmt->execute();
    $stmt->close();


    $sql = "INSERT INTO `server_categories` VALUES (NULL, 0, '', 0,2,0);";
    $stmt = $connection->prepare($sql);
    $stmt->execute();
    $stmt->close();


    $msg = '▪️یه اسم برای دسته بندی وارد کن:';
    sendMessage($msg,$cancelKey);
    exit;
}
if(preg_match('/^addNewCategory/',$userInfo['step']) and $text!=$buttonValues['cancel']){
    $step = checkStep('server_categories');
    if($step==2 and $text!=$buttonValues['cancel'] ){
        
        $stmt = $connection->prepare("UPDATE `server_categories` SET `title`=?,`step`=4,`active`=1 WHERE `active`=0");
        $stmt->bind_param("s", $text);
        $stmt->execute();
        $stmt->close();


        $msg = 'یه دسته بندی جدید برات ثبت کردم 🙂☑️';
        sendMessage($msg,$removeKeyboard);
        sendMessage($mainValues['reached_main_menu'],getCategoriesKeys());
    }
}
if(preg_match('/^wizwizcategorydelete(\d+)_(\d+)/',$data, $match) and ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $stmt = $connection->prepare("DELETE FROM `server_categories` WHERE `id`=?");
    $stmt->bind_param("i", $match[1]);
    $stmt->execute();
    $stmt->close();

    alert("دسته بندی رو برات حذفش کردم ☹️☑️");
    
    $stmt = $connection->prepare("SELECT * FROM `server_categories` WHERE `active`=1 AND `parent`=0");
    $stmt->execute();
    $cats = $stmt->get_result();
    $stmt->close();

    $keys = getCategoriesKeys($match[2]);
    editText($message_id,"☑️ مدیریت دسته ها:", $keys);
}
if(preg_match('/^wizwizcategoryedit/',$data) and ($from_id == $admin || $userInfo['isAdmin'] == true) && $text != $buttonValues['cancel']){
    setUser($data);
    delMessage();
    sendMessage("〽️ یه اسم جدید برا دسته بندی انتخاب کن:",$cancelKey);exit;
}
if(preg_match('/wizwizcategoryedit(\d+)_(\d+)/',$userInfo['step'], $match) && $text != $buttonValues['cancel']){
    $stmt = $connection->prepare("UPDATE `server_categories` SET `title`=? WHERE `id`=?");
    $stmt->bind_param("si", $text, $match[1]);
    $stmt->execute();
    $stmt->close();

    sendMessage("با موفقیت برات تغییر دادم ☺️☑️");
    setUser();
    
    sendMessage("☑️ مدیریت دسته ها:", getCategoriesKeys($match[2]));
}
if(($data=='serversSetting' || preg_match('/^nextServerPage(\d+)/',$data,$match)) and ($from_id == $admin || $userInfo['isAdmin'] == true)){
    if(isset($match[1])) $keys = getServerListKeys($match[1]);
    else $keys = getServerListKeys();
    
    editText($message_id,"☑️ مدیریت سرور ها:",$keys);
}
if(preg_match('/^toggleServerState(\d+)_(\d+)/',$data,$match) && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $stmt = $connection->prepare("UPDATE `server_info` SET `state` = IF(`state` = 0,1,0) WHERE `id`=?");
    $stmt->bind_param("i", $match[1]);
    $stmt->execute();
    $cats= $stmt->get_result();
    $stmt->close();
    
    alert("وضعیت سرور با موفقیت تغییر کرد");
    
    $keys = getServerListKeys($match[2]);
    editText($message_id,"☑️ مدیریت سرور ها:",$keys);
}
if(preg_match('/^showServerSettings(\d+)_(\d+)/',$data,$match) and ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $keys = getServerConfigKeys($match[1], $match[2]);
    editText($message_id,"☑️ مدیریت سرور ها: $cname",$keys);
}
if(preg_match('/^changesServerIp(\d+)/',$data,$match) && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $stmt = $connection->prepare("SELECT * FROM `server_config` WHERE `id`=?");
    $stmt->bind_param("i", $match[1]);
    $stmt->execute();
    $serverIp= $stmt->get_result()->fetch_assoc()['ip']??"اطلاعاتی یافت نشد";
    $stmt->close();
    
    delMessage();
    sendMessage("لیست آیپی های فعلی: \n$serverIp\nلطفا آیپی های جدید را در خط های جدا بفرستید\n\nبرای خالی کردن متن /empty را وارد کنید",$cancelKey,null,null,null);
    setUser($data);
    exit();
}
if(preg_match('/^changesServerIp(\d+)/',$userInfo['step'],$match) && ($from_id == $admin || $userInfo['isAdmin'] == true) && $text != $buttonValues['cancel']){
    $stmt = $connection->prepare("UPDATE `server_config` SET `ip` = ? WHERE `id`=?");
    if($text == "/empty") $text = "";
    $stmt->bind_param("si", $text, $match[1]);
    $stmt->execute();
    $stmt->close();
    sendMessage($mainValues['saved_successfuly'],$removeKeyboard);
    setUser();
    
    $keys = getServerConfigKeys($match[1]);
    sendMessage("☑️ مدیریت سرور ها: $cname",$keys);
    exit();
}
if(preg_match('/^changePortType(\d+)/',$data,$match) && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $stmt = $connection->prepare("UPDATE `server_config` SET `port_type` = IF(`port_type` = 'auto', 'random', 'auto') WHERE `id`=?");
    $stmt->bind_param("i", $match[1]);
    $stmt->execute();
    $stmt->close();
    alert("نوعیت پورت سرور مورد نظر با موفقیت تغییر کرد");
    
    $keys = getServerConfigKeys($match[1]);
    editText($message_id,"☑️ مدیریت سرور ها: $cname",$keys);
    
    exit();
}
if(preg_match('/^changeRealityState(\d+)/',$data,$match)){
    $stmt = $connection->prepare("UPDATE `server_config` SET `reality` = IF(`reality` = 'true', 'false', 'true') WHERE `id` = ?");
    $stmt->bind_param("i", $match[1]);
    $stmt->execute();
    $stmt->close();
    
    $keys = getServerConfigKeys($match[1]);
    editText($message_id,"☑️ مدیریت سرور ها: $cname",$keys);
    
    exit();
}
if(preg_match('/^changeServerType(\d+)/',$data,$match) && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    editText($message_id,"
    
🔰 نکته مهم: ( پنل x-ui خود را به آخرین نسخه آپدیت کنید ) 

❤️ اگر از پنل سنایی استفاده میکنید لطفا نوع پنل را ( سنایی ) انتخاب کنید
🧡 اگر از پنل علیرضا استفاده میکنید لطفا نوع پنل را ( علیرضا ) انتخاب کنید
💚 اگر از پنل نیدوکا استفاده میکنید لطفا نوع پنل را ( ساده ) انتخاب کنید 
💙 اگر از پنل چینی استفاده میکنید لطفا نوع پنل را ( ساده ) انتخاب کنید 
⁮⁮ ⁮⁮ ⁮⁮ ⁮⁮
📣 حتما نوع پنل را انتخاب کنید وگرنه براتون مشکل ساز میشه !
⁮⁮ ⁮⁮ ⁮⁮ ⁮⁮
",json_encode(['inline_keyboard'=>[
        [['text'=>"ساده",'callback_data'=>"chhangeServerTypenormal_" . $match[1]],['text'=>"سنایی",'callback_data'=>"chhangeServerTypesanaei_" . $match[1]]],
        [['text'=>"علیرضا",'callback_data'=>"chhangeServerTypealireza_" . $match[1]]]
        ]]));
    exit();
}
if(preg_match('/^chhangeServerType(\w+)_(\d+)/',$data,$match) && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    alert($mainValues['saved_successfuly']);
    $stmt = $connection->prepare("UPDATE `server_config` SET `type` = ? WHERE `id`=?");
    $stmt->bind_param("si",$match[1], $match[2]);
    $stmt->execute();
    $stmt->close();
    
    $keys = getServerConfigKeys($match[2]);
    editText($message_id, "☑️ مدیریت سرور ها: $cname",$keys);
}
if($data=='addNewServer' and (($from_id == $admin || $userInfo['isAdmin'] == true))){
    delMessage();
    setUser('addserverName');
    sendMessage("مرحله اول: 
▪️یه اسم برا سرورت انتخاب کن:",$cancelKey);
    exit();
}
if($userInfo['step'] == 'addserverName' and $text != $buttonValues['cancel']) {
	sendMessage('مرحله دوم: 
▪️ظرفیت تعداد ساخت کانفیگ رو برای سرورت مشخص کن ( عدد باشه )');
    $data = array();
    $data['title'] = $text;

    setUser('addServerUCount' . json_encode($data,JSON_UNESCAPED_UNICODE));
    exit();
}
if(preg_match('/^addServerUCount(.*)/',$userInfo['step'],$match) and $text != $buttonValues['cancel']) {
    $data = json_decode($match[1],true);
    $data['ucount'] = $text;

    sendMessage("مرحله سوم: 
▪️یه اسم ( ریمارک ) برا کانفیگ انتخاب کن:
 ( به صورت انگیلیسی و بدون فاصله )
");
    setUser('addServerRemark' . json_encode($data,JSON_UNESCAPED_UNICODE));
    exit();
}
if(preg_match('/^addServerRemark(.*)/',$userInfo['step'], $match) and $text != $buttonValues['cancel']) {
    $data = json_decode($match[1], true);
    $data['remark'] = $text;

    sendMessage("مرحله چهارم:
▪️لطفا یه ( ایموجی پرچم 🇮🇷 ) برا سرورت انتخاب کن:");
    setUser('addServerFlag' . json_encode($data,JSON_UNESCAPED_UNICODE));
    exit();
}
if(preg_match('/^addServerFlag(.*)/',$userInfo['step'], $match) and $text != $buttonValues['cancel']) {
    $data = json_decode($match[1],true);
    $data['flag'] = $text;

    sendMessage("مرحله پنجم:

▪️لطفا آدرس پنل x-ui رو به صورت مثال زیر وارد کن:

❕https://yourdomain.com:54321
❕https://yourdomain.com:54321/path
❗️http://125.12.12.36:54321
❗️http://125.12.12.36:54321/path

اگر سرور مورد نظر با دامنه و ssl هست از مثال ( ❕) استفاده کنید
اگر سرور مورد نظر با ip و بدون ssl هست از مثال ( ❗️) استفاده کنید
⁮⁮ ⁮⁮ ⁮⁮ ⁮⁮
");
    setUser('addServerPanelUrl' . json_encode($data,JSON_UNESCAPED_UNICODE));
    exit();
}
if(preg_match('/^addServerPanelUrl(.*)/',$userInfo['step'],$match) and $text != $buttonValues['cancel']) {
    $data = json_decode($match[1],true);
    $data['panel_url'] = $text;
    setUser('addServerIp' . json_encode($data,JSON_UNESCAPED_UNICODE));
    sendMessage( "🔅 لطفا ip یا دامنه تانل شده پنل را وارد کنید:

نمونه: 
91.257.142.14
sub.domain.com
❗️در صورتی که میخواید چند دامنه یا ip کانفیگ بگیرید باید زیر هم بنویسید و برای ربات بفرستین:
    \n\n🔻برای خالی گذاشتن متن /empty را وارد کنید");
    exit();
}
if(preg_match('/^addServerIp(.*)/',$userInfo['step'],$match) and $text != $buttonValues['cancel']) {
    $data = json_decode($match[1],true);
    $data['panel_ip'] = $text;
    setUser('addServerSni' . json_encode($data, JSON_UNESCAPED_UNICODE));
    sendMessage( "🔅 لطفا sni پنل را وارد کنید\n\n🔻برای خالی گذاشتن متن /empty را وارد کنید");
    exit();
}
if(preg_match('/^addServerSni(.*)/',$userInfo['step'],$match) and $text != $buttonValues['cancel']) {
    $data = json_decode($match[1],true);
    $data['sni'] = $text;
    setUser('addServerHeaderType' . json_encode($data, JSON_UNESCAPED_UNICODE));
    sendMessage( "🔅 اگر  از header type استفاده میکنید لطفا http را تایپ کنید:\n\n🔻برای خالی گذاشتن متن /empty را وارد کنید");
    exit();
}
if(preg_match('/^addServerHeaderType(.*)/',$userInfo['step'],$match) and $text != $buttonValues['cancel']) {
    $data = json_decode($match[1],true);
    $data['header_type'] = $text;
    setUser('addServerRequestHeader' . json_encode($data, JSON_UNESCAPED_UNICODE));
    sendMessage( "🔅اگر از هدر استفاده میکنید لطفا آدرس رو به این صورت Host:test.com وارد کنید و به جای test.com آدرس دلخواه بزنید:\n\n🔻برای خالی گذاشتن متن /empty را وارد کنید");
    exit();
}
if(preg_match('/^addServerRequestHeader(.*)/',$userInfo['step'],$match) and $text != $buttonValues['cancel']) {
    $data = json_decode($match[1],true);
    $data['request_header'] = $text;
    setUser('addServerResponseHeader' . json_encode($data, JSON_UNESCAPED_UNICODE));
    sendMessage( "🔅 لطفا response header پنل را وارد کنید\n\n🔻برای خالی گذاشتن متن /empty را وارد کنید");
    exit();
}
if(preg_match('/^addServerResponseHeader(.*)/',$userInfo['step'],$match) and $text != $buttonValues['cancel']) {
    $data = json_decode($match[1],true);
    $data['response_header'] = $text;
    setUser('addServerSecurity' . json_encode($data, JSON_UNESCAPED_UNICODE));
    sendMessage( "🔅 لطفا security پنل را وارد کنید

⚠️ توجه: برای استفاده از tls یا xtls لطفا کلمه tls یا xtls رو تایپ کنید در غیر این صورت 👇
\n🔻برای خالی گذاشتن متن /empty را وارد کنید");
exit();
}
if(preg_match('/^addServerSecurity(.*)/',$userInfo['step'],$match) and $text != $buttonValues['cancel']) {
    $data = json_decode($match[1],true);
    $data['security'] = $text;
    setUser('addServerTlsSetting' . json_encode($data, JSON_UNESCAPED_UNICODE));
    sendMessage("
    🔅 لطفا tls|xtls setting پنل را وارد کنید🔻برای خالی گذاشتن متن /empty را وارد کنید 

⚠️ لطفا تنظیمات سرتیفیکیت رو با دقت انجام بدید مثال:
▫️serverName: yourdomain
▫️certificateFile: /root/cert.crt
▫️keyFile: /root/private.key
\n
"
        .'<b>tls setting:</b> <code>{"serverName": "","certificates": [{"certificateFile": "","keyFile": ""}]}</code>' . "\n"
        .'<b>xtls setting:</b> <code>{"serverName": "","certificates": [{"certificateFile": "","keyFile": ""}],"alpn": []}</code>', null, "HTML");

    exit();
}
if(preg_match('/^addServerTlsSetting(.*)/',$userInfo['step'],$match) and $text != $buttonValues['cancel']) {
    $data = json_decode($match[1],true);
    $data['tls_setting'] = $text;
    setUser('addServerPanelUser' . json_encode($data, JSON_UNESCAPED_UNICODE));
    sendMessage( "مرحله ششم: 
▪️لطفا یوزر پنل را وارد کنید:");

    exit();
}
if(preg_match('/^addServerPanelUser(.*)/',$userInfo['step'],$match) and $text != $buttonValues['cancel']) {
    $data = json_decode($match[1],true);
    $data['panel_user'] = $text;
    setUser('addServerPanePassword' . json_encode($data, JSON_UNESCAPED_UNICODE));
    sendMessage( "مرحله هفتم: 
▪️لطفا پسورد پنل را وارد کنید:");
exit();
}
if(preg_match('/^addServerPanePassword(.*)/',$userInfo['step'],$match) and $text != $buttonValues['cancel']){
    sendMessage("⏳ در حال ورود به اکانت ...");
    $data = json_decode($match[1],true);

    $title = $data['title'];
    $ucount = $data['ucount'];
    $remark = $data['remark'];
    $flag = $data['flag'];

    $panel_url = $data['panel_url'];
    $ip = $data['panel_ip']!="/empty"?$data['panel_ip']:"";
    $sni = $data['sni']!="/empty"?$data['sni']:"";
    $header_type = $data['header_type']!="/empty"?$data['header_type']:"none";
    $request_header = $data['request_header']!="/empty"?$data['request_header']:"";
    $response_header = $data['response_header']!="/empty"?$data['response_header']:"";
    $security = $data['security']!="/empty"?$data['security']:"none";
    $tlsSettings = $data['tls_setting']!="/empty"?$data['tls_setting']:"";
    $serverName = $data['panel_user'];
    $serverPass = $text;
    $loginUrl = $panel_url . '/login';
    $postFields = array(
        "username" => $serverName,
        "password" => $serverPass
        );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $loginUrl);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postFields));
    curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . '/tempCookie.txt');
    $loginResponse = json_decode(curl_exec($ch),true);
    curl_close($ch);
    if(!$loginResponse['success']){
        setUser('addServerPanelUser' . json_encode($data, JSON_UNESCAPED_UNICODE));
        sendMessage( "
⚠️ با خطا مواجه شدی ! 

برای رفع این مشکل روی لینک زیر بزن و ویس رو با دقت گوش کن 👇

⛔️🔗 https://t.me/testbotnoovix/8

مجدد نام کاربری پنل را وارد کنید:
⁮⁮ ⁮⁮
        ");
        exit();
    }
    unlink("tempCookie.txt");
    $stmt = $connection->prepare("INSERT INTO `server_info` (`title`, `ucount`, `remark`, `flag`, `active`)
                                                    VALUES (?,?,?,?,1)");
    $stmt->bind_param("siss", $title, $ucount, $remark, $flag);
    $stmt->execute();
    $rowId = $stmt->insert_id;
    $stmt->close();


    $stmt = $connection->prepare("INSERT INTO `server_config` (`id`, `panel_url`, `ip`, `sni`, `header_type`, `request_header`, `response_header`, `security`, `tlsSettings`, `username`, `password`)
                                           VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("issssssssss", $rowId, $panel_url, $ip, $sni, $header_type, $request_header, $response_header, $security, $tlsSettings, $serverName, $serverPass);
    $stmt->execute();
    $rowId = $stmt->insert_id;
    $stmt->close();

    sendMessage(" تبریک ; سرورت رو ثبت کردی 🥹",$removeKeyboard);

        sendMessage("
    
🔰 نکته مهم: ( پنل x-ui خود را به آخرین نسخه آپدیت کنید ) 

❤️ اگر از پنل سنایی استفاده میکنید لطفا نوع پنل را ( سنایی ) انتخاب کنید
🧡 اگر از پنل علیرضا استفاده میکنید لطفا نوع پنل را ( علیرضا ) انتخاب کنید
💚 اگر از پنل نیدوکا استفاده میکنید لطفا نوع پنل را ( ساده ) انتخاب کنید 
💙 اگر از پنل چینی استفاده میکنید لطفا نوع پنل را ( ساده ) انتخاب کنید 
⁮⁮ ⁮⁮ ⁮⁮ ⁮⁮
📣 حتما نوع پنل را انتخاب کنید وگرنه براتون مشکل ساز میشه !
⁮⁮ ⁮⁮ ⁮⁮ ⁮⁮
    ",json_encode(['inline_keyboard'=>[
            [['text'=>"ساده",'callback_data'=>"chhangeServerTypenormal_" . $rowId],['text'=>"سنایی",'callback_data'=>"chhangeServerTypesanaei_" . $rowId]],
            [['text'=>"علیرضا",'callback_data'=>"chhangeServerTypealireza_" . $rowId]]
            ]]));
    setUser();
    exit();
}
if(preg_match('/^changesServerLoginInfo(\d+)/',$data,$match)) {
    delMessage();
    setUser($data);
    sendMessage( "▪️لطفا آدرس پنل را وارد کنید:",$cancelKey);
}
if(preg_match('/^changesServerLoginInfo(\d+)/',$userInfo['step'],$match) && $text != $buttonValues['cancel']) {
    $data = array();
    $data['rowId'] = $match[1];
    $data['panel_url'] = $text;
    setUser('editServerPaneUser' . json_encode($data, JSON_UNESCAPED_UNICODE));
    sendMessage( "▪️لطفا یوزر پنل را وارد کنید:",$cancelKey);
    exit();
}
if(preg_match('/^editServerPaneUser(.*)/',$userInfo['step'],$match) && $text != $buttonValues['cancel']) {
    $data = json_decode($match[1],true);
    $data['panel_user'] = $text;
    setUser('editServerPanePassword' . json_encode($data, JSON_UNESCAPED_UNICODE));
    sendMessage( "▪️لطفا پسورد پنل را وارد کنید:");
    exit();
}
if(preg_match('/^editServerPanePassword(.*)/',$userInfo['step'],$match) and $text != $buttonValues['cancel']){
    sendMessage("⏳ در حال ورود به اکانت ...");
    $data = json_decode($match[1],true);

    $rowId = $data['rowId'];
    $panel_url = $data['panel_url'];
    $serverName = $data['panel_user'];
    $serverPass = $text;
    $loginUrl = $panel_url . '/login';
    $postFields = array(
        "username" => $serverName,
        "password" => $serverPass
        );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $loginUrl);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postFields));
    curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . '/tempCookie.txt');
    $loginResponse = json_decode(curl_exec($ch),true);
    curl_close($ch);
    if(!$loginResponse['success']) sendMessage( "اطلاعاتی که وارد کردی اشتباهه 😂");
    else{
        $stmt = $connection->prepare("UPDATE `server_config` SET `panel_url` = ?, `username` = ?, `password` = ? WHERE `id` = ?");
        $stmt->bind_param("sssi", $panel_url, $serverName, $serverPass, $rowId);
        $stmt->execute();
        $stmt->close();
        
        sendMessage("اطلاعات ورود سرور با موفقیت عوض شد",$removeKeyboard);
    }
    unlink("tempCookie.txt");

    $keys = getServerConfigKeys($rowId);
    sendMessage('☑️ مدیریت سرور ها:',$keys);
    setUser();
}
if(preg_match('/^wizwizdeleteserver(\d+)/',$data,$match) and ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $stmt = $connection->prepare("DELETE FROM `server_info` WHERE `id`=?");
    $stmt->bind_param("i", $match[1]);
    $stmt->execute();
    $stmt->close();
    
    $stmt = $connection->prepare("DELETE FROM `server_config` WHERE `id`=?");
    $stmt->bind_param("i", $match[1]);
    $stmt->execute();
    $stmt->close();

    alert("🙂 سرور رو چرا حذف کردی اخه ...");
    

    $keys = getServerListKeys();
    if($keys == null) editText($message_id,"موردی یافت نشد");
    else editText($message_id,"☑️ مدیریت سرور ها:",$keys);
}
if(preg_match('/^editServer(\D+)(\d+)/',$data,$match) && $text != $buttonValues['cancel']){
    switch($match[1]){
        case "Name":
            $txt ="اسم";
            break;
        case "Max":
            $txt = "ظرفیت";
            break;
        case "Remark":
            $txt ="ریمارک";
            break;
        case "Flag":
            $txt = "پرچم";
            break;
        default:
            $txt = str_replace("_", " ", $match[1]);
            $end = "برای خالی کردن متن /empty را وارد کنید";
            break;
    }
    delMessage();
    sendMessage("🔘|لطفا " . $txt . " جدید را وارد کنید" . $end,$cancelKey);
    setUser($data);
    exit();
}
if(preg_match('/^editServer(\D+)(\d+)/',$userInfo['step'],$match) && $text != $buttonValues['cancel']){
    switch($match[1]){
        case "Name":
            $txt ="title";
            break;
        case "Max":
            $txt = "ucount";
            break;
        case "Remark":
            $txt ="remark";
            break;
        case "Flag":
            $txt = "flag";
            break;
        default:
            $txt = $match[1];
            break;
    }
    
    if($text == "/empty"){
        $stmt = $connection->prepare("UPDATE `server_info` SET `$txt` IS NULL WHERE `id`=?");
        $stmt->bind_param("i", $match[2]);
        $stmt->execute();
        $stmt->close();
    }else{
        $stmt = $connection->prepare("UPDATE `server_info` SET `$txt`=? WHERE `id`=?");
        $stmt->bind_param("si",$text, $match[2]);
        $stmt->execute();
        $stmt->close();
    }
    
    sendMessage($mainValues['saved_successfuly'],$removeKeyboard);
    setUser();
    
    $keys = getServerConfigKeys($match[2]);
    sendMessage("مدیریت سرور $cname",$keys);
    exit();
}
if(preg_match('/^editsServer(\D+)(\d+)/',$data,$match) && $text != $buttonValues['cancel']){
    $txt = str_replace("_", " ", $match[1]);
    delMessage();
    sendMessage("🔘|لطفا " . $txt . " جدید را وارد کنید\nبرای خالی کردن متن /empty را وارد کنید",$cancelKey);
    setUser($data);
    exit();
}
if(preg_match('/^editsServer(\D+)(\d+)/',$userInfo['step'],$match) && $text != $buttonValues['cancel']){
    if($text == "/empty"){
        if($match[1] == "header_type" || $match[1] == "security"){
            $stmt = $connection->prepare("UPDATE `server_config` SET `{$match[1]}` = 'none' WHERE `id`=?");
            $stmt->bind_param("i", $match[2]);
        }else{
            $stmt = $connection->prepare("UPDATE `server_config` SET `{$match[1]}` = '' WHERE `id`=?");
            $stmt->bind_param("i", $match[2]);
        }
    }else{
        if($match[1] == "header_type" && $text != "http" && $text != "none"){
            sendMessage("برای نوع header type فقط none و یا http مجاز است");
            exit();
        }
        elseif($match[1] == "security" && $text != "tls" && $text != "none" && $text != "xtls"){
            sendMessage("برای نوع security فقط tls یا xtls و یا هم none مجاز است");
            exit();
        }
        $stmt = $connection->prepare("UPDATE `server_config` SET `{$match[1]}`=? WHERE `id`=?");
        $stmt->bind_param("si",$text, $match[2]);
    }
    $stmt->execute();
    $stmt->close();
    
    sendMessage($mainValues['saved_successfuly'],$removeKeyboard);
    setUser();
    
    $keys = getServerConfigKeys($match[2]);
    sendMessage("مدیریت سرور $cname",$keys);
    exit();
}
if(preg_match('/^editServer(\D+)(\d+)/',$data,$match) && $text != $buttonValues['cancel']){
    switch($match[1]){
        case "Name":
            $txt ="اسم";
            break;
        case "Max":
            $txt = "ظرفیت";
            break;
        case "Remark":
            $txt ="ریمارک";
            break;
        case "Flag":
            $txt = "پرچم";
            break;
    }
    delMessage();
    sendMessage("🔘|لطفا " . $txt . " جدید را وارد کنید",$cancelKey);
    setUser($data);
}
if(preg_match('/^editServer(\D+)(\d+)/',$userInfo['step'],$match) && $text != $buttonValues['cancel']){
    switch($match[1]){
        case "Name":
            $txt ="title";
            break;
        case "Max":
            $txt = "ucount";
            break;
        case "Remark":
            $txt ="remark";
            break;
        case "Flag":
            $txt = "flag";
            break;
    }
    
    $stmt = $connection->prepare("UPDATE `server_info` SET `$txt`=? WHERE `id`=?");
    $stmt->bind_param("si",$text, $match[2]);
    $stmt->execute();
    $stmt->close();
    
    sendMessage($mainValues['saved_successfuly'],$removeKeyboard);
    setUser();
    
    $keys = getServerConfigKeys($match[2]);
    sendMessage("مدیریت سرور $cname",$keys);
}
if($data=="discount_codes" && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    editText($message_id,"مدیریت کد های تخفیف",getDiscountCodeKeys());
}
if($data=="addDiscountCode" && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    delMessage();
    sendMessage("🔘|لطفا مقدار تخفیف را وارد کنید\nبرای درصد علامت % را در کنار عدد وارد کنید در غیر آن مقدار تخفیف به تومان محاسبه میشود",$cancelKey);
    setUser($data);
}
if($userInfo['step'] == "addDiscountCode" && $text != $buttonValues['cancel'] && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $dInfo = array();
    $dInfo['type'] = 'amount';
    if(strpos($text, "%")) $dInfo['type'] = 'percent';
    $text = trim(str_replace("%", "", $text));
    if(is_numeric($text)){
        $dInfo['amount'] = $text;
        setUser("addDiscountDate" . json_encode($dInfo,JSON_UNESCAPED_UNICODE));
        sendMessage("🔘|لطفا مدت زمان این تخفیف را به روز وارد کنید\nبرای نامحدود بودن 0 وارد کنید");
    }else sendMessage("🔘|لطفا فقط عدد و یا درصد بفرستید");
}
if(preg_match('/^addDiscountDate(.*)/',$userInfo['step'],$match) && $text != $buttonValues['cancel'] && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    if(is_numeric($text)){
        $dInfo = json_decode($match[1],true);
        $dInfo['date'] = $text != 0?time() + ($text * 24 * 60 * 60):0;
        
        setUser("addDiscountCount" . json_encode($dInfo,JSON_UNESCAPED_UNICODE));
        sendMessage("🔘|لطفا تعداد استفاده این تخفیف را وارد کنید\nبرای نامحدود بودن 0 وارد کنید");
    }else sendMessage("🔘|لطفا فقط عدد بفرستید");
}
if(preg_match('/^addDiscountCount(.*)/',$userInfo['step'],$match) && $text != $buttonValues['cancel'] && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    if(is_numeric($text)){ 
        $dInfo = json_decode($match[1],true);
        $dInfo['count'] = $text>0?$text:-1;
        
        setUser('addDiscountCanUse' . json_encode($dInfo,JSON_UNESCAPED_UNICODE));
        sendMessage("لطفا تعداد استفاده هر یوزر را وارد کنید");
    }else sendMessage("🔘|لطفا فقط عدد بفرستید");
}
if(preg_match('/^addDiscountCanUse(.*)/',$userInfo['step'],$match) && $text != $buttonValues['cancel'] && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    if(is_numeric($text)){ 
        $dInfo = json_decode($match[1],true);
        $dInfo['can_use'] = $text>0?$text:-1;
         
        $hashId = RandomString();
        
        $stmt = $connection->prepare("INSERT INTO `discounts` (`hash_id`, `type`, `amount`, `expire_date`, `expire_count`, `can_use`)
                                        VALUES (?,?,?,?,?,?)");
        $stmt->bind_param("ssiiii", $hashId, $dInfo['type'], $dInfo['amount'], $dInfo['date'], $dInfo['count'], $dInfo['can_use']);
        $stmt->execute();
        $stmt->close();
        sendMessage("کد تخفیف جدید (<code>$hashId</code>) با موفقیت ساخته شد",$removeKeyboard,"HTML");
        setUser();
        sendMessage("مدیریت کد های تخفیف",getDiscountCodeKeys());
    }else sendMessage("🔘|لطفا فقط عدد بفرستید");
}

// ==================== هندلرهای سیستم جدید خرید سرویس ====================

// نمایش دسته‌بندی‌های سرویس
if($data == 'buyService'){
    $stmt = $connection->prepare("SELECT * FROM `plan_categories` WHERE `status`='active' ORDER BY `sort_order` ASC");
    $stmt->execute();
    $categories = $stmt->get_result();
    $stmt->close();
    
    if($categories->num_rows == 0){
        alert("⚠️ در حال حاضر سرویسی موجود نیست!");
        exit;
    }
    
    $message = "🔥 <b>خرید سرویس APN</b>\n\n";
    $message .= "📦 لطفا دسته‌بندی مورد نظر خود را انتخاب کنید:";
    
    $keyboard = [];
    while($cat = $categories->fetch_assoc()){
        $keyboard[] = [['text' => "{$cat['emoji']} {$cat['name']}", 'callback_data' => "showPlansInCategory_{$cat['id']}"]];
    }
    $keyboard[] = [['text' => '🔙 بازگشت', 'callback_data' => 'mainMenu']];
    
    delMessage();
    sendMessage($message, json_encode(['inline_keyboard' => $keyboard]), 'HTML');
    exit;
}

// نمایش تعرفه‌های یک دسته
if(preg_match('/^showPlansInCategory_(\d+)$/', $data, $match)){
    $category_id = $match[1];
    
    // دریافت اطلاعات دسته
    $stmt = $connection->prepare("SELECT * FROM `plan_categories` WHERE `id`=? AND `status`='active'");
    $stmt->bind_param("i", $category_id);
    $stmt->execute();
    $category = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if(!$category){
        alert("❌ دسته‌بندی یافت نشد!");
        exit;
    }
    
    // دریافت تعرفه‌های این دسته
    $stmt = $connection->prepare("SELECT sp.*, s.name as server_name, s.location 
                                   FROM `service_plans` sp 
                                   JOIN `servers` s ON sp.server_id = s.id 
                                   WHERE sp.category_id = ? AND sp.status = 'active' AND s.status = 'active' 
                                   ORDER BY sp.price ASC");
    $stmt->bind_param("i", $category_id);
    $stmt->execute();
    $plans = $stmt->get_result();
    $stmt->close();
    
    if($plans->num_rows == 0){
        alert("⚠️ تعرفه‌ای در این دسته موجود نیست!");
        exit;
    }
    
    $message = "{$category['emoji']} <b>{$category['name']}</b>\n\n";
    $message .= "📋 تعرفه‌های موجود:\n\n";
    
    $keyboard = [];
    while($plan = $plans->fetch_assoc()){
        // نمایش نامحدود با حداکثر 200 گیگ
        if($plan['volume_gb'] == 0){
            $volume_text = 'نامحدود (حداکثر 200GB)';
        } else {
            $volume_text = $plan['volume_gb'] . ' گیگ';
        }
        $price_text = number_format($plan['price']);
        
        $message .= "━━━━━━━━━━━━━━━━━━\n";
        $message .= "📦 <b>{$plan['name']}</b>\n";
        $message .= "🔋 حجم: <code>{$volume_text}</code>\n";
        $message .= "⏰ مدت: <code>{$plan['days']} روز</code>\n";
        $message .= "🌍 لوکیشن: <code>{$plan['location']}</code>\n";
        $message .= "💰 قیمت: <code>{$price_text} تومان</code>\n";
        $message .= "━━━━━━━━━━━━━━━━━━\n\n";
        
        $keyboard[] = [['text' => "🛒 خرید {$plan['name']}", 'callback_data' => "buyPlan_{$plan['id']}"]];  
    }
    
    // دکمه کد تخفیف بعد از لیست پلن‌ها
    $keyboard[] = [['text' => '🎫 کد تخفیف دارید؟', 'callback_data' => "categoryDiscount_{$category_id}"]];
    $keyboard[] = [['text' => '🔙 بازگشت', 'callback_data' => 'buyService']];    delMessage();
    sendMessage($message, json_encode(['inline_keyboard' => $keyboard]), 'HTML');
    exit;
}

// خرید تعرفه
if(preg_match('/^buyPlan_(\d+)$/', $data, $match)){
    $plan_id = $match[1];
    
    $stmt = $connection->prepare("SELECT sp.*, pc.name as category_name, pc.id as category_id, s.name as server_name, s.location 
                                   FROM `service_plans` sp 
                                   JOIN `plan_categories` pc ON sp.category_id = pc.id 
                                   JOIN `servers` s ON sp.server_id = s.id 
                                   WHERE sp.id = ? AND sp.status = 'active' AND s.status = 'active'");
    $stmt->bind_param("i", $plan_id);
    $stmt->execute();
    $plan = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if(!$plan){
        alert("❌ تعرفه یافت نشد یا غیرفعال است!");
        exit;
    }
    
    // نمایش نامحدود با حداکثر 200 گیگ
    if($plan['volume_gb'] == 0){
        $volume_text = 'نامحدود (حداکثر 200GB)';
    } else {
        $volume_text = $plan['volume_gb'] . ' گیگابایت';
    }
    $price_text = number_format($plan['price']);
    
    // چک کردن تابع jdate
    if(function_exists('jdate')){
        $expire_shamsi = jdate('Y/m/d', strtotime('+' . $plan['days'] . ' days'));
    } else {
        $expire_shamsi = date('Y-m-d', strtotime('+' . $plan['days'] . ' days'));
    }
    
    $message = "🛒 <b>تایید خرید</b>\n\n";
    $message .= "━━━━━━━━━━━━━━━━━━\n";
    $message .= "📦 <b>{$plan['name']}</b>\n";
    $message .= "━━━━━━━━━━━━━━━━━━\n\n";
    $message .= "📂 دسته: <code>{$plan['category_name']}</code>\n";
    $message .= "🖥️ سرور: <code>{$plan['server_name']}</code>\n";
    $message .= "🌍 لوکیشن: <code>{$plan['location']}</code>\n";
    $message .= "🔋 حجم: <code>{$volume_text}</code>\n";
    $message .= "⏰ مدت: <code>{$plan['days']} روز</code>\n";
    $message .= "📅 انقضا: <code>{$expire_shamsi}</code>\n\n";
    $message .= "💰 <b>مبلغ قابل پرداخت: {$price_text} تومان</b>\n\n";
    $message .= "━━━━━━━━━━━━━━━━━━\n";
    $message .= "💳 روش پرداخت خود را انتخاب کنید:";
    
    // چک اگر کد تخفیف در temp دارد
    $has_discount = !empty($userInfo['temp']);
    
    $keyboard = [];
    
    if(!$has_discount){
        // اگر کد تخفیف ندارد، دکمه اعمال تخفیف نمایش بده
        $keyboard[] = [['text' => '🎫 کد تخفیف دارید؟', 'callback_data' => "applyDiscount_{$plan_id}"]];
    }
    
    $keyboard[] = [['text' => '💳 پرداخت از کیف پول', 'callback_data' => "payFromWallet_{$plan_id}"]];
    $keyboard[] = [['text' => '🏦 پرداخت فیش بانکی', 'callback_data' => "payByReceipt_{$plan_id}"]];
    $keyboard[] = [['text' => '🔙 انصراف', 'callback_data' => "showPlansInCategory_{$plan['category_id']}"]];
    
    delMessage();
    sendMessage($message, json_encode(['inline_keyboard' => $keyboard]), 'HTML');
    exit;
}

// اعمال کد تخفیف
if(preg_match('/^applyDiscount_(\d+)$/', $data, $match)){
    $plan_id = $match[1];
    
    delMessage();
    setUser("waitingDiscountCode_{$plan_id}", 'step');
    sendMessage("🎫 لطفا کد تخفیف خود را وارد کنید:\n\n💡 مثال: <code>WELCOME10</code>", $cancelKey, 'HTML');
    exit;
}

// اعمال کد تخفیف از صفحه دسته‌بندی
if(preg_match('/^categoryDiscount_(\d+)$/', $data, $match)){
    $category_id = $match[1];
    
    delMessage();
    setUser("waitingCategoryDiscount_{$category_id}", 'step');
    sendMessage("🎫 <b>کد تخفیف</b>\n\nلطفا کد تخفیف خود را وارد کنید:\n\n💡 مثال: <code>WELCOME10</code>\n\n✅ بعد از وارد کردن کد، پلن مورد نظر خود را انتخاب کنید.", $cancelKey, 'HTML');
    exit;
}

// دریافت کد تخفیف از صفحه دسته‌بندی
if(preg_match('/^waitingCategoryDiscount_(\d+)$/', $userInfo['step'], $match) && $text){
    if($text == $buttonValues['cancel']){
        setUser('none', 'step');
        $data = "showPlansInCategory_{$match[1]}";
        // برگشت به لیست پلن‌ها
    } else {
        $category_id = $match[1];
        $code = strtoupper(trim($text));
        
        // بررسی وجود کد
        $stmt = $connection->prepare("SELECT * FROM `discounts` WHERE `code` = ? AND `status` = 'active'");
        $stmt->bind_param("s", $code);
        $stmt->execute();
        $discount = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        
        if(!$discount){
            sendMessage("❌ کد تخفیف نامعتبر است!\n\nلطفا دوباره امتحان کنید.", $cancelKey);
            exit;
        }
        
        // چک تاریخ انقضا
        if($discount['expire_date'] && $discount['expire_date'] < time()){
            sendMessage("❌ کد تخفیف منقضی شده است!", $cancelKey);
            exit;
        }
        
        // چک تعداد استفاده
        if($discount['max_use'] > 0 && $discount['used_count'] >= $discount['max_use']){
            sendMessage("❌ ظرفیت استفاده از این کد تخفیف تمام شده است!", $cancelKey);
            exit;
        }
        
        // چک استفاده قبلی این کاربر
        $stmt = $connection->prepare("SELECT COUNT(*) as cnt FROM `discount_usage` WHERE `user_id` = ? AND `discount_id` = ?");
        $stmt->bind_param("ii", $from_id, $discount['id']);
        $stmt->execute();
        $usage = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        
        if($usage['cnt'] > 0){
            sendMessage("❌ شما قبلاً از این کد تخفیف استفاده کرده‌اید!", $cancelKey);
            exit;
        }
        
        // ذخیره کد در temp
        setUser($code, 'temp');
        setUser('none', 'step');
        
        $discount_text = $discount['type'] == 'fixed' 
            ? number_format($discount['amount']) . ' تومان' 
            : $discount['amount'] . '%';
        
        sendMessage("✅ <b>کد تخفیف معتبر است!</b>\n\n🎫 تخفیف: <code>{$discount_text}</code>\n\n🛒 حالا پلن مورد نظر خود را انتخاب کنید.\n\n💰 تخفیف به صورت خودکار در زمان پرداخت اعمال می‌شود.", getMainKeys(), 'HTML');
        
        // برگشت به لیست پلن‌ها
        $data = "showPlansInCategory_{$category_id}";
    }
}

// اعمال کد تخفیف از صفحه دسته‌بندی
if(preg_match('/^categoryDiscount_(\d+)$/', $data, $match)){
    $category_id = $match[1];
    
    delMessage();
    setUser("waitingCategoryDiscount_{$category_id}", 'step');
    sendMessage("🎫 <b>کد تخفیف</b>\n\nلطفا کد تخفیف خود را وارد کنید:\n\n💡 مثال: <code>WELCOME10</code>\n\n✅ بعد از وارد کردن کد، پلن مورد نظر خود را انتخاب کنید.", $cancelKey, 'HTML');
    exit;
}

// دریافت کد تخفیف از صفحه دسته‌بندی
if(preg_match('/^waitingCategoryDiscount_(\d+)$/', $userInfo['step'], $match) && $text){
    if($text == $buttonValues['cancel']){
        setUser('none', 'step');
        $data = "showPlansInCategory_{$match[1]}";
        // برگشت به لیست پلن‌ها
    } else {
        $category_id = $match[1];
        $code = strtoupper(trim($text));
        
        // بررسی وجود کد
        $stmt = $connection->prepare("SELECT * FROM `discounts` WHERE `code` = ? AND `status` = 'active'");
        $stmt->bind_param("s", $code);
        $stmt->execute();
        $discount = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        
        if(!$discount){
            sendMessage("❌ کد تخفیف نامعتبر است!\n\nلطفا دوباره امتحان کنید.", $cancelKey);
            exit;
        }
        
        // چک تاریخ انقضا
        if($discount['expire_date'] && $discount['expire_date'] < time()){
            sendMessage("❌ کد تخفیف منقضی شده است!", $cancelKey);
            exit;
        }
        
        // چک تعداد استفاده
        if($discount['max_use'] > 0 && $discount['used_count'] >= $discount['max_use']){
            sendMessage("❌ ظرفیت استفاده از این کد تخفیف تمام شده است!", $cancelKey);
            exit;
        }
        
        // چک استفاده قبلی این کاربر
        $stmt = $connection->prepare("SELECT COUNT(*) as cnt FROM `discount_usage` WHERE `user_id` = ? AND `discount_id` = ?");
        $stmt->bind_param("ii", $from_id, $discount['id']);
        $stmt->execute();
        $usage = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        
        if($usage['cnt'] > 0){
            sendMessage("❌ شما قبلاً از این کد تخفیف استفاده کرده‌اید!", $cancelKey);
            exit;
        }
        
        // ذخیره کد در temp
        setUser($code, 'temp');
        setUser('none', 'step');
        
        $discount_text = $discount['type'] == 'fixed' 
            ? number_format($discount['amount']) . ' تومان' 
            : $discount['amount'] . '%';
        
        sendMessage("✅ <b>کد تخفیف معتبر است!</b>\n\n🎫 تخفیف: <code>{$discount_text}</code>\n\n🛍 حالا پلن مورد نظر خود را انتخاب کنید.\n\n💰 تخفیف به صورت خودکار در زمان پرداخت اعمال می‌شود.", getMainKeys(), 'HTML');
        
        // بازگشت به لیست پلن‌ها
        $data = "showPlansInCategory_{$category_id}";
    }
}

// اعمال کد تخفیف
if(preg_match('/^applyDiscount_(\d+)$/', $data, $match)){
    $plan_id = $match[1];
    
    delMessage();
    setUser("waitingDiscountCode_{$plan_id}", 'step');
    sendMessage("🎟️ لطفا کد تخفیف خود را وارد کنید:", $cancelKey);
    exit;
}

// دریافت کد تخفیف
if(preg_match('/^waitingDiscountCode_(\d+)$/', $userInfo['step'], $match) && $text){
    if($text == $buttonValues['cancel']){
        setUser('none', 'step');
        sendMessage("❌ لغو شد", getMainKeys());
        exit;
    }
    
    $plan_id = $match[1];
    $code = trim($text);
    
    // بررسی کد تخفیف
    $stmt = $connection->prepare("SELECT * FROM `discounts` WHERE `code` = ? AND `status` = 'active'");
    $stmt->bind_param("s", $code);
    $stmt->execute();
    $discount = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if(!$discount){
        sendMessage("❌ کد تخفیف نامعتبر است!", $cancelKey);
        exit;
    }
    
    // چک تاریخ انقضا
    if($discount['expire_date'] && strtotime($discount['expire_date']) < time()){
        sendMessage("❌ کد تخفیف منقضی شده است!", $cancelKey);
        exit;
    }
    
    // چک تعداد استفاده
    if($discount['max_use'] > 0 && $discount['used_count'] >= $discount['max_use']){
        sendMessage("❌ ظرفیت استفاده از این کد تخفیف تمام شده است!", $cancelKey);
        exit;
    }
    
    // چک استفاده قبلی این کاربر
    $stmt = $connection->prepare("SELECT COUNT(*) as cnt FROM `discount_usage` WHERE `user_id` = ? AND `discount_id` = ?");
    $stmt->bind_param("ii", $from_id, $discount['id']);
    $stmt->execute();
    $usage = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if($usage['cnt'] > 0){
        sendMessage("❌ شما قبلاً از این کد تخفیف استفاده کرده‌اید!", $cancelKey);
        exit;
    }
    
    // دریافت اطلاعات پلن
    $stmt = $connection->prepare("SELECT sp.*, pc.name as category_name 
                                   FROM `service_plans` sp 
                                   JOIN `plan_categories` pc ON sp.category_id = pc.id 
                                   WHERE sp.id = ? AND sp.status = 'active'");
    $stmt->bind_param("i", $plan_id);
    $stmt->execute();
    $plan = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if(!$plan){
        sendMessage("❌ تعرفه یافت نشد!", getMainKeys());
        setUser('none', 'step');
        exit;
    }
    
    // محاسبه تخفیف
    $original_price = $plan['price'];
    if($discount['type'] == 'percent'){
        $discount_amount = ($original_price * $discount['amount']) / 100;
    } else {
        $discount_amount = $discount['amount'];
    }
    
    $final_price = max(0, $original_price - $discount_amount);
    
    // ذخیره کد تخفیف برای این سفارش
    setUser("discountApplied_{$plan_id}_{$discount['id']}", 'step');
    
    // نمایش قیمت با تخفیف
    $volume_text = $plan['volume_gb'] == 0 ? 'نامحدود (حداکثر 200GB)' : $plan['volume_gb'] . ' گیگابایت';
    $original_price_text = number_format($original_price);
    $discount_text = number_format($discount_amount);
    $final_price_text = number_format($final_price);
    
    if(function_exists('jdate')){
        $expire_shamsi = jdate('Y/m/d', strtotime('+' . $plan['days'] . ' days'));
    } else {
        $expire_shamsi = date('Y-m-d', strtotime('+' . $plan['days'] . ' days'));
    }
    
    $message = "🎉 <b>کد تخفیف با موفقیت اعمال شد!</b>\n\n";
    $message .= "🛒 <b>تایید خرید</b>\n\n";
    $message .= "━━━━━━━━━━━━━━━━━━\n";
    $message .= "📦 <b>{$plan['name']}</b>\n";
    $message .= "━━━━━━━━━━━━━━━━━━\n\n";
    $message .= "📂 دسته: <code>{$plan['category_name']}</code>\n";
    $message .= "🔋 حجم: <code>{$volume_text}</code>\n";
    $message .= "⏰ مدت: <code>{$plan['days']} روز</code>\n";
    $message .= "📅 انقضا: <code>{$expire_shamsi}</code>\n\n";
    $message .= "━━━━━━━━━━━━━━━━━━\n";
    $message .= "💵 قیمت اصلی: <s>{$original_price_text}</s> تومان\n";
    $message .= "🎟️ تخفیف: <code>{$discount_text}</code> تومان\n";
    $message .= "💰 <b>قیمت نهایی: {$final_price_text} تومان</b>\n\n";
    $message .= "━━━━━━━━━━━━━━━━━━\n";
    $message .= "💳 روش پرداخت خود را انتخاب کنید:";
    
    $keyboard = [
        [['text' => '💳 پرداخت از کیف پول', 'callback_data' => "payFromWalletWithDiscount_{$plan_id}_{$discount['id']}"]],
        [['text' => '🏦 پرداخت فیش بانکی', 'callback_data' => "payByReceiptWithDiscount_{$plan_id}_{$discount['id']}"]],
        [['text' => '🔙 انصراف', 'callback_data' => "buyPlan_{$plan_id}"]]
    ];
    
    sendMessage($message, json_encode(['inline_keyboard' => $keyboard]), 'HTML');
    exit;
}

// پرداخت از کیف پول
if(preg_match('/^payFromWallet_(\d+)$/', $data, $match)){
    $plan_id = $match[1];
    
    $stmt = $connection->prepare("SELECT * FROM `service_plans` WHERE `id` = ? AND `status` = 'active'");
    $stmt->bind_param("i", $plan_id);
    $stmt->execute();
    $plan = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if(!$plan){
        alert("❌ تعرفه یافت نشد!");
        exit;
    }
    
    // اعمال تخفیف اگر کد دارد
    include_once 'discount_system.php';
    $price_info = applyDiscount($from_id, $plan['price'], $plan_id);
    $final_price = $price_info['price'];
    $discount_amount = $price_info['discount'];
    $discount_code = $price_info['code'];
    
    if($userInfo['wallet'] < $final_price){
        alert("❌ موجودی کیف پول شما کافی نیست!\n\nموجودی: " . number_format($userInfo['wallet']) . " تومان\nمورد نیاز: " . number_format($final_price) . " تومان");
        exit;
    }
    
    // کسر از کیف پول
    $new_wallet = $userInfo['wallet'] - $final_price;
    $stmt = $connection->prepare("UPDATE `users` SET `wallet` = ? WHERE `userid` = ?");
    $stmt->bind_param("ii", $new_wallet, $from_id);
    $stmt->execute();
    $stmt->close();
    
    // ساخت سرویس
    $hash_id = RandomString();
    $result = createServiceAccount($from_id, $plan_id, $hash_id);
    
    if($result['success']){
        delMessage();
        
        $success_msg = "✅ پرداخت موفق!\n\n";
        if($discount_amount > 0 && $discount_code){
            $success_msg .= "🎫 کد تخفیف: <code>{$discount_code}</code>\n";
            $success_msg .= "💰 تخفیف: " . number_format($discount_amount) . " تومان\n";
            $success_msg .= "💵 پرداخت شده: " . number_format($final_price) . " تومان\n\n";
        }
        $success_msg .= "🎉 سرویس شما در حال آماده‌سازی است...";
        
        sendMessage($success_msg, $removeKeyboard, 'HTML');
    } else {
        // بازگشت پول
        $stmt = $connection->prepare("UPDATE `users` SET `wallet` = ? WHERE `userid` = ?");
        $old_wallet = $userInfo['wallet'];
        $stmt->bind_param("ii", $old_wallet, $from_id);
        $stmt->execute();
        $stmt->close();
        
        alert("❌ خطا در ساخت سرویس: " . $result['error']);
    }
    exit;
}

// پرداخت از کیف پول با تخفیف
if(preg_match('/^payFromWalletWithDiscount_(\d+)_(\d+)$/', $data, $match)){
    $plan_id = $match[1];
    $discount_id = $match[2];
    
    $stmt = $connection->prepare("SELECT * FROM `service_plans` WHERE `id` = ? AND `status` = 'active'");
    $stmt->bind_param("i", $plan_id);
    $stmt->execute();
    $plan = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if(!$plan){
        alert("❌ تعرفه یافت نشد!");
        exit;
    }
    
    // بررسی کد تخفیف
    $stmt = $connection->prepare("SELECT * FROM `discounts` WHERE `id` = ? AND `status` = 'active'");
    $stmt->bind_param("i", $discount_id);
    $stmt->execute();
    $discount = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if(!$discount){
        alert("❌ کد تخفیف نامعتبر است!");
        exit;
    }
    
    // محاسبه قیمت نهایی
    $original_price = $plan['price'];
    if($discount['type'] == 'percent'){
        $discount_amount = ($original_price * $discount['amount']) / 100;
    } else {
        $discount_amount = $discount['amount'];
    }
    $final_price = max(0, $original_price - $discount_amount);
    
    if($userInfo['wallet'] < $final_price){
        alert("❌ موجودی کیف پول شما کافی نیست!\n\nموجودی: " . number_format($userInfo['wallet']) . " تومان\nمورد نیاز: " . number_format($final_price) . " تومان");
        exit;
    }
    
    // کسر از کیف پول
    $new_wallet = $userInfo['wallet'] - $final_price;
    $stmt = $connection->prepare("UPDATE `users` SET `wallet` = ? WHERE `userid` = ?");
    $stmt->bind_param("ii", $new_wallet, $from_id);
    $stmt->execute();
    $stmt->close();
    
    // ثبت استفاده از کد تخفیف
    $stmt = $connection->prepare("INSERT INTO `discount_usage` (`user_id`, `discount_id`, `plan_id`, `discount_amount`) VALUES (?, ?, ?, ?)");
    $stmt->bind_param("iiii", $from_id, $discount_id, $plan_id, $discount_amount);
    $stmt->execute();
    $stmt->close();
    
    // افزایش شمارنده استفاده
    $stmt = $connection->prepare("UPDATE `discounts` SET `used_count` = `used_count` + 1 WHERE `id` = ?");
    $stmt->bind_param("i", $discount_id);
    $stmt->execute();
    $stmt->close();
    
    // ساخت سرویس
    $hash_id = RandomString();
    $result = createServiceAccount($from_id, $plan_id, $hash_id);
    
    if($result['success']){
        delMessage();
        setUser('none', 'step');
        sendMessage("✅ پرداخت موفق!\n\n🎉 سرویس شما در حال آماده‌سازی است...\n\n💰 مبلغ پرداختی: " . number_format($final_price) . " تومان\n🎟️ تخفیف: " . number_format($discount_amount) . " تومان", $removeKeyboard);
    } else {
        // بازگشت پول
        $stmt = $connection->prepare("UPDATE `users` SET `wallet` = ? WHERE `userid` = ?");
        $old_wallet = $userInfo['wallet'];
        $stmt->bind_param("ii", $old_wallet, $from_id);
        $stmt->execute();
        $stmt->close();
        
        alert("❌ خطا در ساخت سرویس: " . $result['error']);
    }
    exit;
}

// پرداخت فیش بانکی
if(preg_match('/^payByReceipt_(\d+)$/', $data, $match)){
    $plan_id = $match[1];
    
    // دریافت اطلاعات پلن
    $stmt = $connection->prepare("SELECT * FROM `service_plans` WHERE `id` = ? AND `status` = 'active'");
    $stmt->bind_param("i", $plan_id);
    $stmt->execute();
    $plan = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if(!$plan){
        editText($message_id, "❌ تعرفه یافت نشد!", getMainKeys());
        exit;
    }
    
    delMessage();
    setUser("uploadReceiptForPlan_{$plan_id}", 'step');
    
    // نمایش اطلاعات کارت
    $price_text = number_format($plan['price']);
    $cardMsg = "💳 <b>اطلاعات پرداخت</b>\n\n";
    $cardMsg .= "💰 مبلغ قابل پرداخت: <b>{$price_text} تومان</b>\n\n";
    
    if(!empty($paymentKeys['bankAccount']) && !empty($paymentKeys['holderName'])){
        $cardMsg .= "📌 لطفا به کارت زیر واریز کنید:\n\n";
        $cardMsg .= "💳 شماره کارت:\n<code>{$paymentKeys['bankAccount']}</code>\n\n";
        $cardMsg .= "👤 نام صاحب حساب:\n<b>{$paymentKeys['holderName']}</b>\n\n";
    }
    
    $cardMsg .= "📤 لطفا تصویر فیش واریزی خود را ارسال کنید:";
    
    sendMessage($cardMsg, $cancelKey, 'HTML');
    exit;
}

// پرداخت فیش بانکی با تخفیف
if(preg_match('/^payByReceiptWithDiscount_(\d+)_(\d+)$/', $data, $match)){
    $plan_id = $match[1];
    $discount_id = $match[2];
    
    // دریافت اطلاعات پلن
    $stmt = $connection->prepare("SELECT * FROM `service_plans` WHERE `id` = ? AND `status` = 'active'");
    $stmt->bind_param("i", $plan_id);
    $stmt->execute();
    $plan = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if(!$plan){
        editText($message_id, "❌ تعرفه یافت نشد!", getMainKeys());
        exit;
    }
    
    // بررسی کد تخفیف
    $stmt = $connection->prepare("SELECT * FROM `discounts` WHERE `id` = ? AND `status` = 'active'");
    $stmt->bind_param("i", $discount_id);
    $stmt->execute();
    $discount = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if(!$discount){
        alert("❌ کد تخفیف نامعتبر است!");
        exit;
    }
    
    // محاسبه قیمت نهایی
    $original_price = $plan['price'];
    if($discount['type'] == 'percent'){
        $discount_amount = ($original_price * $discount['amount']) / 100;
    } else {
        $discount_amount = $discount['amount'];
    }
    $final_price = max(0, $original_price - $discount_amount);
    
    delMessage();
    setUser("uploadReceiptForPlanWithDiscount_{$plan_id}_{$discount_id}", 'step');
    
    // نمایش اطلاعات کارت با تخفیف
    $final_price_text = number_format($final_price);
    $original_price_text = number_format($original_price);
    $discount_text = number_format($discount_amount);
    
    $cardMsg = "💳 <b>اطلاعات پرداخت</b>\n\n";
    $cardMsg .= "💵 قیمت اصلی: <s>{$original_price_text}</s> تومان\n";
    $cardMsg .= "🎟️ تخفیف: <code>{$discount_text}</code> تومان\n";
    $cardMsg .= "💰 <b>مبلغ قابل پرداخت: {$final_price_text} تومان</b>\n\n";
    
    if(!empty($paymentKeys['bankAccount']) && !empty($paymentKeys['holderName'])){
        $cardMsg .= "📌 لطفا به کارت زیر واریز کنید:\n\n";
        $cardMsg .= "💳 شماره کارت:\n<code>{$paymentKeys['bankAccount']}</code>\n\n";
        $cardMsg .= "👤 نام صاحب حساب:\n<b>{$paymentKeys['holderName']}</b>\n\n";
    }
    
    $cardMsg .= "📤 لطفا تصویر فیش واریزی خود را ارسال کنید:";
    
    sendMessage($cardMsg, $cancelKey, 'HTML');
    exit;
}

// دریافت فیش (فقط برای کاربران عادی، نه ادمین)
if(preg_match('/^uploadReceiptForPlan_(\d+)$/', $userInfo['step'], $match) && $from_id != $admin && !$userInfo['isAdmin']){
    if($text == $buttonValues['cancel']){
        setUser('none', 'step');
        sendMessage("❌ لغو شد", getMainKeys());
        exit;
    }
    
    if(!isset($photo)){
        sendMessage("⚠️ لطفا تصویر فیش را ارسال کنید!", $cancelKey);
        exit;
    }
    
    $plan_id = $match[1];
    
    $stmt = $connection->prepare("SELECT * FROM `service_plans` WHERE `id` = ? AND `status` = 'active'");
    $stmt->bind_param("i", $plan_id);
    $stmt->execute();
    $plan = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if(!$plan){
        sendMessage("❌ تعرفه یافت نشد!", getMainKeys());
        setUser('none', 'step');
        exit;
    }
    
    // لاگ برای دیباگ
    error_log("📸 فیش دریافت شد - User: {$from_id}, Plan: {$plan_id}, Photo: {$photo}");
    
    // ثبت در دیتابیس (جدول pays)
    $hash_id = RandomString();
    $stmt = $connection->prepare("INSERT INTO `pays` (`user_id`, `hash_id`, `type`, `price`, `state`, `photo`) 
                                   VALUES (?, ?, 'SERVICE_PLAN', ?, 'pending', ?)");
    $stmt->bind_param("isis", $from_id, $hash_id, $plan['price'], $photo);
    $stmt->execute();
    $stmt->close();
    
    error_log("💾 فیش در دیتابیس ثبت شد - Hash: {$hash_id}");
    
    // ذخیره plan_id در جدول موقت
    $stmt = $connection->prepare("INSERT INTO `temp_service_purchases` (`hash_id`, `user_id`, `plan_id`) VALUES (?, ?, ?)");
    $stmt->bind_param("sii", $hash_id, $from_id, $plan_id);
    $stmt->execute();
    $stmt->close();
    
    setUser('none', 'step');
    
    // ارسال پیام تایید به کاربر
    $confirm_sent = sendMessage("✅ فیش شما با موفقیت ثبت شد!\n\n⏳ پس از بررسی توسط ادمین، سرویس شما فعال خواهد شد.\n\n🆔 شناسه پرداخت: <code>{$hash_id}</code>", getMainKeys(), 'HTML');
    error_log("📤 پیام تایید به کاربر ارسال شد: " . ($confirm_sent->ok ? 'موفق' : 'ناموفق'));
    
    // اطلاع به ادمین
    $price_text = number_format($plan['price']);
    $user_name = $first_name ?? $userInfo['name'] ?? "کاربر";
    $user_username = $username != " ندارد " ? "@{$username}" : "ندارد";
    
    $adminMsg = "💳 <b>فیش جدید دریافت شد</b>\n\n";
    $adminMsg .= "👤 کاربر: {$user_name}\n";
    $adminMsg .= "🆔 یوزرنیم: {$user_username}\n";
    $adminMsg .= "🔢 آیدی: <code>{$from_id}</code>\n";
    $adminMsg .= "📦 تعرفه: {$plan['name']}\n";
    $adminMsg .= "💰 مبلغ: {$price_text} تومان\n\n";
    $adminMsg .= "🆔 کد پیگیری: <code>{$hash_id}</code>";
    
    $adminKeyboard = [
        [['text' => '✅ تایید و ارسال اتوماتیک', 'callback_data' => "approveAuto_{$hash_id}"]],
        [['text' => '📝 تایید و ارسال دستی', 'callback_data' => "approveManual_{$hash_id}"]],
        [['text' => '❌ رد درخواست', 'callback_data' => "rejectPayment_{$hash_id}"]]
    ];
    
    error_log("📨 در حال ارسال به ادمین - Admin ID: {$admin}, Photo: {$photo}");
    
    // ارسال عکس به ادمین با تابع bot
    $admin_result = bot('sendPhoto', [
        'chat_id' => $admin,
        'photo' => $photo,
        'caption' => $adminMsg,
        'parse_mode' => 'HTML',
        'reply_markup' => json_encode(['inline_keyboard' => $adminKeyboard])
    ]);
    
    error_log("📬 نتیجه ارسال به ادمین: " . json_encode($admin_result));
    
    exit;
}

// دریافت فیش با تخفیف
if(preg_match('/^uploadReceiptForPlanWithDiscount_(\d+)_(\d+)$/', $userInfo['step'], $match) && $from_id != $admin && !$userInfo['isAdmin']){
    if($text == $buttonValues['cancel']){
        setUser('none', 'step');
        sendMessage("❌ لغو شد", getMainKeys());
        exit;
    }
    
    if(!isset($photo)){
        sendMessage("⚠️ لطفا تصویر فیش را ارسال کنید!", $cancelKey);
        exit;
    }
    
    $plan_id = $match[1];
    $discount_id = $match[2];
    
    $stmt = $connection->prepare("SELECT * FROM `service_plans` WHERE `id` = ? AND `status` = 'active'");
    $stmt->bind_param("i", $plan_id);
    $stmt->execute();
    $plan = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if(!$plan){
        sendMessage("❌ تعرفه یافت نشد!", getMainKeys());
        setUser('none', 'step');
        exit;
    }
    
    // بررسی کد تخفیف
    $stmt = $connection->prepare("SELECT * FROM `discounts` WHERE `id` = ? AND `status` = 'active'");
    $stmt->bind_param("i", $discount_id);
    $stmt->execute();
    $discount = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if(!$discount){
        sendMessage("❌ کد تخفیف نامعتبر است!", getMainKeys());
        setUser('none', 'step');
        exit;
    }
    
    // محاسبه قیمت نهایی
    $original_price = $plan['price'];
    if($discount['type'] == 'percent'){
        $discount_amount = ($original_price * $discount['amount']) / 100;
    } else {
        $discount_amount = $discount['amount'];
    }
    $final_price = max(0, $original_price - $discount_amount);
    
    error_log("📸 فیش با تخفیف دریافت شد - User: {$from_id}, Plan: {$plan_id}, Discount: {$discount_id}, Final Price: {$final_price}");
    
    // ثبت در دیتابیس
    $hash_id = RandomString();
    $stmt = $connection->prepare("INSERT INTO `pays` (`user_id`, `hash_id`, `type`, `price`, `state`, `photo`, `discount_id`) 
                                   VALUES (?, ?, 'SERVICE_PLAN', ?, 'pending', ?, ?)");
    $stmt->bind_param("isisi", $from_id, $hash_id, $final_price, $photo, $discount_id);
    $stmt->execute();
    $stmt->close();
    
    // ذخیره plan_id در جدول موقت
    $stmt = $connection->prepare("INSERT INTO `temp_service_purchases` (`hash_id`, `user_id`, `plan_id`, `discount_id`) VALUES (?, ?, ?, ?)");
    $stmt->bind_param("siii", $hash_id, $from_id, $plan_id, $discount_id);
    $stmt->execute();
    $stmt->close();
    
    setUser('none', 'step');
    
    // ارسال پیام تایید به کاربر
    sendMessage("✅ فیش شما با موفقیت ثبت شد!\n\n⏳ پس از بررسی توسط ادمین، سرویس شما فعال خواهد شد.\n\n💰 مبلغ پرداختی: " . number_format($final_price) . " تومان\n🎟️ تخفیف: " . number_format($discount_amount) . " تومان\n\n🆔 شناسه پرداخت: <code>{$hash_id}</code>", getMainKeys(), 'HTML');
    
    // اطلاع به ادمین
    $final_price_text = number_format($final_price);
    $original_price_text = number_format($original_price);
    $discount_text = number_format($discount_amount);
    $user_name = $first_name ?? $userInfo['name'] ?? "کاربر";
    $user_username = $username != " ندارد " ? "@{$username}" : "ندارد";
    
    $adminMsg = "💳 <b>فیش جدید با تخفیف دریافت شد</b>\n\n";
    $adminMsg .= "👤 کاربر: {$user_name}\n";
    $adminMsg .= "🆔 یوزرنیم: {$user_username}\n";
    $adminMsg .= "🔢 آیدی: <code>{$from_id}</code>\n";
    $adminMsg .= "📦 تعرفه: {$plan['name']}\n";
    $adminMsg .= "💵 قیمت اصلی: <s>{$original_price_text}</s> تومان\n";
    $adminMsg .= "🎟️ کد تخفیف: <code>{$discount['code']}</code> (-{$discount_text} تومان)\n";
    $adminMsg .= "💰 مبلغ نهایی: {$final_price_text} تومان\n\n";
    $adminMsg .= "🆔 کد پیگیری: <code>{$hash_id}</code>";
    
    $adminKeyboard = [
        [['text' => '✅ تایید و ارسال اتوماتیک', 'callback_data' => "approveAuto_{$hash_id}"]],
        [['text' => '📝 تایید و ارسال دستی', 'callback_data' => "approveManual_{$hash_id}"]],
        [['text' => '❌ رد درخواست', 'callback_data' => "rejectPayment_{$hash_id}"]]
    ];
    
    bot('sendPhoto', [
        'chat_id' => $admin,
        'photo' => $photo,
        'caption' => $adminMsg,
        'parse_mode' => 'HTML',
        'reply_markup' => json_encode(['inline_keyboard' => $adminKeyboard])
    ]);
    
    exit;
}

// ============================================
// سیستم تایید/رد پرداخت توسط ادمین
// ============================================

// 1️⃣ تایید و ارسال اتوماتیک (ساخت اتوماتیک سرویس)
if(preg_match('/^approveAuto_(.+)$/', $data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $hash_id = $match[1];
    
    // دریافت اطلاعات خرید موقت
    $stmt = $connection->prepare("SELECT * FROM `temp_service_purchases` WHERE `hash_id` = ?");
    $stmt->bind_param("s", $hash_id);
    $stmt->execute();
    $purchase = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if(!$purchase){
        alert("❌ اطلاعات خرید یافت نشد!");
        exit;
    }
    
    delMessage();
    sendMessage("⏳ در حال ساخت سرویس و ارسال به کاربر...\n\nلطفا صبر کنید...");
    
    // ساخت سرویس اتوماتیک
    $result = createServiceAccount($purchase['user_id'], $purchase['plan_id'], $hash_id);
    
    if($result['success']){
        // به‌روزرسانی وضعیت پرداخت
        $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'approved' WHERE `hash_id` = ?");
        $stmt->bind_param("s", $hash_id);
        $stmt->execute();
        $stmt->close();
        
        // 🎁 اضافه کردن 3000 تومان کش‌بک به کیف پول
        $cashback_amount = 3000;
        $stmt = $connection->prepare("UPDATE `users` SET `wallet` = `wallet` + ? WHERE `userid` = ?");
        $stmt->bind_param("ii", $cashback_amount, $purchase['user_id']);
        $stmt->execute();
        $stmt->close();
        
        // حذف از جدول موقت
        $stmt = $connection->prepare("DELETE FROM `temp_service_purchases` WHERE `hash_id` = ?");
        $stmt->bind_param("s", $hash_id);
        $stmt->execute();
        $stmt->close();
        
        // اطلاع به کاربر درباره کش‌بک
        bot('sendMessage', [
            'chat_id' => $purchase['user_id'],
            'text' => "🎁 <b>تبریک! کش‌بک خرید</b>\n\n💰 به پاس خرید شما، " . number_format($cashback_amount) . " تومان به کیف پول شما اضافه شد!\n\n✨ می‌توانید از آن برای خریدهای بعدی استفاده کنید.",
            'parse_mode' => 'HTML'
        ]);
        
        sendMessage("✅ سرویس با موفقیت ساخته شد و اتوماتیک به کاربر ارسال گردید!\n\n🎁 کش‌بک: " . number_format($cashback_amount) . " تومان به کیف پول کاربر اضافه شد\n\n🆔 کد پیگیری: <code>{$hash_id}</code>", getMainKeys(), 'HTML');
    } else {
        $error_msg = isset($result['error']) ? $result['error'] : (isset($result['message']) ? $result['message'] : 'خطای ناشناخته');
        sendMessage("❌ خطا در ساخت سرویس:\n\n{$error_msg}\n\n🆔 کد پیگیری: <code>{$hash_id}</code>", getMainKeys(), 'HTML');
    }
    exit;
}

// 2️⃣ تایید و ارسال دستی (ادمین لینک اشتراک رو خودش میده)
if(preg_match('/^approveManual_(.+)$/', $data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $hash_id = $match[1];
    
    // دریافت اطلاعات خرید
    $stmt = $connection->prepare("SELECT tsp.*, sp.name as plan_name 
                                   FROM `temp_service_purchases` tsp
                                   JOIN `service_plans` sp ON tsp.plan_id = sp.id
                                   WHERE tsp.hash_id = ?");
    $stmt->bind_param("s", $hash_id);
    $stmt->execute();
    $purchase = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if(!$purchase){
        alert("❌ اطلاعات خرید یافت نشد!");
        exit;
    }
    
    // تنظیم step برای دریافت لینک
    setUser("waitingManualConfig_{$hash_id}_{$purchase['user_id']}_{$purchase['plan_id']}", 'step');
    
    delMessage();
    
    $msg = "📝 <b>ارسال دستی لینک اشتراک</b>\n\n";
    $msg .= "👤 کاربر: <code>{$purchase['user_id']}</code>\n";
    $msg .= "📦 سرویس: {$purchase['plan_name']}\n";
    $msg .= "🆔 کد: <code>{$hash_id}</code>\n\n";
    $msg .= "━━━━━━━━━━━━━━━━\n\n";
    $msg .= "لطفا لینک اشتراک (Config Link) را ارسال کنید:\n\n";
    $msg .= "مثال:\n";
    $msg .= "<code>vless://uuid@server:port?...</code>";
    
    $cancelKey = [
        [['text' => '❌ انصراف', 'callback_data' => 'cancelManualSend']]
    ];
    
    sendMessage($msg, $cancelKey, 'HTML');
    exit;
}

// دریافت لینک اشتراک دستی از ادمین
if(preg_match('/^waitingManualConfig_([a-zA-Z0-9]+)_(\d+)_(\d+)$/', $userInfo['step'], $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    error_log("📝 === MANUAL CONFIG HANDLER START ===");
    error_log("📝 Step: {$userInfo['step']}");
    error_log("📝 From ID: {$from_id}, Admin ID: {$admin}");
    error_log("📝 Is Admin: " . ($userInfo['isAdmin'] ? 'YES' : 'NO'));
    error_log("📝 Text: " . ($text ?? 'NULL'));
    error_log("📝 Text length: " . (isset($text) ? strlen($text) : '0'));
    error_log("📝 Is empty: " . (empty($text) ? 'YES' : 'NO'));
    error_log("📝 Data: " . ($data ?? 'NULL'));
    
    $hash_id = $match[1];
    $customer_id = $match[2];
    $plan_id = $match[3];
    
    error_log("📝 Matched - Hash: {$hash_id}, Customer: {$customer_id}, Plan: {$plan_id}");
    
    // چک کردن اگر دکمه انصراف زده شده
    if($data == 'cancelManualSend' || $text == $buttonValues['cancel']){
        error_log("❌ User cancelled via: " . ($data == 'cancelManualSend' ? 'callback' : 'text'));
        setUser('none', 'step');
        delMessage();
        sendMessage("❌ ارسال دستی لغو شد", getMainKeys());
        exit;
    }
    
    // اگر text نداریم، منتظر دریافت text هستیم
    if(empty($text)){
        error_log("⚠️ No text received yet, waiting for config link");
        exit;
    }
    
    error_log("✅ Text received: {$text}");
    
    // بررسی فرمت لینک (باید شامل http:// یا https:// یا vless:// و ... باشه)
    if(!preg_match('/(https?|vless|vmess|trojan|ss|ssr):\/\//', $text)){
        error_log("❌ Invalid config link format");
        $cancelKey = json_encode(['inline_keyboard' => [
            [['text' => '❌ انصراف', 'callback_data' => 'cancelManualSend']]
        ]]);
        sendMessage("⚠️ فرمت لینک اشتراک صحیح نیست!\n\nلطفا یک لینک معتبر ارسال کنید:\n\n• http://...\n• https://...\n• vless://...\n• vmess://...\n• trojan://...\n• ss://...", $cancelKey);
        exit;
    }
    
    $config_link = trim($text);
    
    // دریافت اطلاعات پلن
    $stmt = $connection->prepare("SELECT * FROM `service_plans` WHERE `id` = ?");
    $stmt->bind_param("i", $plan_id);
    $stmt->execute();
    $plan = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if(!$plan){
        sendMessage("❌ پلن یافت نشد!");
        exit;
    }
    
    // محاسبه تاریخ انقضا
    $expire_timestamp = time() + ($plan['days'] * 24 * 60 * 60);
    if(function_exists('jdate')){
        $expire_date = jdate('Y/m/d', $expire_timestamp);
    } else {
        $expire_date = date('Y/m/d', $expire_timestamp);
    }
    
    // ثبت در دیتابیس service_orders
    $stmt = $connection->prepare("INSERT INTO `service_orders` 
                                   (`user_id`, `plan_id`, `server_id`, `config`, `expire_date`, `status`, `created_at`) 
                                   VALUES (?, ?, ?, ?, ?, 'active', NOW())");
    $server_id = $plan['server_id'] ?? 1;
    $stmt->bind_param("iiiss", $customer_id, $plan_id, $server_id, $config_link, $expire_date);
    $stmt->execute();
    $service_id = $connection->insert_id;
    $stmt->close();
    
    // به‌روزرسانی وضعیت پرداخت
    $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'approved' WHERE `hash_id` = ?");
    $stmt->bind_param("s", $hash_id);
    $stmt->execute();
    $stmt->close();
    
    // حذف از جدول موقت
    $stmt = $connection->prepare("DELETE FROM `temp_service_purchases` WHERE `hash_id` = ?");
    $stmt->bind_param("s", $hash_id);
    $stmt->execute();
    $stmt->close();
    
    setUser('none', 'step');
    
    // 🎁 اضافه کردن 3000 تومان کش‌بک به کیف پول
    $cashback_amount = 3000;
    $stmt = $connection->prepare("UPDATE `users` SET `wallet` = `wallet` + ? WHERE `userid` = ?");
    $stmt->bind_param("ii", $cashback_amount, $customer_id);
    $stmt->execute();
    $stmt->close();
    
    // ارسال به کاربر
    $customer_msg = "🎉 <b>سرویس شما با موفقیت فعال شد!</b>\n\n";
    $customer_msg .= "📦 سرویس: {$plan['name']}\n";
    $customer_msg .= "💾 حجم: {$plan['volume_gb']} گیگابایت\n";
    $customer_msg .= "📅 مدت: {$plan['days']} روز\n";
    $customer_msg .= "⏰ تاریخ انقضا: {$expire_date}\n\n";
    $customer_msg .= "━━━━━━━━━━━━━━━━\n\n";
    $customer_msg .= "🔗 <b>لینک اشتراک شما:</b>\n\n";
    $customer_msg .= "<code>{$config_link}</code>\n\n";
    $customer_msg .= "━━━━━━━━━━━━━━━━\n\n";
    $customer_msg .= "📱 برای اتصال:\n";
    $customer_msg .= "۱. لینک بالا را کپی کنید\n";
    $customer_msg .= "۲. در اپلیکیشن v2rayNG وارد کنید\n";
    $customer_msg .= "۳. روی Connect بزنید\n\n";
    $customer_msg .= "❓ راهنمای اتصال را از منو دریافت کنید.\n\n";
    $customer_msg .= "━━━━━━━━━━━━━━━━\n\n";
    $customer_msg .= "🎁 <b>پاداش خرید!</b>\n";
    $customer_msg .= "💰 " . number_format($cashback_amount) . " تومان به کیف پول شما اضافه شد!\n\n";
    $customer_msg .= "✨ می‌توانید از آن برای خریدهای بعدی استفاده کنید.";
    
    $customer_keyboard = [
        [['text' => '📱 راهنمای اتصال', 'callback_data' => 'connectionGuide']],
        [['text' => '📋 سرویس‌های من', 'callback_data' => 'myServices']],
        [['text' => '🏠 منوی اصلی', 'callback_data' => 'mainMenu']]
    ];
    
    error_log("📤 Sending to customer: {$customer_id}");
    
    bot('sendMessage', [
        'chat_id' => $customer_id,
        'text' => $customer_msg,
        'parse_mode' => 'HTML',
        'reply_markup' => json_encode(['inline_keyboard' => $customer_keyboard])
    ]);
    
    error_log("✅ Message sent to customer");
    
    // تایید به ادمین
    sendMessage("✅ <b>سرویس با موفقیت ارسال شد!</b>\n\n👤 به کاربر: <code>{$customer_id}</code>\n🆔 کد پیگیری: <code>{$hash_id}</code>\n📦 ID سرویس: {$service_id}\n\n🎁 کش‌بک: " . number_format($cashback_amount) . " تومان به کیف پول کاربر اضافه شد", getMainKeys(), 'HTML');
    
    error_log("✅ Manual approval completed successfully");
    exit;
}

// لغو ارسال دستی
if($data == 'cancelManualSend' && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    setUser('none', 'step');
    delMessage();
    sendMessage("❌ ارسال دستی لغو شد", getMainKeys());
    exit;
}

// 3️⃣ رد درخواست (با دریافت دلیل از ادمین)
if(preg_match('/^rejectPayment_(.+)$/', $data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    $hash_id = $match[1];
    
    // دریافت اطلاعات پرداخت و کاربر
    $stmt = $connection->prepare("SELECT p.*, tsp.user_id, tsp.plan_id 
                                   FROM `pays` p 
                                   LEFT JOIN `temp_service_purchases` tsp ON p.hash_id = tsp.hash_id
                                   WHERE p.hash_id = ?");
    $stmt->bind_param("s", $hash_id);
    $stmt->execute();
    $payment = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if(!$payment){
        alert("❌ پرداخت یافت نشد!");
        exit;
    }
    
    // تنظیم step برای دریافت دلیل رد
    setUser("waitingRejectReason_{$hash_id}_{$payment['user_id']}", 'step');
    
    delMessage();
    
    $msg = "📝 <b>دلیل رد درخواست</b>\n\n";
    $msg .= "👤 کاربر: <code>{$payment['user_id']}</code>\n";
    $msg .= "💰 مبلغ: " . number_format($payment['price']) . " تومان\n";
    $msg .= "🆔 کد: <code>{$hash_id}</code>\n\n";
    $msg .= "━━━━━━━━━━━━━━━━\n\n";
    $msg .= "لطفا دلیل رد درخواست را وارد کنید:\n\n";
    $msg .= "مثال:\n";
    $msg .= "• فیش تکراری است\n";
    $msg .= "• مبلغ کامل واریز نشده\n";
    $msg .= "• اطلاعات واریز اشتباه است";
    
    $cancelKey = [
        [['text' => '❌ انصراف', 'callback_data' => 'cancelReject']]
    ];
    
    sendMessage($msg, $cancelKey, 'HTML');
    exit;
}

// دریافت دلیل رد از ادمین
if(preg_match('/^waitingRejectReason_([a-zA-Z0-9]+)_(\d+)$/', $userInfo['step'], $match) && ($from_id == $admin || $userInfo['isAdmin'] == true) && $text){
    error_log("❌ Reject Handler - Step: {$userInfo['step']}, Text: {$text}");
    
    $hash_id = $match[1];
    $customer_id = $match[2];
    
    error_log("❌ Matched - Hash: {$hash_id}, Customer: {$customer_id}");
    
    if($text == $buttonValues['cancel']){
        setUser('none', 'step');
        sendMessage("❌ رد درخواست لغو شد", getMainKeys());
        exit;
    }
    
    $reject_reason = trim($text);
    
    if(empty($reject_reason) || mb_strlen($reject_reason) < 3){
        $cancelKey = [
            [['text' => '❌ انصراف', 'callback_data' => 'cancelReject']]
        ];
        sendMessage("⚠️ لطفا یک دلیل مناسب وارد کنید (حداقل ۳ کاراکتر)", $cancelKey);
        exit;
    }
    
    // دریافت اطلاعات پرداخت
    $stmt = $connection->prepare("SELECT * FROM `pays` WHERE `hash_id` = ?");
    $stmt->bind_param("s", $hash_id);
    $stmt->execute();
    $payment = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    // به‌روزرسانی وضعیت پرداخت
    $stmt = $connection->prepare("UPDATE `pays` SET `state` = 'rejected' WHERE `hash_id` = ?");
    $stmt->bind_param("s", $hash_id);
    $stmt->execute();
    $stmt->close();
    
    // حذف از جدول موقت
    $stmt = $connection->prepare("DELETE FROM `temp_service_purchases` WHERE `hash_id` = ?");
    $stmt->bind_param("s", $hash_id);
    $stmt->execute();
    $stmt->close();
    
    setUser('none', 'step');
    
    // ارسال پیام حرفه‌ای رد به کاربر
    $customer_msg = "❌ <b>درخواست شما رد شد</b>\n\n";
    $customer_msg .= "متاسفانه پرداخت شما توسط بخش مالی تایید نشد.\n\n";
    $customer_msg .= "🆔 کد پیگیری: <code>{$hash_id}</code>\n";
    $customer_msg .= "💰 مبلغ: " . number_format($payment['price']) . " تومان\n\n";
    $customer_msg .= "━━━━━━━━━━━━━━━━\n\n";
    $customer_msg .= "📋 <b>دلیل رد:</b>\n";
    $customer_msg .= "{$reject_reason}\n\n";
    $customer_msg .= "━━━━━━━━━━━━━━━━\n\n";
    $customer_msg .= "💬 در صورت نیاز به پشتیبانی، با ما تماس بگیرید.";
    
    $customer_keyboard = [
        [['text' => '💬 ارتباط با پشتیبانی', 'callback_data' => 'supportSection']],
        [['text' => '🔄 تلاش مجدد', 'callback_data' => 'buyService']],
        [['text' => '🏠 منوی اصلی', 'callback_data' => 'mainMenu']]
    ];
    
    bot('sendMessage', [
        'chat_id' => $customer_id,
        'text' => $customer_msg,
        'parse_mode' => 'HTML',
        'reply_markup' => json_encode(['inline_keyboard' => $customer_keyboard])
    ]);
    
    // تایید به ادمین
    sendMessage("✅ <b>درخواست رد شد و به کاربر اطلاع داده شد</b>\n\n👤 کاربر: <code>{$customer_id}</code>\n🆔 کد: <code>{$hash_id}</code>\n📝 دلیل: {$reject_reason}", getMainKeys(), 'HTML');
    
    exit;
}

// لغو رد درخواست
if($data == 'cancelReject' && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    setUser('none', 'step');
    delMessage();
    sendMessage("❌ رد درخواست لغو شد", getMainKeys());
    exit;
}

// ============================================
// سیستم یکپارچه سرویس‌های من (ادغام شده در mySubscriptions)
// ============================================

// نمایش جزئیات یک سرویس خاص
if(preg_match('/^viewService_(\d+)$/', $data, $match)){
    $service_id = $match[1];
    
    // دریافت اطلاعات سرویس
    $stmt = $connection->prepare("SELECT so.*, sp.name as plan_name, sp.volume_gb, sp.days 
                                   FROM `service_orders` so
                                   LEFT JOIN `service_plans` sp ON so.plan_id = sp.id
                                   WHERE so.id = ? AND so.user_id = ?");
    $stmt->bind_param("ii", $service_id, $from_id);
    $stmt->execute();
    $service = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if(!$service){
        alert("❌ سرویس یافت نشد!");
        exit;
    }
    
    $expire_date = jdate('Y/m/d', strtotime($service['expire_date']));
    $created_date = jdate('Y/m/d', strtotime($service['created_at']));
    $remaining_days = ceil((strtotime($service['expire_date']) - time()) / (60 * 60 * 24));
    $status_text = $service['status'] == 'active' ? '✅ فعال' : '❌ غیرفعال';
    $status_icon = $service['status'] == 'active' ? '✅' : '❌';
    
    $msg = "📱 <b>جزئیات سرویس #{$service['id']}</b>\n\n";
    $msg .= "━━━━━━━━━━━━━━━━━━\n";
    $msg .= "📦 <b>{$service['plan_name']}</b>\n";
    $msg .= "━━━━━━━━━━━━━━━━━━\n\n";
    
    $msg .= "📊 <b>مشخصات:</b>\n";
    $msg .= "├ 🆔 شناسه سرویس: <code>#{$service['id']}</code>\n";
    $msg .= "├ {$status_icon} وضعیت: {$status_text}\n";
    $msg .= "├ 💾 حجم: <code>{$service['volume_gb']} گیگابایت</code>\n";
    $msg .= "└ ⏰ مدت: <code>{$service['days']} روز</code>\n\n";
    
    $msg .= "📅 <b>تاریخ‌ها:</b>\n";
    $msg .= "├ 🎯 تاریخ ساخت: <code>{$created_date}</code>\n";
    $msg .= "├ ⏳ تاریخ انقضا: <code>{$expire_date}</code>\n";
    $msg .= "└ ⌛ روزهای باقی‌مانده: <code>{$remaining_days} روز</code>\n\n";
    
    if(!empty($service['uuid'])){
        $msg .= "🔑 <b>اطلاعات اتصال:</b>\n";
        $msg .= "├ 🔐 UUID: <code>{$service['uuid']}</code>\n";
        if(!empty($service['email'])){
            $msg .= "├ 📧 Email: <code>{$service['email']}</code>\n";
        }
        $msg .= "━━━━━━━━━━━━━━━━━━\n\n";
    }
    
    $keyboard = [];
    
    // دکمه دریافت لینک کانفیگ
    if(!empty($service['config_link'])){
        $keyboard[] = [['text' => '🔗 دریافت لینک کانفیگ', 'callback_data' => "getConfig_{$service_id}"]];
    } elseif(!empty($service['config'])){
        $keyboard[] = [['text' => '🔗 دریافت لینک کانفیگ', 'callback_data' => "getConfig_{$service_id}"]];
    }
    
    // دکمه راهنمای اتصال
    $keyboard[] = [['text' => '📱 راهنمای نصب و اتصال', 'callback_data' => 'connectionGuide']];
    // دکمه تولید QR کد برای لینک کانفیگ (اگر لینک موجود باشد)
    if(!empty($service['config_link']) || !empty($service['config'])){
        $keyboard[] = [['text' => '📷 QR کد', 'callback_data' => "getConfigQR_{$service_id}"]];
    }
    
    // دکمه تمدید (اگر نزدیک به انقضا)
    if($remaining_days <= 7 && $remaining_days > 0){
        $keyboard[] = [['text' => '🔄 تمدید سرویس', 'callback_data' => "renewService_{$service_id}"]];
    }
    
    $keyboard[] = [['text' => '◀️ بازگشت به لیست', 'callback_data' => 'myServices']];
    $keyboard[] = [['text' => '🏠 منوی اصلی', 'callback_data' => 'mainMenu']];
    
    editText($message_id, $msg, $keyboard, 'HTML');
    exit;
}

// ارسال لینک کانفیگ
if(preg_match('/^getConfig_(\d+)$/', $data, $match)){
    $service_id = $match[1];
    
    $stmt = $connection->prepare("SELECT * FROM `service_orders` WHERE `id` = ? AND `user_id` = ?");
    $stmt->bind_param("ii", $service_id, $from_id);
    $stmt->execute();
    $service = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if(!$service){
        alert("❌ سرویس یافت نشد!");
        exit;
    }
    
    $config_link = $service['config_link'] ?? $service['config'] ?? '';
    
    // لاگ برای دیباگ
    error_log("🔗 getConfig Handler - Service ID: {$service_id}, Config Link: {$config_link}");
    
    if(empty($config_link)){
        error_log("❌ Config link is empty for service #{$service_id}");
        alert("❌ لینک کانفیگ موجود نیست!");
        exit;
    }
    
    // ارسال لینک به صورت پیام جداگانه
    $config_msg = "🔗 <b>لینک کانفیگ سرویس #{$service_id}</b>\n\n";
    $config_msg .= "━━━━━━━━━━━━━━━━━━\n\n";
    $config_msg .= "<code>{$config_link}</code>\n\n";
    $config_msg .= "━━━━━━━━━━━━━━━━━━\n\n";
    $config_msg .= "📱 <b>نحوه استفاده:</b>\n";
    $config_msg .= "۱. لینک بالا را کپی کنید\n";
    $config_msg .= "۲. در اپلیکیشن v2rayNG وارد کنید\n";
    $config_msg .= "۳. روی Connect کلیک کنید\n\n";
    $config_msg .= "💡 برای راهنمای کامل نصب، از منو استفاده کنید.";
    
    $config_keyboard = [
        [['text' => '📱 راهنمای نصب', 'callback_data' => 'connectionGuide']],
        [['text' => '◀️ بازگشت به سرویس', 'callback_data' => "viewService_{$service_id}"]],
        [['text' => '🏠 منوی اصلی', 'callback_data' => 'mainMenu']]
    ];
    
    sendMessage($config_msg, $config_keyboard, 'HTML');
    alert("✅ لینک کانفیگ ارسال شد!");
    exit;
}

// تولید و ارسال QR کد برای لینک کانفیگ
if(preg_match('/^getConfigQR_(\d+)$/', $data, $match)){
    $service_id = $match[1];

    $stmt = $connection->prepare("SELECT * FROM `service_orders` WHERE `id` = ? AND `user_id` = ?");
    $stmt->bind_param("ii", $service_id, $from_id);
    $stmt->execute();
    $service = $stmt->get_result()->fetch_assoc();
    $stmt->close();

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

    $config_link = $service['config_link'] ?? $service['config'] ?? '';
    if(empty($config_link)){
        alert("❌ لینک کانفیگ موجود نیست!");
        exit;
    }

    // از کتابخانه phpqrcode استفاده می‌کنیم
    include_once __DIR__ . '/phpqrcode/qrlib.php';
    $tmpdir = __DIR__ . '/phpqrcode/temp/';
    if(!is_dir($tmpdir)) mkdir($tmpdir, 0755, true);
    $filename = 'phpqrcode/temp/qr_' . $service_id . '_' . time() . '.png';
    $filepath = __DIR__ . '/' . $filename;

    // تولید تصویر QR
    QRcode::png($config_link, $filepath, QR_ECLEVEL_L, 6, 2);

    $caption = "📷 <b>QR کد کانفیگ سرویس #{$service_id}</b>";
    $keyboard = [
        [['text' => '◀️ بازگشت به سرویس', 'callback_data' => "viewService_{$service_id}" ]],
        [['text' => '🏠 منوی اصلی', 'callback_data' => 'mainMenu']]
    ];

    // ارسال تصویر QR (ارسال آدرس قابل دسترس وب از متغیر $botUrl)
    sendPhoto($botUrl . $filename, $caption, json_encode(['inline_keyboard'=>$keyboard]), 'HTML');
    alert("✅ QR کد ارسال شد!");
    exit;
}

// ============================================
// هندلرهای سرویس VIP - نمایش لینک و QR کد
// ============================================

// نمایش لینک کامل سرویس VIP
if(preg_match('/^viewVipLink_(\d+)$/', $data, $match)){
    $order_id = $match[1];
    
    $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `id` = ? AND `userid` = ?");
    $stmt->bind_param("ii", $order_id, $from_id);
    $stmt->execute();
    $order = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if(!$order){
        alert("❌ سرویس یافت نشد!");
        exit;
    }
    
    $acc_link = $order['link'];
    
    if(empty($acc_link) || $acc_link == '0' || $acc_link == 'null'){
        alert("❌ لینک اتصال موجود نیست!");
        exit;
    }
    
    $remark = $order['remark'];
    
    $link_msg = "🔗 <b>لینک اتصال کامل</b>\n\n";
    $link_msg .= "📦 سرویس: <code>{$remark}</code>\n\n";
    $link_msg .= "━━━━━━━━━━━━━━━━━━\n\n";
    $link_msg .= "<code>{$acc_link}</code>\n\n";
    $link_msg .= "━━━━━━━━━━━━━━━━━━\n\n";
    $link_msg .= "💡 <b>نحوه استفاده:</b>\n";
    $link_msg .= "۱. لینک بالا را کپی کنید (کلیک روی لینک)\n";
    $link_msg .= "۲. در برنامه v2rayNG یا مشابه وارد کنید\n";
    $link_msg .= "۳. روی Connect کلیک کنید\n\n";
    $link_msg .= "📱 برای راهنمای نصب از دکمه زیر استفاده کنید.";
    
    $keyboard = [
        [['text' => '📷 QR کد', 'callback_data' => "getVipQR_{$order_id}"]],
        [['text' => '📱 راهنمای نصب', 'callback_data' => 'connectionGuide']],
        [['text' => '◀️ بازگشت به سرویس', 'callback_data' => "orderDetails{$order_id}"]],
        [['text' => '🏠 منوی اصلی', 'callback_data' => 'mainMenu']]
    ];
    
    sendMessage($link_msg, json_encode(['inline_keyboard'=>$keyboard]), 'HTML');
    alert("✅ لینک کامل ارسال شد!");
    exit;
}

// تولید QR کد برای سرویس VIP
if(preg_match('/^getVipQR_(\d+)$/', $data, $match)){
    $order_id = $match[1];
    
    $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `id` = ? AND `userid` = ?");
    $stmt->bind_param("ii", $order_id, $from_id);
    $stmt->execute();
    $order = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if(!$order){
        alert("❌ سرویس یافت نشد!");
        exit;
    }
    
    $acc_link = $order['link'];
    
    if(empty($acc_link) || $acc_link == '0' || $acc_link == 'null'){
        alert("❌ لینک اتصال موجود نیست!");
        exit;
    }
    
    // استفاده از کتابخانه phpqrcode
    include_once __DIR__ . '/phpqrcode/qrlib.php';
    $tmpdir = __DIR__ . '/phpqrcode/temp/';
    if(!is_dir($tmpdir)) mkdir($tmpdir, 0755, true);
    $filename = 'phpqrcode/temp/vip_qr_' . $order_id . '_' . time() . '.png';
    $filepath = __DIR__ . '/' . $filename;
    
    // تولید تصویر QR
    QRcode::png($acc_link, $filepath, QR_ECLEVEL_L, 6, 2);
    
    $remark = $order['remark'];
    $caption = "📷 <b>QR کد سرویس VIP</b>\n\n";
    $caption .= "📦 {$remark}\n\n";
    $caption .= "💡 این QR کد را در برنامه خود اسکن کنید";
    
    $keyboard = [
        [['text' => '🔗 مشاهده لینک کامل', 'callback_data' => "viewVipLink_{$order_id}"]],
        [['text' => '📱 راهنمای نصب', 'callback_data' => 'connectionGuide']],
        [['text' => '◀️ بازگشت به سرویس', 'callback_data' => "orderDetails{$order_id}"]],
        [['text' => '🏠 منوی اصلی', 'callback_data' => 'mainMenu']]
    ];
    
    // ارسال تصویر QR
    sendPhoto($botUrl . $filename, $caption, json_encode(['inline_keyboard'=>$keyboard]), 'HTML');
    alert("✅ QR کد ارسال شد!");
    exit;
}

// ============================================
// پایان سیستم تایید/رد
// ============================================

// دریافت کانفیگ سرویس
if(preg_match('/^getServiceConfig_(\d+)$/', $data, $match)){
    $order_id = $match[1];
    
    $stmt = $connection->prepare("SELECT so.*, sp.name as plan_name, sp.volume_gb, sp.days 
                                   FROM `service_orders` so 
                                   JOIN `service_plans` sp ON so.plan_id = sp.id 
                                   WHERE so.id = ? AND so.user_id = ?");
    $stmt->bind_param("ii", $order_id, $from_id);
    $stmt->execute();
    $order = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if(!$order){
        alert("❌ سرویس یافت نشد!");
        exit;
    }
    
    if($order['status'] != 'active'){
        alert("⚠️ این سرویس غیرفعال است!");
        exit;
    }
    
    // ارسال کانفیگ
    $config_link = $order['config_link'];
    $uuid = $order['uuid'];
    
    $volume_text = $order['volume_gb'] > 0 ? $order['volume_gb'] . ' گیگ' : 'نامحدود';
    $expire_date = jdate('Y/m/d', strtotime($order['expire_date']));
    
    $config_msg = "📱 <b>کانفیگ سرویس شما</b>\n\n";
    $config_msg .= "━━━━━━━━━━━━━━━━━━\n";
    $config_msg .= "📦 پلن: <b>{$order['plan_name']}</b>\n";
    $config_msg .= "🔋 حجم: <code>{$volume_text}</code>\n";
    $config_msg .= "⏰ مدت: <code>{$order['days']} روز</code>\n";
    $config_msg .= "📅 انقضا: <code>{$expire_date}</code>\n";
    $config_msg .= "━━━━━━━━━━━━━━━━━━\n\n";
    $config_msg .= "🔑 <b>UUID:</b>\n<code>{$uuid}</code>\n\n";
    
    if($config_link){
        $config_msg .= "🔗 <b>لینک کانفیگ:</b>\n<code>{$config_link}</code>\n\n";
    }
    
    $config_msg .= "━━━━━━━━━━━━━━━━━━\n";
    $config_msg .= "💡 برای کپی کردن، روی متن کلیک کنید.";
    
    $keyboard = [
        [['text' => '📱 راهنمای اتصال', 'callback_data' => 'connectionGuide']],
        [['text' => '🔄 تمدید سرویس', 'callback_data' => "renewService_{$order_id}"]],
        [['text' => '🏠 منو اصلی', 'callback_data' => 'mainMenu']]
    ];
    
    delMessage();
    sendMessage($config_msg, json_encode(['inline_keyboard' => $keyboard]), 'HTML');
    exit;
}

if(preg_match('/^delDiscount(\d+)/',$data,$match)){
    $stmt = $connection->prepare("DELETE FROM `discounts` WHERE `id` = ?");
    $stmt->bind_param("i", $match[1]);
    $stmt->execute();
    $stmt->close();
    
    alert("کد تخفیف مورد نظر با موفقیت حذف شد");
    editText($message_id,"مدیریت کد های تخفیف",getDiscountCodeKeys());
}
if(preg_match('/^copyHash(.*)/',$data,$match)){
    sendMessage("<code>" . $match[1] . "</code>",null,"HTML");
}
if($data == "managePanel" and (($from_id == $admin || $userInfo['isAdmin'] == true))){
    
    setUser();
    $msg = "
👤 عزیزم به بخش مدیریت خوشومدی 
🤌 هرچی نیاز داشتی میتونی اینجا طبق نیازهات اضافه و تغییر بدی ، عزیزم $first_name جان اگه از فروش ربات درآمد داری از من حمایت کن تا پروژه همیشه آپدیت بمونه !

🆔 @NoovixCo

🚪 /start
";
    editText($message_id, $msg, getAdminKeys());
}
if($data == 'reciveApplications') {
    $stmt = $connection->prepare("SELECT * FROM `needed_sofwares` WHERE `status`=1");
    $stmt->execute();
    $respd= $stmt->get_result();
    $stmt->close();

    $keyboard = []; 
    while($file =  $respd->fetch_assoc()){ 
        $link = $file['link'];
        $title = $file['title'];
        $keyboard[] = ['text' => "$title", 'url' => $link];
    }
    $keyboard[] = ['text'=>$buttonValues['back_to_main'],'callback_data'=>"mainMenu"];
    $keyboard = array_chunk($keyboard,1); 
    editText($message_id, "
🔸می توانید به راحتی همه فایل ها را (به صورت رایگان) دریافت کنید
📌 شما میتوانید برای راهنمای اتصال به سرویس کانال رسمی مارا دنبال کنید و همچنین از دکمه های زیر میتوانید برنامه های مورد نیاز هر سیستم عامل را دانلود کنید

✅ پیشنهاد ما برنامه V2rayng است زیرا کار با آن ساده است و برای تمام سیستم عامل ها قابل اجرا است، میتوانید به بخش سیستم عامل مورد نظر مراجعه کنید و لینک دانلود را دریافت کنید
", json_encode(['inline_keyboard'=>$keyboard]));
}
if ($text == $buttonValues['cancel']) {
    setUser();
    $stmt = $connection->prepare("DELETE FROM `server_plans` WHERE `active`=0");
    $stmt->execute();
    $stmt->close();

    sendMessage($mainValues['waiting_message'], $removeKeyboard);
    sendMessage($mainValues['reached_main_menu'],getMainKeys());
}
?>
