import requests
import json
import os
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, ReplyKeyboardMarkup, KeyboardButton
from telegram.ext import (
    Application, CommandHandler, CallbackQueryHandler, MessageHandler,
    ConversationHandler, ContextTypes, filters
)

# ==================== কনফিগারেশন ====================
BOT_TOKEN       = "8816149180:AAHt9jltbvPU3lp2pQc2hpG_s9cqUNZXkT0"
ADMIN_ID        = 8917651304                          # অ্যাডমিনের Numeric ID
API_URL         = "https://auto.elitepay.top/api.php"
API_KEY         = "EPZ"   # config.php এর api_secret

BALANCE_FILE    = "balances.json"
# ====================================================

# Conversation states
AMOUNT, TRX_ID = range(2)


# ---------- Helper Functions ----------
def load_balances():
    if os.path.exists(BALANCE_FILE):
        with open(BALANCE_FILE, "r", encoding="utf-8") as f:
            return json.load(f)
    return {}

def save_balances(data):
    with open(BALANCE_FILE, "w", encoding="utf-8") as f:
        json.dump(data, f, indent=4, ensure_ascii=False)

def get_balance(user_id):
    balances = load_balances()
    return balances.get(str(user_id), 0)

def add_balance(user_id, amount):
    balances = load_balances()
    uid = str(user_id)
    balances[uid] = balances.get(uid, 0) + float(amount)
    save_balances(balances)
    return balances[uid]

def send_to_admin(bot, text):
    try:
        bot.send_message(chat_id=ADMIN_ID, text=text, parse_mode="HTML")
    except:
        pass


# ---------- Elite Pay Verify ----------
def verify_trx(trx_id: str):
    payload = {
        "action": "verify",
        "api_key": API_KEY,
        "transaction_id": trx_id.strip()
    }
    headers = {
        "Content-Type": "application/json",
        "X-API-KEY": API_KEY
    }
    try:
        res = requests.post(API_URL, json=payload, headers=headers, timeout=30)
        return res.json()
    except Exception as e:
        return {"status": False, "message": str(e)}


# ---------- Start ----------
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user = update.effective_user
    balance = get_balance(user.id)

    keyboard = [
        [KeyboardButton("💰 ডিপোজিট")],
        [KeyboardButton("💳 ব্যালেন্স"), KeyboardButton("📞 সাপোর্ট")]
    ]
    reply_markup = ReplyKeyboardMarkup(keyboard, resize_keyboard=True)

    await update.message.reply_text(
        f"স্বাগতম <b>{user.first_name}</b>!\n\n"
        f"আপনার বর্তমান ব্যালেন্স: <b>{balance} ৳</b>\n\n"
        f"ডিপোজিট করতে নিচের বাটনে ক্লিক করুন।",
        parse_mode="HTML",
        reply_markup=reply_markup
    )


# ---------- Deposit Button ----------
async def deposit_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text(
        "💰 <b>ডিপোজিট এমাউন্ট লিখুন</b>\n\n"
        "উদাহরণ: <code>100</code> বা <code>50.5</code>\n\n"
        "বাতিল করতে /cancel লিখুন।",
        parse_mode="HTML"
    )
    return AMOUNT


# ---------- Amount Received ----------
async def amount_received(update: Update, context: ContextTypes.DEFAULT_TYPE):
    text = update.message.text.strip()

    try:
        amount = float(text)
        if amount <= 0:
            raise ValueError
    except:
        await update.message.reply_text("❌ সঠিক এমাউন্ট লিখুন। উদাহরণ: 100")
        return AMOUNT

    context.user_data["deposit_amount"] = amount

    await update.message.reply_text(
        f"✅ এমাউন্ট: <b>{amount} ৳</b>\n\n"
        f"এখন <b>বিকাশ/নগদের অফিসিয়াল Transaction ID</b> লিখুন:\n\n"
        f"বাতিল করতে /cancel লিখুন।",
        parse_mode="HTML"
    )
    return TRX_ID


# ---------- Transaction ID Received ----------
async def trx_received(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user = update.effective_user
    trx_id = update.message.text.strip()
    amount = context.user_data.get("deposit_amount")

    await update.message.reply_text("🔄 ট্রানজেকশন চেক করা হচ্ছে, একটু অপেক্ষা করুন...")

    result = verify_trx(trx_id)

    if result.get("status") is True and result.get("approved") is True:
        # ===== সফল =====
        new_balance = add_balance(user.id, amount)

        # ইউজারকে মেসেজ
        await update.message.reply_text(
            f"✅ <b>ডিপোজিট সফল হয়েছে!</b>\n\n"
            f"💰 পরিমাণ: <b>{amount} ৳</b>\n"
            f"🧾 TrxID: <code>{trx_id}</code>\n"
            f"💳 নতুন ব্যালেন্স: <b>{new_balance} ৳</b>",
            parse_mode="HTML"
        )

        # অ্যাডমিনকে নোটিফিকেশন
        admin_text = (
            f"✅ <b>নতুন ডিপোজিট সফল</b>\n\n"
            f"👤 ইউজার: <b>{user.full_name}</b>\n"
            f"🆔 ID: <code>{user.id}</code>\n"
            f"💰 এমাউন্ট: <b>{amount} ৳</b>\n"
            f"🧾 TrxID: <code>{trx_id}</code>\n"
            f"💳 মেথড: {result.get('payment_method', 'N/A')}"
        )
        await context.bot.send_message(chat_id=ADMIN_ID, text=admin_text, parse_mode="HTML")

    else:
        # ===== ব্যর্থ =====
        await update.message.reply_text(
            f"❌ <b>ট্রানজেকশন খুঁজে পাওয়া যায়নি</b>\n\n"
            f"TrxID: <code>{trx_id}</code>\n\n"
            f"সঠিক অফিসিয়াল Transaction ID দিয়ে আবার চেষ্টা করুন।",
            parse_mode="HTML"
        )

        # অ্যাডমিনকে ফেইলড অ্যাটেম্পট
        admin_text = (
            f"⚠️ <b>ফেইলড ডিপোজিট অ্যাটেম্পট</b>\n\n"
            f"👤 ইউজার: <b>{user.full_name}</b>\n"
            f"🆔 ID: <code>{user.id}</code>\n"
            f"💰 চেষ্টা করা এমাউন্ট: <b>{amount} ৳</b>\n"
            f"🧾 TrxID: <code>{trx_id}</code>\n"
            f"📝 কারণ: {result.get('message', 'Not matched')}"
        )
        await context.bot.send_message(chat_id=ADMIN_ID, text=admin_text, parse_mode="HTML")

    context.user_data.clear()
    return ConversationHandler.END


# ---------- Cancel ----------
async def cancel(update: Update, context: ContextTypes.DEFAULT_TYPE):
    context.user_data.clear()
    await update.message.reply_text("❌ ডিপোজিট বাতিল করা হয়েছে।")
    return ConversationHandler.END


# ---------- Balance ----------
async def balance(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user = update.effective_user
    bal = get_balance(user.id)
    await update.message.reply_text(f"💳 আপনার বর্তমান ব্যালেন্স: <b>{bal} ৳</b>", parse_mode="HTML")


# ---------- Support ----------
async def support(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("📞 সাপোর্টের জন্য অ্যাডমিনের সাথে যোগাযোগ করুন।")


# ---------- Main ----------
def main():
    app = Application.builder().token(BOT_TOKEN).build()

    conv_handler = ConversationHandler(
        entry_points=[MessageHandler(filters.Regex("^(💰 ডিপোজিট)$"), deposit_start)],
        states={
            AMOUNT: [MessageHandler(filters.TEXT & \~filters.COMMAND, amount_received)],
            TRX_ID: [MessageHandler(filters.TEXT & \~filters.COMMAND, trx_received)],
        },
        fallbacks=[CommandHandler("cancel", cancel)],
    )

    app.add_handler(CommandHandler("start", start))
    app.add_handler(conv_handler)
    app.add_handler(MessageHandler(filters.Regex("^(💳 ব্যালেন্স)$"), balance))
    app.add_handler(MessageHandler(filters.Regex("^(📞 সাপোর্ট)$"), support))

    print("Bot is running...")
    app.run_polling()


if __name__ == "__main__":
    main()