<?php
global $connection, $data, $text, $from_id, $admin, $userInfo, $message_id, $mainValues, $buttonValues, $cancelKey, $removeKeyboard, $fileid, $caption, $botState;

// مدیریت کال‌بک پیام خصوصی به کاربر خاص
if ($data == 'messageToSpeceficUser' && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    setUser('messageToSpeceficUser');
    editText($message_id, "👤 لطفا آیدی عددی کاربر مورد نظر را ارسال کنید:", $cancelKey);
}
// دریافت آیدی عددی کاربر و هدایت به استپ ارسال پیام
if ($userInfo['step'] == 'messageToSpeceficUser' && ($from_id == $admin || $userInfo['isAdmin'] == true) && $text != $buttonValues['cancel']) {
    if (is_numeric($text)) {
        setUser("sendMessageToUser_" . $text . "_" . $message_id);
        sendMessage('🔘| لطفا پیام خود را برای کاربر ارسال کنید:', $cancelKey);
    } else {
        sendMessage("❌ آیدی عددی نامعتبر است. لطفا مجددا آیدی عددی را بفرستید:", $cancelKey);
    }
}

if (preg_match('/^sendMessageToUser(\d+)/', (string)$data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true) && $text != $buttonValues['cancel']) {
    editText($message_id, '🔘|لطفا پیامت رو بفرست');
    setUser("sendMessageToUser_" . $match[1] . "_" . $message_id);
}
if (preg_match('/^sendMessageToUser_(?P<userid>\d+)_(?P<msg_id>\d+)/', (string)$userInfo['step'], $match) && ($from_id == $admin || $userInfo['isAdmin'] == true) && $text != $buttonValues['cancel']) {
    $target_user_id = $match['userid'];
    $notify_msg_id = $match['msg_id'];
    
    sendMessage($text, null, null, $target_user_id);
    editText($notify_msg_id, "💬 پیام ارسالی به مخاطب:\n\n" . $text);
    
    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+)/', (string)$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+)/", (string)$data, $match)) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    if ($data != "botSettings") {
        if ($match[1] == "cartToCartAutoAcceptType")
            $newValue = $botState[$match[1]] == "0" ? "1" : ($botState[$match[1]] == "1" ? "2" : 0);
        else
            $newValue = $botState[$match[1]] == "on" ? "off" : "on";
        setSettings($match[1], $newValue);
    }
    editText($message_id, $mainValues['change_bot_settings_message'], getBotSettingKeys());
}
if ($data == "changeUpdateConfigLinkState" && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $newValue = $botState['updateConnectionState'] == "robot" ? "site" : "robot";
    setSettings('updateConnectionState', $newValue);
    editText($message_id, $mainValues['change_bot_settings_message'], getBotSettingKeys());
}
if (($data == "gateWays_Channels" or preg_match("/^changeGateWays(\w+)/", (string)$data, $match)) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    if ($data != "gateWays_Channels") {
        $newValue = ($botState[$match[1]] ?? 'off') == "on" ? "off" : "on";
        setSettings($match[1], $newValue);
    }
    editText($message_id, $mainValues['change_bot_settings_message'], getGateWaysKeys());
}
if ($data == "changeConfigRemarkType") {
    switch ($botState['remark']) {
        case "digits":
            $newValue = "manual";
            break;
        case "manual":
            $newValue = "idanddigits";
            break;
        default:
            $newValue = "digits";
            break;
    }
    setSettings('remark', $newValue);
    editText($message_id, $mainValues['change_bot_settings_message'], getBotSettingKeys());
}

if (($data == "agentsList" || preg_match('/^nextAgentList(\d+)/', (string)$data, $match)) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $keys = getAgentsList($match[1] ?? 0);
    if ($keys != null)
        editText($message_id, $mainValues['agents_list'], $keys);
    else
        alert("نماینده ای یافت نشد");
}
if (preg_match('/^agentDetails(\d+)/', (string)$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+)/', (string)$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']);
    $keys = getAgentsList();
    if ($keys != null)
        editKeys($keys);
    else
        editKeys(json_encode(['inline_keyboard' => [[['text' => $buttonValues['back_button'], 'callback_data' => "managePanel"]]]]));
}
if (preg_match('/^agentPercentDetails(\d+)/', (string)$data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $stmt = $connection->prepare("SELECT * FROM `users` WHERE `userid` = ?");
    $stmt->bind_param('i', $match[1]);
    $stmt->execute();
    $info = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    $userName = $info['name'];
    editText($message_id, str_replace("AGENT-NAME", $userName, $mainValues['agent_discount_settings']), getAgentDiscounts($match[1]));
}
if (preg_match('/^addDiscount(Server|Plan)Agent(\d+)/', (string)$data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $stmt = $connection->prepare("SELECT * FROM `users` WHERE `userid` = ?");
    $stmt->bind_param('i', $match[2]);
    $stmt->execute();
    $info = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $userName = $info['name'];

    if ($match[1] == "Plan") {
        $offset = 0;
        $limit = 20;

        $condition = array_values(array_keys(json_decode($info['discount_percent'], true)['plans'] ?? array()));
        $condition = count($condition) > 0 ? "WHERE `id` NOT IN (" . implode(",", $condition) . ")" : "";
        $stmt = $connection->prepare("SELECT * FROM `server_plans` $condition LIMIT ? OFFSET ?");
        $stmt->bind_param("ii", $limit, $offset);
        $stmt->execute();
        $list = $stmt->get_result();
        $stmt->close();

        if ($list->num_rows > 0) {
            $keys = array();
            while ($row = $list->fetch_assoc()) {
                $stmt = $connection->prepare("SELECT * FROM `server_categories` WHERE `id` = ?");
                $stmt->bind_param("i", $row['catid']);
                $stmt->execute();
                $catInfo = $stmt->get_result()->fetch_assoc();
                $stmt->close();

                $keys[] = [['text' => $row['title'] . " " . $catInfo['title'], 'callback_data' => "editAgentDiscountPlan" . $match[2] . "_" . $row['id']]];
            }

            if ($list->num_rows >= $limit) {
                $keys[] = [['text' => "▶️", 'callback_data' => "nextAgentDiscountPlan" . $match[2] . "_" . ($offset + $limit)]];
            }
            $keys[] = [['text' => $buttonValues['back_button'], 'callback_data' => "agentPercentDetails" . $match[2]]];
            $keys = json_encode(['inline_keyboard' => $keys]);

            editText($message_id, "لطفا سرور مورد نظر را برای افزودن تخفیف به نماینده $userName انتخاب کنید", $keys);
        } else
            alert("سروری باقی نمانده است");
    } else {
        $condition = array_values(array_keys(json_decode($info['discount_percent'], true)['servers'] ?? array()));
        $condition = count($condition) > 0 ? "WHERE `id` NOT IN (" . implode(",", $condition) . ")" : "";
        $stmt = $connection->prepare("SELECT * FROM `server_info` $condition");
        $stmt->execute();
        $list = $stmt->get_result();
        $stmt->close();

        if ($list->num_rows > 0) {
            $keys = array();
            while ($row = $list->fetch_assoc()) {
                $keys[] = [['text' => $row['title'], 'callback_data' => "editAgentDiscountServer" . $match[2] . "_" . $row['id']]];
            }

            $keys[] = [['text' => $buttonValues['back_button'], 'callback_data' => "agentPercentDetails" . $match[2]]];
            $keys = json_encode(['inline_keyboard' => $keys]);

            editText($message_id, "لطفا سرور مورد نظر را برای افزودن تخفیف به نماینده $userName انتخاب کنید", $keys);
        } else
            alert("سروری باقی نمانده است");
    }
}
if (preg_match('/^nextAgentDiscountPlan(?<agentId>\d+)_(?<offset>\d+)/', (string)$data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $stmt = $connection->prepare("SELECT * FROM `users` WHERE `userid` = ?");
    $stmt->bind_param('i', $match['agentId']);
    $stmt->execute();
    $info = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $userName = $info['name'];

    $offset = $match['offset'];
    $limit = 20;

    $condition = array_values(array_keys(json_decode($info['discount_percent'], true)['plans'] ?? array()));
    $condition = count($condition) > 0 ? "WHERE `id` NOT IN (" . implode(",", $condition) . ")" : "";
    $stmt = $connection->prepare("SELECT * FROM `server_plans` $condition LIMIT ? OFFSET ?");
    $stmt->bind_param("ii", $limit, $offset);
    $stmt->execute();
    $list = $stmt->get_result();
    $stmt->close();

    if ($list->num_rows > 0) {
        $keys = array();
        while ($row = $list->fetch_assoc()) {
            $stmt = $connection->prepare("SELECT * FROM `server_categories` WHERE `id` = ?");
            $stmt->bind_param("i", $row['catid']);
            $stmt->execute();
            $catInfo = $stmt->get_result()->fetch_assoc();
            $stmt->close();

            $keys[] = [['text' => $row['title'] . " " . $catInfo['title'], 'callback_data' => "editAgentDiscountPlan" . $match['agentId'] . "_" . $row['id']]];
        }

        if ($list->num_rows >= $limit && $offset == 0) {
            $keys[] = [['text' => "▶️", 'callback_data' => "nextAgentDiscountPlan" . $match['agentId'] . "_" . ($offset + $limit)]];
        } elseif ($list->num_rows >= $limit && $offset != 0) {
            $keys[] = [
                ['text' => "◀️️", 'callback_data' => "nextAgentDiscountPlan" . $match['agentId'] . "_" . ($offset - $limit)],
                ['text' => "▶️", 'callback_data' => "nextAgentDiscountPlan" . $match['agentId'] . "_" . ($offset + $limit)]
            ];
        } elseif ($offset != 0) {
            $keys[] = [
                ['text' => "◀️️", 'callback_data' => "nextAgentDiscountPlan" . $match['agentId'] . "_" . ($offset - $limit)]
            ];
        }
        $keys[] = [['text' => $buttonValues['back_button'], 'callback_data' => "agentPercentDetails" . $match['agentId']]];
        $keys = json_encode(['inline_keyboard' => $keys]);

        editText($message_id, "لطفا سرور مورد نظر را برای افزودن تخفیف به نماینده $userName انتخاب کنید", $keys);
    } else
        alert("سروری باقی نمانده است");
}
if (preg_match('/^removePercentOfAgent(?<type>Server|Plan)(?<agentId>\d+)_(?<serverId>\d+)/', (string)$data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $stmt = $connection->prepare("SELECT * FROM `users` WHERE `userid` = ?");
    $stmt->bind_param('i', $match['agentId']);
    $stmt->execute();
    $info = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    $discounts = json_decode($info['discount_percent'], true);
    if ($match['type'] == "Server")
        unset($discounts['servers'][$match['serverId']]);
    elseif ($match['type'] == "Plan")
        unset($discounts['plans'][$match['serverId']]);

    $discounts = json_encode($discounts, 488);
    $stmt = $connection->prepare("UPDATE `users` SET `discount_percent` = ? WHERE `userid` = ?");
    $stmt->bind_param("si", $discounts, $match['agentId']);
    $stmt->execute();
    $stmt->close();

    alert('با موفقیت حذف شد');
    editText($message_id, str_replace("AGENT-NAME", $userName, $mainValues['agent_discount_settings']), getAgentDiscounts($match['agentId']));
}
if (preg_match('/^editAgentDiscount(Server|Plan|Normal)(\d+)_(.*)/', (string)$data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    delMessage();
    sendMessage($mainValues['send_agent_discount_percent'], $cancelKey);
    setUser($data);
}
if (preg_match('/^editAgentDiscount(Server|Plan|Normal)(\d+)_(.*)/', (string)$userInfo['step'], $match) && ($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', $match[2]);
        $stmt->execute();
        $info = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        $discountInfo = json_decode($info['discount_percent'], true);
        if ($match[1] == "Server")
            $discountInfo['servers'][$match[3]] = $text;
        elseif ($match[1] == "Plan")
            $discountInfo['plans'][$match[3]] = $text;
        elseif ($match[1] == "Normal")
            $discountInfo['normal'] = $text;
        $text = json_encode($discountInfo);

        sendMessage($mainValues['saved_successfuly'], $removeKeyboard);

        $stmt = $connection->prepare("UPDATE `users` SET `discount_percent` = ? WHERE `userid` = ?");
        $stmt->bind_param("si", $text, $match[2]);
        $stmt->execute();
        $stmt->close();
        sendMessage(str_replace("AGENT-NAME", $userName, $mainValues['agent_discount_settings']), getAgentDiscounts($match[2]));
        setUser();
    } else
        sendMessage($mainValues['send_only_number']);
}

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' => [
        [getBtn("invite_banner", "inviteBanner")],
        [
            getBtn("edit_invite_amount", "editInviteAmount"),
            getBtn("invite_commission", "NetFreedomVPN")
        ],
        [
            getBtn("back_button", "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' => [
        [getBtn("edit_invite_banner", "editInviteBannerText")],
        [getBtn("back_button", "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' => [
        [getBtn("edit_invite_banner", "editInviteBannerText")],
        [getBtn("back_button", "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" && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    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' => [
            [getBtn("invite_banner", "inviteBanner")],
            [
                getBtn("edit_invite_amount", "editInviteAmount"),
                getBtn("invite_commission", "NetFreedomVPN")
            ],
            [
                getBtn("back_button", "botSettings")
            ],
        ]]);
        sendMessage("✅ تنظیمات بازاریابی", $keys);
        setUser();
    } else
        sendMessage($mainValues['send_only_number']);
}


// --- Start of Range 779 to 814 ---
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") {
            setSettings('rewardChannel', $text);
            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") {
            setSettings("lockChannel", $text);
            sendMessage($mainValues['change_bot_settings_message'], getGateWaysKeys());
            setUser();
            exit();
        }
    }
    sendMessage($mainValues['the_bot_in_not_admin']);
}

// --- Start of Range 1189 to 1311 ---
// --- 2. دریافت پیام همگانی از ادمین ---
if ($userInfo['step'] == 's2a' && $text != $buttonValues['cancel'] && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    setUser(); // خروج از حالت استپ

    // تعیین نوع پیام (متن یا فایل)
    $msgType = 'text';
    $msgContent = $text;
    $fileId = null;

    if (isset($update['message']['photo'])) {
        $msgType = 'photo';
        $fileId = end($update['message']['photo'])['file_id']; // با کیفیت‌ترین عکس
        $msgContent = $caption ?? "";
    } elseif (isset($update['message']['document'])) {
        $msgType = 'document';
        $fileId = $update['message']['document']['file_id'];
        $msgContent = $caption ?? "";
    } elseif (isset($update['message']['video'])) {
        $msgType = 'video';
        $fileId = $update['message']['video']['file_id'];
        $msgContent = $caption ?? "";
    } elseif (isset($update['message']['voice'])) {
        $msgType = 'voice';
        $fileId = $update['message']['voice']['file_id'];
        $msgContent = $caption ?? "";
    }

    // ذخیره در دیتابیس
    if ($fileId !== null) {
        $stmt = $connection->prepare("INSERT INTO `send_list` (`type`, `text`, `file_id`) VALUES (?, ?, ?)");
        $stmt->bind_param('sss', $msgType, $msgContent, $fileId);
    } else {
        $stmt = $connection->prepare("INSERT INTO `send_list` (`type`, `text`) VALUES ('text', ?)");
        $stmt->bind_param("s", $text);
    }

    $stmt->execute();
    $id = $stmt->insert_id;
    $stmt->close();

    sendMessage('⏳ مرسی از پیامت ... ', $removeKeyboard);
    sendMessage("برای همه بفرستم؟", json_encode(['inline_keyboard' => [
        [getBtn("yes_send_to_all", "yesSend2All" . $id)],
        [getBtn("no_dont_send_to_all", "noDontSend2all" . $id)]
    ]]));
}

// --- 3. درخواست فوروارد همگانی ---
if ($data == "forwardToAll" && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $stmt = $connection->prepare("SELECT * FROM `send_list` WHERE `state` = 1");
    $stmt->execute();
    $info = $stmt->get_result();
    $stmt->close();

    if ($info->num_rows > 0) {
        // نمایش وضعیت صف
        $sendInfo = $info->fetch_assoc();
        $offset = $sendInfo['offset'] ?? 0;

        $stmt = $connection->prepare("SELECT COUNT(*) as count FROM `users`");
        $stmt->execute();
        $usersCount = $stmt->get_result()->fetch_assoc()['count'];
        $stmt->close();

        $leftMessages = $usersCount - $offset;

        sendMessage("❗️ یک فوروارد همگانی در صف انتشار می‌باشد...
        
🔰 تعداد کاربران: $usersCount
☑️ فوروارد شده: $offset
📣 باقیمانده: $leftMessages");
    } else {
        // حذف پیام قبلی و درخواست پیام جدید برای فوروارد
        delMessage();
        setUser('forwardToAll');
        sendMessage($mainValues['forward_your_message'], $cancelKey);
    }
}

// --- 4. دریافت پیام برای فوروارد ---
if ($userInfo['step'] == "forwardToAll" && ($from_id == $admin || $userInfo['isAdmin'] == true) && $text != $buttonValues['cancel']) {
    // ذخیره اطلاعات برای فوروارد (فقط آیدی پیام و چت کافیست)
    $stmt = $connection->prepare("INSERT INTO `send_list` (`type`, `message_id`, `chat_id`) VALUES ('forwardall', ?, ?)");
    $stmt->bind_param('ss', $message_id, $chat_id);
    $stmt->execute();
    $id = $stmt->insert_id;
    $stmt->close();

    setUser(); // خروج
    sendMessage('⏳ مرسی از پیامت ... ', $removeKeyboard);
    sendMessage("برای همه فوروارد کنم؟", json_encode(['inline_keyboard' => [
        [getBtn("yes_send_to_all", "yesSend2All" . $id)],
        [getBtn("no_dont_send_to_all", "noDontSend2all" . $id)]
    ]]));
}

// --- 5. دکمه تایید ارسال (مشترک برای پیام و فوروارد) ---
if (preg_match('/^yesSend2All(\d+)/', (string)$data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $stmt = $connection->prepare("UPDATE `send_list` SET `state` = 1 WHERE `id` = ?");
    $stmt->bind_param('i', $match[1]);
    $stmt->execute();
    $stmt->close();

    // ویرایش پیام به جای حذف دکمه (زیباتر)
    editKeys(json_encode(['inline_keyboard' => []]));
    sendMessage('✅ دستور ارسال صادر شد. کم‌کم برای همه ارسال میشه...', getMainKeys());
}

// --- 6. دکمه لغو ارسال ---
if (preg_match('/^noDontSend2all(\d+)/', (string)$data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $stmt = $connection->prepare("DELETE FROM `send_list` WHERE `id` = ?");
    $stmt->bind_param('i', $match[1]);
    $stmt->execute();
    $stmt->close();

    editKeys(json_encode(['inline_keyboard' => []]));
    sendMessage('❌ ارسال پیام همگانی لغو شد.', getMainKeys());
}



// --- Start of Range 3184 to 3296 ---
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+)/', (string)$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'] && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    if (!isset($update->message->text)) {
        sendMessage("لطفا فقط متن بفرستید");
        exit();
    }
    sendMessage("لطفا پاسخ دکمه را وارد کنید");
    setUser("setMainButtonAnswer" . $text);
}
if (preg_match('/^setMainButtonAnswer(.*)/', (string)$userInfo['step'], $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    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']);
    }
}

// --- Start of Range 3357 to 3367 ---
if (preg_match('/^showMainButtonAns(\d+)/', (string)$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"]]
    ]]));
}

// --- Start of Range 3431 to 3452 ---
if ($data == "rejectedAgentList" && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $keys = getRejectedAgentList();
    if ($keys != null) {
        editText($message_id, "لیست کاربران رد شده از نمایندگی", $keys);
    } else
        alert("کاربری یافت نشد");
}
if (preg_match('/^releaseRejectedAgent(\d+)/', (string)$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['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"]]]]));
}
