<?php

namespace Bot\BotHandler;

trait TourFormTrait
{

    public function handleInputStep($chatId, $messageId, $step, $text, $backCallback, $userLanguage)
    {
        $this->fileHandler->saveMessageId($this->chatId, $messageId);

        if ($this->fileHandler->saveState($chatId, 'awaiting_' . $step)) {
            $response = $this->sendRequest("editMessageText", [
                "chat_id" => $chatId,
                "message_id" => $messageId,
                "text" => $text,
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [
                            ["text" => "🔙 بازگشت", "callback_data" => $backCallback],
                            ["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()
            ]);
        }
    }


    public  function end_date_options($chatId, $messageId, $text)
    {
        $today = new DateTime('now', new DateTimeZone('Asia/Tehran'));
        $tomorrow = (clone $today)->modify('+1 day');
        $dayAfterTomorrow = (clone $today)->modify('+2 days');
        $oneWeekLater = (clone $today)->modify('+7 days');

        $buttons = [
            [
                ["text" => "📅 امروز", "callback_data" => "set_tour_end_date_" . $today->format('Y-m-d')],
                ["text" => "🗓️ فردا", "callback_data" => "set_tour_end_date_" . $tomorrow->format('Y-m-d')]
            ],
            [
                ["text" => "🗓️ پس  فردا", "callback_data" => "set_tour_end_date_" . $dayAfterTomorrow->format('Y-m-d')],
                ["text" => "🗓️ یک هفته دیگر", "callback_data" => "set_tour_end_date_" . $oneWeekLater->format('Y-m-d')]
            ],

            [["text" => "⬅️ بازگشت", "callback_data" => "back_await_start_date"]]
        ];

        $promptText = "🗓️ <b> تاریخ پایان تور</b>\n\n"
            . "لطفاً تاریخ پایان تور را <b>انتخاب</b> کنید،\n"
            . "یا <b>تاریخ دقیق</b> (مثال: `1404/05/10` یا `2025-08-01`) وارد کنید:";

        $response = $this->sendRequest("editMessageText", [
            "chat_id" => $chatId,
            "message_id" => $messageId,
            "text" => $text . "\n " . $promptText,
            "parse_mode" => "HTML",
            "reply_markup" => json_encode(["inline_keyboard" => $buttons])
        ]);
        return $response;
    }


    private function generateTourSummaryText($tourData)
    {
        if (empty($tourData)) {
            return "";
        }

        // فرض می کنیم فرم ما همیشه 'tour_creation' است.
        // در آینده می توانید این بخش را هم داینامیک تر کنید تا از state خوانده شود.
        $formKey = 'tour_creation';
        $fieldsConfig = $this->forms[$formKey]['fields'];

        $summary = "<b>✅ خلاصه تور تا این لحظه:</b>\n";
        $hasData = false;

        // به جای نوشتن دستی، روی تمام فیلدهای تعریف شده در Forms.php حلقه می زنیم
        foreach ($fieldsConfig as $fieldKey => $fieldInfo) {

            // اگر داده ای برای این فیلد ثبت شده بود
            if (isset($tourData[$fieldKey]) && !empty($tourData[$fieldKey])) {
                $hasData = true;
                $label = $fieldInfo['label'];
                $value = $tourData[$fieldKey];
                $displayValue = '';

                // بر اساس نوع داده، آن را برای نمایش فرمت بندی می کنیم
                switch ($fieldKey) {
                    case 'start_date':
                    case 'end_date':
                        $displayValue = $this->gregorianToJalali($value);
                        break;

                    case 'transport_options':
                    case 'services_options':
                        $allOptions = $fieldInfo['options'];
                        $selectedLabels = array_map(fn($k) => $allOptions[$k] ?? $k, $value);
                        $displayValue = implode('، ', $selectedLabels);
                        break;

                    case 'location':
                        $displayValue = '✅ (لوکیشن دریافت شد)';
                        break;

                    case 'banner':
                        $displayValue = '✅ (تصویر بنر دریافت شد)';
                        break;

                    case 'pricing':
                        $priceStrings = [];
                        if (is_array($value)) {
                            foreach ($value as $priceInfo) {
                                if (is_array($priceInfo) && isset($priceInfo['label'], $priceInfo['amount'])) {
                                    $priceStrings[] = htmlspecialchars($priceInfo['label']) . ": " . number_format($priceInfo['amount']) . " تومان";
                                }
                            }
                        }
                        $displayValue = empty($priceStrings) ? '✅ (ثبت شد)' : implode("\n- ", $priceStrings);
                        break;

                    default:
                        if (is_array($value)) {
                            $displayValue = '✅ (اطلاعات ثبت شد)';
                        } else {
                            $displayValue = htmlspecialchars((string)$value);
                        }
                        break;
                }

                $summary .= "<b>" . htmlspecialchars($label) . ":</b> " . $displayValue . "\n";
            }
        }

        $summary .= "\n";

        // اگر هیچ داده ای برای نمایش وجود نداشت، یک متن خالی برمی گردانیم
        return $hasData ? $summary : "";
    }


    private function generateTourDetailsText($tourId): string
    {
        $tour = $this->db->getTourById($tourId);
        $summaryText = "🏕️ <b>~ " . htmlspecialchars($tour['title'] ?? '') . " ~</b> 🏕️\n\n";
        if (!empty($tour['description'])) $summaryText .=  htmlspecialchars($tour['description']) . "\n\n";




        $summaryText .= "<b> اطلاعات کلی برنامه </b>\n";
        if (!empty($tour['difficulty'])) {
            $difficultyLabels = [
                '1' => 'آسان (۱ از ۵)',
                '2' => 'معمولی (۲ از ۵)',
                '3' => 'متوسط (۳ از ۵)',
                '4' => 'چالش‌برانگیز (۴ از ۵)',
                '5' => 'سخت (۵ از ۵)'
            ];
            $difficultyText = $difficultyLabels[$tour['difficulty']] ?? htmlspecialchars($tour['difficulty']);
            $summaryText .= "<blockquote>🧗‍♂️ <b>سطح سختی:</b> " . $difficultyText . "\n";
        }
        if (!empty($tour['origin_address'])) {
            $summaryText .= "🚩 <b>مبدا حرکت:</b> " . htmlspecialchars($tour['origin_address']) . "\n";
        }
        if (!empty($tour['region'])) $summaryText .= "📍 <b>منطقه:</b> " . htmlspecialchars($tour['region']) . "\n";
        if (!empty($tour['latitude']) && !empty($tour['longitude'])) {
            $lat = $tour['latitude'];
            $lon = $tour['longitude'];
            $summaryText .= "🗺️ <b>لوکیشن منطقه:</b> <a href='https://www.google.com/maps/search/?api=1&query={$lat},{$lon}'>مشاهده روی نقشه</a>\n";
        }
        $summaryText .= "</blockquote>";
        $weekDays = [
            'Saturday' => 'شنبه',
            'Sunday' => 'یک شنبه',
            'Monday' => 'دو شنبه',
            'Tuesday' => 'سه شنبه',
            'Wednesday' => 'چهار شنبه',
            'Thursday' => 'پنج شنبه',
            'Friday' => 'جمعه',
        ];

        $summaryText .= "<b> زمان بندی </b>\n";
        if (!empty($tour['start_date'])) {
            $start_dt = new DateTime($tour['start_date']);
            $jalali_date = $this->gregorianToJalali($start_dt->format('Y-m-d'));
            $time = $start_dt->format('H:i');
            $dayOfWeek = $weekDays[$start_dt->format('l')]; // گرفتن نام روز هفته
            $summaryText .= "<blockquote>🗓️ <b>حرکت:</b> " . $jalali_date . " ($dayOfWeek)، ساعت " . $time . "\n";
        }

        if (!empty($tour['end_date'])) {
            $end_dt = new DateTime($tour['end_date']);
            $jalali_date = $this->gregorianToJalali($end_dt->format('Y-m-d'));
            $time = $end_dt->format('H:i');
            $dayOfWeek = $weekDays[$end_dt->format('l')]; // گرفتن نام روز هفته
            $summaryText .= "🗓️ <b>بازگشت:</b> " . $jalali_date . " ($dayOfWeek)، ساعت " . $time . "</blockquote>\n";
        }

        if (!empty($tour['pricing'])) {
            $pricingData = $tour['pricing']; // Already an array from Database class
            if (is_array($pricingData) && !empty($pricingData)) {
                $summaryText .= "💰 <b>هزینه تور:</b>";
                $summaryText .= "<blockquote>";
                foreach ($pricingData as $priceInfo) {
                    if (is_array($priceInfo) && $priceInfo['amount'] > 0) {

                        $summaryText .= "• " . htmlspecialchars($priceInfo['label']) . ": <b>" . number_format($priceInfo['amount']) . "</b> تومان\n";
                    } else if ($priceInfo['amount'] == 0) {
                        $summaryText .= "• " . htmlspecialchars($priceInfo['label']) . ": <b>رایگان</b> \n";
                    }
                }
                $summaryText .= "</blockquote>";
            }
        }

        if (!empty($tour['services_options'])) {
            $servicesData = $tour['services_options'];
            if (is_array($servicesData) && !empty($servicesData)) {
                $allServices = ['insurance' => '🛡️ بیمه', 'accommodation' => '🏡 اسکان', 'meals' => '🍱 وعده غذایی', 'tour_guide' => '🧑‍🏫 راهنمای تور'];
                $summaryText .= "🛎️ <b>خدمات تور:</b><blockquote>";
                foreach ($servicesData as $serviceKey) {
                    $summaryText .= "- " . ($allServices[$serviceKey] ?? $serviceKey) . "\n";
                }
                if (in_array('meals', $servicesData) && !empty($tour['meal_details'])) {
                    $summaryText .= "  - <i>(جزئیات: " . htmlspecialchars($tour['meal_details']) . ")</i>\n";
                }
                $summaryText .= "</blockquote>";
            }
        }

        if (!empty($tour['required_items'])) $summaryText .= "🎒 <b>لوازم مورد نیاز:</b><blockquote>" . htmlspecialchars($tour['required_items']) . "</blockquote>" . "\n";

        if (!empty($tour['notes'])) $summaryText .= "⚠️ <b>نکات مهم:</b><blockquote>" . htmlspecialchars($tour['notes']) . "</blockquote>" . "\n";
        if (!empty($tour['capacity'])) $summaryText .= "👥 <b>ظرفیت:</b> " . htmlspecialchars($tour['capacity']) . " نفر\n";


        return $summaryText;
    }


    private function startTourRegistrationProcess(int $chatId, int $tourId, ?int $messageId = null): void
    {
        $tour = $this->db->getTourById($tourId);

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

        if (!$this->db->registeredExplorerByUserId($chatId)) {
            $this->fileHandler->setTempData($chatId, ['pending_tour_id' => $tourId]);
            $this->sendRequest("sendMessage", [
                "chat_id" => $chatId,
                "text" => "برای ثبت نام در تور، لطفاً ابتدا اطلاعات خود را در ربات تکمیل کنید.",
                "reply_markup" => json_encode(["inline_keyboard" => [[["text" => "✅ شروع ثبت نام", "callback_data" => "register"]]]])
            ]);
            return;
        }

        $capacity_count = $this->db->checkCapacityTour($tourId);
        if ($tour['is_full'] == 1 || $capacity_count >= $tour['capacity']) {
            $sendError('❌ ظرفیت تور تکمیل شده است.');
            return;
        }

        if ($this->db->isUserPayedComplete($chatId, $tourId)) {
            $sendError("شما قبلاً در این تور ثبت نام کرده و پرداخت را تکمیل کرده اید!");
            return;
        }

        $username = $this->db->getUsernameByChatId($chatId);
        $this->db->registerUserToTour($tour['chat_id'], $chatId, $tourId, $username, 'pending');

        $this->showVehicleSelectionMenu($chatId, $tourId, $messageId);
    }


    private function showVehicleSelectionMenu(int $chatId, int $tourId, ?int $messageId = null): void
    {
        $tour = $this->db->getTourById($tourId);
        $summaryText = $this->generateTourDetailsText($tourId);
        $message = $summaryText . "\n\n" . "لطفاً برای ادامه ثبت نام، وسیله نقلیه مورد نظر خود را انتخاب کنید:";

        $vehicleButtons = [];
        $pricingData = $tour['pricing'];
        foreach ($pricingData as $vehicle => $priceInfo) {
            $label = $priceInfo['label'];
            $vehicleButtons[] = [["text" => $label, "callback_data" => "select_vehicle_{$vehicle}_{$tourId}"]];
        }
        $vehicleButtons[] = [["text" => " ❌ انصراف ", "callback_data" => "go_to_menu"]];

        $requestData = [
            "chat_id" => $chatId,
            "text" => $message,
            "parse_mode" => "HTML",
            "reply_markup" => json_encode(["inline_keyboard" => $vehicleButtons])
        ];

        if ($messageId) {
            $requestData['message_id'] = $messageId;
            $this->sendRequest("editMessageText", $requestData);
        } else {
            $this->sendRequest("sendMessage", $requestData);
        }
    }


    private function showQuantitySelector(int $chatId, int $tourId, int $messageId, int $quantity = 1): void
    {
        $tour = $this->db->getTourById($tourId);
        $tempData = $this->fileHandler->getTempData($chatId);
        $selectedVehicle = $tempData['selected_vehicle'] ?? null;

        if (!$tour || !$selectedVehicle) {
            $this->sendRequest("editMessageText", ["chat_id" => $chatId, "message_id" => $messageId, "text" => "❌ خطایی رخ داده است. لطفاً دوباره تلاش کنید."]);
            return;
        }

        $pricingData = $tour['pricing'];
        $pricePerPerson = $pricingData[$selectedVehicle]['amount'] ?? 0;
        $totalPrice = $pricePerPerson * $quantity;
        $vehicleLabel = $pricingData[$selectedVehicle]['label'] ?? 'انتخاب نشده';

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

        $text = "🎟️ <b>ثبت نام در تور: " . htmlspecialchars($tour['title']) . "</b>\n\n";
        $text .= "<blockquote>";
        $text .= "<b>وسیله نقلیه:</b> " . htmlspecialchars($vehicleLabel) . "\n";
        $text .= "<b>هزینه هر نفر:</b> " . number_format($pricePerPerson) . " تومان\n";
        $text .= "</blockquote>\n";
        $text .= "تعداد نفرات خود را مشخص کنید:\n\n";
        $text .= "💰 <b>هزینه نهایی: " . number_format($totalPrice) . " تومان</b>";

        $keyboard = [];
        $quantityRow = [];

        if ($quantity > 1) {
            $quantityRow[] = ['text' => '➖', 'callback_data' => "change_quantity_{$tourId}_" . ($quantity - 1)];
        } else {
            $quantityRow[] = ['text' => ' ', 'callback_data' => 'no_op'];
        }

        $quantityRow[] = ['text' => "👤 " . $quantity, 'callback_data' => 'no_op'];

        if ($quantity < $remainingCapacity) {
            $quantityRow[] = ['text' => '➕', 'callback_data' => "change_quantity_{$tourId}_" . ($quantity + 1)];
        } else {
            $quantityRow[] = ['text' => ' ', 'callback_data' => 'no_op'];
        }
        $keyboard[] = $quantityRow;

        $keyboard[] = [['text' => '✅ تایید و ادامه', 'callback_data' => "confirm_quantity_{$tourId}_{$quantity}"]];
        $keyboard[] = [['text' => '🔙 بازگشت (تغییر وسیله نقلیه)', 'callback_data' => "register_active_{$tourId}"]];


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


    private function askForNextPriceInEditMode($chatId, $messageId)
    {
        $state = $this->stateManager->getState($chatId);
        if (!$state || ($state['next_action'] ?? '') !== 'awaiting_new_price') {
            return;
        }

        $vehiclesToPrice = $state['context']['vehicles_to_price'];

        // اگر لیست وسایل نقلیه برای قیمت گذاری خالی بود، فرآیند را تمام کن
        if (empty($vehiclesToPrice)) {
            $tourId = $state['context']['tour_id'];
            $newPricingData = $state['context']['new_pricing_data'];

            // ذخیره نهایی قیمت ها در دیتابیس
            $this->db->updateTourField($tourId, 'pricing', json_encode($newPricingData));
            $this->stateManager->clearState($chatId);

            $keyboard = [
                "inline_keyboard" => [
                    [['text' => '🔙 بازگشت به منوی ویرایش', 'callback_data' => 'edit_tour_' . $tourId]]
                ]
            ];
            $this->sendRequest("sendMessage", [
                "chat_id" => $chatId,
                "text" => "✅ تمام قیمت ها با موفقیت تنظیم شدند.",
                "reply_markup" => json_encode($keyboard)
            ]);
            // بازگشت به منوی ویرایش اصلی
            $fakeCallbackQuery = ["data" => "edit_tour_" . $tourId, "message" => ["message_id" => $messageId, "chat" => ['id' => $chatId]]];
            $this->handleCallbackQuery($fakeCallbackQuery);
            return;
        }

        // دریافت اولین وسیله نقلیه از لیست برای قیمت گذاری
        $vehicleToPrice = $vehiclesToPrice[0];
        $fieldConfig = $this->forms['tour_creation']['fields']['transport_options'];
        // دریافت برچسب فارسی و خوانا برای نمایش به کاربر
        $vehicleLabel = $fieldConfig['options'][$vehicleToPrice] ?? $vehicleToPrice;

        $this->sendRequest("editMessageText", [
            "chat_id" => $chatId,
            "message_id" => $messageId,
            "text" => "💰 لطفاً قیمت جدید برای «" . htmlspecialchars($vehicleLabel) . "» را به تومان وارد کنید:"
        ]);
    }


    public function updateTourPost(int $tourId)
    {
        $tourData = $this->db->getTourById($tourId);
        if (!$tourData) {
            error_log("updateTourPost: Tour with ID {$tourId} not found.");
            return;
        }

        $targets = [];
        if (!empty($tourData['channel_id']) && !empty($tourData['channel_message_id'])) {
            $targets[] = ['id' => $tourData['channel_id'], 'message_id' => $tourData['channel_message_id']];
        }
        if (!empty($tourData['group_id']) && !empty($tourData['group_message_id'])) {
            $targets[] = ['id' => $tourData['group_id'], 'message_id' => $tourData['group_message_id']];
        }

        if (empty($targets)) {
            error_log("updateTourPost: No channel/group post found for tour ID {$tourId}. Skipping update.");
            return;
        }

        // تولید محتوای به‌روز شده
        $summaryText = $this->generateTourDetailsText($tourId);
        $participantCount = $this->db->countRegisters($tourId);

        $replyMarkup = [
            'inline_keyboard' => [
                [
                    ['text' => '🏖 ثبت نام در تور', 'url' => $this->botLink . "register_{$tourId}"],
                    // ['text' => "👥 تعداد ثبت نام کنندگان: {$participantCount}", 'callback_data' => "noop"]
                ],
                [
                    ['text' => '🕵️ ثبت نام لیدر', 'url' => $this->botLink . "join_leader"],
                    ['text' => '👨‍⚖️ ثبت نام طبیعت گرد', 'url' => $this->botLink . "join_user"]
                ]
            ]
        ];

        foreach ($targets as $target) {
            $this->editTextOrCaption($target['id'], $target['message_id'], $summaryText, $replyMarkup);
        }
    }


    private function showToursList($chatId, $language, int $page = 1, $messageId = null): void
    {
        $itemsPerPage = 8;
        $offset = ($page - 1) * $itemsPerPage;
        $tours = $this->db->getToursByChatIdPaginated($chatId, $itemsPerPage, $offset);
        $totalTours = $this->db->getToursCountByChatId($chatId);

        $this->displayPaginatedTours(
            $chatId,
            $messageId,
            $page,
            $language,
            $tours,
            $totalTours,
            "🗺️ لیست تورهای شما",
            "tour_details_",
            "leader_tours_menu_page_",
            "شما هنوز هیچ توری ایجاد نکرده اید."
        );
    }


    private function showAllTours($chatId, $language, int $page = 1, $messageId = null): void
    {
        $itemsPerPage = 8;
        $offset = ($page - 1) * $itemsPerPage;
        $tours = $this->db->getAllToursPaginated($itemsPerPage, $offset);
        $totalTours = $this->db->getAllToursCount();

        $this->displayPaginatedTours(
            $chatId,
            $messageId,
            $page,
            $language,
            $tours,
            $totalTours,
            "👑 لیست تمام تورها",
            "admin_tour_details_",
            "tours_menu_page_",
            "هیچ توری در سیستم ثبت نشده است.",
            "admin_dashboard",
            "🔙 بازگشت به داشبورد"
        );
    }


    private function showActiveToursList($chatId, $language, int $page = 1, $messageId = null): void
    {
        $itemsPerPage = 8;
        $offset = ($page - 1) * $itemsPerPage;
        $tours = $this->db->getActiveTours($itemsPerPage, $offset);
        $totalTours = $this->db->getActiveToursCount();

        $this->displayPaginatedTours(
            $chatId,
            $messageId,
            $page,
            $language,
            $tours,
            $totalTours,
            "📜 لیست تورهای فعال",
            "active_tour_details_",
            "active_tours_page_",
            "هیچ تور فعالی یافت نشد."
        );
    }


    private function displayPaginatedTours($chatId, $messageId, $page, $language, $tours, $totalTours, $title, $detailsCallbackPrefix, $pageCallbackPrefix, $emptyTextMessage, $backCallback = 'go_to_menu', $backButtonText = "🔙 بازگشت به منو")
    {
        $itemsPerPage = 8;
        $totalPages = ceil($totalTours / $itemsPerPage);

        if ($totalTours === 0) {
            $text = $emptyTextMessage;
            $this->sendRequest("answerCallbackQuery", [
                "callback_query_id" => $this->callbackQueryId,
                "text" => $text,
                "show_alert" => true
            ]);
            return;
        }

        $tourButtons = [];
        foreach ($tours as $tour) {
            $tourButtons[] = ["text" => $tour['title'], "callback_data" => $detailsCallbackPrefix . $tour['id']];
        }
        $keyboard = array_chunk($tourButtons, 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" => $backButtonText, "callback_data" => $backCallback]];

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

}
