<?php

namespace Bot\BotHandler;

trait PaymentTrait
{

    public function handleSuccessfulPayment($update): void
    {
        $userLanguage = $this->db->getUserLanguage($this->chatId);

        if (isset($update['message']['successful_payment'])) {
            $chatId = $update['message']['chat']['id'];
            $payload = $update['message']['successful_payment']['invoice_payload'];
            $successfulPayment = $update['message']['successful_payment'];

            if (str_starts_with($payload, "access_tour_")) {
                $tourId = intval(str_replace("access_tour_", "", $payload));
                $amountPaid = $successfulPayment['total_amount'];
                $refId = $successfulPayment['telegram_payment_charge_id'];
                $currency = "XTR";

                $tourDetails = $this->db->getTourDetailsWithPrice($tourId);
                if (!$tourDetails) {
                    error_log("❌ Tour not found for ID: $tourId");
                    $this->sendRequest("sendMessage", [
                        "chat_id" => $chatId,
                        "text" => $userLanguage === 'fa' ? "⚠️ تور موردنظر پیدا نشد." : "⚠️ The requested tour was not found."
                    ]);
                    return;
                }

                // --- شروع تغییرات ---

                // ۱. خواندن تعداد و وسیله نقلیه از فایل موقت
                $temp = $this->fileHandler->getTempData($this->chatId);
                $selectedVehicle = $temp['selected_vehicle'] ?? null;
                $quantity = $temp['quantity'] ?? 1; // خواندن تعداد

                $this->db->insertUserPaymentStar($chatId, $tourId, $amountPaid, $refId);

                // ۲. پاس دادن "تعداد" به تابع دیتابیس
                $this->db->updateTourPaymentStatus($chatId, $tourId, 'completed', $refId, $selectedVehicle, null, $quantity);

                $this->updateTourParticipantCount($tourId);
                $registration = $this->db->getUserTourRegistration($chatId, $tourId);

                // ۳. اصلاح پیام موفقیت برای کاربر
                $messages = [
                    'fa' => "✅ پرداخت شما با موفقیت انجام شد.\n\n"
                        . "🏆 <b>تور:</b> {$tourDetails['title']}\n"
                        . "👥 <b>تعداد نفرات:</b> {$quantity} نفر\n" // این خط اضافه شد
                        . "💰 <b>مبلغ پرداخت شده:</b> {$amountPaid} Star\n"
                        . "🔢 <b>شماره مرجع:</b> {$refId}\n\n"
                        . "شما اکنون در این تور ثبت نام شده اید!",
                    'en' => "✅ Your payment was successful.\n\n"
                        . "🏆 <b>Tour:</b> {$tourDetails['title']}\n"
                        . "👥 <b>Quantity:</b> {$quantity}\n" // This line was added
                        . "💰 <b>Amount Paid:</b> {$amountPaid} Star\n"
                        . "🔢 <b>Reference ID:</b> {$refId}\n\n"
                        . "You are now registered for this tour!"
                ];

                // --- پایان تغییرات ---

                $exitButton = [
                    'inline_keyboard' => [
                        [["text" =>  "🏠 بازگشت به منو", "callback_data" => "go_to_menu"]],
                    ]
                ];

                $this->sendRequest("sendMessage", [
                    "chat_id" => $chatId,
                    "text" => $messages[$userLanguage] ?? $messages['en'],
                    "parse_mode" => "HTML",
                    "reply_markup" => json_encode($exitButton)
                ]);

                $admins = $this->db->getAdmins();
                foreach ($admins as $admin) {
                    $adminMessages = [
                        'fa' => "💸 <b>پرداخت جدید (استار) برای تور!</b>\n\n"
                            . "👤 <b>کاربر:</b> @{$this->db->getUsernameByChatId($chatId)}\n"
                            . "📌 <b>Chat ID:</b> {$chatId}\n"
                            . "🏆 <b>تور:</b> {$tourDetails['title']}\n"
                            . "👥 <b>تعداد نفرات:</b> {$quantity} نفر\n"
                            . "💰 <b>مبلغ:</b> {$amountPaid} XTR\n"
                            . "🔢 <b>شماره مرجع:</b> {$refId}",
                        'en' => "💸 <b>New Tour Payment (Star)!</b>\n\n"
                            . "👤 <b>User:</b> @{$this->db->getUsernameByChatId($chatId)}\n"
                            . "📌 <b>Chat ID:</b> {$chatId}\n"
                            . "🏆 <b>Tour:</b> {$tourDetails['title']}\n"
                            . "👥 <b>Quantity:</b> {$quantity}\n"
                            . "💰 <b>Amount:</b> {$amountPaid} XTR\n"
                            . "🔢 <b>Reference ID:</b> {$refId}"
                    ];

                    $this->sendRequest("sendMessage", [
                        "chat_id" => $admin['chat_id'],
                        "text" => $adminMessages[$userLanguage] ?? $adminMessages['en'],
                        "parse_mode" => "HTML"
                    ]);
                }

                file_put_contents('log.txt', date('Y-m-d H:i:s') . " - Payment completed: chat_id={$chatId}, tour_id={$tourId}, amount={$amountPaid}, refId={$refId}, currency={$currency}\n", FILE_APPEND);
            } else {
                $this->sendRequest("sendMessage", [
                    "chat_id" => $chatId,
                    "text" => $userLanguage === 'fa' ? "⚠️ درخواست پرداخت نامعتبر است." : "⚠️ Invalid payment request."
                ]);
            }
        }
    }


    public function handlePreCheckoutQuery($update): void
    {
        if (isset($update['pre_checkout_query'])) {
            $query_id = $update['pre_checkout_query']['id'];

            file_put_contents('log.txt', date('Y-m-d H:i:s') . " - Received pre_checkout_query: " . print_r($update, true) . "\n", FILE_APPEND);

            $url = "https://api.telegram.org/bot" . $this->botToken . "/answerPreCheckoutQuery";
            $post_fields = [
                'pre_checkout_query_id' => $query_id,
                'ok' => true,
                'error_message' => ""
            ];

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_fields));
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
            $response = curl_exec($ch);
            curl_close($ch);
            file_put_contents('log.txt', date('Y-m-d H:i:s') . " - answerPreCheckoutQuery Response: " . print_r(json_decode($response, true), true) . "\n", FILE_APPEND);
        }
    }


    private function notifyAdminsOfWithdrawalRequest(int $requestId, array $requestData)
    {
        $admins = $this->db->getAdmins();
        $userInfo = $this->db->getUserInfo($requestData['user_id']);
        $userName = trim(($userInfo['first_name'] ?? '') . ' ' . ($userInfo['last_name'] ?? 'کاربر'));

        $message = "<b>💰 درخواست برداشت وجه جدید</b>\n\n";
        $message .= "<b>کاربر:</b> <a href='tg://user?id={$requestData['user_id']}'>{$userName}</a>\n";
        $message .= "<b>شناسه عددی:</b> <code>{$requestData['user_id']}</code>\n";
        $message .= "<b>مبلغ:</b> <code>" . number_format($requestData['amount']) . "</code> تومان\n";
        $message .= "<b>شماره شبا:</b> <code>{$requestData['payment_detail']}</code>\n\n";
        $message .= "لطفاً پس از بررسی و واریز وجه، روی دکمه 'تایید' کلیک کنید.";

        $keyboard = [
            'inline_keyboard' => [
                [
                    ['text' => '✅ تایید و ارسال رسید', 'callback_data' => "admin_approve_withdraw_{$requestId}"],
                    ['text' => '❌ رد درخواست', 'callback_data' => "admin_reject_withdraw_{$requestId}"]
                ]
            ]
        ];

        foreach ($admins as $admin) {
            $this->sendRequest("sendMessage", [
                "chat_id" => $admin['chat_id'],
                "text" => $message,
                "parse_mode" => "HTML",
                "reply_markup" => json_encode($keyboard)
            ]);
        }
    }


    private function showAdminPaymentTours($chatId, $messageId, $language, $page = 1): void
    {
        $tours = $this->db->getAllTours();
        $perPage = 8;
        $totalPages = ceil(count($tours) / $perPage);

        $page = max(1, min($page, $totalPages)); // محدود کردن صفحه به بازه درست

        $start = ($page - 1) * $perPage;
        $pagedTours = array_slice($tours, $start, $perPage);

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

        foreach ($pagedTours as $index => $tour) {
            $button = [
                "text" => $tour['title'],
                "callback_data" => "admin_payment_tour_details_" . $tour['id']
            ];
            $row[] = $button;

            if (count($row) === 2) {
                $keyboard[] = $row;
                $row = [];
            }
        }
        if (!empty($row)) {
            $keyboard[] = $row;
        }

        // ➕ دکمه های صفحه بندی
        $paginationRow = [];

        if ($page > 1) {
            $paginationRow[] = [
                "text" => "◀️ " . ($language === 'fa' ? "قبلی" : "Previous"),
                "callback_data" => "admin_payment_tours_page_" . ($page - 1)
            ];
        }

        if ($page < $totalPages) {
            $paginationRow[] = [
                "text" => ($language === 'fa' ? "بعدی" : "Next") . " ▶️",
                "callback_data" => "admin_payment_tours_page_" . ($page + 1)
            ];
        }

        if (!empty($paginationRow)) {
            $keyboard[] = $paginationRow;
        }
        $keyboard[] = [
            [
                "text" => $language === 'fa' ? "🔙 بازگشت" : "🔙 Back",
                "callback_data" => "admin_finance_menu"
            ]
        ];

        $this->sendRequest("editMessageText", [
            "chat_id" => $chatId,
            "message_id" => $messageId,
            "text" => $language === 'fa' ? "لیست تورها (صفحه {$page} از {$totalPages})" : "Tour list (Page {$page} of {$totalPages})",
            "reply_markup" => [
                "inline_keyboard" => $keyboard
            ]
        ]);
    }


    private function showUserPayments($chatId, $language, $messageId): void
    {
        $payments = $this->db->getPaymentsByUserId($chatId);
        $status = array("pending" => 'در انتظار پرداخت ', "completed" => 'پرداخت شده', "failed" => 'پرداخت ناموفق');
        if (empty($payments)) {
            $this->sendRequest("answerCallbackQuery", [
                "callback_query_id" => $this->callbackQueryId,
                "text" => "❌هیچ پرداختی یافت نشد.",
                "show_alert" => true
            ]);
            return;
        }

        $keyboard = [];

        foreach ($payments as $index => $pay) {
            $tour = $this->db->getTourById($pay['tour_id']);
            $paymentList = ($index + 1) . ". " . "جزییات پرداخت" . " " . $tour['title'] . "(" . $status[$pay['payment_status']] . ")" . "\n";
            $keyboard[] = [
                [
                    "text" => $paymentList,
                    "callback_data" => "pay_details_" . $pay['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
            ]
        ]);
    }


    private function showOnlinePayments($chatId, $tourId, $callbackQueryId, $language): void
    {
        $payments = $this->db->getOnlinePayments($tourId);
        $status = array("pending" => 'در انتظار پرداخت ', "completed" => 'پرداخت شده', "failed" => 'پرداخت ناموفق');
        if (empty($payments)) {
            $this->sendRequest("answerCallbackQuery", [
                "callback_query_id" => $this->callbackQueryId,
                "text" => "❌هیچ پرداختی یافت نشد.",
                "show_alert" => true // این گزینه باعث نمایش popup می شود
            ]);
            return;
        }

        $keyboard = [];

        foreach ($payments as $index => $pay) {
            $tour = $this->db->getTourById($pay['tour_id']);
            $user = $this->db->registeredExplorerByUserId($pay['chat_id']);
            $fullname = $user['first_name'] . ' ' . $user['last_name'];

            $paymentList = ($index + 1) . ". " . $fullname . " " . "(" . $status[$pay['payment_status']] . ")" . "\n";
            $keyboard[] = [
                [
                    "text" => $paymentList,
                    "callback_data" => "pay_details_" . $pay['id']
                ]
            ];
        }

        $keyboard[] = [
            [
                "text" => $language === 'fa' ? "🔙 بازگشت" : "🔙 Back",
                "callback_data" => "admin_payment_tour_details_" . $tourId
            ]
        ];
        $this->sendRequest("sendMessage", [
            "chat_id" => $chatId,
            "text" =>  "لیست پرداخت های کاربران:",
            "reply_markup" => [
                "inline_keyboard" => $keyboard
            ]
        ]);
    }


    private function showCardToCardPayments($chatId, $tourId, $callbackQueryId, $language): void
    {
        $payments = $this->db->getCardToCardPayments($tourId);
        $status = array("pending" => 'در انتظار پرداخت ', "completed" => 'پرداخت شده', "failed" => 'پرداخت ناموفق');
        if (empty($payments)) {
            $this->sendRequest("answerCallbackQuery", [
                "callback_query_id" => $this->callbackQueryId,
                "text" => "❌هیچ پرداختی یافت نشد.",
                "show_alert" => true // این گزینه باعث نمایش popup می شود
            ]);
            return;
        }

        $keyboard = [];

        foreach ($payments as $index => $pay) {
            $tour = $this->db->getTourById($pay['tour_id']);
            $user = $this->db->registeredExplorerByUserId($pay['explorer_id']);
            $fullname = $user['first_name'] . ' ' . $user['last_name'];

            $paymentList = ($index + 1) . ". " . $fullname . " " . "(" . $status[$pay['payment_status']] . ")" . "\n";
            $keyboard[] = [
                [
                    "text" => $paymentList,
                    "callback_data" => "payment_details_" . $pay['id']
                ]
            ];
        }

        $keyboard[] = [
            [
                "text" => $language === 'fa' ? "🔙 بازگشت" : "🔙 Back",
                "callback_data" => "admin_payment_tour_details_" . $tourId
            ]
        ];
        $this->sendRequest("sendMessage", [
            "chat_id" => $chatId,
            "text" =>  "لیست پرداخت های کاربران:",
            "reply_markup" => [
                "inline_keyboard" => $keyboard
            ]
        ]);
    }


    private function showLeaderPayments($chatId, $language, $messageId): void
    {
        $payments = $this->db->getPaymentsByLeaderId($chatId);

        if (empty($payments)) {
            $this->sendRequest("answerCallbackQuery", [
                "callback_query_id" => $this->callbackQueryId,
                "text" => "❌هیچ پرداختی یافت نشد.",
                "show_alert" => true
            ]);
            return;
        }

        // گرفتن ID یکتا از تورها
        $tourIds = [];
        foreach ($payments as $pay) {
            $tourIds[$pay['tour_id']] = true;
        }

        $keyboard = [];
        foreach (array_keys($tourIds) as $tourId) {
            $tour = $this->db->getTourBytourId($tourId);
            $tourTitle = $tour['title'] ?? 'عنوان نامشخص';

            $keyboard[] = [[
                "text" => "📌 " . $tourTitle,
                "callback_data" => "tour_payments_" . $tourId
            ]];
        }
        $keyboard[] = [[
            "text" => "⬅️ بازگشت ",
            "callback_data" => "leader_finance_menu"
        ]];

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


    private function showTourPayments($chatId, $tourId, $language, $messageId): void
    {
        $payments = $this->db->getPaymentsByLeaderId($chatId);

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

        $filtered = array_filter($payments, function ($pay) use ($tourId) {
            return $pay['tour_id'] == $tourId;
        });

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

        $keyboard = [];
        $tour = $this->db->getTourBytourId($tourId);
        $tourTitle = $tour['title'] ?? 'عنوان نامشخص';

        foreach ($filtered as $index => $pay) {
            $statusText = $statusTexts[$pay['payment_status']] ?? 'نامشخص';
            $user = $this->db->registeredExplorerByUserId($pay['explorer_id']);
            $user_fullName = ($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? '');

            $label = ($index + 1) . ". " . $user_fullName . " - " . $statusText;

            $keyboard[] = [[
                "text" => $label,
                "callback_data" => "payment_leader_details_" . $pay['id']
            ]];
        }

        // افزودن دکمه بازگشت به لیست تورها
        $keyboard[] = [[
            "text" => "⬅️ بازگشت به لیست تورها",
            "callback_data" => "leader_payments_menu"
        ]];

        $this->sendRequest("editMessageText", [
            "chat_id" => $chatId,
            "text" => "🧾 پرداخت های تور: " . $tourTitle,
            "message_id" => $messageId,
            "reply_markup" => [
                "inline_keyboard" => $keyboard
            ]
        ]);
    }


    private function checkPendingTourAfterRegister()
    {
        $pendingData = $this->fileHandler->getTempData($this->chatId);

        if (isset($pendingData['pending_tour_id'])) {
            $tourId = $pendingData['pending_tour_id'];
            $this->fileHandler->clearTempData($this->chatId);

            $this->sendRequest("sendMessage", [
                "chat_id" => $this->chatId,
                "text" => "✅ ثبت نام شما در ربات تکمیل شد. اکنون به فرآیند ثبت نام در تور بازگردانده می شوید..."
            ]);

            $this->startTourRegistrationProcess($this->chatId, $tourId);
        }
    }


    public function distributePaymentToLeaderAndAdmin(int $tourId, int $leaderId, float $totalPaidAmount, string $paymentMethod = 'online', string $currency = 'toman'): bool
    {
        $hasCommission = in_array($paymentMethod, ['online', 'crypto', 'stars', 'online_payment', 'star_payment']);
        $commissionRate = $hasCommission ? 0.05 : 0.00;
        
        $leaderShare = $totalPaidAmount * (1 - $commissionRate);
        $adminShare  = $totalPaidAmount * $commissionRate;

        $descLeader = "درآمد از تور شماره $tourId (" . ($paymentMethod === 'card' ? 'کارت به کارت' : 'آنلاین') . ")";
        $leaderResult = $this->db->addWalletTransaction(
            $leaderId,
            $leaderShare,
            $currency,
            'completed',
            true,
            $descLeader,
            $tourId
        );

        $adminResult = true;
        if ($adminShare > 0) {
            $adminUserId = 7722371725; 
            $descAdmin = "کارمزد 5٪ پلتفرم از تور شماره $tourId";
            $adminResult = $this->db->addWalletTransaction(
                $adminUserId,
                $adminShare,
                $currency,
                'completed',
                true,
                $descAdmin,
                $tourId,
                true
            );
        }

        return $leaderResult && $adminResult;
    }


    public function handleWithdrawn(int $messageId, int $page = 1)
    {
        $perPage = 5; // تعداد آیتم در هر صفحه
        $withdraw_requests = $this->db->getWithdrawRequests();

        if (empty($withdraw_requests)) {
            $this->sendRequest("editMessageText", [
                "chat_id" => $this->chatId,
                "message_id" => $messageId,
                "text" => "هیچ درخواست برداشت وجهی وجود ندارد.",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [["text" => " 🔙 بازگشت", "callback_data" => "admin_finance_menu"]]
                    ]
                ])
            ]);
            return;
        }

        // محاسبه تعداد کل صفحات
        $total = count($withdraw_requests);
        $totalPages = ceil($total / $perPage);

        // برش لیست برای صفحه جاری
        $offset = ($page - 1) * $perPage;
        $pageItems = array_slice($withdraw_requests, $offset, $perPage);

        $keyboard = [];
        foreach ($pageItems as $request) {
            $formattedAmount = number_format($request['amount']);
            $keyboard[] = [[
                "text" => "💰 {$formattedAmount} تومان - {$request['user_id']}",
                "callback_data" => "withdraw_request_{$request['id']}"
            ]];
        }

        // دکمه های صفحه بندی
        $paginationRow = [];
        if ($page > 1) {
            $paginationRow[] = [
                "text" => "⬅️ قبلی",
                "callback_data" => "withdraw_page_" . ($page - 1)
            ];
        }
        if ($page < $totalPages) {
            $paginationRow[] = [
                "text" => "➡️ بعدی",
                "callback_data" => "withdraw_page_" . ($page + 1)
            ];
        }
        if (!empty($paginationRow)) {
            $keyboard[] = $paginationRow;
        }

        // دکمه بازگشت
        $keyboard[] = [["text" => " 🔙 بازگشت", "callback_data" => "admin_finance_menu"]];

        $this->sendRequest("editMessageText", [
            "chat_id" => $this->chatId,
            "message_id" => $messageId,
            "text" => "📄 لطفاً یکی از درخواست های برداشت زیر را انتخاب کنید (صفحه {$page}/{$totalPages}):",
            "reply_markup" => json_encode([
                "inline_keyboard" => $keyboard
            ]),
        ]);
    }


    public function handleAdminPayments(int $messageId)
    {
        $payments = $this->db->getAdminPayments();
        if (empty($payments)) {
            $this->sendRequest("editMessageText", [
                "chat_id" => $this->chatId,
                "message_id" => $messageId,
                "text" => "هیچ واریزی وجود ندارد.",
                "reply_markup" => json_encode([
                    "inline_keyboard" => [
                        [["text" => " 🔙 بازگشت", "callback_data" => "admin_finance_menu"]]
                    ]
                ])
            ]);
            return;
        }
        $keyboard = [];
        foreach ($payments as $payment) {
            $formattedAmount = number_format($payment['paid_amount']);
            $keyboard[] = [
                [
                    "text" => "💰 {$formattedAmount} تومان - {$payment['user_id']}",
                    "callback_data" => "admin_deposit_{$payment['id']}"
                ]
            ];
        }

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

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

}
