"""
ELEVATEX BOMBER - Complete Free Telegram Bot
Owner: @elevatexzaid
Fully Premium Ui & Colorful Button By ElevateX By ZaiD
FULLY FREE - No Credits System
"""

import os
import sys
import subprocess
import asyncio
import json
import sqlite3
import re
import logging
from datetime import datetime, timedelta
from typing import Optional, Dict, List, Tuple

# ======================== INSTALL REQUIREMENTS ========================
def install_requirements():
    print("📦 Checking requirements...")
    packages = [
        "python-telegram-bot==22.7",
        "aiohttp==3.8.5"
    ]
    try:
        subprocess.check_call([sys.executable, "-m", "pip", "install", "--upgrade", *packages])
        print("✅ Requirements installed successfully!")
    except subprocess.CalledProcessError as e:
        print(f"❌ Requirements installation failed: {e}")
        raise

install_requirements()

from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Application, CommandHandler, CallbackQueryHandler, MessageHandler, filters, ContextTypes
import aiohttp

# ======================== CONFIGURATION ========================
BOT_TOKEN = "YOUR_BOT_TOKEN"
OWNER_ID = YOUR_CHAT_ID
ADMIN_IDS = [AGAIN_YOUR_CHAT_ID]
API_URL = "https://sms-bomber.elevatex.workers.dev/"
MAX_SMS_LIMIT = 50
MIN_SMS_LIMIT = 1

# Force Join Channels
FORCE_JOIN_CHANNELS = [
    "@elevatexbyzaid",
    "@elevatex_chat", 
    "@exzhub"
]

logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO
)
logger = logging.getLogger(__name__)

# ======================== UI FORMATTER ========================
def format_ui(text: str) -> str:
    """Format text with premium UI borders and small caps."""
    caps = {
        'a': 'ᴀ', 'b': 'ʙ', 'c': 'ᴄ', 'd': 'ᴅ', 'e': 'ᴇ', 'f': 'ꜰ', 'g': 'ɢ', 'h': 'ʜ', 'i': 'ɪ', 'j': 'ᴊ', 'k': 'ᴋ', 'l': 'ʟ', 'm': 'ᴍ', 'n': 'ɴ', 'o': 'ᴏ', 'p': 'ᴘ', 'q': 'ǫ', 'r': 'ʀ', 's': 's', 't': 'ᴛ', 'u': 'ᴜ', 'v': 'ᴠ', 'w': 'ᴡ', 'x': 'x', 'y': 'ʏ', 'z': 'ᴢ',
        'A': 'ᴀ', 'B': 'ʙ', 'C': 'ᴄ', 'D': 'ᴅ', 'E': 'ᴇ', 'F': 'ꜰ', 'G': 'ɢ', 'H': 'ʜ', 'I': 'ɪ', 'J': 'ᴊ', 'K': 'ᴋ', 'L': 'ʟ', 'M': 'ᴍ', 'N': 'ɴ', 'O': 'ᴏ', 'P': 'ᴘ', 'Q': 'ǫ', 'R': 'ʀ', 'S': 's', 'T': 'ᴛ', 'U': 'ᴜ', 'V': 'ᴠ', 'W': 'ᴡ', 'X': 'x', 'Y': 'ʏ', 'Z': 'ᴢ'
    }
    lines = text.split('\n')
    res_lines = []
    for line in lines:
        words = line.split(' ')
        res_words = []
        for w in words:
            if w.startswith('http') or w.startswith('@') or w.startswith('/') or w.startswith('+'):
                res_words.append(w)
            else:
                new_w = "".join(caps.get(c, c) for c in w)
                res_words.append(new_w)
        res_lines.append(" ".join(res_words))
    
    ui = f"╭━━〔 𝐄𝐥𝐞𝐯𝐚𝐭𝐞𝐗 𝐅𝐑𝐄𝐄 〕━━┈⊷\n┃ \n"
    for line in res_lines:
        ui += f"┃ {line}\n"
    ui += f"┃ \n╰━━━━━━━━━━━━━━━━━━━━━━┈⊷"
    return ui

# ======================== DATABASE ========================
class Database:
    def __init__(self, db_name="elevatex.db"):
        self.db_name = db_name
        self.init_db()
    
    def get_connection(self):
        return sqlite3.connect(self.db_name, timeout=10)
    
    def init_db(self):
        conn = self.get_connection()
        cursor = conn.cursor()
        
        # Users table - NO CREDITS SYSTEM
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS users (
                user_id INTEGER PRIMARY KEY,
                username TEXT,
                first_name TEXT,
                last_name TEXT,
                is_banned BOOLEAN DEFAULT FALSE,
                join_date DATETIME DEFAULT CURRENT_TIMESTAMP,
                total_sms INTEGER DEFAULT 0,
                last_used DATETIME
            )
        ''')
        
        # SMS History
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS sms_history (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_id INTEGER,
                phone TEXT,
                message TEXT,
                api_used TEXT,
                status TEXT,
                date DATETIME DEFAULT CURRENT_TIMESTAMP
            )
        ''')
        
        # Settings
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS settings (
                key TEXT PRIMARY KEY,
                value TEXT,
                updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
            )
        ''')
        
        # Blacklist
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS blacklist (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                number TEXT UNIQUE,
                reason TEXT,
                added_by INTEGER,
                date DATETIME DEFAULT CURRENT_TIMESTAMP
            )
        ''')
        
        # Admin Logs
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS admin_logs (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                admin_id INTEGER,
                action TEXT,
                target_user INTEGER,
                details TEXT,
                date DATETIME DEFAULT CURRENT_TIMESTAMP
            )
        ''')
        
        # Default settings - FULLY FREE
        cursor.execute('''
            INSERT OR IGNORE INTO settings (key, value) VALUES
            ('maintenance_mode', 'false'),
            ('cooldown_seconds', '10'),
            ('force_join_channels', '["@elevatexbyzaid", "@elevatex_chat", "@exzhub"]'),
            ('max_sms_limit', '50'),
            ('allow_bulk', 'true')
        ''')
        
        conn.commit()
        conn.close()
    
    # ===== USER METHODS =====
    def add_user(self, user_id: int, username: str, first_name: str, last_name: str = None):
        conn = self.get_connection()
        cursor = conn.cursor()
        cursor.execute('''
            INSERT OR IGNORE INTO users (user_id, username, first_name, last_name)
            VALUES (?, ?, ?, ?)
        ''', (user_id, username, first_name, last_name))
        conn.commit()
        conn.close()
    
    def get_user(self, user_id: int):
        conn = self.get_connection()
        cursor = conn.cursor()
        cursor.execute('SELECT * FROM users WHERE user_id = ?', (user_id,))
        user = cursor.fetchone()
        conn.close()
        return user
    
    def update_last_used(self, user_id: int):
        conn = self.get_connection()
        cursor = conn.cursor()
        cursor.execute('UPDATE users SET last_used = CURRENT_TIMESTAMP WHERE user_id = ?', (user_id,))
        conn.commit()
        conn.close()
    
    def set_banned(self, user_id: int, status: bool):
        conn = self.get_connection()
        cursor = conn.cursor()
        cursor.execute('UPDATE users SET is_banned = ? WHERE user_id = ?', (status, user_id))
        conn.commit()
        conn.close()
    
    def get_all_users(self):
        conn = self.get_connection()
        cursor = conn.cursor()
        cursor.execute('SELECT user_id, username, first_name, is_banned, join_date, total_sms FROM users')
        users = cursor.fetchall()
        conn.close()
        return users
    
    def get_stats(self, user_id: int):
        conn = self.get_connection()
        cursor = conn.cursor()
        cursor.execute('''
            SELECT total_sms, join_date, last_used
            FROM users WHERE user_id = ?
        ''', (user_id,))
        stats = cursor.fetchone()
        conn.close()
        return stats
    
    def add_sms_history(self, user_id: int, phone: str, message: str, api_used: str, status: str):
        conn = self.get_connection()
        cursor = conn.cursor()
        cursor.execute('''
            INSERT INTO sms_history (user_id, phone, message, api_used, status)
            VALUES (?, ?, ?, ?, ?)
        ''', (user_id, phone, message, api_used, status))
        cursor.execute('UPDATE users SET total_sms = total_sms + 1 WHERE user_id = ?', (user_id,))
        conn.commit()
        conn.close()
    
    def get_sms_history(self, user_id: int, limit: int = 10):
        conn = self.get_connection()
        cursor = conn.cursor()
        cursor.execute('''
            SELECT phone, status, date
            FROM sms_history
            WHERE user_id = ?
            ORDER BY date DESC
            LIMIT ?
        ''', (user_id, limit))
        history = cursor.fetchall()
        conn.close()
        return history
    
    def get_settings(self, key: str = None):
        conn = self.get_connection()
        cursor = conn.cursor()
        if key:
            cursor.execute('SELECT value FROM settings WHERE key = ?', (key,))
            result = cursor.fetchone()
            conn.close()
            return result[0] if result else None
        else:
            cursor.execute('SELECT key, value FROM settings')
            settings = dict(cursor.fetchall())
            conn.close()
            return settings
    
    def update_setting(self, key: str, value: str):
        conn = self.get_connection()
        cursor = conn.cursor()
        cursor.execute('''
            UPDATE settings SET value = ?, updated_at = CURRENT_TIMESTAMP
            WHERE key = ?
        ''', (value, key))
        conn.commit()
        conn.close()
    
    def add_blacklist(self, number: str, reason: str, added_by: int):
        conn = self.get_connection()
        cursor = conn.cursor()
        cursor.execute('''
            INSERT OR IGNORE INTO blacklist (number, reason, added_by)
            VALUES (?, ?, ?)
        ''', (number, reason, added_by))
        conn.commit()
        conn.close()
    
    def get_blacklist(self):
        conn = self.get_connection()
        cursor = conn.cursor()
        cursor.execute('SELECT number, reason FROM blacklist')
        result = cursor.fetchall()
        conn.close()
        return result
    
    def remove_blacklist(self, number: str):
        conn = self.get_connection()
        cursor = conn.cursor()
        cursor.execute('DELETE FROM blacklist WHERE number = ?', (number,))
        conn.commit()
        conn.close()
    
    def log_admin_action(self, admin_id: int, action: str, target_user: int = None, details: str = None):
        conn = self.get_connection()
        cursor = conn.cursor()
        cursor.execute('''
            INSERT INTO admin_logs (admin_id, action, target_user, details)
            VALUES (?, ?, ?, ?)
        ''', (admin_id, action, target_user, details))
        conn.commit()
        conn.close()
    
    def get_last_used(self, user_id: int):
        conn = self.get_connection()
        cursor = conn.cursor()
        cursor.execute('SELECT last_used FROM users WHERE user_id = ?', (user_id,))
        result = cursor.fetchone()
        conn.close()
        return result[0] if result else None

# ======================== MAIN BOT ========================
class ElevateXBomber:
    def __init__(self):
        self.db = Database()
        self.application = Application.builder().token(BOT_TOKEN).build()
        self.setup_handlers()
    
    def setup_handlers(self):
        self.application.add_handler(CommandHandler("start", self.start_command))
        self.application.add_handler(CommandHandler("help", self.help_command))
        self.application.add_handler(CommandHandler("stats", self.stats_command))
        self.application.add_handler(CommandHandler("history", self.history_command))
        self.application.add_handler(CommandHandler("admin", self.admin_command))
        self.application.add_handler(CallbackQueryHandler(self.button_callback))
        self.application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, self.handle_all_text))
    
    # ==================== FORCE JOIN ====================
    async def check_force_join(self, user_id: int, context: ContextTypes.DEFAULT_TYPE) -> Tuple[bool, Optional[str]]:
        try:
            channels = json.loads(self.db.get_settings('force_join_channels') or '["@elevatexbyzaid", "@elevatex_chat", "@exzhub"]')
            if not channels:
                return True, None
            for channel in channels:
                try:
                    chat_id = channel.strip()
                    if not chat_id.startswith('@'):
                        chat_id = '@' + chat_id
                    if not chat_id:
                        continue
                    member = await context.bot.get_chat_member(chat_id, user_id)
                    if member.status not in ['member', 'administrator', 'creator']:
                        return False, channel
                except Exception:
                    return False, channel
            return True, None
        except Exception as e:
            logger.error(f"Force join check error: {e}")
            return False, None
    
    async def get_join_keyboard(self):
        channels = json.loads(self.db.get_settings('force_join_channels') or '["@elevatexbyzaid", "@elevatex_chat", "@exzhub"]')
        keyboard = []
        for channel in channels:
            if channel.startswith('@'):
                clean_channel = channel.replace('@', '')
                keyboard.append([InlineKeyboardButton(f"📢 Join {channel}", url=f"https://t.me/{clean_channel}", style="primary")])
        keyboard.append([InlineKeyboardButton("✅ Done — I've Joined All", callback_data="check_join", style="success")])
        return InlineKeyboardMarkup(keyboard)
    
    # ==================== START COMMAND ====================
    async def start_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        user = update.effective_user
        user_id = user.id
        
        user_data = self.db.get_user(user_id)
        if user_data and user_data[4]:  # is_banned
            await update.message.reply_text(format_ui("❌ *You are banned!*\nContact @elevatexzaid"), parse_mode='Markdown')
            return
        
        self.db.add_user(user_id, user.username, user.first_name, user.last_name)
        
        # Check maintenance
        if self.db.get_settings('maintenance_mode') == 'true' and user_id != OWNER_ID:
            await update.message.reply_text(format_ui("⚠️ *Bot is under maintenance!*\nPlease try again later."), parse_mode='Markdown')
            return
        
        # Force Join Check
        joined, missing_channel = await self.check_force_join(user_id, context)
        safe_name = user.first_name.replace('_', '\\_').replace('*', '\\*').replace('[', '').replace('`', '') if user.first_name else "User"
        
        if not joined:
            keyboard = await self.get_join_keyboard()
            channels = json.loads(self.db.get_settings('force_join_channels') or '["@elevatexbyzaid", "@elevatex_chat", "@exzhub"]')
            safe_channels = [ch.replace('_', '\\_') for ch in channels]
            
            content = (
                f"👋 *Welcome {safe_name}!*\n\n"
                f"⚠️ *Please join our channels first:*\n\n" +
                "\n".join([f"• {ch}" for ch in safe_channels]) +
                f"\n\n✅ *After joining all channels*\n"
                f"Click the button Done— I've Joined All ✅:\n\n"
                f"🔹 *100% FREE - No Credits Payment Needed*\n"
            )
            await update.message.reply_text(format_ui(content), reply_markup=keyboard, parse_mode='Markdown')
            return
        
        await self.show_main_menu(update, context, user_id)
    
    # ==================== MAIN MENU ====================
    async def show_main_menu(self, update, context, user_id: int, edit: bool = False):
        user_data = self.db.get_user(user_id)
        if not user_data:
            return
        
        stats = self.db.get_stats(user_id)
        max_sms = int(self.db.get_settings('max_sms_limit') or MAX_SMS_LIMIT)
        cooldown = self.db.get_settings('cooldown_seconds') or 10
        
        keyboard = [
            [InlineKeyboardButton("💣 Send SMS", callback_data="send_bomber", style="danger"), 
             InlineKeyboardButton("📊 Dashboard", callback_data="dashboard", style="primary")],
            [InlineKeyboardButton("📢 Updates", url="https://t.me/elevatexbyzaid", style="success"), 
             InlineKeyboardButton("💬 Chat Group", url="https://t.me/elevatex_chat", style="success")]
        ]
        if user_id == OWNER_ID or user_id in ADMIN_IDS:
            keyboard.append([InlineKeyboardButton("⚙️ Admin Panel", callback_data="admin_panel", style="danger")])
        
        safe_name = str(user_data[2]).replace('_', '\\_').replace('*', '\\*') if user_data[2] else "User"
        
        content = (
            f"👋 *Welcome {safe_name}!*\n\n"
            f"📱 Total SMS: `{stats[0] if stats else 0}`\n"
            f"📅 Joined: {stats[1] if stats else 'N/A'}\n\n"
            f"━━━━━━━━━━━━━━━━━━━━━━\n"
            f"🔹 *100% FREE - No Credits Needed*\n"
            f"🔹 *Max {max_sms} SMS per request*\n"
            f"🔹 *Cooldown: {cooldown} seconds*\n"
            f"🔹 *Bulk SMS Available*\n\n"
            f"Select an option below:"
        )
        
        if edit:
            await update.callback_query.edit_message_text(
                format_ui(content),
                reply_markup=InlineKeyboardMarkup(keyboard),
                parse_mode='Markdown'
            )
        else:
            await update.message.reply_text(
                format_ui(content),
                reply_markup=InlineKeyboardMarkup(keyboard),
                parse_mode='Markdown'
            )
    
    # ==================== BUTTON CALLBACK ====================
    async def button_callback(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        query = update.callback_query
        try:
            await query.answer()
        except:
            pass
        
        user_id = query.from_user.id
        data = query.data
        
        user_data = self.db.get_user(user_id)
        if user_data and user_data[4]:  # banned
            await query.edit_message_text(format_ui("❌ *You are banned!*\nContact @elevatexzaid"), parse_mode='Markdown')
            return
        
        if data == "check_join":
            joined, missing_channel = await self.check_force_join(user_id, context)
            if joined:
                await self.show_main_menu(update, context, user_id, edit=True)
            else:
                keyboard = await self.get_join_keyboard()
                channels = json.loads(self.db.get_settings('force_join_channels') or '["@elevatexbyzaid", "@elevatex_chat", "@exzhub"]')
                safe_channels = [ch.replace('_', '\\_') for ch in channels]
                safe_missing = missing_channel.replace('_', '\\_') if missing_channel else ""
                
                content = (
                    f"❌ *You haven't joined all channels yet!*\n\n"
                    f"Please join:\n" + "\n".join([f"• {ch}" for ch in safe_channels]) +
                    f"\n\n*Missing: {safe_missing}*\n\n"
                    f"✅ Click the button below after joining:"
                )
                await query.edit_message_text(
                    format_ui(content),
                    reply_markup=keyboard,
                    parse_mode='Markdown'
                )
            return
        
        elif data == "main_menu":
            await self.show_main_menu(update, context, user_id, edit=True)
            return
        
        elif data == "send_bomber":
            await self.show_bomber_menu(update, context, user_id, edit=True)
        
        elif data.startswith("bomb_"):
            count = data.replace("bomb_", "")
            if count == "custom":
                context.user_data['expecting_custom_count'] = True
                content = f"🔢 *Enter custom count (1-{MAX_SMS_LIMIT}):*"
                await query.edit_message_text(format_ui(content), parse_mode='Markdown')
                return
            
            count = int(count)
            context.user_data['bomb_count'] = count
            context.user_data['expecting_phone'] = True
            
            content = (
                f"📱 *Enter phone number:*\n\n"
                f"Count: `{count}` SMS\n"
                f"Example: `+923001234567`\n\n"
                f"⚡ *100% FREE - No Credits Needed*\n"
                f"📊 Max: {MAX_SMS_LIMIT} SMS per request\n\n"
                f"Type the number to start bombing:"
            )
            await query.edit_message_text(format_ui(content), parse_mode='Markdown')
        
        elif data == "bulk_numbers":
            context.user_data['expecting_bulk'] = True
            content = (
                f"📊 *Enter bulk numbers:*\n\n"
                f"One number per line:\n"
                f"`+923001234567\n+923001234568`\n\n"
                f"⚡ *100% FREE - No Credits Needed*"
            )
            await query.edit_message_text(format_ui(content), parse_mode='Markdown')
        
        elif data == "dashboard":
            await self.show_dashboard(update, context, user_id, edit=True)
        
        # Admin Panel
        elif data == "admin_panel":
            if user_id == OWNER_ID or user_id in ADMIN_IDS:
                await self.show_admin_panel(update, context, user_id, edit=True)
        
        elif data == "admin_users":
            if user_id == OWNER_ID or user_id in ADMIN_IDS:
                await self.show_admin_users(update, context, user_id, edit=True)
        
        elif data == "admin_settings":
            if user_id == OWNER_ID or user_id in ADMIN_IDS:
                await self.show_admin_settings(update, context, user_id, edit=True)
        
        elif data == "admin_stats":
            if user_id == OWNER_ID or user_id in ADMIN_IDS:
                await self.show_admin_stats(update, context, user_id, edit=True)
        
        elif data == "admin_blacklist":
            if user_id == OWNER_ID or user_id in ADMIN_IDS:
                await self.show_admin_blacklist(update, context, user_id, edit=True)
        
        elif data == "admin_ban":
            if user_id == OWNER_ID or user_id in ADMIN_IDS:
                context.user_data['expecting_ban_user'] = True
                await query.edit_message_text(format_ui("🚫 *Ban/Unban User*\n\nEnter user ID:\nExample: `8204336028`"), parse_mode='Markdown')
        
        elif data == "admin_broadcast":
            if user_id == OWNER_ID or user_id in ADMIN_IDS:
                context.user_data['expecting_broadcast'] = True
                await query.edit_message_text(format_ui("📢 *Broadcast Message*\n\nType your message below."), parse_mode='Markdown')
        
        elif data == "admin_toggle_maintenance":
            if user_id == OWNER_ID or user_id in ADMIN_IDS:
                current = self.db.get_settings('maintenance_mode')
                new = 'false' if current == 'true' else 'true'
                self.db.update_setting('maintenance_mode', new)
                await query.edit_message_text(
                    format_ui(f"✅ *Maintenance {'ENABLED' if new == 'true' else 'DISABLED'}!*"),
                    reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🔙 Back", callback_data="admin_settings", style="primary")]]),
                    parse_mode='Markdown'
                )
        
        elif data == "admin_set_cooldown":
            if user_id == OWNER_ID or user_id in ADMIN_IDS:
                context.user_data['expecting_cooldown'] = True
                await query.edit_message_text(format_ui("⏱ *Set Cooldown Seconds*\n\nEnter cooldown in seconds for all users:"), parse_mode='Markdown')
        
        elif data == "admin_set_max_sms":
            if user_id == OWNER_ID or user_id in ADMIN_IDS:
                context.user_data['expecting_max_sms'] = True
                await query.edit_message_text(format_ui(f"📊 *Set Max SMS Limit*\n\nEnter max SMS per request (1-{MAX_SMS_LIMIT}):"), parse_mode='Markdown')
        
        elif data == "admin_toggle_bulk":
            if user_id == OWNER_ID or user_id in ADMIN_IDS:
                current = self.db.get_settings('allow_bulk')
                new = 'false' if current == 'true' else 'true'
                self.db.update_setting('allow_bulk', new)
                await query.edit_message_text(
                    format_ui(f"✅ *Bulk SMS {'ENABLED' if new == 'true' else 'DISABLED'}!*"),
                    reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🔙 Back", callback_data="admin_settings", style="primary")]]),
                    parse_mode='Markdown'
                )
        
        elif data == "admin_channels":
            if user_id == OWNER_ID or user_id in ADMIN_IDS:
                await self.show_admin_channels(update, context, user_id, edit=True)
        
        elif data.startswith("admin_remove_channel_"):
            if user_id == OWNER_ID or user_id in ADMIN_IDS:
                channel = data.replace("admin_remove_channel_", "")
                channels = json.loads(self.db.get_settings('force_join_channels') or '["@elevatexbyzaid", "@elevatex_chat", "@exzhub"]')
                if channel in channels:
                    channels.remove(channel)
                    self.db.update_setting('force_join_channels', json.dumps(channels))
                await query.edit_message_text(
                    format_ui("✅ *Channel removed!*"),
                    reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🔙 Back", callback_data="admin_channels", style="primary")]]),
                    parse_mode='Markdown'
                )
        
        elif data == "admin_add_channel":
            if user_id == OWNER_ID or user_id in ADMIN_IDS:
                context.user_data['expecting_channel'] = True
                await query.edit_message_text(format_ui("➕ *Add Channel*\n\nEnter channel username:\nExample: `@channel_name`"), parse_mode='Markdown')
        
        elif data == "admin_add_blacklist":
            if user_id == OWNER_ID or user_id in ADMIN_IDS:
                context.user_data['expecting_blacklist'] = True
                await query.edit_message_text(format_ui("➕ *Add to Blacklist*\n\nFormat: `number reason`\nExample: `+923001234567 Spam`"), parse_mode='Markdown')
        
        elif data == "admin_remove_blacklist":
            if user_id == OWNER_ID or user_id in ADMIN_IDS:
                context.user_data['expecting_remove_blacklist'] = True
                await query.edit_message_text(format_ui("🚫 *Remove from Blacklist*\n\nEnter the number to remove:\nExample: `+923001234567`"), parse_mode='Markdown')
    
    # ==================== BOMBER MENU ====================
    async def show_bomber_menu(self, update, context, user_id: int, edit: bool = False):
        allow_bulk = self.db.get_settings('allow_bulk') == 'true'
        max_sms = int(self.db.get_settings('max_sms_limit') or MAX_SMS_LIMIT)
        
        keyboard = [
            [InlineKeyboardButton("📱 1 SMS", callback_data="bomb_1", style="danger"), 
             InlineKeyboardButton("📱 5 SMS", callback_data="bomb_5", style="danger")],
            [InlineKeyboardButton("📱 10 SMS", callback_data="bomb_10", style="danger"), 
             InlineKeyboardButton("📱 25 SMS", callback_data="bomb_25", style="danger")],
            [InlineKeyboardButton(f"📱 {max_sms} SMS", callback_data=f"bomb_{max_sms}", style="danger"), 
             InlineKeyboardButton("🔢 Custom", callback_data="bomb_custom", style="success")]
        ]
        if allow_bulk:
            keyboard.append([InlineKeyboardButton("📊 Bulk Numbers", callback_data="bulk_numbers", style="primary")])
        keyboard.append([InlineKeyboardButton("🔙 Back", callback_data="main_menu", style="primary")])
        
        content = (
            f"💣 *Select SMS Count*\n\n"
            f"⚡ *100% FREE - No Credits Needed*\n"
            f"📊 Max: {max_sms} SMS per request\n"
            f"⏱ Cooldown: {self.db.get_settings('cooldown_seconds') or 10} seconds\n\n"
            f"Select count below:"
        )
        
        if edit:
            await update.callback_query.edit_message_text(
                format_ui(content),
                reply_markup=InlineKeyboardMarkup(keyboard),
                parse_mode='Markdown'
            )
        else:
            await update.message.reply_text(
                format_ui(content),
                reply_markup=InlineKeyboardMarkup(keyboard),
                parse_mode='Markdown'
            )
    
    # ==================== DASHBOARD ====================
    async def show_dashboard(self, update, context, user_id: int, edit: bool = False):
        stats = self.db.get_stats(user_id)
        if not stats:
            return
        history = self.db.get_sms_history(user_id)
        
        content = (
            f"📊 *Dashboard*\n\n"
            f"📱 Total SMS: `{stats[0]}`\n"
            f"📅 Joined: {stats[1]}\n"
            f"🕐 Last Used: {stats[2] if stats[2] else 'Never'}\n\n"
            f"*Recent Activity:*\n"
        )
        if history:
            for h in history[:5]:
                content += f"• {h[0]} - {'✅' if h[1] == 'Sent' else '❌'} ({h[2].split()[0]})\n"
        else:
            content += "• No activity yet\n"
        
        keyboard = [[InlineKeyboardButton("🔙 Back", callback_data="main_menu", style="primary")]]
        if edit:
            await update.callback_query.edit_message_text(
                format_ui(content),
                reply_markup=InlineKeyboardMarkup(keyboard),
                parse_mode='Markdown'
            )
        else:
            await update.message.reply_text(
                format_ui(content),
                reply_markup=InlineKeyboardMarkup(keyboard),
                parse_mode='Markdown'
            )
    
    # ==================== TEXT HANDLER ====================
    async def handle_all_text(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        ud = context.user_data
        
        if ud.get('expecting_phone'):
            await self.handle_phone(update, context)
        elif ud.get('expecting_custom_count'):
            await self.handle_custom_count(update, context)
        elif ud.get('expecting_bulk'):
            await self.handle_bulk(update, context)
        elif ud.get('expecting_channel'):
            await self.handle_channel(update, context)
        elif ud.get('expecting_ban_user'):
            await self.handle_ban_user(update, context)
        elif ud.get('expecting_broadcast'):
            await self.handle_broadcast(update, context)
        elif ud.get('expecting_blacklist'):
            await self.handle_blacklist(update, context)
        elif ud.get('expecting_remove_blacklist'):
            await self.handle_remove_blacklist(update, context)
        elif ud.get('expecting_cooldown'):
            try:
                seconds = int(update.message.text.strip())
                if seconds < 1:
                    seconds = 1
                self.db.update_setting('cooldown_seconds', str(seconds))
                await update.message.reply_text(
                    format_ui(f"✅ Cooldown set to `{seconds}` seconds!"),
                    parse_mode='Markdown'
                )
            except:
                await update.message.reply_text(format_ui("❌ Invalid number!"), parse_mode='Markdown')
            ud['expecting_cooldown'] = False
        elif ud.get('expecting_max_sms'):
            try:
                limit = int(update.message.text.strip())
                if limit < 1 or limit > MAX_SMS_LIMIT:
                    await update.message.reply_text(format_ui(f"❌ Please enter a number between 1 and {MAX_SMS_LIMIT}!"), parse_mode='Markdown')
                    return
                self.db.update_setting('max_sms_limit', str(limit))
                await update.message.reply_text(
                    format_ui(f"✅ Max SMS limit set to `{limit}`!"),
                    parse_mode='Markdown'
                )
            except:
                await update.message.reply_text(format_ui("❌ Invalid number!"), parse_mode='Markdown')
            ud['expecting_max_sms'] = False
        else:
            # Handle any other text
            await update.message.reply_text(
                format_ui("❌ *Unknown command*\n\nUse /start to return to menu."),
                parse_mode='Markdown'
            )
    
    # ==================== SMS PROCESSING ====================
    async def handle_phone(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        context.user_data['expecting_phone'] = False
        user_id = update.effective_user.id
        phone = update.message.text.strip()
        
        if not re.match(r'^\+?[0-9]{10,15}$', phone):
            await update.message.reply_text(format_ui("❌ *Invalid Phone Number!*"), parse_mode='Markdown')
            return
        
        count = context.user_data.get('bomb_count', 1)
        max_sms = int(self.db.get_settings('max_sms_limit') or MAX_SMS_LIMIT)
        count = max(MIN_SMS_LIMIT, min(count, max_sms))
        
        user_data = self.db.get_user(user_id)
        if not user_data:
            await update.message.reply_text(format_ui("❌ *User not found!*"), parse_mode='Markdown')
            return
        
        # Check cooldown
        cooldown = int(self.db.get_settings('cooldown_seconds') or 10)
        last_used = self.db.get_last_used(user_id)
        
        if last_used:
            try:
                last_time = datetime.strptime(last_used, '%Y-%m-%d %H:%M:%S')
                time_diff = (datetime.utcnow() - last_time).total_seconds()
                if time_diff < cooldown:
                    remaining = int(cooldown - time_diff)
                    keyboard = [[InlineKeyboardButton("🔙 Back", callback_data="main_menu", style="primary")]]
                    content = f"⏳ *Please wait {remaining} seconds before next request!*"
                    await update.message.reply_text(
                        format_ui(content),
                        reply_markup=InlineKeyboardMarkup(keyboard),
                        parse_mode='Markdown'
                    )
                    return
            except Exception as e:
                logger.error(f"Cooldown check error: {e}")
        
        await self.process_sms(update, context, user_id, phone, count)
        context.user_data['bomb_count'] = 1
    
    async def handle_custom_count(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        context.user_data['expecting_custom_count'] = False
        try:
            max_sms = int(self.db.get_settings('max_sms_limit') or MAX_SMS_LIMIT)
            count = int(update.message.text.strip())
            count = max(MIN_SMS_LIMIT, min(count, max_sms))
            context.user_data['bomb_count'] = count
            context.user_data['expecting_phone'] = True
            await update.message.reply_text(
                format_ui(f"✅ *Count set to `{count}` SMS*\n\nNow enter the phone number:"),
                parse_mode='Markdown'
            )
        except:
            await update.message.reply_text(
                format_ui(f"❌ *Invalid Number!*\n\nPlease enter a number between 1-{MAX_SMS_LIMIT}."),
                parse_mode='Markdown'
            )
    
    async def handle_bulk(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        context.user_data['expecting_bulk'] = False
        user_id = update.effective_user.id
        
        allow_bulk = self.db.get_settings('allow_bulk') == 'true'
        if not allow_bulk:
            await update.message.reply_text(format_ui("❌ *Bulk SMS is disabled by admin!*"), parse_mode='Markdown')
            return
        
        numbers = [n.strip() for n in update.message.text.strip().split('\n') if n.strip()]
        
        valid = [n for n in numbers if re.match(r'^\+?[0-9]{10,15}$', n)]
        if not valid:
            await update.message.reply_text(format_ui("❌ *No valid numbers found!*"), parse_mode='Markdown')
            return
        
        await update.message.reply_text(
            format_ui(f"💣 *Sending Bulk SMS*\n\nTotal: {len(valid)} numbers\n⏳ Processing..."),
            parse_mode='Markdown'
        )
        
        sent = 0
        failed = 0
        for num in valid:
            if await self.process_sms(update, context, user_id, num, 1, bulk=True):
                sent += 1
            else:
                failed += 1
            await asyncio.sleep(0.5)
        
        await update.message.reply_text(
            format_ui(f"✅ *Bulk SMS Complete!*\n\n✅ Sent: `{sent}`\n❌ Failed: `{failed}`"),
            parse_mode='Markdown'
        )
    
    async def process_sms(self, update, context, user_id, phone, count=1, bulk=False):
        try:
            max_sms = int(self.db.get_settings('max_sms_limit') or MAX_SMS_LIMIT)
            count = max(MIN_SMS_LIMIT, min(count, max_sms))
            
            # Check blacklist
            blacklist = self.db.get_blacklist()
            for num, _ in blacklist:
                if phone == num:
                    if not bulk:
                        await update.message.reply_text(format_ui(f"❌ *Number {phone} is blacklisted!*"), parse_mode='Markdown')
                    return False
            
            # Send API request
            params = {'phone': phone, 'count': count}
            async with aiohttp.ClientSession() as session:
                try:
                    async with session.get(API_URL, params=params, timeout=30) as response:
                        status = 'Sent' if response.status == 200 else f'Failed ({response.status})'
                except Exception as e:
                    status = f'Failed'
            
            # Update database
            self.db.add_sms_history(user_id, phone, f'Bomb {count} SMS', 'ElevateX API', status)
            self.db.update_last_used(user_id)
            
            if not bulk:
                content = (
                    f"✅ *SMS Bomb Sent!*\n\n"
                    f"📱 Target: `{phone}`\n"
                    f"💣 Count: `{count}` SMS\n"
                    f"📊 Status: {status}\n"
                    f"📱 Total Sent: `{self.db.get_user(user_id)[5] if self.db.get_user(user_id) else 0}`\n\n"
                    f"Use /start to return to menu"
                )
                await update.message.reply_text(format_ui(content), parse_mode='Markdown')
            return True
        except Exception as e:
            logger.error(f"SMS process error: {e}")
            if not bulk:
                await update.message.reply_text(format_ui("❌ *Error sending SMS!*"), parse_mode='Markdown')
            return False
    
    # ==================== ADMIN PANEL ====================
    async def show_admin_panel(self, update, context, user_id: int, edit: bool = False):
        keyboard = [
            [InlineKeyboardButton("👥 Users", callback_data="admin_users", style="primary"),
             InlineKeyboardButton("⚙️ Settings", callback_data="admin_settings", style="primary")],
            [InlineKeyboardButton("📢 Broadcast", callback_data="admin_broadcast", style="success"),
             InlineKeyboardButton("📊 Analytics", callback_data="admin_stats", style="success")],
            [InlineKeyboardButton("🚫 Blacklist", callback_data="admin_blacklist", style="danger"),
             InlineKeyboardButton("🔙 Back", callback_data="main_menu", style="primary")]
        ]
        
        users = self.db.get_all_users()
        
        content = (
            f"⚙️ *Admin Panel*\n\n"
            f"👥 Total Users: `{len(users)}`\n"
            f"🚫 Banned: `{sum(1 for u in users if u[3])}`\n\n"
            f"👇 Select an option:"
        )
        
        if edit:
            await update.callback_query.edit_message_text(
                format_ui(content),
                reply_markup=InlineKeyboardMarkup(keyboard),
                parse_mode='Markdown'
            )
        else:
            await update.message.reply_text(
                format_ui(content),
                reply_markup=InlineKeyboardMarkup(keyboard),
                parse_mode='Markdown'
            )
    
    async def show_admin_users(self, update, context, user_id: int, edit: bool = False):
        users = self.db.get_all_users()
        content = f"👥 *User Management*\n\nTotal: `{len(users)}` users\n\n*Recent Users:*\n"
        for u in users[-10:]:
            safe_name = str(u[2]).replace('_', '\\_').replace('*', '\\*').replace('[', '').replace('`', '') if u[2] else "User"
            safe_user = str(u[1]).replace('_', '\\_') if u[1] else "None"
            content += f"• {safe_name} (@{safe_user}) - {u[5]} SMS{'🚫' if u[3] else ''}\n"
        
        keyboard = [
            [InlineKeyboardButton("🚫 Ban/Unban", callback_data="admin_ban", style="danger")],
            [InlineKeyboardButton("🔙 Back", callback_data="admin_panel", style="primary")]
        ]
        
        if edit:
            await update.callback_query.edit_message_text(
                format_ui(content),
                reply_markup=InlineKeyboardMarkup(keyboard),
                parse_mode='Markdown'
            )
        else:
            await update.message.reply_text(
                format_ui(content),
                reply_markup=InlineKeyboardMarkup(keyboard),
                parse_mode='Markdown'
            )
    
    async def show_admin_settings(self, update, context, user_id: int, edit: bool = False):
        settings = self.db.get_settings()
        maintenance = settings.get('maintenance_mode', 'false') == 'true'
        allow_bulk = settings.get('allow_bulk', 'true') == 'true'
        channels = json.loads(settings.get('force_join_channels', '["@elevatexbyzaid", "@elevatex_chat", "@exzhub"]'))
        
        keyboard = [
            [InlineKeyboardButton(f"{'🟢' if maintenance else '🔴'} Toggle Maint.", callback_data="admin_toggle_maintenance", style="primary"),
             InlineKeyboardButton("📢 Channels", callback_data="admin_channels", style="success")],
            [InlineKeyboardButton(f"{'✅' if allow_bulk else '❌'} Toggle Bulk", callback_data="admin_toggle_bulk", style="primary"),
             InlineKeyboardButton("⏱ Set Cooldown", callback_data="admin_set_cooldown", style="primary")],
            [InlineKeyboardButton("📊 Set Max SMS", callback_data="admin_set_max_sms", style="primary"),
             InlineKeyboardButton("🔙 Back", callback_data="admin_panel", style="primary")]
        ]
        
        content = (
            f"⚙️ *Settings*\n\n"
            f"🛠 Maintenance: {'ON' if maintenance else 'OFF'}\n"
            f"⏱ Cooldown: `{settings.get('cooldown_seconds', '10')}` seconds\n"
            f"📊 Max SMS: `{settings.get('max_sms_limit', MAX_SMS_LIMIT)}`\n"
            f"📊 Bulk SMS: {'✅ Enabled' if allow_bulk else '❌ Disabled'}\n"
            f"📢 Channels: {len(channels)} channels\n"
        )
        
        if edit:
            await update.callback_query.edit_message_text(
                format_ui(content),
                reply_markup=InlineKeyboardMarkup(keyboard),
                parse_mode='Markdown'
            )
        else:
            await update.message.reply_text(
                format_ui(content),
                reply_markup=InlineKeyboardMarkup(keyboard),
                parse_mode='Markdown'
            )
    
    async def show_admin_stats(self, update, context, user_id: int, edit: bool = False):
        users = self.db.get_all_users()
        
        conn = self.db.get_connection()
        cursor = conn.cursor()
        total_sms = cursor.execute('SELECT COUNT(*) FROM sms_history').fetchone()[0]
        conn.close()
        
        content = (
            f"📊 *Analytics Dashboard*\n\n"
            f"👥 Total Users: `{len(users)}`\n"
            f"🚫 Banned: `{sum(1 for u in users if u[3])}`\n"
            f"📱 Total SMS: `{total_sms}`\n"
            f"📱 Avg SMS/User: `{total_sms // len(users) if len(users) > 0 else 0}`\n"
        )
        
        keyboard = [[InlineKeyboardButton("🔙 Back", callback_data="admin_panel", style="primary")]]
        
        if edit:
            await update.callback_query.edit_message_text(
                format_ui(content),
                reply_markup=InlineKeyboardMarkup(keyboard),
                parse_mode='Markdown'
            )
        else:
            await update.message.reply_text(
                format_ui(content),
                reply_markup=InlineKeyboardMarkup(keyboard),
                parse_mode='Markdown'
            )
    
    async def show_admin_blacklist(self, update, context, user_id: int, edit: bool = False):
        blacklist = self.db.get_blacklist()
        content = f"🚫 *Blacklist*\n\n"
        if blacklist:
            for num, reason in blacklist[:20]:
                content += f"• {num} - {reason}\n"
        else:
            content += "Empty\n"
        
        keyboard = [
            [InlineKeyboardButton("➕ Add Number", callback_data="admin_add_blacklist", style="danger"),
             InlineKeyboardButton("➖ Remove Number", callback_data="admin_remove_blacklist", style="success")],
            [InlineKeyboardButton("🔙 Back", callback_data="admin_panel", style="primary")]
        ]
        
        if edit:
            await update.callback_query.edit_message_text(
                format_ui(content),
                reply_markup=InlineKeyboardMarkup(keyboard),
                parse_mode='Markdown'
            )
        else:
            await update.message.reply_text(
                format_ui(content),
                reply_markup=InlineKeyboardMarkup(keyboard),
                parse_mode='Markdown'
            )
    
    async def show_admin_channels(self, update, context, user_id: int, edit: bool = False):
        channels = json.loads(self.db.get_settings('force_join_channels') or '["@elevatexbyzaid", "@elevatex_chat", "@exzhub"]')
        keyboard = []
        for ch in channels:
            keyboard.append([InlineKeyboardButton(f"❌ Remove {ch}", callback_data=f"admin_remove_channel_{ch}", style="success")])
        keyboard.append([InlineKeyboardButton("➕ Add Channel", callback_data="admin_add_channel", style="success")])
        keyboard.append([InlineKeyboardButton("🔙 Back", callback_data="admin_settings", style="primary")])
        
        safe_channels = [ch.replace('_', '\\_') for ch in channels]
        content = f"📢 *Manage Channels*\n\nCurrent channels:\n" + "\n".join([f"• {ch}" for ch in safe_channels]) if safe_channels else "No channels"
        
        if edit:
            await update.callback_query.edit_message_text(
                format_ui(content),
                reply_markup=InlineKeyboardMarkup(keyboard),
                parse_mode='Markdown'
            )
        else:
            await update.message.reply_text(
                format_ui(content),
                reply_markup=InlineKeyboardMarkup(keyboard),
                parse_mode='Markdown'
            )
    
    # ==================== ADMIN INPUT HANDLERS ====================
    async def handle_channel(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        context.user_data['expecting_channel'] = False
        channel = update.message.text.strip()
        if not channel.startswith('@'):
            channel = '@' + channel
        channels = json.loads(self.db.get_settings('force_join_channels') or '["@elevatexbyzaid", "@elevatex_chat", "@exzhub"]')
        if channel not in channels:
            channels.append(channel)
            self.db.update_setting('force_join_channels', json.dumps(channels))
            safe_ch = channel.replace('_', '\\_')
            await update.message.reply_text(
                format_ui(f"✅ *Channel {safe_ch} added!*"),
                parse_mode='Markdown'
            )
        else:
            await update.message.reply_text(format_ui("❌ *Channel already exists!*"), parse_mode='Markdown')
    
    async def handle_ban_user(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        context.user_data['expecting_ban_user'] = False
        try:
            target_id = int(update.message.text.strip())
            user_data = self.db.get_user(target_id)
            if user_data:
                new_status = not user_data[4]
                self.db.set_banned(target_id, new_status)
                status = "banned" if new_status else "unbanned"
                self.db.log_admin_action(update.effective_user.id, 'ban_user', target_id, status)
                await update.message.reply_text(
                    format_ui(f"✅ *User `{target_id}` {status}!*"),
                    parse_mode='Markdown'
                )
                try:
                    await context.bot.send_message(
                        target_id,
                        format_ui(f"🚫 *You have been {status} by admin.*\n\nContact @elevatexzaid for details."),
                        parse_mode='Markdown'
                    )
                except:
                    pass
            else:
                await update.message.reply_text(format_ui("❌ *User not found!*"), parse_mode='Markdown')
        except:
            await update.message.reply_text(format_ui("❌ *Invalid ID!*"), parse_mode='Markdown')
    
    async def handle_broadcast(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        context.user_data['expecting_broadcast'] = False
        message = update.message.text
        users = self.db.get_all_users()
        sent = 0
        failed = 0
        
        await update.message.reply_text(
            format_ui(f"📢 *Broadcast started...*\nTotal: `{len(users)}` users"),
            parse_mode='Markdown'
        )
        
        for u in users:
            try:
                await context.bot.send_message(u[0], message, parse_mode='Markdown')
                sent += 1
            except:
                failed += 1
            await asyncio.sleep(0.05)
        
        self.db.log_admin_action(update.effective_user.id, 'broadcast', None, f'Sent to {sent}, failed {failed}')
        
        await update.message.reply_text(
            format_ui(f"✅ *Broadcast Complete!*\n\n✅ Sent: `{sent}`\n❌ Failed: `{failed}`"),
            parse_mode='Markdown'
        )
    
    async def handle_blacklist(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        context.user_data['expecting_blacklist'] = False
        try:
            parts = update.message.text.strip().split()
            number = parts[0]
            reason = ' '.join(parts[1:]) if len(parts) > 1 else 'No reason'
            if not re.match(r'^\+?[0-9]{10,15}$', number):
                await update.message.reply_text(format_ui("❌ *Invalid number format!*"), parse_mode='Markdown')
                return
            self.db.add_blacklist(number, reason, update.effective_user.id)
            self.db.log_admin_action(update.effective_user.id, 'add_blacklist', None, f'{number} - {reason}')
            await update.message.reply_text(
                format_ui(f"✅ *Added `{number}` to blacklist!*\nReason: {reason}"),
                parse_mode='Markdown'
            )
        except:
            await update.message.reply_text(
                format_ui("❌ *Invalid format!*\n\nUse: `+923001234567 reason`"),
                parse_mode='Markdown'
            )
    
    async def handle_remove_blacklist(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        context.user_data['expecting_remove_blacklist'] = False
        try:
            number = update.message.text.strip()
            self.db.remove_blacklist(number)
            self.db.log_admin_action(update.effective_user.id, 'remove_blacklist', None, number)
            await update.message.reply_text(
                format_ui(f"✅ *Removed `{number}` from blacklist!*"),
                parse_mode='Markdown'
            )
        except:
            await update.message.reply_text(
                format_ui("❌ *Invalid number format!*"),
                parse_mode='Markdown'
            )
    
    # ==================== COMMANDS ====================
    async def help_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        content = (
            f"📚 *Help Menu*\n\n"
            f"*Commands:*\n"
            f"• /start - Open the bot\n"
            f"• /stats - View your stats\n"
            f"• /history - View SMS history\n"
            f"• /admin - Admin panel\n"
            f"• /help - Show this message\n\n"
            f"*How to use:*\n"
            f"1. Join all required channels\n"
            f"2. Enter phone number\n"
            f"3. Select SMS count\n\n"
            f"⚡ *100% FREE - No Credits Needed*\n\n"
            f"👑 Owner: @elevatexzaid"
        )
        await update.message.reply_text(format_ui(content), parse_mode='Markdown')
    
    async def stats_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        user_id = update.effective_user.id
        stats = self.db.get_stats(user_id)
        if not stats:
            return
        
        content = (
            f"📊 *Your Statistics*\n\n"
            f"📱 Total SMS: `{stats[0]}`\n"
            f"📅 Joined: {stats[1]}\n"
            f"🕐 Last Used: {stats[2] if stats[2] else 'Never'}\n\n"
            f"⚡ *100% FREE - No Credits Needed*"
        )
        await update.message.reply_text(format_ui(content), parse_mode='Markdown')
    
    async def history_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        user_id = update.effective_user.id
        history = self.db.get_sms_history(user_id)
        content = f"📜 *SMS History*\n\n"
        if history:
            for h in history[:10]:
                content += f"• {h[0]} - {'✅' if h[1] == 'Sent' else '❌'} ({h[2].split()[0]})\n"
        else:
            content += "No history yet\n"
        await update.message.reply_text(format_ui(content), parse_mode='Markdown')
    
    async def admin_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        user_id = update.effective_user.id
        if user_id == OWNER_ID or user_id in ADMIN_IDS:
            await self.show_admin_panel(update, context, user_id, edit=False)
        else:
            await update.message.reply_text(format_ui("❌ *Unauthorized!*"), parse_mode='Markdown')
    
    # ==================== RUN ====================
    def run(self):
        print("🤖 ElevateX FREE Bomber is running...")
        print(f"👑 Owner: {OWNER_ID}")
        print(f"📢 Force Join Channels:")
        channels = json.loads(self.db.get_settings('force_join_channels') or '["@elevatexbyzaid", "@elevatex_chat", "@exzhub"]')
        for ch in channels:
            print(f"   • {ch}")
        print("⚡ 100% FREE - No Credits Needed!")
        print("🚀 Bot is ready!")
        self.application.run_polling()

if __name__ == '__main__':
    if sys.platform == 'win32':
        asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
    bot = ElevateXBomber()
    bot.run()