from telegram import Update, ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardRemove
from telegram.ext import ContextTypes
import database as db
from config import ADMIN_IDS, REQUIRED_CHANNEL, CARD_NUMBER, CARD_HOLDER, BANK_NAME, USDT_WALLET, WORK_HOURS_START, WORK_HOURS_END
from utils.strings import t
from utils.theme import build_main_menu, build_welcome_text, get_color_indicator
from datetime import datetime

STATUS_FA = {
    'pending':          '⏳ در انتظار رسید',
    'waiting_confirm':  '🔍 در حال بررسی',
    'confirmed':        '✅ تأیید شده',
    'rejected':         '❌ رد شده',
    'delivered':        '📦 تحویل داده شده',
}

def get_lang(user_id):
    u = db.get_user(user_id)
    return u['lang'] if u else 'fa'

async def check_channel_membership(bot, user_id):
    try:
        member = await bot.get_chat_member(REQUIRED_CHANNEL, user_id)
        return member.status not in ['left', 'kicked']
    except:
        return True

def is_work_hours():
    now = datetime.now().hour
    return WORK_HOURS_START <= now < WORK_HOURS_END

async def send_main_menu(target, context, user_id, lang='fa', text=None):
    """ارسال منوی اصلی به عنوان InlineKeyboard"""
    user_data = db.get_user(user_id)
    is_admin = user_id in ADMIN_IDS
    is_vip = user_data.get('is_vip', False) if user_data else False
    menu = build_main_menu(user_id, is_admin=is_admin, is_vip=is_vip)
    msg_text = text or build_welcome_text(
        user_data.get('full_name','') if user_data else '',
        is_vip=is_vip,
        lang=lang
    )
    if hasattr(target, 'message'):
        await target.message.reply_text(msg_text, reply_markup=menu, parse_mode='Markdown')
    else:
        await target.reply_text(msg_text, reply_markup=menu, parse_mode='Markdown')

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user = update.effective_user
    args = context.args
    referred_by = None

    if args:
        arg = args[0]
        if arg.startswith('ref_'):
            referrer = db.get_user_by_referral(arg[4:])
            if referrer and referrer['user_id'] != user.id:
                referred_by = referrer['user_id']

    is_new = db.add_user(user.id, user.username, user.full_name, referred_by)
    lang = get_lang(user.id)
    user_data = db.get_user(user.id)

    if user_data and user_data['is_blacklisted']:
        await update.message.reply_text(t('blacklisted', lang))
        return

    if is_new:
        for admin_id in ADMIN_IDS:
            try:
                ref_text = f"\n👥 معرفی شده توسط: {referred_by}" if referred_by else ""
                await context.bot.send_message(
                    admin_id,
                    f"👤 کاربر جدید!\n\n🆔 {user.id}\n👤 {user.full_name}\n📌 @{user.username or 'ندارد'}{ref_text}"
                )
            except: pass

    is_member = await check_channel_membership(context.bot, user.id)
    if not is_member:
        kb = InlineKeyboardMarkup([
            [InlineKeyboardButton("📢 عضویت در کانال", url=f"https://t.me/{REQUIRED_CHANNEL.lstrip('@')}")],
            [InlineKeyboardButton("✅ عضو شدم", callback_data="check_join")]
        ])
        await update.message.reply_text(t('join_required', lang), reply_markup=kb)
        return

    if not user_data or not user_data['is_verified']:
        kb = ReplyKeyboardMarkup(
            [[KeyboardButton(t('send_phone_btn', lang), request_contact=True)]],
            resize_keyboard=True, one_time_keyboard=True
        )
        await update.message.reply_text(t('send_phone', lang), reply_markup=kb)
        return

    await send_main_menu(update, context, user.id, lang)

async def handle_contact(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user = update.effective_user
    contact = update.message.contact
    lang = get_lang(user.id)

    if contact.user_id != user.id:
        await update.message.reply_text("❌ لطفاً شماره تلفن خودتان را ارسال کنید.")
        return

    db.set_user_phone(user.id, contact.phone_number)

    for admin_id in ADMIN_IDS:
        try:
            await context.bot.send_message(
                admin_id,
                f"✅ احراز هویت\n\n🆔 {user.id}\n👤 {user.full_name}\n📌 @{user.username or 'ندارد'}\n📱 {contact.phone_number}"
            )
        except: pass

    await update.message.reply_text(t('verified', lang), reply_markup=ReplyKeyboardRemove())
    await send_main_menu(update, context, user.id, lang)

async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user = update.effective_user
    lang = get_lang(user.id)
    text = update.message.text
    user_data = db.get_user(user.id)

    if user_data and user_data['is_blacklisted']:
        await update.message.reply_text(t('blacklisted', lang))
        return

    # مراحل افزودن/ویرایش محصول (ادمین)
    if (context.user_data.get('adding_product') or context.user_data.get('editing_product')) and user.id in ADMIN_IDS:
        from handlers.admin_handlers import handle_product_text_input
        handled = await handle_product_text_input(update, context)
        if handled: return

    # مراحل افزودن کانفیگ (ادمین)
    if context.user_data.get('adding_config') and user.id in ADMIN_IDS:
        from handlers import config_handlers
        handled = await config_handlers.handle_config_text_input(update, context)
        if handled: return

    # تیکت فعال
    if context.user_data.get('open_ticket_id'):
        tid = context.user_data['open_ticket_id']
        db.add_ticket_message(tid, user.id, text)
        for admin_id in ADMIN_IDS:
            try:
                await context.bot.send_message(
                    admin_id,
                    f"💬 پیام تیکت #{tid}\n👤 {user.full_name}\n\n{text}",
                    reply_markup=InlineKeyboardMarkup([[
                        InlineKeyboardButton(f"↩️ پاسخ #{tid}", callback_data=f"reply_ticket_{tid}")
                    ]])
                )
            except: pass
        await update.message.reply_text(f"✅ پیام در تیکت #{tid} ثبت شد.")
        return

    # broadcast ادمین
    if context.user_data.get('broadcast_mode') and user.id in ADMIN_IDS:
        users = db.get_all_users()
        success = 0
        for u in users:
            try:
                await context.bot.send_message(u['user_id'], text)
                success += 1
            except: pass
        context.user_data.pop('broadcast_mode', None)
        await update.message.reply_text(f"📢 به {success} نفر ارسال شد.")
        return

    # پاسخ تیکت ادمین
    if context.user_data.get('replying_ticket') and user.id in ADMIN_IDS:
        tid = context.user_data.pop('replying_ticket')
        ticket = db.get_ticket(tid)
        if ticket:
            db.add_ticket_message(tid, user.id, text, is_admin=True)
            try:
                await context.bot.send_message(ticket['user_id'], f"📩 پاسخ پشتیبانی - تیکت #{tid}:\n\n{text}")
            except: pass
            await update.message.reply_text(f"✅ پاسخ تیکت #{tid} ارسال شد.")
        return

    # ویرایش قیمت ادمین
    if context.user_data.get('editing_price_id') and user.id in ADMIN_IDS:
        pid = context.user_data.pop('editing_price_id')
        try:
            price = int(text.replace(',','').replace(' ',''))
            db.update_product_price(pid, price)
            await update.message.reply_text(f"✅ قیمت به {price:,} تومان تغییر کرد.")
        except:
            await update.message.reply_text("❌ عدد معتبر وارد کنید.")
        return

    # کد تخفیف
    if context.user_data.get('waiting_discount'):
        context.user_data.pop('waiting_discount')
        if text != '/skip':
            disc = db.get_discount_code(text)
            if disc:
                pid = context.user_data.get('selected_product_id')
                product = db.get_product(pid)
                new_price = int(product['price'] * (1 - disc['percent'] / 100))
                context.user_data['discount_code'] = text
                context.user_data['final_price'] = new_price
                await update.message.reply_text(t('discount_applied', lang, percent=disc['percent'], new_price=new_price))
                await show_payment_methods(update, context, new_price)
            else:
                await update.message.reply_text(t('discount_invalid', lang))
        else:
            pid = context.user_data.get('selected_product_id')
            product = db.get_product(pid)
            context.user_data['final_price'] = product['price']
            await show_payment_methods(update, context, product['price'])
        return

    # ارسال اکانت ادمین
    if context.user_data.get('sending_account') and user.id in ADMIN_IDS:
        info = context.user_data.pop('sending_account')
        order_id = info['order_id']
        expires_at = info['expires_at']
        db.set_order_account(order_id, text, expires_at)
        order = db.get_order(order_id)
        try:
            await context.bot.send_message(
                order['user_id'],
                t('account_delivered', lang, account_info=text, expires=expires_at[:10])
            )
            stars_btns = InlineKeyboardMarkup([[
                InlineKeyboardButton(f"{'⭐'*i}", callback_data=f"rate_{order_id}_{i}") for i in range(1,6)
            ]])
            await context.bot.send_message(order['user_id'], t('rate_order', lang, order_id=order_id), reply_markup=stars_btns)
        except: pass
        u_data = db.get_user(order['user_id'])
        if u_data and u_data.get('referred_by'):
            bonus = int(order['amount'] * 0.05)
            db.update_wallet(u_data['referred_by'], bonus)
            try:
                await context.bot.send_message(u_data['referred_by'], f"🎁 {bonus:,} تومان پورسانت معرفی دریافت کردید!")
            except: pass
        await update.message.reply_text("✅ اکانت ارسال شد.")
        return

    # ثبت نظر
    if context.user_data.get('rating'):
        rating = context.user_data.pop('rating')
        comment = text
        if comment != '/skip':
            db.add_review(user.id, rating['order_id'], rating['stars'], comment)
            await update.message.reply_text("✅ نظر شما ثبت شد. ممنون!")
        else:
            db.add_review(user.id, rating['order_id'], rating['stars'], '')
            await update.message.reply_text("✅ امتیاز ثبت شد.")
        return

    # ویرایش تم ادمین
    if context.user_data.get('editing_theme') and user.id in ADMIN_IDS:
        key = context.user_data.pop('editing_theme')
        db.save_theme(key, text)
        await update.message.reply_text(f"✅ تنظیم شد!\n\n🔑 {key}: {text}")
        return

    # /start دوباره یا هر متن ناشناس
    await send_main_menu(update, context, user.id, lang)

async def show_services(update_or_query, context, edit=False):
    lang = get_lang(update_or_query.from_user.id if hasattr(update_or_query,'from_user') else update_or_query.effective_user.id)
    services = db.get_services()
    if not services:
        msg = t('no_products', lang)
        if edit:
            await update_or_query.edit_message_text(msg)
        else:
            await update_or_query.message.reply_text(msg)
        return
    theme = db.get_theme()
    mc = theme.get('color_main','green')
    ci = get_color_indicator(mc, 0)
    buttons = [[InlineKeyboardButton(ci + s, callback_data=f"service_{s}")] for s in services]
    buttons.append([InlineKeyboardButton("🔙 بازگشت", callback_data="menu_back")])
    kb = InlineKeyboardMarkup(buttons)
    text = "🛒 *سرویس مورد نظر را انتخاب کنید:*"
    if edit:
        await update_or_query.edit_message_text(text, reply_markup=kb, parse_mode='Markdown')
    else:
        await update_or_query.message.reply_text(text, reply_markup=kb, parse_mode='Markdown')

async def show_payment_methods(update, context, amount):
    user = update.effective_user
    lang = get_lang(user.id)
    user_data = db.get_user(user.id)
    wallet = user_data.get('wallet', 0) if user_data else 0
    buttons = [
        [InlineKeyboardButton("💳 کارت به کارت", callback_data="pay_card")],
        [InlineKeyboardButton(f"👛 کیف پول ({wallet:,} ت)", callback_data="pay_wallet")],
        [InlineKeyboardButton("💎 تتر USDT", callback_data="pay_usdt")],
        [InlineKeyboardButton("🟣 زرین‌پال", callback_data="pay_zarinpal")],
    ]
    await update.message.reply_text(t('select_payment', lang), reply_markup=InlineKeyboardMarkup(buttons))

async def my_orders(update, context):
    user = update.effective_user
    lang = get_lang(user.id)
    orders = db.get_user_orders(user.id)
    if not orders:
        await update.message.reply_text(t('no_orders', lang))
        return
    text = "📦 *سفارش‌های اخیر شما:*\n\n"
    for o in orders[:5]:
        text += (f"🔹 *#{o['id']}* | {o['service']} {o['duration']}\n"
                 f"   💰 {o['amount']:,} ت | {STATUS_FA.get(o['status'], o['status'])}\n\n")
    await update.message.reply_text(text, parse_mode='Markdown')

async def show_wallet(update, context):
    user = update.effective_user
    lang = get_lang(user.id)
    user_data = db.get_user(user.id)
    await update.message.reply_text(
        t('wallet_balance', lang, balance=user_data.get('wallet',0), points=user_data.get('points',0))
    )

async def show_referral(update, context):
    user = update.effective_user
    lang = get_lang(user.id)
    user_data = db.get_user(user.id)
    ref_code = user_data.get('referral_code','')
    bot = await context.bot.get_me()
    all_users = db.get_all_users()
    count = sum(1 for u in all_users if u.get('referred_by') == user.id)
    await update.message.reply_text(
        t('referral_info', lang, bot_username=bot.username, ref_code=ref_code, count=count)
    )

async def show_reviews(update, context):
    reviews = db.get_reviews(8)
    if not reviews:
        await update.message.reply_text("⭐ هنوز نظری ثبت نشده.")
        return
    text = "⭐ *نظرات کاربران:*\n\n"
    for r in reviews:
        text += f"{'⭐'*r['stars']}\n👤 {r['full_name'] or 'کاربر'}\n💬 {r['comment']}\n\n"
    await update.message.reply_text(text, parse_mode='Markdown')

async def button_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()
    data = query.data
    user = query.from_user
    lang = get_lang(user.id)
    user_data = db.get_user(user.id)
    theme = db.get_theme()

    # ===== منوی اصلی =====
    if data == "menu_back":
        is_admin = user.id in ADMIN_IDS
        is_vip = user_data.get('is_vip', False) if user_data else False
        menu = build_main_menu(user.id, is_admin=is_admin, is_vip=is_vip)
        welcome = build_welcome_text(user_data.get('full_name','') if user_data else '', is_vip=is_vip)
        await query.edit_message_text(welcome, reply_markup=menu, parse_mode='Markdown')

    elif data == "menu_buy":
        await show_services(query, context, edit=True)

    elif data == "menu_orders":
        orders = db.get_user_orders(user.id)
        if not orders:
            await query.edit_message_text("📦 سفارشی ندارید.", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🔙 بازگشت", callback_data="menu_back")]]))
            return
        text = "📦 *سفارش‌های اخیر:*\n\n"
        for o in orders[:5]:
            text += f"🔹 *#{o['id']}* | {o['service']} {o['duration']}\n   💰 {o['amount']:,} ت | {STATUS_FA.get(o['status'],o['status'])}\n\n"
        await query.edit_message_text(text, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🔙 بازگشت", callback_data="menu_back")]]), parse_mode='Markdown')

    elif data == "menu_configs":
        from handlers import config_handlers
        await config_handlers.show_my_configs_inline(query, context)

    elif data == "menu_wallet":
        bal = user_data.get('wallet',0) if user_data else 0
        pts = user_data.get('points',0) if user_data else 0
        await query.edit_message_text(
            f"👛 *کیف پول:*\n\n💰 موجودی: {bal:,} تومان\n⭐ امتیاز: {pts}",
            reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🔙 بازگشت", callback_data="menu_back")]]),
            parse_mode='Markdown'
        )

    elif data == "menu_support":
        if not is_work_hours():
            await query.edit_message_text(
                t('off_hours', lang, start=WORK_HOURS_START, end=WORK_HOURS_END),
                reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🔙 بازگشت", callback_data="menu_back")]])
            )
            return
        await query.edit_message_text(
            "🎧 *پشتیبانی:*\n\nگزینه مورد نظر را انتخاب کنید:",
            reply_markup=InlineKeyboardMarkup([
                [InlineKeyboardButton("➕ تیکت جدید", callback_data="new_ticket")],
                [InlineKeyboardButton("💬 چت زنده با ادمین", callback_data="live_chat")],
                [InlineKeyboardButton("🔙 بازگشت", callback_data="menu_back")]
            ]),
            parse_mode='Markdown'
        )

    elif data == "menu_referral":
        ref_code = user_data.get('referral_code','') if user_data else ''
        bot = await context.bot.get_me()
        all_users = db.get_all_users()
        count = sum(1 for u in all_users if u.get('referred_by') == user.id)
        await query.edit_message_text(
            f"🔗 *لینک رفرال شما:*\n\n`t.me/{bot.username}?start=ref_{ref_code}`\n\n"
            f"👥 تعداد معرفی‌ها: {count}\n"
            f"💰 پورسانت هر خرید: ۵٪ به کیف پول",
            reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🔙 بازگشت", callback_data="menu_back")]]),
            parse_mode='Markdown'
        )

    elif data == "menu_reviews":
        reviews = db.get_reviews(5)
        text = "⭐ *نظرات کاربران:*\n\n"
        for r in reviews:
            text += f"{'⭐'*r['stars']} {r['full_name'] or 'کاربر'}\n{r['comment'] or ''}\n\n"
        if not reviews: text += "هنوز نظری ثبت نشده."
        await query.edit_message_text(text, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🔙 بازگشت", callback_data="menu_back")]]), parse_mode='Markdown')

    elif data == "menu_payment":
        await query.edit_message_text(
            f"💳 *روش‌های پرداخت:*\n\n"
            f"1️⃣ کارت به کارت:\n🏦 {BANK_NAME}\n💳 `{CARD_NUMBER}`\n👤 {CARD_HOLDER}\n\n"
            f"2️⃣ تتر USDT (TRC20):\n`{USDT_WALLET}`\n\n"
            f"3️⃣ کیف پول ربات\n4️⃣ زرین‌پال",
            reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🔙 بازگشت", callback_data="menu_back")]]),
            parse_mode='Markdown'
        )

    elif data == "menu_about":
        await query.edit_message_text(
            f"ℹ️ *{theme.get('bot_name','ربات پرمیوم')}*\n\n"
            f"🚀 نسخه {theme.get('bot_version','1.0.0')}\n\n"
            f"✅ پشتیبانی ۲۴ ساعته\n✅ تحویل سریع\n✅ ضمانت اکانت",
            reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🔙 بازگشت", callback_data="menu_back")]]),
            parse_mode='Markdown'
        )

    elif data == "menu_admin" and user.id in ADMIN_IDS:
        from handlers.admin_handlers import admin_panel_inline
        await admin_panel_inline(query, context)

    # ===== جوین کانال =====
    elif data == "check_join":
        is_member = await check_channel_membership(context.bot, user.id)
        if is_member:
            if not user_data or not user_data['is_verified']:
                kb = ReplyKeyboardMarkup([[KeyboardButton(t('send_phone_btn',lang), request_contact=True)]], resize_keyboard=True, one_time_keyboard=True)
                await query.message.reply_text(t('send_phone', lang), reply_markup=kb)
            else:
                await send_main_menu(query.message, context, user.id, lang)
        else:
            await query.answer("❌ هنوز عضو نشده‌اید!", show_alert=True)

    # ===== خرید =====
    elif data.startswith("service_"):
        service = data[8:]
        products = [p for p in db.get_products() if p['service'] == service]
        mc = theme.get('color_main','green')
        ci = get_color_indicator(mc, 0)
        buttons = []
        for p in products:
            flash = db.get_flash_sale(p['id'])
            label = f"{ci}{p['duration']} — {p['price']:,} ت"
            if flash:
                disc_price = int(p['price'] * (1 - flash['discount_percent']/100))
                label = f"🔥 {p['duration']} — {disc_price:,} ت ({flash['discount_percent']}% تخفیف)"
            buttons.append([InlineKeyboardButton(label, callback_data=f"product_{p['id']}")])
        buttons.append([InlineKeyboardButton("🔙 بازگشت", callback_data="back_services")])
        await query.edit_message_text(f"📦 *{service}*\n\nمدت زمان را انتخاب کنید:", reply_markup=InlineKeyboardMarkup(buttons), parse_mode='Markdown')

    elif data == "back_services":
        await show_services(query, context, edit=True)

    elif data.startswith("product_"):
        product_id = int(data[8:])
        product = db.get_product(product_id)
        if not product: return
        flash = db.get_flash_sale(product_id)
        price = product['price']
        if flash:
            price = int(price * (1 - flash['discount_percent']/100))
        if user_data and user_data.get('is_reseller') and user_data.get('reseller_discount'):
            price = int(price * (1 - user_data['reseller_discount']/100))
        context.user_data['selected_product_id'] = product_id
        context.user_data['final_price'] = price
        buttons = [
            [InlineKeyboardButton("✅ تأیید و ادامه", callback_data=f"confirm_order_{product_id}")],
            [InlineKeyboardButton("🎟 کد تخفیف دارم", callback_data=f"enter_discount_{product_id}")],
        ]
        if not user_data.get('free_trial_used'):
            buttons.append([InlineKeyboardButton("🎁 دوره آزمایشی رایگان", callback_data=f"free_trial_{product_id}")])
        if product.get('bulk_price') and product['bulk_price'] < product['price']:
            buttons.append([InlineKeyboardButton(f"📦 خرید عمده — {product['bulk_price']:,} ت", callback_data=f"bulk_{product_id}")])
        buttons.append([InlineKeyboardButton("🔙 بازگشت", callback_data=f"service_{product['service']}")])
        await query.edit_message_text(
            f"🛒 *جزئیات سفارش:*\n\n📦 {product['service']}\n⏱ {product['duration']}\n💰 {price:,} تومان",
            reply_markup=InlineKeyboardMarkup(buttons), parse_mode='Markdown'
        )

    elif data.startswith("enter_discount_"):
        pid = int(data[15:])
        context.user_data['waiting_discount'] = True
        context.user_data['selected_product_id'] = pid
        await query.edit_message_text(t('enter_discount', lang))

    elif data.startswith("free_trial_"):
        pid = int(data[11:])
        product = db.get_product(pid)
        if user_data.get('free_trial_used'):
            await query.answer(t('trial_used', lang), show_alert=True)
            return
        db.use_free_trial(user.id)
        order_id = db.create_order(user.id, product['service'], '24 ساعت (آزمایشی)', 0, payment_method='free_trial')
        for admin_id in ADMIN_IDS:
            try:
                await context.bot.send_message(admin_id, f"🎁 درخواست آزمایشی\n👤 {user.full_name}\n📦 {product['service']}\n🆔 #{order_id}")
            except: pass
        await query.edit_message_text(f"✅ دوره آزمایشی ثبت شد!\n🆔 #{order_id}\n\nبه زودی ارسال می‌شود.")

    elif data.startswith("bulk_"):
        pid = int(data[5:])
        product = db.get_product(pid)
        order_id = db.create_order(user.id, product['service'], product['duration']+' (عمده)', product['bulk_price'], payment_method='card')
        context.user_data['current_order_id'] = order_id
        await query.edit_message_text(
            t('order_created', lang, order_id=order_id, amount=product['bulk_price'], bank=BANK_NAME, card=CARD_NUMBER, holder=CARD_HOLDER),
            parse_mode='Markdown'
        )

    elif data.startswith("confirm_order_"):
        pid = int(data[14:])
        product = db.get_product(pid)
        price = context.user_data.get('final_price', product['price'])
        wallet = user_data.get('wallet', 0) if user_data else 0
        await query.edit_message_text(
            t('select_payment', lang),
            reply_markup=InlineKeyboardMarkup([
                [InlineKeyboardButton("💳 کارت به کارت", callback_data=f"dopay_card_{pid}")],
                [InlineKeyboardButton(f"👛 کیف پول ({wallet:,} ت)", callback_data=f"dopay_wallet_{pid}")],
                [InlineKeyboardButton("💎 تتر USDT", callback_data=f"dopay_usdt_{pid}")],
                [InlineKeyboardButton("🟣 زرین‌پال", callback_data=f"dopay_zarinpal_{pid}")],
            ])
        )

    elif data.startswith("dopay_"):
        parts = data.split("_")
        method = parts[1]
        pid = int(parts[2])
        product = db.get_product(pid)
        price = context.user_data.get('final_price', product['price'])
        disc = context.user_data.get('discount_code')

        if method == "wallet":
            if (user_data.get('wallet') or 0) < price:
                await query.answer("❌ موجودی کافی نیست!", show_alert=True)
                return
            db.update_wallet(user.id, -price)
            order_id = db.create_order(user.id, product['service'], product['duration'], price, product['price'], disc, 'wallet')
            db.update_order_status(order_id, 'waiting_confirm')
            context.user_data['current_order_id'] = order_id
            await query.edit_message_text(f"✅ پرداخت از کیف پول انجام شد!\n🆔 سفارش #{order_id} در حال بررسی است.")
            for admin_id in ADMIN_IDS:
                try:
                    await context.bot.send_message(admin_id, f"💳 پرداخت کیف پول\n👤 {user.full_name}\n📦 {product['service']} {product['duration']}\n💰 {price:,} ت\n🆔 #{order_id}",
                        reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("✅ تأیید", callback_data=f"approve_{order_id}"), InlineKeyboardButton("❌ رد", callback_data=f"reject_{order_id}")]]))
                except: pass
        elif method == "usdt":
            order_id = db.create_order(user.id, product['service'], product['duration'], price, product['price'], disc, 'usdt')
            context.user_data['current_order_id'] = order_id
            await query.edit_message_text(
                f"💎 *پرداخت با تتر USDT:*\n\n📍 شبکه: TRC20\n💳 آدرس:\n`{USDT_WALLET}`\n\n💰 معادل {price:,} تومان\n\n📸 تصویر تراکنش را ارسال کنید.",
                parse_mode='Markdown'
            )
        elif method == "zarinpal":
            order_id = db.create_order(user.id, product['service'], product['duration'], price, product['price'], disc, 'zarinpal')
            context.user_data['current_order_id'] = order_id
            await query.edit_message_text(f"🟣 درگاه زرین‌پال\n\n💰 {price:,} تومان\n\n📸 رسید را ارسال کنید.")
        else:
            order_id = db.create_order(user.id, product['service'], product['duration'], price, product['price'], disc, 'card')
            context.user_data['current_order_id'] = order_id
            if disc: db.use_discount_code(disc)
            await query.edit_message_text(
                t('order_created', lang, order_id=order_id, amount=price, bank=BANK_NAME, card=CARD_NUMBER, holder=CARD_HOLDER),
                parse_mode='Markdown'
            )

    elif data.startswith("approve_"):
        if user.id not in ADMIN_IDS: return
        order_id = int(data[8:])
        db.update_order_status(order_id, 'confirmed')
        order = db.get_order(order_id)
        await query.edit_message_reply_markup(reply_markup=None)
        conn = db.get_db()
        conn.execute("UPDATE users SET total_spent=total_spent+?, points=points+? WHERE user_id=?",
                     (order['amount'], order['amount']//1000, order['user_id']))
        conn.commit(); conn.close()
        vip_up = db.check_vip_upgrade(order['user_id'])
        from config import VIP_CHANNEL_ID
        invite_link = None
        try:
            from datetime import timedelta
            link_obj = await context.bot.create_chat_invite_link(VIP_CHANNEL_ID, name=f"Order #{order_id}", member_limit=1, expire_date=datetime.now()+timedelta(hours=48))
            invite_link = link_obj.invite_link
        except: pass
        try:
            msg = t('order_confirmed', lang, order_id=order_id, service=order['service'], duration=order['duration'])
            if invite_link: msg += f"\n\n🔗 لینک VIP (۴۸ ساعته):\n{invite_link}"
            if vip_up: msg += "\n\n👑 تبریک! شما VIP شدید!"
            await context.bot.send_message(user.id, f"✅ سفارش #{order_id} تأیید شد.\n\nاکانت را ارسال کنید:",
                reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(f"📦 ارسال اکانت #{order_id}", callback_data=f"send_account_{order_id}")]]))
            await context.bot.send_message(order['user_id'], msg)
        except Exception as e:
            await query.message.reply_text(f"⚠️ خطا: {e}")

    elif data.startswith("send_account_"):
        if user.id not in ADMIN_IDS: return
        order_id = int(data[13:])
        order = db.get_order(order_id)
        dur = order['duration']
        months = 1
        if '3' in dur: months=3
        elif '6' in dur: months=6
        elif '12' in dur: months=12
        from datetime import timedelta
        expires = (datetime.now()+timedelta(days=30*months)).strftime('%Y-%m-%d')
        context.user_data['sending_account'] = {'order_id': order_id, 'expires_at': expires}
        await query.edit_message_text(f"📦 اطلاعات اکانت سفارش #{order_id} را بنویسید:")

    elif data.startswith("reject_"):
        if user.id not in ADMIN_IDS: return
        order_id = int(data[7:])
        db.update_order_status(order_id, 'rejected')
        order = db.get_order(order_id)
        await query.edit_message_reply_markup(reply_markup=None)
        try: await context.bot.send_message(order['user_id'], t('order_rejected', lang, order_id=order_id))
        except: pass

    elif data.startswith("rate_"):
        parts = data.split("_")
        order_id = int(parts[1]); stars = int(parts[2])
        context.user_data['rating'] = {'order_id': order_id, 'stars': stars}
        await query.edit_message_text(f"{'⭐'*stars}\n\nنظر خود را بنویسید (یا /skip):")

    elif data == "new_ticket":
        context.user_data['waiting_ticket_subject'] = True
        await query.edit_message_text(t('new_ticket', lang))

    elif data == "live_chat":
        for admin_id in ADMIN_IDS:
            try:
                await context.bot.send_message(admin_id, f"💬 درخواست چت زنده\n👤 {user.full_name} (@{user.username or '?'})\n🆔 {user.id}",
                    reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("↩️ پاسخ", url=f"tg://user?id={user.id}")]]))
            except: pass
        await query.edit_message_text("✅ درخواست ارسال شد. ادمین به زودی پیام می‌دهد.")

    elif data.startswith("reply_ticket_"):
        if user.id not in ADMIN_IDS: return
        tid = int(data[13:])
        context.user_data['replying_ticket'] = tid
        await query.message.reply_text(f"✍️ پاسخ تیکت #{tid}:")

async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await send_main_menu(update, context, update.effective_user.id)
