<?php
if($user && isset($user->step) && strpos($user->step, 'edit_order_count:') === 0 && $text && $text != "/start" && $text != "🔙 بازگشت به منو قبل") {
    $orderId = intval(substr($user->step, strlen('edit_order_count:')));
    $text = trim($text);
    $text = convertPersianToEnglishNumbers($text);

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

    $newCount = intval($text);
    $stmt = $pdo->prepare("SELECT * FROM `orders` WHERE `order_id` = ? AND `user_id` = ? LIMIT 1");
    $stmt->execute([$orderId, $chat_id]);
    $order = $stmt->fetch();

if(!$order || !in_array($order->status, ['running', 'pending'], true)) {
        setStep($chat_id, 'none');
        sendMessage($chat_id, "❌ این سفارش یافت نشد یا دیگر فعال نیست.", getMainMenuKeyboard($user));
        die;
}

    $done = intval($order->members_done ?? 0);

if($newCount < $done) {
        sendMessage($chat_id, "⚠️ *تعداد جدید نامعتبر است*\n\n✅ انجام شده تا این لحظه: *$done* نفر\n\nلطفاً عددی مساوی یا بزرگ‌تر از انجام‌شده وارد کنید.");
        die;
}

    $oldCount = intval($order->members_count ?? 0);
    $oldTotalPaid = floatval($order->total_cost ?? 0);
    $basePerMember = floatval($order->coin_per_member ?? 0);
    $extraPaid = calcOrderExtraPaid($order);
    $extraPerMember = ($oldCount > 0) ? ($extraPaid / $oldCount) : 0.0;
    $newTotalPaid = ($basePerMember + $extraPerMember) * $newCount;
    $delta = $newTotalPaid - $oldTotalPaid;
    $stmtU = $pdo->prepare("SELECT `coins` FROM `users` WHERE `user_id` = ? LIMIT 1");
    $stmtU->execute([$chat_id]);
    $userCoins = floatval($stmtU->fetchColumn() ?? 0);

if($delta > 0 && $userCoins < $delta) {
        $need = formatCoins($delta);
        $have = formatCoins($userCoins);
        sendMessage($chat_id, "💸 *موجودی ناکافی برای افزایش سفارش*\n\n💰 مبلغ مورد نیاز: *$need* سکه\n💳 موجودی فعلی: *$have* سکه\n\nابتدا موجودی خود را افزایش دهید و سپس دوباره تلاش کنید.");
        die;
}

    $deltaText = ($delta >= 0) ? ("➕ پرداخت اضافه: *" . formatCoins($delta) . "* سکه") : ("➖ برگشت به کیف پول: *" . formatCoins(abs($delta)) . "* سکه");
    $remainingNew = $newCount - $done;

if($remainingNew < 0) $remainingNew = 0;
    $details = "✏️ *تایید ویرایش سفارش*\n\n" .
        "🧾 سفارش: *#{$order->order_id}*\n" .
        "📢 کانال: *{$order->channel_name}*\n\n" .
        "✅ انجام شده: *$done* نفر\n" .
        "👥 تعداد فعلی: *$oldCount* نفر\n" .
        "👥 تعداد جدید: *$newCount* نفر\n" .
        "⏳ باقیمانده جدید: *$remainingNew* نفر\n\n" .
        $deltaText . "\n" .
        "💰 مبلغ کل جدید: *" . formatCoins($newTotalPaid) . "* سکه";
    $keyboard = [
        "inline_keyboard" => [
            [
                ['text' => '✅ تایید تغییر', 'callback_data' => "edit_order_confirm:{$order->order_id}:$newCount"],
                ['text' => '❌ انصراف', 'callback_data' => 'my_orders_page:1']
            ]
        ]
    ];
    sendMessage($chat_id, $details, json_encode($keyboard));
    die;
}


if($text == "📦 سفارشات من" || $text == "/my_orders") {
    setStep($chat_id, 'none');
    showMyOrders($chat_id, 1);
    die;
}


if(strpos($data, 'my_orders_page:') === 0) {
    $page = intval(substr($data, strlen('my_orders_page:')));
    setStep($chat_id, 'none');
    showMyOrders($chat_id, $page, $message_id);
    die;
}


if(strpos($data, 'boost_order_select:') === 0) {
    $order_id = substr($data, strlen('boost_order_select:'));
    $stmt = $pdo->prepare("SELECT * FROM `orders` WHERE `order_id` = ? AND `user_id` = ?");
    $stmt->execute([$order_id, $chat_id]);
    $order = $stmt->fetch();

if($order) {

if($order->boost_manual > 0) {
            answerCallbackQuery($query_id, "⚠️ توجه\n\nاین سفارش قبلاً بوست شده و در اولویت قرار دارد.", true);
            return;
}

        $baseCost     = $order->members_count * 1;
        $boostCost    = $baseCost * 0.2;
        $boostCostInt = intval($boostCost);
        $userCoins = isset($user->coins) ? intval($user->coins) : 0;
        $responseText = "🚀 *ارتقاء به سفارش بوست شده*\n\n" .
            "📢 کانال: *{$order->channel_name}*\n" .
            "💰 هزینه بوست: *$boostCostInt* سکه\n" .
            "💳 موجودی شما: *$userCoins* سکه\n\n" .
            "با بوست کردن، سفارش شما در *اولویت بالاتر* نمایش داده می‌شود.";
        $keyboard = [
            "inline_keyboard" => [
                [['text' => '✅ تایید و پرداخت', 'callback_data' => "boost_order_confirm:$order_id"]],
                [['text' => '🔙 بازگشت به منو قبل', 'callback_data' => "my_orders_page:1"]]
            ]
        ];
        editMessage($chat_id, $message_id, $responseText, json_encode($keyboard));
} else {
        answerCallbackQuery($query_id, "❌ خطا\n\nسفارش مورد نظر یافت نشد یا حذف شده است.", true);
}

    die;
}


if(strpos($data, 'boost_order_confirm:') === 0) {
    $order_id = substr($data, strlen('boost_order_confirm:'));
    $stmt = $pdo->prepare("SELECT * FROM `orders` WHERE `order_id` = ? AND `user_id` = ?");
    $stmt->execute([$order_id, $chat_id]);
    $order = $stmt->fetch();

if($order) {

if($order->boost_manual > 0) {
            answerCallbackQuery($query_id, "⚠️ توجه\n\nاین سفارش قبلاً بوست شده است.", true);
            return;
}

        $baseCost  = $order->members_count * 1;
        $boostCost = $baseCost * 0.2;
        $userCoins = isset($user->coins) ? intval($user->coins) : 0;

if($userCoins >= $boostCost) {
            $stmt = $pdo->prepare("UPDATE `users` SET `coins` = `coins` - ? WHERE `user_id` = ?");
            $stmt->execute([$boostCost, $chat_id]);
            $stmt = $pdo->prepare("UPDATE `orders` SET `boost_manual` = ?, `total_cost` = `total_cost` + ? WHERE `order_id` = ?");
            $stmt->execute([$boostCost, $boostCost, $order_id]);
            answerCallbackQuery($query_id, "✅ عملیات موفق\n\nسفارش شما با موفقیت بوست شد و در لیست بالاتر قرار گرفت.", true);
            showMyOrders($chat_id, 1, $message_id);
} else {
            answerCallbackQuery($query_id, "💳 موجودی ناکافی\n\nبرای انجام این عملیات موجودی سکه شما کافی نیست.", true);
}

}

    die;
}


if(strpos($data, 'cancel_order_select:') === 0) {
    $order_id = substr($data, strlen('cancel_order_select:'));
    $stmt = $pdo->prepare("SELECT * FROM `orders` WHERE `order_id` = ? AND `user_id` = ?");
    $stmt->execute([$order_id, $chat_id]);
    $order = $stmt->fetch();

if($order) {

if($order->status != 'running' && $order->status != 'pending') {
            answerCallbackQuery($query_id, "⚠️ توجه\n\nفقط سفارش‌های فعال یا در صف انتظار قابل لغو هستند.", true);
            return;
}

        $refund = calcOrderCancelRefund($order);
        $remaining = $refund['remaining'];
        $refundBase = $refund['base_refund'];
        $refundExtra = $refund['extra_refund'];
        $refundTotal = $refund['total_refund'];
        $responseText = "❌ *لغو سفارش*\n\n" .
            "آیا مطمئن هستید که می‌خواهید این سفارش را لغو کنید؟\n\n" .
            "👥 باقی‌مانده: *$remaining* عضو\n" .
            "💰 بازگشت بابت اعضای انجام‌نشده: *" . formatCoins($refundBase) . "* سکه\n" .
            ($refundExtra > 0 ? ("🚀 بازگشت بابت بوست/هزینه اضافه: *" . formatCoins($refundExtra) . "* سکه\n") : "") .
            "🧾 مجموع بازگشت: *" . formatCoins($refundTotal) . "* سکه\n\n" .
            "⚠️ توجه: این عملیات *غیرقابل بازگشت* است.";
        $keyboard = [
            "inline_keyboard" => [
                [['text' => '✅ بله، لغو شود', 'callback_data' => "cancel_order_confirm:$order_id"]],
                [['text' => '🔙 بازگشت به منو قبل', 'callback_data' => "my_orders_page:1"]]
            ]
        ];
        editMessage($chat_id, $message_id, $responseText, json_encode($keyboard));
}

    die;
}


if(strpos($data, 'cancel_order_confirm:') === 0) {
    $order_id = substr($data, strlen('cancel_order_confirm:'));
    try {
        $pdo->beginTransaction();
        $stmt = $pdo->prepare("SELECT * FROM `orders` WHERE `order_id` = ? AND `user_id` = ? FOR UPDATE");
        $stmt->execute([$order_id, $chat_id]);
        $order = $stmt->fetch();

if(!$order || !in_array($order->status, ['running', 'pending'], true)) {
            $pdo->rollBack();
            answerCallbackQuery($query_id, "❌ امکان لغو این سفارش وجود ندارد.", true);
            die;
}

        $refund = calcOrderCancelRefund($order);
        $refundTotal = $refund['total_refund'];

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

        $stmt = $pdo->prepare("UPDATE `orders` SET `status` = 'cancelled', `finished_at` = NOW() WHERE `order_id` = ?");
        $stmt->execute([$order_id]);
        $pdo->commit();
        answerCallbackQuery($query_id, "✅ سفارش لغو شد و مبلغ قابل بازگشت به کیف پول شما اضافه شد.", true);
        showMyOrders($chat_id, 1, $message_id);
} catch (Exception $e) {

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

    die;
}


if(strpos($data, 'edit_order_select:') === 0) {
    $order_id = substr($data, strlen('edit_order_select:'));
    $stmt = $pdo->prepare("SELECT * FROM `orders` WHERE `order_id` = ? AND `user_id` = ? LIMIT 1");
    $stmt->execute([$order_id, $chat_id]);
    $order = $stmt->fetch();

if(!$order || !in_array($order->status, ['running', 'pending'], true)) {
        answerCallbackQuery($query_id, "❌ این سفارش یافت نشد یا دیگر فعال نیست.", true);
        die;
}

    $done = intval($order->members_done ?? 0);
    $count = intval($order->members_count ?? 0);
    setStep($chat_id, "edit_order_count:{$order->order_id}");
    $responseText = "✏️ *ویرایش تعداد سفارش*\n\n" .
        "🧾 سفارش: *#{$order->order_id}*\n" .
        "📢 کانال: *{$order->channel_name}*\n\n" .
        "👥 تعداد فعلی: *$count* نفر\n" .
        "✅ انجام شده: *$done* نفر\n\n" .
        "🔢 لطفاً تعداد جدید را ارسال کنید.\n" .
        "⚠️ تعداد جدید نباید از انجام‌شده کمتر باشد.";
    $keyboard = json_encode([
        "inline_keyboard" => [
            [['text' => '🔙 بازگشت به لیست سفارشات', 'callback_data' => 'my_orders_page:1']]
        ]
    ]);
    editMessage($chat_id, $message_id, $responseText, $keyboard);
    die;
}


if(strpos($data, 'edit_order_confirm:') === 0) {
    $parts = explode(':', $data);
    $orderId = intval($parts[1] ?? 0);
    $newCount = intval($parts[2] ?? 0);

if($orderId <= 0 || $newCount <= 0) {
        answerCallbackQuery($query_id, "❌ درخواست نامعتبر است.", true);
        die;
}

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

if(!$order || !in_array($order->status, ['running', 'pending'], true)) {
            $pdo->rollBack();
            answerCallbackQuery($query_id, "❌ این سفارش دیگر فعال نیست.", true);
            die;
}

        $done = intval($order->members_done ?? 0);

if($newCount < $done) {
            $pdo->rollBack();
            answerCallbackQuery($query_id, "⚠️ تعداد جدید نباید از انجام‌شده کمتر باشد.", true);
            die;
}

        $oldCount = intval($order->members_count ?? 0);
        $oldTotalPaid = floatval($order->total_cost ?? 0);
        $basePerMember = floatval($order->coin_per_member ?? 0);
        $extraPaid = calcOrderExtraPaid($order);
        $extraPerMember = ($oldCount > 0) ? ($extraPaid / $oldCount) : 0.0;
        $newTotalPaid = ($basePerMember + $extraPerMember) * $newCount;
        $delta = $newTotalPaid - $oldTotalPaid;

if(abs($delta) < 0.00001 && $newCount === $oldCount) {
            $pdo->rollBack();
            answerCallbackQuery($query_id, "ℹ️ تغییری اعمال نشد.", false);
            showMyOrders($chat_id, 1, $message_id);
            die;
}


if($delta > 0) {
            $stmtBal = $pdo->prepare("SELECT `coins` FROM `users` WHERE `user_id` = ? FOR UPDATE");
            $stmtBal->execute([$chat_id]);
            $bal = floatval($stmtBal->fetchColumn() ?? 0);

if($bal < $delta) {
                $pdo->rollBack();
                answerCallbackQuery($query_id, "💸 موجودی برای افزایش سفارش کافی نیست.", true);
                die;
}

            $stmtUpd = $pdo->prepare("UPDATE `users` SET `coins` = `coins` - ? WHERE `user_id` = ?");
            $stmtUpd->execute([$delta, $chat_id]);
} elseif ($delta < 0) {
            $refund = abs($delta);
            $stmtUpd = $pdo->prepare("UPDATE `users` SET `coins` = `coins` + ? WHERE `user_id` = ?");
            $stmtUpd->execute([$refund, $chat_id]);
}

        $stmtUpdOrder = $pdo->prepare("UPDATE `orders` SET `members_count` = ?, `total_cost` = ? WHERE `order_id` = ?");
        $stmtUpdOrder->execute([$newCount, $newTotalPaid, $orderId]);
        $pdo->commit();
        setStep($chat_id, 'none');
        answerCallbackQuery($query_id, "✅ تعداد سفارش با موفقیت بروزرسانی شد.", false);
        showMyOrders($chat_id, 1, $message_id);
} catch (Exception $e) {

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

    die;
}


if(strpos($data, 'check_order_memberships:') === 0) {
    $order_id = substr($data, strlen('check_order_memberships:'));
    $stmt = $pdo->prepare("SELECT * FROM `orders` WHERE `order_id` = ? AND `user_id` = ?");
    $stmt->execute([$order_id, $chat_id]);
    $order = $stmt->fetch();

if(!$order) {
        answerCallbackQuery($query_id, "❌ سفارش یافت نشد.", true);
        die;
}


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

    $stmt = $pdo->prepare("SELECT * FROM `memberships` WHERE `order_id` = ?");
    $stmt->execute([$order_id]);
    $memberships = $stmt->fetchAll();
    $totalMembers = count($memberships);

if($totalMembers == 0) {
        answerCallbackQuery($query_id, "ℹ️ هیچ کاربری هنوز عضو نشده است.", true);
        die;
}

    $processed     = 0;
    $joined        = 0;
    $dropped       = 0;
    $refundedTotal = 0;
    $dropRewardCount = 0;
    $dropRewardTotal = 0.0;
    $responseText = "⏳ در حال بررسی عضویت‌ها...\n\n" .
        "📊 وضعیت: 0/$totalMembers (0%)\n" .
        "📉 ریزش: 0 نفر";
    editMessage($chat_id, $message_id, $responseText);
    $channelIdentity = null;
    $stmtCh          = $pdo->prepare("SELECT * FROM `channels` WHERE `channel_name` = ? OR `invite_link` = ? LIMIT 1");
    $stmtCh->execute([$order->channel_name, $order->invite_link]);
    $channelInfo = $stmtCh->fetch();

if($channelInfo) {
        $channelIdentity = $channelInfo->channel_username ? "@" . $channelInfo->channel_username : null;
}


if(!$channelIdentity && preg_match('/ble\.ir\/([a-zA-Z0-9_]+)/', $order->invite_link, $matches)) {

if(strpos($matches[1], '+') === false) {
            $channelIdentity = "@" . $matches[1];
}

}


if(!$channelIdentity) {
        answerCallbackQuery($query_id, "❌ امکان بررسی کانال وجود ندارد (لینک نامعتبر).", true);
        showMyOrders($chat_id, 1, $message_id);
        die;
}

    $lastUpdate = time();

foreach($memberships as $member) {
        $processed++;

if($member->status == 'active') {
            $isMember = false;
            $check    = getChatMember(strtolower($channelIdentity), $member->user_id);

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

if(in_array($status, ['member', 'administrator', 'creator'])) {
                    $isMember = true;
                    $joined++;
}

}


if(!$isMember) {
                $joinTime = strtotime($member->joined_at);
                $timeDiff = time() - $joinTime;

if($timeDiff < 86400) {
                    $dropped++;
                    $refundAmount = $order->coin_per_member;
                    $stmtRef = $pdo->prepare("UPDATE `users` SET `coins` = `coins` + ? WHERE `user_id` = ?");
                    $stmtRef->execute([$refundAmount, $chat_id]);
                    $penaltyAmount = calculateReward($order);
                    $stmtDed       = $pdo->prepare("UPDATE `users` SET `coins` = `coins` - ? WHERE `user_id` = ?");
                    $stmtDed->execute([$penaltyAmount, $member->user_id]);
                    $stmtUpd = $pdo->prepare("UPDATE `memberships` SET `status` = 'left_refunded', `left_at` = NOW(), `penalty_applied` = 1 WHERE `id` = ?");
                    $stmtUpd->execute([$member->id]);
                    $stmtDec = $pdo->prepare("UPDATE `orders` SET `members_done` = IF(`members_done` > 0, `members_done` - 1, 0) WHERE `order_id` = ?");
                    $stmtDec->execute([$order->order_id]);
                    $stmtReopen = $pdo->prepare("UPDATE `orders` SET `status` = 'running', `finished_at` = NULL WHERE `order_id` = ? AND `status` = 'completed' AND `members_done` < `members_count`");
                    $stmtReopen->execute([$order->order_id]);
                    $refundedTotal += $refundAmount;

if(empty($member->drop_compensation_paid)) {
                        $dropReward = 0.75;
                        $stmtDrop = $pdo->prepare("UPDATE `users` SET `coins` = `coins` + ? WHERE `user_id` = ?");
                        $stmtDrop->execute([$dropReward, $chat_id]);
                        $stmtMark = $pdo->prepare("UPDATE `memberships` SET `drop_compensation_paid` = 1, `drop_compensation_paid_at` = NOW() WHERE `id` = ?");
                        $stmtMark->execute([$member->id]);
                        $dropRewardCount++;
                        $dropRewardTotal += $dropReward;
}

} else {
                    $stmtUpd = $pdo->prepare("UPDATE `memberships` SET `status` = 'left_expired', `left_at` = NOW() WHERE `id` = ?");
                    $stmtUpd->execute([$member->id]);

if(empty($member->drop_compensation_paid)) {
                        $dropReward = 0.75;
                        $stmtDrop = $pdo->prepare("UPDATE `users` SET `coins` = `coins` + ? WHERE `user_id` = ?");
                        $stmtDrop->execute([$dropReward, $chat_id]);
                        $stmtMark = $pdo->prepare("UPDATE `memberships` SET `drop_compensation_paid` = 1, `drop_compensation_paid_at` = NOW() WHERE `id` = ?");
                        $stmtMark->execute([$member->id]);
                        $dropRewardCount++;
                        $dropRewardTotal += $dropReward;
}

}

}

} else {

if(in_array($member->status, ['left_refunded', 'left_expired'], true)) {
                $dropped++;

if(empty($member->drop_compensation_paid)) {
                    $dropReward = 0.75;
                    $stmtDrop = $pdo->prepare("UPDATE `users` SET `coins` = `coins` + ? WHERE `user_id` = ?");
                    $stmtDrop->execute([$dropReward, $chat_id]);
                    $stmtMark = $pdo->prepare("UPDATE `memberships` SET `drop_compensation_paid` = 1, `drop_compensation_paid_at` = NOW() WHERE `id` = ?");
                    $stmtMark->execute([$member->id]);
                    $dropRewardCount++;
                    $dropRewardTotal += $dropReward;
}

}

}


if($processed % 5 == 0 || time() - $lastUpdate > 1) {
            $percent      = intval(($processed / $totalMembers) * 100);
            $responseText = "⏳ در حال بررسی عضویت‌ها...\n\n" .
                "📊 وضعیت: $processed/$totalMembers ($percent%)\n" .
                "📉 ریزش یافت شده: $dropped نفر";
            editMessage($chat_id, $message_id, $responseText);
            $lastUpdate = time();
}

}

    $responseText = "✅ *بررسی تکمیل شد*\n\n" .
        "👥 کل بررسی: *$totalMembers* نفر\n" .
        "✅ عضو شده: *$joined* نفر\n" .
        "📉 تعداد ریزش: *$dropped* نفر\n" .
        ($dropRewardCount > 0 ? ("💰 بازگشت بابت ریزش: *" . formatCoins($dropRewardTotal) . "* سکه ({$dropRewardCount}×0.75)") : "");
    $keyboard = [
        "inline_keyboard" => [
            [['text' => '🔙 بازگشت به منو قبل', 'callback_data' => "my_orders_page:1"]]
        ]
    ];
    editMessage($chat_id, $message_id, $responseText, json_encode($keyboard));
    die;
}


function showMyOrders($chat_id, $page, $message_id = null)
{
    global $pdo;
    $limit  = 1;
    $offset = ($page - 1) * $limit;
    $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM `orders` WHERE `user_id` = ?");
    $stmt->execute([$chat_id]);
    $total = $stmt->fetch()->total;

if($total == 0) {
        $responseText = "📭 *لیست سفارشات خالی است*\n\nشما تاکنون هیچ سفارشی ثبت نکرده‌اید.\nبرای افزایش ممبر کانال خود، از *منوی اصلی* اقدام به *ثبت سفارش* کنید.";

if($message_id) {
            editMessage($chat_id, $message_id, $responseText);
} else {
            sendMessage($chat_id, $responseText);
}

        die;
}

    $stmt = $pdo->prepare("SELECT * FROM `orders` WHERE `user_id` = ? ORDER BY `created_at` DESC LIMIT $limit OFFSET $offset");
    $stmt->execute([$chat_id]);
    $orders = $stmt->fetchAll();

if(empty($orders)) {

if($page > 1) {
            showMyOrders($chat_id, 1, $message_id);
            die;
}

}

    $order = $orders[0];
    $stmtLeft = $pdo->prepare("SELECT COUNT(*) as c FROM `memberships` WHERE `order_id` = ? AND `status` = 'left_refunded'");
    $stmtLeft->execute([$order->order_id]);
    $leftCountRow = $stmtLeft->fetch();
    $leftCount    = $leftCountRow ? intval($leftCountRow->c) : 0;
    $progress = 0;
    $totalDone = $order->members_done;

if($order->status == 'completed') {
        $progress = 100;

if($totalDone < $order->members_count) {
             $totalDone = $order->members_count;
}

} elseif ($order->members_count > 0) {
        $progress = ($totalDone / $order->members_count) * 100;
}


if($progress > 100) $progress = 100;
    $progressInt = intval($progress);
    $statusText  = "نامشخص";
    $statusEmoji = "⚪️";

if($order->status == 'running') {
        $statusText  = "فعال";
        $statusEmoji = "📌";
} elseif ($order->status == 'pending') {
        $statusText  = "در صف انتظار";
        $statusEmoji = "⏳";
} elseif ($order->status == 'completed') {
        $statusText  = "تکمیل شده";
        $statusEmoji = "✅";
} elseif ($order->status == 'cancelled') {
        $statusText  = "لغو شده";
        $statusEmoji = "❌";
}

    $isBoosted = ($order->boost_manual > 0);
    $boostText = $isBoosted ? "*(🚀 بوست شده)*" : "";
    $reward = settings('cost_per_join', 0.5);
    $is_vip = $order->is_vip ? "ویژه 💎" : "عادی 🏅";
    $started_at  = jdate("H:i  Y/m/d", strtotime($order->started_at));
    $finished_at = !$order->finished_at ? "محاسبه نشده" : jdate("H:i  Y/m/d", strtotime($order->finished_at));
    $responseText = "$statusEmoji *سفارش #{$order->order_id}*\n" .
        "📢 *{$order->channel_name}*\n\n" .
        "📊 پیشرفت: *$progressInt%* ({$totalDone}/{$order->members_count})\n" .
        "💰 پاداش: *" . floatval($reward) . "* سکه $boostText\n" .
        "📌 وضعیت: *$statusText*\n" .
        "🔘 نوع سفارش: *$is_vip*\n" .
        "🟠 تاریخ شروع: $started_at\n" .
        "🟢 تاریخ اتمام: $finished_at"
    ;
    $keyboard = [];
    $row1     = [];

if($order->status == 'running' || $order->status == 'pending') {
        $row1[] = ['text' => '✏️ ویرایش', 'callback_data' => "edit_order_select:{$order->order_id}"];

if(!$isBoosted && $order->status == 'running') {
            $row1[] = ['text' => '🚀 فعالسازی بوست', 'callback_data' => "boost_order_select:{$order->order_id}"];
}

        $row1[] = ['text' => '❌ لغو سفارش', 'callback_data' => "cancel_order_select:{$order->order_id}"];
}


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


if($order->status == 'running' || $order->status == 'completed') {
        $keyboard[] = [['text' => '👥 بررسی ریزش و عضویت‌ها', 'callback_data' => "check_order_memberships:{$order->order_id}"]];
}

    $row2 = [];

if($page > 1) {
        $row2[] = ['text' => '➡️ قبلی', 'callback_data' => "my_orders_page:" . ($page - 1)];
}


if($page * $limit < $total) {
        $row2[] = ['text' => 'بعدی ⬅️', 'callback_data' => "my_orders_page:" . ($page + 1)];
}


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

    $markup = ["inline_keyboard" => $keyboard];

if($message_id) {
        editMessage($chat_id, $message_id, $responseText, json_encode($markup));
} else {
        sendMessage($chat_id, $responseText, json_encode($markup));
}

}

