from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton
from telegram.ext import ContextTypes, ConversationHandler
import database as db
from config import ADMIN_IDS, LOG_CHANNEL_ID

async def handle_receipt_photo(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user = update.effective_user
    order_id = context.user_data.get('current_order_id')

    if not order_id:
        await update.message.reply_text("❌ سفارش فعالی یافت نشد. ابتدا خرید کنید.")
        return

    file_id = update.message.photo[-1].file_id
    db.update_order_receipt(order_id, file_id)
    order = db.get_order(order_id)

    await update.message.reply_text(f"✅ رسید دریافت شد!\n🔍 سفارش #{order_id} در حال بررسی است.")

    buttons = InlineKeyboardMarkup([
        [InlineKeyboardButton("✅ تأیید", callback_data=f"approve_{order_id}"),
         InlineKeyboardButton("❌ رد", callback_data=f"reject_{order_id}")]
    ])

    caption = (
        f"🛒 سفارش جدید - #{order_id}\n\n"
        f"👤 {user.full_name}\n"
        f"🆔 {user.id}\n"
        f"📌 @{user.username or 'ندارد'}\n"
        f"📦 {order['service']} - {order['duration']}\n"
        f"💰 {order['amount']:,} تومان\n"
        f"💳 {order.get('payment_method','card')}"
    )

    for admin_id in ADMIN_IDS:
        try:
            await context.bot.send_photo(admin_id, photo=file_id, caption=caption, reply_markup=buttons)
        except:
            pass

    if LOG_CHANNEL_ID:
        try:
            await context.bot.send_photo(LOG_CHANNEL_ID, photo=file_id, caption=caption, reply_markup=buttons)
        except Exception as e:
            print(f"خطا کانال لاگ: {e}")

    context.user_data.pop('current_order_id', None)

order_conv_handler = ConversationHandler(entry_points=[], states={}, fallbacks=[])
