<?php
if($text == "🔎 جستجوی سفارش" && ($user->is_owner || $user->is_admin)) {
    setStep($chat_id, 'admin:search_order');
    $cancel_keyboard = json_encode([
        'keyboard' => [
            [['text' => '🔙 بازگشت به مدیریت']]
        ],
        'resize_keyboard' => true
    ]);
    sendMessage($chat_id, "🔢 لطفا *کد سفارش* (Order ID) مورد نظر را ارسال کنید:", $cancel_keyboard);
    die;
}


if($text == "📦 آخرین سفارشات" && ($user->is_owner || $user->is_admin)) {
    adminShowLatestOrders($chat_id, 1, $pdo);
    die;
}


if($user->step == 'admin:search_order') {

if(!is_numeric($text)) {
        sendMessage($chat_id, "⚠️ کد سفارش باید عددی باشد.");
        die;
}

    $target_order_id = $text;
    adminShowOrderInfo($chat_id, $target_order_id, $pdo);
    setStep($chat_id, 'none');
    die;
}


if(strpos($user->step, 'admin:edit_order_count:') === 0) {
    $target_order_id = explode(':', $user->step)[2];

if(!is_numeric($text) || intval($text) < 1) {
        sendMessage($chat_id, "⚠️ لطفا یک عدد معتبر بزرگتر از 0 وارد کنید.");
        die;
}

    $new_count = intval($text);
    $stmt = $pdo->prepare("SELECT * FROM `orders` WHERE `order_id` = ?");
    $stmt->execute([$target_order_id]);
    $order = $stmt->fetch();

if(!$order) {
        sendMessage($chat_id, "⚠️ سفارش یافت نشد.", $admin_keyboard);
        setStep($chat_id, 'none');
        die;
}

    $stmt = $pdo->prepare("UPDATE `orders` SET `members_count` = ? WHERE `order_id` = ?");
    $stmt->execute([$new_count, $target_order_id]);
    sendMessage($chat_id, "✅ تعداد درخواستی سفارش #$target_order_id به *$new_count* نفر تغییر یافت.");
    adminShowOrderInfo($chat_id, $target_order_id, $pdo);
    setStep($chat_id, 'none');
    die;
}


function adminShowOrderInfo($chat_id, $order_id, $pdo, $message_id = null, $navRow = null, $refreshCallback = null)
{
    $stmt = $pdo->prepare("SELECT o.*, u.user_id as owner_id, u.full_name, u.username FROM `orders` o LEFT JOIN `users` u ON o.user_id = u.user_id WHERE o.order_id = ?");
    $stmt->execute([$order_id]);
    $order = $stmt->fetch();

if(!$order) {
        $msg = "⚠️ سفارشی با این کد یافت نشد.";

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

        return;
}

    $progress = 0;

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

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

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

    $stmtLeft = $pdo->prepare("SELECT COUNT(*) FROM `memberships` WHERE `order_id` = ? AND `status` = 'left_refunded'");
    $stmtLeft->execute([$order_id]);
    $dropsCount = $stmtLeft->fetchColumn();
    $isBoosted = ($order->boost_manual > 0);
    $boostText = $isBoosted ? "🚀 (بوست شده)" : "";
    $ownerName = $order->full_name ?? 'نامشخص';
    $ownerLink = "https://web.bale.ai/chat?uid=" . $order->owner_id;
    $responseText = "$statusEmoji *جزئیات کامل سفارش #{$order->order_id}*\n" .
        "━━━━━━━━━━━━━━━━━━━━\n" .
        "👤 *صاحب سفارش:* [$ownerName]($ownerLink) ({$order->owner_id})\n" .
        "📢 *کانال:* {$order->channel_name}\n" .
        "🔗 *لینک:* {$order->invite_link}\n\n" .
        "🔢 *تعداد درخواستی:* *{$order->members_count}* نفر\n" .
        "✅ *انجام شده:* *{$order->members_done}* نفر\n" .
        "📉 *ریزش (لفت):* *{$dropsCount}* نفر\n" .
        "📊 *پیشرفت:* *$progressInt%*\n\n" .
        "💰 *هزینه کل:* *" . number_format($order->total_cost) . "* سکه $boostText\n" .
        "📌 *وضعیت:* *$statusText*\n" .
        "📅 *تاریخ ثبت:* *" . jdate("H:i Y/m/d", strtotime($order->created_at)) . "*\n";

if($order->finished_at) {
        $responseText .= "🏁 *تاریخ اتمام:* *" . jdate("H:i Y/m/d", strtotime($order->finished_at)) . "*\n";
}

    $keyboard = [];
    $row1 = [];

if($order->status == 'running') {
        $row1[] = ['text' => '⛔️ توقف سفارش', 'callback_data' => "adm_ord_stop:{$order->order_id}"];
} elseif ($order->status == 'stopped') {
        $row1[] = ['text' => '▶️ شروع مجدد', 'callback_data' => "adm_ord_start:{$order->order_id}"];
}


if($order->status == 'running' || $order->status == 'stopped') {
        $row1[] = ['text' => '✅ اتمام دستی', 'callback_data' => "adm_ord_finish:{$order->order_id}"];
}


if($order->status != 'cancelled' && $order->status != 'completed') {
        $row1[] = ['text' => '❌ لغو سفارش', 'callback_data' => "adm_ord_cancel:{$order->order_id}"];
}


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

if(!$isBoosted && ($order->status == 'running' || $order->status == 'stopped')) {
        $row2[] = ['text' => '🚀 بوست سفارش', 'callback_data' => "adm_ord_boost:{$order->order_id}"];
}

    $row2[] = ['text' => '✏️ تغییر تعداد', 'callback_data' => "adm_ord_edit_count:{$order->order_id}"];

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

if(!$refreshCallback) {
        $refreshCallback = "adm_ord_refresh:{$order->order_id}";
}

    $keyboard[] = [
        ['text' => '🔄 بروزرسانی', 'callback_data' => $refreshCallback]
    ];

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

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

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

}


function adminShowLatestOrders($chat_id, $page, $pdo, $message_id = null)
{
    $limit  = 1;
    $offset = ($page - 1) * $limit;
    $stmt = $pdo->query("SELECT COUNT(*) FROM `orders`");
    $total = intval($stmt->fetchColumn());

if($total == 0) {
        $msg = "📭 هیچ سفارشی ثبت نشده است.";

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

        return;
}

    $stmt = $pdo->prepare("SELECT `order_id` FROM `orders` ORDER BY `created_at` DESC LIMIT $limit OFFSET $offset");
    $stmt->execute();
    $row = $stmt->fetch();

if(!$row) {
        $page = 1;
        $stmt = $pdo->prepare("SELECT `order_id` FROM `orders` ORDER BY `created_at` DESC LIMIT $limit OFFSET 0");
        $stmt->execute();
        $row = $stmt->fetch();
}


if(!$row) {
        $msg = "📭 سفارشی یافت نشد.";

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

        return;
}

    $navRow = [];

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


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

    adminShowOrderInfo($chat_id, $row->order_id, $pdo, $message_id, !empty($navRow) ? $navRow : null, "adm_ord_refresh_latest:$page");
}


if(!empty($data) && ($user->is_owner || $user->is_admin)) {

if(strpos($data, 'adm_ord_refresh:') === 0) {
        $order_id = explode(':', $data)[1];
        adminShowOrderInfo($chat_id, $order_id, $pdo, $message_id);
        answerCallbackQuery($query_id, "بروزرسانی شد");
        die;
}


if(strpos($data, 'adm_ord_refresh_latest:') === 0) {
        $page = intval(explode(':', $data)[1]);
        adminShowLatestOrders($chat_id, $page, $pdo, $message_id);
        answerCallbackQuery($query_id, "بروزرسانی شد");
        die;
}


if(strpos($data, 'adm_ord_stop:') === 0) {
        $order_id = explode(':', $data)[1];
        $stmt = $pdo->prepare("UPDATE `orders` SET `status` = 'stopped' WHERE `order_id` = ?");
        $stmt->execute([$order_id]);
        answerCallbackQuery($query_id, "✅ سفارش متوقف شد.", true);
        adminShowOrderInfo($chat_id, $order_id, $pdo, $message_id);
        die;
}


if(strpos($data, 'adm_ord_start:') === 0) {
        $order_id = explode(':', $data)[1];
        $stmt = $pdo->prepare("UPDATE `orders` SET `status` = 'running' WHERE `order_id` = ?");
        $stmt->execute([$order_id]);
        answerCallbackQuery($query_id, "✅ سفارش مجدداً فعال شد.", true);
        adminShowOrderInfo($chat_id, $order_id, $pdo, $message_id);
        die;
}


if(strpos($data, 'adm_ord_finish:') === 0) {
        $order_id = explode(':', $data)[1];
        $stmt = $pdo->prepare("UPDATE `orders` SET `status` = 'completed', `finished_at` = NOW() WHERE `order_id` = ?");
        $stmt->execute([$order_id]);
        answerCallbackQuery($query_id, "✅ سفارش به حالت تکمیل شده تغییر یافت.", true);
        adminShowOrderInfo($chat_id, $order_id, $pdo, $message_id);
        die;
}


if(strpos($data, 'adm_ord_boost:') === 0) {
        $order_id = explode(':', $data)[1];
        $stmt = $pdo->prepare("UPDATE `orders` SET `boost_manual` = 1 WHERE `order_id` = ?");
        $stmt->execute([$order_id]);
        answerCallbackQuery($query_id, "✅ سفارش بوست شد.", true);
        adminShowOrderInfo($chat_id, $order_id, $pdo, $message_id);
        die;
}


if(strpos($data, 'adm_ord_edit_count:') === 0) {
        $order_id = explode(':', $data)[1];
        setStep($chat_id, "admin:edit_order_count:$order_id");
        $cancel_keyboard = json_encode([
            'keyboard' => [
                [['text' => '🔙 بازگشت به مدیریت']]
            ],
            'resize_keyboard' => true
        ]);
        sendMessage($chat_id, "✏️ لطفا *تعداد جدید* اعضای درخواستی را وارد کنید:", $cancel_keyboard);
        answerCallbackQuery($query_id);
        die;
}


if(strpos($data, 'adm_ord_cancel:') === 0) {
        $order_id = explode(':', $data)[1];
        $stmt = $pdo->prepare("SELECT * FROM `orders` WHERE `order_id` = ?");
        $stmt->execute([$order_id]);
        $order = $stmt->fetch();

if($order && $order->status != 'cancelled' && $order->status != 'completed') {
            $remaining = $order->members_count - $order->members_done;

if($remaining < 0) {
                $remaining = 0;
}

            $refundAmount = $remaining * $order->coin_per_member;
            $stmt = $pdo->prepare("UPDATE `users` SET `coins` = `coins` + ? WHERE `user_id` = ?");
            $stmt->execute([$refundAmount, $order->user_id]);
            $stmt = $pdo->prepare("UPDATE `orders` SET `status` = 'cancelled', `finished_at` = NOW() WHERE `order_id` = ?");
            $stmt->execute([$order_id]);
            $msg = "❌ *سفارش شما توسط مدیریت لغو شد.*\n\n" .
                "🔖 *سفارش #{$order_id}*\n" .
                "💰 *مبلغ بازگشتی:* " . number_format($refundAmount) . " سکه";
            sendMessage($order->user_id, $msg);
            answerCallbackQuery($query_id, "✅ سفارش لغو شد و مبلغ به کاربر برگشت داده شد.", true);
            adminShowOrderInfo($chat_id, $order_id, $pdo, $message_id);
} else {
            answerCallbackQuery($query_id, "❌ امکان لغو این سفارش وجود ندارد.", true);
}

        die;
}


if(strpos($data, 'admin_latest_orders_page:') === 0) {
        $page = intval(explode(':', $data)[1]);
        adminShowLatestOrders($chat_id, $page, $pdo, $message_id);
        answerCallbackQuery($query_id);
        die;
}


if($data == 'admin_panel_back') {
         $msg = "👋 به پنل مدیریت بازگشتید.";
         sendMessage($chat_id, $msg);
         answerCallbackQuery($query_id);
         die;
}


if(strpos($data, 'adm_ord_check:') === 0) {
        $order_id = explode(':', $data)[1];
        $stmt = $pdo->prepare("SELECT * FROM `orders` WHERE `order_id` = ?");
        $stmt->execute([$order_id]);
        $order = $stmt->fetch();

if(!$order) {
            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;
}

        editMessage($chat_id, $message_id, "⏳ در حال بررسی وضعیت اعضا...");
        $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);
            adminShowOrderInfo($chat_id, $order_id, $pdo, $message_id);
            die;
}

        $processed     = 0;
        $dropped       = 0;
        $refundedTotal = 0;
        $joined        = 0;
        $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, $order->user_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_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_id]);
                        $refundedTotal += $refundAmount;
} else {
                        $stmtUpd = $pdo->prepare("UPDATE `memberships` SET `status` = 'left_expired', `left_at` = NOW() WHERE `id` = ?");
                        $stmtUpd->execute([$member->id]);
}

}

} else {

if($member->status == 'left_refunded') {
                    $dropped++;
}

}


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

}

        $msg = "✅ *بررسی تکمیل شد*\n\n" .
            "👥 کل بررسی: $totalMembers نفر\n" .
            "✅ عضو مانده: $joined نفر\n" .
            "📉 تعداد ریزش (زیر ۲۴ ساعت): $dropped نفر\n" .
            "💰 مبلغ بازگشتی به صاحب سفارش: " . intval($refundedTotal) . " سکه";
        adminShowOrderInfo($chat_id, $order_id, $pdo, $message_id);
        sendMessage($chat_id, $msg);
        die;
}

}

