<?php

namespace Bot\BotHandler;

trait GroupTrait
{

    public function handleMyChatMember($myChatMember): void
    {
        $chat = $myChatMember['chat'];
        $chatId = $chat['id'];
        $chatTitle = $chat['title'] ?? ($chat['first_name'] . ' ' . ($chat['last_name'] ?? ''));
        $chatUsername = $chat['username'] ?? null;
        $chatType = $chat['type']; 
        
        $newMember = $myChatMember['new_chat_member'];
        $status = $newMember['status']; 
        
        $fromId = $myChatMember['from']['id']; 
        
        if (in_array($status, ['administrator', 'member'])) {
            $typeStr = ($chatType === 'channel') ? 'channel' : 'group';
            $this->db->registerLeaderChat($chatId, $fromId, $chatTitle, $chatUsername, $typeStr);
            
            // Send confirmation to the leader
            $this->sendRequest("sendMessage", [
                "chat_id" => $fromId,
                "text" => "✅ ربات با موفقیت به " . ($typeStr === 'channel' ? "کانال" : "گروه") . " «{$chatTitle}» اضافه و متصل شد.",
                "parse_mode" => "HTML"
            ]);
        }
    }


    private function showRegisteredToursList($chatId, $language, $messageId): void
    {
        $tours = $this->db->getRegisteredTours($chatId);
        $status = array("pending" => 'در انتظار پرداخت ', "completed" => 'ثبت نام تکمیل شده');
        if (empty($tours)) {

            $this->sendRequest("answerCallbackQuery", [
                "callback_query_id" => $this->callbackQueryId,
                "text" => $language === 'fa'
                    ? "📭 هنوز توری در لیستت ثبت نشده!\nمی تونی از تورهای فعال یکی رو انتخاب کنی و به ماجراجویی بپیوندی 🏕️✨"
                    : "📭 You haven't joined any tours yet!\nCheck the active tours and join your next adventure 🏕️✨",
                "show_alert" => true
            ]);


            return;
        }

        $keyboard = [];

        foreach ($tours as $index => $tour) {
            $tourList = ($index + 1) . ". " . $tour['title'] . "(" . $status[$tour['payment_status']] . ")" . "\n";
            $keyboard[] = [
                [
                    "text" => $tourList,
                    "callback_data" => "registered_tour_details_" . $tour['tour_id']
                ],

            ];
        }
        $keyboard[] = [
            [
                "text" => $language === 'fa' ? "🔙 بازگشت" : "🔙 Back",
                "callback_data" => "user_panel"
            ]
        ];

        $this->sendRequest("editMessageText", [
            "chat_id" => $chatId,
            "text" =>  "لیست تور های من:",
            "message_id" => $messageId,
            "reply_markup" => [
                "inline_keyboard" => $keyboard
            ]
        ]);
    }


    public function RegisteredTourUsers($chatId, $language)
    {
        $tours = $this->db->getToursByChatId($chatId);
        if (empty($tours)) {
            $this->sendRequest("answerCallbackQuery", [
                "callback_query_id" => $this->callbackQueryId,
                "text" => $language === 'fa'
                    ? "📭 هنوز توری در لیستت ثبت نشده!\nمی تونی از تورهای فعال یکی رو انتخاب کنی و به ماجراجویی بپیوندی 🏕️✨"
                    : "📭 You haven't joined any tours yet!\nCheck the active tours and join your next adventure 🏕️✨",
                "show_alert" => true
            ]);
            return;
        }

        $keyboard = [];

        foreach ($tours as $index => $tour) {
            $tourList = ($index + 1) . ". " . $tour['title'] . "\n";

            $keyboard[] = [

                [
                    "text" => $tourList,
                    "callback_data" => "tour_register_" . $tour['id']
                ]


            ];
        }

        $this->sendRequest("sendMessage", [
            "chat_id" => $chatId,
            "text" =>  "لیست تور های من:",
            "reply_markup" => [
                "inline_keyboard" => $keyboard
            ]
        ]);
    }


    public function showRegisteredUsers($chatId, $tourId, $callbackQueryId, $messageId)
    {
        $users = $this->db->getRegisteredUsersByTourId($tourId);

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


        $text = "کاربران ثبت نام شده در این تور:\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_leader_details_" . $userInfo['chat_id'] . "_" . $tourId
                ]
            ];
        }
        $keyboard[] = [['text' => '🔙 بازگشت ', 'callback_data' => "tour_details_" . $tourId]];

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


    public function updateTourParticipantCount($tourId)
    {
        $tourData        = $this->db->getTourById($tourId);
        $channelId       = $tourData['channel_id'];
        $channelMessageId = $tourData['channel_message_id'] ?? null;

        if (!$channelId || !$channelMessageId) {
            error_log("⚠️ Channel ID or message ID not available for tour ID {$tourId}");
            return;
        }

        // فقط تعداد ثبت نام کنندگان
        $participantCount = $this->db->countRegisters($tourId);


        // دکمه ها (inline_keyboard)
        $buttons = [
            [
                ['text' => '🏖 ثبت نام در تور', 'url' => $this->botLink . "register_{$tourId}"],
                ['text' => "👥 تعداد ثبت نام کنندگان: {$participantCount}", 'callback_data' => "noop"]
            ],

            [
                ['text' => '🕵️ ثبت نام لیدر', 'url' => $this->botLink . "join_leader"],
                ['text' => '👨‍⚖️ ثبت نام طبیعت گرد', 'url' => $this->botLink . "join_user"]
            ]
        ];
        $payload = [
            "chat_id"      => "$channelId",
            "message_id"   => $channelMessageId,
            "parse_mode"   => "HTML",
            "reply_markup" => json_encode(['inline_keyboard' => $buttons]),
        ];

        $this->sendRequest("editMessageReplyMarkup", [
            'chat_id'      => $channelId,
            'message_id'   => $channelMessageId,
            'reply_markup' => json_encode(['inline_keyboard' => $buttons])
        ]);
    }


    public function showRegisteredUsersChannel($chatId, $tourId)
    {
        // دریافت کاربران ثبت نام شده برای تور مشخص
        $users = $this->db->getRegisteredUsersByTourId($tourId);

        $tour = $this->db->getTourById($tourId);
        $channelMessageId = $tour['channel_message_id'];

        $text = "دوستانی که در این برنامه شرکت می کنند:\n\n";
        foreach ($users as $index => $user) {
            $userInfo = $this->db->registeredExplorerByUserId($user['explorer_id']);
            $text .= ($index + 1) . ". " . $userInfo['nick_name'] . " \n";
        }


        $leaderChannelId = $this->db->getLeaderChannel($chatId); // یا -1001234567890
        $this->sendRequest("sendMessage", [
            "chat_id" => $leaderChannelId,
            "text" => $text,
            "reply_to_message_id" => $channelMessageId

        ]);
    }


    public function showRegisteredUsersGroup($chatId, $tourId)
    {
        $users = $this->db->getRegisteredUsersByTourId($tourId);

        $tour = $this->db->getTourById($tourId);
        $groupMessageId = $tour['group_message_id'];

        $text = "دوستانی که در این برنامه شرکت می کنند:\n\n";
        foreach ($users as $index => $user) {
            $userInfo = $this->db->registeredExplorerByUserId($user['explorer_id']);
            $text .= ($index + 1) . ". " . $userInfo['nick_name'] .  " \n"; // فرض بر اینکه `name` و `phone` در جدول user هست
        }


        $leaderGroupId = $this->db->getLeaderGroup($chatId); // یا -1001234567890
        $this->sendRequest("sendMessage", [
            "chat_id" => $leaderGroupId,
            "text" => $text,
            "reply_to_message_id" => $groupMessageId

        ]);
    }


    public function UserList($chatId, $roleName)
    {
        $users = $this->db->getUsersByroleId($roleName);


        $keyboard = [];
        foreach ($users as $index => $user) {
            $userList = ($index + 1) . ". " . $user['first_name'] . " " . $user['last_name'] . "\n";
            $keyboard[] = [
                [
                    "text" => $userList,
                    "callback_data" => "user_details_" . $user['id']
                ]
            ];
        }
        $keyboard[] = [['text' => '🔙 بازگشت ', 'callback_data' => "go_to_menu"]];

        $this->sendRequest("sendMessage", [
            "chat_id" => $chatId,
            "text" =>  "لیست کاربران:",
            "reply_markup" => [
                "inline_keyboard" => $keyboard
            ]
        ]);
    }


    public function BotUserList($chatId)
    {
        $users = $this->db->getAllUsers();

        $keyboard = [];
        $row = [];

        foreach ($users as $index => $user) {
            $username = $user['username'];
            if (empty($username)) {
                $username = $user['first_name'];
            }
            $userList = ($index + 1) . ". " . $username;

            $row[] = [
                "text" => $userList,
                "callback_data" => "bot_user_details_" . $user['id']
            ];

            // هر دو دکمه یک ردیف، دکمه سوم به ردیف بعدی
            if (count($row) == 2) {
                $keyboard[] = $row;
                $row = [];
            }
        }

        // اگر تعداد کاربران فرد باشه دکمه آخر رو اضافه می کنیم
        if (count($row) > 0) {
            $keyboard[] = $row;
        }

        // دکمه بازگشت رو در یک ردیف جدا قرار بدیم
        $keyboard[] = [['text' => '🔙 بازگشت ', 'callback_data' => "bot_status"]];

        $this->sendRequest("sendMessage", [
            "chat_id" => $chatId,
            "text" => "لیست کاربران:",
            "reply_markup" => [
                "inline_keyboard" => $keyboard
            ]
        ]);
    }


    private function showAllUsers($chatId, $language, int $page = 1, $messageId = null): void
    {
        $itemsPerPage = 8;
        $offset = ($page - 1) * $itemsPerPage;
        $users = $this->db->getAllUsersPaginated($itemsPerPage, $offset);
        $totalUsers = $this->db->getAllUsersCount();

        $this->displayPaginatedUsers(
            $chatId,
            $messageId,
            $page,
            $language,
            $users,
            $totalUsers,
            "👑 لیست تمام کاربران",
            "bot_user_details_",
            "users_menu_page_",
            "هیچ کاربری در سیستم ثبت نشده است."
        );
    }


    private function displayPaginatedUsers($chatId, $messageId, $page, $language, $users, $totalUsers, $title, $detailsCallbackPrefix, $pageCallbackPrefix, $emptyTextMessage)
    {
        $itemsPerPage = 8;
        $totalPages = ceil($totalUsers / $itemsPerPage);

        if ($totalUsers === 0) {
            $text = $emptyTextMessage;
            $keyboard = [["text" => "🔙 بازگشت ", "callback_data" => "bot_status"]];
            if ($messageId) {
                $this->sendRequest("editMessageText", ["chat_id" => $chatId, "message_id" => $messageId, "text" => $text, "reply_markup" => json_encode(["inline_keyboard" => [$keyboard]])]);
            } else {
                $this->sendRequest("sendMessage", ["chat_id" => $chatId, "text" => $text, "reply_markup" => $this->getMainKeyboard()]);
            }
            return;
        }

        $userButtons = [];
        foreach ($users as $user) {
            $userButtons[] = ["text" => $user['username'], "callback_data" => $detailsCallbackPrefix . $user['id']];
        }
        $keyboard = array_chunk($userButtons, 1);

        $navigationRow = [];
        if ($page > 1) {
            $navigationRow[] = ["text" => "⬅️ قبلی", "callback_data" => $pageCallbackPrefix . ($page - 1)];
        }
        if ($page < $totalPages) {
            $navigationRow[] = ["text" => "بعدی ➡️", "callback_data" => $pageCallbackPrefix . ($page + 1)];
        }

        if (!empty($navigationRow)) {
            $keyboard[] = $navigationRow;
        }

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

        $fullTitle = $title . " (صفحه {$page} از {$totalPages})";
        $requestData = [
            "chat_id" => $chatId,
            "text" => $fullTitle,
            "reply_markup" => ["inline_keyboard" => $keyboard]
        ];


        $update = json_decode(file_get_contents('php://input'), true);
        $callbackQuery = $update['callback_query'] ?? null;

        if ($messageId && !isset($callbackQuery["message"]["photo"])) {
            $requestData['message_id'] = $messageId;
            $this->sendRequest("editMessageText", $requestData);
        } else {
            if ($messageId) {
                $this->sendRequest("deleteMessage", ["chat_id" => $chatId, "message_id" => $messageId]);
            }
            $this->sendRequest("sendMessage", $requestData);
        }
    }


    public function uploadGuidesMenu($chatId, $messageId = null, $parentId = null, $backDestination = 'go_to_menu')
    {
        $isAdmin = $this->db->isAdmin($chatId);

        $messageIdToDelete = $this->fileHandler->getMessageIds($chatId);
        if ($messageIdToDelete) {
            foreach ($messageIdToDelete as $oldMsgId) {
                $this->sendRequest("deleteMessage", ["chat_id" => $chatId, "message_id" => $oldMsgId]);
            }
            $this->fileHandler->clearMessageIds($chatId);
        }

        $keyboard = [];
        $text = "";
        $currentFolder = null;
        if ($parentId !== null) {
            $currentFolder = $this->db->getGuideFolderById($parentId);
        }

        if ($currentFolder && !empty($currentFolder['description'])) {
            $text = "📚 <b>" . $currentFolder['name'] . "</b>\n\n" . $currentFolder['description'] . "\n\n";
        } else {
            $text = "📚 <b>راهنما:</b>\n\n"
                . "در این بخش می توانید دسته بندی ها و آموزش های مرتبط با استفاده از ربات و پروژه ها را مشاهده کنید.\n"
                . "برای مشاهده هر راهنما یا دسته بندی، روی دکمه مربوطه کلیک کنید.\n\n";
        }

        $guideFolders = $this->db->getGuideFolders($parentId);

        if (!empty($guideFolders)) {
            $tempRow = [];
            foreach ($guideFolders as $index => $folder) {
                $tempRow[] = ['text' => '📁 ' . $folder['name'], 'callback_data' => 'view_guide_folder_' . $folder['id']];
                if (count($tempRow) === 2 || $index === count($guideFolders) - 1) {
                    $keyboard[] = $tempRow;
                    $tempRow = [];
                }
            }
        }

        // 2. نمایش آیتم های راهنما
        $guideItems = $this->db->getGuideItemsInFolder($parentId);
        if (!empty($guideItems)) {
            $tempRow = [];
            foreach ($guideItems as $index => $item) {
                $itemText = "";
                if ($item['type'] === 'text') {
                    $itemText = "📝 " . (mb_strlen($item['title']) > 30 ? mb_substr($item['title'], 0, 30) . '...' : ($item['title'] ?? 'بدون عنوان'));
                } else {
                    $itemText = "📎 " . (mb_strlen($item['title']) > 20 ? mb_substr($item['title'], 0, 20) . '...' : ($item['title'] ?? 'بدون عنوان'));
                }
                $tempRow[] = ['text' => $itemText, 'callback_data' => 'view_guide_item_' . $item['id']];
                if (count($tempRow) === 2 || $index === count($guideItems) - 1) {
                    $keyboard[] = $tempRow;
                    $tempRow = [];
                }
            }
        }
        if (empty($guideFolders) && empty($guideItems)) {
            $text .= "پوشه خالی\n\n";
        }

        if ($isAdmin) {
            $adminButtonsRow = [];
            $adminButtonsRow[] = ['text' => '➕ ایجاد پوشه', 'callback_data' => 'create_guide_folder_' . ($parentId ?? 'null')];
            if ($parentId) {
                $adminButtonsRow[] = ['text' => '➕ افزودن فایل جدید', 'callback_data' => 'set_guide_item_title_' . $parentId];
            }
            $keyboard[] = $adminButtonsRow;
            $keyboard[] = [['text' => '⚙️ تنظیمات این دسته بندی', 'callback_data' => 'manage_guide_folder_' . ($parentId ?? 'null')]]; // جدید
        }

        $backButtonCallback = '';
        $backButtonText = '';

        if ($parentId === null) {
            $backButtonCallback = $backDestination;
            $backButtonText = ($backDestination === 'admin_dashboard') ? '🔙 بازگشت به داشبورد' : '🔙 بازگشت به منو';
        } else {

            $grandparentId = $this->db->getParentFolderId($parentId);
            if ($grandparentId === null) {
                $backButtonText = '🔙 بازگشت به راهنما';
                $backButtonCallback = 'upload_guides_menu';
            } else {
                $backButtonText = '🔙 بازگشت';
                $backButtonCallback = 'view_guide_folder_' . $grandparentId;
            }
        }
        $keyboard[] = [['text' => $backButtonText, 'callback_data' => $backButtonCallback]];
        if ($messageId) {
            $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => $text,
                "parse_mode" => "HTML",
                "reply_markup" => json_encode([
                    "inline_keyboard" => $keyboard
                ])
            ]);
        } else {
            $this->sendRequest("sendMessage", [
                "chat_id" => $chatId,
                "text" => $text,
                "parse_mode" => "HTML",
                "reply_markup" => json_encode([
                    "inline_keyboard" => $keyboard
                ])
            ]);
        }
    }


    public function viewGuideItem($chatId, $itemId, $callbackQueryId = null)
    {
        $this->sendRequest('answerCallbackQuery', [
            'callback_query_id' => $this->callbackQueryId,
            'text' => 'در حال بارگذاری...'
        ]);
        $item = $this->db->getGuideItemById($itemId);

        if (!$item) {
            $this->sendRequest("sendMessage", [
                "chat_id" => $chatId,
                "text" => "❌ آیتم راهنما یافت نشد یا حذف شده است.",
                "parse_mode" => "HTML"
            ]);
            return;
        }

        $caption = $item['caption'] ?? '';
        $title = $item['title'] ?? 'بدون عنوان';
        $messageText = "📚 <b>{$title}</b>\n\n" . $caption;

        // ✅ اصلاح اصلی: چک کردن طول متن و تقسیم آن
        if (in_array($item['type'], ['photo', 'video', 'document'])) {

            $remainingText = '';
            $captionLimit = 1000;
            $captionPart = $messageText;
            $remainingText = '';

            if (mb_strlen($messageText) > $captionLimit) {
                $lastSpace = mb_strrpos(mb_substr($messageText, 0, $captionLimit), ' ');
                if ($lastSpace !== false) {
                    $captionPart = mb_substr($messageText, 0, $lastSpace);
                    $remainingText = trim(mb_substr($messageText, $lastSpace));
                } else {
                    $captionPart = mb_substr($messageText, 0, $captionLimit);
                    $remainingText = trim(mb_substr($messageText, $captionLimit));
                }
            }

            $messageData = [
                "chat_id" => $chatId,
                "caption" => $captionPart,
                "parse_mode" => "HTML",
            ];

            $method = "send" . ucfirst($item['type']);
            $messageData[$item['type']] = $item['file_id'];

            $firstResponse = $this->sendRequest($method, $messageData);
            $firstMessageId = $firstResponse['result']['message_id'] ?? null;
            if (!$firstMessageId) return;
            if (!empty($remainingText)) {
                $secondResponse = $this->sendRequest("sendMessage", [
                    "chat_id" => $chatId,
                    "text" => $remainingText,
                    "parse_mode" => "HTML",
                    "reply_to_message_id" => $firstMessageId,
                ]);

                $secondMessageId = $secondResponse['result']['message_id'] ?? null;
                if ($secondMessageId) {
                    $idsToDelete = "{$firstMessageId},{$secondMessageId}";
                    $this->sendRequest("editMessageReplyMarkup", [
                        "chat_id" => $chatId,
                        "message_id" => $secondMessageId,
                        "reply_markup" => ['inline_keyboard' => [[['text' => '🔙 بازگشت', 'callback_data' => 'delete_items_' . $idsToDelete]]]]
                    ]);
                }
            } else {
                $this->sendRequest("editMessageReplyMarkup", [
                    "chat_id" => $chatId,
                    "message_id" => $firstMessageId,
                    "reply_markup" => ['inline_keyboard' => [[['text' => '🔙 بازگشت', 'callback_data' => 'delete_items_' . $firstMessageId]]]]
                ]);
            }
        } else {
            $res = $this->sendRequest("sendMessage", [
                "chat_id" => $chatId,
                "text" => $messageText,
                "parse_mode" => "HTML"
            ]);
            if (isset($res['result']['message_id'])) {
                $this->sendRequest("editMessageReplyMarkup", [
                    "chat_id" => $chatId,
                    "message_id" => $res['result']['message_id'],
                    "reply_markup" => ['inline_keyboard' => [[['text' => '🔙 بازگشت', 'callback_data' => 'delete_items_' . $res['result']['message_id']]]]]
                ]);
            }
        }
    }


    public function manageGuideFolderOptions($chatId, $messageIdToDelete = null, $currentFolderId = null)
    {
        $isAdmin = $this->db->isAdmin($chatId);
        $messageIdToDelete = $this->fileHandler->getMessageIds($chatId);
        if ($messageIdToDelete) {
            foreach ($messageIdToDelete as $oldMsgId) {
                $this->sendRequest("deleteMessage", ["chat_id" => $chatId, "message_id" => $oldMsgId]);
            }
            $this->fileHandler->clearMessageIds($chatId);
        }

        $messagesToSend = [];
        $allSentMessageIds = [];

        // 2. گرفتن پوشه ها و آیتم ها در پوشه فعلی
        $childFolders = $this->db->getGuideFolders($currentFolderId);
        $guideItems = $this->db->getGuideItemsInFolder($currentFolderId); // آیتم های راهنما در پوشه فعلی

        // 3. افزودن پوشه ها به messagesToSend
        if (!empty($childFolders)) {
            $messagesToSend[] = [
                'text' => "📂 <b>پوشه ها:</b>\n",
                'keyboard' => []
            ];
            foreach ($childFolders as $folder) {
                $folderName = '📁 ' . $folder['name'];
                $folderDescription = $folder['description'] ? ("\n" . "<i>توضیحات:</i> " . htmlspecialchars($folder['description'])) : '';

                $messagesToSend[] = [
                    'text' => "<b>{$folderName}</b>{$folderDescription}",
                    'keyboard' => [
                        [
                            ['text' => '✏️ نام', 'callback_data' => 'edit_guide_folder_name_' . $folder['id']],
                            ['text' => '📝 توضیحات', 'callback_data' => 'edit_guide_folder_description_' . $folder['id']]
                        ],
                        [
                            ['text' => '🗑 حذف', 'callback_data' => 'confirm_delete_guide_folder_' . $folder['id']],
                        ]
                    ]
                ];
            }
        }

        // 4. افزودن آیتم های راهنما به messagesToSend
        if (!empty($guideItems)) {
            $messagesToSend[] = [
                'text' => "📄 <b>آیتم ها</b>\n",
                'keyboard' => []
            ];
            foreach ($guideItems as $item) {
                $itemTitle = $item['title'];
                $itemCaption = $item['caption'] ? ("\n" . "<i>کپشن:</i> " . htmlspecialchars(mb_substr($item['caption'], 0, 50)) . '...') : ''; // خلاصه کپشن
                $itemTypeText = '';
                switch ($item['type']) {
                    case 'text':
                        $itemTypeText = '📝 متن: ';
                        break;
                    case 'photo':
                        $itemTypeText = '🖼 عکس: ';
                        break;
                    case 'video':
                        $itemTypeText = '🎞 ویدیو: ';
                        break;
                    case 'document':
                        $itemTypeText = '📄 فایل: ';
                        break;
                }

                $messagesToSend[] = [
                    'text' => "<b>{$itemTypeText}{$itemTitle}</b>{$itemCaption}",
                    'keyboard' => [
                        [
                            ['text' => '👀 مشاهده', 'callback_data' => 'view_setings_guide_item_' . $item['id']]
                        ],
                        [
                            ['text' => '✏️ نام', 'callback_data' => 'edit_guide_item_name' . $item['id']],
                            ['text' => '✏️ کپشن', 'callback_data' => 'edit_guide_item_caption' . $item['id']],
                        ],
                        [

                            ['text' => '✏️ محتوا', 'callback_data' => 'edit_guide_item_media' . $item['id']],
                            ['text' => '🗑 حذف', 'callback_data' => 'delete_guide_item_' . $item['id']]
                        ]
                    ]
                ];
            }
        }

        // 5. پیام در صورت خالی بودن پوشه
        if (empty($childFolders) && empty($guideItems)) {
            $messagesToSend[] = [
                'text' => "پوشه خالی",
                'keyboard' => []
            ];
        }

        // 6. تعیین دکمه بازگشت (یکپارچه با نمایش محتوای پوشه)
        $backButtonCallback = '';
        $backButtonText = '';

        if ($currentFolderId === null) {
            $backButtonText = '🔙 بازگشت به راهنما';
            $backButtonCallback = 'upload_guides_menu';
        } else {
            $grandparentId = $this->db->getParentFolderId($currentFolderId);
            if ($grandparentId === null) {
                $backButtonText = '🔙 بازگشت به راهنما ';
                $backButtonCallback = 'upload_guides_menu';
            } else {
                $backButtonText = '🔙 بازگشت به دسته بندی های قبلی';
                $backButtonCallback = 'view_guide_folder_' . $grandparentId;
            }
        }

        $response = $this->sendRequest("editMessageText", [
            "chat_id" => $chatId,
            "message_id" => $this->messageId,
            "text" => "⚙️ <b>مدیریت دسته بندی ها:</b>\n\n",
            "parse_mode" => "HTML"
        ]);
        $allSentMessageIds[] = $response['result']['message_id'];

        // 7. ارسال تمامی پیام ها به صورت جداگانه
        $totalMessages = count($messagesToSend);
        foreach ($messagesToSend as $index => $msgData) {
            $currentKeyboard = $msgData['keyboard'];

            // اگر آخرین پیام در لیست ارسال است، دکمه بازگشت را اضافه کن
            if ($index === $totalMessages - 1) {
                $currentKeyboard[] = [['text' => $backButtonText, 'callback_data' => $backButtonCallback]];
                $this->sendRequest("sendMessage", [
                    "chat_id" => $chatId,
                    "text" => $msgData['text'],
                    "parse_mode" => "HTML",
                    "reply_markup" => json_encode(["inline_keyboard" => $currentKeyboard])
                ]);
            } else {
                $response = $this->sendRequest("sendMessage", [
                    "chat_id" => $chatId,
                    "text" => $msgData['text'],
                    "parse_mode" => "HTML",
                    "reply_markup" => json_encode(["inline_keyboard" => $currentKeyboard])
                ]);
            }

            if (isset($response['ok']) && $response['ok']) {
                $allSentMessageIds[] = $response['result']['message_id'];
            }
        }

        // 8. ذخیره تمامی message_id های ارسال شده برای این فرآیند
        $this->fileHandler->clearMessageIds($chatId);
        foreach ($allSentMessageIds as $msgId) {
            $this->fileHandler->addMessageId($chatId, $msgId);
        }
    }


    public function handleBotStats()
    {
        // آمار کلی ربات
        $stats = $this->db->getBotStats();
        // آمار عضویت کاربران
        $joiningStats = $this->db->getUserJoiningStats();
        // آمار فعالیت کاربران
        $activityStats = $this->db->getUserActivityStats();
        // آمار جدید
        $roleStats = $this->db->getRoleStats(); // تابع جدید
        $tourStats = $this->db->getTourStats(); // تابع جدید


        // بخش اول: وضعیت کلی ربات
        $message = "<b><code>📊 Bot Status</code></b> #Status\n";
        $message .= "👥 <b>Users:</b> All: <code>" . ($stats['total_users'] ?? 0) . "</code>\t\t";
        $message .= "🚫 Blocked: <code>" . ($stats['total_blocked_users'] ?? 0) . "</code>\n";
        $message .= "👮 <b>All Admin:</b> <code>" . ($stats['total_admins'] ?? 0) . "</code>\t\t";
        $message .= "📺 <b>Channels:</b> <code>" . ($stats['total_channels'] ?? 0) . "</code>\n";

        // بخش دوم: آمار نقش ها (بخش جدید)
        $message .= "➖➖➖➖➖➖➖➖➖➖➖➖➖➖\n";
        $message .= "<b>🎭 Roles Stats:</b>\n";
        $message .= "🏢 <b>Leaders:</b> <code>" . ($roleStats['total_leaders'] ?? 0) . "</code>\t\t";
        $message .= "🧑‍💻 <b>Users:</b> <code>" . ($roleStats['total_users'] ?? 0) . "</code>\n";


        $message .= "➖➖➖➖➖➖➖➖➖➖➖➖➖➖\n";
        $message .= "<b>📂 Tours Stats:</b>\n";
        $message .= "▪️ <i>Total Tours:</i> <code>" . ($tourStats['total_tours'] ?? 0) . "</code>\n";


        // // بخش چهارم: آمار مالی (بخش جدید)
        // $message .= "➖➖➖➖➖➖➖➖➖➖➖➖➖➖\n";
        // $message .= "<b>💳 Financial Stats:</b>\n";
        // $message .= "▫️ <i>Pending Withdrawals:</i> <code>" . ($financialStats['pending_withdrawals'] ?? 0) . "</code>\n";

        // بخش پنجم: آمار عضویت کاربران
        $message .= "➖➖➖➖➖➖➖➖➖➖➖➖➖➖\n";
        $message .= "<b>💹 User Joined Status:</b>\n";
        $message .= "🕹 <i>Joined Today:</i> <code>" . ($joiningStats['joined_today'] ?? 0) . "</code>\t\t";
        $message .= "🕹 <i>Yesterday:</i> <code>" . ($joiningStats['joined_yesterday'] ?? 0) . "</code>\n";
        $message .= "🕹 <i>Last Week:</i> <code>" . ($joiningStats['joined_last_week'] ?? 0) . "</code>\t\t";
        $message .= "🕹 <i>Last Month:</i> <code>" . ($joiningStats['joined_last_month'] ?? 0) . "</code>\n";

        // بخش ششم: آمار فعالیت کاربران
        $message .= "➖➖➖➖➖➖➖➖➖➖➖➖➖➖\n";
        $message .= "<b>🖲 User Activity:</b>\t\t";
        $message .= "🟢 <i>Online:</i> <code>" . ($activityStats['online_users'] ?? 0) . "</code>\n";
        $message .= "⏰ <i>Last Hour:</i> <code>" . ($activityStats['last_hour_users'] ?? 0) . "</code>\t\t";
        $message .= "⏳ <i>Yesterday:</i> <code>" . ($activityStats['yesterday_users'] ?? 0) . "</code>\n";
        $message .= "📆 <i>Last Week:</i> <code>" . ($activityStats['last_week_users'] ?? 0) . "</code>\t\t";
        $message .= "📅 <i>Last Month:</i> <code>" . ($activityStats['last_month_users'] ?? 0) . "</code>\n";

        $inlineKeyboard = [
            [
                ["text" => "👤 10 Last Users", "callback_data" => "show_last_users"],
                ["text" => "🚫 10 Last Blocked Users", "callback_data" => "show_last_blocked_users"]
            ],
            [
                ["text" => "🧑‍💻 10 Last Leaders", "callback_data" => "show_last_leaders"],
                ["text" => "🏢 10 Last Explorers", "callback_data" => "show_last_explorers"]
            ],
            [
                ['text' => '👥 Admins', 'callback_data' => 'admins'],
                ['text' => '🤖 Users',   'callback_data' => 'bot_users']
            ],
            [
                ["text" => "🔙 بازگشت", "callback_data" => "admin_dashboard"]
            ]
        ];

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


    public function showLastLeaders()
    {
        $leaders = $this->db->getLastLeaders(10);
        $message = "<b>🧑‍💻 10 Last Registered Leaders:</b>\n\n";

        if (empty($leaders)) {
            $message .= "No leaders found.";
        } else {
            foreach ($leaders as $index => $leader) {
                $message .= "<b>" . ($index + 1) . ".</b> <a href='tg://user?id=" . $leader['chat_id'] . "'>" . htmlspecialchars($leader['full_name']) . "</a>\n";
                $message .= "<b>Username:</b> @" . ($leader['username'] ?? 'Not set') . "\n";
                $message .= "<b>Date:</b> " . $leader['created_at'] . "\n\n";
            }
        }

        $this->sendRequest("editMessageText", [
            "chat_id" => $this->chatId,
            "message_id" => $this->messageId,
            "text" => $message,
            "parse_mode" => "HTML",
            "reply_markup" => json_encode([
                "inline_keyboard" => [
                    [["text" => "🔙 Back to Stats", "callback_data" => "bot_status"]]
                ]
            ])
        ]);
    }


    public function showLastExplorers()
    {
        $explorers = $this->db->getLastExplorers(10);
        $message = "<b>🧑‍💻 10 Last Registered Explorers:</b>\n\n";

        if (empty($explorers)) {
            $message .= "No explorers found.";
        } else {
            foreach ($explorers as $index => $explorer) {
                $message .= "<b>" . ($index + 1) . ".</b> <a href='tg://user?id=" . $explorer['chat_id'] . "'>" . htmlspecialchars($explorer['full_name']) . "</a>\n";
                $message .= "<b>Username:</b> @" . ($explorer['username'] ?? 'Not set') . "\n";
                $message .= "<b>Date:</b> " . $explorer['created_at'] . "\n\n";
            }
        }

        $this->sendRequest("editMessageText", [
            "chat_id" => $this->chatId,
            "message_id" => $this->messageId,
            "text" => $message,
            "parse_mode" => "HTML",
            "reply_markup" => json_encode([
                "inline_keyboard" => [
                    [["text" => "🔙 Back to Stats", "callback_data" => "bot_status"]]
                ]
            ])
        ]);
    }


    public function showLastUsers()
    {
        $users = $this->db->getLastTenUsers();
        $message = "<b>🏢 10 Last Active Users:</b>\n\n";

        if (empty($users)) {
            $message .= "No users found.";
        } else {
            foreach ($users as $index => $user) {
                $message .= "<b>" . ($index + 1) . ".</b> <a href='tg://user?id=" . $user['chat_id'] . "'>" . htmlspecialchars($user['first_name']) . "</a>\n";
                $message .= "<b>Username:</b> @" . ($user['username'] ?? 'Not set') . "\n";
            }
        }

        $this->sendRequest("editMessageText", [
            "chat_id" => $this->chatId,
            "message_id" => $this->messageId,
            "text" => $message,
            "parse_mode" => "HTML",
            "reply_markup" => json_encode([
                "inline_keyboard" => [
                    [["text" => "🔙 Back to Stats", "callback_data" => "bot_status"]]
                ]
            ])
        ]);
    }

}
