<?php
if(!function_exists('calcOrderCosts')) {
    function calcOrderCosts($count, $isBoosted, $isVip)
    {
        $count     = intval($count);
        $isBoosted = intval($isBoosted) ? 1 : 0;
        $costPerMember = settings('cost_per_member', 1);
        $baseCost      = $count * $costPerMember;
        $boostPercent        = settings('boost_percent', 20) / 100;
        $boostCost           = $isBoosted ? ($baseCost * $boostPercent) : 0;
        $totalBeforeDiscount = $baseCost + $boostCost;
        $discountAmount = 0;

if($isVip) {
            $vipDiscountPercent = settings('vip_discount_percent', 10) / 100;
            $discountAmount     = $totalBeforeDiscount * $vipDiscountPercent;
}

        $totalCost = $totalBeforeDiscount - $discountAmount;
        return [
            'baseCost' => $baseCost,
            'boostCost' => $boostCost,
            'discountAmount' => $discountAmount,
            'totalCost' => $totalCost,
        ];
}

}


if(strpos($user->step, 'order_channel:') === 0 && $text != "🔙 بازگشت به منو قبل") {
    $channel_id = substr($user->step, strlen('order_channel:'));
    $text = trim($text);
    $text = convertPersianToEnglishNumbers($text);

if(!is_numeric($text) || intval($text) <= 0 || intval($text) > 100000) {
        $responseText = "❌ *ورودی نامعتبر*\n\n" .
            "لطفاً یک عدد معتبر بین 1 تا 100,000 ارسال کنید.";
        sendMessage($chat_id, $responseText);
} else {
        $count = intval($text);
        $isVip = $user->is_vip ?? 0;

if($isVip && strtotime($user->vip_expire) < time()) {
            $isVip = 0;
}

        $maxDailyOrders = ($isVip) ? settings('max_daily_orders_vip', 10) : settings('max_daily_orders_normal', 3);
        $stmtDaily      = $pdo->prepare("SELECT COUNT(*) FROM `orders` WHERE `user_id` = ? AND DATE(`created_at`) = CURDATE()");
        $stmtDaily->execute([$chat_id]);
        $dailyOrders = $stmtDaily->fetchColumn();

if($dailyOrders >= $maxDailyOrders) {
            $responseText = "🚫 *محدودیت سفارش روزانه*\n\n" .
                "سقف مجاز شما برای امروز تکمیل شده است.\n" .
                "📊 حداکثر مجاز امروز: *$maxDailyOrders* سفارش\n\n" .
                "⏰ فردا می‌توانید دوباره سفارش ثبت کنید.";
            sendMessage($chat_id, $responseText);
            die;
}

        $minOrder = ($isVip) ? settings('min_order_vip', 5) : settings('min_order_normal', 15);

if($count < $minOrder) {
            $responseText = "❌ *تعداد درخواستی کمتر از حد مجاز است*\n\n" .
                "📊 حداقل مجاز برای شما: *$minOrder* ممبر\n";
            sendMessage($chat_id, $responseText);
            die;
}

        $stmt = $pdo->prepare("SELECT * FROM `channels` WHERE `id` = ?");
        $stmt->execute([$channel_id]);
        $channel = $stmt->fetch();

if($channel) {
            $compensation = 0;
            $channelNameDup = ($channel->channel_name ?: $channel->channel_username);
            $inviteLinkDup = $channel->invite_link;
            $stmtPrev = $pdo->prepare("SELECT `order_id` FROM `orders` WHERE `user_id` = ? AND (`channel_name` = ? OR (`invite_link` = ? AND `invite_link` != '')) AND `status` IN ('completed','cancelled') ORDER BY `created_at` DESC LIMIT 1");
            $stmtPrev->execute([$chat_id, $channelNameDup, $inviteLinkDup]);
            $prevOrderId = intval($stmtPrev->fetchColumn() ?? 0);

if($prevOrderId > 0) {
                $stmtDrop = $pdo->prepare("SELECT COUNT(*) FROM `memberships` WHERE `order_id` = ? AND `status` = 'left_refunded'");
                $stmtDrop->execute([$prevOrderId]);
                $compensation = intval($stmtDrop->fetchColumn() ?? 0);

if($compensation < 0) $compensation = 0;
}

            $finalCount = $count + $compensation;
            $warningsLimit = settings('channel_warnings_limit', 5);

if($channel->warnings_count >= $warningsLimit) {
                sendMessage($chat_id, "⛔️ *این کانال به‌دلیل دریافت $warningsLimit اخطار، مسدود است و امکان ثبت سفارش ندارد.*");
                die;
}

            $coins         = isset($user->coins) ? intval($user->coins) : 0;
            $costPerMember = settings('cost_per_member', 1);
            $baseCost      = $finalCount * $costPerMember;
            $boostPercent = settings('boost_percent', 20) / 100;
            $boostCost    = $baseCost * $boostPercent;
            $baseCostDisplay  = intval($baseCost);
            $boostCostDisplay = $boostCost;
            $coinsDisplay     = intval($coins);
            $responseText = "*🚀 انتخاب بوست سفارش*\n\n" .
                "📢 *نام کانال:* " . ($channel->channel_name ?: $channel->channel_username) . "\n" .
                "👥 *تعداد نهایی:* $finalCount ممبر\n" .
                ($compensation > 0 ? ("📉 *جبران ریزش سفارش قبلی:* +$compensation ممبر\n") : "") .
                "💵 *هزینه پایه:* $baseCostDisplay سکه\n" .
                "💰 *موجودی شما:* $coinsDisplay سکه\n\n" .
                "🚀 بوست یعنی نمایش با اولویت بالاتر.\n" .
                "🔥 هزینه بوست: *$boostCostDisplay سکه* (" . intval(settings('boost_percent', 20)) . "٪)\n\n" .
                "یکی از گزینه‌ها را انتخاب کنید:";
            $keyboard = json_encode([
                "inline_keyboard" => [
                    [['text' => '🏎 با بوست', 'callback_data' => "select_boost:$channel_id:$finalCount:1"], ['text' => '🚶‍♂️ بدون بوست', 'callback_data' => "select_boost:$channel_id:$finalCount:0"]],
                    [['text' => '❌ لغو و بازگشت', 'callback_data' => 'back_to_channels_list']],
                ]
            ]);
            setStep($chat_id, "order_boost_select:$channel_id:$finalCount");
            sendMessage($chat_id, $responseText, $keyboard);
} else {
            $responseText = "❌ کانال یافت نشد.";
            sendMessage($chat_id, $responseText);
            setStep($chat_id, 'none');
}

        die;
}

}


if(strpos($data, 'select_boost:') === 0) {
    $parts      = explode(':', $data);
    $channel_id = $parts[1];
    $count      = intval($parts[2]);
    $isBoosted  = intval($parts[3]);
    $stmt = $pdo->prepare("SELECT * FROM `channels` WHERE `id` = ?");
    $stmt->execute([$channel_id]);
    $channel = $stmt->fetch();

if($channel) {
        $userObj        = getUser($chat_id);
        $isVip          = $userObj->is_vip && strtotime($userObj->vip_expire) > time();
        $costs          = calcOrderCosts($count, $isBoosted, $isVip);
        $baseCost       = $costs['baseCost'];
        $boostCost      = $costs['boostCost'];
        $discountAmount = $costs['discountAmount'];
        $totalCost      = $costs['totalCost'];
        $compensation = 0;
        $channelNameDup = ($channel->channel_name ?: $channel->channel_username);
        $inviteLinkDup = $channel->invite_link;
        $stmtPrev = $pdo->prepare("SELECT `order_id` FROM `orders` WHERE `user_id` = ? AND (`channel_name` = ? OR (`invite_link` = ? AND `invite_link` != '')) AND `status` IN ('completed','cancelled') ORDER BY `created_at` DESC LIMIT 1");
        $stmtPrev->execute([$chat_id, $channelNameDup, $inviteLinkDup]);
        $prevOrderId = intval($stmtPrev->fetchColumn() ?? 0);

if($prevOrderId > 0) {
            $stmtDrop = $pdo->prepare("SELECT COUNT(*) FROM `memberships` WHERE `order_id` = ? AND `status` = 'left_refunded'");
            $stmtDrop->execute([$prevOrderId]);
            $compensation = intval($stmtDrop->fetchColumn() ?? 0);

if($compensation < 0) $compensation = 0;
}

        $baseCostDisplay  = intval($baseCost);
        $boostCostDisplay = $boostCost;
        $discountDisplay  = round($discountAmount, 2);
        $totalCostDisplay = intval($totalCost);
        $responseText = "🧾 *فاکتور سفارش*\n\n" .
            "📢 کانال: *" . ($channel->channel_name ?: $channel->channel_username) . "*\n" .
            "👥 تعداد نهایی: *$count* ممبر\n" .
            ($compensation > 0 ? ("♻️ جبران ریزش سفارش قبلی شما: *$compensation* ممبر\n") : "") .
            "\n" .
            "💵 هزینه پایه: *$baseCostDisplay* سکه\n" .
            ($isBoosted ? ("🚀 بوست: *$boostCostDisplay* سکه\n") : "") ;

if($isVip && $discountDisplay > 0) {
            $responseText .= "💎 تخفیف ویژه: *$discountDisplay* سکه\n";
}

        $responseText .= "\n💰 مبلغ نهایی: *$totalCostDisplay* سکه\n\n" .
            "برای ثبت نهایی، تایید را بزنید.";
        $keyboard = json_encode([
            "inline_keyboard" => [
                [
                    ['text' => '✅ تایید', 'callback_data' => "confirm_order:$channel_id:$count:$isBoosted"],
                    ['text' => '❌ لغو', 'callback_data' => 'cancel_order']
                ],
                [['text' => '🔙 تغییر بوست', 'callback_data' => "back_to_boost:$channel_id:$count"]]
            ]
        ]);
        editMessage($chat_id, $message_id, $responseText, $keyboard);
        die;
}

}


if(strpos($data, 'back_to_boost:') === 0) {
    $parts      = explode(':', $data);
    $channel_id = $parts[1];
    $count      = intval($parts[2]);
    $stmt = $pdo->prepare("SELECT * FROM `channels` WHERE `id` = ?");
    $stmt->execute([$channel_id]);
    $channel = $stmt->fetch();

if($channel) {
        $coins           = isset($user->coins) ? intval($user->coins) : 0;
        $costPerMember   = settings('cost_per_member', 1);
        $boostPercent    = settings('boost_percent', 20) / 100;
        $boostPercentVal = intval(settings('boost_percent', 20));
        $baseCost        = $count * $costPerMember;
        $boostCost       = $baseCost * $boostPercent;
        $responseText = "🚀 *بوست سفارش*\n\n" .
            "📢 *کانال:* " . ($channel->channel_name ?: $channel->channel_username) . "\n" .
            "👥 *اعضا:* $count\n" .
            "💵 *هزینه پایه:* " . intval($baseCost) . " سکه\n" .
            "💰 *موجودی شما:* " . intval($coins) . " سکه\n\n" .
            "🔥 با پرداخت *" . intval($boostCost) . " سکه* (" . $boostPercentVal . "٪)، سفارش با اولویت بالاتر نمایش داده می‌شود.\n\n" .
            "👇 یکی از گزینه‌های زیر را انتخاب کنید:";
        $keyboard = json_encode([
            "inline_keyboard" => [
                [
                    ['text' => '🏎 فعالسازی بوست', 'callback_data' => "select_boost:$channel_id:$count:1"],
                    ['text' => '🚶‍♂️ بدون بوست', 'callback_data' => "select_boost:$channel_id:$count:0"]
                ],
                [['text' => '❌ لغو و بازگشت', 'callback_data' => 'cancel_order']]
            ]
        ]);
        editMessage($chat_id, $message_id, $responseText, $keyboard);
        die;
}

    die;
}


if(strpos($data, 'confirm_order:') === 0) {
    $parts      = explode(':', $data);
    $channel_id = $parts[1];
    $count      = intval($parts[2]);
    $isBoosted  = intval($parts[3]);

if(function_exists('checkSpam') && checkSpam($chat_id)) {
        answerCallbackQuery($query_id, "⏳ لطفاً چند لحظه صبر کنید و دوباره تلاش کنید.", true);
        die;
}

    $stmt = $pdo->prepare("SELECT * FROM `channels` WHERE `id` = ?");
    $stmt->execute([$channel_id]);
    $channel = $stmt->fetch();

if($channel) {
        $userCoins      = $user->coins ?? 0;
        $userObj        = getUser($chat_id);
        $isVip          = $userObj->is_vip && strtotime($userObj->vip_expire) > time();
        $costs          = calcOrderCosts($count, $isBoosted, $isVip);
        $baseCost       = $costs['baseCost'];
        $boostCost      = $costs['boostCost'];
        $discountAmount = $costs['discountAmount'];
        $totalCost      = $costs['totalCost'];

if($userCoins >= $totalCost) {
            $bot_member   = getChatMember("@" . strtolower($channel->channel_username), BOT_ID);
            $bot_is_admin = false;

if(isset($bot_member->result)) {
                $status = $bot_member->result->status;

if($status == 'administrator' || $status == 'creator') {
                    $bot_is_admin = true;
}

}


if(!$bot_is_admin) {
                answerCallbackQuery($query_id, "❌ ربات دیگر ادمین کانال نیست! لطفاً ربات را ادمین کرده و مجدد تلاش کنید.", true);
                die;
}

            $channelNameDup = ($channel->channel_name ?: $channel->channel_username);
            $inviteLink = $channel->invite_link;

if(!$inviteLink) {
                answerCallbackQuery($query_id, "❌ خطای سیستمی. لطفاً دوباره تلاش کنید.", true);
                die;
}

            $inviteLink = "https://ble.ir/{$channel->channel_username}";
            $stmtUpd    = $pdo->prepare("UPDATE `channels` SET `invite_link` = ? WHERE `id` = ?");
            $stmtUpd->execute([$inviteLink, $channel->id]);
            try {
                $pdo->beginTransaction();
                $stmtBal = $pdo->prepare("SELECT `coins` FROM `users` WHERE `user_id` = ? FOR UPDATE");
                $stmtBal->execute([$chat_id]);
                $stmtDup = $pdo->prepare("SELECT COUNT(*) FROM `orders` WHERE `user_id` = ? AND `status` IN ('pending','running') AND (`channel_name` = ? OR (`invite_link` = ? AND `invite_link` != ''))");
                $stmtDup->execute([$chat_id, $channelNameDup, $inviteLink]);

if(intval($stmtDup->fetchColumn()) > 0) {
                    $pdo->rollBack();
                    answerCallbackQuery($query_id, "⚠️ شما قبلاً یک سفارش فعال برای این کانال دارید.\nلطفاً تا پایان سفارش قبلی صبر کنید.", true);
                    die;
}

                $currentBal = intval($stmtBal->fetchColumn() ?? 0);

if($currentBal < $totalCost) {
                    $pdo->rollBack();
                    answerCallbackQuery($query_id, "❌ موجودی شما کافی نیست.", true);
                    die;
}


for($i = 0; $i < 6; $i++) {
                    $candidate = random_int(1000, 99999);
                    $stmtCheck = $pdo->prepare("SELECT COUNT(*) FROM `orders` WHERE `order_id` = ?");
                    $stmtCheck->execute([$candidate]);

if(intval($stmtCheck->fetchColumn()) === 0) {
                        $orderId = $candidate;
                        break;
}

}


if(!$orderId) {
                    $pdo->rollBack();
                    answerCallbackQuery($query_id, "❌ خطای سیستمی. لطفاً دوباره تلاش کنید", true);
                    die;
}

                $query = "INSERT INTO `orders` 
                    (`order_id`, `channel_name`, `invite_link`, `user_id`, `members_count`, `members_done`, `total_cost`, `coin_per_member`, `coins_penalty`, `boost_manual`, `is_vip`, `status`, `created_at`) 
                    VALUES (?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?, 'running', NOW())";
                $coinPerMember = $totalCost / $count;
                $coinsPenalty  = $coinPerMember * 2;
                $vipChecker    = $isVip ? 1 : 0;
                $stmtIns = $pdo->prepare($query);
                $stmtIns->execute([
                    $orderId,
                    ($channel->channel_name ?: $channel->channel_username),
                    $inviteLink,
                    $chat_id,
                    $count,
                    $totalCost,
                    $coinPerMember,
                    $coinsPenalty,
                    $boostCost,
                    $vipChecker
                ]);
                $pdo->commit();
} catch (Exception $e) {

if($pdo->inTransaction())
                    $pdo->rollBack();
                answerCallbackQuery($query_id, "❌ خطا در ثبت سفارش.", true);
                die;
}

            $formatCoins = function ($amount) {
                $amount  = floatval($amount);
                $rounded = round($amount, 2);

if(abs($rounded - round($rounded)) < 0.00001) {
                    return number_format((int) round($rounded), 0);
}

                $s = number_format($rounded, 2, '.', '');
                $s = rtrim(rtrim($s, '0'), '.');
                return $s;
};
            $channelName = ($channel->channel_name ?: $channel->channel_username);
            $orderLogChannel = settings('channel_new_order_log', 'none');

if($orderLogChannel && $orderLogChannel !== 'none') {
                $logMsg = "🛍 سفارش جدید ثبت شد\n\n" .
                    "👤 کاربر: [$from_id](uid:$from_id)\n" .
                    "📋 شماره سفارش: #$orderId\n" .
                    "📢 کانال: $channelName\n" .
                    "🔗 لینک کانال: $inviteLink\n" .
                    "👥 تعداد عضو: $count\n" .
                    "🔥 بوست: " . $formatCoins($boostCost) . " سکه\n" .
                    "💰 هزینه کل: " . $formatCoins($totalCost) . " سکه";
                sendMessage($orderLogChannel, $logMsg);
}

            $vipDiscountPercent = settings('vip_discount_percent', 10);
            $responseText = "✅ *سفارش شما با موفقیت ثبت شد!*\n\n" .
                "📋 شماره سفارش: *#$orderId*\n" .
                "📢 کانال: *$channelName*\n" .
                "👥 تعداد عضو درخواستی: *$count* ممبر\n\n" .
                "💰 *جزئیات هزینه:*\n" .
                "💵 هزینه پایه: *" . $formatCoins($baseCost) . "* سکه\n" .
                "🔥 هزینه بوست: *" . $formatCoins($boostCost) . "* سکه\n";

if($isVip && floatval($discountAmount) > 0) {
                $responseText .= "💎 تخفیف ویژه (" . intval($vipDiscountPercent) . "٪): *" . $formatCoins($discountAmount) . "* سکه\n";
}

            $responseText .= "\n💰 *هزینه کل پرداختی: " . $formatCoins($totalCost) . " سکه*\n\n" .
                "📌 سفارش شما در حال انجام است و به محض تکمیل، اطلاع‌رسانی خواهد شد.";
            $newCoins   = $currentBal - $totalCost;
            $stmtBalUpd = $pdo->prepare("UPDATE `users` SET `coins` = ? WHERE `user_id` = ?");
            $stmtBalUpd->execute([$newCoins, $chat_id]);
            sendMessage($chat_id, $responseText, getMainMenuKeyboard($user));
            setStep($chat_id, 'none');
            deleteMessage($chat_id, $message_id);
} else {
            $responseText = "💸 *موجودی ناکافی*\n\n" .
                "💰 هزینه سفارش: *" . intval($totalCost) . "* سکه\n" .
                "💳 موجودی فعلی: *" . intval($userCoins) . "* سکه\n\n" .
                "برای افزایش موجودی از «کسب سکه» یا «فروشگاه» استفاده کنید.";
            sendMessage($chat_id, $responseText);
}

        die;
} else {
        answerCallbackQuery($query_id, "❌ کانال یافت نشد.", true);
        die;
}

}


if(strpos($data, 'cancel_active_order:') === 0) {
    $order_id = substr($data, strlen('cancel_active_order:'));

if(function_exists('checkSpam') && checkSpam($chat_id)) {
        answerCallbackQuery($query_id, "⏳ لطفاً چند لحظه صبر کنید و دوباره تلاش کنید.", true);
        die;
}

    $stmt = $pdo->prepare("SELECT * FROM `orders` WHERE `order_id` = ? AND `user_id` = ? FOR UPDATE");
    try {
        $pdo->beginTransaction();
        $stmt->execute([$order_id, $chat_id]);
        $order = $stmt->fetch();

if($order && in_array($order->status, ['pending', 'running'])) {
            $refund = calcOrderCancelRefund($order);
            $refundTotal = $refund['total_refund'];
            $refundBase = $refund['base_refund'];
            $refundExtra = $refund['extra_refund'];
            $remainingMembers = $refund['remaining'];

if($refundTotal > 0) {
                $stmtRefund = $pdo->prepare("UPDATE `users` SET `coins` = `coins` + ? WHERE `user_id` = ?");
                $stmtRefund->execute([$refundTotal, $chat_id]);
}

            $stmtCancel = $pdo->prepare("UPDATE `orders` SET `status` = 'cancelled', `finished_at` = NOW() WHERE `order_id` = ?");
            $stmtCancel->execute([$order_id]);
            $pdo->commit();
            $responseText = "✅ *سفارش با موفقیت لغو شد.*\n\n" .
                "📋 شماره سفارش: #{$order->order_id}\n" .
                "📉 تعداد درخواستی: {$order->members_count}\n" .
                "✅ تعداد انجام شده: {$order->members_done}\n" .
                "💰 بازگشت بابت اعضای انجام‌نشده: " . formatCoins($refundBase) . " سکه\n" .
                ($refundExtra > 0 ? ("🚀 بازگشت بابت بوست/هزینه اضافه: " . formatCoins($refundExtra) . " سکه\n") : "") .
                "🧾 مجموع بازگشت: " . formatCoins($refundTotal) . " سکه\n\n" .
                "مبلغ به کیف پول شما بازگشت داده شد.";
            $keyboard = json_encode([
                "inline_keyboard" => [
                    [['text' => '🔙 بازگشت به منو قبل', 'callback_data' => 'back_to_channels_list']]
                ]
            ]);
            editMessage($chat_id, $message_id, $responseText, $keyboard);
            $cancelLogChannel = settings('channel_order_cancel_log', 'none');

if($cancelLogChannel && $cancelLogChannel !== 'none') {
                $logMsg = "❌ لغو سفارش\n\n" .
                    "👤 کاربر: $chat_id\n" .
                    "📋 شماره سفارش: #{$order->order_id}\n" .
                    "📢 کانال: {$order->channel_name}\n" .
                    "💰 برگشت: " . formatCoins($refundTotal) . " سکه";
                sendMessage($cancelLogChannel, $logMsg);
}

            die;
} else {
            $pdo->rollBack();
            answerCallbackQuery($query_id, "❌ سفارش یافت نشد یا قبلاً لغو شده است.", true);
            die;
}

} catch (Exception $e) {

if($pdo->inTransaction())
            $pdo->rollBack();
        answerCallbackQuery($query_id, "❌ خطا در لغو سفارش.", true);
        die;
}

}


if($data == 'back_to_channels_list') {
    $query = "SELECT * FROM `channels` WHERE `added_by` = ?";
    $stmt  = $pdo->prepare($query);
    $stmt->execute([$chat_id]);
    $channels = $stmt->fetchAll();
    $responseText = "🗂 *کانال‌های شما*\n\nیک کانال را برای ثبت سفارش انتخاب کنید یا کانال جدیدی اضافه کنید.\n\n⚠️ *توجه:* ربات باید ادمین کانال باشد!";
    $keyboard     = generateChannelsKeyboard($channels);
    editMessage($chat_id, $message_id, $responseText, $keyboard);
    die;
}


if($data == 'cancel_order') {
    $query = "SELECT * FROM `channels` WHERE `added_by` = ?";
    $stmt  = $pdo->prepare($query);
    $stmt->execute([$chat_id]);
    $channels = $stmt->fetchAll();
    $responseText = "🗂 *کانال‌های شما*\n\nیک کانال را برای ثبت سفارش انتخاب کنید یا کانال جدیدی اضافه کنید.\n\n⚠️ *توجه:* ربات باید ادمین کانال باشد!";
    $keyboard     = generateChannelsKeyboard($channels);
    editMessage($chat_id, $message_id, $responseText, $keyboard);
    setStep($chat_id, 'none');
    die;
}

