# bot.py
from telegram import Update, KeyboardButton, ReplyKeyboardMarkup, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, ContextTypes, filters
import aiohttp
import base64
import logging

# ---------------- CONFIG ----------------
BOT_TOKEN = "8520469513:AAH3dWw4wnqs1i1_0LfoRtdcV06OWuOHIBg"
SERVER_URL = "http://10.129.13.65/telegram"  # Replace with your domain/subdomain

# ---------------- LOGGING ----------------
logging.basicConfig(
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    level=logging.INFO
)

# ---------------- START COMMAND ----------------
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    button = KeyboardButton("📱 Share Phone Number", request_contact=True)
    reply_markup = ReplyKeyboardMarkup([[button]], resize_keyboard=True, one_time_keyboard=True)
    await update.message.reply_text(
        "Welcome 🎮\n\nPlease share your phone number to continue:",
        reply_markup=reply_markup
    )

# ---------------- CONTACT HANDLER ----------------
async def contact_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if not update.message.contact:
        return

    user = update.message.from_user
    contact = update.message.contact

    # Ensure user shares own contact
    if contact.user_id != user.id:
        await update.message.reply_text("❌ Please share your own phone number.")
        return

    telegram_id = user.id
    phone = contact.phone_number
    username = user.username or ""
    first_name = user.first_name or ""

    try:
        # Send user data to server
        async with aiohttp.ClientSession() as session:
            async with session.post(
                f"{SERVER_URL}/save_user.php",
                data={
                    "telegram_id": telegram_id,
                    "phone": phone,
                    "username": username,
                    "first_name": first_name
                },
                timeout=5
            ) as response:

                if response.status == 200:
                    # Encode Telegram ID
                    encoded_id = base64.b64encode(str(telegram_id).encode()).decode()
                    dashboard_link = f"{SERVER_URL}/dashboard.php?id={encoded_id}"

                    keyboard = [[InlineKeyboardButton("🎮 Open Dashboard", url=dashboard_link)]]
                    reply_markup = InlineKeyboardMarkup(keyboard)

                    await update.message.reply_text(
                        "✅ Account saved successfully!\n\nClick below to open your dashboard:",
                        reply_markup=reply_markup
                    )
                else:
                    await update.message.reply_text("❌ Failed to save data.")

    except Exception as e:
        logging.error(f"Server error: {e}")
        await update.message.reply_text("⚠️ Server connection error.")

# ---------------- MAIN FUNCTION ----------------
def main():
    app = ApplicationBuilder().token(BOT_TOKEN).build()
    app.add_handler(CommandHandler("start", start))
    app.add_handler(MessageHandler(filters.CONTACT, contact_handler))
    print("Bot is running...")
    app.run_polling()

if __name__ == "__main__":
    main()
