# -*- coding: utf-8 -*-
"""
هندلرهای پنل ادمین
"""

from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import ContextTypes

import database as db
import keyboards as kb
from config import ADMIN_IDS

STATUS_LABELS = {
    "pending": "⏳ در انتظار بررسی",
    "done": "✅ انجام شد",
    "rejected": "❌ رد شده",
}


def is_admin(user_id: int, context=None) -> bool:
    if user_id in ADMIN_IDS:
        return True
    if context and hasattr(context, "application"):
        return user_id == context.application.bot_data.get("reseller_admin_id")
    return False


def clear_state(context: ContextTypes.DEFAULT_TYPE):
    context.user_data.pop("state", None)
    context.user_data.pop("temp", None)


# ---------------- ورود به پنل ----------------

async def panel_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if not is_admin(update.effective_user.id, context):
        return
    clear_state(context)
    await update.message.reply_text("🔧 پنل مدیریت بات", reply_markup=kb.admin_menu())


async def panel_text_trigger(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if not is_admin(update.effective_user.id, context):
        return
    clear_state(context)
    await update.message.reply_text("🔧 پنل مدیریت بات", reply_markup=kb.admin_menu())


# ---------------- روتر کال‌بک‌های ادمین ----------------

async def handle_admin_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    user_id = update.effective_user.id

    if not is_admin(user_id, context):
        await query.answer("⛔️ شما به این بخش دسترسی ندارید.", show_alert=True)
        return

    await query.answer()
    data = query.data
    parts = data.split(":")

    if data == "admin:back":
        clear_state(context)
        await query.edit_message_text("🔧 پنل مدیریت بات", reply_markup=kb.admin_menu())
        return

    if data == "admin:orders":
        await list_pending_orders(query, context)
    elif data == "admin:deposits":
        await list_pending_deposits(query, context)
    elif data == "admin:kyc_requests":
        await list_pending_kyc(query, context)
    elif data == "admin:users":
        await ask_user_search(query, context)
    elif data == "admin:products":
        await query.edit_message_text("🛒 کدام دسته از خدمات رو می‌خوای مدیریت کنی؟", reply_markup=kb.admin_products_categories_kb())
    elif data.startswith("admin:products_cat:"):
        category = parts[2]
        await list_products_admin(query, context, category)
    elif data == "admin:stats":
        await show_stats(query, context)
    elif data == "admin:broadcast":
        await ask_broadcast(query, context)
    elif data == "admin:settings":
        await query.edit_message_text("⚙️ تنظیمات بات:", reply_markup=kb.settings_menu_kb())

    elif data == "admin:tools":
        await query.edit_message_text("🛠 ابزارهای پیشرفته:", reply_markup=kb.advanced_tools_kb())
    elif data == "admin:discounts":
        await list_discount_codes_admin(query, context)
    elif data == "admin:discount_add":
        context.user_data["state"] = "awaiting_discount_code_create"
        await query.edit_message_text(
            "➕ برای ساختن کد تخفیف، اطلاعات رو به این فرمت ارسال کن:\n\n"
            "کد,نوع,مقدار,حداکثر_استفاده,تاریخ_انقضا\n\n"
            "نوع: percent (درصد) یا fixed (مقدار ثابت تومان)\n"
            "مثال ۱۰٪، ۵ بار، بدون انقضا:  SALE10,percent,10,5,\n"
            "مثال ۵۰۰۰ تومان، بی‌نهایت:  VIP5K,fixed,5000,,",
            reply_markup=kb.admin_back(),
        )
    elif data.startswith("admin:discount_toggle:"):
        db.toggle_discount_code(parts[2])
        await list_discount_codes_admin(query, context)
    elif data.startswith("admin:discount_del:"):
        db.delete_discount_code(parts[2])
        await list_discount_codes_admin(query, context)
    elif data == "admin:staff":
        await list_staff_admin(query, context)
    elif data == "admin:staff_add":
        context.user_data["state"] = "awaiting_staff_add"
        await query.edit_message_text(
            "👮 اطلاعات ادمین جدید رو به این فرمت ارسال کن:\n"
            "آیدی_عددی,نقش\n"
            "نقش‌ها: full | orders | products\n"
            "مثال: 123456789,orders",
            reply_markup=kb.admin_back(),
        )
    elif data.startswith("admin:staff_del:"):
        db.remove_staff(int(parts[2]))
        await list_staff_admin(query, context)
    elif data == "admin:resellers":
        await list_resellers_admin(query, context)
    elif data.startswith("admin:reseller_toggle:"):
        uid = int(parts[2])
        r = db.get_reseller(uid)
        if r:
            db.set_reseller_active(uid, not r["is_active"])
        await list_resellers_admin(query, context)
    elif data.startswith("admin:reseller_del:"):
        db.delete_reseller(int(parts[2]))
        await list_resellers_admin(query, context)
    elif data.startswith("admin:reseller_detail:"):
        await show_reseller_detail(query, context, int(parts[2]))
    elif data.startswith("admin:reseller_change_admin:"):
        context.user_data["state"] = "awaiting_reseller_new_admin"
        context.user_data["temp"]  = {"reseller_id": int(parts[2])}
        await query.edit_message_text("آیدی عددی ادمین جدید را وارد کنید:", reply_markup=kb.admin_back())
    elif data == "admin:category_toggles":
        await show_category_toggles(query, context)
    elif data.startswith("admin:cat_toggle:"):
        db.toggle_category(parts[2])
        await show_category_toggles(query, context)
    elif data == "admin:export_excel":
        await export_excel(query, context)
    elif data == "admin:backup_now":
        await backup_db(query, context)
    elif data == "admin:referral_settings":
        await show_referral_settings(query, context)
    elif data == "admin:set_referral_type_percent":
        db.set_setting("referral_type", "percent")
        await show_referral_settings(query, context)
    elif data == "admin:set_referral_type_fixed":
        db.set_setting("referral_type", "fixed")
        await show_referral_settings(query, context)
    elif data == "admin:set_referral_value":
        context.user_data["state"] = "awaiting_referral_value"
        rtype = db.get_setting("referral_type")
        label = "درصد (عدد ۱ تا ۱۰۰)" if rtype == "percent" else "مقدار ثابت (تومان)"
        await query.edit_message_text(f"مقدار پاداش زیرمجموعه ({label}) رو وارد کن:", reply_markup=kb.admin_back())
    elif data == "admin:set_admin_group":
        context.user_data["state"] = "awaiting_admin_group_id"
        cur = db.get_setting("admin_group_id") or "تنظیم نشده"
        await query.edit_message_text(
            f"آیدی عددی گروه خصوصی ادمین‌ها رو بفرست (با -100 شروع می‌شود).\nفعلی: {cur}",
            reply_markup=kb.admin_back(),
        )
    elif data == "admin:set_usdt_rate":
        context.user_data["state"] = "awaiting_usdt_rate"
        cur = db.get_setting("usdt_rate") or "0"
        await query.edit_message_text(
            f"نرخ فعلی تتر/دلار: {cur} تومان\nنرخ جدید رو فقط به‌صورت عدد وارد کن (مثلاً 68000):",
            reply_markup=kb.admin_back(),
        )
    elif data == "admin:set_gram_profit":
        context.user_data["state"] = "awaiting_gram_profit"
        cur = db.get_setting("gram_profit_percent") or "10"
        await query.edit_message_text(
            f"سود گرام فعلی: {cur}٪\nدرصد سود جدید رو وارد کن:",
            reply_markup=kb.admin_back(),
        )
    elif data == "admin:set_gram_min":
        context.user_data["state"] = "awaiting_gram_min"
        cur = db.get_setting("gram_min_order") or "0.1"
        await query.edit_message_text(
            f"حداقل سفارش گرام فعلی: {cur}\nمقدار جدید رو وارد کن (مثال: 0.5):",
            reply_markup=kb.admin_back(),
        )
    elif data == "admin:set_gram_desc":
        context.user_data["state"] = "awaiting_gram_desc"
        await query.edit_message_text(
            "متن توضیحی صفحه خرید گرام رو بنویس:",
            reply_markup=kb.admin_back(),
        )
    elif data == "admin:set_star_price":
        context.user_data["state"] = "awaiting_star_price"
        cur = db.get_setting("stars_price_per_star") or "0"
        await query.edit_message_text(
            f"قیمت هر استارز فعلی: {cur} تومان\nقیمت جدید هر استارز رو وارد کن (۰ = محاسبه از پکیج‌ها):",
            reply_markup=kb.admin_back(),
        )
    elif data == "admin:set_support_cooldown":
        context.user_data["state"] = "awaiting_support_cooldown"
        cur = db.get_setting("support_cooldown_minutes") or "10"
        await query.edit_message_text(
            f"فاصله زمانی پیام پشتیبانی فعلی: {cur} دقیقه\nمقدار جدید رو (به دقیقه) وارد کن (۰ = بدون محدودیت):",
            reply_markup=kb.admin_back(),
        )
    elif data == "admin:set_abandoned_minutes":
        context.user_data["state"] = "awaiting_abandoned_minutes"
        cur = db.get_setting("abandoned_reminder_minutes") or "60"
        await query.edit_message_text(
            f"زمان یادآوری سفارش نیمه‌کاره فعلی: {cur} دقیقه\nمقدار جدید رو (به دقیقه) وارد کن:",
            reply_markup=kb.admin_back(),
        )
    elif data == "admin:set_backup_interval":
        context.user_data["state"] = "awaiting_backup_interval"
        cur = db.get_setting("backup_interval_hours") or "24"
        await query.edit_message_text(
            f"فاصله بکاپ خودکار فعلی: {cur} ساعت\nمقدار جدید رو (به ساعت) وارد کن:",
            reply_markup=kb.admin_back(),
        )
    elif data == "admin:toggle_reseller":
        cur = db.get_setting("reseller_enabled")
        db.set_setting("reseller_enabled", "0" if cur == "1" else "1")
        await query.edit_message_text("⚙️ تنظیمات بات:", reply_markup=kb.settings_menu_kb())
    elif data == "admin:set_reseller_fee":
        context.user_data["state"] = "awaiting_reseller_fee"
        cur = db.get_setting("reseller_fee") or "0"
        await query.edit_message_text(
            f"هزینه فعال‌سازی نمایندگی فعلی: {int(cur):,} تومان\nمقدار جدید رو وارد کن (۰ = رایگان):",
            reply_markup=kb.admin_back(),
        )

    elif data.startswith("admin:product_add:"):
        category = parts[2]
        context.user_data["state"] = "awaiting_product_add"
        context.user_data["temp"] = {"category": category}
        label = db.CATEGORY_LABELS.get(category, category)
        await query.edit_message_text(
            f"➕ افزودن محصول جدید در دسته «{label}»\n\n"
            "اطلاعات رو به این فرمت ارسال کن: عنوان محصول,قیمت تومان\n"
            "مثال: 100 استارز,55000\n"
            "مثال: پریمیوم سه ماهه,250000",
            reply_markup=kb.admin_back(),
        )
    elif data.startswith("admin:product_toggle:"):
        product_id = int(parts[2])
        product = db.get_product(product_id)
        db.toggle_product(product_id)
        if product:
            await list_products_admin(query, context, product["category"])
    elif data.startswith("admin:product_del:"):
        product_id = int(parts[2])
        product = db.get_product(product_id)
        db.delete_product(product_id)
        if product:
            await list_products_admin(query, context, product["category"])

    elif data.startswith("admin:order_done:"):
        order_id = int(parts[2])
        await finish_order(query, context, order_id, "done")
    elif data.startswith("admin:order_reject:"):
        order_id = int(parts[2])
        context.user_data["state"] = "awaiting_reject_reason"
        context.user_data["temp"]  = {"order_id": order_id}
        await query.edit_message_text(
            f"❌ رد سفارش #{order_id}\n\nدلیل رد سفارش را بنویسید (برای مشتری ارسال می‌شود):\n(یا برای رد بدون دلیل «-» ارسال کنید)",
            reply_markup=kb.admin_back(),
        )

    elif data.startswith("admin:deposit_ok:"):
        deposit_id = int(parts[2])
        await finish_deposit(query, context, deposit_id, True)
    elif data.startswith("admin:deposit_no:"):
        deposit_id = int(parts[2])
        await finish_deposit(query, context, deposit_id, False)
    elif data.startswith("admin:deposit_manual:"):
        deposit_id = int(parts[2])
        context.user_data["state"] = "awaiting_manual_deposit_amount"
        context.user_data["temp"] = {"deposit_id": deposit_id}
        await context.bot.send_message(
            query.from_user.id,
            f"مقدار موجودی‌ای که می‌خوای برای این کاربر تایید و اضافه کنی رو ارسال کن (فقط عدد، تومان):",
            reply_markup=kb.admin_back(),
        )

    elif data.startswith("admin:kyc_ok:"):
        request_id = int(parts[2])
        await finish_kyc(query, context, request_id, True)
    elif data.startswith("admin:kyc_no:"):
        request_id = int(parts[2])
        await finish_kyc(query, context, request_id, False)

    elif data.startswith("admin:balance_add:"):
        target_id = int(parts[2])
        context.user_data["state"] = "awaiting_balance_value"
        context.user_data["temp"] = {"target_id": target_id, "direction": 1}
        await query.edit_message_text(
            f"مبلغی که می‌خوای به موجودی کاربر {target_id} اضافه کنی رو وارد کن (فقط عدد، تومان):",
            reply_markup=kb.admin_back(),
        )
    elif data.startswith("admin:balance_sub:"):
        target_id = int(parts[2])
        context.user_data["state"] = "awaiting_balance_value"
        context.user_data["temp"] = {"target_id": target_id, "direction": -1}
        await query.edit_message_text(
            f"مبلغی که می‌خوای از موجودی کاربر {target_id} کم کنی رو وارد کن (فقط عدد، تومان):",
            reply_markup=kb.admin_back(),
        )
    elif data.startswith("admin:block_toggle:"):
        target_id = int(parts[2])
        u = db.get_user(target_id)
        if u:
            db.set_blocked(target_id, not u["is_blocked"])
            u = db.get_user(target_id)
            await show_user_detail(query, u)

    elif data.startswith("admin:balance_zero:"):
        target_id = int(parts[2])
        u = db.get_user(target_id)
        if u and u["balance"] > 0:
            db.update_balance(target_id, -u["balance"])
        u = db.get_user(target_id)
        await show_user_detail(query, u)

    elif data.startswith("admin:user_orders:"):
        target_id = int(parts[2])
        orders = db.get_user_orders(target_id, limit=8)
        if not orders:
            await query.answer("هیچ سفارشی ندارد.", show_alert=True)
        else:
            lines = [f"📦 آخرین سفارشات {target_id}:\n"]
            for o in orders:
                lines.append(f"#{o['id']} | {o['title']} | {o['price']:,}T | {STATUS_LABELS.get(o['status'], o['status'])}")
            await context.bot.send_message(query.from_user.id, "\n".join(lines))

    elif data.startswith("admin:user_deposits:"):
        target_id = int(parts[2])
        deps = db.get_user_deposits(target_id, limit=8)
        if not deps:
            await query.answer("هیچ واریزی ندارد.", show_alert=True)
        else:
            lines = [f"🧾 آخرین واریزی‌های {target_id}:\n"]
            for d in deps:
                lines.append(f"#{d['id']} | {d['amount']:,}T | {STATUS_LABELS.get(d['status'], d['status'])}")
            await context.bot.send_message(query.from_user.id, "\n".join(lines))

    elif data.startswith("admin:user_reseller:"):
        target_id = int(parts[2])
        r = db.get_reseller(target_id)
        if r:
            db.delete_reseller(target_id)
            await query.answer("نمایندگی لغو شد.", show_alert=True)
            try:
                from reseller_manager import stop_reseller_bot
                await stop_reseller_bot(target_id)
            except Exception:
                pass
        else:
            await query.answer("کاربر نمایندگی ندارد. برای تبدیل، از طریق ثبت‌نام نماینده اقدام کند.", show_alert=True)
        u = db.get_user(target_id)
        if u:
            await show_user_detail(query, u)
    elif data.startswith("admin:reply_user:"):
        target_id = int(parts[2])
        context.user_data["state"] = "awaiting_reply_to_user"
        context.user_data["temp"] = {"target_id": target_id}
        await query.edit_message_text(
            f"متن پیامی که می‌خوای برای کاربر {target_id} ارسال شود رو بنویس:",
            reply_markup=kb.admin_back(),
        )

    elif data == "admin:set_card_number":
        context.user_data["state"] = "awaiting_card_number"
        await query.edit_message_text("شماره کارت جدید رو ارسال کن:", reply_markup=kb.admin_back())
    elif data == "admin:set_card_holder":
        context.user_data["state"] = "awaiting_card_holder"
        await query.edit_message_text("نام صاحب کارت جدید رو ارسال کن:", reply_markup=kb.admin_back())
    elif data == "admin:set_rules":
        context.user_data["state"] = "awaiting_rules_text"
        await query.edit_message_text("متن جدید قوانین و راهنما رو ارسال کن:", reply_markup=kb.admin_back())
    elif data == "admin:set_support_text":
        context.user_data["state"] = "awaiting_support_text_setting"
        await query.edit_message_text("متن جدید پشتیبانی رو ارسال کن:", reply_markup=kb.admin_back())
    elif data == "admin:set_deposit_warning":
        context.user_data["state"] = "awaiting_deposit_warning_text"
        await query.edit_message_text(
            "متن جدید هشدار/قوانینی که قبل از شارژ موجودی نمایش داده می‌شود رو ارسال کن:",
            reply_markup=kb.admin_back(),
        )
    elif data == "admin:set_welcome":
        context.user_data["state"] = "awaiting_welcome_text"
        await query.edit_message_text("متن جدید خوش‌آمدگویی (پیام /start) رو ارسال کن:", reply_markup=kb.admin_back())
    elif data == "admin:rename_buttons":
        await query.edit_message_text(
            "✏️ روی هر دکمه بزن تا متن جدیدش رو ازت بپرسم:", reply_markup=kb.rename_buttons_kb()
        )
    elif data.startswith("admin:set_btn:"):
        key = parts[2]
        context.user_data["state"] = "awaiting_button_label"
        context.user_data["temp"] = {"key": key}
        await query.edit_message_text(
            f"متن جدید برای این دکمه رو ارسال کن (ایموجی هم می‌تونی بگذاری):\n\nمتن فعلی: {db.get_setting(key)}",
            reply_markup=kb.admin_back(),
        )
    elif data == "admin:set_sales_channel":
        context.user_data["state"] = "awaiting_sales_channel_id"
        current = db.get_setting("sales_channel_id") or "تنظیم نشده"
        await query.edit_message_text(
            "📣 آیدی عددی کانال گزارش فروش رو ارسال کن (با -100 شروع می‌شود) یا یوزرنیم کانال رو با @ بفرست.\n"
            "⚠️ بات باید قبلاً به‌عنوان ادمین با دسترسی ارسال پیام در آن کانال اضافه شده باشد.\n\n"
            f"مقدار فعلی: {current}",
            reply_markup=kb.admin_back(),
        )
    elif data == "admin:toggle_kyc":
        current = db.get_setting("kyc_enabled")
        db.set_setting("kyc_enabled", "0" if current == "1" else "1")
        await query.edit_message_text("⚙️ تنظیمات بات:", reply_markup=kb.settings_menu_kb())


# ---------------- سفارشات ----------------

async def list_pending_orders(query, context):
    orders = db.get_pending_orders()
    if not orders:
        await query.edit_message_text("هیچ سفارش در انتظاری وجود ندارد.", reply_markup=kb.admin_back())
        return

    await query.edit_message_text(f"📦 {len(orders)} سفارش در انتظار بررسی:", reply_markup=kb.admin_back())
    for o in orders:
        text = (
            f"سفارش #{o['id']}\n"
            f"👤 کاربر: {o['user_id']}\n"
            f"{o['title']}\n"
            f"💰 قیمت: {o['price']:,} تومان\n"
            f"📨 گیرنده: {o['recipient_username']}"
        )
        await context.bot.send_message(query.from_user.id, text, reply_markup=kb.order_admin_kb(o["id"]))


async def finish_order(query, context, order_id, status, reason=""):
    order = db.get_order(order_id)
    if not order or order["status"] != "pending":
        try: await query.edit_message_text("این سفارش قبلاً بررسی شده است.")
        except: pass
        return

    db.update_order_status(order_id, status)
    reseller_id = order.get("reseller_id")

    if status == "rejected":
        if reseller_id:
            # برگشت موجودی به نماینده (نه مشتری — نماینده خودش با مشتریش حساب می‌کنه)
            db.update_balance(reseller_id, order["price"])
        else:
            # برگشت موجودی به مشتری بات اصلی
            db.update_balance(order["user_id"], order["price"])

    try: await query.edit_message_text(f"سفارش #{order_id} → {STATUS_LABELS[status]} ✅")
    except: pass

    reason_text = f"\n📝 دلیل: {reason}" if reason and reason != "-" else ""

    # پیام به مشتری
    if status == "rejected":
        user_text = f"❌ سفارش #{order_id} شما رد شد.{reason_text}\n\nمبلغ به کیف پولتان بازگردانده شد."
    else:
        user_text = f"✅ سفارش #{order_id} شما انجام شد. ممنون از خریدتان! ⭐️"

    if reseller_id:
        try:
            from reseller_manager import notify_customer_via_reseller, notify_reseller_admin
            await notify_customer_via_reseller(reseller_id, order["user_id"], user_text)
            # اطلاع‌رسانی به ادمین نماینده از وضعیت سفارش
            reseller_notice = (
                f"{'✅' if status=='done' else '❌'}  سفارش #{order_id} {'انجام شد' if status=='done' else 'رد شد'}.\n"
                f"💰 مبلغ: {order['price']:,} تومان\n"
                f"📨 گیرنده: {order['recipient_username']}"
                + (f"\n📝 دلیل رد: {reason}" if status=="rejected" and reason and reason!="-" else "")
                + ("\n\n💰 مبلغ به موجودی اعتباری شما برگشت داده شد." if status=="rejected" else "")
            )
            await notify_reseller_admin(reseller_id, reseller_notice)
        except Exception:
            pass
    else:
        try: await context.bot.send_message(order["user_id"], user_text)
        except: pass

    if status == "done":
        await send_sales_report(context, order)
        try:
            rating_text = f"⭐ لطفاً به سفارش #{order_id} امتیاز بده:"
            if reseller_id:
                from reseller_manager import notify_customer_via_reseller
                await notify_customer_via_reseller(reseller_id, order["user_id"], rating_text)
            else:
                from keyboards import rating_kb
                await context.bot.send_message(order["user_id"], rating_text, reply_markup=rating_kb(order_id))
        except Exception:
            pass


async def send_sales_report(context, order):
    channel_id = db.get_setting("sales_channel_id")
    if not channel_id:
        return
    template = db.get_setting("sales_report_template")
    try:
        text = template.format(title=order["title"], price=f"{order['price']:,}")
    except Exception:
        text = f"✅ یک سفارش جدید انجام شد!\n{order['title']}\n💰 {order['price']:,} تومان"
    target = channel_id
    if channel_id.lstrip("-").isdigit():
        target = int(channel_id)
    try:
        await context.bot.send_message(target, text)
    except Exception:
        pass


# ---------------- رسیدهای واریزی ----------------

async def list_pending_deposits(query, context):
    deposits = db.get_pending_deposits()
    if not deposits:
        await query.edit_message_text("هیچ رسید در انتظاری وجود ندارد.", reply_markup=kb.admin_back())
        return

    await query.edit_message_text(f"🧾 {len(deposits)} رسید در انتظار بررسی:", reply_markup=kb.admin_back())
    for d in deposits:
        caption = (
            f"رسید #{d['id']}\n"
            f"👤 کاربر: {d['user_id']}\n"
            f"💰 مبلغ اعلامی: {d['amount']:,} تومان"
        )
        try:
            await context.bot.send_photo(
                query.from_user.id, d["receipt_file_id"], caption=caption,
                reply_markup=kb.deposit_admin_kb(d["id"]),
            )
        except Exception:
            await context.bot.send_message(query.from_user.id, caption, reply_markup=kb.deposit_admin_kb(d["id"]))


async def finish_deposit(query, context, deposit_id, approve: bool):
    deposit = db.get_deposit(deposit_id)
    if not deposit or deposit["status"] != "pending":
        if query.message.photo:
            await query.edit_message_caption(caption="این رسید قبلاً بررسی شده است.")
        else:
            await query.edit_message_text("این رسید قبلاً بررسی شده است.")
        return

    if approve:
        db.update_deposit_status(deposit_id, "done")
        db.update_balance(deposit["user_id"], deposit["amount"])
        admin_note = f"رسید #{deposit_id} تایید شد و {deposit['amount']:,} تومان به کیف پول کاربر اضافه شد. ✅"
        user_note = f"✅ رسید واریزی شما تایید شد و {deposit['amount']:,} تومان به کیف پولتان اضافه شد."
        await maybe_require_kyc(context, deposit["user_id"])
    else:
        db.update_deposit_status(deposit_id, "rejected")
        admin_note = f"رسید #{deposit_id} رد شد. ❌"
        user_note = "❌ رسید واریزی شما رد شد. در صورت اشتباه، با پشتیبانی در ارتباط باشید."

    if query.message.photo:
        await query.edit_message_caption(caption=admin_note)
    else:
        await query.edit_message_text(admin_note)

    try:
        await context.bot.send_message(deposit["user_id"], user_note)
    except Exception:
        pass

    if approve:
        await maybe_send_kyc_gate_message(context, deposit["user_id"])


async def maybe_require_kyc(context, user_id):
    if db.get_setting("kyc_enabled") == "1":
        u = db.get_user(user_id)
        if u and not u["kyc_verified"]:
            db.set_kyc_pending(user_id, True)


async def maybe_send_kyc_gate_message(context, user_id):
    u = db.get_user(user_id)
    if u and u["kyc_required_pending"] and not u["kyc_verified"]:
        try:
            await context.bot.send_message(
                user_id,
                "🪪 برای استفاده از بات، لطفاً عکس کارت بانکی‌ای که با آن واریز کردید رو همینجا ارسال کنید "
                "تا توسط ادمین تایید شود.",
            )
        except Exception:
            pass


async def finish_deposit_manual(admin_chat_id, context, deposit_id, amount):
    deposit = db.get_deposit(deposit_id)
    if not deposit or deposit["status"] != "pending":
        await context.bot.send_message(admin_chat_id, "این رسید قبلاً بررسی شده است.")
        return

    db.update_deposit_status(deposit_id, "done")
    db.update_balance(deposit["user_id"], amount)
    await maybe_require_kyc(context, deposit["user_id"])

    await context.bot.send_message(
        admin_chat_id,
        f"✅ رسید #{deposit_id} تایید شد و {amount:,} تومان (مقدار دستی) به کیف پول کاربر اضافه شد.",
    )
    try:
        await context.bot.send_message(
            deposit["user_id"],
            f"✅ رسید واریزی شما تایید شد و {amount:,} تومان به کیف پولتان اضافه شد.",
        )
    except Exception:
        pass
    await maybe_send_kyc_gate_message(context, deposit["user_id"])


async def finish_kyc(query, context, request_id, approve: bool):
    request = db.get_kyc_request(request_id)
    if not request or request["status"] != "pending":
        if query.message.photo:
            await query.edit_message_caption(caption="این درخواست قبلاً بررسی شده است.")
        else:
            await query.edit_message_text("این درخواست قبلاً بررسی شده است.")
        return

    if approve:
        db.update_kyc_request_status(request_id, "approved")
        db.set_kyc_verified(request["user_id"])
        admin_note = f"✅ احراز هویت #{request_id} تایید شد و کاربر از حالت مسدودی خارج شد."
        user_note = "✅ احراز هویت شما تایید شد. حالا می‌توانید دوباره از بات استفاده کنید."
    else:
        db.update_kyc_request_status(request_id, "rejected")
        admin_note = f"❌ احراز هویت #{request_id} رد شد."
        user_note = "❌ احراز هویت شما رد شد. لطفاً عکس واضح‌تری از کارت بانکی خودتان ارسال کنید."

    if query.message.photo:
        await query.edit_message_caption(caption=admin_note)
    else:
        await query.edit_message_text(admin_note)

    try:
        await context.bot.send_message(request["user_id"], user_note)
    except Exception:
        pass


# ---------------- کاربران ----------------

async def ask_user_search(query, context):
    context.user_data["state"] = "awaiting_user_search"
    await query.edit_message_text(
        "👥 آیدی عددی یا یوزرنیم کاربری که می‌خوای جستجو کنی رو ارسال کن:",
        reply_markup=kb.admin_back(),
    )


async def show_user_detail(target_message_or_query, user_row, send_new=False, context=None):
    uid = user_row["user_id"]
    order_count = db.get_user_order_count(uid)
    total_spent = db.get_user_total_spent(uid)
    reseller = db.get_reseller(uid)
    avg_rating, rating_count = db.get_average_rating()
    ref_count = db.get_referral_count(uid)
    reseller_label = f"🏪 نماینده فعال (@{reseller['bot_username']})" if reseller and reseller["is_active"] else ("🏪 نماینده غیرفعال" if reseller else "—")

    text = (
        f"👤 اطلاعات کاربر\n\n"
        f"🆔 آیدی: {uid}\n"
        f"📛 یوزرنیم: @{user_row['username'] or '---'}\n"
        f"💰 موجودی: {user_row['balance']:,} تومان\n"
        f"🛍 تعداد سفارشات: {order_count} بار\n"
        f"💵 مجموع خرید: {total_spent:,} تومان\n"
        f"🎁 زیرمجموعه‌ها: {ref_count} نفر\n"
        f"🎉 درآمد رفرال: {user_row.get('referral_earnings', 0):,} تومان\n"
        f"🏪 نمایندگی: {reseller_label}\n"
        f"🚦 وضعیت: {'مسدود 🔴' if user_row['is_blocked'] else 'فعال 🟢'}\n"
        f"🪪 KYC: {'تایید شده ✅' if user_row.get('kyc_verified') else 'تایید نشده ❌'}\n"
        f"📅 عضویت: {user_row['joined_at']}"
    )
    markup = kb.user_admin_kb(uid, user_row["is_blocked"], is_reseller=bool(reseller))
    if send_new and context:
        await context.bot.send_message(target_message_or_query, text, reply_markup=markup)
    else:
        await target_message_or_query.edit_message_text(text, reply_markup=markup)


# ---------------- احراز هویت ----------------

async def list_pending_kyc(query, context):
    requests = db.get_pending_kyc_requests()
    if not requests:
        await query.edit_message_text("هیچ درخواست احراز هویتی در انتظار نیست.", reply_markup=kb.admin_back())
        return

    await query.edit_message_text(f"🪪 {len(requests)} درخواست احراز هویت در انتظار:", reply_markup=kb.admin_back())
    for r in requests:
        caption = f"درخواست #{r['id']}\n👤 کاربر: {r['user_id']}"
        try:
            await context.bot.send_photo(
                query.from_user.id, r["photo_file_id"], caption=caption,
                reply_markup=kb.kyc_admin_kb(r["id"]),
            )
        except Exception:
            await context.bot.send_message(query.from_user.id, caption, reply_markup=kb.kyc_admin_kb(r["id"]))


# ---------------- محصولات ----------------

async def list_products_admin(query, context, category):
    products = db.get_products(active_only=False, category=category)
    label = db.CATEGORY_LABELS.get(category, category)
    text = f"🛒 لیست محصولات «{label}»:" if products else f"هیچ محصولی در دسته «{label}» ثبت نشده. یکی اضافه کن 👇"
    await query.edit_message_text(text, reply_markup=kb.products_admin_kb(products, category))


# ---------------- آمار ----------------

async def show_category_toggles(query, context):
    cats = {"stars": "⭐ استارز", "premium": "🌟 پریمیوم", "gift": "🎁 گیفت", "gram": "💎 گرام"}
    buttons = []
    for key, label in cats.items():
        enabled = db.is_category_enabled(key)
        status  = "🟢 فعال" if enabled else "🔴 غیرفعال"
        buttons.append([InlineKeyboardButton(f"{label}  —  {status}", callback_data=f"admin:cat_toggle:{key}")])
    buttons.append([InlineKeyboardButton("🔙 بازگشت", callback_data="admin:settings")])
    await query.edit_message_text(
        "🗂 مدیریت دسته‌بندی‌ها\nبرای روشن/خاموش کردن هر دسته روی آن بزنید:",
        reply_markup=InlineKeyboardMarkup(buttons)
    )


async def show_reseller_detail(query, context, reseller_id):
    r = db.get_reseller(reseller_id)
    u = db.get_user(reseller_id)
    if not r:
        await query.edit_message_text("نماینده یافت نشد."); return
    status = "🟢 فعال" if r["is_active"] else "🔴 غیرفعال"
    await query.edit_message_text(
        f"🏪 مدیریت نماینده\n{'─'*28}\n"
        f"🤖 بات: @{r['bot_username']}\n"
        f"👤 صاحب: {reseller_id}\n"
        f"👮 ادمین: {r['admin_id']}\n"
        f"💰 موجودی: {(u['balance'] if u else 0):,} تومان\n"
        f"💸 سود: {r.get('profit_percent', 0)}٪\n"
        f"📦 فروش کل: {r.get('total_sales', 0):,} تومان\n"
        f"🚦 وضعیت: {status}",
        reply_markup=InlineKeyboardMarkup([
            [InlineKeyboardButton("🔄 روشن/خاموش", callback_data=f"admin:reseller_toggle:{reseller_id}"),
             InlineKeyboardButton("🗑 حذف",         callback_data=f"admin:reseller_del:{reseller_id}")],
            [InlineKeyboardButton("👮 تغییر ادمین", callback_data=f"admin:reseller_change_admin:{reseller_id}"),
             InlineKeyboardButton("➕ شارژ اعتبار", callback_data=f"admin:balance_add:{reseller_id}")],
            [InlineKeyboardButton("🔙 بازگشت",      callback_data="admin:resellers")],
        ])
    )


async def show_stats(query, context):
    s = db.get_full_stats()
    avg = f"{s['avg_rating']:.1f}" if s['avg_rating'] else "ندارد"
    top = "\n".join([f"  • {u['username'] or u['user_id']}: {u['balance']:,} تومان" for u in s["top_users"]]) or "  —"
    text = (
        "📊 آمار کامل بات\n\n"
        f"👥 کاربران: {s['total_users']} کل | {s['blocked_users']} مسدود\n"
        f"💰 جمع موجودی کیف‌پول‌ها: {s['total_balance']:,} تومان\n\n"
        f"📦 سفارشات:\n"
        f"  امروز: {s['orders_today']} | این هفته: {s['orders_week']} | این ماه: {s['orders_month']} | کل: {s['orders_total']}\n\n"
        f"💵 درآمد تایید‌شده:\n"
        f"  امروز: {s['revenue_today']:,} | هفته: {s['revenue_week']:,} | ماه: {s['revenue_month']:,} | کل: {s['revenue_total']:,} تومان\n\n"
        f"⏳ در انتظار: {s['pending_orders']} سفارش | {s['pending_deposits']} رسید | {s['pending_kyc']} احراز هویت\n"
        f"⭐ میانگین امتیاز: {avg} (از {s['rating_count']} نظر)\n"
        f"🏪 نمایندگان فعال: {s['active_resellers']}\n\n"
        f"🏆 ثروتمندترین کاربران:\n{top}"
    )
    await query.edit_message_text(text, reply_markup=kb.admin_back())


# ---------------- کدهای تخفیف ----------------

async def list_discount_codes_admin(query, context):
    codes = db.list_discount_codes()
    if not codes:
        markup = InlineKeyboardMarkup([
            [InlineKeyboardButton("➕ افزودن کد تخفیف", callback_data="admin:discount_add")],
            [InlineKeyboardButton("🔙 بازگشت", callback_data="admin:back")],
        ])
        await query.edit_message_text("هیچ کد تخفیفی ثبت نشده.", reply_markup=markup)
        return

    buttons = []
    for c in codes:
        status = "🟢" if c["is_active"] else "🔴"
        vtype = "%" if c["type"] == "percent" else "T"
        uses = f"{c['used_count']}/{c['max_uses']}" if c["max_uses"] else f"{c['used_count']}/∞"
        buttons.append([
            InlineKeyboardButton(
                f"{status} {c['code']} ({c['value']}{vtype}) {uses}",
                callback_data=f"admin:discount_toggle:{c['code']}",
            ),
            InlineKeyboardButton("🗑", callback_data=f"admin:discount_del:{c['code']}"),
        ])
    buttons.append([InlineKeyboardButton("➕ افزودن کد تخفیف", callback_data="admin:discount_add")])
    buttons.append([InlineKeyboardButton("🔙 بازگشت", callback_data="admin:back")])
    await query.edit_message_text("🎟 لیست کدهای تخفیف:", reply_markup=InlineKeyboardMarkup(buttons))


# ---------------- نقش‌های ادمین (Staff) ----------------

ROLE_LABELS = {"full": "دسترسی کامل", "orders": "فقط سفارشات", "products": "فقط محصولات"}


async def list_staff_admin(query, context):
    staff = db.list_staff()
    buttons = []
    for s in staff:
        role_label = ROLE_LABELS.get(s["role"], s["role"])
        buttons.append([
            InlineKeyboardButton(f"👮 {s['user_id']} — {role_label}", callback_data=f"admin:staff_del:{s['user_id']}"),
        ])
    buttons.append([InlineKeyboardButton("➕ افزودن ادمین جدید", callback_data="admin:staff_add")])
    buttons.append([InlineKeyboardButton("🔙 بازگشت", callback_data="admin:tools")])
    msg = "👮 لیست ادمین‌های فعال (روی هر ردیف بزن تا حذف شود):" if staff else "هیچ ادمین اضافه‌ای ثبت نشده."
    await query.edit_message_text(msg, reply_markup=InlineKeyboardMarkup(buttons))


# ---------------- مدیریت نمایندگان ----------------

async def list_resellers_admin(query, context):
    resellers = db.get_all_resellers_with_stats()
    if not resellers:
        await query.edit_message_text("هیچ نماینده‌ای ثبت نشده.", reply_markup=kb.advanced_tools_kb())
        return
    buttons = []
    for r in resellers:
        status = "🟢" if r["is_active"] else "🔴"
        buttons.append([InlineKeyboardButton(
            f"{status} @{r['bot_username']}  |  {r.get('total_sales',0):,}T",
            callback_data=f"admin:reseller_detail:{r['user_id']}"
        )])
    buttons.append([InlineKeyboardButton("🔙 بازگشت", callback_data="admin:tools")])
    await query.edit_message_text("🏪 لیست نمایندگان (کلیک برای مدیریت):", reply_markup=InlineKeyboardMarkup(buttons))


# ---------------- خروجی اکسل ----------------

async def export_excel(query, context):
    import io
    try:
        import openpyxl
        wb = openpyxl.Workbook()
        ws_orders = wb.active
        ws_orders.title = "سفارشات"
        ws_orders.append(["ID", "User", "Title", "Price", "Recipient", "Status", "Date"])
        for o in db.get_user_orders(0, limit=10000):
            ws_orders.append([o["id"], o["user_id"], o["title"], o["price"], o["recipient_username"], o["status"], o["created_at"]])
        ws_users = wb.create_sheet("کاربران")
        ws_users.append(["UserID", "Username", "Balance", "Orders", "Joined"])
        for uid in db.all_user_ids():
            u = db.get_user(uid)
            ws_users.append([u["user_id"], u["username"], u["balance"], db.get_user_order_count(uid), u["joined_at"]])
        buf = io.BytesIO()
        wb.save(buf)
        buf.seek(0)
        await context.bot.send_document(
            query.from_user.id, document=buf, filename="shop_export.xlsx", caption="📊 خروجی اکسل بات"
        )
        await query.answer("✅ فایل اکسل ارسال شد.")
    except ImportError:
        await query.answer("برای خروجی اکسل: pip install openpyxl", show_alert=True)
    except Exception as e:
        await query.answer(f"خطا: {e}", show_alert=True)


# ---------------- بکاپ دیتابیس ----------------

async def backup_db(query, context):
    import shutil, os, io
    from config import DB_PATH
    try:
        backup_path = DB_PATH + ".bak"
        shutil.copy2(DB_PATH, backup_path)
        with open(backup_path, "rb") as f:
            await context.bot.send_document(
                query.from_user.id, document=f, filename="shop_backup.db",
                caption=f"📦 بکاپ دیتابیس — {db.now()}"
            )
        os.remove(backup_path)
        await query.answer("✅ بکاپ ارسال شد.")
    except Exception as e:
        await query.answer(f"خطا: {e}", show_alert=True)


# ---------------- تنظیمات زیرمجموعه‌گیری ----------------

async def show_referral_settings(query, context):
    rtype = db.get_setting("referral_type")
    rvalue = db.get_setting("referral_value")
    label = f"{rvalue}٪" if rtype == "percent" else f"{rvalue} تومان ثابت"
    buttons = [
        [InlineKeyboardButton("📊 درصدی", callback_data="admin:set_referral_type_percent"),
         InlineKeyboardButton("💵 مقدار ثابت", callback_data="admin:set_referral_type_fixed")],
        [InlineKeyboardButton(f"✏️ تغییر مقدار (فعلی: {label})", callback_data="admin:set_referral_value")],
        [InlineKeyboardButton("🔙 بازگشت", callback_data="admin:settings")],
    ]
    await query.edit_message_text(
        f"🔗 تنظیمات زیرمجموعه‌گیری\n\nنوع: {'درصدی' if rtype=='percent' else 'ثابت'}\nمقدار: {label}",
        reply_markup=InlineKeyboardMarkup(buttons),
    )


# ---------------- پیام همگانی ----------------

async def ask_broadcast(query, context):
    context.user_data["state"] = "awaiting_broadcast_message"
    await query.edit_message_text(
        "📢 متن پیامی که می‌خوای برای همه کاربران ارسال شود رو بنویس:",
        reply_markup=kb.admin_back(),
    )


# ---------------- دیسپچر حالت‌های متنی ادمین ----------------
# این تابع از handlers_user.py صدا زده می‌شود

async def handle_admin_text_state(update: Update, context: ContextTypes.DEFAULT_TYPE, state: str, text: str) -> bool:
    user_id = update.effective_user.id
    if not is_admin(user_id):
        return False

    if state == "awaiting_reseller_new_admin":
        if not text.strip().isdigit():
            await update.message.reply_text("آیدی عددی معتبر وارد کنید.")
            return True
        reseller_id = context.user_data.get("temp", {}).get("reseller_id")
        db.update_reseller_admin(reseller_id, int(text.strip()))
        clear_state(context)
        await update.message.reply_text(f"✅ ادمین نماینده به {text.strip()} تغییر یافت.", reply_markup=kb.admin_menu())
        return True

    if state == "awaiting_reject_reason":
        order_id = context.user_data.get("temp", {}).get("order_id")
        reason   = text.strip()
        clear_state(context)
        class FakeQuery:
            async def edit_message_text(self, t): pass
            from_user = update.effective_user
        await finish_order(FakeQuery(), context, order_id, "rejected", reason)
        await update.message.reply_text(f"✅ سفارش #{order_id} رد شد و دلیل برای مشتری ارسال شد.", reply_markup=kb.admin_menu())
        return True

    if state == "awaiting_broadcast_message":
        clear_state(context)
        ids = db.all_user_ids()
        sent = 0
        for uid in ids:
            try:
                await context.bot.send_message(uid, f"📢 پیام از طرف مدیریت:\n\n{text}")
                sent += 1
            except Exception:
                pass
        await update.message.reply_text(f"پیام همگانی برای {sent} کاربر ارسال شد. ✅", reply_markup=kb.admin_menu())
        return True

    if state == "awaiting_product_add":
        try:
            title_str, price_str = text.split(",")
            title = title_str.strip()
            price = int(price_str.strip())
            if not title:
                raise ValueError
        except Exception:
            await update.message.reply_text("فرمت اشتباه است. به این شکل ارسال کن: عنوان محصول,قیمت تومان")
            return True
        category = context.user_data.get("temp", {}).get("category", "stars")
        db.add_product(title, price, category=category)
        clear_state(context)
        await update.message.reply_text("✅ محصول جدید اضافه شد.", reply_markup=kb.admin_menu())
        return True

    if state == "awaiting_user_search":
        clear_state(context)
        target = None
        cleaned = text.strip()
        if cleaned.lstrip("-").isdigit():
            target = db.get_user(int(cleaned))
        else:
            target = db.find_user_by_username(cleaned)
        if not target:
            await update.message.reply_text("کاربری پیدا نشد.", reply_markup=kb.admin_menu())
            return True
        await show_user_detail(update.effective_chat.id, target, send_new=True, context=context)
        return True

    if state == "awaiting_balance_value":
        if not text.isdigit() or int(text) <= 0:
            await update.message.reply_text("لطفاً فقط یک عدد معتبر و بزرگ‌تر از صفر ارسال کن.")
            return True
        amount = int(text)
        temp = context.user_data.get("temp", {})
        target_id = temp.get("target_id")
        direction = temp.get("direction", 1)
        db.update_balance(target_id, amount * direction)
        clear_state(context)
        u = db.get_user(target_id)
        await update.message.reply_text("✅ موجودی کاربر به‌روزرسانی شد.", reply_markup=kb.admin_menu())
        try:
            note = "افزایش" if direction > 0 else "کاهش"
            await context.bot.send_message(
                target_id, f"💰 موجودی کیف پول شما توسط مدیریت {note} یافت. موجودی فعلی: {u['balance']:,} تومان"
            )
        except Exception:
            pass
        return True

    if state == "awaiting_card_number":
        db.set_setting("card_number", text)
        clear_state(context)
        await update.message.reply_text("✅ شماره کارت به‌روزرسانی شد.", reply_markup=kb.admin_menu())
        return True

    if state == "awaiting_card_holder":
        db.set_setting("card_holder", text)
        clear_state(context)
        await update.message.reply_text("✅ نام صاحب کارت به‌روزرسانی شد.", reply_markup=kb.admin_menu())
        return True

    if state == "awaiting_rules_text":
        db.set_setting("rules_text", text)
        clear_state(context)
        await update.message.reply_text("✅ متن قوانین به‌روزرسانی شد.", reply_markup=kb.admin_menu())
        return True

    if state == "awaiting_support_text_setting":
        db.set_setting("support_text", text)
        clear_state(context)
        await update.message.reply_text("✅ متن پشتیبانی به‌روزرسانی شد.", reply_markup=kb.admin_menu())
        return True

    if state == "awaiting_deposit_warning_text":
        db.set_setting("deposit_warning_text", text)
        clear_state(context)
        await update.message.reply_text("✅ متن هشدار شارژ به‌روزرسانی شد.", reply_markup=kb.admin_menu())
        return True

    if state == "awaiting_manual_deposit_amount":
        if not text.isdigit() or int(text) <= 0:
            await update.message.reply_text("لطفاً فقط یک عدد معتبر و بزرگ‌تر از صفر ارسال کن.")
            return True
        amount = int(text)
        deposit_id = context.user_data.get("temp", {}).get("deposit_id")
        clear_state(context)
        await finish_deposit_manual(update.effective_chat.id, context, deposit_id, amount)
        return True

    if state == "awaiting_welcome_text":
        db.set_setting("welcome_text", text)
        clear_state(context)
        await update.message.reply_text("✅ متن خوش‌آمدگویی به‌روزرسانی شد.", reply_markup=kb.admin_menu())
        return True

    if state == "awaiting_button_label":
        key = context.user_data.get("temp", {}).get("key")
        if key:
            db.set_setting(key, text)
        clear_state(context)
        await update.message.reply_text("✅ متن دکمه به‌روزرسانی شد.", reply_markup=kb.admin_menu())
        return True

    if state == "awaiting_sales_channel_id":
        db.set_setting("sales_channel_id", text.strip())
        clear_state(context)
        await update.message.reply_text(
            "✅ کانال گزارش فروش ثبت شد. حتماً بات رو به‌عنوان ادمین با دسترسی ارسال پیام به آن کانال اضافه کن.",
            reply_markup=kb.admin_menu(),
        )
        return True

    if state == "awaiting_reply_to_user":
        temp = context.user_data.get("temp", {})
        target_id = temp.get("target_id")
        clear_state(context)
        try:
            await context.bot.send_message(target_id, f"☎️ پیام از طرف پشتیبانی:\n\n{text}")
            await update.message.reply_text("✅ پیام ارسال شد.", reply_markup=kb.admin_menu())
        except Exception:
            await update.message.reply_text("ارسال پیام ناموفق بود (شاید کاربر بات را بلاک کرده).", reply_markup=kb.admin_menu())
        return True

    if state == "awaiting_discount_code_create":
        parts = [p.strip() for p in text.split(",")]
        if len(parts) < 3:
            await update.message.reply_text("فرمت اشتباه. مثال: SALE10,percent,10,5,")
            return True
        code = parts[0].upper()
        dtype = parts[1] if parts[1] in ("percent", "fixed") else "percent"
        try:
            value = int(parts[2])
        except ValueError:
            await update.message.reply_text("مقدار باید عدد صحیح باشد.")
            return True
        max_uses = int(parts[3]) if len(parts) > 3 and parts[3] else None
        expires_at = parts[4] if len(parts) > 4 and parts[4] else None
        db.create_discount_code(code, dtype, value, max_uses, expires_at)
        clear_state(context)
        await update.message.reply_text(f"✅ کد تخفیف «{code}» ساخته شد.", reply_markup=kb.admin_menu())
        return True

    if state == "awaiting_staff_add":
        parts = [p.strip() for p in text.split(",")]
        if len(parts) != 2 or not parts[0].isdigit() or parts[1] not in db.STAFF_ROLES:
            await update.message.reply_text("فرمت اشتباه. مثال: 123456789,orders")
            return True
        db.add_staff(int(parts[0]), parts[1])
        clear_state(context)
        await update.message.reply_text("✅ ادمین جدید اضافه شد.", reply_markup=kb.admin_menu())
        return True

    if state == "awaiting_referral_value":
        if not text.strip().replace(".", "").isdigit():
            await update.message.reply_text("لطفاً فقط یک عدد وارد کن.")
            return True
        db.set_setting("referral_value", text.strip())
        clear_state(context)
        await update.message.reply_text("✅ مقدار پاداش زیرمجموعه به‌روزرسانی شد.", reply_markup=kb.admin_menu())
        return True

    if state == "awaiting_admin_group_id":
        db.set_setting("admin_group_id", text.strip())
        clear_state(context)
        await update.message.reply_text("✅ گروه ادمین ذخیره شد.", reply_markup=kb.admin_menu())
        return True

    if state == "awaiting_usdt_rate":
        if not text.strip().replace(".", "").isdigit():
            await update.message.reply_text("لطفاً فقط یک عدد وارد کن.")
            return True
        db.set_setting("usdt_rate", text.strip())
        clear_state(context)
        await update.message.reply_text(f"✅ نرخ دلار به تومان {text.strip()} تومان ذخیره شد.", reply_markup=kb.admin_menu())
        return True

    if state == "awaiting_gram_profit":
        if not text.strip().replace(".", "").isdigit():
            await update.message.reply_text("لطفاً فقط یک عدد وارد کن.")
            return True
        db.set_setting("gram_profit_percent", text.strip())
        clear_state(context)
        await update.message.reply_text(f"✅ سود گرام {text.strip()}٪ ذخیره شد.", reply_markup=kb.admin_menu())
        return True

    if state == "awaiting_gram_min":
        if not text.strip().replace(".", "").isdigit():
            await update.message.reply_text("لطفاً فقط یک عدد وارد کن.")
            return True
        db.set_setting("gram_min_order", text.strip())
        clear_state(context)
        await update.message.reply_text(f"✅ حداقل سفارش گرام {text.strip()} ذخیره شد.", reply_markup=kb.admin_menu())
        return True

    if state == "awaiting_gram_desc":
        db.set_setting("gram_description", text)
        clear_state(context)
        await update.message.reply_text("✅ متن توضیحی گرام ذخیره شد.", reply_markup=kb.admin_menu())
        return True

    if state == "awaiting_star_price":
        if not text.strip().replace(".", "").isdigit():
            await update.message.reply_text("لطفاً فقط یک عدد وارد کن.")
            return True
        db.set_setting("stars_price_per_star", text.strip())
        clear_state(context)
        await update.message.reply_text(f"✅ قیمت هر استارز {text.strip()} تومان ذخیره شد.", reply_markup=kb.admin_menu())
        return True

    if state == "awaiting_support_cooldown":
        if not text.strip().isdigit():
            await update.message.reply_text("لطفاً فقط یک عدد وارد کن.")
            return True
        db.set_setting("support_cooldown_minutes", text.strip())
        clear_state(context)
        await update.message.reply_text(f"✅ فاصله زمانی پشتیبانی {text.strip()} دقیقه ذخیره شد.", reply_markup=kb.admin_menu())
        return True

    if state == "awaiting_abandoned_minutes":
        if not text.strip().isdigit():
            await update.message.reply_text("لطفاً فقط یک عدد وارد کن.")
            return True
        db.set_setting("abandoned_reminder_minutes", text.strip())
        clear_state(context)
        await update.message.reply_text(f"✅ زمان یادآوری {text.strip()} دقیقه ذخیره شد.", reply_markup=kb.admin_menu())
        return True

    if state == "awaiting_backup_interval":
        if not text.strip().isdigit():
            await update.message.reply_text("لطفاً فقط یک عدد وارد کن.")
            return True
        db.set_setting("backup_interval_hours", text.strip())
        clear_state(context)
        await update.message.reply_text(f"✅ فاصله بکاپ خودکار {text.strip()} ساعت ذخیره شد.", reply_markup=kb.admin_menu())
        return True

    if state == "awaiting_reseller_fee":
        if not text.strip().isdigit():
            await update.message.reply_text("لطفاً فقط یک عدد وارد کن.")
            return True
        db.set_setting("reseller_fee", text.strip())
        clear_state(context)
        await update.message.reply_text(f"✅ هزینه نمایندگی {int(text.strip()):,} تومان ذخیره شد.", reply_markup=kb.admin_menu())
        return True

    return False
