<?php

require __DIR__ . '/../vendor/autoload.php';

use Config\AppConfig;
use Bot\BotHandler;
use Bot\FileHandler;
use Bot\InlineQueryHandler;
use Payment\ZarinpalPaymentHandler;

$config = AppConfig::getConfig();


$update = json_decode(file_get_contents('php://input'), true);


if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (isset($update['inline_query'])) {
    $inlineQuery = $update['inline_query'];
    $query = $inlineQuery['query'];

    $inlineQueryHandler = new InlineQueryHandler();
    $inlineQueryHandler->handleInlineQuery($inlineQuery);
} elseif (isset($update['message'])) {
    $message = $update['message'];
    $chatId = $message['chat']['id'];
    $text = $message['text'] ?? '';
    $messageId = $message['message_id'] ?? null;

    $bot = new BotHandler($chatId, $text, $messageId, $message);

    if (isset($message['successful_payment'])) {
        $bot->handleSuccessfulPayment($update);
    } else {
        $bot->handleRequest();
    }
} elseif (isset($update['callback_query'])) {
    $callbackQuery = $update['callback_query'];
    $chatId = $callbackQuery['message']['chat']['id'];
    $messageId = $callbackQuery['message']['message_id'] ?? null;
    $bot = new BotHandler($chatId, '', $messageId, $callbackQuery['message']);
    $bot->handleCallbackQuery($callbackQuery);
} elseif (isset($update['my_chat_member'])) {
    $myChatMember = $update['my_chat_member'];
    $chatId = $myChatMember['chat']['id'];
    $bot = new BotHandler($chatId, '', null, null);
    $bot->handleMyChatMember($myChatMember);
}

elseif (isset($_GET['chat_id']) && isset($_GET['Authority']) && isset($_GET['tour_id'])) {
    $chatId = $_GET['chat_id'];
    $authority = $_GET['Authority'];
    $tourId = $_GET['tour_id'];

    $bot = new BotHandler($chatId, '', null, null);
    $zarinpalPaymentHandler = new ZarinpalPaymentHandler();
    $explorer=$bot->db->getExplorerByChatId($chatId);
    $paymentDetails = $bot->db->getUserPaymentByAuthority($authority);
    if (!$paymentDetails) {
        error_log("Payment not found for Authority: $authority");
        exit("Payment not found");
    }

    $amount = $paymentDetails['amount'];
    $_SESSION['amount'] = $amount;

    $paymentResult = $zarinpalPaymentHandler->verifyZarinpalPayment($_SESSION['amount'] * 10, $authority);

    if ($paymentResult['status']) {
        $refId = $paymentResult['ref_id'];
        $amountPaid = $amount;
        $registration = $bot->db->getUserTourRegistration($chatId, $tourId);
       // $penaltyAmountStar = intval($registration['penalty_amount'] ?? 0);
       // $penaltyAmountToman = $penaltyAmountStar * 3 * 1000;

     //   $bot->db->addToWalletHoldToman($chatId, $penaltyAmountToman);

        $fileHandler = new FileHandler();
        $temp = $fileHandler->getTempData($chatId);

        $quantity = $temp['quantity'] ?? 1; 
        $selectedVehicle = $temp['selected_vehicle'] ?? null;
        $vehicle=$bot->getLabelVehicle($selectedVehicle);

        $userDetails = $bot->db->getUserByChatIdOrUsername($chatId);
        $tourDetails = $bot->db->getTourDetailsWithPrice($tourId);

        

        $bot->db->updateUserPaymentStatus($authority, 'completed', $refId);
        $paymentUpdated = $bot->db->updateTourPaymentStatus($chatId, $tourId, 'completed', 'online_payment', $selectedVehicle, null, $quantity);

        $tour_info=$bot->db->getTourById($tourId);
        $dt = new DateTime($tour_info['start_date']);
        $start_date = $dt->format('Y/m/d');
        $time = $dt->format('H:i');
        $persianDate=$bot->MiladiToShamsi($start_date);

         $leader_id=$tour_info['leader_id'];
         $leader=$bot->db->getExplorerByChatId($leader_id);
         $bot->distributePaymentToLeaderAndAdmin($tourId,$leader_id,$amount);
         $bot->updateTourParticipantCount($tourId);
        $fileHandler = new FileHandler();
        $temp = $fileHandler->getTempData($chatId);
        $quantity = $temp['quantity'] ?? 1; 

        $userMessages = [
            'fa' => "✅ پرداخت شما با موفقیت انجام شد.\n\n"
                . "🏆 <b>تور:</b> {$tourDetails['title']}\n"
                . "💰 <b>مبلغ پرداخت‌شده:</b> {$amountPaid} تومان\n"
                . "🔢 <b>شماره مرجع:</b> {$refId}\n\n"
                . "👥 <b>تعداد نفرات:</b> {$quantity} نفر\n"
                . "📌 <b>ثبت‌نام شما با وسیله نقلیه «{$vehicle}» انجام شد.</b>\n\n"
                . "📅 لطفاً در تاریخ <b>{$persianDate}</b> ساعت <b>{$time}</b>\n"
                . "📍 در محل قرار: <b>{$tour_info['origin_address']}</b> حضور داشته باشید.\n\n"
                . "⏰ لطفاً چند دقیقه زودتر در محل حاضر شوید تا بدون مشکل حرکت کنیم 🌿",

            'en' => "✅ Your payment was successful.\n\n"
                . "🏆 <b>Challenge:</b> {$tourDetails['title']}\n"
                . "💰 <b>Amount Paid:</b> {$amountPaid} Toman\n"
                . "🔢 <b>Reference ID:</b> {$refId}\n\n"
                . "📌 <b>You are registered with vehicle: «{$vehicle}» ✅</b>\n\n"
                . "📅 Please be there on <b>{$persianDate}</b> at <b>{$time}</b>\n"
                . "📍 Meeting point: <b>{$tour_info['origin_address']}</b>\n\n"
                . "⏰ Please arrive a few minutes earlier so we can start smoothly 🌿"
        ];

        $userLanguage = 'fa';
        //$userLanguage = $bot->db->getUserLanguage($chatId);
        $selectedMessage = $userMessages[$userLanguage] ?? $userMessages['en'];

        $menuButton = [
            'inline_keyboard' => [
                [["text" => ($userLanguage === 'fa' ? "🏠 بازگشت به منو" : "🏠 Back to Menu"), "callback_data" => "go_to_menu"]],
            ]
        ];

        $bot->sendRequest("sendMessage", [
            "chat_id" => $chatId,
            "text" => $selectedMessage,
            "parse_mode" => "HTML",
            "reply_markup" => json_encode($menuButton)
        ]);



        $Message  = "<b>✅ کاربر " . htmlspecialchars($explorer['first_name'] . ' ' . $explorer['last_name'])
            . " برای {$quantity} نفر در تور «" . htmlspecialchars($tour_info['title']) . "» ثبت‌نام کرد.</b>\n\n";

        $Message .= "<b>اطلاعات شخصی:</b>\n<blockquote>"
            . "▫️ <b>نام:</b> " . htmlspecialchars($explorer['first_name'] . ' ' . $explorer['last_name']) . "\n"
            . "▫️ <b>نام مستعار:</b> " . htmlspecialchars($explorer['nick_name']) . "\n"
            . "▫️ <b>شناسه:</b> <code>" . $chatId . "</code>\n"
            . "▫️ <b>لینک مستقیم:</b> <a href='tg://user?id={$chatId}'>تماس با کاربر</a>"
            . "</blockquote>\n";

        $Message .= "<b>اطلاعات تماس:</b>\n<blockquote>"
            . "▫️ <b>تلفن:</b> <code>" . htmlspecialchars($explorer['phone']) . "</code>"
            . "</blockquote>\n";

        $adminMessage = "<b>اطلاعات تور:</b>\n<blockquote>"
            . "▫️ <b>عنوان:</b> " . htmlspecialchars($tour_info['title']) . "\n"
            . "▫️ <b>لیدر تور:</b> " . htmlspecialchars($leader['first_name'] . ' ' . $leader['last_name']) . "\n"
            . "▫️ <b>شماره تماس لیدر:</b> <code>" . htmlspecialchars($leader['phone']) . "</code>". "\n"
            . "▫️ <b>ارتباط با لیدر:</b> <a href='tg://user?id={$leader['chat_id']}'>مشاهده پروفایل</a>"
            . "</blockquote>\n";

        $leaderMessage = "<b>اطلاعات تور:</b>\n<blockquote>"
            . "▫️ <b>عنوان:</b> " . htmlspecialchars($tour_info['title']) . "\n"
            . "▫️ <b>وسیله نقلیه انتخابی:</b> " . htmlspecialchars($vehicle) . "\n"
            . "</blockquote>";



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

            $selectedAdminMessage = $adminMessages[$userLanguage] ?? $adminMessages['en'];

            $bot->sendRequest("sendMessage", [
                "chat_id" => $admin['chat_id'],
                "text" => $selectedAdminMessage,
                "parse_mode" => "HTML"
            ]);
            $bot->sendRequest("sendMessage", [
                "chat_id" => $admin['chat_id'],
                "text" => $Message.$adminMessage,
                "parse_mode" => "HTML"
            ]);
        }


       if(!empty($tour_info['leader_id'])) {
           $leaderMessages = [
               'fa' => "💸 <b>پرداخت جدید برای تور!</b>\n\n👤 <b>کاربر:</b> @{$userDetails['username']}\n📌 \n🏆 <b>تور:</b> {$tourDetails['title']}\n💰 <b>مبلغ:</b> {$amountPaid} تومان\n🔢 <b>شماره مرجع:</b> {$refId}",
               'en' => "💸 <b>New Tour Payment!</b>\n\n👤 <b>User:</b> @{$userDetails['username']}\n📌 <b>Chat ID:</b> {$chatId}\n🏆 <b>Tour:</b> {$tourDetails['title']}\n💰 <b>Amount:</b> {$amountPaid} Toman\n🔢 <b>Reference ID:</b> {$refId}"
           ];

           $selectedLeaderMessage = $leaderMessages[$userLanguage] ?? $leaderMessages['en'];

           $bot->sendRequest("sendMessage", [
               "chat_id" => $leader_id,
               "text" => $selectedLeaderMessage,
               "parse_mode" => "HTML"
           ]);
           $bot->sendRequest("sendMessage", [
               "chat_id" => $leader_id,
               "text" => $Message.$leaderMessage,
               "parse_mode" => "HTML"
           ]);
       }




      // header("Location:/assets/styles/success.php?ref_id=".$refId);
       // include 'assets/styles/success.php';
        header("Location: receipt.php?status=success&amount={$amountPaid}&ref_id={$refId}");
    } else {
        $bot->db->updateUserPaymentStatus($authority, 'failed');

        $bot->sendRequest("sendMessage", [
            "chat_id" => $chatId,
            "text" => "❌ پرداخت شما ناموفق بود. لطفاً دوباره تلاش کنید."
        ]);
        header("Location: receipt.php?status=failed&message=خطا در پرداخت" );
       // header("Location:/assets/styles/failed.php");
    }
}


elseif (isset($update['pre_checkout_query'])) {
    $bot = new BotHandler(null, null, null, null);
    $bot->handlePreCheckoutQuery($update);
}
