<?php
declare(strict_types=1);

function showAdminDashboard(PDO $pdo, int $chatId, ?int $editMsgId = null): void {
    $settings = getSettings($pdo);
    $isOpen = (int) $settings['is_open'] === 1;
    $roundId = (int) $settings['current_round_id'];
    $channelStatus = !empty($settings['report_channel_id']) ? 'متصل ✅' : 'تنظیم نشده ⚠️';

    $confirmed = 0;
    $cancelled = 0;
    $revenue = 0;

    if ($roundId > 0) {
        $st = $pdo->prepare("
            SELECT
                SUM(CASE WHEN status IN ('confirmed', 'delivered') THEN 1 ELSE 0 END) AS ok_cnt,
                SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS can_cnt,
                SUM(CASE WHEN status IN ('confirmed', 'delivered') THEN price_at_order ELSE 0 END) AS total_rev
            FROM orders
            WHERE round_id = ?
        ");
        $st->execute([$roundId]);
        $agg = $st->fetch();
        $confirmed = (int) ($agg['ok_cnt'] ?? 0);
        $cancelled = (int) ($agg['can_cnt'] ?? 0);
        $revenue   = (int) ($agg['total_rev'] ?? 0);
    }

    $statusStr = $isOpen ? "🟢 <b>باز</b> (دوره #{$roundId})" : "🔴 <b>بسته</b> (آخرین دوره: #{$roundId})";
    $revStr = number_format($revenue);

    $text = "🛠 <b>پنل مدیریت ربات آف</b>\n\n"
          . "وضعیت: {$statusStr}\n"
          . "📦 سفارش‌های فعال دوره: <code>{$confirmed}</code> | ❌ لغوشده: <code>{$cancelled}</code>\n"
          . "💰 فروش تخمینی دوره: <code>{$revStr}</code> تومان\n"
          . "📢 کانال گزارش: {$channelStatus}";

    $roundBtn = $isOpen
        ? ['text' => '🔴 بستن آف فعلی', 'callback_data' => 'adm_close_ask']
        : ['text' => '🟢 شروع آف جدید', 'callback_data' => 'adm_start_round'];

    $markup = inlineKb([
        [$roundBtn, ['text' => '📣 خبر دادن به اعضا', 'callback_data' => 'adm_broadcast']],
        [['text' => '📦 مدیریت محصولات', 'callback_data' => 'adm_prods_1'], ['text' => '➕ افزودن محصول', 'callback_data' => 'adm_add_prod']],
        [['text' => '📊 آمار لحظه‌ای دوره', 'callback_data' => 'adm_stats'], ['text' => '🔍 پیگیری کد تحویل', 'callback_data' => 'adm_track']],
        [['text' => '🚫 لیست بدقول‌ها', 'callback_data' => 'adm_badusers'], ['text' => '📢 تنظیم کانال گزارش', 'callback_data' => 'adm_set_channel']],
        [['text' => '🔄 بروزرسانی داشبورد', 'callback_data' => 'adm_home']],
    ]);

    if ($editMsgId !== null) {
        editMsg($chatId, $editMsgId, $text, $markup);
    } else {
        sendMsg($chatId, $text, $markup);
    }
}

function buildRoundSummaryText(PDO $pdo, int $roundId, string $header): string {
    if ($roundId <= 0) {
        return "هنوز هیچ دوره آفی ثبت نشده است.";
    }

    $stmt = $pdo->prepare("
        SELECT
            o.product_id,
            o.product_name,
            SUM(CASE WHEN o.status IN ('confirmed', 'delivered') THEN 1 ELSE 0 END) AS sold_cnt,
            SUM(CASE WHEN o.status = 'delivered' THEN 1 ELSE 0 END) AS del_cnt,
            SUM(CASE WHEN o.status = 'cancelled' THEN 1 ELSE 0 END) AS can_cnt,
            SUM(CASE WHEN o.status = 'no_show' THEN 1 ELSE 0 END) AS ns_cnt,
            SUM(CASE WHEN o.status IN ('confirmed', 'delivered') THEN o.price_at_order ELSE 0 END) AS sum_price,
            COALESCE(p.stock, 0) AS rem_stock
        FROM orders o
        LEFT JOIN products p ON p.id = o.product_id
        WHERE o.round_id = ?
        GROUP BY o.product_id, o.product_name, p.stock
        ORDER BY sold_cnt DESC
    ");
    $stmt->execute([$roundId]);
    $rows = $stmt->fetchAll();

    $text = "{$header}\n🗓 دوره: <b>#R{$roundId}</b>\n──────────────\n";
    if (!$rows) {
        return $text . "در این دوره هنوز سفارشی ثبت نشده است.";
    }

    $totalUnits = 0;
    $totalMoney = 0;
    foreach ($rows as $r) {
        $sold = (int) $r['sold_cnt'];
        $totalUnits += $sold;
        $totalMoney += (int) $r['sum_price'];
        $money = number_format((int) $r['sum_price']);
        $text .= "▪️ <b>" . h($r['product_name']) . "</b>\n"
               . "   فروش: <code>{$sold}</code> | مانده: <code>{$r['rem_stock']}</code> | لغو: <code>{$r['can_cnt']}</code> | مبلغ: <code>{$money}</code> ت\n";
    }

    $text .= "──────────────\n"
           . "📦 جمع تعداد فروش: <b>{$totalUnits}</b> عدد\n"
           . "💰 جمع کل تخمینی: <b>" . number_format($totalMoney) . "</b> تومان";
    return $text;
}

function showAdminProductsPage(PDO $pdo, int $chatId, int $page, int $msgId): void {
    $perPage = PRODUCTS_PER_PAGE;
    $total = (int) $pdo->query("SELECT COUNT(*) FROM products")->fetchColumn();
    if ($total === 0) {
        editMsg($chatId, $msgId, "هنوز محصولی ثبت نشده است.", inlineKb([
            [['text' => '➕ افزودن محصول', 'callback_data' => 'adm_add_prod']],
            [['text' => '🔙 بازگشت به پنل', 'callback_data' => 'adm_home']],
        ]));
        return;
    }

    $totalPages = (int) ceil($total / $perPage);
    $page = max(1, min($page, $totalPages));
    $offset = ($page - 1) * $perPage;

    $stmt = $pdo->prepare("SELECT * FROM products ORDER BY id DESC LIMIT :lim OFFSET :off");
    $stmt->bindValue(':lim', $perPage, PDO::PARAM_INT);
    $stmt->bindValue(':off', $offset, PDO::PARAM_INT);
    $stmt->execute();
    $prods = $stmt->fetchAll();

    $text = "📦 <b>مدیریت محصولات (صفحه {$page} از {$totalPages})</b>\n\n";
    $btns = [];
    foreach ($prods as $p) {
        $icon = (int) $p['is_active'] === 1 ? '🟢' : '⚪️';
        $price = number_format((int) $p['price']);
        $text .= "{$icon} <b>" . h($p['name']) . "</b> — {$price} ت | موجودی: <code>{$p['stock']}</code> | سقف: {$p['max_per_user']}\n";
        $btns[] = ['text' => $p['name'], 'callback_data' => 'adm_prod_' . $p['id']];
    }

    $rows = array_chunk($btns, 2);
    if ($totalPages > 1) {
        $nav = [];
        if ($page > 1) $nav[] = ['text' => 'قبل ▶️', 'callback_data' => 'adm_prods_' . ($page - 1)];
        $nav[] = ['text' => "{$page} / {$totalPages}", 'callback_data' => 'noop'];
        if ($page < $totalPages) $nav[] = ['text' => '◀️ بعد', 'callback_data' => 'adm_prods_' . ($page + 1)];
        $rows[] = $nav;
    }
    $rows[] = [['text' => '🔙 بازگشت به پنل', 'callback_data' => 'adm_home']];

    editMsg($chatId, $msgId, $text, inlineKb($rows));
}

function showAdminSingleProduct(PDO $pdo, int $chatId, int $prodId, int $msgId): void {
    $stmt = $pdo->prepare("SELECT * FROM products WHERE id = ?");
    $stmt->execute([$prodId]);
    $p = $stmt->fetch();
    if (!$p) {
        editMsg($chatId, $msgId, "محصول پیدا نشد.", inlineKb([[['text' => '🔙 بازگشت', 'callback_data' => 'adm_prods_1']]]));
        return;
    }

    $activeStr = (int) $p['is_active'] === 1 ? 'فعال 🟢' : 'مخفی ⚪️';
    $toggleText = (int) $p['is_active'] === 1 ? '👁 مخفی کردن محصول' : '👁 فعال کردن محصول';

    $text = "📦 <b>" . h($p['name']) . "</b>\n\n"
          . "💰 قیمت: <code>" . number_format((int) $p['price']) . "</code> تومان\n"
          . "📊 موجودی فعلی: <code>{$p['stock']}</code> عدد\n"
          . "👤 سقف خرید هر نفر: <code>{$p['max_per_user']}</code> عدد\n"
          . "📌 وضعیت نمایش: {$activeStr}";

    $markup = inlineKb([
        [
            ['text' => '+5', 'callback_data' => "adm_stk_{$prodId}_5"],
            ['text' => '+1', 'callback_data' => "adm_stk_{$prodId}_1"],
            ['text' => '-1', 'callback_data' => "adm_stk_{$prodId}_-1"],
            ['text' => 'صفر (0)', 'callback_data' => "adm_stk_{$prodId}_zero"],
        ],
        [
            ['text' => '✏️ تغییر قیمت', 'callback_data' => "adm_price_{$prodId}"],
            ['text' => $toggleText,     'callback_data' => "adm_toggle_{$prodId}"],
        ],
        [
            ['text' => '🗑 حذف محصول', 'callback_data' => "adm_del_ask_{$prodId}"],
            ['text' => '🔙 لیست محصولات', 'callback_data' => 'adm_prods_1'],
        ]
    ]);
    editMsg($chatId, $msgId, $text, $markup);
}

function showAdminBadUsers(PDO $pdo, int $chatId, int $msgId): void {
    $badUsers = $pdo->query("
        SELECT telegram_id, full_name, student_id, no_show_count, is_banned
        FROM users
        WHERE no_show_count > 0 OR is_banned = 1
        ORDER BY no_show_count DESC
        LIMIT 15
    ")->fetchAll();

    if (!$badUsers) {
        editMsg($chatId, $msgId, "✅ هیچ کاربر بدقول یا مسدودی ثبت نشده است.", inlineKb([
            [['text' => '🔙 بازگشت به پنل', 'callback_data' => 'adm_home']]
        ]));
        return;
    }

    $text = "🚫 <b>لیست افراد بدقول / مسدودشده:</b>\n\n";
    $rows = [];
    foreach ($badUsers as $bu) {
        $tag = (int) $bu['is_banned'] === 1 ? '🔴 مسدود' : '🟡 آزاد';
        $name = $bu['full_name'] ?: (string) $bu['telegram_id'];
        $text .= "👤 <b>" . h($name) . "</b> (<code>" . h((string) $bu['student_id']) . "</code>) — غیبت: {$bu['no_show_count']} | {$tag}\n";
        $rows[] = [[
            'text'          => (int) $bu['is_banned'] === 1 ? "🔓 آزاد کردن {$name}" : "🚫 بن کردن {$name}",
            'callback_data' => ((int) $bu['is_banned'] === 1 ? 'adm_unban_' : 'adm_ban_') . $bu['telegram_id'],
        ]];
    }
    $rows[] = [['text' => '🔙 بازگشت به پنل', 'callback_data' => 'adm_home']];
    editMsg($chatId, $msgId, $text, inlineKb($rows));
}

function updateOrderStatusByAdmin(PDO $pdo, int $orderId, string $newStatus): array {
    try {
        $pdo->beginTransaction();
        $stmt = $pdo->prepare("SELECT * FROM orders WHERE id = ? FOR UPDATE");
        $stmt->execute([$orderId]);
        $order = $stmt->fetch();

        if (!$order) {
            $pdo->rollBack();
            return ['ok' => false, 'msg' => 'سفارش یافت نشد.'];
        }

        $oldStatus = $order['status'];
        if ($oldStatus === $newStatus) {
            $pdo->rollBack();
            return ['ok' => true, 'msg' => 'وضعیت قبلاً همین بوده است.'];
        }

        if ($newStatus === 'cancelled' && $oldStatus !== 'cancelled') {
            $pdo->prepare("UPDATE products SET stock = stock + 1 WHERE id = ?")->execute([(int) $order['product_id']]);
        }

        if ($newStatus === 'no_show' && $oldStatus !== 'no_show') {
            $pdo->prepare("UPDATE users SET no_show_count = no_show_count + 1 WHERE telegram_id = ?")->execute([(int) $order['user_id']]);
        } elseif ($oldStatus === 'no_show' && $newStatus === 'delivered') {
            $pdo->prepare("UPDATE users SET no_show_count = GREATEST(0, no_show_count - 1) WHERE telegram_id = ?")->execute([(int) $order['user_id']]);
        }

        $pdo->prepare("UPDATE orders SET status = ? WHERE id = ?")->execute([$newStatus, $orderId]);
        $pdo->commit();
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        return ['ok' => false, 'msg' => 'خطا در بروزرسانی وضعیت.'];
    }

    syncChannelOrderCard($pdo, $orderId);
    return ['ok' => true, 'msg' => 'وضعیت به «' . formatStatusLabel($newStatus) . '» تغییر کرد.'];
}

function showTrackedOrderToAdmin(PDO $pdo, int $chatId, int $orderId, ?int $editMsgId = null): void {
    $stmt = $pdo->prepare("
        SELECT o.*, u.full_name, u.student_id, u.phone, u.is_banned, u.no_show_count
        FROM orders o
        JOIN users u ON u.telegram_id = o.user_id
        WHERE o.id = ?
    ");
    $stmt->execute([$orderId]);
    $order = $stmt->fetch();

    if (!$order) {
        $text = "❌ سفارشی پیدا نشد.";
        $editMsgId ? editMsg($chatId, $editMsgId, $text) : sendMsg($chatId, $text);
        return;
    }

    $text = formatChannelOrderCard($order) . "\n🚫 تعداد بدقولی قبلی: <code>{$order['no_show_count']}</code>";
    $banBtn = (int) $order['is_banned'] === 1
        ? ['text' => '🔓 رفع مسدودیت کاربر', 'callback_data' => "adm_unban_{$order['user_id']}_{$orderId}"]
        : ['text' => '🚫 مسدود کردن کاربر',  'callback_data' => "adm_ban_{$order['user_id']}_{$orderId}"];

    $markup = inlineKb([
        [
            ['text' => '✅ تحویل شد', 'callback_data' => "adm_ord_del_{$orderId}"],
            ['text' => '🚫 نیامد',    'callback_data' => "adm_ord_ns_{$orderId}"],
        ],
        [
            ['text' => '❌ لغو دستی + برگشت انبار', 'callback_data' => "adm_ord_can_{$orderId}"],
            $banBtn,
        ],
        [['text' => '🔙 بازگشت به پنل', 'callback_data' => 'adm_home']],
    ]);

    $editMsgId ? editMsg($chatId, $editMsgId, $text, $markup) : sendMsg($chatId, $text, $markup);
}

function handleChannelCallback(PDO $pdo, array $cb): bool {
    $data = (string) ($cb['data'] ?? '');
    if (strpos($data, 'ch_del_') !== 0 && strpos($data, 'ch_ns_') !== 0) {
        return false;
    }

    $fromId = (int) $cb['from']['id'];
    if (!isAdmin($fromId)) {
        answerCb($cb['id'], '⛔ فقط ادمین می‌تواند وضعیت تحویل را تغییر دهد.', true);
        return true;
    }

    $isDel = strpos($data, 'ch_del_') === 0;
    $orderId = (int) substr($data, $isDel ? 7 : 6);
    $res = updateOrderStatusByAdmin($pdo, $orderId, $isDel ? 'delivered' : 'no_show');
    answerCb($cb['id'], $res['msg']);
    return true;
}

function handleAdminCallback(PDO $pdo, array $cb): bool {
    $data = (string) ($cb['data'] ?? '');
    if (strpos($data, 'adm_') !== 0) {
        return false;
    }

    $userId = (int) $cb['from']['id'];
    $chatId = (int) $cb['message']['chat']['id'];
    $msgId  = (int) $cb['message']['message_id'];
    $cbId   = (string) $cb['id'];

    if (!isAdmin($userId)) {
        answerCb($cbId, '⛔ شما دسترسی ادمین ندارید.', true);
        return true;
    }

    if ($data === 'adm_home') {
        setUserState($pdo, $userId, 'idle', null);
        answerCb($cbId);
        showAdminDashboard($pdo, $chatId, $msgId);
        return true;
    }

    if ($data === 'adm_start_round') {
        $title = 'آف ' . date('Y-m-d H:i');
        $pdo->prepare("INSERT INTO rounds (title) VALUES (?)")->execute([$title]);
        $newRoundId = (int) $pdo->lastInsertId();
        $pdo->prepare("UPDATE settings SET is_open = 1, current_round_id = ? WHERE id = 1")->execute([$newRoundId]);
        answerCb($cbId, "✅ آف جدید (دوره #{$newRoundId}) باز شد!");
        showAdminDashboard($pdo, $chatId, $msgId);
        return true;
    }

    if ($data === 'adm_close_ask') {
        answerCb($cbId);
        editMsg($chatId, $msgId, "⚠️ مطمئنید می‌خواهید آف این دوره را ببندید؟\n(ثبت سفارش و لغو سفارش برای کاربران قفل می‌شود و گزارش جمع‌بندی به کانال ارسال خواهد شد.)", inlineKb([
            [
                ['text' => '🔴 بله، ببند', 'callback_data' => 'adm_close_yes'],
                ['text' => '🔙 انصراف',     'callback_data' => 'adm_home'],
            ]
        ]));
        return true;
    }

    if ($data === 'adm_close_yes') {
        $settings = getSettings($pdo);
        $roundId = (int) $settings['current_round_id'];
        $pdo->exec("UPDATE settings SET is_open = 0 WHERE id = 1");
        if ($roundId > 0) {
            $pdo->prepare("UPDATE rounds SET closed_at = NOW() WHERE id = ?")->execute([$roundId]);
        }

        if (!empty($settings['report_channel_id']) && $roundId > 0) {
            $summary = buildRoundSummaryText($pdo, $roundId, "📊 <b>جمع‌بندی پایان آف</b>");
            sendMsg((int) $settings['report_channel_id'], $summary);
        }

        answerCb($cbId, '🔴 آف بسته شد و گزارش به کانال ارسال گردید.');
        showAdminDashboard($pdo, $chatId, $msgId);
        return true;
    }

    if ($data === 'adm_broadcast') {
        $settings = getSettings($pdo);
        if ((int) $settings['is_open'] !== 1) {
            answerCb($cbId, '⚠️ اول آف جدید را باز کنید، بعد خبررسانی بزنید.', true);
            return true;
        }
        answerCb($cbId, 'در حال ارسال اعلان به اعضا...');
        $users = $pdo->query("SELECT telegram_id FROM users WHERE notify_me = 1 AND is_banned = 0")->fetchAll();
        $sent = 0;
        $broadcastKb = inlineKb([[['text' => '🛍 مشاهده محصولات آف', 'callback_data' => 'page_1']]]);
        foreach ($users as $u) {
            $r = sendMsg((int) $u['telegram_id'], "🔥 <b>آف امروز باز شد!</b>\nظرفیت محدود است؛ برای مشاهده لیست و ثبت سفارش کلیک کنید:", $broadcastKb);
            if (!empty($r['ok'])) $sent++;
            usleep(40000);
        }
        sendMsg($chatId, "📣 اعلان باز شدن آف برای <b>{$sent}</b> نفر ارسال شد.");
        return true;
    }

    if ($data === 'adm_stats') {
        $settings = getSettings($pdo);
        answerCb($cbId);
        $summary = buildRoundSummaryText($pdo, (int) $settings['current_round_id'], "📊 <b>آمار لحظه‌ای دوره فعلی</b>");
        editMsg($chatId, $msgId, $summary, inlineKb([
            [['text' => '🔄 بروزرسانی آمار', 'callback_data' => 'adm_stats']],
            [['text' => '🔙 بازگشت به پنل', 'callback_data' => 'adm_home']],
        ]));
        return true;
    }

    if (strpos($data, 'adm_prods_') === 0) {
        $page = (int) substr($data, 10);
        answerCb($cbId);
        showAdminProductsPage($pdo, $chatId, $page, $msgId);
        return true;
    }

    if (strpos($data, 'adm_prod_') === 0) {
        $prodId = (int) substr($data, 9);
        answerCb($cbId);
        showAdminSingleProduct($pdo, $chatId, $prodId, $msgId);
        return true;
    }

    if (strpos($data, 'adm_stk_') === 0) {
        $parts = explode('_', $data);
        $prodId = (int) $parts[2];
        $delta = $parts[3];

        if ($delta === 'zero') {
            $pdo->prepare("UPDATE products SET stock = 0 WHERE id = ?")->execute([$prodId]);
        } else {
            $d = (int) $delta;
            $pdo->prepare("UPDATE products SET stock = GREATEST(0, stock + ?) WHERE id = ?")->execute([$d, $prodId]);
        }
        answerCb($cbId, 'موجودی بروزرسانی شد.');
        showAdminSingleProduct($pdo, $chatId, $prodId, $msgId);
        return true;
    }

    if (strpos($data, 'adm_toggle_') === 0) {
        $prodId = (int) substr($data, 11);
        $pdo->prepare("UPDATE products SET is_active = IF(is_active = 1, 0, 1) WHERE id = ?")->execute([$prodId]);
        answerCb($cbId, 'وضعیت نمایش تغییر کرد.');
        showAdminSingleProduct($pdo, $chatId, $prodId, $msgId);
        return true;
    }

    if (strpos($data, 'adm_price_') === 0) {
        $prodId = (int) substr($data, 10);
        setUserState($pdo, $userId, 'adm_edit_price', ['product_id' => $prodId]);
        answerCb($cbId);
        editMsg($chatId, $msgId, "💰 قیمت جدید محصول را به <b>تومان</b> (فقط عدد) بفرستید:", inlineKb([
            [['text' => '❌ انصراف', 'callback_data' => 'adm_home']]
        ]));
        return true;
    }

    if (strpos($data, 'adm_del_ask_') === 0) {
        $prodId = (int) substr($data, 12);
        $stmt = $pdo->prepare("SELECT name FROM products WHERE id = ?");
        $stmt->execute([$prodId]);
        $prodName = $stmt->fetchColumn();

        if ($prodName === false) {
            answerCb($cbId, 'محصول پیدا نشد یا قبلاً حذف شده است.', true);
            showAdminProductsPage($pdo, $chatId, 1, $msgId);
            return true;
        }

        $activeOrders = $pdo->prepare("SELECT COUNT(*) FROM orders WHERE product_id = ? AND status = 'confirmed'");
        $activeOrders->execute([$prodId]);
        $pendingCnt = (int) $activeOrders->fetchColumn();

        $warnText = $pendingCnt > 0
            ? "\n⚠️ توجه: این محصول <b>{$pendingCnt}</b> سفارش در انتظار تحویل دارد (سوابق سفارش‌ها در آمار حفظ می‌شوند)."
            : "";

        answerCb($cbId);
        editMsg($chatId, $msgId, "🗑 آیا از حذف کامل محصول «<b>" . h((string) $prodName) . "</b>» مطمئن هستید؟{$warnText}\n\n<i>(اگر فقط می‌خواهید موقتاً نمایش داده نشود، از گزینه «مخفی کردن» استفاده کنید.)</i>", inlineKb([
            [
                ['text' => '🗑 بله، حذف شود', 'callback_data' => "adm_del_yes_{$prodId}"],
                ['text' => '🔙 انصراف',       'callback_data' => "adm_prod_{$prodId}"],
            ]
        ]));
        return true;
    }

    if (strpos($data, 'adm_del_yes_') === 0) {
        $prodId = (int) substr($data, 12);
        $pdo->prepare("DELETE FROM products WHERE id = ?")->execute([$prodId]);
        answerCb($cbId, '🗑 محصول با موفقیت حذف شد.');
        showAdminProductsPage($pdo, $chatId, 1, $msgId);
        return true;
    }

    if ($data === 'adm_add_prod') {
        setUserState($pdo, $userId, 'adm_prod_name', []);
        answerCb($cbId);
        editMsg($chatId, $msgId, "➕ <b>افزودن محصول جدید (مرحله ۱ از ۴)</b>\n\nنام کوتاه محصول را وارد کنید (مناسب دکمه‌های ۲ ستونه، مثلاً: جزوه ریاضی ۲):", inlineKb([
            [['text' => '❌ انصراف', 'callback_data' => 'adm_home']]
        ]));
        return true;
    }

    if ($data === 'adm_track') {
        setUserState($pdo, $userId, 'adm_track_code', null);
        answerCb($cbId);
        editMsg($chatId, $msgId, "🔍 کد تحویل ۵ رقمی دانشجو را وارد کنید (مثلاً <code>48219</code>):", inlineKb([
            [['text' => '❌ انصراف', 'callback_data' => 'adm_home']]
        ]));
        return true;
    }

    if (strpos($data, 'adm_ord_') === 0) {
        $parts = explode('_', $data);
        $action = $parts[2];
        $orderId = (int) $parts[3];
        $map = ['del' => 'delivered', 'ns' => 'no_show', 'can' => 'cancelled'];
        if (isset($map[$action])) {
            $res = updateOrderStatusByAdmin($pdo, $orderId, $map[$action]);
            answerCb($cbId, $res['msg']);
            showTrackedOrderToAdmin($pdo, $chatId, $orderId, $msgId);
        }
        return true;
    }

    if (strpos($data, 'adm_ban_') === 0 || strpos($data, 'adm_unban_') === 0) {
        $isBan = strpos($data, 'adm_ban_') === 0;
        $parts = explode('_', $data);
        $targetId = (int) $parts[2];
        $orderId = isset($parts[3]) ? (int) $parts[3] : 0;

        $pdo->prepare("UPDATE users SET is_banned = ? WHERE telegram_id = ?")->execute([$isBan ? 1 : 0, $targetId]);
        answerCb($cbId, $isBan ? '🚫 کاربر مسدود شد.' : '🔓 مسدودیت کاربر برداشته شد.');

        if ($orderId > 0) {
            showTrackedOrderToAdmin($pdo, $chatId, $orderId, $msgId);
        } else {
            showAdminBadUsers($pdo, $chatId, $msgId);
        }
        return true;
    }

    if ($data === 'adm_badusers') {
        answerCb($cbId);
        showAdminBadUsers($pdo, $chatId, $msgId);
        return true;
    }

    if ($data === 'adm_set_channel') {
        setUserState($pdo, $userId, 'adm_wait_channel', null);
        answerCb($cbId);
        $text = "📢 <b>تنظیم کانال گزارش خصوصی</b>\n\n"
              . "۱. اول ربات را در کانال موردنظر <b>ادمین</b> کنید (دسترسی ارسال و ویرایش پیام).\n"
              . "۲. حالا <b>یک پیام از آن کانال را به اینجا فوروارد کنید</b> (یا آیدی عددی کانال مثل <code>-1001234567890</code> را بفرستید):";
        editMsg($chatId, $msgId, $text, inlineKb([
            [['text' => '❌ انصراف', 'callback_data' => 'adm_home']]
        ]));
        return true;
    }

    return true;
}

function handleAdminStep(PDO $pdo, array $msg, array $user): bool {
    $userId = (int) $msg['from']['id'];
    if (!isAdmin($userId)) {
        return false;
    }

    $chatId = (int) $msg['chat']['id'];
    $step = $user['step'];
    $temp = getTempData($user);
    $text = trim((string) ($msg['text'] ?? ''));

    // ۱. مراحل افزودن محصول
    if ($step === 'adm_prod_name') {
        if ($text === '') return true;
        $temp['name'] = $text;
        setUserState($pdo, $userId, 'adm_prod_price', $temp);
        sendMsg($chatId, "💰 (مرحله ۲ از ۴) <b>قیمت</b> محصول به تومان را فقط به عدد وارد کنید (مثلاً 85000):");
        return true;
    }

    if ($step === 'adm_prod_price') {
        $num = preg_replace('/[^\d]/', '', toEnglishDigits($text));
        if ($num === '' || (int) $num <= 0) {
            sendMsg($chatId, "⚠️ قیمت باید عدد معتبر بزرگ‌تر از صفر باشد:");
            return true;
        }
        $temp['price'] = (int) $num;
        setUserState($pdo, $userId, 'adm_prod_stock', $temp);
        sendMsg($chatId, "📦 (مرحله ۳ از ۴) <b>تعداد موجودی</b> اولیه را وارد کنید:");
        return true;
    }

    if ($step === 'adm_prod_stock') {
        $num = preg_replace('/[^\d]/', '', toEnglishDigits($text));
        if ($num === '') {
            sendMsg($chatId, "⚠️ موجودی باید عدد صحیح باشد:");
            return true;
        }
        $temp['stock'] = (int) $num;
        setUserState($pdo, $userId, 'adm_prod_max', $temp);
        sendMsg($chatId, "👤 (مرحله ۴ از ۴) <b>سقف خرید هر دانشجو</b> در هر دوره آف چند عدد باشد؟ (معمولاً 1 یا 2):");
        return true;
    }

    if ($step === 'adm_prod_max') {
        $num = (int) preg_replace('/[^\d]/', '', toEnglishDigits($text));
        if ($num < 1 || $num > 50) {
            sendMsg($chatId, "⚠️ لطفاً عددی بین ۱ تا ۵۰ وارد کنید:");
            return true;
        }
        $pdo->prepare("INSERT INTO products (name, price, stock, max_per_user) VALUES (?, ?, ?, ?)")
            ->execute([$temp['name'], $temp['price'], $temp['stock'], $num]);
        setUserState($pdo, $userId, 'idle', null);

        sendMsg($chatId, "✅ محصول «<b>" . h($temp['name']) . "</b>» با قیمت <code>" . number_format($temp['price']) . "</code> تومان و موجودی <code>{$temp['stock']}</code> اضافه شد.");
        showAdminDashboard($pdo, $chatId);
        return true;
    }

    // ۲. ویرایش قیمت محصول
    if ($step === 'adm_edit_price') {
        $num = preg_replace('/[^\d]/', '', toEnglishDigits($text));
        if ($num === '' || (int) $num <= 0) {
            sendMsg($chatId, "⚠️ قیمت معتبر وارد کنید:");
            return true;
        }
        $prodId = (int) ($temp['product_id'] ?? 0);
        $pdo->prepare("UPDATE products SET price = ? WHERE id = ?")->execute([(int) $num, $prodId]);
        setUserState($pdo, $userId, 'idle', null);
        sendMsg($chatId, "✅ قیمت محصول با موفقیت بروزرسانی شد.");
        showAdminDashboard($pdo, $chatId);
        return true;
    }

    // ۳. پیگیری کد تحویل ۵ رقمی
    if ($step === 'adm_track_code') {
        $code = (int) preg_replace('/[^\d]/', '', toEnglishDigits($text));
        setUserState($pdo, $userId, 'idle', null);

        $stmt = $pdo->prepare("SELECT id FROM orders WHERE delivery_code = ? LIMIT 1");
        $stmt->execute([$code]);
        $orderId = (int) $stmt->fetchColumn();

        if ($orderId <= 0) {
            sendMsg($chatId, "❌ سفارشی با کد <code>{$code}</code> پیدا نشد.", inlineKb([
                [['text' => '🔙 بازگشت به پنل', 'callback_data' => 'adm_home']]
            ]));
            return true;
        }
        showTrackedOrderToAdmin($pdo, $chatId, $orderId);
        return true;
    }

    // ۴. تنظیم کانال گزارش با فوروارد
    if ($step === 'adm_wait_channel') {
        $channelId = null;

        if (!empty($msg['forward_origin']['chat']['id']) && ($msg['forward_origin']['chat']['type'] ?? '') === 'channel') {
            $channelId = (int) $msg['forward_origin']['chat']['id'];
        } elseif (!empty($msg['forward_from_chat']['id']) && ($msg['forward_from_chat']['type'] ?? '') === 'channel') {
            $channelId = (int) $msg['forward_from_chat']['id'];
        } elseif (preg_match('/^-100\d{6,}$/', toEnglishDigits($text))) {
            $channelId = (int) toEnglishDigits($text);
        }

        if ($channelId === null) {
            sendMsg($chatId, "⚠️ لطفاً حتماً یک پیام از <b>کانال</b> فوروارد کنید (یا آیدی عددی آن را که با <code>-100</code> شروع می‌شود بفرستید).");
            return true;
        }

        $test = sendMsg($channelId, "✅ <b>اتصال موفق!</b> از این پس گزارش سفارش‌های ربات آف در این کانال ثبت می‌شود.");
        if (empty($test['ok'])) {
            sendMsg($chatId, "❌ ربات نتوانست در این کانال پیام بفرستد. مطمئن شوید ربات را با دسترسی <b>ارسال و ویرایش پیام</b> در کانال ادمین کرده‌اید و دوباره پیام فوروارد کنید.");
            return true;
        }

        $pdo->prepare("UPDATE settings SET report_channel_id = ? WHERE id = 1")->execute([$channelId]);
        setUserState($pdo, $userId, 'idle', null);
        sendMsg($chatId, "✅ کانال گزارش با آیدی <code>{$channelId}</code> با موفقیت متصل شد.");
        showAdminDashboard($pdo, $chatId);
        return true;
    }

    return false;
}
