from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardMarkup
from telegram.ext import ContextTypes
import database as db
from config import ADMIN_IDS
from datetime import datetime, timedelta

def is_admin(uid): return uid in ADMIN_IDS

async def admin_panel(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if not is_admin(update.effective_user.id): return
    s = db.get_stats()
    buttons = [
        [InlineKeyboardButton("📊 آمار", callback_data="adm_stats"), InlineKeyboardButton("📋 سفارش‌ها", callback_data="adm_orders")],
        [InlineKeyboardButton("🔍 در انتظار تأیید", callback_data="adm_pending")],
        [InlineKeyboardButton("💰 قیمت‌ها", callback_data="adm_prices"), InlineKeyboardButton("🎟 کدهای تخفیف", callback_data="adm_discounts")],
        [InlineKeyboardButton("🔥 فلش سیل", callback_data="adm_flashsale"), InlineKeyboardButton("🎫 تیکت‌ها", callback_data="adm_tickets")],
        [InlineKeyboardButton("👥 کاربران", callback_data="adm_users"), InlineKeyboardButton("⛔ بلک‌لیست", callback_data="adm_blacklist")],
        [InlineKeyboardButton("📢 همگانی", callback_data="adm_broadcast"), InlineKeyboardButton("💾 بکاپ", callback_data="adm_backup")],
        [InlineKeyboardButton("🏪 ریسلرها", callback_data="adm_resellers"), InlineKeyboardButton("⚙️ تنظیمات", callback_data="adm_settings")],
    ]
    await update.message.reply_text(
        f"⚙️ پنل مدیریت\n\n📦 در انتظار: {s['pending_orders']} | 💰 امروز: {s['today_revenue']:,} ت",
        reply_markup=InlineKeyboardMarkup(buttons)
    )

async def stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if not is_admin(update.effective_user.id): return
    s = db.get_stats()
    await update.message.reply_text(
        f"📊 آمار کامل:\n\n"
        f"👥 کل کاربران: {s['total_users']}\n"
        f"✅ احراز هویت: {s['verified_users']}\n"
        f"👑 VIP: {s['vip_users']}\n\n"
        f"📦 کل سفارش: {s['total_orders']}\n"
        f"✅ تحویل شده: {s['delivered_orders']}\n"
        f"⏳ در انتظار: {s['pending_orders']}\n\n"
        f"💰 درآمد کل: {s['total_revenue']:,} ت\n"
        f"📅 امروز: {s['today_orders']} سفارش | {s['today_revenue']:,} ت"
    )

async def list_orders(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if not is_admin(update.effective_user.id): return
    orders = db.get_all_orders(15)
    if not orders:
        await update.message.reply_text("📋 سفارشی وجود ندارد.")
        return
    STATUS = {'pending':'⏳','waiting_confirm':'🔍','confirmed':'✅','rejected':'❌','delivered':'📦'}
    text = "📋 آخرین سفارش‌ها:\n\n"
    for o in orders:
        text += f"{STATUS.get(o['status'],'?')} #{o['id']} | {o['service']} {o['duration']} | {o['amount']:,}ت | @{o.get('username') or '?'}\n"
    await update.message.reply_text(text)

async def broadcast_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if not is_admin(update.effective_user.id): return
    context.user_data['broadcast_mode'] = True
    await update.message.reply_text("📢 پیام همگانی را بنویسید:")

async def set_price(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if not is_admin(update.effective_user.id): return
    products = db.get_products()
    buttons = [[InlineKeyboardButton(f"{p['service']} {p['duration']} - {p['price']:,}ت", callback_data=f"editprice_{p['id']}")] for p in products]
    await update.message.reply_text("💰 محصول مورد نظر:", reply_markup=InlineKeyboardMarkup(buttons))

async def add_card(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if not is_admin(update.effective_user.id): return
    await update.message.reply_text("💳 شماره کارت را در config.py ویرایش کنید.")

async def handle_admin_callbacks(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()
    data = query.data
    user = query.from_user
    if not is_admin(user.id): return

    if data == "adm_stats":
        s = db.get_stats()
        await query.edit_message_text(
            f"📊 آمار:\n\n👥 کل: {s['total_users']} | ✅ احراز: {s['verified_users']} | 👑 VIP: {s['vip_users']}\n"
            f"📦 سفارش: {s['total_orders']} | ✅ تحویل: {s['delivered_orders']} | ⏳ انتظار: {s['pending_orders']}\n"
            f"💰 کل: {s['total_revenue']:,} ت\n📅 امروز: {s['today_orders']} سفارش | {s['today_revenue']:,} ت"
        )

    elif data == "adm_orders":
        orders = db.get_all_orders(10)
        STATUS = {'pending':'⏳','waiting_confirm':'🔍','confirmed':'✅','rejected':'❌','delivered':'📦'}
        text = "📋 آخرین سفارش‌ها:\n\n"
        for o in orders:
            text += f"{STATUS.get(o['status'],'?')} #{o['id']} | {o['service']} {o['duration']} | {o['amount']:,}ت\n"
        await query.edit_message_text(text or "سفارشی نیست.")

    elif data == "adm_pending":
        orders = db.get_pending_orders()
        if not orders:
            await query.edit_message_text("✅ سفارش در انتظاری نیست.")
            return
        for o in orders[:5]:
            buttons = InlineKeyboardMarkup([
                [InlineKeyboardButton("✅ تأیید", callback_data=f"approve_{o['id']}"),
                 InlineKeyboardButton("❌ رد", callback_data=f"reject_{o['id']}")]
            ])
            caption = (f"🧾 سفارش #{o['id']}\n👤 {o['full_name']} | @{o.get('username') or '?'}\n"
                      f"📦 {o['service']} {o['duration']}\n💰 {o['amount']:,} ت\n💳 {o.get('payment_method','card')}")
            if o.get('receipt_file_id'):
                await query.message.reply_photo(o['receipt_file_id'], caption=caption, reply_markup=buttons)
            else:
                await query.message.reply_text(caption, reply_markup=buttons)

    elif data == "adm_prices":
        products = db.get_products()
        buttons = [[InlineKeyboardButton(f"{p['service']} {p['duration']} - {p['price']:,}ت", callback_data=f"editprice_{p['id']}")] for p in products]
        await query.edit_message_text("💰 محصول مورد نظر:", reply_markup=InlineKeyboardMarkup(buttons))

    elif data.startswith("editprice_"):
        pid = int(data[10:])
        context.user_data['editing_price_id'] = pid
        product = db.get_product(pid)
        await query.edit_message_text(f"✏️ قیمت جدید برای {product['service']} {product['duration']} (تومان):")

    elif data == "adm_discounts":
        codes = db.get_all_discount_codes()
        text = "🎟 کدهای تخفیف:\n\n"
        for c in codes:
            status = "✅" if c['is_active'] else "❌"
            text += f"{status} {c['code']} | {c['percent']}% | {c['used_count']}/{c['max_uses'] if c['max_uses']!=-1 else '∞'}\n"
        buttons = [[InlineKeyboardButton("➕ کد جدید", callback_data="new_discount")]]
        await query.edit_message_text(text or "کدی وجود ندارد.", reply_markup=InlineKeyboardMarkup(buttons))

    elif data == "new_discount":
        context.user_data['creating_discount'] = 'code'
        await query.edit_message_text("🎟 کد تخفیف را وارد کنید (مثلاً: SALE20):")

    elif data == "adm_flashsale":
        products = db.get_products()
        buttons = [[InlineKeyboardButton(f"{p['service']} {p['duration']}", callback_data=f"flashsale_{p['id']}")] for p in products]
        await query.edit_message_text("🔥 فلش سیل - محصول را انتخاب کنید:", reply_markup=InlineKeyboardMarkup(buttons))

    elif data.startswith("flashsale_"):
        pid = int(data[10:])
        context.user_data['flashsale_pid'] = pid
        context.user_data['flashsale_step'] = 'discount'
        await query.edit_message_text("🔥 درصد تخفیف را وارد کنید (مثلاً: 20):")

    elif data == "adm_tickets":
        tickets = db.get_open_tickets()
        if not tickets:
            await query.edit_message_text("✅ تیکت بازی وجود ندارد.")
            return
        text = f"🎫 {len(tickets)} تیکت باز:\n\n"
        buttons = []
        for tk in tickets[:10]:
            text += f"#{tk['id']} | @{tk.get('username','?')} | {tk['subject'][:25]}\n"
            buttons.append([InlineKeyboardButton(f"↩️ پاسخ #{tk['id']}", callback_data=f"reply_ticket_{tk['id']}")])
        await query.edit_message_text(text, reply_markup=InlineKeyboardMarkup(buttons))

    elif data.startswith("reply_ticket_"):
        tid = int(data[13:])
        context.user_data['replying_ticket'] = tid
        await query.edit_message_text(f"✍️ پاسخ تیکت #{tid}:")

    elif data == "adm_users":
        users = db.get_all_users()
        text = f"👥 کاربران ({len(users)}):\n\n"
        for u in users[:15]:
            vip = "👑" if u['is_vip'] else ""
            text += f"{vip} {u['full_name']} | @{u.get('username') or '?'} | {u['user_id']}\n"
        await query.edit_message_text(text)

    elif data == "adm_blacklist":
        context.user_data['blacklisting'] = True
        await query.edit_message_text("⛔ آیدی عددی کاربر برای بلک‌لیست را وارد کنید:")

    elif data == "adm_broadcast":
        context.user_data['broadcast_mode'] = True
        await query.edit_message_text("📢 پیام همگانی را بنویسید:")

    elif data == "adm_backup":
        import shutil, os
        from datetime import datetime
        backup_name = f"backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}.db"
        shutil.copy('database.db', backup_name)
        try:
            with open(backup_name, 'rb') as f:
                await context.bot.send_document(user.id, document=f, filename=backup_name, caption="💾 بکاپ دیتابیس")
            os.remove(backup_name)
        except Exception as e:
            await query.edit_message_text(f"❌ خطا در بکاپ: {e}")
        await query.edit_message_text("✅ بکاپ ارسال شد.")

    elif data == "adm_resellers":
        context.user_data['adding_reseller'] = 'uid'
        await query.edit_message_text("🏪 آیدی عددی ریسلر جدید را وارد کنید:")

    elif data == "adm_settings":
        ws = db.get_setting('work_hours_start', '9')
        we = db.get_setting('work_hours_end', '23')
        maintenance = db.get_setting('maintenance', '0')
        await query.edit_message_text(
            f"⚙️ تنظیمات:\n\n⏰ ساعت کاری: {ws}:00 تا {we}:00\n🔧 تعمیرات: {'فعال' if maintenance=='1' else 'غیرفعال'}",
            reply_markup=InlineKeyboardMarkup([
                [InlineKeyboardButton("⏰ تغییر ساعت کاری", callback_data="set_workhours")],
                [InlineKeyboardButton("🔧 تعمیرات on/off", callback_data="toggle_maintenance")],
            ])
        )


    elif data == "adm_theme":
        from utils.theme import get_theme_preview, COLOR_SETS, get_color_indicator
        preview = get_theme_preview()
        colors = list(COLOR_SETS.keys())
        btns = [
            [InlineKeyboardButton("🤖 نام ربات", callback_data="edittheme_bot_name"),
             InlineKeyboardButton("📌 نسخه", callback_data="edittheme_bot_version")],
            [InlineKeyboardButton("👋 ایموجی خوش‌آمد", callback_data="edittheme_welcome_emoji")],
        ]
        for c in colors:
            ci = get_color_indicator(c, 0)
            btns.append([InlineKeyboardButton(f"{ci} رنگ اصلی: {c}", callback_data=f"setcolor_main_{c}")])
        btns.append([InlineKeyboardButton("✏️ ویرایش متن دکمه‌ها", callback_data="edittheme_btns")])
        btns.append([InlineKeyboardButton("🔙 بازگشت", callback_data="adm_back")])
        await query.edit_message_text(preview, reply_markup=InlineKeyboardMarkup(btns))

    elif data.startswith("setcolor_main_"):
        color = data[14:]
        db.save_theme("color_main", color)
        from utils.theme import get_color_indicator
        ci = get_color_indicator(color, 0)
        await query.answer(f"✅ رنگ اصلی: {ci}{color}", show_alert=True)

    elif data == "edittheme_btns":
        theme = db.get_theme()
        btns_list = [
            ("btn_buy","خرید"),("btn_orders","سفارش‌ها"),("btn_configs","کانفیگ‌ها"),
            ("btn_wallet","کیف پول"),("btn_support","پشتیبانی"),("btn_referral","رفرال"),
            ("btn_reviews","نظرات"),("btn_payment","پرداخت"),("btn_about","درباره"),
        ]
        btns = [[InlineKeyboardButton(f"✏️ {lbl}: {theme.get(key,key)[:15]}", callback_data=f"edittheme_{key}")] for key,lbl in btns_list]
        btns.append([InlineKeyboardButton("🔙 بازگشت", callback_data="adm_theme")])
        await query.edit_message_text("✏️ دکمه مورد نظر را انتخاب کنید:", reply_markup=InlineKeyboardMarkup(btns))

    elif data.startswith("edittheme_"):
        key = data[10:]
        context.user_data["editing_theme"] = key
        theme = db.get_theme()
        val = theme.get(key, "—")
        msg = f"✏️ مقدار جدید برای *{key}* را بنویسید:\n\nمقدار فعلی: {val}\n\n(ایموجی + متن)"
        await query.edit_message_text(msg, parse_mode="Markdown")

    elif data == "adm_back":
        from handlers.admin_handlers import admin_panel_inline
        await admin_panel_inline(query, context)

    elif data == 'adm_autoprice':
        from utils.price_updater import update_telegram_premium_prices, calculate_auto_prices
        setting = db.get_setting('auto_price_enabled','0')
        result = calculate_auto_prices()
        if result:
            prices, usd_rate = result
            preview = f'💵 نرخ دلار: {usd_rate:,} تومان\n\nپیش‌نمایش قیمت‌های جدید:\n'
            for dur, info in prices.items():
                preview += f'  {dur}: {info["price"]:,} ت\n'
        else:
            preview = '❌ دریافت نرخ ناموفق بود'
        auto_status = '✅ فعال' if setting == '1' else '❌ غیرفعال'
        btns = [
            [InlineKeyboardButton('🔄 بروزرسانی همین الان', callback_data='autoprice_now')],
            [InlineKeyboardButton(f'⚙️ بروزرسانی خودکار: {auto_status}', callback_data='autoprice_toggle')],
            [InlineKeyboardButton('🔙 بازگشت', callback_data='adm_back')],
        ]
        msg = f'💰 *مدیریت قیمت خودکار*\n\n{preview}\n\nقیمت‌ها هر ۶ ساعت بروز میشن.'
        await query.edit_message_text(msg,
            reply_markup=InlineKeyboardMarkup(btns),
            parse_mode='Markdown'
        )

    elif data == 'autoprice_now':
        await query.edit_message_text('⏳ در حال دریافت نرخ و بروزرسانی...')
        from utils.price_updater import update_telegram_premium_prices
        success, result = update_telegram_premium_prices()
        if success:
            text = '✅ *قیمت‌ها بروز شد!*\n\n'
            text += f'💵 نرخ دلار: {result["usd_rate"]:,} تومان\n\n'
            for u in result['updated']:
                diff = u['new_price'] - u['old_price']
                arrow = '📈' if diff>0 else '📉' if diff<0 else '➡️'
                text += f'{arrow} {u["service"]} {u["duration"]}\n'
                text += f'   {u["old_price"]:,} ← {u["new_price"]:,} ت\n\n'
        else:
            text = f'❌ خطا: {result}'
        await query.edit_message_text(
            text,
            reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton('🔙 بازگشت', callback_data='adm_autoprice')]]),
            parse_mode='Markdown'
        )

    elif data == 'autoprice_toggle':
        cur = db.get_setting('auto_price_enabled','0')
        new_val = '0' if cur=='1' else '1'
        db.set_setting('auto_price_enabled', new_val)
        status = '✅ فعال' if new_val=='1' else '❌ غیرفعال'
        await query.answer(f'بروزرسانی خودکار: {status}', show_alert=True)

    elif data == "toggle_maintenance":
        cur = db.get_setting('maintenance', '0')
        new_val = '0' if cur == '1' else '1'
        db.set_setting('maintenance', new_val)
        await query.edit_message_text(f"🔧 حالت تعمیرات: {'فعال' if new_val=='1' else 'غیرفعال'}")

    elif data == "set_workhours":
        context.user_data['setting_workhours'] = True
        await query.edit_message_text("⏰ ساعت شروع و پایان را وارد کنید (مثلاً: 9 23):")

async def admin_panel_inline(query, context):
    """پنل ادمین inline"""
    from handlers.admin_handlers import is_admin
    if not is_admin(query.from_user.id): return
    s = db.get_stats()
    buttons = [
        [InlineKeyboardButton("📊 آمار", callback_data="adm_stats"), InlineKeyboardButton("📋 سفارش‌ها", callback_data="adm_orders")],
        [InlineKeyboardButton("🔍 در انتظار تأیید", callback_data="adm_pending")],
        [InlineKeyboardButton("💰 قیمت‌ها", callback_data="adm_prices"), InlineKeyboardButton("🎟 تخفیف", callback_data="adm_discounts")],
        [InlineKeyboardButton("🔥 فلش سیل", callback_data="adm_flashsale"), InlineKeyboardButton("🎫 تیکت‌ها", callback_data="adm_tickets")],
        [InlineKeyboardButton("👥 کاربران", callback_data="adm_users"), InlineKeyboardButton("⛔ بلک‌لیست", callback_data="adm_blacklist")],
        [InlineKeyboardButton("📢 همگانی", callback_data="adm_broadcast"), InlineKeyboardButton("💾 بکاپ", callback_data="adm_backup")],
        [InlineKeyboardButton("⚙️ کانفیگ‌ها", callback_data="adm_configs"), InlineKeyboardButton("🏪 ریسلرها", callback_data="adm_resellers")],
        [InlineKeyboardButton("🎨 تنظیم تم", callback_data="adm_theme")],
        [InlineKeyboardButton("🔙 بازگشت", callback_data="menu_back")],
    ]
    await query.edit_message_text(
        f"⚙️ *پنل مدیریت*\n\n📦 انتظار: {s['pending_orders']} | 💰 امروز: {s['today_revenue']:,} ت",
        reply_markup=InlineKeyboardMarkup(buttons),
        parse_mode='Markdown'
    )


# ===== مدیریت محصولات از تلگرام =====
async def handle_product_management(query, context):
    """منوی مدیریت محصولات"""
    products = db.get_all_products_admin()
    services = {}
    for p in products:
        services.setdefault(p['service'], []).append(p)

    text = "📦 *مدیریت محصولات*\n\n"
    for svc, prods in services.items():
        active = sum(1 for p in prods if p['is_active'])
        text += f"🗂 *{svc}* ({active}/{len(prods)} فعال)\n"
        for p in prods:
            st = "✅" if p['is_active'] else "❌"
            text += f"  {st} {p['duration']} — {p['price']:,} ت\n"
        text += "\n"

    buttons = [
        [InlineKeyboardButton("➕ افزودن سرویس جدید", callback_data="prod_add_service")],
        [InlineKeyboardButton("➕ افزودن مدت به سرویس موجود", callback_data="prod_add_duration")],
        [InlineKeyboardButton("✏️ ویرایش محصول", callback_data="prod_edit_list")],
        [InlineKeyboardButton("🗑 حذف محصول", callback_data="prod_delete_list")],
        [InlineKeyboardButton("🔛 فعال/غیرفعال", callback_data="prod_toggle_list")],
        [InlineKeyboardButton("🔙 بازگشت", callback_data="adm_back")],
    ]
    await query.edit_message_text(text or "محصولی وجود ندارد.",
                                  reply_markup=InlineKeyboardMarkup(buttons),
                                  parse_mode='Markdown')

async def handle_product_callbacks(update_or_query, context):
    """هندل همه callback های محصول"""
    query = update_or_query
    await query.answer()
    data = query.data
    user = query.from_user
    if not is_admin(user.id): return

    if data == "prod_manage":
        await handle_product_management(query, context)

    elif data == "prod_add_service":
        context.user_data['adding_product'] = {'step': 'service_name', 'mode': 'new_service'}
        await query.edit_message_text(
            "➕ *افزودن سرویس جدید*\n\n"
            "📛 نام سرویس را وارد کنید:\n"
            "(مثلاً: یوتیوب پرمیوم، Disney+، ChatGPT Plus)",
            parse_mode='Markdown'
        )

    elif data == "prod_add_duration":
        products = db.get_all_products_admin()
        services = list({p['service'] for p in products})
        buttons = [[InlineKeyboardButton(s, callback_data=f"prod_addto_{s}")] for s in services]
        buttons.append([InlineKeyboardButton("🔙 بازگشت", callback_data="prod_manage")])
        await query.edit_message_text("📦 سرویس مورد نظر را انتخاب کنید:",
                                      reply_markup=InlineKeyboardMarkup(buttons))

    elif data.startswith("prod_addto_"):
        service = data[11:]
        context.user_data['adding_product'] = {'step': 'duration', 'mode': 'add_duration', 'service': service}
        await query.edit_message_text(
            f"➕ افزودن مدت به *{service}*\n\n"
            "⏱ مدت زمان را وارد کنید:\n"
            "(مثلاً: 1 ماهه / 3 ماهه / 6 ماهه / 1 ساله)",
            parse_mode='Markdown'
        )

    elif data == "prod_edit_list":
        products = db.get_all_products_admin()
        buttons = [[InlineKeyboardButton(
            f"{'✅' if p['is_active'] else '❌'} {p['service']} {p['duration']} — {p['price']:,}ت",
            callback_data=f"prod_edit_{p['id']}"
        )] for p in products]
        buttons.append([InlineKeyboardButton("🔙 بازگشت", callback_data="prod_manage")])
        await query.edit_message_text("✏️ محصول مورد نظر را انتخاب کنید:",
                                      reply_markup=InlineKeyboardMarkup(buttons))

    elif data.startswith("prod_edit_"):
        pid = int(data[10:])
        p = db.get_product(pid)
        context.user_data['editing_product'] = {'id': pid, 'step': 'service', 'data': dict(p)}
        await query.edit_message_text(
            f"✏️ *ویرایش محصول #{pid}*\n\n"
            f"📦 {p['service']} — {p['duration']}\n"
            f"💰 قیمت: {p['price']:,} ت\n\n"
            f"نام سرویس جدید را بنویسید (یا /skip برای بدون تغییر):",
            parse_mode='Markdown'
        )

    elif data == "prod_delete_list":
        products = db.get_all_products_admin()
        buttons = [[InlineKeyboardButton(
            f"🗑 {p['service']} {p['duration']} — {p['price']:,}ت",
            callback_data=f"prod_del_{p['id']}"
        )] for p in products]
        buttons.append([InlineKeyboardButton("🔙 بازگشت", callback_data="prod_manage")])
        await query.edit_message_text("🗑 محصول مورد نظر برای حذف:",
                                      reply_markup=InlineKeyboardMarkup(buttons))

    elif data.startswith("prod_del_"):
        pid = int(data[9:])
        p = db.get_product(pid)
        buttons = InlineKeyboardMarkup([
            [InlineKeyboardButton("⚠️ بله، حذف کن", callback_data=f"prod_delconfirm_{pid}"),
             InlineKeyboardButton("❌ لغو", callback_data="prod_manage")]
        ])
        await query.edit_message_text(
            f"⚠️ آیا مطمئنی؟\n\n🗑 {p['service']} — {p['duration']} — {p['price']:,} ت\n\nحذف می‌شود!",
            reply_markup=buttons
        )

    elif data.startswith("prod_delconfirm_"):
        pid = int(data[16:])
        db.delete_product(pid)
        await query.edit_message_text(f"✅ محصول #{pid} حذف شد.",
                                      reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🔙 بازگشت", callback_data="prod_manage")]]))

    elif data == "prod_toggle_list":
        products = db.get_all_products_admin()
        buttons = [[InlineKeyboardButton(
            f"{'✅ فعال' if p['is_active'] else '❌ غیرفعال'} — {p['service']} {p['duration']}",
            callback_data=f"prod_toggle_{p['id']}"
        )] for p in products]
        buttons.append([InlineKeyboardButton("🔙 بازگشت", callback_data="prod_manage")])
        await query.edit_message_text("🔛 برای تغییر وضعیت کلیک کنید:",
                                      reply_markup=InlineKeyboardMarkup(buttons))

    elif data.startswith("prod_toggle_"):
        pid = int(data[12:])
        db.toggle_product(pid)
        p = db.get_product(pid)
        await query.answer(f"{'✅ فعال' if p['is_active'] else '❌ غیرفعال'} شد!", show_alert=True)
        await handle_product_management(query, context)

async def handle_product_text_input(update, context):
    """هندل ورودی متنی برای افزودن/ویرایش محصول"""
    user = update.effective_user
    if not is_admin(user.id): return False
    text = update.message.text

    # ===== افزودن محصول =====
    state = context.user_data.get('adding_product')
    if state:
        step = state['step']
        mode = state.get('mode', 'new_service')

        if step == 'service_name':
            state['service'] = text
            state['step'] = 'duration'
            await update.message.reply_text(
                f"✅ سرویس: *{text}*\n\n"
                "⏱ مدت زمان را وارد کنید:\n(مثلاً: 1 ماهه / 3 ماهه / 6 ماهه / 1 ساله)",
                parse_mode='Markdown'
            )

        elif step == 'duration':
            state['duration'] = text
            state['step'] = 'price'
            await update.message.reply_text(
                f"✅ مدت: *{text}*\n\n💰 قیمت (تومان) را وارد کنید:",
                parse_mode='Markdown'
            )

        elif step == 'price':
            try:
                state['price'] = int(text.replace(',','').replace(' ',''))
            except:
                await update.message.reply_text("❌ عدد معتبر وارد کنید.")
                return True
            state['step'] = 'bulk_price'
            await update.message.reply_text(
                f"✅ قیمت: *{state['price']:,} ت*\n\n"
                "📦 قیمت عمده (تومان) را وارد کنید:\n(برای یکسان با قیمت معمولی: /skip)",
                parse_mode='Markdown'
            )

        elif step == 'bulk_price':
            if text == '/skip':
                state['bulk_price'] = state['price']
            else:
                try:
                    state['bulk_price'] = int(text.replace(',','').replace(' ',''))
                except:
                    state['bulk_price'] = state['price']
            state['step'] = 'description'
            await update.message.reply_text(
                "📝 توضیح کوتاه (اختیاری):\n(برای بدون توضیح: /skip)"
            )

        elif step == 'description':
            desc = '' if text == '/skip' else text
            pid = db.add_product(
                service=state.get('service', ''),
                duration=state.get('duration', ''),
                price=state.get('price', 0),
                bulk_price=state.get('bulk_price', 0),
                description=desc
            )
            context.user_data.pop('adding_product', None)
            await update.message.reply_text(
                f"✅ *محصول جدید اضافه شد!*\n\n"
                f"🆔 #{pid}\n"
                f"📦 {state.get('service')} — {state.get('duration')}\n"
                f"💰 {state.get('price',0):,} تومان\n"
                f"📦 عمده: {state.get('bulk_price',0):,} تومان",
                parse_mode='Markdown'
            )
        return True

    # ===== ویرایش محصول =====
    edit_state = context.user_data.get('editing_product')
    if edit_state:
        step = edit_state['step']
        pid = edit_state['id']
        d = edit_state['data']

        if step == 'service':
            if text != '/skip': d['service'] = text
            edit_state['step'] = 'duration'
            await update.message.reply_text(
                f"مدت زمان ({d['duration']}):\n/skip برای بدون تغییر"
            )
        elif step == 'duration':
            if text != '/skip': d['duration'] = text
            edit_state['step'] = 'price'
            await update.message.reply_text(
                f"قیمت ({d['price']:,} ت):\n/skip برای بدون تغییر"
            )
        elif step == 'price':
            if text != '/skip':
                try: d['price'] = int(text.replace(',',''))
                except: pass
            edit_state['step'] = 'bulk_price'
            await update.message.reply_text(
                f"قیمت عمده ({d.get('bulk_price',0):,} ت):\n/skip برای بدون تغییر"
            )
        elif step == 'bulk_price':
            if text != '/skip':
                try: d['bulk_price'] = int(text.replace(',',''))
                except: pass
            edit_state['step'] = 'description'
            await update.message.reply_text(
                f"توضیح ({d.get('description','—')}):\n/skip برای بدون تغییر"
            )
        elif step == 'description':
            if text != '/skip': d['description'] = text
            db.update_product(pid, d['service'], d['duration'], d['price'], d.get('bulk_price',0), d.get('description',''))
            context.user_data.pop('editing_product', None)
            await update.message.reply_text(
                f"✅ *محصول #{pid} ویرایش شد!*\n\n"
                f"📦 {d['service']} — {d['duration']}\n"
                f"💰 {d['price']:,} تومان",
                parse_mode='Markdown'
            )
        return True

    return False
