<?php

namespace Bot\BotHandler;

use Bot\FormManager;
use Bot\DatePicker;
use Bot\locationHandler;

trait CallbackTrait
{

    public function handleCallbackQuery($callbackQuery): void
    {
        $callbackData = $callbackQuery["data"] ?? null;
        $chatId = $callbackQuery["message"]["chat"]["id"] ?? null;
        $this->callbackQueryId = $callbackQuery["id"] ?? null;
        $messageId = $callbackQuery["message"]["message_id"] ?? null;
        $currentKeyboard = $callbackQuery["message"]["reply_markup"]["inline_keyboard"] ?? [];
        $userLanguage = $this->db->getUserLanguage($this->chatId);

        $user = $this->message['from'] ?? $this->callbackQuery['from'] ?? null;


        if ($user !== null) {
            $this->db->saveUser($user);
        } else {
            error_log("❌ Cannot save user: 'from' is missing in both message and callbackQuery.");
        }
        if ($this->checkUserStatus($this->chatId)) {
            return;
        }

        $state = $this->stateManager->getState($this->chatId);

        if ($state && isset($state['form_key'])) {
            $formsConfig = include(__DIR__ . '/Forms.php');
            $currentStepKey = $state['current_step'];
            $fieldConfig = $formsConfig[$state['form_key']]['fields'][$currentStepKey] ?? null;

            // --- پردازشگر اختصاصی برای DatePicker و TimePicker ---
            if ($fieldConfig && ($fieldConfig['type'] === 'datepicker' || $fieldConfig['type'] === 'timepicker')) {

                $datePicker = new \Bot\DatePicker();

                // بر اساس نوع فیلد، متد مناسب را از DatePicker فراخوانی کن
                $result = ($fieldConfig['type'] === 'datepicker')
                    ? $datePicker->handleCallback($callbackData)
                    : $datePicker->handleTimeCallback($callbackData);

                // --- اگر کاربر در حال تغییر نما است (مثلا تغییر ماه) ---
                if ($result['status'] === 'update') {
                    // شما قبلا یک تابع برای تولید خلاصه ساخته اید
                    // اگر حذف شده، باید آن را برگردانید یا از FormManager بگیرید
                    $summaryText = $this->generateTourSummaryText($state['data']);

                    $this->sendRequest("editMessageText", [
                        "chat_id" => $this->chatId,
                        "message_id" => $this->messageId,
                        "text" => $summaryText . "\n" . $result['new_data']['text'],
                        "parse_mode" => "HTML",
                        "reply_markup" => $result['new_data']['reply_markup']
                    ]);

                    // --- اگر کاربر انتخاب خود را تایید کرده است ---
                } elseif ($result['status'] === 'confirmed') {
                    $value = null;

                    if ($fieldConfig['type'] === 'datepicker') {
                        $date = $result['date'];
                        // تاریخ شمسی را به فرمت استاندارد میلادی تبدیل می کنیم
                        $gregorianArray = $this->jalaliToGregorian($date['year'], $date['month'], $date['day']);
                        $value = sprintf('%04d-%02d-%02d', $gregorianArray[0], $gregorianArray[1], $gregorianArray[2]);
                    } else { // اگر timepicker بود
                        $value = $result['time'];
                    }

                    // مقدار نهایی را به FormManager ارسال می کنیم تا آن را ذخیره کرده و به مرحله بعد برود
                    $formManager = new FormManager($this, $this->stateManager, $formsConfig);
                    $formManager->handle($this->chatId, $value);
                } elseif ($result['status'] === 'back') {
                    $formManager = new FormManager($this, $this->stateManager, $formsConfig);
                    $formManager->goToPreviousStep($this->chatId); // تابعی که مرحله قبلی را لود می کند
                }

                return; // اجرای ادامه کد متوقف شود
            }

            // اگر callback مربوط به فرم بود ولی از نوع تقویم نبود، آن را به FormManager بسپار
            $formManager = new FormManager($this, $this->stateManager, $formsConfig);
            $formManager->handle($this->chatId, $callbackData);
            return;
        }

        if (!$callbackData || !$chatId || !$messageId) {
            error_log("Callback query missing required data.");
            return;
        }

        if ($callbackData == 'user_panel') {
            $userInfo = $this->db->registeredExplorerByUserId($this->chatId);
            $firstName = $userInfo['first_name'] ?? 'کاربر';

            $welcomeText = "سلام <b>" . htmlspecialchars($firstName) . "</b> عزیز،\n\n";
            $welcomeText .= "به پنل کاربری خودت خوش اومدی! 🌿\n\n";
            $welcomeText .= "از گزینه های زیر برای مدیریت حساب و تورها استفاده کن 👇";

            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => $welcomeText,
                "parse_mode" => "HTML",
                "reply_markup" => $this->getUserPanelKeyboard()
            ]);
        }

        if ($callbackData == 'bot_guide') {
            $this->uploadGuidesMenu($this->chatId, $this->messageId);
        }
        if ($callbackData == 'support_user') {
            $supportText = "📞 *پشتیبانی*\n\n" .
                "اگر سوالی داشتی یا به کمک نیاز داشتی، ما اینجا هستیم تا کمکت کنیم! 😊\n" .
                "برای ارتباط مستقیم با پشتیبانی، لطفاً به آی دی زیر پیام بده:\n\n" .
                "[📨 @Arcbau ](https://t.me/Arcbau )\n\n" .
                "سعی می کنیم در سریع ترین زمان ممکن پاسخگوی شما باشیم.";
            $response = $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => $supportText,
                "parse_mode" => "Markdown",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [
                            ["text" => "🔙 بازگشت به پنل", "callback_data" => "go_to_menu"],
                        ]
                    ]
                ])
            ]);
        }
        if (str_starts_with($callbackData, 'edit_user_field_')) {
            $fieldKey = str_replace('edit_user_field_', '', $callbackData);

            $fieldLabels = [
                'first_name' => 'نام',
                'last_name' => 'نام خانوادگی',
                'nick_name' => 'نام مستعار',
                'phone' => 'شماره همراه',
                'city' => 'شهر'
            ];

            $label = $fieldLabels[$fieldKey] ?? 'فیلد';
            $this->fileHandler->saveState($chatId, 'awaiting_user_edit_' . $fieldKey);

            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => "لطفاً مقدار جدید برای «<b>" . htmlspecialchars($label) . "</b>» را وارد کنید:",
                "parse_mode" => "HTML",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [['text' => '❌ لغو ویرایش', 'callback_data' => 'user_info']]
                    ]
                ])
            ]);
            return;
        }
        if ($callbackData == 'edit_user_profile') {
            $res = $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => "کدام بخش از اطلاعات خود را می خواهید ویرایش کنید؟",
                "reply_markup" => $this->getEditUserProfileKeyboard()
            ]);
            $this->fileHandler->saveMessageId($chatId, $res['result']['message_id'] ?? '');
            return;
        }

        if ($callbackData == 'user_info') {
            $user_info = $this->db->registeredExplorerByUserId($this->chatId);
            if ($user_info) {
                $text = "📄 <b>اطلاعات پروفایل طبیعتگردی شما</b>\n\n";
                $text .= "<blockquote>";
                $text .= "👤 <b>نام:</b> " . htmlspecialchars($user_info['first_name'] . " " . $user_info['last_name']) . "\n";
                $text .= "👥 <b>نام مستعار:</b> " . htmlspecialchars($user_info['nick_name']) . "\n";
                $text .= "🎂 <b>تاریخ تولد:</b> " . $this->gregorianToJalali($user_info['date_of_birth']) . "\n";
                $text .= "📱 <b>شماره همراه:</b> <code>" . htmlspecialchars($user_info['phone']) . "</code>\n"; // استفاده از تگ code برای کپی راحت تر
                $text .= "🏙️ <b>شهر:</b> " . htmlspecialchars($user_info['city']);
                $text .= "</blockquote>\n\n";
                $text .= "<i>در صورت نیاز به تغییر، از دکمه ویرایش استفاده کنید.</i>";

                $keyboard = [
                    'inline_keyboard' => [
                        [
                            ['text' => '✏️ ویرایش اطلاعات', 'callback_data' => 'edit_user_profile'],
                        ],
                        [
                            ['text' => '🔙 بازگشت به پنل', 'callback_data' => 'user_panel'],
                        ]
                    ]
                ];

                // ۳. ارسال درخواست ویرایش پیام
                $this->sendRequest("editMessageText", [
                    "chat_id" => $chatId,
                    "message_id" => $messageId,
                    "text" => $text,
                    "parse_mode" => "HTML",
                    "reply_markup" => json_encode($keyboard)
                ]);
            } else {
                // ۴. بهبود مدیریت خطا
                $this->sendRequest("editMessageText", [
                    "chat_id" => $chatId,
                    "message_id" => $messageId,
                    "text" => "❌ اطلاعات پروفایل شما یافت نشد. لطفاً ابتدا ثبت نام خود را تکمیل کنید.",
                    "reply_markup" => json_encode([
                        "inline_keyboard" => [
                            [['text' => "🔙 بازگشت", "callback_data" => "user_panel"]]
                        ]
                    ])
                ]);
            }
            return;
        }

        if (strpos($callbackData, 'user_details_') === 0) {

            $explorerId = (int) str_replace('user_details_', '', $callbackData);

            $explorer_profile = $this->db->getExplorerById($explorerId);

            // ۳. بررسی یافت شدن کاربر و مدیریت خطا
            if (!$explorer_profile) {
                $this->sendRequest("answerCallbackQuery", [
                    "callback_query_id" => $this->callbackQueryId,
                    "text" => "❌ کاربر پیدا نشد.",
                    "show_alert" => true
                ]);
                return;
            }

            // ۴. دریافت نقش های کاربر از جدول `users` با استفاده از `chat_id`
            $user_roles = $this->db->getUserByUserId($explorer_profile['chat_id']);

            // ۵. ساخت متن پیام بر اساس نقش کاربر
            $text = "👤 اطلاعات کاربر\n\n";
            $text .= "<b>نام:</b> " . htmlspecialchars($explorer_profile['first_name'] . ' ' . $explorer_profile['last_name']) . "\n";
            $text .= "<b>نام مستعار:</b> " . htmlspecialchars($explorer_profile['nick_name']) . "\n";
            $text .= "<b>شماره همراه:</b> <code>" . htmlspecialchars($explorer_profile['phone']) . "</code>\n";
            $text .= "<b>شهر:</b> " . htmlspecialchars($explorer_profile['city']) . "\n";
            $keyboard = [];
            // اگر کاربر نقش لیدر را داشت، اطلاعات بیشتری نمایش بده
            if ($user_roles && $user_roles['is_leader']) {
                $text .= "\n👑 اطلاعات تکمیلی لیدر:\n";
                $text .= "<b>کد ملی:</b> " . htmlspecialchars($explorer_profile['national_code']) . "\n";
                $text .= "<b>کانال:</b> " . htmlspecialchars($explorer_profile['channel']) . "\n";
                $text .= "<b>گروه:</b> " . htmlspecialchars($explorer_profile['group_link']) . "\n";
                $text .= "<b>شماره کارت:</b> <code>" . htmlspecialchars($explorer_profile['card_number']) . "</code>\n";
                $keyboard = [
                    "inline_keyboard" => [
                        //
                        [
                            ["text" => "🔙 بازگشت", "callback_data" => "admin_view_leaders_page_1"]
                        ]
                    ]
                ];
            } else {

                $keyboard = [
                    "inline_keyboard" => [
                        //                    [
                        //                        ["text" => "🚫 مسدود کردن", "callback_data" => "block_user_" . $explorer_profile['chat_id']],
                        //                        ["text" => "🗑 حذف", "callback_data" => "delete_user_" . $explorer_profile['chat_id']]
                        //                    ],
                        [
                            ["text" => "🔙 بازگشت", "callback_data" => "admin_view_users_page_1"]
                        ]
                    ]
                ];
            }

            // ۷. ارسال پیام ویرایش شده با اطلاعات جدید
            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => $text,
                "parse_mode" => "HTML", // برای نمایش صحیح تگ های <b> و <code>
                "reply_markup" => json_encode($keyboard)
            ]);
        }


        if (strpos($callbackData, 'user_leader_details_') === 0) {

            $parts = explode('_', $callbackData); // [user, leader, details, explorerId, tourId]
            $explorerId = (int)$parts[3];
            $tourId = (int)$parts[4];
            $explorer_profile = $this->db->registeredExplorerByUserId($explorerId);
            $payment = $this->db->getPaymentDetailsByUserId($explorerId, $tourId);


            // ۳. بررسی یافت شدن کاربر و مدیریت خطا
            if (!$explorer_profile) {
                $this->sendRequest("answerCallbackQuery", [
                    "callback_query_id" => $this->callbackQueryId,
                    "text" => "❌ کاربر پیدا نشد.",
                    "show_alert" => true
                ]);
                return;
            }

            // ۴. دریافت نقش های کاربر از جدول `users` با استفاده از `chat_id`
            $user_roles = $this->db->getUserByUserId($explorer_profile['chat_id']);
            $statusTexts = [
                "pending"   => "در انتظار پرداخت",
                "completed" => "پرداخت شده",
                "failed"    => "پرداخت ناموفق"
            ];
            $paymentTexts = [
                "online_payment"   => "آنلاین",
                "card_to_card" => "کارت به کارت(تایید نشده)",
                "card_to_card_admin"    => "کارت به کارت",
                "free"   => "رایگان"
            ];
            // ۵. ساخت متن پیام بر اساس نقش کاربر
            $text  = "👤 <b>اطلاعات کاربر</b>\n\n";
            $text .= "🧑‍💼 <b>نام:</b> " . htmlspecialchars($explorer_profile['first_name'] . ' ' . $explorer_profile['last_name']) . "\n";
            $text .= "⭐ <b>نام مستعار:</b> " . htmlspecialchars($explorer_profile['nick_name']) . "\n";
            $text .= "📱 <b>شماره همراه:</b> <code>" . htmlspecialchars($explorer_profile['phone']) . "</code>\n";
            $text .= "🏙️ <b>شهر:</b> " . htmlspecialchars($explorer_profile['city']) . "\n\n";

            $text .= "🚗 <b>وسیله نقلیه انتخابی:</b> " . htmlspecialchars($this->getLabelVehicle($payment['vehicle'])) . "\n";
            $text .= "💳 <b>نوع پرداخت:</b> " . htmlspecialchars($paymentTexts[$payment['payment_ref_id']]) . "\n";
            $text .= "📌 <b>وضعیت پرداخت:</b> " . htmlspecialchars($statusTexts[$payment['payment_status']]) . "\n";



            // ۶. ساخت دکمه های مدیریتی (مسدود کردن، حذف و بازگشت)
            $keyboard = [
                "inline_keyboard" => [

                    [

                        ["text" => "🔙 بازگشت", "callback_data" => "tour_register_" . $tourId]
                    ]
                ]
            ];

            // ۷. ارسال پیام ویرایش شده با اطلاعات جدید
            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => $text,
                "parse_mode" => "HTML", // برای نمایش صحیح تگ های <b> و <code>
                "reply_markup" => json_encode($keyboard)
            ]);
        }



        if (strpos($callbackData, 'user_admin_details_') === 0) {

            $parts = explode('_', $callbackData); // [user, leader, details, explorerId, tourId]
            $explorerId = (int)$parts[3];
            $tourId = (int)$parts[4];
            $explorer_profile = $this->db->registeredExplorerByUserId($explorerId);
            $payment = $this->db->getPaymentDetailsByUserId($explorerId, $tourId);

            // ۳. بررسی یافت شدن کاربر و مدیریت خطا
            if (!$explorer_profile) {
                $this->sendRequest("answerCallbackQuery", [
                    "callback_query_id" => $this->callbackQueryId,
                    "text" => "❌ کاربر پیدا نشد.",
                    "show_alert" => true
                ]);
                return;
            }

            // ۴. دریافت نقش های کاربر از جدول `users` با استفاده از `chat_id`
            $user_roles = $this->db->getUserByUserId($explorer_profile['chat_id']);
            $statusTexts = [
                "pending"   => "در انتظار پرداخت",
                "completed" => "پرداخت شده",
                "failed"    => "پرداخت ناموفق"
            ];
            $paymentTexts = [
                "online_payment"   => "آنلاین",
                "card_to_card" => "کارت به کارت(تایید نشده)",
                "card_to_card_admin"    => "کارت به کارت"
            ];
            // ۵. ساخت متن پیام بر اساس نقش کاربر
            $text  = "👤 <b>اطلاعات کاربر</b>\n\n";
            $text .= "🧑‍💼 <b>نام و نام خانوادگی:</b> " . htmlspecialchars($explorer_profile['first_name'] . ' ' . $explorer_profile['last_name']) . "\n";
            $text .= "⭐ <b>نام مستعار:</b> " . htmlspecialchars($explorer_profile['nick_name']) . "\n";
            $text .= "📱 <b>شماره همراه:</b> <code>" . htmlspecialchars($explorer_profile['phone']) . "</code>\n";
            $text .= "🏙️ <b>شهر:</b> " . htmlspecialchars($explorer_profile['city']) . "\n\n";

            $text .= "🚗 <b>وسیله نقلیه:</b> " . htmlspecialchars($payment['vehicle']) . "\n";
            $text .= "💳 <b>نوع پرداخت:</b> " . htmlspecialchars($paymentTexts[$payment['payment_ref_id']]) . "\n";
            $text .= "📌 <b>وضعیت پرداخت:</b> " . htmlspecialchars($statusTexts[$payment['payment_status']]) . "\n";




            // ۶. ساخت دکمه های مدیریتی (مسدود کردن، حذف و بازگشت)
            $keyboard = [
                "inline_keyboard" => [

                    [

                        ["text" => "🔙 بازگشت", "callback_data" => "admin_tour_details_" . $tourId]
                    ]
                ]
            ];

            // ۷. ارسال پیام ویرایش شده با اطلاعات جدید
            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => $text,
                "parse_mode" => "HTML", // برای نمایش صحیح تگ های <b> و <code>
                "reply_markup" => json_encode($keyboard)
            ]);
        }


        if ($callbackData == 'bot_users') {
            $this->showAllUsers($chatId, $userLanguage, 1, $messageId);
        }
        if ($callbackData == 'user_manager') {
            $this->UserList($chatId, 'explorer');
        }
        if ($callbackData == 'leader_manager') {
            $this->UserList($chatId, 'leader');
        }

        if ($callbackData == 'leader_request') {
            $this->fileHandler->saveMessageId($this->chatId, $messageId);

            $text  = "🎉 خیلی خوشحالیم که می خوای به عنوان لیدر به ما بپیوندی! 🧭✨\n\n";
            $text .= "با <b>ثبت نام رایگان</b> در این ربات، تو هم به جمع بیش از 100 لیدر فعال در حوزه تور و طبیعت گردی اضافه می شی. 🧑‍🌾\n\n";
            $text .= "به عنوان لیدر، می تونی تورهای اختصاصی خودت رو بسازی، اون ها رو مدیریت کنی و با علاقه مندان به اشتراک بذاری. 🌍\n\n";
            $text .= "<b>🚀 قدم اول:</b> برای شروع فرآیند ثبت نام، لطفاً نام خودت رو وارد کن 👇";


            if ($this->fileHandler->saveState($chatId, 'awaiting_leader_firstname')) {

                $response = $this->sendRequest("editMessageText", [
                    "chat_id" => $chatId,
                    "message_id" => $messageId,
                    "parse_mode"   => "HTML",
                    "text" => $text, // استفاده از متن جدید
                    "reply_markup" => json_encode([
                        "inline_keyboard" => [
                            [
                                ["text" => "🔙 بازگشت", "callback_data" => "go_to_menu"]
                            ]
                        ]
                    ])
                ]);

                if (isset($response['result']['message_id'])) {
                    $this->fileHandler->saveMessageId($chatId, $response['result']['message_id']);
                }
            } else {
                error_log("❌ Failed to save state for chatId: $chatId");
                $this->sendRequest("sendMessage", [
                    "chat_id" => $chatId,
                    "text" => $userLanguage === 'fa' ? "خطا در پردازش. لطفاً دوباره سعی کنید." : "Processing error. Please try again.",
                    "reply_markup" => $this->getMainKeyboard()
                ]);
            }
        }


        if ($callbackData == 'leader_profile_menu') {
            $leader_info = $this->db->registeredExplorerByUserId($this->chatId);
            if ($leader_info) {
                $response = $this->sendRequest("editMessageText", [
                    "chat_id" => $chatId,
                    "message_id" => $messageId,
                    "text" =>
                    "<b>👤 مشخصات لیدر:</b>\n\n" .
                        "👨‍💼 <b>نام و نام خانوادگی:</b> " . $leader_info['first_name'] . " " . $leader_info['last_name'] . "\n" .
                        "🏷️ <b>نام مستعار:</b> " . $leader_info['nick_name'] . "\n" .
                        "🎂 <b>تاریخ تولد:</b> " . $this->gregorianToJalali($leader_info['date_of_birth']) . "\n" .
                        "📱  <b>شماره همراه:</b> " . $leader_info['phone'] . "\n" .
                        "🏙️ <b>شهر:</b> " . $leader_info['city'] . "\n" .
                        "📍  <b>آدرس:</b> " . $leader_info['address'] . "\n" .
                        "🔖 <b>کد ملی:</b> " . $leader_info['national_code'] . "\n" .
                        "📣 <b>آیدی کانال:</b> " . htmlspecialchars($leader_info['channel']) . "\n" .
                        "👥 <b>گروه:</b> " . htmlspecialchars($leader_info['group_link']) . "\n" .
                        "💳 <b>شماره کارت:</b><code> " . htmlspecialchars($leader_info['card_number']) . "</code>\n" .
                        "🏦 <b>شماره شبا:</b><code>" . htmlspecialchars($leader_info['sheba']) . "</code>",

                    "parse_mode" => "HTML",

                    "reply_markup" => json_encode([
                        "inline_keyboard" => [
                            [["text" => "✏️ ویرایش اطلاعات", "callback_data" => "edit_leader_menu"]],
                            [["text" => "🔙 بازگشت", "callback_data" => "leader_dashboard"]]
                        ]
                    ])
                ]);
            } else {

                $this->sendRequest("sendMessage", [
                    "chat_id" => $chatId,
                    "text" => "کاربری با این شناسه پیدا نشد.",
                    "reply_markup" => json_encode([

                        "inline_keyboard" => [
                            [
                                ["text" => "🔙 بازگشت", "callback_data" => "leader_dashboard"],

                            ]
                        ]
                    ])
                ]);
            }
        }
        if ($callbackData == 'edit_leader_menu') {
            $this->showLeaderEditMenu($chatId, $messageId);
        } elseif (str_starts_with($callbackData, 'edit_leader_')) {
            $fieldKey = str_replace('edit_leader_', '', $callbackData);
            $this->askForLeaderFieldUpdate($chatId, $messageId, $fieldKey);
        } elseif (str_starts_with($callbackData, "confirm_leader_")) {
            $parts = explode("_", $callbackData);
            $userId = $parts[2];
            $temp = $this->fileHandler->getLeaderData($userId);
            $registration = $this->db->registeredExplorerByUserId($userId);

            $this->db->setLeaderStatus($userId, true);
            $this->db->updateLeaderConfirm($userId);
            $this->sendRequest("editMessageReplyMarkup", [
                "chat_id" => $this->chatId,
                "message_id" => $callbackQuery['message']['message_id'],
                "reply_markup" => json_encode(['inline_keyboard' => []])
            ]);
            $this->sendRequest("sendMessage", [
                "chat_id" => $userId,
                "text" => "✅ اطلاعات شما تایید شد. .\nبزن بریم🚀",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [["text" => "🏠 منو", "callback_data" => "go_to_menu"]]
                    ]
                ])
            ]);

            $this->sendRequest("sendMessage", [
                "chat_id" => $this->chatId,
                "reply_to_message_id" => $messageId,
                "text" => " اطلاعات لیدر تأیید شد.",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [["text" => "🏠 منو", "callback_data" => "go_to_menu"]]
                    ]
                ])
            ]);
        } elseif (str_starts_with($callbackData, "reject_leader_")) {
            $parts = explode("_", $callbackData);
            $userId = $parts[2];
            $this->db->setLeaderStatus($chatId, false);


            $this->sendRequest("sendMessage", [
                "chat_id" => $userId,
                "text" => "❌ متاسفانه درخواست لیدری شما توسط ادمین رد شد.\nاگر اشتباهی پیش اومده لطفاً دوباره تلاش کن یا با پشتیبانی در ارتباط باش."
            ]);

            $this->sendRequest("sendMessage", [
                "chat_id" => $this->chatId,
                "reply_to_message_id" => $messageId,
                "text" => " درخواست لیدر رد شد.",
            ]);
        }


        if ($callbackData == 'payments_menu') {
            $userLanguage = 'fa';
            $this->showAdminPaymentTours($chatId, $messageId, $userLanguage);
        }
        if (strpos($callbackData, 'online_payments_') === 0) {
            $tourId = (int) str_replace('online_payments_', '', $callbackData);
            $userLanguage = 'fa';
            $this->showOnlinePayments($chatId, $tourId, $this->callbackQueryId, $userLanguage);
        }
        if (strpos($callbackData, 'manual_payments_') === 0) {
            $tourId = (int)str_replace('manual_payments_', '', $callbackData);
            $userLanguage = 'fa';
            $this->showCardToCardPayments($chatId, $tourId, $this->callbackQueryId, $userLanguage);
        }
        if ($callbackData == 'leader_users') {
            $this->RegisteredTourUsers($chatId, $userLanguage);
        }
        if (strpos($callbackData, "tour_payments_") === 0) {
            $tourId = (int) str_replace("tour_payments_", "", $callbackData);
            $this->showTourPayments($chatId, $tourId, $userLanguage, $messageId);
        }

        $tourListCallbacks = [
            'tours_menu' => 'showAllTours',
            'leader_tours_menu' => 'showToursList',
            'active_tours' => 'showActiveToursList'
        ];

        foreach ($tourListCallbacks as $baseCallback => $methodToCall) {

            if (str_starts_with($callbackData, $baseCallback)) {
                $page = 1;

                if (str_contains($callbackData, '_page_')) {
                    $pageParts = explode('_page_', $callbackData);
                    $page = (int) end($pageParts);
                }

                $this->$methodToCall($chatId, $userLanguage, max(1, $page), $messageId);
                return; // اجرای هندلر متوقف می شود
            }
        }
        if ($callbackData == 'leader_payments_menu') {
            $this->showLeaderPayments($chatId, $userLanguage, $messageId);
        } elseif (strpos($callbackData, 'tour_details_') === 0) {

            $tourId = (int) str_replace('tour_details_', '', $callbackData);
            $tour = $this->db->getTourById($tourId);

            if (!$tour) {
                $this->sendRequest("answerCallbackQuery", [
                    "callback_query_id" => $this->callbackQueryId,
                    "text" => "❌ تور پیدا نشد.",
                    "show_alert" => true
                ]);
                return;
            }
            $registeredCount = $this->db->checkCapacityTour($tourId);
            $totalCapacity = $tour['capacity'] ?? 0;
            $remainingCapacity = $totalCapacity - $registeredCount;

            $summaryText = "id:" . $tour['id'] . "\n" . $this->generateTourDetailsText($tourId);

            $summaryText .= "\n"
                . "▫️ <b>ثبت‌نام شده:</b> " . $registeredCount . " نفر\n"
                . "▫️ <b>ظرفیت باقی‌مانده:</b> " . $remainingCapacity . " نفر";


            $leaderKeyboard = [
                "inline_keyboard" => [
                    [
                        ["text" => "✏️ ویرایش تور", "callback_data" => "edit_tour_" . $tourId],
                        ["text" => "🗑 حذف تور", "callback_data" => "delete_tour_" . $tourId]
                    ],
                    [
                        ["text" => "📤 درج لیست کاربران در گروه", "callback_data" => "list_group_" . $tourId],

                        ["text" => "📤 درج لیست کاربران در کانال", "callback_data" => "list_channel_" . $tourId]
                    ],
                    [
                        ["text" => "📢 درج تور در کانال", "callback_data" => "post_channel_" . $tourId],
                        ["text" => "📨 درج تور در گروه", "callback_data" => "post_group_" . $tourId]
                    ],
                    [
                        ["text" => "📢 ارسال پیام همگانی", "callback_data" => "broadcast_tour_" . $tourId]
                    ],
                    [
                        ["text" => "👥 لیست ثبت نامی ها", "callback_data" => "tour_register_" . $tourId],
                        ["text" => "❌ اتمام ظرفیت تور ", "callback_data" => "tour_complete_" . $tourId]
                    ],
                    [

                        ["text" => "🔙 بازگشت به لیست تورها", "callback_data" => "leader_tours_menu"]

                    ]

                ]
            ];

            if (!empty($tour['banner']) && mb_strlen($summaryText, 'UTF-8') <= 1024) {

                $this->deleteMessageWithDelay();
                $this->sendRequest("sendPhoto", [
                    "chat_id" => $chatId,
                    "photo" => $tour['banner'],
                    "caption" => $summaryText,
                    "parse_mode" => "HTML",
                    "reply_markup" => $leaderKeyboard
                ]);
            } else {

                $this->sendRequest("editMessageText", [
                    "chat_id" => $chatId,
                    "message_id" => $messageId,
                    "text" => $summaryText,
                    "parse_mode" => "HTML",
                    "reply_markup" => $leaderKeyboard
                ]);
            }
        } else if (strpos($callbackData, 'delete_tour_') === 0) {
            $tourId = (int) str_replace('delete_tour_', '', $callbackData);
            $tour = $this->db->getTourById($tourId);
            $tourTitle = $tour ? $tour['title'] : "این تور";
            $confirmationText = "⚠️ آیا از حذف تور «" . htmlspecialchars($tourTitle) . "» مطمئن هستید؟\nاین عمل غیرقابل بازگشت است.";
            $confirmationKeyboard = [
                "inline_keyboard" => [
                    [
                        ["text" => "✅ بله، حذف کن", "callback_data" => "confirm_delete_tour_" . $tourId],
                        ["text" => "❌ خیر، بازگشت", "callback_data" => "tour_details_" . $tourId]
                    ],
                ]
            ];

            if ($messageId && !isset($callbackQuery["message"]["photo"])) {
                $this->sendRequest("editMessageText", [
                    "chat_id" => $chatId,
                    "message_id" => $messageId,
                    "text" => $confirmationText,
                    "parse_mode" => "HTML",
                    "reply_markup" => $confirmationKeyboard
                ]);
            } else {
                // --- حالت ۲: اگر پیام قبلی عکس دار بود ---
                $this->sendRequest("editMessageCaption", [
                    "chat_id" => $chatId,
                    "message_id" => $messageId,
                    "caption" => $confirmationText,
                    "parse_mode" => "HTML",
                    "reply_markup" => $confirmationKeyboard
                ]);
            }
        } else if (strpos($callbackData, 'confirm_delete_tour_') === 0) {
            $tourId = (int) str_replace('confirm_delete_tour_', '', $callbackData);
            $success = $this->db->deleteTourById($tourId);
            $this->sendRequest("answerCallbackQuery", [
                "callback_query_id" => $this->callbackQueryId,
                "text" => $success ? "✅ تور با موفقیت حذف شد." : "❌ خطا در حذف تور.",
                "show_alert" => true
            ]);

            if ($success) {
                $this->showToursList($chatId, $userLanguage, 1, $messageId);
            }
        } else if (strpos($callbackData, 'admin_delete_tour_') === 0) {
            $tourId = (int) str_replace('admin_delete_tour_', '', $callbackData);
            $tour = $this->db->getTourById($tourId);

            $registeredUsers = $this->db->getRegisteredUsersByTourId($tourId);

            if (!empty($registeredUsers)) {
                $this->sendRequest("answerCallbackQuery", [
                    "callback_query_id" => $this->callbackQueryId,
                    "text" => "❌ امکان حذف این تور وجود ندارد زیرا " . count($registeredUsers) . " کاربر در آن ثبت‌نام کرده‌اند.",
                    "show_alert" => true
                ]);
                return;
            }

            $tourTitle = $tour ? $tour['title'] : "این تور";
            $confirmationText = "⚠️ آیا از حذف تور «" . htmlspecialchars($tourTitle) . "» مطمئن هستید؟\nاین عمل غیرقابل بازگشت است.";
            $confirmationKeyboard = [
                "inline_keyboard" => [
                    [
                        ["text" => "✅ بله، حذف کن", "callback_data" => "admin_confirm_delete_tour_" . $tourId],
                        ["text" => "❌ خیر، بازگشت", "callback_data" => "admin_tour_details_" . $tourId]
                    ],
                ]
            ];

            if ($messageId && !isset($callbackQuery["message"]["photo"])) {
                $this->sendRequest("editMessageText", [
                    "chat_id" => $chatId,
                    "message_id" => $messageId,
                    "text" => $confirmationText,
                    "parse_mode" => "HTML",
                    "reply_markup" => $confirmationKeyboard
                ]);
            } else {
                // --- حالت ۲: اگر پیام قبلی عکس دار بود ---
                $this->sendRequest("editMessageCaption", [
                    "chat_id" => $chatId,
                    "message_id" => $messageId,
                    "caption" => $confirmationText,
                    "parse_mode" => "HTML",
                    "reply_markup" => $confirmationKeyboard
                ]);
            }
        } else if (strpos($callbackData, 'admin_confirm_delete_tour_') === 0) {
            $tourId = (int) str_replace('admin_confirm_delete_tour_', '', $callbackData);
            $success = $this->db->deleteTourById($tourId);
            $this->sendRequest("answerCallbackQuery", [
                "callback_query_id" => $this->callbackQueryId,
                "text" => $success ? "✅ تور با موفقیت حذف شد." : "❌ خطا در حذف تور.",
                "show_alert" => true
            ]);

            if ($success) {
                $this->showAllTours($chatId, $userLanguage, 1, $messageId);
            }
        } elseif (strpos($callbackData, needle: 'active_tour_details_') === 0) {
            $tourId = (int) str_replace('active_tour_details_', '', $callbackData);
            $tour = $this->db->getTourById($tourId);

            if (!$tour) {
                $this->sendRequest("answerCallbackQuery", [
                    "callback_query_id" => $this->callbackQueryId,
                    "text" => "❌ تور پیدا نشد.",
                    "show_alert" => true
                ]);
                return;
            }

            $registeredCount = $this->db->checkCapacityTour($tourId);
            $totalCapacity = $tour['capacity'] ?? 0;
            $remainingCapacity = $totalCapacity - $registeredCount;

            $summaryText = $this->generateTourDetailsText($tourId);

            $summaryText .= "\n"
                . "▫️ <b>ثبت‌نام شده:</b> " . $registeredCount . " نفر\n"
                . "▫️ <b>ظرفیت باقی‌مانده:</b> " . $remainingCapacity . " نفر";

            $leaderChatId = $tour['leader_id'] ?? null;
            $keyboardButtons = [];

            $keyboardButtons[] = [['text' => "✅ ثبت نام در تور", 'callback_data' => "register_active_{$tourId}"]];

            if (!empty($leaderChatId)) {
                $keyboardButtons[] = [['text' => "💬  چت با لیدر ", 'url' => "tg://user?id={$leaderChatId}"]];
            }

            $keyboardButtons[] = [['text' => "🔙 بازگشت به لیست تورها", 'callback_data' => "active_tours_page_1"]];

            $keyboard = ['inline_keyboard' => $keyboardButtons];


            if (!empty($tour['banner']) && mb_strlen($summaryText, 'UTF-8') <= 1024) {
                $this->deleteMessageWithDelay();
                $this->sendRequest("sendPhoto", [
                    "chat_id" => $chatId,
                    "photo" => $tour['banner'],
                    "caption" => $summaryText,
                    "parse_mode" => "HTML",
                    "reply_markup" => $keyboard
                ]);
            } else {
                $this->sendRequest("editMessageText", [
                    "chat_id" => $chatId,
                    "message_id" => $messageId,
                    "text" => $summaryText,
                    "parse_mode" => "HTML",
                    "reply_markup" => $keyboard
                ]);
            }
        }



        if (strpos($callbackData, 'admin_tour_details_') === 0) {
            $tourId = (int) str_replace('admin_tour_details_', '', $callbackData);
            $tour = $this->db->getTourById($tourId);
            $this->fileHandler->saveTourId($this->chatId, $tourId);
            if (!$tour) {
                $this->sendRequest("answerCallbackQuery", [
                    "callback_query_id" => $this->callbackQueryId,
                    "text" => "❌ تور پیدا نشد.",
                    "show_alert" => true
                ]);
                return;
            }

            $registeredCount = $this->db->checkCapacityTour($tourId);
            $totalCapacity = $tour['capacity'] ?? 0;
            $remainingCapacity = $totalCapacity - $registeredCount;

            $summaryText = $this->generateTourDetailsText($tourId);

            $summaryText .= "\n"
                . "▫️ <b>ثبت‌نام شده:</b> " . $registeredCount . " نفر\n"
                . "▫️ <b>ظرفیت باقی‌مانده:</b> " . $remainingCapacity . " نفر";


            $this->sendRequest("editMessageText", [
                "chat_id" => $this->chatId,
                "message_id" => $messageId,
                "text" => $summaryText,
                "parse_mode" => "HTML",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [

                        [
                            [
                                "text" => "✏️ ویرایش تور",
                                "callback_data" => "edit_tour_{$tourId}"
                            ],
                            [
                                "text" => "🗑 حذف تور",
                                "callback_data" => "admin_delete_tour_{$tourId}"
                            ]
                        ],

                        [
                            [
                                "text" => "🧑‍🌾 ثبت نامی ها",
                                "callback_data" => "show_registered_users_{$tourId}"
                            ]
                        ],
                        [

                            [
                                "text" => "🔙 بازگشت",
                                "callback_data" => "go_to_menu"
                            ]
                        ]
                    ]
                ])
            ]);
        }

        if (strpos($callbackData, 'show_registered_users_') === 0) {
            $tourId = (int) str_replace('show_registered_users_', '', $callbackData);
            $users = $this->db->getRegisteredUsersByTourId($tourId);
            if (empty($users)) {
                $this->sendRequest("answerCallbackQuery", [
                    "callback_query_id" => $this->callbackQueryId,
                    "text" => "هیچ کاربری در این تور ثبت نام نکرده است.",
                    "show_alert" => true // این گزینه باعث نمایش popup می شود
                ]);
                return;
            }


            $text = "🎉 <b>لیست کاربران ثبت نام شده در این تور</b>\n\n";

            $keyboard = [];
            foreach ($users as $index => $user) {
                $userInfo = $this->db->registeredExplorerByUserId($user['explorer_id']);
                $usersList = ($index + 1) . ". " . $userInfo['first_name'] . " " . $userInfo['last_name'] . " (" . $userInfo['phone'] . ")\n"; // فرض بر اینکه `name` و `phone` در جدول user هست
                $keyboard[] = [
                    [
                        "text" => $usersList,
                        "callback_data" => "user_admin_details_" . $userInfo['chat_id'] . "_" . $tourId
                    ]
                ];
            }
            $keyboard[] = [['text' => '🔙 بازگشت ', 'callback_data' => "go_to_menu"]];

            $this->sendRequest("sendMessage", [
                "chat_id" => $chatId,
                //            "message_id"=>$this->messageId,
                "text" => $text,
                "parse_mode" => "HTML",
                "reply_markup" => [
                    "inline_keyboard" => $keyboard
                ]
            ]);
        }


        if (strpos($callbackData, 'admin_payment_tour_details_') === 0) {
            $tourId = (int) str_replace('admin_payment_tour_details_', '', $callbackData);
            $tour = $this->db->getTourById($tourId);
            $this->fileHandler->saveTourId($this->chatId, $tourId);

            if (!$tour) {
                $this->sendRequest("answerCallbackQuery", [
                    "callback_query_id" => $this->callbackQueryId,
                    "text" => "❌ تور پیدا نشد.",
                    "show_alert" => true
                ]);
                return;
            }
            $summaryText = " ";
            if (!empty($tour['pricing'])) {
                $pricingData = $tour['pricing']; // Already an array from Database class
                if (is_array($pricingData) && !empty($pricingData)) {
                    $summaryText .= "💰 <b>هزینه تور:</b>\n";
                    foreach ($pricingData as $priceInfo) {
                        if (is_array($priceInfo)) $summaryText .= "- " . htmlspecialchars($priceInfo['label']) . ": <b>" . number_format($priceInfo['amount']) . "</b> تومان\n";
                    }
                    $summaryText .= "\n";
                }
            }

            $this->sendRequest("editMessageText", [
                "chat_id" => $this->chatId,
                "message_id" => $messageId,
                "text" =>
                "<b>📌 عنوان تور:</b> {$tour['title']}\n\n" . $summaryText,
                "parse_mode" => "HTML",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [

                        [
                            [
                                "text" => "💳 پرداخت های آنلاین",
                                "callback_data" => "online_payments_" . $tour['id']
                            ],
                            [
                                "text" => "🏦 پرداخت های کارت به کارت",
                                "callback_data" => "manual_payments_" . $tour['id']
                            ]
                        ],
                        [['text' => '🔙 بازگشت ', 'callback_data' => "admin_payment_tours_page_1"]]

                    ]
                ])
            ]);
        }
        if (str_starts_with($callbackData, "admin_payment_tours_page_")) {
            $page = (int) str_replace("admin_payment_tours_page_", "", $callbackData);
            $language = $this->db->getUserLanguage($this->chatId);
            $this->showAdminPaymentTours($this->chatId, $messageId, $language, $page);
        }


        if ($callbackData == 'registered_user_tours') {
            $userLanguage = 'fa';
            $this->showRegisteredToursList($chatId, $userLanguage, $messageId);
        }
        if (strpos($callbackData, 'registered_tour_details_') === 0) {
            $tourId = (int) str_replace('registered_tour_details_', '', $callbackData);
            $tour = $this->db->getTourById($tourId);
            $this->fileHandler->saveTourId($this->chatId, $tourId);
            $count_capacity = $this->db->checkCapacityTour($tourId);

            if (!$tour) {
                $this->sendRequest("answerCallbackQuery", [
                    "callback_query_id" => $this->callbackQueryId,
                    "text" => "❌ تور پیدا نشد.",
                    "show_alert" => true
                ]);
                return;
            }

            $keyboard = [[["text" => "🔙 بازگشت", "callback_data" => "registered_user_tours"]]];
            $message = " ";

            $summaryText = $this->generateTourDetailsText($tourId);

            $vehicleButtons = [];
            $row = [];

            if (!$this->db->isUserPayedComplete($chatId, $tourId)) {
                $message = "لطفا جهت ادامه ثبت نام وسیله نقلیه مورد نظر خود را انتخاب کنید:";
                $pricingData = $tour['pricing'];
                foreach ($pricingData as $vehicle => $priceInfo) {
                    $row[] = ["text" => $priceInfo['label'], "callback_data" => "select_vehicle_{$vehicle}_{$tourId}"];
                    if (count($row) === 2) {
                        $vehicleButtons[] = $row;
                        $row = [];
                    }
                }
                if (!empty($row)) {
                    $vehicleButtons[] = $row;
                }
            } else {
                $message = "شما قبلا مبلغ تور را پرداخت کرده اید.";
                $vehicleButtons[] = [["text" => "🔙 بازگشت", "callback_data" => "registered_user_tours"]];
            }
            $vehicleButtons[] = [["text" => " ❌انصراف ", "callback_data" => "go_to_menu"]];

            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,

                "text" => $summaryText . "\n" . $message, // استفاده از متن فرمت شده جدید
                "parse_mode" => "HTML", // برای نمایش صحیح تگ های <b> و <i>

                "reply_markup" => json_encode([
                    "inline_keyboard" => $vehicleButtons
                ])

            ]);
        }
        if ($callbackData == 'user_pays') {
            $userLanguage = 'fa';
            $this->showUserPayments($this->chatId, $userLanguage, $messageId);
        } else if (strpos($callbackData, 'pay_details_') === 0) {
            $payId = (int) str_replace('pay_details_', '', $callbackData);
            $payment = $this->db->getPayDetailsById($payId);
            $user = $this->db->registeredExplorerByUserId($payment['chat_id']);
            $tour = $this->db->getTourById($payment['tour_id']);
            $status = array("pending" => 'در انتظار پرداخت', "completed" => 'پرداخت شده', "failed" => 'پرداخت ناموفق');
            $summaryText = " ";
            if (!empty($tour['pricing'])) {
                $pricingData = $tour['pricing']; // Already an array from Database class
                if (is_array($pricingData) && !empty($pricingData)) {
                    $summaryText .= "💰 <b>هزینه تور:</b>\n";
                    foreach ($pricingData as $priceInfo) {
                        if (is_array($priceInfo)) $summaryText .= "- " . htmlspecialchars($priceInfo['label']) . ": <b>" . number_format($priceInfo['amount']) . "</b> تومان\n";
                    }
                    $summaryText .= "\n";
                }
            }
            if (!$payment) {
                $this->sendRequest("answerCallbackQuery", [
                    "callback_query_id" => $this->callbackQueryId,
                    "text" => "❌ اطلاعات پرداخت یافت نشد.",
                    "show_alert" => true
                ]);
                return;
            }

            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" =>
                "<b>📄 اطلاعات پرداخت</b>\n\n" .
                    "👤 <b>پرداخت کننده:</b> {$user['first_name']} {$user['last_name']}\n" .
                    "🧭 <b>عنوان تور:</b> {$tour['title']}\n" .
                    $summaryText .
                    "💵 <b>مبلغ پرداختی:</b> " . number_format($payment['amount']) . " تومان\n" .
                    "📅 <b>تاریخ پرداخت:</b> {$payment['created_at']}\n" .
                    "🧾 <b>شماره مرجع:</b> {$payment['ref_id']}\n" .
                    "✅ <b>وضعیت پرداخت:</b> " . $status[$payment['payment_status']] . "\n",
                "parse_mode" => "HTML",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [
                            ["text" => "🔙 بازگشت ", "callback_data" => "user_pays"]
                        ]
                    ]
                ])
            ]);
        } else if (strpos($callbackData, 'payment_details_') === 0) {
            $payId = (int) str_replace('payment_details_', '', $callbackData);

            $payment = $this->db->getPaymentDetailsById($payId);
            if (!$payment) {
                $this->sendRequest("answerCallbackQuery", [
                    "callback_query_id" => $this->callbackQueryId,
                    "text" => "❌ اطلاعات پرداخت یافت نشد.",
                    "show_alert" => true
                ]);
                return;
            }

            $user = $this->db->registeredExplorerByUserId($payment['explorer_id']);
            $tour = $this->db->getTourById($payment['tour_id']);

            $statusTexts = [
                "pending"   => "در انتظار پرداخت",
                "completed" => "پرداخت شده",
                "failed"    => "پرداخت ناموفق"
            ];

            $statusText = $statusTexts[$payment['payment_status']] ?? "نامشخص";
            $fullName = trim(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? ''));
            $tourTitle = $tour['title'] ?? "عنوان نامشخص";
            $price = number_format($tour['price'] ?? 0);

            $createdAt = $payment['created_at'] ?? '---';

            $paymentTypeText = '';

            switch ($payment['payment_ref_id']) {
                case 'online_payment':
                    $onlinePay = $this->db->getOnlinePayment($user['chat_id'], $tour['id']);
                    $amount = number_format($onlinePay['amount'] ?? 0);
                    $created = $onlinePay['created_at'] ?? '---';
                    $refId = $onlinePay['ref_id'] ?? '---';
                    $paymentTypeText =
                        "💵 <b>مبلغ پرداختی:</b> {$amount} تومان\n" .
                        "📅 <b>تاریخ پرداخت:</b> {$created}\n" .
                        "🧾 <b>شماره مرجع:</b> {$refId}\n";
                    break;

                case 'card_to_card':
                case 'card_to_card_admin':
                    $paymentTypeText =
                        "✅ <b>نوع پرداخت:</b> کارت به کارت\n";
                    break;
            }
            $summaryText = " ";
            if (!empty($tour['pricing'])) {
                $pricingData = $tour['pricing']; // Already an array from Database class
                if (is_array($pricingData) && !empty($pricingData)) {
                    $summaryText .= "💰 <b>هزینه تور:</b>\n";
                    foreach ($pricingData as $priceInfo) {
                        if (is_array($priceInfo)) $summaryText .= "- " . htmlspecialchars($priceInfo['label']) . ": <b>" . number_format($priceInfo['amount']) . "</b> تومان\n";
                    }
                    $summaryText .= "\n";
                }
            }

            $text = "<b>📄 اطلاعات پرداخت</b>\n\n" .
                "👤 <b>پرداخت کننده:</b> {$fullName}\n" .
                "🧭 <b>عنوان تور:</b> {$tourTitle}\n" .
                $summaryText .
                $paymentTypeText .
                "✅ <b>وضعیت پرداخت:</b> {$statusText}";

            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => $text,
                "parse_mode" => "HTML",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [
                            ["text" =>  "🔙 بازگشت ", "callback_data" => "manual_payments_" . $payment['tour_id']]
                        ]
                    ]
                ])
            ]);
        } else if (strpos($callbackData, 'payment_leader_details_') === 0) {
            $payId = (int) str_replace('payment_leader_details_', '', $callbackData);

            $payment = $this->db->getPaymentDetailsById($payId);
            if (!$payment) {
                $this->sendRequest("answerCallbackQuery", [
                    "callback_query_id" => $this->callbackQueryId,
                    "text" => "❌ اطلاعات پرداخت یافت نشد.",
                    "show_alert" => true
                ]);
                return;
            }

            $user = $this->db->registeredExplorerByUserId($payment['explorer_id']);
            $tour = $this->db->getTourById($payment['tour_id']);

            $statusTexts = [
                "pending"   => "در انتظار پرداخت",
                "completed" => "پرداخت شده",
                "failed"    => "پرداخت ناموفق"
            ];

            $statusText = $statusTexts[$payment['payment_status']] ?? "نامشخص";
            $fullName = trim(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? ''));
            $tourTitle = $tour['title'] ?? "عنوان نامشخص";
            $price = number_format($tour['price'] ?? 0);

            $createdAt = $payment['created_at'] ?? '---';

            $paymentTypeText = '';

            switch ($payment['payment_ref_id']) {
                case 'online_payment':
                    $onlinePay = $this->db->getOnlinePayment($user['chat_id'], $tour['id']);
                    $amount = number_format($onlinePay['amount'] ?? 0);
                    $created = $onlinePay['created_at'] ?? '---';
                    $refId = $onlinePay['ref_id'] ?? '---';
                    $paymentTypeText =
                        "💵 <b>مبلغ پرداختی:</b> {$amount} تومان\n" .
                        "📅 <b>تاریخ پرداخت:</b> {$created}\n" .
                        "🧾 <b>شماره مرجع:</b> {$refId}\n";
                    break;

                case 'card_to_card':
                case 'card_to_card_admin':
                    $paymentTypeText =
                        "✅ <b>نوع پرداخت:</b> کارت به کارت\n";
                    break;
            }
            $summaryText = " ";
            if (!empty($tour['pricing'])) {
                $pricingData = $tour['pricing']; // Already an array from Database class
                if (is_array($pricingData) && !empty($pricingData)) {
                    $summaryText .= "💰 <b>هزینه تور:</b>\n";
                    foreach ($pricingData as $priceInfo) {
                        if (is_array($priceInfo)) $summaryText .= "- " . htmlspecialchars($priceInfo['label']) . ": <b>" . number_format($priceInfo['amount']) . "</b> تومان\n";
                    }
                    $summaryText .= "\n";
                }
            }

            $text = "<b>📄 اطلاعات پرداخت</b>\n\n" .
                "👤 <b>پرداخت کننده:</b> {$fullName}\n" .
                "🧭 <b>عنوان تور:</b> {$tourTitle}\n" .
                $summaryText .
                $paymentTypeText .
                "✅ <b>وضعیت پرداخت:</b> {$statusText}";

            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => $text,
                "parse_mode" => "HTML",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [
                            ["text" =>  "🔙 بازگشت ", "callback_data" => "tour_payments_" . $payment['tour_id']]
                        ]
                    ]
                ])
            ]);
        }

        if ($callbackData == 'register') {
            $this->fileHandler->saveMessageId($this->chatId, $messageId);
            if ($this->fileHandler->saveState($chatId, 'awaiting_user_firstname')) {
                $text  = "🌿 <b>به جمع طبیعت گردها خوش اومدی!</b> 🌿\n\n";
                $text .= "برای اینکه <b>سریع تر</b> بتونی توی تورها ثبت نام کنی و به <b>پروفایل اختصاصیت</b> دسترسی داشته باشی، ";
                $text .= "کافیه فقط یک بار اطلاعاتت رو وارد کنی. 📝\n\n";
                $text .= "✨ <b>قدم اول:</b>\n";
                $text .= "لطفاً <b>نام</b> خودت رو وارد کن 👇";


                $response = $this->sendRequest("editMessageText", [
                    "chat_id" => $chatId,
                    "message_id" => $messageId,
                    "text" => $text,
                    "parse_mode" => "HTML",
                    "reply_markup" => json_encode(["inline_keyboard" => [
                        [
                            ["text" => "🔙 بازگشت", "callback_data" => "go_to_menu"],
                        ]
                    ]])
                ]);
                if (isset($response['result']['message_id'])) {
                    $this->fileHandler->saveMessageId($chatId, $response['result']['message_id']);
                }
            } else {
                error_log("❌ Failed to save state for chatId: $chatId");
                $this->sendRequest("sendMessage", [
                    "chat_id" => $chatId,
                    "text" => $userLanguage === 'fa' ? "خطا در پردازش. لطفاً دوباره سعی کنید." : "Processing error. Please try again.",
                    "reply_markup" =>  $this->getMainKeyboard()
                ]);
            }
        }

        if ($callbackData == 'go_to_menu') {
            $this->fileHandler->clearUserData($chatId);

            $text  = "<i><b>سلام دوست طبیعت گرد!</b></i> 🪷\n";
            $text .= "به ربات <b>طبیعت گرد</b> خوش اومدی 🏕️✨\n\n";
            $text .= "<blockquote>اینجا می تونی تورهای هیجان انگیز رو ببینی، ثبت نام کنی و برای ماجراجویی بعدی آماده بشی! 🏝🏜</blockquote>\n\n";
            $text .= "<b>لیدر:</b> کسیه که مسئولیت برگزاری و راهنمایی تورها رو به عهده داره. 🧭\n";
            $text .= "<b>طبیعت گرد:</b> کسیه که برای لذت بردن از سفر و کشف زیبایی های طبیعت همراه گروه میاد. 🌿\n\n";
            $text .= "از گزینه های زیر استفاده کن 👇:";

            if ($messageId) {

                $this->sendRequest("editMessageText", [
                    "chat_id" => $chatId,
                    "message_id" => $messageId,
                    "text" => $text,

                    "parse_mode" => "HTML",
                    "reply_markup" =>  $this->getMainKeyboard()
                ]);
            } else {
                $this->deleteMessageWithDelay();
                $this->sendRequest("sendMessage", [
                    "chat_id" => $chatId,
                    "text" => $text,
                    "parse_mode" => "HTML",
                    "reply_markup" =>  $this->getMainKeyboard()
                ]);
            }
        }

        if ($callbackData == 'choice_telegram_name') {
            $telegramName = $this->db->getUserFullName($this->chatId);
            $first_name = $this->fileHandler->getFirstName($this->chatId);
            $last_name = $this->fileHandler->getLastName($this->chatId);
            $this->fileHandler->setNickname($this->chatId, $telegramName);
            $nick_name = $this->fileHandler->getNickName($this->chatId);

            $messageId = $this->fileHandler->getMessageId($this->chatId);  // حتما messageId رو از فایل بگیر

            if ($this->fileHandler->saveState($chatId, 'awaiting_user_birthdate')) {

                $this->deleteMessageWithDelay();

                $datePicker = new \Bot\DatePicker();
                $birthPicker = $datePicker->generate(1375, 1, 1, 'birthdate', "اطلاعات شما تا این لحظه:\n" .
                    "👤 نام: {$first_name}\n" .
                    "📝 نام خانوادگی: {$last_name}\n" .
                    "⭐ نام مستعار: {$nick_name}\n\n" .
                    "🎂 لطفاً تاریخ تولد خود را انتخاب کنید:");

                $response = $this->sendRequest("sendMessage", [
                    "chat_id" => $chatId,
                    //                    "message_id" => $messageId,
                    "text" => $birthPicker['text'],
                    "parse_mode" => "HTML",
                    "reply_markup" => $birthPicker['reply_markup']
                ]);

                if (is_array($response) && isset($response['result']['message_id'])) {
                    $this->fileHandler->saveMessageId($chatId, $response['result']['message_id']);
                } else {
                    error_log("❌ ارسال پیام یا دریافت message_id با مشکل مواجه شد. پاسخ: " . var_export($response, true));
                }
            } else {
                error_log("❌ Failed to save state for chatId: $chatId");
                $this->sendRequest("sendMessage", [
                    "chat_id" => $chatId,
                    "text" => $userLanguage === 'fa' ? "خطا در پردازش. لطفاً دوباره سعی کنید." : "Processing error. Please try again.",
                    "reply_markup" =>  $this->getMainKeyboard()
                ]);
            }
        }


        if ($callbackData == 'choice_explorer_name') {
            $user_fullname = $this->fileHandler->getUserName($this->chatId);
            $first_name = $this->fileHandler->getFirstName($this->chatId);
            $last_name = $this->fileHandler->getLastName($this->chatId);
            $this->fileHandler->setNickname($this->chatId, $user_fullname);
            $nick_name = $this->fileHandler->getNickName($this->chatId);
            $messageId = $this->fileHandler->getMessageId($this->chatId);

            if ($this->fileHandler->saveState($chatId, 'awaiting_user_birthdate')) {
                $this->deleteMessageWithDelay();
                $datePicker = new DatePicker();
                $birthPicker = $datePicker->generate(1375, 1, 1, 'birthdate', "اطلاعات شما تا این لحظه:\n" .
                    "👤 نام: {$first_name}\n" .
                    "📝 نام خانوادگی: {$last_name}\n" .
                    "⭐ نام مستعار: {$nick_name}\n\n" .
                    "🎂 لطفاً تاریخ تولد خود را انتخاب کنید:");

                $response = $this->sendRequest("sendMessage", [
                    "chat_id" => $chatId,
                    // "message_id" => $messageId,
                    "text" => $birthPicker['text'],
                    "parse_mode" => "HTML",
                    "reply_markup" => $birthPicker['reply_markup']
                ]);
                if (is_array($response) && isset($response['result']['message_id'])) {
                    $this->fileHandler->saveMessageId($chatId, $response['result']['message_id']);
                } else {
                    error_log("❌ ارسال پیام یا دریافت message_id با مشکل مواجه شد. پاسخ: " . var_export($response, true));
                }
            } else {
                error_log("❌ Failed to save state for chatId: $chatId");
                $this->sendRequest("sendMessage", [
                    "chat_id" => $chatId,
                    "text" => $userLanguage === 'fa' ? "خطا در پردازش. لطفاً دوباره سعی کنید." : "Processing error. Please try again.",
                    "reply_markup" =>  $this->getMainKeyboard()
                ]);
            }
        }


        //Leader choice nickname//
        if ($callbackData == 'choice_leader_telegram_name') {

            $telegramName = $this->db->getUserFullName($this->chatId);
            $first_name = $this->fileHandler->getLeaderFirstName($this->chatId);
            $last_name = $this->fileHandler->getLeaderLastName($this->chatId);
            $this->fileHandler->setLeaderNickname($this->chatId, $telegramName);
            if ($this->fileHandler->saveState($chatId, 'awaiting_leader_birthdate')) {

                $this->deleteMessageWithDelay();

                $datePicker = new \Bot\DatePicker();
                $birthPicker = $datePicker->generate(1375, 1, 1, 'birthday', "اطلاعات شما تا این لحظه:\n" .
                    "👤 نام: {$first_name}\n" .
                    "📝 نام خانوادگی: {$last_name}\n" .
                    "⭐ نام مستعار: {$telegramName}\n\n" .
                    "🎂 لطفاً تاریخ تولد خود را انتخاب کنید 👇");

                $response = $this->sendRequest("sendMessage", [
                    "chat_id" => $chatId,
                    //                    "message_id" => $messageId,
                    "text" => $birthPicker['text'],
                    "parse_mode" => "HTML",
                    "reply_markup" => $birthPicker['reply_markup']
                ]);

                if (is_array($response) && isset($response['result']['message_id'])) {
                    $this->fileHandler->saveMessageId($chatId, $response['result']['message_id']);
                }
            } else {
                error_log("❌ Failed to save state for chatId: $chatId");
                $this->sendRequest("sendMessage", [
                    "chat_id" => $chatId,
                    "text" => $userLanguage === 'fa' ? "خطا در پردازش. لطفاً دوباره سعی کنید." : "Processing error. Please try again.",
                    "reply_markup" =>  $this->getMainKeyboard()
                ]);
            }
        }

        if ($callbackData == 'choice_leader_real_name') {
            $leader_fullname = $this->fileHandler->getLeaderName($this->chatId);
            $first_name = $this->fileHandler->getLeaderFirstName($this->chatId);
            $last_name = $this->fileHandler->getLeaderLastName($this->chatId);
            $this->fileHandler->setNickname($this->chatId, $leader_fullname);
            if ($this->fileHandler->saveState($chatId, 'awaiting_leader_birthdate')) {

                $this->deleteMessageWithDelay();

                $datePicker = new \Bot\DatePicker();
                $birthPicker = $datePicker->generate(1375, 1, 1, 'birthday', "اطلاعات شما تا این لحظه:\n" .
                    "👤 نام: {$first_name}\n" .
                    "📝 نام خانوادگی: {$last_name}\n" .
                    "⭐ نام مستعار: {$leader_fullname}\n\n" .
                    "🎂 لطفاً تاریخ تولد خود را انتخاب کنید 👇");

                $response = $this->sendRequest("sendMessage", [
                    "chat_id" => $chatId,
                    //                    "message_id" => $messageId,
                    "text" => $birthPicker['text'],
                    "parse_mode" => "HTML",
                    "reply_markup" => $birthPicker['reply_markup']
                ]);

                if (is_array($response) && isset($response['result']['message_id'])) {
                    $this->fileHandler->saveMessageId($chatId, $response['result']['message_id']);
                }
            } else {
                $this->sendRequest("sendMessage", [
                    "chat_id" => $chatId,
                    "text" => $userLanguage === 'fa' ? "خطا در پردازش. لطفاً دوباره سعی کنید." : "Processing error. Please try again.",
                    "reply_markup" =>  $this->getMainKeyboard()
                ]);
            }
        }

        if ($callbackData === 'create_tour') {
            $introText = "به بخش ایجاد تور جدید خوش آمدید! 🏕️\n\n"
                . "در مراحل بعدی، ربات اطلاعاتی مانند عنوان، توضیحات، تاریخ، قیمت، خدمات و... را به صورت مرحله به مرحله از شما دریافت خواهد کرد.\n\n"
                . "لطفاً سعی کنید اطلاعات را با دقت وارد کنید تا یک تور کامل و جذاب برای طبیعت‌گردها ایجاد کنید.\n\n"
                . "✅ برای شروع فرآیند، دکمه زیر را فشار دهید.";

            $keyboard = [
                'inline_keyboard' => [
                    [['text' => '🚀 بزن بریم', 'callback_data' => 'start_tour_creation_form']],
                    [['text' => '🔙 بازگشت', 'callback_data' => 'leader_dashboard']]
                ]
            ];

            $this->sendRequest("editMessageText", [
                "chat_id" => $this->chatId,
                "message_id" => $messageId,
                "text" => $introText,
                "reply_markup" => json_encode($keyboard)
            ]);
            return;
        }

        if ($callbackData === 'start_tour_creation_form') {
            $formsConfig = include(__DIR__ . '/Forms.php');
            $formManager = new FormManager($this, $this->stateManager, $formsConfig);
            $formManager->start($this->chatId, 'tour_creation', $this->callbackQueryId, $messageId);
            return;
        }

        if ($callbackData === 'user_firstname') {
            $this->handleInputStep($chatId, $messageId, 'user_firstname', 'لطفاً نام خود را وارد کنید:', 'register', $userLanguage);
        } else if ($callbackData === 'user_lastname') {
            $this->handleInputStep($chatId, $messageId, 'user_lastname', 'لطفاً نام خانوادگی خود را وارد کنید:', 'user_firstname', $userLanguage);
        } else if ($callbackData === 'user_nickname') {
            $telegramName = $this->db->getUserFullName($this->chatId);
            $user_fullname = $this->fileHandler->getUserName($this->chatId);
            $this->fileHandler->saveMessageId($this->chatId, $messageId);
            if ($this->fileHandler->saveState($chatId, 'awaiting_user_nickname')) {
                $response = $this->sendRequest("editMessageText", [
                    "chat_id" => $chatId,
                    "message_id" => $messageId,
                    "text" => "لطفاً نام مستعار خود را دستی وارد کنید:\nیا از بین دو گزینه زیر انتخاب کنید:",
                    "reply_markup" => json_encode([
                        "inline_keyboard" => [
                            [["text" => "انتخاب نام تلگرام($telegramName)", "callback_data" => "choice_telegram_name"]],
                            [["text" => "انتخاب نام واقعی($user_fullname)", "callback_data" => "choice_explorer_name"]],
                            [
                                ["text" => "🔙 بازگشت", "callback_data" => "user_lastname"],
                                ["text" => "❌ انصراف", "callback_data" => "go_to_menu"]
                            ]
                        ]
                    ])
                ]);
            }
        } else if ($callbackData === 'user_phone') {
            $this->handleInputStep($chatId, $messageId, 'user_phone', "لطفاً شماره موبایل خود را وارد کنید:\n(حتما از کیبورد انگلیسی استفاده کنید)", 'user_birthdate', $userLanguage);
        } else if ($callbackData === 'user_city') {
            $this->handleInputStep($chatId, $messageId, 'user_city', 'لطفاً شهر محل سکونت خود را وارد کنید:', 'user_phone', $userLanguage);
        }

        if ($callbackData === 'leader_firstname') {
            $this->handleInputStep($chatId, $messageId, 'leader_firstname', 'لطفاً نام خود را وارد کنید:', 'go_to_menu', $userLanguage);
        } else if ($callbackData === 'leader_lastname') {
            $this->handleInputStep($chatId, $messageId, 'leader_lastname', 'لطفاً نام خانوادگی خود را وارد کنید:', 'leader_firstname', $userLanguage);
        } else if ($callbackData === 'leader_nickname') {
            $telegramName = $this->db->getUserFullName($this->chatId);
            $leader_fullname = $this->fileHandler->getLeaderName($this->chatId);
            $this->fileHandler->saveMessageId($this->chatId, $messageId);
            if ($this->fileHandler->saveState($chatId, 'awaiting_leader_nickname')) {
                $response = $this->sendRequest("editMessageText", [
                    "chat_id" => $chatId,
                    "message_id" => $messageId,
                    "text" => "لطفاً نام مستعار خود را دستی وارد کنید:\nیا یکی از موارد زیر را انتخاب نمایید:",
                    "reply_markup" => json_encode([
                        "inline_keyboard" => [
                            [["text" => "نام تلگرام ($telegramName)", "callback_data" => "choice_leader_telegram_name"]],
                            [["text" => "نام واقعی ($leader_fullname)", "callback_data" => "choice_leader_real_name"]],
                            [
                                ["text" => "🔙 بازگشت", "callback_data" => "leader_lastname"],
                                ["text" => "❌ انصراف", "callback_data" => "go_to_menu"]
                            ]
                        ]
                    ])
                ]);
            }
        } else if ($callbackData === 'leader_birthdate') {
            $leaderData = $this->fileHandler->getLeaderData($chatId);
            $messageId = $this->fileHandler->getMessageId($chatId);
            $text = "📌 <b>اطلاعات شما تا این لحظه:</b>\n\n";
            $text .= "👤 <b>نام:</b> " . htmlspecialchars($leaderData['first_name']) . "\n";
            $text .= "📝 <b>نام خانوادگی:</b> " . htmlspecialchars($leaderData['last_name']) . "\n";
            $text .= "⭐ <b>نام مستعار:</b> " . htmlspecialchars($leaderData['nick_name']) . "\n\n";
            $text .= "🎂 <b>لطفاً تاریخ تولد خود را انتخاب کنید:</b>";

            // بازگشت به مرحله قبلی = دوباره نشان دادن DatePicker
            $datePicker = new \Bot\DatePicker();
            $birthPicker = $datePicker->generate(
                $leaderData['year'] ?? 1375,
                $leaderData['month'] ?? 1,
                $leaderData['day'] ?? 1,
                'birthday',
                $text
            );

            $this->fileHandler->saveState($chatId, 'awaiting_leader_birthdate');

            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => $birthPicker['text'],
                "parse_mode" => "HTML",
                "reply_markup" => $birthPicker['reply_markup']
            ]);

            return;
        } else if ($callbackData === 'leader_phone') {
            $this->handleInputStep($chatId, $messageId, 'leader_phone', "شماره موبایل خود را وارد کنید:\n(فقط با کیبورد انگلیسی)", 'leader_birthdate', $userLanguage);
        } else if ($callbackData === 'leader_city') {
            $this->handleInputStep($chatId, $messageId, 'leader_city', 'شهر محل سکونت خود را وارد کنید:', 'leader_phone', $userLanguage);
        } else if ($callbackData === 'leader_address') {
            $this->handleInputStep($chatId, $messageId, 'leader_city', 'آدرس خود را وارد کنید:', 'leader_city', $userLanguage);
        } else if ($callbackData === 'leader_code') {
            $this->handleInputStep($chatId, $messageId, 'leader_code', 'لطفا کد ملی خود را وارد کنید:', 'leader_address', $userLanguage);
        } else if ($callbackData === 'leader_channel') {
            $this->handleInputStep($chatId, $messageId, 'leader_channel', 'لطفا آیدی کانال خود را وارد کنید:', 'leader_code', $userLanguage);
        } else if ($callbackData === 'leader_group') {
            $this->handleInputStep($chatId, $messageId, 'leader_group', 'لطفا آیدی گروه خود را وارد کنید:', 'leader_channel', $userLanguage);
        } else if ($callbackData === 'leader_card') {
            $this->handleInputStep($chatId, $messageId, 'leader_card', 'لطفا شماره کارت خود را وارد کنید:', 'leader_group', $userLanguage);
        }

        if (str_starts_with($callbackData, "set_tour_start_date_")) { // کاربر تاریخ شروع را انتخاب یا تایپ کرده
            $dateInput = str_replace("set_tour_start_date_", "", $callbackData);

            $this->fileHandler->setTourData($chatId, ['start_date' => $dateInput]);
            if ($this->fileHandler->saveState($chatId, 'await_tour_end_date')) {
                // $this->deleteMessageWithDelay();
                $text = "لطفا تاریخ پایان تور را وارد کنید:";
                $this->end_date_options($chatId, $messageId, $text);
            } else {
                error_log("❌ Failed to save state for chatId: $chatId");
                $this->sendRequest("sendMessage", [
                    "chat_id" => $chatId,
                    "text" => $userLanguage === 'fa' ? "خطا در پردازش. لطفاً دوباره سعی کنید." : "Processing error. Please try again.",
                    "reply_markup" =>  $this->getMainKeyboard()
                ]);
            }
        }

        if (str_starts_with($callbackData, "set_tour_end_date_")) { // کاربر تاریخ شروع را انتخاب یا تایپ کرده
            $dateInput = str_replace("set_tour_end_date_", "", $callbackData);

            $this->fileHandler->setTourData($chatId, ['end_date' => $dateInput]);
            if ($this->fileHandler->saveState($chatId, 'await_tour_start_time')) {
                // $this->deleteMessageWithDelay();
                $response = $this->sendRequest("editMessageText", [
                    "chat_id" => $chatId,
                    "message_id" => $messageId,
                    "text" =>
                    "لطفاً ساعت شروع تور را وارد کنید مانند(8:00):",
                    "reply_markup" => json_encode([
                        "inline_keyboard" => [
                            [
                                ["text" => "🔙 بازگشت", "callback_data" => "back_await_start_time"],
                                ["text" => "❌ انصراف", "callback_data" => "go_to_menu"]
                            ]
                        ]
                    ])
                ]);
            } else {
                error_log("❌ Failed to save state for chatId: $chatId");
                $this->sendRequest("sendMessage", [
                    "chat_id" => $chatId,
                    "text" => $userLanguage === 'fa' ? "خطا در پردازش. لطفاً دوباره سعی کنید." : "Processing error. Please try again.",
                    "reply_markup" =>  $this->getMainKeyboard()
                ]);
            }
        }
        if (strpos($callbackData, 'tour_register_') === 0) {
            $tourId = (int)str_replace('tour_register_', '', $callbackData);
            $this->showRegisteredUsers($chatId, $tourId, $this->callbackQueryId, $messageId);
        } elseif (strpos($callbackData, 'tour_complete_') === 0) {
            $tourId = (int)str_replace('tour_complete_', '', $callbackData);

            // ارسال دکمه های تأیید یا لغو
            $keyboard = [
                'inline_keyboard' => [
                    [
                        ['text' => "✅ تایید", 'callback_data' => "confirm_complete_$tourId"],
                        ['text' => "❌ انصراف", 'callback_data' => "go_to_menu"]
                    ]
                ]
            ];

            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => "آیا مطمئنی می خوای ظرفیت این تور رو تکمیل کنی؟",
                "reply_markup" => json_encode($keyboard)
            ]);
        } elseif (strpos($callbackData, 'confirm_complete_') === 0) {
            $tourId = (int)str_replace('confirm_complete_', '', $callbackData);

            $this->db->updateTourIsComplete($tourId);

            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => "✅ ظرفیت تور شماره $tourId تکمیل شد."
            ]);
        } elseif (strpos($callbackData, 'list_channel_') === 0) {
            $tourId = (int)str_replace('list_channel_', '', $callbackData);
            $this->showRegisteredUsersChannel($chatId, $tourId);
        } elseif (strpos($callbackData, 'list_group_') === 0) {
            $tourId = (int)str_replace('list_group_', '', $callbackData);
            $this->showRegisteredUsersGroup($chatId, $tourId);
        } else if (preg_match('/^edit_tour_(\d+)$/', $callbackData, $matches)) {
            $tourId = (int)$matches[1];
            $tour = $this->db->getTourById($tourId);
            if (!$tour) {
                $this->sendRequest("answerCallbackQuery", [
                    "callback_query_id" => $this->callbackQueryId,
                    "text" => "❌ تور پیدا نشد.",
                    "show_alert" => true
                ]);
                return;
            }

            $summaryText = $this->generateTourDetailsText($tourId);

            $fieldsToEdit = [
                'title'             => '✏️ عنوان',
                'description'       => '📝 توضیحات',
                'difficulty'        => '🧗‍♂️ سطح سختی',
                'origin_address'    => '🚩 مبدا حرکت',
                'region'            => '📍 منطقه',
                'location'          => '🗺️ لوکیشن',
                'start_date'        => '🗓️ تاریخ شروع',
                'start_time'        => '⏰ ساعت شروع',
                'end_date'          => '🗓️ تاریخ پایان',
                'end_time'          => '⏰ ساعت پایان',
                'transport_options' => '🚌 وسایل نقلیه',
                'pricing'           => '💰 قیمت ها',
                'services_options'  => '🛎️ خدمات تور',
                'meal_details'      => '🍱 جزئیات غذا',
                'required_items'    => '🎒 لوازم مورد نیاز',
                'capacity'          => '👥 ظرفیت',
                'notes'             => '⚠️ نکات مهم',
                'banner'            => '🖼️ بنر'
            ];
            $editButtons = [];
            $row = [];

            foreach ($fieldsToEdit as $key => $label) {
                if ($key === 'pricing' && empty($tour['transport_options'])) {
                    continue;
                }
                $row[] = ['text' =>  $label, 'callback_data' => "prompt_edit_{$key}_{$tourId}"];

                if (count($row) == 2) {
                    $editButtons[] = $row;
                    $row = [];
                }
            }

            if (!empty($row)) {
                $editButtons[] = $row;
            }

            $editButtons[] = [['text' => '🔙 بازگشت', 'callback_data' => 'tour_details_' . $tourId]];

            $finalKeyboard = ["inline_keyboard" => $editButtons];

            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => "<b>منوی ویرایش تور:</b>\n\n" . $summaryText,
                "parse_mode" => "HTML",
                "reply_markup" => $finalKeyboard
            ]);

            return;
        }
        if (preg_match('/^prompt_edit_pricing_(\d+)$/', $callbackData, $matches)) {
            $tourId = (int)$matches[1];
            $tour = $this->db->getTourById($tourId);

            if (!$tour) {
                return;
            }

            $transportOptions = $tour['transport_options'] ?? [];
            $currentPricing = $tour['pricing'] ?? [];

            if (empty($transportOptions)) {
                $this->sendRequest("answerCallbackQuery", ["callback_query_id" => $this->callbackQueryId, "text" => "❌ ابتدا باید وسیله نقلیه ای برای تور انتخاب کنید.", "show_alert" => true]);
                return;
            }

            $text = "💰 <b>مدیریت قیمت ها</b>\n\nکدام قیمت را می خواهید ویرایش کنید؟\n\n";
            $keyboard = [];

            $transportLabels = $this->forms['tour_creation']['fields']['transport_options']['options'];

            foreach ($transportOptions as $vehicleKey) {
                $label = $transportLabels[$vehicleKey] ?? $vehicleKey;

                $price = $currentPricing[$vehicleKey]['amount'] ?? 0;
                $priceFormatted = number_format($price);

                $keyboard[] = [
                    ['text' => htmlspecialchars($label) . ": " . $priceFormatted . " تومان", 'callback_data' => 'no_op'],
                    ['text' => '✏️ ویرایش', 'callback_data' => "prompt_single_price_{$vehicleKey}_{$tourId}"]
                ];
            }

            $keyboard[] = [['text' => '🔄 بازنشانی و ورود همه قیمت ها ', 'callback_data' => "reset_all_prices_{$tourId}"]];
            $keyboard[] = [['text' => '🔙 بازگشت به منوی ویرایش', 'callback_data' => "edit_tour_{$tourId}"]];

            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => $text,
                "parse_mode" => "HTML",
                "reply_markup" => ['inline_keyboard' => $keyboard]
            ]);
            return;
        }

        if (preg_match('/^prompt_edit_(\w+)_(\d+)$/', $callbackData, $matches)) {
            $field = $matches[1];
            $tourId = (int)$matches[2];
            $fieldConfig = $this->forms['tour_creation']['fields'][$field];
            $fieldType = $fieldConfig['type'] ?? 'text';
            $tour = $this->db->getTourById($tourId);

            $backButton = [['text' => '❌ لغو', 'callback_data' => 'edit_tour_' . $tourId]];

            switch ($fieldType) {
                case 'buttons':
                    $options = $fieldConfig['options'];
                    foreach ($options as &$row) {
                        foreach ($row as &$button) {
                            $button['callback_data'] = "confirm_edit_{$field}_{$button['callback_data']}_{$tourId}";
                        }
                    }
                    $options[] = $backButton;
                    $this->sendRequest("editMessageText", ["chat_id" => $chatId, "message_id" => $messageId, "text" => $fieldConfig['prompt'], "reply_markup" => ['inline_keyboard' => $options]]);
                    break;

                case 'multi_select':
                    $selectedOptions = $tour[$field] ?? [];
                    $options = $fieldConfig['options'];
                    $keyboard = [];
                    foreach ($options as $key => $label) {
                        $isChecked = in_array($key, $selectedOptions);
                        $text = ($isChecked ? "✅ " : "🔲 ") . $label;
                        $keyboard[] = [['text' => $text, 'callback_data' => "toggle_edit_multiselect_{$field}_{$key}_{$tourId}"]];
                    }
                    $keyboard[] = [['text' => '✅ تایید و ادامه', 'callback_data' => "confirm_edit_multiselect_{$field}_{$tourId}"]];
                    $keyboard[] = $backButton;
                    $this->sendRequest("editMessageText", ["chat_id" => $chatId, "message_id" => $messageId, "text" => $fieldConfig['prompt'], "reply_markup" => ['inline_keyboard' => $keyboard]]);
                    break;

                case 'datepicker':
                case 'timepicker':
                    $this->stateManager->saveState($chatId, ['next_action' => 'awaiting_new_value', 'context' => ['tour_id' => $tourId, 'field' => $field]]);
                    $datePicker = new DatePicker();
                    $pickerData = ($fieldType === 'datepicker')
                        ? $datePicker->generate(null, null, null, "edit_{$field}_{$tourId}", $fieldConfig['prompt'])
                        : $datePicker->generateTimePicker(12, 0, "edit_{$field}_{$tourId}", $fieldConfig['prompt']);

                    $this->sendRequest('editMessageText', [
                        'chat_id' => $chatId,
                        'message_id' => $messageId,
                        'text' => $pickerData['text'],
                        'parse_mode' => 'HTML',
                        'reply_markup' => $pickerData['reply_markup']
                    ]);
                    break;

                default: // photo, location, text
                    $this->stateManager->saveState($chatId, ['next_action' => 'awaiting_new_value', 'context' => ['tour_id' => $tourId, 'field' => $field]]);
                    $res = $this->sendRequest("editMessageText", ["chat_id" => $chatId, "message_id" => $messageId, "text" => "✍️ لطفاً مقدار جدید برای «{$fieldConfig['label']}» را وارد یا ارسال کنید:", "reply_markup" => ["inline_keyboard" => [$backButton]]]);
                    $this->fileHandler->saveMessageId($chatId, $res['result']['message_id'] ?? '');
                    break;
            }
            return;
        } else if (preg_match('/^edit_([a-zA-Z_]+)_(\d+)-(.+)/', $callbackData, $matches)) {
            $fieldFromCallback = $matches[1];
            $tourId = (int)$matches[2];
            $pickerCallbackData = $matches[0];
            $datePicker = new \Bot\DatePicker();
            $isDatePicker = (strpos($fieldFromCallback, 'date') !== false);
            $result = $isDatePicker ? $datePicker->handleCallback($pickerCallbackData) : $datePicker->handleTimeCallback($pickerCallbackData);

            if ($result['status'] === 'update') {
                $this->sendRequest("editMessageText", [
                    "chat_id" => $chatId,
                    "message_id" => $messageId,
                    "text" => $result['new_data']['text'],
                    "parse_mode" => "HTML",
                    "reply_markup" => $result['new_data']['reply_markup']
                ]);
            } elseif ($result['status'] === 'confirmed') {
                $newValue = null;
                $dbField = str_replace(['_time', '_date'], ['_date', '_date'], $fieldFromCallback);

                if ($isDatePicker) {
                    $date = $result['date'];
                    $gregorianArray = $this->jalaliToGregorian($date['year'], $date['month'], $date['day']);
                    $newValue = sprintf('%04d-%02d-%02d', $gregorianArray[0], $gregorianArray[1], $gregorianArray[2]);
                } else { // Time picker
                    $newValue = $result['time'];
                }

                $tour = $this->db->getTourById($tourId);
                $existingDateTime = $tour[$dbField] ?? 'now';

                $fullDateTime = '';
                if ($isDatePicker) {
                    $timePart = date('H:i:s', strtotime($existingDateTime));
                    $fullDateTime = $newValue . ' ' . $timePart;
                } else {
                    $datePart = date('Y-m-d', strtotime($existingDateTime));
                    $fullDateTime = $datePart . ' ' . $newValue . ':00';
                }

                $success = $this->db->updateTourField($tourId, $dbField, $fullDateTime);

                if ($success) {
                    $this->updateTourPost($tourId);
                    $this->sendRequest("answerCallbackQuery", ["callback_query_id" => $this->callbackQueryId, "text" => "✅ تاریخ/زمان با موفقیت ویرایش شد."]);
                    $fakeCallbackQuery = ["data" => "edit_tour_" . $tourId, "message" => $callbackQuery['message']];
                    $this->handleCallbackQuery($fakeCallbackQuery);
                } else {
                    $this->sendRequest("answerCallbackQuery", ["callback_query_id" => $this->callbackQueryId, "text" => "❌ خطا در ذخیره اطلاعات."]);
                }
            } elseif ($result['status'] === 'back') {
                $fakeCallbackQuery = ["data" => "edit_tour_" . $tourId, "message" => $callbackQuery['message']];
                $this->handleCallbackQuery($fakeCallbackQuery);
            }
            return;
        } elseif (str_starts_with($callbackData, 'toggle_edit_multiselect_')) {
            // لاگ ۱: دریافت callback_data اولیه
            error_log("[DEBUG] Handling 'toggle_edit_multiselect'. Raw Callback Data: " . $callbackData);

            // --- شروع بخش解析 (Parsing) ---
            $dataPart = str_replace('toggle_edit_multiselect_', '', $callbackData);

            $lastUnderscorePos = strrpos($dataPart, '_');
            if ($lastUnderscorePos === false) {
                error_log("[ERROR] Could not find the last underscore to determine tourId. Data part: " . $dataPart);
                return;
            }

            $tourId = (int)substr($dataPart, $lastUnderscorePos + 1);
            $fieldAndOption = substr($dataPart, 0, $lastUnderscorePos);

            $field = null;
            $optionKey = null;

            // تشخیص نام فیلد و کلید گزینه
            if (str_starts_with($fieldAndOption, 'services_options_')) {
                $field = 'services_options';
                $optionKey = substr($fieldAndOption, strlen('services_options_'));
            } elseif (str_starts_with($fieldAndOption, 'transport_options_')) {
                $field = 'transport_options';
                $optionKey = substr($fieldAndOption, strlen('transport_options_'));
            }

            // لاگ ۲: مقادیر استخراج شده
            error_log("[DEBUG] Parsed values -> Field: [{$field}], OptionKey: [{$optionKey}], TourID: [{$tourId}]");

            if (!$field || !$optionKey) {
                error_log("[ERROR] Could not parse field or optionKey from callback: " . $callbackData);
                $this->sendRequest("answerCallbackQuery", ["callback_query_id" => $this->callbackQueryId, "text" => "خطای داخلی.", "show_alert" => true]);
                return;
            }
            // --- پایان بخش解析 (Parsing) ---

            $tour = $this->db->getTourById($tourId);
            $fieldConfig = $this->forms['tour_creation']['fields'][$field] ?? null;

            if (!$fieldConfig) {
                error_log("[ERROR] Invalid field config for '{$field}'.");
                $this->sendRequest("answerCallbackQuery", ["callback_query_id" => $this->callbackQueryId, "text" => "خطای فیلد نامعتبر.", "show_alert" => true]);
                return;
            }

            $selectedOptions = $tour[$field] ?? [];
            error_log("[DEBUG] Current selected options for '{$field}': " . json_encode($selectedOptions));

            // منطق اصلی: افزودن یا حذف گزینه
            if (in_array($optionKey, $selectedOptions)) {
                $selectedOptions = array_values(array_diff($selectedOptions, [$optionKey]));
                error_log("[INFO] Option '{$optionKey}' REMOVED. New options: " . json_encode($selectedOptions));
            } else {
                $selectedOptions[] = $optionKey;
                error_log("[INFO] Option '{$optionKey}' ADDED. New options: " . json_encode($selectedOptions));
            }

            // ذخیره در دیتابیس
            $updateResult = $this->db->updateTourField($tourId, $field, json_encode($selectedOptions));
            error_log("[INFO] Database update for '{$field}' was " . ($updateResult ? 'SUCCESSFUL' : 'FAILED'));

            // ساخت مجدد کیبورد
            $keyboard = [];
            foreach ($fieldConfig['options'] as $key => $label) {
                $isChecked = in_array($key, $selectedOptions);
                $text = ($isChecked ? "✅ " : "🔲 ") . $label;
                $keyboard[] = [['text' => $text, 'callback_data' => "toggle_edit_multiselect_{$field}_{$key}_{$tourId}"]];
            }
            $keyboard[] = [['text' => '✅ تایید نهایی', 'callback_data' => "confirm_edit_multiselect_{$field}_{$tourId}"]];
            $keyboard[] = [['text' => '❌ لغو', 'callback_data' => 'edit_tour_' . $tourId]];

            // ارسال پیام ویرایش شده
            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => $fieldConfig['prompt'],
                "reply_markup" => ['inline_keyboard' => $keyboard]
            ]);
            return;
        } elseif (preg_match('/^confirm_edit_multiselect_(\w+)_(\d+)$/', $callbackData, $matches)) {
            $field = $matches[1];
            $tourId = (int)$matches[2];

            // اگر فیلد وسایل نقلیه بود، قیمت‌ها را ریست کن
            if ($field === 'transport_options') {
                $this->db->updateTourField($tourId, 'pricing', json_encode([]));
            }

            $this->updateTourPost($tourId);

            $this->sendRequest("answerCallbackQuery", [
                "callback_query_id" => $this->callbackQueryId,
                "text" => "✅ گزینه‌ها با موفقیت ذخیره شدند."
            ]);

            // بازگشت به منوی ویرایش
            $fakeCallbackQuery = ["data" => "edit_tour_" . $tourId, "message" => $callbackQuery['message']];
            $this->handleCallbackQuery($fakeCallbackQuery);
            return;
        } elseif (preg_match('/^confirm_edit_(\w+)_([a-zA-Z0-9_]+)_(\d+)$/', $callbackData, $matches)) {
            $field = $matches[1];
            $value = $matches[2];
            $tourId = (int)$matches[3];
            $success = $this->db->updateTourField($tourId, $field, $value);

            if ($success) {
                $this->updateTourPost($tourId);

                $this->sendRequest("answerCallbackQuery", [
                    "callback_query_id" => $this->callbackQueryId,
                    "text" => "✅ اطلاعات با موفقیت به‌روزرسانی شد.",
                    "show_alert" => false
                ]);

                $fakeCallbackQuery = [
                    "data" => "edit_tour_" . $tourId,
                    "message" => $callbackQuery['message']
                ];
                $this->handleCallbackQuery($fakeCallbackQuery);
            } else {
                $this->sendRequest("answerCallbackQuery", [
                    "callback_query_id" => $this->callbackQueryId,
                    "text" => "❌ خطا در به‌روزرسانی اطلاعات.",
                    "show_alert" => true
                ]);
            }
            return;
        } else if (preg_match('/^toggle_edit_transport_(\w+)_(\d+)$/', $callbackData, $matches)) {
            $optionKey = $matches[1];
            $tourId = (int)$matches[2];


            if (!$chatId || !$messageId) {
                error_log("❌ chatId یا messageId یافت نشد در toggle_edit_transport");
                return;
            }

            // دریافت اطلاعات تور
            $tour = $this->db->getTourById($tourId);
            $selectedOptions = $tour['transport_options'] ?? [];

            // بروزرسانی لیست گزینه ها
            if (in_array($optionKey, $selectedOptions)) {
                $newOptions = array_values(array_diff($selectedOptions, [$optionKey]));
            } else {
                $newOptions = array_merge($selectedOptions, [$optionKey]);
            }

            // ذخیره در دیتابیس
            $this->db->updateTourField($tourId, 'transport_options', json_encode($newOptions));

            // دریافت گزینه ها از پیکربندی فرم
            $options = $this->forms['tour_creation']['fields']['transport_options']['options'];
            $keyboard = [];

            foreach ($options as $key => $label) {
                $isChecked = in_array($key, $newOptions);
                $text = ($isChecked ? "✅ " : "🔲 ") . $label;
                $keyboard[] = [[
                    'text' => $text,
                    'callback_data' => "toggle_edit_transport_{$key}_{$tourId}"
                ]];
            }

            $keyboard[] = [[
                'text' => '✅ تایید و ادامه',
                'callback_data' => "confirm_edit_transport_{$tourId}"
            ]];

            // بروزرسانی پیام با لیست جدید
            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => "لطفاً گزینه ها را انتخاب کنید:",
                "reply_markup" => ['inline_keyboard' => $keyboard]
            ]);
            return;
        } else if (preg_match('/^confirm_edit_transport_(\d+)$/', $callbackData, $matches)) {
            $tourId = (int)$matches[1];
            $this->db->updateTourField($tourId, 'pricing', json_encode([])); // پاک کردن قیمت های قبلی
            $this->updateTourPost($tourId);

            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => "وسایل نقلیه تغییر کرد. قیمت های قبلی پاک شدند. آیا می خواهید اکنون قیمت های جدید را تنظیم کنید؟",
                "reply_markup" => ["inline_keyboard" => [

                    [['text' => '✅ بله، قیمت ها را تنظیم کن', 'callback_data' => "reset_all_prices_{$tourId}"]],

                    [['text' => ' خیر، بازگشت به منو', 'callback_data' => "edit_tour_{$tourId}"]]
                ]]
            ]);
            return;
        } else if (preg_match('/^prompt_single_price_(\w+)_(\d+)$/', $callbackData, $matches)) {
            $vehicleKey = $matches[1];
            $tourId = (int)$matches[2];

            $transportLabels = $this->forms['tour_creation']['fields']['transport_options']['options'];
            $label = $transportLabels[$vehicleKey] ?? $vehicleKey;

            // وضعیت جدید برای دریافت قیمت یک وسیله خاص
            $this->stateManager->saveState($chatId, [
                'next_action' => 'awaiting_single_price_update',
                'context' => [
                    'tour_id' => $tourId,
                    'vehicle_key' => $vehicleKey
                ]
            ]);

            $res =  $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => "✍️ لطفاً قیمت جدید برای «" . htmlspecialchars($label) . "» را به تومان وارد کنید:",
                "reply_markup" => ["inline_keyboard" => [[['text' => '❌ لغو', 'callback_data' => 'prompt_edit_pricing_' . $tourId]]]]
            ]);
            $this->fileHandler->saveMessageId($chatId, $res['result']['message_id'] ?? '');
            return;
        } else if (preg_match('/^reset_all_prices_(\d+)$/', $callbackData, $matches)) {
            $tourId = (int)$matches[1];
            $tour = $this->db->getTourById($tourId);
            $transportOptions = $tour['transport_options'] ?? [];

            if (empty($transportOptions)) {
                $this->sendRequest("answerCallbackQuery", ["callback_query_id" => $this->callbackQueryId, "text" => "❌ وسیله نقلیه ای یافت نشد.", "show_alert" => true]);
                return;
            }

            $this->stateManager->saveState($chatId, [
                'next_action' => 'awaiting_new_price',
                'context' => [
                    'tour_id' => $tourId,
                    'vehicles_to_price' => $transportOptions,
                    'new_pricing_data' => [],
                    'prompt_message_id' => $messageId
                ]
            ]);

            $this->askForNextPriceInEditMode($chatId, $messageId);
            return;
        } else if ($callbackData === 'no_op') {
            $this->sendRequest("answerCallbackQuery", ["callback_query_id" => $this->callbackQueryId]);
            return;
        }
        if (strpos($callbackData, 'pay_with_toman_') === 0) {

            $tourId = intval(str_replace("pay_with_toman_", "", $callbackData));
            //            $userLanguage = $this->db->getUserLanguage($this->chatId);
            $userLanguage = 'fa';

            $this->fileHandler->saveTourId($this->chatId, $tourId);
            $this->fileHandler->saveState($this->chatId, "awaiting_discount_input");
            $messages = [
                'fa' => "💰 آیا کد تخفیف دارید؟\n\n"
                    . "🔹 اگر کد تخفیف دارید، آن را ارسال کنید.\n"
                    . "🔹 اگر کد تخفیف ندارید، دکمه <b>بدون کد تخفیف</b> را بزنید.",
                'en' => "💰 Do you have a discount code?\n\n"
                    . "🔹 If you have a discount code, please send it.\n"
                    . "🔹 If not, press <b>Proceed without discount</b>."
            ];

            $inlineKeyboard = [
                [
                    ["text" => ($userLanguage === 'fa' ? "🚀 بدون کد تخفیف" : "🚀 Proceed without discount"), "callback_data" => "no_discount_code_toman"]
                ],
                [["text" => "❌انصراف", "callback_data" => "go_to_menu"]]
            ];

            $this->sendRequest("editMessageText", [
                "chat_id" => $this->chatId,
                "message_id" => $messageId,
                "text" =>  $messages['fa'],
                "parse_mode" => "HTML",
                "reply_markup" => json_encode(["inline_keyboard" => $inlineKeyboard])
            ]);
        } elseif ($callbackData === "no_discount_code_toman") {
            $this->fileHandler->saveState($this->chatId, "null");
            $userLanguage = 'fa';
            $tourId = $this->fileHandler->getTourId($this->chatId);
            $tourDetails = $this->db->getTourDetailsWithPrice($tourId);

            $tempData = $this->fileHandler->getTempData($this->chatId);
            $selectedVehicle = $tempData['selected_vehicle'] ?? null;
            $quantity = $tempData['quantity'] ?? 1;

            $pricingData = json_decode($tourDetails['pricing'], true);
            $tourPricePerPerson = 0;
            if (is_array($pricingData) && isset($pricingData[$selectedVehicle])) {
                $tourPricePerPerson = $pricingData[$selectedVehicle]['amount'];
            }

            $totalAmount = $tourPricePerPerson * $quantity;

            $paymentResponse = $this->zarinpalPaymentHandler->createZarinpalPayment($totalAmount, $this->chatId, $tourId);

            if ($paymentResponse && isset($paymentResponse['authority'])) {
                $authority = $paymentResponse['authority'];
                $paymentUrl = "https://www.zarinpal.com/pg/StartPay/{$authority}";

                $this->db->insertUserPayment($this->chatId, $tourId, $totalAmount, $authority);

                $amountFormatted = number_format($totalAmount);

                $paymentMessages = [
                    'fa' => "✅ برای ورود به تور '{$tourDetails['title']}' لطفاً پرداخت را انجام بده:\n\n"
                        . "[💳 پرداخت]({$paymentUrl})\n\n"
                        . "👤 تعداد نفرات: {$quantity}\n"
                        . "💰 هزینه هر نفر: " . number_format($tourPricePerPerson) . " تومان\n"
                        . "💲 مبلغ کل: {$amountFormatted} تومان\n\n",

                    'en' => "✅ To join the tour '{$tourDetails['title']}', please complete your payment:\n\n"
                        . "[💳 Pay Now]({$paymentUrl})\n\n"
                        . "👥 Quantity: {$quantity}\n"
                        . "💰 Price per person: " . number_format($tourPricePerPerson) . " Toman\n"
                        . "💲 Total: {$amountFormatted} Toman\n\n"
                ];

                $this->sendRequest("editMessageText", [
                    "chat_id" => $this->chatId,
                    "message_id" => $messageId,
                    "text" => $paymentMessages[$userLanguage] ?? $paymentMessages['en'],
                    "parse_mode" => "Markdown"
                ]);
            } else {
                error_log("[Zarinpal Payment Error] Failed to get authority from Zarinpal for Chat ID: {$this->chatId} | Tour ID: {$tourId} | Amount: {$totalAmount}");
            }
        } elseif (str_starts_with($callbackData, "pay_card_to_card_")) {
            $tourId = str_replace("pay_card_to_card_", "", $callbackData);
            $this->fileHandler->saveState($this->chatId, "null");

            $userLanguage = $this->db->getUserLanguage($this->chatId);
            $tourDetails = $this->db->getTourById($tourId);
            $registration = $this->db->getUserTourRegistration($this->chatId, $tourId);

            $cardNumber = $this->db->getLeaderCard($tourDetails['chat_id']);
            $cardOwner = $this->db->getLeaderCardName($tourDetails['chat_id']);

            $tourName = $tourDetails['title'] ?? '';

            // --- شروع تغییرات ---
            $tempData = $this->fileHandler->getTempData($this->chatId);
            $selectedVehicle = $tempData['selected_vehicle'] ?? null;
            $quantity = $tempData['quantity'] ?? 1; // دریافت تعداد از فایل موقت

            $pricingData = $tourDetails['pricing'];
            $pricePerPerson = 0;

            if (is_array($pricingData) && isset($pricingData[$selectedVehicle])) {
                $pricePerPerson = $pricingData[$selectedVehicle]['amount'];
            }

            $totalAmount = $pricePerPerson * $quantity; // محاسبه قیمت کل بر اساس تعداد
            $amountFormatted = number_format($totalAmount);
            // --- پایان تغییرات ---

            $text = "💳 <b>پرداخت کارت به کارت برای شرکت در تور '{$tourName}'</b>\n\n"
                . "لطفاً مبلغ <b>{$amountFormatted} تومان</b> را به شماره کارت زیر واریز کن:\n\n"
                . "<b>شماره کارت:</b> <code>{$cardNumber}</code>\n"
                . "<b>به نام:</b> {$cardOwner}\n\n"
                . "<blockquote>تعداد نفرات انتخاب شده: {$quantity} نفر</blockquote>\n" // نمایش تعداد به کاربر
                . "بعد از پرداخت، روی دکمه زیر بزن و رسید رو ارسال کن.";

            $this->sendRequest("editMessageText", [
                "chat_id" => $this->chatId,
                "text" => $text,
                "message_id" => $messageId,
                "parse_mode" => "HTML",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [["text" => "✅ پرداخت کردم", "callback_data" => "send_card_proof_" . $tourId]],
                        [["text" => "🔙 بازگشت", "callback_data" => "change_quantity_{$tourId}_{$quantity}"]]
                    ]
                ])
            ]);
        } elseif (str_starts_with($callbackData, "send_card_proof_")) {
            $tourId = str_replace("send_card_proof_", "", $callbackData);
            $this->fileHandler->saveState($this->chatId, "awaiting_card_payment_proof_" . $tourId);
            $this->fileHandler->saveMessageId($this->chatId, $messageId);

            $this->sendRequest("editMessageText", [
                "chat_id" => $this->chatId,
                "message_id" => $messageId,
                "text" => "🧾 لطفاً رسید پرداخت کارت به کارت را ارسال کن. می تونی:\n\n- عکس رسید رو بفرستی 📸\n- یا رسید متنی رو بفرستی یا کد پیگیری رو به صورت متنی بنویسی ✍️"
            ]);
        } elseif (str_starts_with($callbackData, "confirm_card_payment_")) {
            $parts = explode("_", $callbackData);
            $userId = $parts[3];
            $tourId = $parts[4];

            $temp = $this->fileHandler->getTempData($userId);
            $selectedVehicle = $temp['selected_vehicle'] ?? null;
            $selectedPrice = $temp['selected_price'] ?? null;
            $quantity = $temp['quantity'] ?? 1;

            $this->db->updateTourPaymentStatus($userId, $tourId, 'completed', 'card_to_card_admin', $selectedVehicle, $selectedPrice, $quantity);

            $tour_info = $this->db->getTourById($tourId);
            $leader_id = $tour_info['leader_id'];
            $this->distributePaymentToLeaderAndAdmin($tourId, $leader_id, $selectedPrice);

            $this->updateTourParticipantCount($tourId);

            // حذف دکمه های پیام لیدر
            $this->sendRequest("editMessageReplyMarkup", [
                "chat_id" => $this->chatId, // chatId لیدر
                "message_id" => $callbackQuery['message']['message_id'],
                "reply_markup" => json_encode(['inline_keyboard' => []])
            ]);

            // ارسال پیام به کاربر
            $this->sendRequest("sendMessage", [
                "chat_id" => $userId,
                "text" => "✅ پرداخت شما توسط لیدر تأیید شد.\nبزن بریم🚀",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [["text" => "🏠 منو", "callback_data" => "go_to_menu"]]
                    ]
                ])
            ]);

            // ارسال پیام به خود لیدر
            $this->sendRequest("sendMessage", [
                "chat_id" => $this->chatId, // chatId لیدر
                "reply_to_message_id" => $messageId,
                "text" => "پرداخت کاربر تأیید شد.",
            ]);

            // اطلاع رسانی به ادمین ها
            $admins = $this->db->getAdmins();
            foreach ($admins as $admin) {
                $this->sendRequest("sendMessage", [
                    "chat_id" => $admin['chat_id'],
                    "text" => "✅ پرداخت کاربر با شناسه <code>$userId</code> برای تور «{$tour_info['title']}» توسط لیدر تأیید شد.",
                    "parse_mode" => "HTML"
                ]);
            }
        } elseif (str_starts_with($callbackData, "reject_card_payment_")) {
            $parts = explode("_", $callbackData);
            $userId = $parts[3];
            $tourId = $parts[4];

            // حذف دکمه های پیام ادمین
            $this->sendRequest("editMessageReplyMarkup", [
                "chat_id" => $this->chatId,
                "message_id" => $callbackQuery['message']['message_id'],
                "reply_markup" => json_encode(['inline_keyboard' => []])
            ]);
            $this->sendRequest("sendMessage", [
                "chat_id" => $userId,
                "text" => "❌ متأسفانه رسید پرداخت شما تأیید نشد.\nاگر اشتباهی پیش اومده لطفاً دوباره تلاش کن یا با پشتیبانی در ارتباط باش."
            ]);

            $this->sendRequest("sendMessage", [
                "chat_id" => $this->chatId,
                "reply_to_message_id" => $messageId,
                "text" => "پرداخت کاربر رد شد.",
            ]);
        } elseif (str_starts_with($callbackData, "pay_with_star_")) {
            $tourId = intval(str_replace("pay_with_star_", "", $callbackData));
            $userLanguage = 'fa';

            $this->fileHandler->saveState($this->chatId, "awaiting_discount_input_star");
            $this->fileHandler->saveTourId($this->chatId, $tourId);

            $messages = [
                'fa' => "⭐ آیا کد تخفیف دارید؟\n\n"
                    . "🔹 اگر کد تخفیف دارید، آن را ارسال کنید.\n"
                    . "🔹 اگر کد تخفیف ندارید، دکمه <b>بدون کد تخفیف</b> را بزنید.",
                'en' => "⭐ Do you have a discount code?\n\n"
                    . "🔹 If you have a discount code, please send it.\n"
                    . "🔹 If not, press <b>Proceed without discount</b>."
            ];

            $inlineKeyboard = [
                [
                    ["text" => ($userLanguage === 'fa' ? "🚀 بدون کد تخفیف" : "🚀 Proceed without discount"), "callback_data" => "no_discount_code_star"]
                ],
                [["text" => "❌انصراف", "callback_data" => "go_to_menu"]]
            ];

            $this->sendRequest("editMessageText", [
                "chat_id" => $this->chatId,
                "message_id" => $messageId,
                "text" => $messages[$userLanguage] ?? $messages['en'],
                "parse_mode" => "HTML",
                "reply_markup" => json_encode(["inline_keyboard" => $inlineKeyboard])
            ]);
        } elseif ($callbackData === "no_discount_code_star") {

            $this->fileHandler->saveState($this->chatId, "null");
            $userLanguage = $this->db->getUserLanguage($this->chatId);
            $tourId = $this->fileHandler->getTourId($this->chatId);
            $tourDetails = $this->db->getTourDetailsWithPrice($tourId);
            $registration = $this->db->getUserTourRegistration($this->chatId, $tourId);

            $tourName = $tourDetails['title'] ?? '';
            $starsTour = intval($tourDetails['price_star'] ?? 0);
            // $penaltyStars = intval($registration['penalty_amount'] ?? 0) * 3;

            $totalStars = $starsTour;


            $this->sendRequest("sendInvoice", [
                "chat_id" => $this->chatId,
                "title" => ($userLanguage === 'fa'
                    ? "پرداخت برای تور: {$tourName}"
                    : "Payment for Tour: {$tourName}"),


                "description" => ($userLanguage === 'fa'
                    ? "برای شرکت در تور '{$tourName}' باید {$starsTour} استار پرداخت کنید.\n"

                    : "To participate in '{$tourName}', you need to pay {$starsTour} Star.\n"),


                "payload" => "access_tour_{$tourId}",
                "currency" => "XTR",
                "prices" => [
                    ["label" => ($userLanguage === 'fa' ? "دسترسی به تور" : "Tour Access "), "amount" => 1]
                ],
                "start_parameter" => "get_access_to_tour"
            ]);
        } elseif ($callbackData === "proceed_to_payment_toman") {
            $userLanguage = 'fa';
            $tourId = $this->fileHandler->getTourId($this->chatId);
            $finalAmount = $this->fileHandler->getFinalAmount($this->chatId);
            $tourDetails = $this->db->getTourDetailsWithPrice($tourId);

            $paymentResponse = $this->zarinpalPaymentHandler->createZarinpalPayment($finalAmount, $this->chatId, $tourId);

            if ($paymentResponse && isset($paymentResponse['authority'])) {
                $authority = $paymentResponse['authority'];

                $this->db->insertUserPayment($this->chatId, $tourId, $finalAmount, $authority);

                $amountFormatted = number_format($finalAmount);
                $paymentUrl = "https://www.zarinpal.com/pg/StartPay/{$authority}";
                $tourName = $tourDetails['tour_name'] ?? '';

                $paymentMessages = [
                    'fa' => "✅ برای شرکت در تور '{$tourName}'، روی لینک پرداخت زیر کلیک کنید:\n\n"
                        . "[💳 پرداخت]({$paymentUrl})\n\n"
                        . "💰 *قیمت نهایی:* {$amountFormatted} تومان",
                    'en' => "✅ To join the tour '{$tourId}', click the payment link below:\n\n"
                        . "[💳 Pay Now]({$paymentUrl})\n\n"
                        . "💰 *Final Price:* {$amountFormatted} Toman"
                ];

                $this->sendRequest("editMessageText", [
                    "chat_id" => $this->chatId,
                    "message_id" => $messageId,
                    "text" => $paymentMessages[$userLanguage] ?? $paymentMessages['en'],
                    "parse_mode" => "Markdown"
                ]);
            } else {
                error_log("[Zarinpal Payment Error] Full Response: " . json_encode($paymentResponse));
                error_log("[Zarinpal Payment Error] Failed to get authority from Zarinpal for Chat ID: {$this->chatId} | Tour ID: {$tourId} | Amount: {$finalAmount}");
            }
        } elseif (str_starts_with($callbackData, 'register_active_')) {
            $tourId = intval(str_replace('register_active_', '', $callbackData));
            $this->startTourRegistrationProcess($chatId, $tourId, $messageId);
            return;
        }

        if ($callbackData !== null && str_starts_with($callbackData, 'select_vehicle_')) {
            preg_match('/select_vehicle_(.+)_(\d+)/', $callbackData, $matches);
            $vehicle = $matches[1];
            $tourId = intval($matches[2]);

            $this->fileHandler->setTempData($this->chatId, [
                'pending_tour_id' => $tourId,
                'selected_vehicle' => $vehicle,
                'quantity' => 1
            ]);

            $this->showQuantitySelector($chatId, $tourId, $messageId, 1);
            return;
        } elseif (str_starts_with($callbackData, 'change_quantity_')) {
            $parts = explode('_', $callbackData);
            $tourId = (int)$parts[2];
            $newQuantity = (int)$parts[3];

            $tempData = $this->fileHandler->getTempData($chatId);
            $tempData['quantity'] = $newQuantity;
            $this->fileHandler->setTempData($chatId, $tempData);

            $this->showQuantitySelector($chatId, $tourId, $messageId, $newQuantity);
            return;
        } elseif (str_starts_with($callbackData, 'confirm_quantity_')) {
            $parts = explode('_', $callbackData);
            $tourId = (int)$parts[2];
            $quantity = (int)$parts[3];

            $tempData = $this->fileHandler->getTempData($chatId);
            $tempData['quantity'] = $quantity;
            $this->fileHandler->setTempData($chatId, $tempData);

            $this->sendRequest("editMessageText", [
                "chat_id" => $this->chatId,
                "message_id" => $messageId,
                "text" => "تعداد " . $quantity . " نفر انتخاب شد. لطفاً روش پرداخت خود را انتخاب کنید:",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [["text" => "💳 کارت به کارت", "callback_data" => "pay_card_to_card_{$tourId}"]],
                        [["text" => "💵 پرداخت آنلاین", "callback_data" => "pay_with_toman_{$tourId}"]],
                        [["text" => "🔙 بازگشت (تغییر تعداد)", "callback_data" => "change_quantity_{$tourId}_{$quantity}"]]
                    ]
                ])
            ]);
            return;
        } elseif ($callbackData === 'no_op') {
            $this->sendRequest("answerCallbackQuery", ["callback_query_id" => $this->callbackQueryId]);
            return;
        } elseif ($callbackData === "manage_discounts") {
            $userLanguage = 'fa';

            $messages = [
                'fa' => "⚙️ <b>مدیریت کدهای تخفیف</b>\n\n"
                    . "📌 از گزینه های زیر برای مدیریت کدهای تخفیف استفاده کنید.",
                'en' => "⚙️ <b>Manage Discount Codes</b>\n\n"
                    . "📌 Use the options below to manage discount codes."
            ];

            $inlineKeyboard = [
                [["text" => $userLanguage === 'fa' ? "➕ افزودن کد جدید" : "➕ Add New Code", "callback_data" => "add_discount"]],
                [["text" => $userLanguage === 'fa' ? "📋 مشاهده کدهای فعال" : "📋 View Active Codes", "callback_data" => "view_discounts"]],
                [["text" => $userLanguage === 'fa' ? "🔙 بازگشت" : "🔙 Back", "callback_data" => "leader_finance_menu"]]
            ];

            $this->sendRequest("editMessageText", [
                "chat_id" => $this->chatId,
                "message_id" => $messageId,
                "text" => $messages['fa'],
                "parse_mode" => "HTML",
                "reply_markup" => json_encode(["inline_keyboard" => $inlineKeyboard])
            ]);
        } elseif ($callbackData === "add_discount") {
            $this->fileHandler->saveState($this->chatId, "awaiting_discount_code");
            $this->fileHandler->saveMessageId($this->chatId, $messageId);

            $messages = [
                'fa' => "🔹 <b>ایجاد کد تخفیف جدید</b>\n\n"
                    . "📌 لطفاً نام کد تخفیف را وارد کنید (مثال: <code>NEWYEAR2025</code>)",
                'en' => "🔹 <b>Create a New Discount Code</b>\n\n"
                    . "📌 Please enter the discount code name (Example: <code>NEWYEAR2025</code>)"
            ];

            $this->sendRequest("editMessageText", [
                "chat_id" => $this->chatId,
                "message_id" => $messageId,
                "text" => $messages['fa'],
                "parse_mode" => "HTML"
            ]);
        } elseif ($callbackData === "discount_type_percent" || $callbackData === "discount_type_fixed") {
            $this->fileHandler->saveState($this->chatId, "awaiting_discount_value");
            $this->fileHandler->saveDiscountType($this->chatId, $callbackData === "discount_type_percent" ? "percent" : "fixed");

            $messages = [
                'fa' => "📌 مقدار تخفیف را وارد کنید:\n\n"
                    . "🔹 اگر درصدی انتخاب کرده اید، مقدار عددی را وارد کنید. (مثلاً `۱۰` برای ۱۰٪)\n"
                    . "🔹 اگر مبلغ ثابت انتخاب کرده اید، مقدار تخفیف را به تومان وارد کنید. (مثلاً `50000` برای ۵۰,۰۰۰ تومان)",
                'en' => "📌 Enter the discount value:\n\n"
                    . "🔹 If you chose percentage, enter the number (e.g., `10` for 10%).\n"
                    . "🔹 If you chose fixed amount, enter the amount in Tomans (e.g., `50000` for 50,000 Tomans)."
            ];

            $this->sendRequest("editMessageText", [
                "chat_id" => $this->chatId,
                "message_id" => $messageId,
                "text" => $messages['fa'],
                "parse_mode" => "HTML"
            ]);
        } elseif ($callbackData === "view_discounts") {
            $userLanguage = 'fa';
            $discountCodes = $this->db->getAllDiscountCodes();

            if (empty($discountCodes)) {
                $messages = [
                    'fa' => "❌ هیچ کد تخفیفی وجود ندارد.",
                    'en' => "❌ No discount codes available."
                ];

                $this->sendRequest("editMessageText", [
                    "chat_id" => $this->chatId,
                    "message_id" => $messageId,
                    "text" => $messages['fa'],
                    "parse_mode" => "HTML"
                ]);
                return;
            }

            $messages = [
                'fa' => "📋 <b>لیست کدهای تخفیف فعال:</b>\n\nبرای مشاهده جزئیات روی هر کد بزنید 👇",
                'en' => "📋 <b>Active Discount Codes:</b>\n\nClick any code to view details 👇"
            ];

            $inlineKeyboard = [];

            foreach ($discountCodes as $discount) {
                $code = $discount['code'];
                $inlineKeyboard[] = [
                    ["text" => "🎟 $code", "callback_data" => "discount_details_$code"]
                ];
            }

            $inlineKeyboard[] = [
                ["text" => $userLanguage === 'fa' ? "🔙 بازگشت" : "🔙 Back", "callback_data" => "manage_discounts"]
            ];

            $this->sendRequest("editMessageText", [
                "chat_id" => $this->chatId,
                "message_id" => $messageId,
                "text" =>  $messages['fa'],
                "parse_mode" => "HTML",
                "reply_markup" => json_encode(["inline_keyboard" => $inlineKeyboard])
            ]);
        } elseif (str_starts_with($callbackData, "delete_discount_")) {
            $code = str_replace("delete_discount_", "", $callbackData);
            $userLanguage = 'fa';

            $messages = [
                'fa' => "⚠️ آیا از حذف کد تخفیف <b>$code</b> اطمینان دارید؟",
                'en' => "⚠️ Are you sure you want to delete the discount code <b>$code</b>?"
            ];

            $inlineKeyboard = [
                [["text" => "✅ بله", "callback_data" => "confirm_delete_discount_$code"]],
                [["text" => "❌ خیر", "callback_data" => "view_discounts"]]
            ];

            $this->sendRequest("editMessageText", [
                "chat_id" => $this->chatId,
                "message_id" => $messageId,
                "text" => $messages['fa'],
                "parse_mode" => "HTML",
                "reply_markup" => json_encode(["inline_keyboard" => $inlineKeyboard])
            ]);
        } elseif (str_starts_with($callbackData, "confirm_delete_discount_")) {
            $code = str_replace("confirm_delete_discount_", "", $callbackData);
            $userLanguage = $this->db->getUserLanguage($this->chatId);

            $this->db->deleteDiscountCode($code);

            $messages = [
                'fa' => "✅ کد تخفیف <b>$code</b> با موفقیت حذف شد.",
                'en' => "✅ Discount code <b>$code</b> has been successfully deleted."
            ];

            $this->sendRequest("editMessageText", [
                "chat_id" => $this->chatId,
                "message_id" => $messageId,
                "text" => $messages['fa'],
                "parse_mode" => "HTML"
            ]);
        } elseif ($callbackData === "max_uses_unlimited") {
            $this->fileHandler->saveState($this->chatId, "awaiting_expiry_date");
            $this->fileHandler->saveMaxUses($this->chatId, null);
            $userLanguage = $this->db->getUserLanguage($this->chatId);


            $messages = [
                'fa' => "📌 تاریخ انقضای کد تخفیف را مشخص کنید. (فرمت: YYYY-MM-DD)\n"
                    . "🔹 یا دکمه <b>نامحدود</b> را بزنید.",
                'en' => "📌 Specify the expiration date for this discount code. (Format: YYYY-MM-DD)\n"
                    . "🔹 Or press <b>Unlimited</b>."
            ];

            $inlineKeyboard = [
                [["text" => "♾ نامحدود", "callback_data" => "expiry_date_unlimited"]]
            ];

            $this->sendRequest("editMessageText", [
                "chat_id" => $this->chatId,
                "message_id" => $messageId,
                "text" => $messages['fa'],
                "parse_mode" => "HTML",
                "reply_markup" => json_encode(["inline_keyboard" => $inlineKeyboard])
            ]);
        } elseif ($callbackData === "expiry_date_unlimited") {
            $this->fileHandler->saveState($this->chatId, null);
            $userLanguage = 'fa';

            $discountCodeData = $this->fileHandler->getDiscountData($this->chatId);
            $this->db->saveDiscountCode(
                $discountCodeData['code'],
                $discountCodeData['type'],
                $discountCodeData['value'],
                $discountCodeData['max_uses'],
                null
            );

            $messages = [
                'fa' => "✅ کد تخفیف بدون تاریخ انقضا با موفقیت ایجاد شد!",
                'en' => "✅ The discount code with no expiration date has been successfully created!"
            ];

            $this->sendRequest("editMessageText", [
                "chat_id" => $this->chatId,
                "message_id" => $messageId,
                "text" => $messages[$userLanguage] ?? $messages['en'],
                "parse_mode" => "HTML"
            ]);

            $this->fileHandler->clearDiscountData($this->chatId);
        } elseif (str_starts_with($callbackData, "discount_details_")) {
            $code = str_replace("discount_details_", "", $callbackData);
            $userLanguage = 'fa';
            $discount = $this->db->getDiscountDetails($code); // باید در دیتابیس باشه

            if (!$discount) {
                $messages = [
                    'fa' => "❌ کد تخفیف یافت نشد.",
                    'en' => "❌ Discount code not found."
                ];
                $this->sendRequest("answerCallbackQuery", [
                    "callback_query_id" => $callbackQuery['id'],
                    "text" => $messages[$userLanguage] ?? $messages['en'],
                    "show_alert" => true
                ]);
                return;
            }

            $type = $discount['discount_type'] === 'percent'
                ? ($userLanguage === 'fa' ? "درصدی" : "Percentage")
                : ($userLanguage === 'fa' ? "مبلغ ثابت" : "Fixed Amount");

            $value = $discount['discount_value'];
            $used = $discount['used_count'];
            $maxUses = $discount['max_uses'] ?? ($userLanguage === 'fa' ? "نامحدود" : "Unlimited");
            $expiry = $discount['expires_at'] ?? ($userLanguage === 'fa' ? "نامحدود" : "Unlimited");

            $text = $userLanguage === 'fa'
                ? "🎟 <b>جزئیات کد تخفیف:</b>\n\n"
                . "🔹 <b>کد:</b> $code\n"
                . "📦 <b>نوع:</b> $type\n"
                . "💰 <b>مقدار:</b> $value\n"
                . "📌 <b>استفاده شده:</b> $used / $maxUses\n"
                . "📅 <b>تاریخ انقضا:</b> $expiry"
                : "🎟 <b>Discount Code Details:</b>\n\n"
                . "🔹 <b>Code:</b> $code\n"
                . "📦 <b>Type:</b> $type\n"
                . "💰 <b>Value:</b> $value\n"
                . "📌 <b>Used:</b> $used / $maxUses\n"
                . "📅 <b>Expiry:</b> $expiry";

            $this->sendRequest("editMessageText", [
                "chat_id" => $this->chatId,
                "message_id" => $messageId,
                "text" => $text,
                "parse_mode" => "HTML",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [
                            ["text" => "🗑 حذف", "callback_data" => "delete_discount_$code"],
                            //                            ["text" => "⚙ ویرایش", "callback_data" => "edit_discount_$code"]
                        ],
                        [
                            ["text" => $userLanguage === 'fa' ? "🔙 بازگشت" : "🔙 Back", "callback_data" => "view_discounts"]
                        ]
                    ]
                ])
            ]);
        }
        if (str_starts_with($callbackData, 'birthdate-')) {
            $datePicker = new DatePicker();
            $result = $datePicker->handleCallback($callbackData);

            if ($result['status'] === 'confirmed') {
                $year = $result['date']['year'];
                $month = $result['date']['month'];
                $day = $result['date']['day'];

                [$gy, $gm, $gd] = $this->jalaliToGregorian($year, $month, $day);
                $birthDateGregorian = sprintf('%04d-%02d-%02d', $gy, $gm, $gd);

                $tempData = $this->fileHandler->getTempData($chatId);
                $tempData['year'] = $year;
                $tempData['month'] = $month;
                $tempData['day'] = $day;
                $tempData['date_of_birth'] = $birthDateGregorian;
                $this->fileHandler->setTempData($chatId, $tempData);

                $this->fileHandler->saveState($chatId, 'awaiting_user_phone');

                $this->sendRequest("editMessageText", [
                    "chat_id" => $chatId,
                    "message_id" => $this->fileHandler->getMessageId($chatId),
                    "text" => "🎉 تاریخ تولد شما با موفقیت ثبت شد!\n\n📱 لطفاً شماره موبایل خود را وارد کنید تا بتونیم راه های ارتباطی مون رو کامل کنیم:",
                    "reply_markup" => json_encode([
                        "inline_keyboard" => [
                            [
                                ["text" => "🔙 بازگشت", "callback_data" => "user_birthdate"],
                                ["text" => "❌ انصراف", "callback_data" => "go_to_menu"]
                            ]
                        ]
                    ])
                ]);
                //                $this->deleteMessageWithDelay();
                //                $this->sendRequest("sendMessage", [
                //                    "chat_id" => $chatId,
                //                    "text" => "🎉 تاریخ تولد شما با موفقیت ثبت شد!\n\n📱 لطفاً شماره موبایل خود را ارسال کنید یا به صورت دستی تایپ کنید:",
                //                    "reply_markup" => json_encode([
                //                        "keyboard" => [
                //                            [
                //                                ["text" => "📱 ارسال شماره من", "request_contact" => true]
                //                            ],
                //                            [
                //                                ["text" => "🔙 بازگشت", "callback_data" => "user_birthdate"],
                //                                ["text" => "❌ انصراف", "callback_data" => "go_to_menu"]
                //                            ]
                //                        ],
                //                        "resize_keyboard" => true,
                //                        "one_time_keyboard" => true
                //                    ])
                //                ]);

            } elseif ($result['status'] === 'update') {
                $this->sendRequest("editMessageText", [
                    "chat_id" => $chatId,
                    "message_id" => $this->fileHandler->getMessageId($chatId),
                    "text" => $result['new_data']['text'],
                    "parse_mode" => "HTML",
                    "reply_markup" => $result['new_data']['reply_markup']
                ]);
            }
        }


        if (str_starts_with($callbackData, 'birthday-')) {
            $datePicker = new DatePicker();
            $result = $datePicker->handleCallback($callbackData);

            if ($result['status'] === 'confirmed') {
                $year = $result['date']['year'];
                $month = $result['date']['month'];
                $day = $result['date']['day'];

                [$gy, $gm, $gd] = $this->jalaliToGregorian($year, $month, $day);
                $birthDateGregorian = sprintf('%04d-%02d-%02d', $gy, $gm, $gd);

                $LeaderData = $this->fileHandler->getLeaderData($chatId);
                $LeaderData['year'] = $year;
                $LeaderData['month'] = $month;
                $LeaderData['day'] = $day;
                $LeaderData['date_of_birth'] = $birthDateGregorian;
                $this->fileHandler->setLeaderData($chatId, $LeaderData);

                $this->fileHandler->saveState($chatId, 'awaiting_leader_phone');

                $this->sendRequest("editMessageText", [
                    "chat_id" => $chatId,
                    "message_id" => $this->fileHandler->getMessageId($chatId),
                    "text" => "🎉 تاریخ تولد شما با موفقیت ثبت شد!\n\n📱 لطفاً شماره موبایل خود را وارد کنید تا بتونیم راه های ارتباطی مون رو کامل کنیم:",
                    "reply_markup" => json_encode([
                        "inline_keyboard" => [
                            [
                                ["text" => "🔙 بازگشت", "callback_data" => "leader_birthdate"],
                                ["text" => "❌ انصراف", "callback_data" => "go_to_menu"]
                            ]
                        ]
                    ])
                ]);
            } elseif ($result['status'] === 'update') {
                $this->sendRequest("editMessageText", [
                    "chat_id" => $chatId,
                    "message_id" => $this->fileHandler->getMessageId($chatId),
                    "text" => $result['new_data']['text'],
                    "parse_mode" => "HTML",
                    "reply_markup" => $result['new_data']['reply_markup']
                ]);
            } elseif ($result['status'] === 'back') {
                // اینجا خودت تعیین می کنی که برگشت به کجا باشه (مثلا مرحله nickname)
                $telegramName = $this->db->getUserFullName($this->chatId);
                $leader_fullname = $this->fileHandler->getLeaderName($this->chatId);
                $this->fileHandler->saveMessageId($this->chatId, $messageId);
                if ($this->fileHandler->saveState($chatId, 'awaiting_leader_nickname')) {
                    $response = $this->sendRequest("editMessageText", [
                        "chat_id" => $chatId,
                        "message_id" => $messageId,
                        "text" => "لطفاً نام مستعار خود را دستی وارد کنید:\nیا یکی از موارد زیر را انتخاب نمایید:",
                        "reply_markup" => json_encode([
                            "inline_keyboard" => [
                                [["text" => "نام تلگرام ($telegramName)", "callback_data" => "choice_leader_telegram_name"]],
                                [["text" => "نام واقعی ($leader_fullname)", "callback_data" => "choice_leader_real_name"]],
                                [
                                    ["text" => "🔙 بازگشت", "callback_data" => "leader_lastname"],
                                    ["text" => "❌ انصراف", "callback_data" => "go_to_menu"]
                                ]
                            ]
                        ])
                    ]);
                }
            }
        }
        if (strpos($callbackData, 'select_province_') === 0) {
            $province = substr($callbackData, strlen('select_province_'));
            $state = $this->fileHandler->getState($chatId);

            $locationHandler = new locationHandler();
            $citiesKeyboard = $locationHandler->getCitiesKeyboard($province);
            if ($state === 'awaiting_user_province') {
                $tempData = $this->fileHandler->getTempData($chatId);
                $tempData['province'] = $province;
                $this->fileHandler->setTempData($chatId, $tempData);
                $this->fileHandler->saveState($chatId, 'awaiting_user_city');
                $text = "🏙️ <b>قدم بعدی:</b>\n"
                    . "لطفاً شهر محل سکونت خود را از لیست زیر انتخاب کنید:";
            } elseif ($state === 'awaiting_leader_province') {
                $leaderData = $this->fileHandler->getLeaderData($chatId);
                $leaderData['province'] = $province;
                $this->fileHandler->setLeaderData($chatId, $leaderData);
                $this->fileHandler->saveState($chatId, 'awaiting_leader_city');
                $text = "🏙️ <b>قدم بعدی:</b>\n"
                    . "لطفاً شهر محل سکونت خود را از لیست زیر انتخاب کنید:";
            } else {
                $text = "❌ وضعیت نامشخص است.";
            }

            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "parse_mode" => "HTML",
                "text" => $text,
                "reply_markup" => json_encode($citiesKeyboard)
            ]);
       } else if (strpos($callbackData, 'select_city_') === 0) {
            $city = substr($callbackData, strlen('select_city_'));
            $state = $this->fileHandler->getState($chatId);
            $locationHandler = new locationHandler();
            
            if ($state === 'awaiting_user_city') {
                // 🛑 تغییر وضعیت فوری برای جلوگیری از اجرای همزمان چند درخواست (Race Condition)
                $this->fileHandler->saveState($chatId, 'processing');

                $tempData = $this->fileHandler->getTempData($chatId);

                $tempData['city'] = $city;
                $explorer = [
                    'first_name' => $tempData['first_name'],
                    'last_name' => $tempData['last_name'],
                    'nick_name' => $tempData['nick_name'],
                    'date_of_birth' => $tempData['date_of_birth'],
                    'phone' => $tempData['phone'],
                    'city' => $tempData['city']
                ];

                $this->fileHandler->setTempData($chatId, $tempData);
                $this->db->insertExplorer($chatId, $explorer);
                $this->fileHandler->clearTempData($chatId);
                
                
                $this->deleteMessageWithDelay();

                $this->sendRequest("sendMessage", [
                    "chat_id" => $chatId,
                    "text" => "\n" . "🎉 اطلاعات شما با موفقیت ثبت شد! 🎉" . "\n" . "\n" .
                        "👤 نام و نام خانوادگی: {$tempData['first_name']} {$tempData['last_name']}\n" .
                        "✨ نام مستعار: {$tempData['nick_name']}\n" .
                        "🎂 تاریخ تولد: " . $this->gregorianToJalali($tempData['date_of_birth'] ?? '2000-01-01') . "\n" . // اصلاح متغیر leaderData به tempData
                        "📞 تلفن: {$tempData['phone']}\n" .
                        "🏙️ شهر: {$tempData['city']}\n\n",
                    "reply_markup" => $this->getMainKeyboard()
                ]);

                $adminMessage = "<b>🧑‍🌾‍ طبیعت گرد جدید ثبت نام کرد</b>\n\n";
                $adminMessage .= "<b>اطلاعات شخصی:</b>\n" . "<blockquote>" . "▫️ <b>نام:</b> " . htmlspecialchars($tempData['first_name'] . ' ' . $tempData['last_name']) . "\n" . "▫️ <b>نام مستعار:</b> " . $tempData['nick_name'] . "\n" . "▫️ <b>شناسه:</b> <code>" . $this->chatId . "</code>\n" . "▫️ <b>لینک مستقیم:</b> <a href='tg://user?id={$this->chatId}'>تماس با کاربر</a>" . "</blockquote>\n";
                $adminMessage .= "<b>اطلاعات تماس:</b>\n" . "<blockquote>" . "▫️ <b>تلفن:</b> <code>" . htmlspecialchars($tempData['phone']) . "</code></blockquote>\n";

                $admins = $this->db->getAdmins();

                foreach ($admins as $admin) {
                    $this->sendRequest(
                        "sendMessage",
                        [
                            "chat_id" => $admin['chat_id'],
                            "text" => $adminMessage,
                            "parse_mode" => "HTML"
                        ]
                    );
                }
                
                $this->fileHandler->saveState($chatId, null);
                $this->checkPendingTourAfterRegister();
            } elseif ($state === 'awaiting_leader_city') {
                // ثبت نهایی برای لیدر
                $leaderData = $this->fileHandler->getLeaderData($chatId);

                $leaderData['city'] = $city;

                $this->fileHandler->setLeaderData($chatId, $leaderData);
                $this->fileHandler->saveState($chatId, 'awaiting_leader_address'); // یا مرحله بعد
                $response = $this->sendRequest("editMessageText", [
                    "chat_id" => $chatId,
                    "text" =>
                    "👤 نام: " . $leaderData['first_name'] . "\n" .
                        "📝 نام خانوادگی: " . $leaderData['last_name'] . "\n" .
                        "⭐ نام مستعار: " . $leaderData['nick_name'] . "\n" .
                        "🎂 تاریخ تولد: " . $this->gregorianToJalali($leaderData['date_of_birth']) . "\n" .
                        "📱 تلفن: " . $leaderData['phone'] . "\n" .
                        "🏙️ شهر: " . $leaderData['city'] . "\n\n" .
                        "📍 لطفاً آدرس دقیق محل سکونت خود را وارد کنید:",

                    "message_id" => $messageId,
                    "reply_markup" => json_encode([
                        "inline_keyboard" => [
                            [
                                ["text" => "🔙 بازگشت", "callback_data" => "leader_city"],
                                ["text" => "❌ انصراف", "callback_data" => "go_to_menu"]
                            ]
                        ]
                    ])
                ]);
            }
        }

        if (preg_match('/^postToBoth_(\d+)$/', $callbackData, $matches)) {
            $tourId = (int)$matches[1];

            $tourData = $this->db->getTourById($tourId);
            if (!$tourData) {
                $this->sendRequest("answerCallbackQuery", [
                    "callback_query_id" => $callbackQuery['id'],
                    'text' => '❌ تور موردنظر یافت نشد.',
                    'show_alert' => true
                ]);
                return;
            }

            $summaryText = $this->generateTourDetailsText($tourId);

            $replyMarkup = json_encode([
                'inline_keyboard' => [
                    [
                        [
                            'text' => '🏖 ثبت نام در تور',
                            'url'  => $this->botLink . "register_{$tourId}"
                        ]
                    ],

                    [
                        [
                            'text' => '🕵️ ثبت نام لیدر',
                            'url'  => $this->botLink . "join_leader"
                        ],
                        [
                            'text' => '👨‍⚖️ ثبت نام طبیعت گرد',
                            'url'  => $this->botLink . "join_user"
                        ]

                    ]

                ]

            ], JSON_UNESCAPED_UNICODE);

            $sendTo = [];

            if ($channel = $this->db->getExplorerChannel($chatId)) {
                $sendTo['channel'] = $channel;
            }

            if ($group = $this->db->getExplorerGroup($chatId)) {
                $sendTo['group'] = $group;
            }

            foreach ($sendTo as $type => $targetChatId) {
                if (!empty($tourData['banner']) && mb_strlen($summaryText, 'UTF-8') <= 1024) {
                    $response = $this->sendRequest('sendPhoto', [
                        'chat_id'      => $targetChatId,
                        'photo'        => $tourData['banner'],
                        'caption'      => $summaryText,
                        'parse_mode'   => 'HTML',
                        'reply_markup' => $replyMarkup
                    ]);
                } else {
                    $response = $this->sendRequest('sendMessage', [
                        'chat_id'      => $targetChatId,
                        'text'         => $summaryText,
                        'parse_mode'   => 'HTML',
                        'reply_markup' => $replyMarkup
                    ]);
                }

                if (!empty($response['ok']) && !empty($response['result'])) {
                    $messageId = $response['result']['message_id'];
                    $chatIdSent = $response['result']['chat']['id'];

                    if ($type === 'channel') {
                        $this->db->updateTourField($tourId, 'channel_id', $chatIdSent);
                        $this->db->updateTourField($tourId, 'channel_message_id', $messageId);
                    } elseif ($type === 'group') {
                        $this->db->updateTourField($tourId, 'group_id', $chatIdSent);
                        $this->db->updateTourField($tourId, 'group_message_id', $messageId);
                    }
                }
            }

            // پاسخ به کاربر
            $this->sendRequest("answerCallbackQuery", [
                "callback_query_id" => $callbackQuery['id'],
                'text' => '✅ تور در کانال و گروه ارسال شد.',
                'show_alert' => false
            ]);
        } elseif (str_starts_with($callbackData, "post_channel_")) {
            $tourId = str_replace("post_channel_", "", $callbackData);
            $tourData = $this->db->getTourById($tourId);
            if (!$tourData) {
                $this->sendRequest("answerCallbackQuery", [
                    "callback_query_id" => $callbackQuery['id'],
                    'text' => '❌ تور موردنظر یافت نشد.',
                    'show_alert' => true
                ]);
                return;
            }

            $summaryText = $this->generateTourDetailsText($tourId);
            $channel = $this->db->getExplorerChannel($chatId);
            $replyMarkup = json_encode([
                'inline_keyboard' => [
                    [
                        [
                            'text' => '🏖 ثبت نام در تور',
                            'url'  => $this->botLink . "register_{$tourId}"
                        ]
                    ],
                    [
                        [
                            'text' => '🕵️ ثبت نام لیدر',
                            'url'  => $this->botLink . "join_leader"
                        ],
                        [
                            'text' => '👨‍⚖️ ثبت نام طبیعت گرد',
                            'url'  => $this->botLink . "join_user"
                        ]
                    ]
                ]
            ], JSON_UNESCAPED_UNICODE);

            if (!empty($tourData['banner']) && mb_strlen($summaryText, 'UTF-8') <= 1024) {
                $response = $this->sendRequest('sendPhoto', [
                    'chat_id'      => $channel,
                    'photo'        => $tourData['banner'],
                    'caption'      => $summaryText,
                    'parse_mode'   => 'HTML',
                    'reply_markup' => $replyMarkup
                ]);
            } else {
                $response = $this->sendRequest('sendMessage', [
                    'chat_id'      => $channel,
                    'text'         => $summaryText,
                    'parse_mode'   => 'HTML',
                    'reply_markup' => $replyMarkup
                ]);
            }

            if (!empty($response['ok']) && !empty($response['result'])) {
                $messageId = $response['result']['message_id'];
                $chatIdSent = $response['result']['chat']['id'];

                $this->db->updateTourField($tourId, 'channel_id', $chatIdSent);
                $this->db->updateTourField($tourId, 'channel_message_id', $messageId);
            }
            $this->sendRequest("answerCallbackQuery", [
                "callback_query_id" => $callbackQuery['id'],
                'text' => '✅ تور در کانال ارسال شد.',
                'show_alert' => false
            ]);
        } else if (str_starts_with($callbackData, 'broadcast_tour_')) {
            $tourId = (int)str_replace('broadcast_tour_', '', $callbackData);
            $this->fileHandler->saveState($this->chatId, 'awaiting_broadcast_message_' . $tourId);
            $this->sendRequest("editMessageText", [
                "chat_id" => $this->chatId,
                "message_id" => $messageId,
                "text" => "لطفاً پیامی که می‌خواهید به تمام ثبت‌نام‌کنندگان این تور ارسال شود را بفرستید (متن، عکس، ویدیو و...).",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [["text" => "❌ لغو", "callback_data" => "tour_details_" . $tourId]]
                    ]
                ])
            ]);
            return;
        } elseif (str_starts_with($callbackData, 'confirm_broadcast_')) {
            $tourId = (int)str_replace('confirm_broadcast_', '', $callbackData);
            $messageToBroadcast = $this->fileHandler->getTemporaryData($this->chatId)['broadcast_message'];
            $registeredUsers = $this->db->getRegisteredUsersByTourId($tourId);


            if (empty($registeredUsers)) {
                $this->sendRequest("editMessageText", [
                    "chat_id" => $this->chatId,
                    "message_id" => $messageId,
                    "text" => "❌ هیچ کاربری برای ارسال پیام در این تور ثبت نام نکرده است."
                ]);
                return;
            }
            $tour = $this->db->getTourById($tourId);
            $tourTitle = $tour['title'] ?? 'تور شما';

            // آرایه‌ای برای ذخیره وضعیت ارسال هر کاربر
            $userStatus = [];
            $userFullNames = [];
            foreach ($registeredUsers as $user) {
                $userInfo = $this->db->registeredExplorerByUserId($user['explorer_id']);
                $fullName = trim(($userInfo['first_name'] ?? '') . ' ' . ($userInfo['last_name'] ?? ''));
                $userFullNames[$user['explorer_id']] = $fullName ?: "کاربر " . $user['explorer_id'];
                $userStatus[$user['explorer_id']] = '⏳'; // در انتظار
            }

            // ساخت و ارسال پیام ابتدایی وضعیت
            $statusText = "📊 وضعیت ارسال پیام همگانی:\n\n";
            foreach ($userStatus as $userId => $status) {
                $statusText .= "{$status} " . htmlspecialchars($userFullNames[$userId]) . "\n";
            }

            $statusMessage = $this->sendRequest("editMessageText", [
                "chat_id" => $this->chatId,
                "message_id" => $messageId,
                "text" => $statusText,
                "parse_mode" => "HTML"
            ]);

            $statusMessageId = $statusMessage['result']['message_id'] ?? $messageId;

            $successCount = 0;
            $failCount = 0;

            foreach ($registeredUsers as $user) {
                $chatIdToSend = $user['explorer_id'];


                $headerText = "📢 پیامی در مورد تور «<b>" . htmlspecialchars($tourTitle) . "</b>»\n\n---\n\n";
                $response = null;
                $messageType = $messageToBroadcast['type'];

                if ($messageType === 'text') {
                    $response = $this->sendRequest('sendMessage', [
                        'chat_id' => $chatIdToSend,
                        'text' => $headerText . $messageToBroadcast['text'],
                        'parse_mode' => 'HTML'
                    ]);
                } else {
                    $newCaption = $headerText . ($messageToBroadcast['caption'] ?? '');
                    $method = 'send' . ucfirst($messageType);
                    $response = $this->sendRequest($method, [
                        'chat_id' => $chatIdToSend,
                        $messageType => $messageToBroadcast['file_id'],
                        'caption' => $newCaption,
                        'parse_mode' => 'HTML'
                    ]);
                }

                if ($response && $response['ok']) {
                    $successCount++;
                    $userStatus[$chatIdToSend] = '✅'; // موفق
                } else {
                    $failCount++;
                    $userStatus[$chatIdToSend] = '❌'; // ناموفق
                    error_log("Broadcast failed for user {$chatIdToSend}: " . ($response['description'] ?? 'Unknown Error'));
                }

                // به‌روزرسانی پیام وضعیت به صورت زنده
                $statusText = "📊 وضعیت ارسال پیام همگانی:\n\n";
                foreach ($userStatus as $userId => $status) {
                    $statusText .= "{$status} " . htmlspecialchars($userFullNames[$userId]) . "\n";
                }

                // برای جلوگیری از خطا، هر بار که لیست را آپدیت میکنیم چک میکنیم که متن تغییر کرده باشد
                // این کار از ارسال درخواست های تکراری به تلگرام جلوگیری میکند
                static $lastStatusText = '';
                if ($lastStatusText !== $statusText) {
                    $this->sendRequest("editMessageText", [
                        "chat_id" => $this->chatId,
                        "message_id" => $statusMessageId,
                        "text" => $statusText,
                        "parse_mode" => "HTML"
                    ]);
                    $lastStatusText = $statusText;
                }

                usleep(500000); // تاخیر 0.5 ثانیه‌ای برای جلوگیری از محدودیت تلگرام
            }

            // ارسال گزارش نهایی
            $finalReport = "\n\n---\nارسال پیام به پایان رسید.\n\n"
                . "✅ موفق: {$successCount} نفر\n"
                . "❌ ناموفق: {$failCount} نفر";

            $this->sendRequest("editMessageText", [
                "chat_id" => $this->chatId,
                "message_id" => $statusMessageId,
                "text" => $statusText . $finalReport,
                "parse_mode" => "HTML",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [["text" => "🔙 بازگشت به جزئیات تور", "callback_data" => "tour_details_" . $tourId]]
                    ]
                ])
            ]);

            $this->fileHandler->clearTemporaryData($this->chatId);
            $this->fileHandler->saveState($this->chatId, null);
            return;
        }else if (str_starts_with($callbackData, 'cancel_broadcast_')) {
            $tourId = (int)str_replace('cancel_broadcast_', '', $callbackData);
            $this->fileHandler->clearTemporaryData($this->chatId);
            $this->fileHandler->saveState($this->chatId, null);

            $this->sendRequest("editMessageText", [
                "chat_id" => $this->chatId,
                "message_id" => $messageId,
                "text" => "ارسال پیام لغو شد.",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [["text" => "🔙 بازگشت به جزئیات تور", "callback_data" => "tour_details_" . $tourId]]
                    ]
                ])
            ]);
            return;
        } elseif (str_starts_with($callbackData, "post_group_")) {
            $tourId = str_replace("post_group_", "", $callbackData);
            $tourData = $this->db->getTourById($tourId);
            if (!$tourData) {
                $this->sendRequest("answerCallbackQuery", [
                    "callback_query_id" => $callbackQuery['id'],
                    'text' => '❌ تور موردنظر یافت نشد.',
                    'show_alert' => true
                ]);
                return;
            }

            $summaryText = $this->generateTourDetailsText($tourId);
            $group = $this->db->getExplorerGroup($chatId);
            $replyMarkup = json_encode([
                'inline_keyboard' => [
                    [
                        [
                            'text' => '🏖 ثبت نام در تور',
                            'url'  => $this->botLink . "register_{$tourId}"
                        ]
                    ],
                    [
                        [
                            'text' => '🕵️ ثبت نام لیدر',
                            'url'  => $this->botLink . "join_leader"
                        ],
                        [
                            'text' => '👨‍⚖️ ثبت نام طبیعت گرد',
                            'url'  => $this->botLink . "join_user"
                        ]
                    ]
                ]
            ], JSON_UNESCAPED_UNICODE);

            if (!empty($tourData['banner']) && mb_strlen($summaryText, 'UTF-8') <= 1024) {
                $response = $this->sendRequest('sendPhoto', [
                    'chat_id'      => $group,
                    'photo'        => $tourData['banner'],
                    'caption'      => $summaryText,
                    'parse_mode'   => 'HTML',
                    'reply_markup' => $replyMarkup
                ]);
            } else {
                $response = $this->sendRequest('sendMessage', [
                    'chat_id'      => $group,
                    'text'         => $summaryText,
                    'parse_mode'   => 'HTML',
                    'reply_markup' => $replyMarkup
                ]);
            }

            if (!empty($response['ok']) && !empty($response['result'])) {
                $messageId = $response['result']['message_id'];
                $chatIdSent = $response['result']['chat']['id'];

                $this->db->updateTourField($tourId, 'group_id', $chatIdSent);
                $this->db->updateTourField($tourId, 'group_message_id', $messageId);
            }

            $this->sendRequest("answerCallbackQuery", [
                "callback_query_id" => $callbackQuery['id'],
                'text' => '✅ تور در گروه ارسال شد.',
                'show_alert' => false
            ]);
        }


        if ($callbackData === 'leader_bot_setting') {

            $botUsername = "Tourambot";
            $buttons = [
                [
                    ['text' => '📢 افزودن ربات به کانال', 'url' => "https://t.me/$botUsername?startchannel=true"],
                ],
                [

                    ['text' => '💬 افزودن ربات به گروه', 'url' => "https://t.me/$botUsername?startgroup=true"],
                ],
                [["text" => "🔙 بازگشت", "callback_data" => "leader_dashboard"]]

            ];

            $this->sendRequest('editMessageText', [
                'chat_id' => $chatId,
                'message_id' => $messageId,
                'text' => "🔧 برای افزودن ربات در کانال و گروه لطفاً انتخاب کن:\n",
                'reply_markup' => json_encode(['inline_keyboard' => $buttons], JSON_UNESCAPED_UNICODE)
            ]);
        }
        if ($callbackData === 'instructor_wallet_menu') {
            $walletData = $this->db->getUserWallet($this->chatId);

            if (!$walletData) {
                $this->sendRequest("sendMessage", [
                    "chat_id" => $this->chatId,
                    "text" => "❌ متاسفانه اطلاعات کیف پول شما پیدا نشد. لطفاً دوباره امتحان کنید."
                ]);
                return;
            }
            $withdrawableToman    = $this->db->getWithdrawableBalance($chatId, 'toman');
            $nonWithdrawableToman = $this->db->getNonWithdrawableBalance($chatId, 'toman');
            $pendingToman         = $this->db->getPendingBalance($chatId, 'toman');

            // ۲. محاسبه موجودی کل
            $totalTomanBalance = $withdrawableToman + $nonWithdrawableToman + $pendingToman;
            $walletBalanceToman = $walletData['available_toman'] ?? 0;
            $walletBalanceStar = $walletData['available_star'] ?? 0;

            //            $messageText = "💳 <b>اطلاعات کیف پول شما:</b>\n\n";
            //            $messageText .= "🔸 <b>موجودی قابل برداشت (تومان):</b> {$walletBalanceToman} تومان\n";
            //            $messageText .= "🔸 <b>موجودی قابل برداشت (استار):</b> {$walletBalanceStar} استار\n";

            $messageText = "📊 <b>داشبورد مالی شما</b>\n\n";
            $messageText .= "سلام! در اینجا می توانید وضعیت کامل حساب مالی خود را مشاهده کنید.\n\n";

            $messageText .= "💵 <b>موجودی تومانی</b>\n";
            $messageText .= "<blockquote>";
            // $messageText .= "▫️ <b>کل موجودی:</b> <code>" . number_format($totalTomanBalance) . "</code> تومان\n";
            $messageText .= "▫️ <b>قابل برداشت:</b> <code>" . number_format($walletBalanceToman) . "</code> تومان\n";
            $messageText .= "▫️ <b>امانی:</b> <code>" . number_format($pendingToman) . "</code> تومان\n";
            $messageText .= "▫️ <b>غیرقابل برداشت:</b> <code>" . number_format($nonWithdrawableToman) . "</code> تومان";
            $messageText .= "</blockquote>\n";

            $transactionDetailsText = "";
            $pendingRequest = $this->db->getPendingWithdrawRequest($chatId);

            if ($pendingRequest) {
                //                $currencyText = $pendingRequest['currency'] === 'toman' ? 'تومان' : 'استار';
                $currencyText = 'تومان';
                $transactionDetailsText .= "<b>⏳ وضعیت برداشت وجه</b>\n";
                $transactionDetailsText .= "<blockquote>";
                $transactionDetailsText .= "▫️ <b>مبلغ:</b> <code>" . number_format($pendingRequest['amount']) . "</code> {$currencyText}\n";
                $transactionDetailsText .= "▫️ <b>وضعیت:</b> در انتظار بررسی ادمین";
                $transactionDetailsText .= "</blockquote>\n";
            }
            // else {
            $lastTransaction = $this->db->getLastTransaction($chatId);
            if ($lastTransaction) {
                $amount = $lastTransaction['amount'];
                $sign = $amount >= 0 ? '➕' : '➖';
                $formattedAmount = number_format(abs($amount));
                //                    $currencyText = $lastTransaction['currency'] === 'toman' ? 'تومان' : 'استار';
                //  $date = jdate('Y/m/d H:i', strtotime($lastTransaction['created_at']));
                $currencyText = 'تومان';
                $transactionDetailsText .= "<b>🧾 آخرین تراکنش شما</b>\n";
                $transactionDetailsText .= "<blockquote>";
                $transactionDetailsText .= "▫️ <b>مبلغ:</b> {$sign} <code>" . $formattedAmount . "</code> {$currencyText}\n";
                $transactionDetailsText .= "▫️ <b>توضیحات:</b> " . htmlspecialchars($lastTransaction['description'] ?? '---') . "\n";
                // $transactionDetailsText .= "▫️ <b>تاریخ:</b> " . $date;
                $transactionDetailsText .= "</blockquote>\n";
            } else {
                $transactionDetailsText .= "<b>🧾 آخرین تراکنش شما</b>\n";
                $transactionDetailsText .= "<blockquote>هنوز تراکنشی برای شما ثبت نشده است.</blockquote>\n";
            }
            // }

            $messageText .= "\n" . $transactionDetailsText;


            $this->sendRequest("editMessageText", [
                "chat_id" => $this->chatId,
                "text" => $messageText,
                "message_id" => $messageId,
                "parse_mode" => "HTML",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [['text' => 'برداشت وجه 🏦', 'callback_data' => 'withdraw_funds']],
                        [['text' => 'بازگشت 🔙', 'callback_data' => 'leader_finance_menu']]
                    ]
                ])
            ]);
        } elseif ($callbackData === 'withdraw_funds') {
            $this->sendRequest("editMessageText", [
                "chat_id" => $this->chatId,
                "message_id" => $messageId,
                "text" => "لطفاً نوع برداشت وجه خود را انتخاب کنید:",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [['text' => 'برداشت استار ✨', 'callback_data' => 'withdraw_star']],
                        [['text' => 'برداشت ریالی 💵', 'callback_data' => 'withdraw_toman']],
                        [['text' => 'بازگشت 🔙', 'callback_data' => 'leader_dashboard']]
                    ]
                ])
            ]);
        } elseif ($callbackData === 'withdraw_toman') {
            $this->fileHandler->saveState($chatId, 'awaiting_withdraw_toman_bank_account');
            $this->fileHandler->saveMessageId($chatId, $messageId);
            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => "لطفاً شماره شبا خود را وارد کنید.\n
                    (مثال: IR060170000000109945007001)",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [['text' => 'بازگشت 🔙', 'callback_data' => 'withdraw_funds']]
                    ]
                ])
            ]);
        } elseif ($callbackData === 'upload_guides_menu') {
            $this->uploadGuidesMenu($chatId, $messageId);
        } elseif (str_starts_with($callbackData, 'view_item_guide_folder_')) {
            $folderId = str_replace('view_item_guide_folder_', '', $callbackData);
            $messagid = $this->fileHandler->getMessageId($this->chatId);
            $this->deleteMessageWithDelay();
            $this->fileHandler->saveMessageId($chatId, '');
            $this->uploadGuidesMenu($chatId, null, (int)$folderId);
        } elseif (str_starts_with($callbackData, 'view_guide_folder_')) {
            $folderId = str_replace('view_guide_folder_', '', $callbackData);
            $this->fileHandler->saveMessageId($chatId, '');
            $this->uploadGuidesMenu($chatId, $messageId, (int)$folderId);
        } elseif ($callbackData === 'skip_guide_folder_description') {
            $this->text = '';
            $this->handleRequest();
        } elseif ($callbackData === 'cancel_guide_folder_creation') {
            $this->fileHandler->clearTemporaryData($chatId);
            $this->fileHandler->saveState($chatId, 'null');
            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => "❌ ایجاد دسته بندی لغو شد. می توانید از ابتدا شروع کنید.",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [['text' => '🔙 بازگشت به مدیریت راهنما', 'callback_data' => 'upload_guides_menu']]
                    ]
                ])
            ]);
        } elseif (str_starts_with($callbackData, 'create_guide_folder_')) {
            $parentIdStr = str_replace('create_guide_folder_', '', $callbackData);
            $parentId = ($parentIdStr === 'null') ? null : (int)$parentIdStr;

            $this->fileHandler->saveState($chatId, 'awaiting_guide_folder_name_' . ($parentId ?? 'null'));
            $this->fileHandler->saveMessageId($chatId, $messageId);
            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => "📁 لطفاً نام دسته بندی جدید (پوشه راهنما) را وارد کنید:",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [['text' => '🔙 بازگشت', 'callback_data' => ($parentId === null ? 'upload_guides_menu' : 'view_guide_folder_' . $parentId)]] // بازگشت به جای درست
                    ]
                ])
            ]);
        } elseif (str_starts_with($callbackData, 'edit_guide_item_name')) {
            $itemId = str_replace('edit_guide_item_name', '', $callbackData);
            $this->fileHandler->saveState($chatId, 'awaiting_edit_guide_item_name_' . $itemId);
            $this->fileHandler->saveMessageId($chatId, $messageId);
            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => "✏️ لطفاً نام جدید برای این راهنما وارد کنید:",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [['text' => '🔙 بازگشت', 'callback_data' => 'manage_guide_folder_' . ($this->db->getParentFolderId($this->db->getGuideItemById($itemId)['folder_id']) ?? 'null')]]
                    ]
                ])
            ]);
        } elseif (str_starts_with($callbackData, 'edit_guide_item_caption')) {
            $itemId = str_replace('edit_guide_item_caption', '', $callbackData);
            $this->fileHandler->saveState($chatId, 'awaiting_edit_guide_item_caption_' . $itemId);
            $this->fileHandler->saveMessageId($chatId, $messageId);
            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => "📝 لطفاً کپشن جدید برای این راهنما وارد کنید:",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [['text' => '🔙 بازگشت', 'callback_data' => 'manage_guide_folder_' . ($this->db->getParentFolderId($this->db->getGuideItemById($itemId)['folder_id']) ?? 'null')]]
                    ]
                ])
            ]);
        } elseif (str_starts_with($callbackData, 'edit_guide_item_media')) {
            $itemId = str_replace('edit_guide_item_media', '', $callbackData);
            $this->fileHandler->saveState($chatId, 'awaiting_edit_guide_item_media_' . $itemId);
            $this->fileHandler->saveMessageId($chatId, $messageId);
            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => "📎 لطفاً محتوای جدید (عکس، ویدیو، فایل یا متن) را ارسال کنید:",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [['text' => '🔙 بازگشت', 'callback_data' => 'manage_guide_folder_' . ($this->db->getParentFolderId($this->db->getGuideItemById($itemId)['folder_id']) ?? 'null')]]
                    ]
                ])
            ]);
        } elseif (str_starts_with($callbackData, 'delete_guide_item_')) {
            $itemId = str_replace('delete_guide_item_', '', $callbackData);

            $this->fileHandler->saveMessageId($chatId, $messageId);
            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => "⚠️ آیا مطمئن هستید که می خواهید این راهنما حذف شود؟",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [['text' => '✅ بله، حذف شود', 'callback_data' => 'confirm_delete_guide_item_' . $itemId]],

                        [['text' => '❌ خیر، بازگشت', 'callback_data' => 'manage_guide_folder_' . ($this->db->getParentFolderId($this->db->getGuideItemById($itemId)['folder_id']) ?? 'null')]]
                    ]
                ])
            ]);
        } elseif (str_starts_with($callbackData, 'confirm_delete_guide_item_')) {
            $itemId = str_replace('confirm_delete_guide_item_', '', $callbackData);
            $item = $this->db->getGuideItemById($itemId);
            $folderId = $item['folder_id'] ?? null;
            $success = $this->db->deleteGuideItem($itemId);
            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => $success ? "✅ راهنما با موفقیت حذف شد." : "❌ خطا در حذف راهنما.",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [['text' => '🔙 بازگشت', 'callback_data' => 'manage_guide_folder_' . ($folderId ?? 'null')]]
                    ]
                ])
            ]);
            $this->fileHandler->saveState($chatId, "null");
        } elseif (str_starts_with($callbackData, 'manage_guide_folder_')) {
            $targetFolderIdStr = str_replace('manage_guide_folder_', '', $callbackData);
            $targetFolderId = ($targetFolderIdStr === 'null') ? null : (int)$targetFolderIdStr;
            $this->manageGuideFolderOptions($chatId, null, $targetFolderId);
        } elseif (str_starts_with($callbackData, 'edit_guide_folder_name_')) {
            $folderId = str_replace('edit_guide_folder_name_', '', $callbackData);
            $this->fileHandler->saveState($chatId, 'awaiting_guide_folder_new_name_' . $folderId);
            $this->fileHandler->saveMessageId($chatId, $messageId); // ذخیره messageId دکمه کلیک شده
            $this->sendRequest("editMessageText", [ // ویرایش پیام دکمه کلیک شده
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => "✏️ لطفاً نام جدید دسته بندی را وارد کنید:",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [['text' => '🔙 بازگشت', 'callback_data' => 'manage_guide_folder_' . ($this->db->getParentFolderId($folderId) ?? 'null')]]
                    ]
                ])
            ]);
        } elseif (str_starts_with($callbackData, 'edit_guide_folder_description_')) {

            $folderId = str_replace('edit_guide_folder_description_', '', $callbackData);
            $this->fileHandler->saveState($chatId, 'awaiting_guide_folder_new_description_' . $folderId);
            $this->fileHandler->saveMessageId($chatId, $messageId); // ذخیره messageId دکمه کلیک شده
            $this->sendRequest("editMessageText", [ // ویرایش پیام دکمه کلیک شده
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => "📝 لطفاً توضیحات جدید دسته بندی را وارد کنید (اختیاری):",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [['text' => 'بدون توضیحات', 'callback_data' => 'skip_guide_folder_new_description_' . $folderId]],
                        [['text' => '🔙 بازگشت', 'callback_data' => 'manage_guide_folder_' . ($this->db->getParentFolderId($folderId) ?? 'null')]]
                    ]
                ])
            ]);
        } elseif (str_starts_with($callbackData, 'skip_guide_folder_new_description_')) {
            $folderId = str_replace('skip_guide_folder_new_description_', '', $callbackData);
            $this->text = ''; // متن را خالی می کنیم تا به عنوان "بدون توضیحات" تلقی شود
            $this->fileHandler->saveState($chatId, 'awaiting_guide_folder_new_description_' . $folderId);
            // باید messageId مربوط به پیام اصلی دریافت توضیحات را حذف کنیم

            $msgIdForDelete = $this->fileHandler->getMessageId($chatId);
            if ($msgIdForDelete) {
                $this->sendRequest("deleteMessage", ["chat_id" => $chatId, "message_id" => $msgIdForDelete]);
            }
            $this->handleRequest();
        } elseif (str_starts_with($callbackData, 'confirm_delete_guide_folder_')) {
            $folderId = str_replace('confirm_delete_guide_folder_', '', $callbackData);
            $folderInfo = $this->db->getGuideFolderById($folderId);
            $folderName = $folderInfo['name'] ?? 'نامشخص';

            $this->fileHandler->saveState($chatId, 'awaiting_guide_folder_delete_confirmation_' . $folderId);
            $this->fileHandler->saveMessageId($chatId, $messageId); // ذخیره messageId دکمه کلیک شده
            $this->sendRequest("editMessageText", [ // ویرایش پیام دکمه کلیک شده
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => "⚠️ آیا مطمئن هستید که می خواهید دسته بندی «{$folderName}» و تمامی محتویات و زیرپوشه های آن را حذف کنید؟ این عمل غیرقابل بازگشت است!",
                "parse_mode" => "HTML",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [['text' => '✅ بله، حذف شود', 'callback_data' => 'delete_guide_folder_' . $folderId]],
                        [['text' => '❌ خیر، بازگشت', 'callback_data' => 'manage_guide_folder_' . ($this->db->getParentFolderId($folderId) ?? 'null')]]
                    ]
                ])
            ]);
        } elseif (str_starts_with($callbackData, 'delete_guide_folder_')) {
            $folderId = str_replace('delete_guide_folder_', '', $callbackData);
            $parentId = $this->db->getParentFolderId($folderId); // parentId را قبل از حذف بگیرید

            $success = $this->db->deleteGuideFolder($folderId);
            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => $success ? "✅ دسته بندی با موفقیت حذف شد." : "❌ خطا در حذف دسته بندی.",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [['text' => '🔙 بازگشت به مدیریت', 'callback_data' => 'manage_guide_folder_' . ($parentId ?? 'null')]]
                    ]
                ])
            ]);
            $this->fileHandler->saveState($chatId, 'null'); // حالت را به null برگردانید
        } elseif (str_starts_with($callbackData, 'set_guide_item_title_')) {
            $parentId = str_replace('set_guide_item_title_', '', $callbackData);
            $this->fileHandler->saveState($chatId, 'awaiting_guide_item_title_' . $parentId);
            $this->fileHandler->saveMessageId($chatId, $messageId);
            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => "📝 لطفاً عنوان این راهنما را وارد کنید:",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [['text' => '🔙 بازگشت', 'callback_data' => 'view_guide_folder_' . $parentId]]
                    ]
                ])
            ]);
        } elseif (str_starts_with($callbackData, 'add_guide_item_')) {
            $parentId = str_replace('add_guide_item_', '', $callbackData);
            $this->fileHandler->saveState($chatId, 'awaiting_guide_item_upload_' . $parentId);
            $this->fileHandler->saveMessageId($chatId, $messageId);
            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => "📎 لطفاً فایل راهنمای خود را ارسال کنید (عکس، ویدیو، متن، یا PDF):",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [['text' => '🔙 بازگشت', 'callback_data' => 'view_guide_folder_' . $parentId]]
                    ]
                ])
            ]);
        } elseif (str_starts_with($callbackData, 'delete_items_')) {
            $idsString = str_replace('delete_items_', '', $callbackData);
            $messageIds = explode(',', $idsString);
            $this->deleteMessages($messageIds);
            return;
        } elseif (str_starts_with($callbackData, 'view_setings_guide_item_')) {
            $itemId = str_replace('view_setings_guide_item_', '', $callbackData);
            $this->viewGuideItem($chatId, (int)$itemId, $this->callbackQueryId);
        } elseif (str_starts_with($callbackData, 'view_guide_item_')) {
            $itemId = str_replace('view_guide_item_', '', $callbackData);
            $this->viewGuideItem($chatId, (int)$itemId, $this->callbackQueryId);
        } elseif (str_starts_with($callbackData, 'upload_guides_menu_parent_')) {
            $parentId = str_replace('upload_guides_menu_parent_', '', $callbackData);
            $parentId = ($parentId === 'null') ? null : (int)$parentId;
            $this->uploadGuidesMenu($chatId, $messageId, $parentId);
        } elseif ($callbackData === "manual_withdrawal") {
            $this->fileHandler->saveState($chatId, "awaiting_manual_withdrawal_userid");

            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => "لطفاً ایدی عددی یا ایدی تلگرامی کاربر را وارد کنید\nمثال: `123456789` یا `@username`",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [["text" => "❌ انصراف", "callback_data" => "go_to_menu"]]
                    ]
                ])
            ]);
        } elseif ($callbackData === 'deposit') {
            $this->handleAdminPayments($messageId);
        } elseif ($callbackData === 'withdrawn') {
            $this->handleWithdrawn($messageId);
        } elseif (str_starts_with($callbackData, "confirm_manual_withdrawal_")) {
            $targetUserId = str_replace("confirm_manual_withdrawal_", "", $callbackData);
            $context = $this->fileHandler->getManualWithdrawalContext($this->chatId);

            //            $this->fileHandler->saveManualWithdrawalContext($this->chatId, [
            //                'user_id' => $targetUserId
            //            ]);

            $this->fileHandler->saveState($this->chatId, "awaiting_manual_withdrawal_receipt");

            $this->sendRequest("sendMessage", [
                "chat_id" => $this->chatId,
                "text" => "🧾 لطفاً عکس رسید کارت به کارت را ارسال کنید.",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [["text" => "❌ انصراف", "callback_data" => "go_to_menu"]],
                    ]
                ])
            ]);
            return;
        } elseif ($callbackData === "bot_status") {
            $this->handleBotStats();
            return;
        } elseif ($callbackData === "show_last_leaders") {
            $this->showLastLeaders();
        } elseif ($callbackData === "show_last_explorers") {
            $this->showLastExplorers();
        } elseif ($callbackData === "show_last_users") {
            $lastUsers = $this->db->getLastTenUsers();

            $message = "💹 <b>Last Ten Users:</b>\n\n";
            foreach ($lastUsers as $user) {
                $message .= "<blockquote>👤 <b>Name:</b> " . htmlspecialchars($user['first_name'] ?? '-') . " " . htmlspecialchars($user['last_name'] ?? '-') . "</blockquote>\n";
                $message .= "<blockquote>📜 <b>Username:</b> " . (!empty($user['username']) ? "<a href='tg://user?id={$user['chat_id']}'>@{$user['username']}</a>" : '-') . "</blockquote>\n";
                $message .= "<blockquote>🆔 <b>Chat ID:</b> <code>" . htmlspecialchars($user['chat_id']) . "</code></blockquote>\n";
                $message .= "<blockquote>🕓 <b>Join Date:</b> <code>" . htmlspecialchars($user['join_date']) . "</code></blockquote>\n";
                $message .= "━━━━━━━━━━━━━━━\n";
            }

            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => $message,
                "parse_mode" => "HTML",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [["text" => "🔙 بازگشت", "callback_data" => "bot_status"]]
                    ]
                ])
            ]);
        } elseif ($callbackData === "show_last_blocked_users") {
            $lastBlockedUsers = $this->db->getLastTenBlockedUsers();

            $message = "🚫 <b>Last Ten Blocked Users:</b>\n\n";
            foreach ($lastBlockedUsers as $user) {
                $message .= "<blockquote>👤 <b>Name:</b> " . htmlspecialchars($user['first_name'] ?? '-') . " " . htmlspecialchars($user['last_name'] ?? '-') . "</blockquote>\n";
                $message .= "<blockquote>📜 <b>Username:</b> " . (!empty($user['username']) ? "<a href='tg://user?id={$user['chat_id']}'>@{$user['username']}</a>" : '-') . "</blockquote>\n";
                $message .= "<blockquote>🆔 <b>Chat ID:</b> <code>" . htmlspecialchars($user['chat_id']) . "</code></blockquote>\n";
                $message .= "<blockquote>🕓 <b>Join Date:</b> <code>" . htmlspecialchars($user['join_date']) . "</code></blockquote>\n";
                $message .= "━━━━━━━━━━━━━━━\n";
            }

            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => $message,
                "parse_mode" => "HTML",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [["text" => "🔙 بازگشت", "callback_data" => "bot_status"]]
                    ]
                ])
            ]);
        } elseif ($callbackData === 'admins') {
            $admins = $this->db->getAdmins();
            if (empty($admins)) {
                $this->sendRequest("sendMessage", [
                    "chat_id" => $chatId,
                    "text" => "❌ هیچ ادمینی ثبت نشده است."
                ]);
                return;
            }

            $keyboard = [];
            foreach ($admins as $admin) {
                $adminName = trim(($admin['first_name'] ?? '') . ' ' . ($admin['last_name'] ?? ''));
                $adminUsername = $admin['username'] ? "(@{$admin['username']})" : '';
                $adminText = $adminName . ' ' . $adminUsername . " [{$admin['chat_id']}]";
                $keyboard[] = [
                    ['text' => $adminText, 'callback_data' => 'noop'],
                    ['text' => '❌ حذف', 'callback_data' => 'delete_admin_' . $admin['chat_id']]
                ];
            }
            // دکمه افزودن ادمین
            $keyboard[] = [
                ['text' => '➕ افزودن ادمین', 'callback_data' => 'add_admin']
            ];
            // دکمه بازگشت
            $keyboard[] = [
                ['text' => '🔙 بازگشت', 'callback_data' => 'bot_status']
            ];

            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => "👥 لیست ادمین ها:",
                "parse_mode" => "HTML",
                "reply_markup" => json_encode([
                    "inline_keyboard" => $keyboard
                ])
            ]);
        } elseif (str_starts_with($callbackData, 'delete_admin_')) {
            $adminId = str_replace('delete_admin_', '', $callbackData);
            $this->db->deleteAdmin($adminId);
            $res =  $this->sendRequest("sendMessage", [
                "chat_id" => $chatId,
                "text" => "✅ ادمین با موفقیت حذف شد."
            ]);
            $this->handleCallbackQuery([
                "data" => "admins",
                "message" => ["chat" => ["id" => $chatId], "message_id" => $messageId],
                "id" => $this->callbackQueryId ?? ''
            ]);
            sleep(2);
            $this->sendRequest("deleteMessage", [
                "chat_id" => $chatId,
                "message_id" => $res['result']['message_id'] ?? ''
            ]);
        } elseif ($callbackData === 'add_admin') {
            $this->fileHandler->saveState($chatId, 'awaiting_new_admin_id');
            $this->fileHandler->saveMessageId($chatId, $messageId);
            $res = $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => "لطفاً آیدی عددی یا یوزرنیم تلگرام ادمین جدید را وارد کنید:",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [['text' => '🔙 بازگشت', 'callback_data' => 'admins']]
                    ]
                ])
            ]);
            $this->fileHandler->saveMessageId($chatId, $res['result']['message_id'] ?? '');
        } elseif (strpos($callbackData, "admin_view_leaders_page_") === 0) {
            $page         = (int) str_replace("admin_view_leaders_page_", "", $callbackData);
            $itemsPerPage = 5;
            $leaders  = $this->db->getLeadersWithPagination($itemsPerPage, $page);
            $totalItems   = $this->db->getLeaderCount();
            $totalPages   = ceil($totalItems / $itemsPerPage);

            if (empty($leaders)) {
                $this->sendRequest("sendMessage", [
                    "chat_id" => $this->chatId,
                    "text"    => "❌ هیچ لیدری یافت نشد.",
                ]);
                return;
            }

            $buttons = [];
            foreach ($leaders as $leader) {
                $buttons[] = [
                    ['text' => $leader['first_name'] . " " . $leader['last_name'], 'callback_data' => 'user_details_' . $leader['id']],
                    ['text' => '🗑 حذف', 'callback_data' => 'delete_leader_' . $leader['chat_id']],
                ];
            }

            $navigationButtons = [];

            if ($page > 1) {
                $navigationButtons[] = ['text' => '⏪ اولین', 'callback_data' => 'admin_view_leaders_page_1'];
                $navigationButtons[] = ['text' => '⬅️ قبلی', 'callback_data' => 'admin_view_leaders_page_' . ($page - 1)];
            }

            if ($page < $totalPages) {
                $navigationButtons[] = ['text' => 'بعدی ➡️', 'callback_data' => 'admin_view_leaders_page_' . ($page + 1)];
                $navigationButtons[] = ['text' => 'آخرین ⏩', 'callback_data' => 'admin_view_leaders_page_' . $totalPages];
            }

            if (! empty($navigationButtons)) {
                $buttons[] = $navigationButtons;
            }

            // دکمه رفتن به صفحه خاص
            //            $buttons[] = [
            //                ['text' => '🔢 رفتن به صفحه...', 'callback_data' => 'admin_leaders_goto_page'],
            //            ];

            // دکمه برگشت
            $buttons[] = [
                ['text' => '🔙 برگشت به منو', 'callback_data' => 'admin_dashboard'],
            ];

            $text = "<b>📜 لیست لیدرها</b>\n\n";
            $text .= "صفحه $page از $totalPages";

            $this->sendRequest("editMessageText", [
                "chat_id"      => $this->chatId,
                "message_id"   => $messageId,
                "text"         => $text,
                "parse_mode"   => "HTML",
                "reply_markup" => json_encode([
                    "inline_keyboard" => $buttons,
                ]),
            ]);
        } elseif (strpos($callbackData, "delete_leader_") === 0) {
            $leaderChatId = str_replace("delete_leader_", "", $callbackData);
            $leader = $this->db->getUserByUserId($leaderChatId);

            if (!$leader) {
                $this->sendRequest("sendMessage", [
                    "chat_id" => $this->chatId,
                    "text"    => "❌ کاربری با این شناسه یافت نشد.",
                ]);
                return;
            }

            $text = "⚠️ آیا مطمئن هستید که می خواهید کاربر زیر را حذف کنید؟\n\n";
            $text .= "👤 <b>نام:</b> {$leader['first_name']} {$leader['last_name']}\n";
            $text .= "📧 <b>موبایل:</b> {$leader['mobile']}\n";


            $buttons = [
                [
                    ['text' => '✅ بله، حذف کن', 'callback_data' => 'confirm_delete_leader_' . $leaderChatId],
                    ['text' => '❌ خیر، بازگشت', 'callback_data' => 'admin_view_leaders_page_1'],
                ],
            ];

            $this->sendRequest("editMessageText", [
                "chat_id"      => $this->chatId,
                "message_id"   => $messageId,
                "text"         => $text,
                "parse_mode"   => "HTML",
                "reply_markup" => json_encode(["inline_keyboard" => $buttons]),
            ]);
        } elseif (strpos($callbackData, "confirm_delete_leader_") === 0) {
            $userChatId   = str_replace("confirm_delete_leader_", "", $callbackData);
            $deleteResult = $this->db->deleteUserByChatId($userChatId);
            $this->db->setLeaderStatus($userChatId, false);

            if ($deleteResult) {
                $this->sendRequest("editMessageText", [
                    "chat_id"    => $this->chatId,
                    "message_id" => $messageId,
                    "text"       => "✅ لیدربا موفقیت حذف شد.",
                ]);
            } else {
                $this->sendRequest("sendMessage", [
                    "chat_id" => $this->chatId,
                    "text"    => "❌ خطا در حذف لیدر. لطفاً دوباره امتحان کنید.",
                ]);
            }

            $this->sendRequest("sendMessage", [
                "chat_id"      => $this->chatId,
                "text"         => "🔙 بازگشت به لیست لیدرها",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [['text' => 'برگشت 🔙', 'callback_data' => 'admin_view_leaders_page_1']],
                    ],
                ]),
            ]);
        } elseif (strpos($callbackData, "admin_view_users_page_") === 0) {
            $page         = (int) str_replace("admin_view_users_page_", "", $callbackData);
            $itemsPerPage = 5;
            $users  = $this->db->getUsersWithPagination($itemsPerPage, $page);
            $totalItems   = $this->db->getUserCount();
            $totalPages   = ceil($totalItems / $itemsPerPage);

            if (empty($users)) {
                $this->sendRequest("sendMessage", [
                    "chat_id" => $this->chatId,
                    "text"    => "❌ هیچ کاربری یافت نشد.",
                ]);
                return;
            }

            $buttons = [];
            foreach ($users as $user) {
                $buttons[] = [
                    ['text' => $user['first_name'] . " " . $user['last_name'], 'callback_data' => 'user_details_' . $user['id']],
                    ['text' => '🗑 حذف', 'callback_data' => 'delete_user_' . $user['chat_id']],
                ];
            }

            $navigationButtons = [];

            if ($page > 1) {
                $navigationButtons[] = ['text' => '⏪ اولین', 'callback_data' => 'admin_view_users_page_1'];
                $navigationButtons[] = ['text' => '⬅️ قبلی', 'callback_data' => 'admin_view_users_page_' . ($page - 1)];
            }

            if ($page < $totalPages) {
                $navigationButtons[] = ['text' => 'بعدی ➡️', 'callback_data' => 'admin_view_users_page_' . ($page + 1)];
                $navigationButtons[] = ['text' => 'آخرین ⏩', 'callback_data' => 'admin_view_users_page_' . $totalPages];
            }

            if (! empty($navigationButtons)) {
                $buttons[] = $navigationButtons;
            }

            // دکمه رفتن به صفحه خاص
            //            $buttons[] = [
            //                ['text' => '🔢 رفتن به صفحه...', 'callback_data' => 'admin_users_goto_page'],
            //            ];

            // دکمه برگشت
            $buttons[] = [
                ['text' => '🔙 برگشت به منو', 'callback_data' => 'admin_dashboard'],
            ];

            $text = "<b>📜 لیست طبیعت گرد ها</b>\n\n";
            $text .= "صفحه $page از $totalPages";

            $this->sendRequest("editMessageText", [
                "chat_id"      => $this->chatId,
                "message_id"   => $messageId,
                "text"         => $text,
                "parse_mode"   => "HTML",
                "reply_markup" => json_encode([
                    "inline_keyboard" => $buttons,
                ]),
            ]);
        } elseif (strpos($callbackData, "delete_user_") === 0) {
            $userChatId = str_replace("delete_user_", "", $callbackData);
            $user = $this->db->getUserByUserId($userChatId);

            if (!$user) {
                $this->sendRequest("sendMessage", [
                    "chat_id" => $this->chatId,
                    "text"    => "❌ کاربری با این شناسه یافت نشد.",
                ]);
                return;
            }

            $text = "⚠️ آیا مطمئن هستید که می خواهید کاربر زیر را حذف کنید؟\n\n";
            $text .= "👤 <b>نام:</b> {$user['first_name']} {$user['last_name']}\n";
            $text .= "📧 <b>موبایل:</b> {$user['mobile']}\n";


            $buttons = [
                [
                    ['text' => '✅ بله، حذف کن', 'callback_data' => 'confirm_delete_user_' . $userChatId],
                    ['text' => '❌ خیر، بازگشت', 'callback_data' => 'admin_view_users_page_1'],
                ],
            ];

            $this->sendRequest("editMessageText", [
                "chat_id"      => $this->chatId,
                "message_id"   => $messageId,
                "text"         => $text,
                "parse_mode"   => "HTML",
                "reply_markup" => json_encode(["inline_keyboard" => $buttons]),
            ]);
        } elseif (strpos($callbackData, "confirm_delete_user_") === 0) {
            $userChatId   = str_replace("confirm_delete_user_", "", $callbackData);
            $deleteResult = $this->db->deleteUserByChatId($userChatId);
            $this->db->setUserStatus($userChatId, false);

            if ($deleteResult) {
                $this->sendRequest("editMessageText", [
                    "chat_id"    => $this->chatId,
                    "message_id" => $messageId,
                    "text"       => "✅ کاربر با موفقیت حذف شد.",
                ]);
            } else {
                $this->sendRequest("sendMessage", [
                    "chat_id" => $this->chatId,
                    "text"    => "❌ خطا در حذف کاربر. لطفاً دوباره امتحان کنید.",
                ]);
            }

            $this->sendRequest("sendMessage", [
                "chat_id"      => $this->chatId,
                "text"         => "🔙 بازگشت به لیست کاربران",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [['text' => 'برگشت 🔙', 'callback_data' => 'admin_view_users_page_1']],
                    ],
                ]),
            ]);
        } elseif (strpos($callbackData, 'withdraw_request_') === 0) {
            $requestId = (int)str_replace('withdraw_request_', '', $callbackData);

            $withdrawRequest = $this->db->getWithdrawRequestById($requestId);
            $user = $this->db->registeredExplorerByUserId($withdrawRequest['user_id']);
            $text = "اطلاعات درخواست برداشت" . "\n" . "\n" .
                "نام و نام خانوادگی:" . $user['first_name'] . " " . $user['last_name'] . "\n" .
                "شماره موبایل:" . $user['phone'] . "\n" .
                " مبلغ درخواستی:" . number_format($withdrawRequest['amount']) . " تومان " . "\n" .
                "شماره شبا:" . "IR" . $withdrawRequest['payment_detail'] . "\n" . "\n" .
                "لطفاً مبلغ مورد نظر برای پرداخت را وارد کنید (به تومان):";

            $this->fileHandler->saveState($this->chatId, "awaiting_manual_withdrawal_amount");
            $this->fileHandler->saveManualWithdrawalContext($this->chatId, [
                'user_id' => $withdrawRequest['user_id'],
                'request_id' => $withdrawRequest['id']
            ]);
            $keyboard[] = [
                ["text" => " 🔙 بازگشت", "callback_data" => "withdrawn"]
            ];

            $this->sendRequest("editMessageText", [
                "chat_id" => $this->chatId,
                "message_id"   => $messageId,
                "text" => $text,
                "reply_markup" => json_encode([
                    "inline_keyboard" => $keyboard
                ]),
            ]);
        } elseif (strpos($callbackData, 'admin_deposit_') === 0) {
            $paymentId = (int)str_replace('admin_deposit_', '', $callbackData);

            $payment = $this->db->getAdminPaymentById($paymentId);
            $withdrawRequest = $this->db->getWithdrawRequestById($payment['request_id']);
            $user = $this->db->registeredExplorerByUserId($payment['user_id']);
            $text = "📄 اطلاعات پرداخت\n\n" .
                "👤 نام و نام خانوادگی: {$user['first_name']} {$user['last_name']}\n" .
                "📱 شماره موبایل: {$user['phone']}\n" .
                "💰 مبلغ درخواستی: " . number_format($withdrawRequest['amount']) . " تومان\n" .
                "🏦 شماره شبا: " . "IR{$withdrawRequest['payment_detail']}\n" .
                "💳 مبلغ واریزی شما: " . number_format($payment['paid_amount']) . " تومان\n";


            $keyboard[] = [
                ["text" => " 🔙 بازگشت", "callback_data" => "deposit"]
            ];

            $this->sendRequest("editMessageText", [
                "chat_id" => $this->chatId,
                "message_id"   => $messageId,
                "text" => $text,
                "reply_markup" => json_encode([
                    "inline_keyboard" => $keyboard
                ]),
            ]);
        } elseif ($callbackData === 'admin_finance_menu') {
            $financeButtons = [
                [
                    ['text' => '💰 پرداخت ها', 'callback_data' => 'payments_menu'],
                    ['text' => '💵 واریزی ها', 'callback_data' => 'deposit']
                ],
                [
                    ['text' => '💳 درخواست های برداشت', 'callback_data' => 'withdrawn'],

                ],
                [['text' => '🔙 بازگشت به داشبورد ادمین', 'callback_data' => 'admin_dashboard']]
            ];

            $this->sendRequest("editMessageText", [
                "chat_id" => $this->chatId,
                "message_id" => $messageId,
                "text" => "💳 بخش مدیریت مالی\n\nاز این قسمت می توانید پرداخت ها، واریزی ها و گزارش های مالی را مدیریت کنید.",
                "reply_markup" => json_encode([
                    "inline_keyboard" => $financeButtons
                ]),
            ]);
        } elseif ($callbackData === 'admin_dashboard') {

            $this->sendRequest("editMessageText", [
                "chat_id" => $this->chatId,
                "message_id"   => $messageId,
                "text" =>
                "👋 <b>خوش آمدید به داشبورد ادمین</b>\n\n"
                    . "<blockquote>از اینجا می توانید تمام بخش های ربات را مدیریت و نظارت کنید:</blockquote>\n\n"
                    . "🧝‍♀️ <b>مدیریت طبیعت گردها</b>\n"
                    . "🧑‍✈️ <b>مدیریت لیدرها</b>\n"
                    . "🌍 <b>مدیریت تورها</b>\n"
                    . "💰 <b>پرداخت ها و تسویه حساب ها</b>\n"
                    . "📊 <b>گزارش ها و وضعیت کلی ربات</b>\n\n"
                    . "✨ <i>📌 همه ابزارهای لازم برای مدیریت حرفه ای اینجاست!</i>",

                "parse_mode" => "HTML",
                "reply_markup" => json_encode([
                    "inline_keyboard" => $this->getAdminDashboardKeyboard()
                ]),
            ]);
        } elseif ($callbackData === 'admin_guide_root') {
            $this->uploadGuidesMenu($this->chatId, $this->messageId, null, 'admin_dashboard');
        } elseif ($callbackData === 'leader_dashboard') {
            $this->sendRequest("editMessageText", [
                "chat_id" => $this->chatId,
                "message_id"   => $messageId,
                "text" => "🧭 به پنل مدیریت لیدر خوش آمدید. از گزینه های زیر استفاده کنید:",
                "parse_mode" => "HTML",
                "reply_markup" => $this->getLeaderDashboardKeyboard()
            ]);
        } elseif ($callbackData === 'leader_finance_menu') {
            $leaderFinanceButtons = [
                [
                    ['text' => '💳 لیست پرداخت ها', 'callback_data' => 'leader_payments_menu'],
                    ['text' => '📋 کدهای تخفیف', 'callback_data' => 'manage_discounts']
                ],
                [
                    ['text' => '💼 کیف پول من', 'callback_data' => 'instructor_wallet_menu']
                ],
                [['text' => '🔙 بازگشت به داشبورد لیدر', 'callback_data' => 'leader_dashboard']]
            ];

            $this->sendRequest("editMessageText", [
                "chat_id" => $this->chatId,
                "message_id" => $messageId,
                "text" => "💳 بخش مدیریت مالی لیدر\n\nاز این قسمت می توانید پرداخت ها، کیف پول و کدهای تخفیف خود را مدیریت کنید.",
                "reply_markup" => json_encode([
                    "inline_keyboard" => $leaderFinanceButtons
                ]),
            ]);
        } elseif (strpos($callbackData, "users_menu_page_") === 0) {
            $page = (int) str_replace("users_menu_page_", "", $callbackData);
            $language = 'fa';
            $this->showAllUsers($chatId, $language, $page, $messageId);
        } elseif (strpos($callbackData, "bot_user_details_") === 0) {
            $id = (int) str_replace("bot_user_details_", "", $callbackData);
            $user = $this->db->getUserById($id);


            $text =
                "<b>👤 اطلاعات کاربر</b>\n\n" .
                "🔹 <b>نام کاربری:</b> @" . htmlspecialchars($user['username']) . "\n" .
                "🆔 <b>آیدی عددی:</b> <code>" . htmlspecialchars($user['chat_id']) . "</code>\n" .
                "📛 <b>نام:</b> " . htmlspecialchars($user['first_name']) . "\n" .
                "👨‍👩‍👧 <b>نام خانوادگی:</b> " . htmlspecialchars($user['last_name']) . "\n" .
                "📅 <b>تاریخ عضویت:</b> " . htmlspecialchars($user['join_date']) . "\n" .
                "⏰ <b>آخرین فعالیت:</b> " . htmlspecialchars($user['last_activity']) . "\n" .
                "✅ <b>وضعیت حساب:</b> " . htmlspecialchars($user['status']);

            $this->sendRequest("sendMessage", [
                "chat_id" => $this->chatId,
                //                "message_id" => $messageId,
                "text" => $text,
                "parse_mode" => "HTML",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [['text' => 'برگشت 🔙', 'callback_data' => 'bot_users']]
                    ]
                ]),
            ]);
        } elseif (str_starts_with($callbackData, "admin_approve_withdraw_")) {
            if (!$this->db->isAdmin($chatId)) return;
            $requestId = (int)str_replace("admin_approve_withdraw_", "", $callbackData);
            $this->db->updateWithdrawRequestStatus($requestId, 'processing');
            $this->fileHandler->saveState($chatId, "awaiting_payment_receipt_{$requestId}");
            $res = $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => "✅ درخواست تایید شد. لطفاً رسید پرداخت را برای کاربر ارسال کنید (عکس یا متن).",
                "reply_markup" => json_encode(['inline_keyboard' => []])
            ]);
            $this->fileHandler->saveMessageId($chatId, $res['result']['message_id']);
        } elseif (str_starts_with($callbackData, "admin_reject_withdraw_")) {
            if (!$this->db->isAdmin($chatId)) return;
            $requestId = (int)str_replace("admin_reject_withdraw_", "", $callbackData);
            $this->db->updateWithdrawRequestStatus($requestId, 'rejected');

            $request = $this->db->getWithdrawRequestById($requestId);
            if ($request) {
                $this->sendRequest("sendMessage", [
                    "chat_id" => $request['user_id'],
                    "text" => "❌ متاسفانه درخواست برداشت وجه شما رد شد. لطفاً برای اطلاعات بیشتر با پشتیبانی تماس بگیرید."
                ]);
            }

            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => "❌ درخواست برداشت وجه رد شد و به کاربر اطلاع داده شد.",
                "reply_markup" => json_encode(['inline_keyboard' => []])
            ]);
        } elseif ($callbackData === 'block_user_menu') {

            $text = "🛑 مدیریت بلاک کاربر\nیکی از گزینه های زیر را انتخاب کنید:";

            $buttons = [
                [
                    ['text' => '➕ بلاک کردن کاربر', 'callback_data' => 'block_user_add'],

                ],
                [
                    ['text' => '❌ حذف از بلاک', 'callback_data' => 'block_user_remove'],
                ],
                [
                    ['text' => '📋 لیست کاربران بلاک شده', 'callback_data' => 'block_user_list_page_0'],
                ],
                [
                    ['text' => '🔙 بازگشت', 'callback_data' => 'admin_dashboard'],
                ],
            ];

            $this->sendRequest("editMessageText", [
                "chat_id"      => $chatId,
                "message_id"   => $messageId,
                "text"         => $text,
                "parse_mode"   => "HTML",
                "reply_markup" => json_encode([
                    "inline_keyboard" => $buttons,
                ]),
            ]);
        } elseif ($callbackData === 'block_user_add') {
            $this->fileHandler->saveState($chatId, 'awaiting_block_user_id_add');
            $this->fileHandler->saveMessageId($chatId, $messageId);
            $this->sendRequest("editMessageText", [
                "chat_id"      => $chatId,
                "message_id"   => $messageId,
                "text"         => "لطفاً آیدی عددی یا آیدی تلگرام کاربر را ارسال کنید.\n\nمثال:\n@username\nیا\n123456789",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [['text' => 'بازگشت 🔙', 'callback_data' => 'block_user_menu']],
                    ],
                ]),
            ]);
        } elseif ($callbackData === 'block_user_remove') {
            $this->fileHandler->saveState($chatId, 'awaiting_block_user_id_remove');
            $this->fileHandler->saveMessageId($chatId, $messageId);
            $this->sendRequest("editMessageText", [
                "chat_id"      => $chatId,
                "message_id"   => $messageId,
                "text"         => "لطفاً آیدی عددی یا آیدی تلگرام کاربر را ارسال کنید.\n\nمثال:\n@username\nیا\n123456789",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [['text' => 'بازگشت 🔙', 'callback_data' => 'block_user_menu']],
                    ],
                ]),
            ]);
        } elseif ($callbackData === 'admin_send_warning') {
            if (!$this->db->isAdmin($this->chatId)) {
                $this->sendRequest("answerCallbackQuery", [
                    "callback_query_id" => $callbackQuery['id'],
                    'text' => "❌ شما مجوز انجام این کار را ندارید.",
                    'show_alert' => true
                ]);
                return;
            }

            $this->fileHandler->saveState($this->chatId, 'awaiting_warning_user_id');

            $res =  $this->sendRequest("editMessageText", [
                "chat_id" => $this->chatId,
                "message_id" => $this->messageId,
                "text" => "👤 لطفاً شناسه عددی (`chat_id`) یا یوزرنیم (@username) کاربری که می خواهید به او هشدار دهید را وارد کنید:",
                "reply_markup" => json_encode(['inline_keyboard' => [[['text' => '🔙 بازگشت', 'callback_data' => 'admin_dashboard']]]])
            ]);
            $this->fileHandler->saveMessageId($this->chatId, $res['result']['message_id']);
        } elseif (str_starts_with($callbackData, 'block_user_list_page_')) {
            $page = 0;
            if (preg_match('/block_user_list_page_(\d+)/', $callbackData, $matches)) {
                $page = (int) $matches[1];
            }

            $perPage    = 5;
            $total      = $this->db->getBlockedUsersCount();
            $totalPages = ceil($total / $perPage);

            // ✅ گرفتن فقط داده های همین صفحه
            $blockedList = $this->db->getBlockedUsersWithPagination($perPage, $page + 1); // چون تابع شما page رو از 1 می گیره

            if (empty($blockedList)) {
                $this->sendRequest("editMessageText", [
                    "chat_id"      => $this->chatId,
                    "message_id"   => $messageId,
                    "text"         => "❌ هیچ کاربری بلاک نشده است.",
                    "reply_markup" => json_encode([
                        "inline_keyboard" => [
                            [['text' => 'بازگشت 🔙', 'callback_data' => 'block_user_menu']],
                        ],
                    ]),
                ]);
                return;
            }

            $text    = "📋 <b>لیست کاربرهای بلاک شده:</b>\n\n";
            $buttons = [];

            foreach ($blockedList as $f) {
                $userId   = $f['chat_id'];
                $fullName = "{$f['first_name']} {$f['last_name']}";

                $text .= "👤 <b>{$fullName}</b>\n";
                $text .= "🆔 <code>{$userId}</code>\n";
                $text .= "📲 <a href='tg://user?id={$userId}'>ارتباط با این کاربر</a>\n\n";

                $buttons[] = [
                    ['text' => "🔓 آنبلاک", 'callback_data' => "unblock_user_{$userId}"],
                    ['text' => $fullName, 'callback_data' => "admin_view_user_{$userId}"],
                ];
            }

            $navigationButtons = [];
            if ($page > 0) {
                $navigationButtons[] = ['text' => '⬅️ قبلی', 'callback_data' => 'block_user_list_page_' . ($page - 1)];
            }
            if ($page < $totalPages - 1) {
                $navigationButtons[] = ['text' => 'بعدی ➡️', 'callback_data' => 'block_user_list_page_' . ($page + 1)];
            }
            if (! empty($navigationButtons)) {
                $buttons[] = $navigationButtons;
            }

            $buttons[] = [
                ['text' => '🔙 بازگشت به منو', 'callback_data' => 'block_user_menu'],
            ];

            $text .= "📄 صفحه " . ($page + 1) . " از " . $totalPages;

            $this->sendRequest("editMessageText", [
                "chat_id"                  => $this->chatId,
                "message_id"               => $messageId,
                "text"                     => $text,
                "parse_mode"               => "HTML",
                "disable_web_page_preview" => true,
                "reply_markup"             => json_encode([
                    "inline_keyboard" => $buttons,
                ]),
            ]);
        } elseif (strpos($callbackData, "withdraw_page_") === 0) {
            $page = (int) str_replace("withdraw_page_", "", $callbackData);
            $this->handleWithdrawn($messageId, $page);
            return;
        }
    }


    public function getUserKeyboard()
    {
        return [
            'inline_keyboard' => [
                [
                    ['text' => '👤 اطلاعات من', 'callback_data' => 'user_info'],
                    ['text' => '🏕️ تورهای من', 'callback_data' => 'registered_user_tours']
                ],
                [
                    ['text' => '💳 پرداخت ها', 'callback_data' => 'user_pays'],
                    ['text' => '🌟 درخواست لیدری', 'callback_data' => 'leader_request']
                ],
                [
                    ['text' => '🔙 بازگشت به منو', 'callback_data' => 'go_to_menu']
                ]
            ]
        ];
    }


    public function getUserPanelKeyboard()
    {
        $user = $this->db->getUserByUserId($this->chatId);
        $keyboard = [];

        // دکمه های مشترک برای همه کاربران ثبت نام شده
        $keyboard[] = [
            ['text' => 'ℹ️ اطلاعات من', 'callback_data' => 'user_info'],
            ['text' => '🏕️ تورهای ثبت نامی', 'callback_data' => 'registered_user_tours']
        ];
        $keyboard[] = [['text' => '💳 تاریخچه پرداخت ها', 'callback_data' => 'user_pays']];

        // دکمه های شرطی بر اساس نقش کاربر
        if ($user && $user['is_leader'] && $user['confirm_leader'] == 1) {
            // اگر کاربر لیدر تایید شده باشد
            $keyboard[] = [['text' => '🧭 ورود به پنل مدیریت لیدر', 'callback_data' => 'leader_dashboard']];
        } else {
            // اگر کاربر لیدر نباشد
            $keyboard[] = [['text' => '🌟 درخواست لیدری', 'callback_data' => 'leader_request']];
        }

        $keyboard[] = [['text' => '🔙 بازگشت به منوی اصلی', 'callback_data' => 'go_to_menu']];

        return ['inline_keyboard' => $keyboard];
    }


    public function getLeaderDashboardKeyboard()
    {
        $keyboard = [
            [
                ['text' => '➕ ایجاد تور جدید', 'callback_data' => 'create_tour'],
                ['text' => '🗺️ مدیریت تورها', 'callback_data' => 'leader_tours_menu']
            ],
            [
                ['text' => '💰 حساب مالی من', 'callback_data' => 'leader_finance_menu'],
                ['text' => '⚙️ تنظیمات ربات', 'callback_data' => 'leader_bot_setting']
            ],
            [
                ['text' => '👤 پروفایل لیدری', 'callback_data' => 'leader_profile_menu']
            ],
            [
                ['text' => '🔙 بازگشت به پنل کاربری', 'callback_data' => 'user_panel']
            ]
        ];
        return ['inline_keyboard' => $keyboard];
    }


    public function getAdminDashboardKeyboard()
    {
        $keyboard = [
            [
                ['text' => '🧑‍✈️ مدیریت لیدرها', 'callback_data' => 'admin_view_leaders_page_1'],
                ['text' => '🧝‍♀️ مدیریت کاربران', 'callback_data' => 'admin_view_users_page_1']
            ],
            [
                ['text' => '🌍 مدیریت تورها', 'callback_data' => 'tours_menu'],
                ['text' => '💳 مدیریت مالی', 'callback_data' => 'admin_finance_menu'],
            ],
            [
                ['text' => '📚 مدیریت راهنما', 'callback_data' => 'admin_guide_root'],
                ['text' => '📊 وضعیت ربات', 'callback_data' => 'bot_status']
            ],
            [
                ['text' => '🔙 بازگشت به منوی اصلی', 'callback_data' => 'go_to_menu']
            ]
        ];
        return $keyboard;
    }


    public function getMainKeyboard()
    {
        $user = $this->db->getUserByUserId($this->chatId);
        $keyboard = [];

        // App URL from config/environment or default to the verified URL
        $appUrl = $_ENV['MINIAPP_URL'] ?? 'https://wizwiz.villux.ir:8443/natureTour/public/miniapp/'; 
        
        $keyboard[] = [[
            'text' => '📱 ورود به پنل کاربری (مینی‌اپ)',
            'web_app' => ['url' => $appUrl],
            'style' => 'primary',
            'icon_custom_emoji_id' => '5039579582764680065'
        ]];

        $keyboard[] = [
            [
                'text' => '🏞️ تورهای فعال', 
                'callback_data' => 'active_tours',
                'style' => 'primary',
                'icon_custom_emoji_id' => '5278467510604160626'
            ],
            [
                'text' => '➕ اتصال به گروه/کانال',
                'url' => 'https://t.me/Tourambot?startgroup=true',
                'style' => 'success',
                'icon_custom_emoji_id' => '5208880351690112495'
            ]
        ];

        $profileAndLeaderRow = [];

        if ($user && $user['is_registered']) {
            $profileAndLeaderRow[] = [
                'text' => '👤 پروفایل من', 
                'callback_data' => 'user_panel',
                'style' => 'primary',
                'icon_custom_emoji_id' => '5409008750893734809'
            ];
        } else {
            $profileAndLeaderRow[] = [
                'text' => '✅ ثبت نام طبیعت گرد', 
                'callback_data' => 'register',
                'style' => 'success',
                'icon_custom_emoji_id' => '5208880351690112495'
            ];
        }

        if ($user && $user['is_leader'] && isset($user['confirm_leader']) && $user['confirm_leader'] == 1) {
            $profileAndLeaderRow[] = [
                'text' => '🧭 پنل لیدری', 
                'callback_data' => 'leader_dashboard',
                'style' => 'primary',
                'icon_custom_emoji_id' => '5332600543963522398'
            ];
        } else {
            $profileAndLeaderRow[] = [
                'text' => '🌟 درخواست لیدری', 
                'callback_data' => 'leader_request',
                'style' => 'primary',
                'icon_custom_emoji_id' => '5332600543963522398'
            ];
        }

        $keyboard[] = $profileAndLeaderRow;

        $keyboard[] = [
            [
                'text' => '📞 پشتیبانی', 
                'callback_data' => 'support_user',
                'style' => 'primary',
                'icon_custom_emoji_id' => '5303138782004924588'
            ],
            [
                'text' => '📚 راهنما', 
                'callback_data' => 'bot_guide',
                'style' => 'primary',
                'icon_custom_emoji_id' => '5132131004097496494'
            ]
        ];

        if ($user && $user['is_admin']) {
            $keyboard[] = [[
                'text' => '⚙ داشبورد ادمین', 
                'callback_data' => 'admin_dashboard',
                'style' => 'primary',
                'icon_custom_emoji_id' => '5332600543963522398'
            ]];
        }

        return ['inline_keyboard' => $keyboard];
    }


    public function getEditUserProfileKeyboard()
    {
        $keyboard = [
            'inline_keyboard' => [
                [
                    ['text' => '✏️ نام', 'callback_data' => 'edit_user_field_first_name'],
                    ['text' => '✏️ نام خانوادگی', 'callback_data' => 'edit_user_field_last_name']
                ],
                [
                    ['text' => '✏️ نام مستعار', 'callback_data' => 'edit_user_field_nick_name']
                ],
                [
                    ['text' => '✏️ شماره همراه', 'callback_data' => 'edit_user_field_phone'],
                    ['text' => '✏️ شهر', 'callback_data' => 'edit_user_field_city']
                ],
                [
                    ['text' => '🔙 بازگشت به پروفایل', 'callback_data' => 'user_info']
                ]
            ]
        ];
        return $keyboard;
    }

}
