import asyncio
import logging
import re
import os
import json
import urllib.parse
import aiohttp
from datetime import datetime, timedelta
from aiogram import Bot, Dispatcher, types, F
from aiogram.filters import Command
from aiogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery
from config import BOT_TOKEN, SUPER_ADMIN_ID
from db import db
from worker import worker_manager

# Temporary state storage for admin actions
admin_waiting_for = {}

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

bot = Bot(token=BOT_TOKEN)
dp = Dispatcher()

# Channel configuration (3 required channels)
CHANNEL_1 = "@aerithiacheck33r"
CHANNEL_2 = "@aerithiaproject"
CHANNEL_3 = "@aerithiayedek"  # Private channel - bot must be admin

# Log group
LOG_GROUP_ID = -5049208474

# Admin IDs
SUPERADMIN_IDS = [7921860052]  # Super admins have full access
ADMIN_IDS = [7921860052, 1341605664, 7861694290]  # Regular admins + super admins

async def check_user_membership(user_id: int) -> tuple:
    """Check if user is member of all 3 required channels"""
    is_in_channel1 = False
    is_in_channel2 = False
    is_in_channel3 = False

    try:
        # Check channel 1 membership
        try:
            logger.info(f"Checking channel 1 membership for user {user_id}...")
            member = await bot.get_chat_member(chat_id=CHANNEL_1, user_id=user_id)
            logger.info(f"Channel 1 status: {member.status}")
            if member.status in ['member', 'administrator', 'creator']:
                is_in_channel1 = True
        except Exception as e:
            logger.error(f"Channel 1 check error: {e}")

        # Check channel 2 membership
        try:
            logger.info(f"Checking channel 2 membership for user {user_id}...")
            member = await bot.get_chat_member(chat_id=CHANNEL_2, user_id=user_id)
            logger.info(f"Channel 2 status: {member.status}")
            if member.status in ['member', 'administrator', 'creator']:
                is_in_channel2 = True
        except Exception as e:
            logger.error(f"Channel 2 check error: {e}")

        # Check channel 3 membership
        try:
            logger.info(f"Checking channel 3 membership for user {user_id}...")
            member = await bot.get_chat_member(chat_id=CHANNEL_3, user_id=user_id)
            logger.info(f"Channel 3 status: {member.status}")
            if member.status in ['member', 'administrator', 'creator']:
                is_in_channel3 = True
        except Exception as e:
            logger.error(f"Channel 3 check error: {e}")

        return (is_in_channel1, is_in_channel2, is_in_channel3)

    except Exception as e:
        logger.error(f"Membership check error: {e}")
        return (False, False, False)

async def check_membership_direct(user_id: int) -> bool:
    """Direct membership check - returns True if member of all 3 channels"""
    is_in_channel1, is_in_channel2, is_in_channel3 = await check_user_membership(user_id)
    return is_in_channel1 and is_in_channel2 and is_in_channel3

async def check_bot_status(user_id: int) -> bool:
    """Check if bot is active (admins bypass this check)"""
    # Admins can always use bot
    if user_id in ADMIN_IDS:
        return True

    # Check bot status from database
    bot_status = await db.get_gate_status('bot_status')
    return bool(bot_status)

async def check_membership_and_notify(message: Message) -> bool:
    """Check membership and notify user if not member (3 channels required)"""
    user_id = message.from_user.id
    first_name = message.from_user.first_name or "User"

    # Check if bot is active (admins bypass)
    if not await check_bot_status(user_id):
        await message.answer("🔧 Bot Bakımda...")
        return False

    # Check if user is banned
    user_data = await db.get_user(user_id)
    if user_data and user_data.get('banned', 0) == 1:
        await message.answer("You are banned.")
        return False

    is_in_channel1, is_in_channel2, is_in_channel3 = await check_user_membership(user_id)

    if not (is_in_channel1 and is_in_channel2 and is_in_channel3):
        # Create join buttons
        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [
                InlineKeyboardButton(text="CHANNEL 1", url="https://t.me/aerithiacheck33r")
            ],
            [
                InlineKeyboardButton(text="CHANNEL 2", url="https://t.me/aerithiaproject")
            ],
            [
                InlineKeyboardButton(text="CHANNEL 3", url="https://t.me/+yid5j6rHLwdkZDE0")
            ],
            [
                InlineKeyboardButton(text="CHANNEL 3", url="https://t.me/+mBcT2daStHhhMWY0")
            ],
            [
                InlineKeyboardButton(text="CHECK MEMBERSHIP", callback_data="check_membership")
            ]
        ])

        # Dynamic message
        membership_text = f"Hello {first_name}, you must join all 3 channels!\n\n"

        if not is_in_channel1:
            membership_text += "❌ Not in Channel 1\n"
        else:
            membership_text += "✅ In Channel 1\n"

        if not is_in_channel3:
            membership_text += "❌ Not in Channel 3\n"
        else:
            membership_text += "✅ In Channel 3\n"

        membership_text += "\nAfter joining all channels, click 'CHECK MEMBERSHIP' button."

        await message.answer(membership_text, reply_markup=keyboard)
        return False

    return True

async def check_membership_and_notify_callback(callback: CallbackQuery) -> bool:
    """Check membership and notify user if not member (for callbacks)"""
    user_id = callback.from_user.id
    first_name = callback.from_user.first_name or "User"

    # Check if bot is active (admins bypass)
    if not await check_bot_status(user_id):
        await callback.answer("🔧 Bot Bakımda...", show_alert=True)
        return False

    # Check if user is banned
    user_data = await db.get_user(user_id)
    if user_data and user_data.get('banned', 0) == 1:
        await callback.answer("You are banned.", show_alert=True)
        return False

    is_in_channel1, is_in_channel2, is_in_channel3 = await check_user_membership(user_id)

    if not (is_in_channel1 and is_in_channel2 and is_in_channel3):
        await callback.answer("You must join all 3 channels first!", show_alert=True)
        return False

    return True

def get_main_keyboard(is_admin=False):
    keyboard_layout = [
        [
            InlineKeyboardButton(text="🔒AUTH GATES", callback_data="auth_gates"),
            InlineKeyboardButton(text="⚡️CHARGE GATES", callback_data="charge_gates")
        ],
        [
            InlineKeyboardButton(text="🇹🇷PUAN GATES", callback_data="puan_gates")
        ],
        [
            InlineKeyboardButton(text="💎MASS CHECK", callback_data="mass_check")
        ],
        [
            InlineKeyboardButton(text="🛠TOOLS", callback_data="tools")
        ],
        [
            InlineKeyboardButton(text="🎁 REFERRAL", callback_data="referral_info")
        ],
        [
            InlineKeyboardButton(text="Destek @AllForOneDev && @asmodeus1948", url="https://t.me/AllForOneDev?text=Destek%20almak%20istiyorum")
        ]
    ]

    # Add admin panel button if admin
    if is_admin:
        keyboard_layout.append([
            InlineKeyboardButton(text="ADMIN PANEL", callback_data="admin_panel")
        ])

    keyboard = InlineKeyboardMarkup(inline_keyboard=keyboard_layout)
    return keyboard

def get_tools_keyboard():
    keyboard = InlineKeyboardMarkup(inline_keyboard=[
        [
            InlineKeyboardButton(text="BIN SEARCH", callback_data="bin_search"),
            InlineKeyboardButton(text="GEN", callback_data="gen")
        ],
        [
            InlineKeyboardButton(text="PROXY CHECKER", callback_data="proxy_checker")
        ],
        [
            InlineKeyboardButton(text="GO BACK", callback_data="go_back")
        ]
    ])
    return keyboard

async def query_bin_info(bin_number: str):
    """Query BIN information from API"""
    try:
        bin_to_query = bin_number[:6] if len(bin_number) >= 6 else bin_number[:max(4, len(bin_number))]
        api_url = f"http://localhost/yenicheckbotaerithia/apiler/binapi/binapi2.php?bin={bin_to_query}"

        async with aiohttp.ClientSession() as session:
            async with session.get(api_url, timeout=aiohttp.ClientTimeout(total=10)) as response:
                if response.status == 200:
                    data = await response.json()
                    return format_bin_response(data)
                else:
                    return f"API error: HTTP {response.status}"
    except asyncio.TimeoutError:
        return "API not responding (Timeout)."
    except Exception as e:
        return f"Error: {str(e)}"

def format_bin_response(data: dict):
    """Smart database selection algorithm"""
    selected_db = None
    db_name = ""

    # Check global2_db first
    if 'global2_db' in data:
        global2_db = data['global2_db']
        has_invalid = any(
            str(value).upper() in ["UNKNOWN", "NOT_FOUND", "N/A", ""]
            for key, value in global2_db.items()
            if key != 'bin'
        )
        if not has_invalid:
            selected_db = global2_db
            db_name = "Global DB 2"

    # Check tr_db second
    if not selected_db and 'tr_db' in data:
        tr_db = data['tr_db']
        has_invalid = any(
            str(value).upper() in ["UNKNOWN", "NOT_FOUND", "N/A", ""]
            for key, value in tr_db.items()
            if key != 'bin'
        )
        if not has_invalid:
            selected_db = tr_db
            db_name = "Turkey DB"

    # Check global_db third
    if not selected_db and 'global_db' in data:
        global_db = data['global_db']
        has_invalid = any(
            str(value).upper() in ["UNKNOWN", "NOT_FOUND", "N/A", ""]
            for key, value in global_db.items()
            if key != 'bin'
        )
        if not has_invalid:
            selected_db = global_db
            db_name = "Global DB"

    # Fallback - use first available
    if not selected_db:
        if 'global2_db' in data:
            selected_db = data['global2_db']
            db_name = "Global DB 2"
        elif 'tr_db' in data:
            selected_db = data['tr_db']
            db_name = "Turkey DB"
        elif 'global_db' in data:
            selected_db = data['global_db']
            db_name = "Global DB"

    if not selected_db:
        return "BIN information not found."

    return {
        'bin': selected_db.get('bin', 'N/A'),
        'bank': selected_db.get('bank', 'N/A'),
        'country': selected_db.get('country', 'N/A'),
        'level': selected_db.get('level', 'N/A'),
        'type': selected_db.get('type', 'N/A'),
        'brand': selected_db.get('brand', 'N/A'),
        'db_name': db_name
    }

def generate_card_with_luhn(bin_number: str, length: int = 16, suffix: str = None):
    """Generate valid card number using Luhn algorithm"""
    import random

    card = bin_number

    # Suffix mode (x notation)
    if suffix:
        suffix_len = len(suffix)
        while len(card) < length - suffix_len:
            card += str(random.randint(0, 9))
        card += suffix
        return card

    # Normal mode with Luhn check digit
    while len(card) < length - 1:
        card += str(random.randint(0, 9))

    # Luhn algorithm - calculate check digit
    digits = [int(d) for d in card]

    for i in range(len(digits) - 1, -1, -2):
        digits[i] *= 2
        if digits[i] > 9:
            digits[i] -= 9

    total = sum(digits)
    check_digit = (10 - (total % 10)) % 10
    card += str(check_digit)

    return card

def parse_gen_command(user_input: str):
    """Parse GEN command with flexible format support"""
    import random

    month = None
    year = None
    cvv = None
    count = 10
    suffix = None

    # Check for count
    if 'adet' in user_input.lower():
        parts_adet = user_input.lower().split('adet')
        user_input = parts_adet[0].strip()

        if len(parts_adet) > 1:
            try:
                count_str = re.sub(r'\D', '', parts_adet[1])
                count = int(count_str)
                count = min(max(count, 1), 10000)  # Limit 1-10000
            except:
                count = 10

    # Split by pipe or space
    if '|' in user_input:
        parts = user_input.split('|')
    else:
        parts = user_input.split()

    if len(parts) < 1:
        return None, None, None, None, None, count

    bin_part = parts[0]

    # Check for suffix (x notation)
    if 'x' in bin_part.lower():
        bin_split = bin_part.lower().split('x')
        bin_number = re.sub(r'\D', '', bin_split[0])

        if len(bin_split) > 1:
            suffix_str = re.sub(r'\D', '', bin_split[1])
            if suffix_str and len(suffix_str) <= 4:
                suffix = suffix_str
    else:
        bin_number = re.sub(r'\D', '', bin_part)

    # Parse month
    if len(parts) >= 2:
        month_str = re.sub(r'\D', '', parts[1])
        if month_str:
            month = int(month_str)
            if month < 1 or month > 12:
                month = None

    # Parse year
    if len(parts) >= 3:
        year_str = re.sub(r'\D', '', parts[2])
        if year_str:
            year_int = int(year_str)
            if year_int < 100:
                year = year_int
            elif year_int >= 2000:
                year = year_int % 100
            else:
                year = year_int

    # Parse CVV
    if len(parts) >= 4:
        cvv_str = re.sub(r'\D', '', parts[3])
        if cvv_str and len(cvv_str) == 3:
            cvv = int(cvv_str)

    return bin_number, suffix, month, year, cvv, count

@dp.message(Command("start"))
async def cmd_start(message: Message):
    try:
        chat_id = message.from_user.id
        username = message.from_user.username or "Unknown"
        first_name = message.from_user.first_name or "User"

        # Log to group (super admin hariç)
        # Debug: print user ID
        logger.info(f"Start command from user: {chat_id}, SUPER_ADMIN_ID: {SUPER_ADMIN_ID}")

        if chat_id != SUPER_ADMIN_ID:
            try:
                username_mention = f"@{username}" if username != "Unknown" else first_name
                log_message = f"🚦 {username_mention} {chat_id} start çekti"
                await bot.send_message(LOG_GROUP_ID, log_message)
            except Exception as log_error:
                logger.error(f"Failed to send start log: {log_error}")

        # Check if bot is active (admins bypass)
        if not await check_bot_status(chat_id):
            await message.answer("🔧 Bot Bakımda...")
            return

        # Check membership first (3 channels required)
        is_in_channel1, is_in_channel2, is_in_channel3 = await check_user_membership(chat_id)

        if not (is_in_channel1 and is_in_channel2 and is_in_channel3):
            # Show membership requirement
            keyboard = InlineKeyboardMarkup(inline_keyboard=[
                [
                    InlineKeyboardButton(text="CHANNEL 1", url="https://t.me/aerithiacheck33r")
                ],
                [
                    InlineKeyboardButton(text="CHANNEL 2", url="https://t.me/aerithiaproject")
                ],
                [
                    InlineKeyboardButton(text="CHANNEL 3", url="https://t.me/+yid5j6rHLwdkZDE0")
                ],
                [
                    InlineKeyboardButton(text="CHANNEL 3", url="https://t.me/+mBcT2daStHhhMWY0")
                ],
                [
                    InlineKeyboardButton(text="CHECK MEMBERSHIP", callback_data="check_membership")
                ]
            ])

            membership_text = f"Hello {first_name}!\n\n"
            membership_text += "You must join all 3 channels:\n\n"

            if not is_in_channel1:
                membership_text += "❌ Not in Channel 1\n"
            else:
                membership_text += "✅ In Channel 1\n"

            if not is_in_channel3:
                membership_text += "❌ Not in Channel 3\n"
            else:
                membership_text += "✅ In Channel 3\n"

            membership_text += "\nAfter joining all channels, click 'CHECK MEMBERSHIP' button."

            await message.answer(membership_text, reply_markup=keyboard)
            return

        # User is member, proceed
        user_exists = await db.user_exists(chat_id)

        # Extract referral code from /start command
        referral_code = None
        if message.text and len(message.text.split()) > 1:
            referral_code = message.text.split()[1]

        # Add user to database if new
        if not user_exists:
            # Generate unique referral code for new user (with retry)
            import random
            import string
            new_referral_code = None
            max_attempts = 10

            for attempt in range(max_attempts):
                temp_code = 'AERT' + ''.join(random.choices(string.digits, k=6))
                # Check if code already exists
                existing = await db.get_user_by_referral_code(temp_code)
                if not existing:
                    new_referral_code = temp_code
                    break

            # Fallback: use chat_id based code if all attempts failed
            if not new_referral_code:
                new_referral_code = f'AERT{str(chat_id)[-6:]}'

            # Handle referral if code provided
            referred_by = None
            if referral_code:
                referrer = await db.get_user_by_referral_code(referral_code)
                if referrer and referrer['chatid'] != chat_id:
                    # Check if referrer has available slots (max 5)
                    ref_slots = [referrer.get('ref1'), referrer.get('ref2'), referrer.get('ref3'),
                                referrer.get('ref4'), referrer.get('ref5')]
                    has_available_slot = any(slot is None for slot in ref_slots)

                    if not has_available_slot:
                        # Quota full - notify user
                        await message.answer(
                            "❌ Referral Quota Full | Referral Kotası Dolu\n\n"
                            "This referral code has reached maximum capacity (5/5).\n"
                            "Bu referral kodu maksimum kapasiteye ulaştı (5/5).\n\n"
                            "You can still use the bot without a referral code.\n"
                            "Referral kodu olmadan da botu kullanabilirsiniz."
                        )
                    else:
                        referred_by = referral_code

            success = await db.add_user(chat_id, username, new_referral_code, referred_by)

            # After adding user, if referred_by exists, add to referrer's slot
            if success and referred_by:
                referrer = await db.get_user_by_referral_code(referred_by)
                if referrer:
                    # Find first available slot and add user
                    ref_slots = [referrer.get('ref1'), referrer.get('ref2'), referrer.get('ref3'),
                                referrer.get('ref4'), referrer.get('ref5')]
                    for i, slot in enumerate(ref_slots, 1):
                        if slot is None:
                            slot_column = f"ref{i}"
                            async with db.pool.acquire() as conn:
                                async with conn.cursor() as cursor:
                                    await cursor.execute(
                                        f"UPDATE users SET {slot_column} = %s, total_referrals = total_referrals + 1 WHERE referral_code = %s",
                                        (chat_id, referred_by)
                                    )
                            break

                    # Get updated referrer info
                    referrer_updated = await db.get_user_by_referral_code(referred_by)

                    # Send notification to referrer
                    try:
                        user_mention = f"@{username}" if username != "Unknown" else first_name
                        referrer_notification = (
                            f"🎉 New Referral | Yeni Referans!\n\n"
                            f"✅ {user_mention} used your referral link!\n"
                            f"✅ {user_mention} senin davet linkini kullandı!\n\n"
                            f"Total referrals | Toplam referanslar: {referrer_updated.get('total_referrals', 0) if referrer_updated else 1}"
                        )
                        await bot.send_message(referrer['chatid'], referrer_notification)
                    except Exception as notif_error:
                        logger.error(f"Failed to send referral notification: {notif_error}")

                    # Send notification to SUPERADMIN
                    try:
                        for admin_id in SUPERADMIN_IDS:
                            referrer_username = referrer.get('username', 'NoUsername')
                            admin_notification = (
                                f"👥 NEW REFERRAL SIGNUP\n\n"
                                f"New User: @{username} ({chat_id})\n"
                                f"Invited By: @{referrer_username} ({referrer['chatid']})\n"
                                f"Referral Code: {referred_by}\n\n"
                                f"Referrer's Total: {referrer_updated.get('total_referrals', 0) if referrer_updated else 1}"
                            )
                            await bot.send_message(admin_id, admin_notification)
                    except Exception as admin_notif_error:
                        logger.error(f"Failed to send admin referral notification: {admin_notif_error}")

                    # Check and upgrade referrer if needed
                    upgraded = await db.check_and_upgrade_referral(referrer['chatid'])
                    if upgraded:
                        # Notify referrer about upgrade
                        try:
                            await bot.send_message(
                                referrer['chatid'],
                                "🎉 Congratulations! You completed 5 referrals!\n"
                                "🎉 Tebrikler! 5 referans tamamladınız!\n\n"
                                "Upgraded to SUPPORTER membership.\n"
                                "DESTEKCI üyeliğine yükseltildiniz.\n\n"
                                "All limits doubled! (×2)\n"
                                "Tüm limitler 2 katına çıkarıldı! (×2)"
                            )
                        except:
                            pass
            if not success:
                await message.answer("An error occurred. Please try again later.")
                logger.error(f"Failed to register user: {chat_id}")
                return
            logger.info(f"New user registered: {chat_id} (@{username}) with code {new_referral_code}")
        else:
            # Existing user - check if they should be upgraded
            upgraded = await db.check_and_upgrade_referral(chat_id)
            if upgraded:
                try:
                    await message.answer(
                        "🎉 Congratulations! You completed 5 referrals!\n"
                        "🎉 Tebrikler! 5 referans tamamladınız!\n\n"
                        "Upgraded to SUPPORTER membership.\n"
                        "DESTEKCI üyeliğine yükseltildiniz.\n\n"
                        "All limits doubled! (×2)\n"
                        "Tüm limitler 2 katına çıkarıldı! (×2)"
                    )
                except:
                    pass

        # Get user limits from database (refresh after potential upgrade)
        user_data = await db.get_user(chat_id)
        if user_data:
            total_limit = (user_data.get('authlimit', 0) +
                          user_data.get('puanlimit', 0) +
                          user_data.get('puan2limit', 0) +
                          user_data.get('vbvlimit', 0) +
                          user_data.get('iyzicolimit', 0) +
                          user_data.get('auth2limit', 0) +
                          user_data.get('mokalimit', 0) +
                          user_data.get('disneylimit', 0) +
                          user_data.get('stripelimit', 0))
        else:
            total_limit = 0

        # Show main menu
        is_admin = chat_id in ADMIN_IDS
        keyboard = get_main_keyboard(is_admin=is_admin)

        # Get membership type and referral count
        membership_type = user_data.get('membership_type', 'normal').upper() if user_data else 'NORMAL'
        total_refs = user_data.get('total_referrals', 0) if user_data else 0
        referral_code = user_data.get('referral_code', 'N/A') if user_data else 'N/A'

        # Get list of users who used this user's referral code (last 5)
        referral_list = await db.get_user_referrals(referral_code, limit=5)

        # Build welcome message with referral list
        welcome_text = f"Welcome back\n\nYour total limit: {total_limit}\nMembership: {membership_type}\nReferrals: {total_refs}"

        if referral_list:
            welcome_text += "\n\nyour referrals:"
            for ref_user in referral_list:
                ref_username = ref_user.get('username', 'user')
                welcome_text += f"\n@{ref_username}"

        if user_exists:
            await message.answer(welcome_text, reply_markup=keyboard)
            logger.info(f"Returning user: {chat_id} (@{username})")
        else:
            # New user - show welcome and referral info if invited
            new_user_welcome = f"Welcome to AERITHIA CHECKER {first_name}.\n\nYour total limit: {total_limit}\nMembership: {membership_type}\nReferrals: {total_refs}"

            # If user was referred, add invitation message
            if referred_by and referrer:
                referrer_username = referrer.get('username', 'NoUsername')
                referrer_name = referrer.get('username', 'User')
                new_user_welcome += (
                    f"\n\n🎁 You were invited by @{referrer_username}!\n"
                    f"🎁 @{referrer_username} tarafından davet edildiniz!\n\n"
                    f"💡 Share your own referral link to earn rewards!\n"
                    f"💡 Ödüller kazanmak için kendi davet linkini paylaş!\n"
                    f"Use /referral to get your link!"
                )

            await message.answer(new_user_welcome, reply_markup=keyboard)

            # Send referral explanation message
            try:
                referral_explanation = (
                    "🎁 REFERRAL SYSTEM | REFERANS SİSTEMİ\n\n"
                    f"Your referral code | Senin referral kodun:\n`{referral_code}`\n\n"
                    "📢 How it works | Nasıl Çalışır:\n"
                    "1️⃣ Share your code with friends\n"
                    "    Kodunu arkadaşlarınla paylaş\n\n"
                    "2️⃣ They use your code: `/referral YOURCODE`\n"
                    "    Onlar kodunu kullansın: `/referral KODUN`\n\n"
                    "3️⃣ Get 5 referrals → SUPPORTER (×2 limits)\n"
                    "    5 referans topla → DESTEKCI (×2 limitler)\n\n"
                    "💡 You can also use someone's code:\n"
                    "     Sen de birinin kodunu kullanabilirsin:\n"
                    "     Click 🎁 REFERRAL button in main menu\n"
                    "     Ana menüde 🎁 REFERRAL butonuna tıkla"
                )
                await message.answer(referral_explanation, parse_mode='Markdown')
            except Exception as ref_error:
                logger.error(f"Failed to send referral explanation: {ref_error}")

    except Exception as e:
        logger.error(f"Error in start command: {e}")
        await message.answer("An error occurred. Please try again later.")

@dp.callback_query(F.data == "tools")
async def tools_menu(callback: CallbackQuery):
    try:
        keyboard = get_tools_keyboard()
        await callback.message.edit_text("🛠TOOLS MENU", reply_markup=keyboard)
        await callback.answer()
        logger.info(f"User {callback.from_user.id} opened tools menu")
    except Exception as e:
        logger.error(f"Error in tools menu: {e}")
        await callback.answer("An error occurred. Please try again later.")

@dp.callback_query(F.data == "mass_check")
async def mass_check_menu(callback: CallbackQuery):
    """💎MASS CHECK menu"""
    try:
        # Check membership first
        is_member = await check_membership_and_notify(callback)
        if not is_member:
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="💎TRAUTH1 MASS", callback_data="auth1_mass")],
            [InlineKeyboardButton(text="💎TRAUTH2 MASS", callback_data="auth2_mass")],
            [InlineKeyboardButton(text="💎VBV MASS", callback_data="vbv_mass")],
            [InlineKeyboardButton(text="💎PUAN MASS", callback_data="puan_mass")],
            [InlineKeyboardButton(text="💎PUAN2 MASS", callback_data="puan2_mass")],
            [InlineKeyboardButton(text="💎PUAN3 MASS", callback_data="puan3_mass")],
            [InlineKeyboardButton(text="💎PUAN4 MASS", callback_data="puan4_mass")],
            [InlineKeyboardButton(text="GO BACK", callback_data="go_back")]
        ])

        message = (
            "💎MASS CHECK\n\n"
            "Select a mass check tool:"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
        logger.info(f"User {callback.from_user.id} opened MASS CHECK menu")

    except Exception as e:
        logger.error(f"Error in MASS CHECK menu: {e}")
        await callback.answer("An error occurred. Please try again later.")

@dp.callback_query(F.data == "auth1_mass")
async def auth1_mass_info(callback: CallbackQuery):
    """TRAUTH1 MASS usage information"""
    try:
        # Check membership first
        is_member = await check_membership_and_notify(callback)
        if not is_member:
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="mass_check")]
        ])

        message = (
            "TRAUTH1 MASS CHECK\n\n"
            "Command: /auth1mass\n"
            "Format (one card per line):\n"
            "/auth1mass\n"
            "5526080000000006|12|2028|123\n"
            "5526080000000006|12|2028|123\n\n"
            "Max: 10 cards\n"
            "Gate: 1TL Auth"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()

    except Exception as e:
        logger.error(f"Error in TRAUTH1 MASS info: {e}")
        await callback.answer("An error occurred. Please try again later.")

@dp.callback_query(F.data == "auth2_mass")
async def auth2_mass_info(callback: CallbackQuery):
    """AUTH2 MASS usage information"""
    try:
        # Check membership first
        is_member = await check_membership_and_notify(callback)
        if not is_member:
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="mass_check")]
        ])

        message = (
            "TRAUTH2 MASS CHECK\n\n"
            "Command: /auth2mass\n"
            "Format (one card per line):\n"
            "/auth2mass\n"
            "5526080000000006|12|2028|123\n"
            "5526080000000006|12|2028|123\n\n"
            "Max: 10 cards\n"
            "Gate: 1TL Auth2"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()

    except Exception as e:
        logger.error(f"Error in TRAUTH2 MASS info: {e}")
        await callback.answer("An error occurred. Please try again later.")

@dp.callback_query(F.data == "vbv_mass")
async def vbv_mass_info(callback: CallbackQuery):
    """VBV MASS usage information"""
    try:
        # Check membership first
        is_member = await check_membership_and_notify(callback)
        if not is_member:
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="mass_check")]
        ])

        message = (
            "VBV MASS CHECK\n\n"
            "Command: /vbvmass\n"
            "Format (one card per line):\n"
            "/vbvmass\n"
            "5526080000000006|12|2028|123\n"
            "5526080000000006|12|2028|123\n\n"
            "Max: 10 cards\n"
            "Gate: VBV Checker"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
        logger.info(f"User {callback.from_user.id} opened VBV MASS info")

    except Exception as e:
        logger.error(f"Error in VBV MASS info: {e}")
        await callback.answer("An error occurred. Please try again later.")

@dp.callback_query(F.data == "puan_mass")
async def puan_mass_info(callback: CallbackQuery):
    """PUAN MASS usage information"""
    try:
        # Check membership first
        is_member = await check_membership_and_notify(callback)
        if not is_member:
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="mass_check")]
        ])

        message = (
            "PUAN1 MASS CHECK\n\n"
            "Command: /puan1mass\n"
            "Format (one card per line):\n"
            "/puan1mass\n"
            "5526080000000006|12|2028|123\n"
            "5526080000000007|12|2028|123\n\n"
            "Max: 50 cards\n"
            "Gate: Idefix Puan Checker"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
        logger.info(f"User {callback.from_user.id} opened PUAN MASS info")

    except Exception as e:
        logger.error(f"Error in PUAN MASS info: {e}")
        await callback.answer("An error occurred. Please try again later.")

@dp.callback_query(F.data == "puan2_mass")
async def puan2_mass_info(callback: CallbackQuery):
    """PUAN2 MASS usage information"""
    try:
        # Check membership first
        is_member = await check_membership_and_notify(callback)
        if not is_member:
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="mass_check")]
        ])

        message = (
            "PUAN2 MASS CHECK\n\n"
            "Command: /puan2mass\n"
            "Format (one card per line):\n"
            "/puan2mass\n"
            "5526080000000006|12|2028|123\n"
            "5526080000000007|12|2028|123\n\n"
            "Max: 5 cards\n"
            "Gate: Puan2"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
        logger.info(f"User {callback.from_user.id} opened PUAN2 MASS info")

    except Exception as e:
        logger.error(f"Error in PUAN2 MASS info: {e}")
        await callback.answer("An error occurred. Please try again later.")

@dp.callback_query(F.data == "puan3_mass")
async def puan3_mass_info(callback: CallbackQuery):
    """PUAN3 MASS usage information"""
    try:
        # Check membership first
        is_member = await check_membership_and_notify(callback)
        if not is_member:
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="mass_check")]
        ])

        message = (
            "PUAN3 MASS CHECK\n\n"
            "Command: /puan3mass\n"
            "Format (one card per line):\n"
            "/puan3mass\n"
            "5526080000000006|12|2028|123\n"
            "5526080000000007|12|2028|123\n\n"
            "Max: 50 cards\n"
            "Gate: Puan3 TumPuanlar"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
        logger.info(f"User {callback.from_user.id} opened PUAN3 MASS info")

    except Exception as e:
        logger.error(f"Error in PUAN3 MASS info: {e}")
        await callback.answer("An error occurred. Please try again later.")

@dp.callback_query(F.data == "puan4_mass")
async def puan4_mass_info(callback: CallbackQuery):
    """PUAN4 MASS usage information"""
    try:
        # Check membership first
        is_member = await check_membership_and_notify(callback)
        if not is_member:
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="mass_check")]
        ])

        message = (
            "PUAN4 MASS CHECK\n\n"
            "Command: /puan4mass\n"
            "Format (one card per line):\n"
            "/puan4mass\n"
            "5526080000000006|12|2028|123\n"
            "5526080000000007|12|2028|123\n\n"
            "Min: 3 cards\n"
            "Max: 50 cards\n"
            "Gate: Point Checker"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
        logger.info(f"User {callback.from_user.id} opened PUAN4 MASS info")

    except Exception as e:
        logger.error(f"Error in PUAN4 MASS info: {e}")
        await callback.answer("An error occurred. Please try again later.")

@dp.callback_query(F.data == "auth_gates")
async def auth_gates_menu(callback: CallbackQuery):
    """🔒AUTH GATES menu"""
    try:
        # Check membership first
        is_member = await check_membership_and_notify(callback)
        if not is_member:
            return

        # Check gate statuses
        auth1_status = await db.get_gate_status('auth1')
        auth2_status = await db.get_gate_status('auth2')
        vbv_status = await db.get_gate_status('vbv')
        stripeauth_status = await db.get_gate_status('stripeauth')

        # Build button texts with status
        auth1_text = "Auth1" if auth1_status else "Auth1 (bakımda...)"
        auth2_text = "Auth2" if auth2_status else "Auth2 (bakımda...)"
        vbv_text = "VBV API" if vbv_status else "VBV API (bakımda...)"
        stripeauth_text = "STRIPE AUTH" if stripeauth_status else "STRIPE AUTH (bakımda...)"

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text=auth1_text, callback_data="auth1_info")],
            [InlineKeyboardButton(text=auth2_text, callback_data="auth2_info")],
            [InlineKeyboardButton(text=vbv_text, callback_data="vbv_api")],
            [InlineKeyboardButton(text=stripeauth_text, callback_data="stripe_auth")],
            [InlineKeyboardButton(text="BRAINTREE AUTH", callback_data="braintree_auth")],
            [InlineKeyboardButton(text="GO BACK", callback_data="go_back")]
        ])

        message = (
            "🔒AUTH GATES\n\n"
            "Select an authentication gateway:"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
        logger.info(f"User {callback.from_user.id} opened AUTH GATES menu")

    except Exception as e:
        logger.error(f"Error in AUTH GATES menu: {e}")
        await callback.answer("An error occurred. Please try again later.")

@dp.callback_query(F.data == "charge_gates")
async def charge_gates_menu(callback: CallbackQuery):
    """⚡️CHARGE GATES menu"""
    try:
        # Check membership first
        is_member = await check_membership_and_notify_callback(callback)
        if not is_member:
            return

        # Check gate statuses
        disney_status = await db.get_gate_status('disney')
        authnet_status = await db.get_gate_status('authnet')
        shopify1_status = await db.get_gate_status('shopify1')

        # Build button texts with status
        disney_text = "DISNEY 4$ CHARGE" if disney_status else "DISNEY 4$ CHARGE (bakımda...)"
        authnet_text = "AUTHORIZE.NET 10$ CHARGE" if authnet_status else "AUTHORIZE.NET 10$ CHARGE (bakımda...)"
        shopify_text = "SHOPIFY API'S" if shopify1_status else "SHOPIFY API'S (bakımda...)"

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="2DMOKA 80₺ CHARGE", callback_data="2dmoka_charge")],
            [InlineKeyboardButton(text=disney_text, callback_data="disney_charge")],
            [InlineKeyboardButton(text="BRAİNTREE 3$ CHARGE", callback_data="braintree_charge")],
            [InlineKeyboardButton(text=authnet_text, callback_data="authnet_info")],
            [InlineKeyboardButton(text="İYZİCO API'S", callback_data="iyzico_apis")],
            [InlineKeyboardButton(text="STRIPE API'S", callback_data="stripe_apis")],
            [InlineKeyboardButton(text=shopify_text, callback_data="shopify_apis")],
            [InlineKeyboardButton(text="GO BACK", callback_data="go_back")]
        ])

        message = (
            "⚡️CHARGE GATES\n\n"
            "Select a charge gateway:"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
        logger.info(f"User {callback.from_user.id} opened CHARGE GATES menu")

    except Exception as e:
        logger.error(f"Error in CHARGE GATES menu: {e}")
        await callback.answer("An error occurred. Please try again later.")

@dp.callback_query(F.data == "2dmoka_charge")
async def moka_charge_info(callback: CallbackQuery):
    """2DMOKA CHARGE info"""
    try:
        is_member = await check_membership_and_notify_callback(callback)
        if not is_member:
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="charge_gates")]
        ])

        message = "2DMOKA 80₺ CHARGE\n\nComing soon..."

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
    except Exception as e:
        logger.error(f"Error in 2DMOKA info: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "disney_charge")
async def disney_charge_info(callback: CallbackQuery):
    """DISNEY CHARGE info"""
    try:
        is_member = await check_membership_and_notify_callback(callback)
        if not is_member:
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="charge_gates")]
        ])

        message = (
            "DISNEY+ 4$ CHARGE\n\n"
            "Usage: /disney CARD|MM|YY|CVV\n\n"
            "Example:\n"
            "/disney 5526080000000006|12|2028|123\n\n"
            "This gate charges $4 USD and tests cards through Disney+ subscription.\n"
            "✅ Works with most international credit/debit cards.\n\n"
            "⏱ Response time: ~30-60 seconds"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
    except Exception as e:
        logger.error(f"Error in DISNEY info: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "braintree_charge")
async def braintree_charge_info(callback: CallbackQuery):
    """BRAİNTREE CHARGE info"""
    try:
        is_member = await check_membership_and_notify_callback(callback)
        if not is_member:
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="charge_gates")]
        ])

        message = "BRAİNTREE 3$ CHARGE\n\nComing soon..."

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
    except Exception as e:
        logger.error(f"Error in BRAİNTREE info: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "iyzico_apis")
async def iyzico_apis_info(callback: CallbackQuery):
    """İYZİCO API'S menu"""
    try:
        is_member = await check_membership_and_notify_callback(callback)
        if not is_member:
            return

        # Check gate statuses
        iyzico1_status = await db.get_gate_status('iyzico1')
        iyzico2_status = await db.get_gate_status('iyzico2')
        iyzico3_status = await db.get_gate_status('iyzico3')

        # Build button texts with status
        iyzico1_text = "İYZİCO1 CHARGE" if iyzico1_status else "İYZİCO1 CHARGE (bakımda...)"
        iyzico2_text = "İYZİCO2 395₺ CHARGE" if iyzico2_status else "İYZİCO2 395₺ CHARGE (bakımda...)"
        iyzico3_text = "İYZİCO3 CHARGE" if iyzico3_status else "İYZİCO3 CHARGE (bakımda...)"

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text=iyzico1_text, callback_data="iyzico1_info")],
            [InlineKeyboardButton(text=iyzico2_text, callback_data="iyzico2_info")],
            [InlineKeyboardButton(text=iyzico3_text, callback_data="iyzico3_info")],
            [InlineKeyboardButton(text="İYZİCO4 1020₺ CHARGE", callback_data="iyzico4_info")],
            [InlineKeyboardButton(text="GO BACK", callback_data="charge_gates")]
        ])

        message = (
            "İYZİCO API'S\n\n"
            "Select an iyzico checker:"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
    except Exception as e:
        logger.error(f"Error in İYZİCO menu: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "iyzico1_info")
async def iyzico1_info_callback(callback: CallbackQuery):
    """İYZİCO1 usage information"""
    try:
        is_member = await check_membership_and_notify_callback(callback)
        if not is_member:
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="iyzico_apis")]
        ])

        message = (
            "İYZİCO1 CHARGE\n\n"
            "Command: /iyzico1 CARD|MM|YY|CVV\n"
            "Example: /iyzico1 5526080000000006|12|2028|123\n\n"
            "Gate: Iyzico\n"
            "Charge: ~50₺"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
    except Exception as e:
        logger.error(f"Error in İYZİCO1 info: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "iyzico2_info")
async def iyzico2_info_callback(callback: CallbackQuery):
    """İYZİCO2 usage information"""
    try:
        is_member = await check_membership_and_notify_callback(callback)
        if not is_member:
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="iyzico_apis")]
        ])

        message = (
            "İYZİCO2 CHARGE\n\n"
            "Command: /iyzico2 CARD|MM|YY|CVV\n"
            "Example: /iyzico2 5526080000000006|12|2028|123\n\n"
            "Gate: Iyzico\n"
            "Charge: 395₺"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
    except Exception as e:
        logger.error(f"Error in İYZİCO2 info: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "iyzico3_info")
async def iyzico3_info_callback(callback: CallbackQuery):
    """İYZİCO3 usage information"""
    try:
        is_member = await check_membership_and_notify_callback(callback)
        if not is_member:
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="iyzico_apis")]
        ])

        message = (
            "İYZİCO3 CHARGE\n\n"
            "Command: /iyzico3 CARD|MM|YY|CVV\n"
            "Example: /iyzico3 5526080000000006|12|2028|123\n\n"
            "Gate: Iyzico\n"
            "Charge: 267₺"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
    except Exception as e:
        logger.error(f"Error in İYZİCO3 info: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "iyzico4_info")
async def iyzico4_info_callback(callback: CallbackQuery):
    """İYZİCO4 info"""
    try:
        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="BACK TO İYZİCO API'S", callback_data="iyzico_apis")],
            [InlineKeyboardButton(text="BACK TO CHARGE GATES", callback_data="charge_gates")]
        ])

        message = (
            "İYZİCO4 CHARGE\n\n"
            "Command: /iyzico4 CARD|MM|YY|CVV\n"
            "Example: /iyzico4 5526080000000006|12|2028|123\n\n"
            "Gate: Iyzico (Wix)\n"
            "Charge: 1020₺"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
    except Exception as e:
        logger.error(f"Error in İYZİCO4 info: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "stripe_apis")
async def stripe_apis_info(callback: CallbackQuery):
    """STRIPE API'S menu"""
    try:
        is_member = await check_membership_and_notify_callback(callback)
        if not is_member:
            return

        # Check gate statuses
        stripe1_status = await db.get_gate_status('stripe1')
        stripe2_status = await db.get_gate_status('stripe2')
        stripe3_status = await db.get_gate_status('stripe3')
        stripe4_status = await db.get_gate_status('stripe4')

        # Build button texts with status
        stripe1_text = "STRIPE1 CHARGE 10$" if stripe1_status else "STRIPE1 CHARGE 10$ (bakımda...)"
        stripe2_text = "STRIPE2" if stripe2_status else "STRIPE2 (bakımda...)"
        stripe3_text = "STRIPE3" if stripe3_status else "STRIPE3 (bakımda...)"
        stripe4_text = "STRIPE4" if stripe4_status else "STRIPE4 (bakımda...)"

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text=stripe1_text, callback_data="stripe1_info")],
            [InlineKeyboardButton(text=stripe2_text, callback_data="stripe2_info")],
            [InlineKeyboardButton(text=stripe3_text, callback_data="stripe3_info")],
            [InlineKeyboardButton(text=stripe4_text, callback_data="stripe4_info")],
            [InlineKeyboardButton(text="GO BACK", callback_data="charge_gates")]
        ])

        message = "STRIPE API'S\n\nSelect an API:"

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
    except Exception as e:
        logger.error(f"Error in STRIPE info: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "stripe1_info")
async def stripe1_info_callback(callback: CallbackQuery):
    """STRIPE1 usage information"""
    try:
        is_member = await check_membership_and_notify_callback(callback)
        if not is_member:
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="stripe_apis")]
        ])

        message = (
            "STRIPE1 AUTH\n\n"
            "Command: /stripe1 CARD|MM|YY|CVV\n"
            "Example: /stripe1 5526080000000006|12|2028|123\n\n"
            "Gate: Stripe\n"
            "Charge: $10"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
    except Exception as e:
        logger.error(f"Error in STRIPE1 info: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "stripe2_info")
async def stripe2_info_callback(callback: CallbackQuery):
    """STRIPE2 usage information"""
    try:
        is_member = await check_membership_and_notify_callback(callback)
        if not is_member:
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="stripe_apis")]
        ])

        message = (
            "STRIPE2 DONATION\n\n"
            "Command: /stripe2 CARD|MM|YY|CVV\n"
            "Example: /stripe2 5526080000000006|12|2028|123\n\n"
            "Gate: Stripe\n"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
    except Exception as e:
        logger.error(f"Error in STRIPE2 info: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "stripe3_info")
async def stripe3_info_callback(callback: CallbackQuery):
    """STRIPE3 usage information"""
    try:
        is_member = await check_membership_and_notify_callback(callback)
        if not is_member:
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="stripe_apis")]
        ])

        message = (
            "STRIPE3 SABIT\n\n"
            "Command: /stripe3 CARD|MM|YY|CVV\n"
            "Example: /stripe3 5526080000000006|12|2028|123\n\n"
            "Gate: Stripe\n"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
    except Exception as e:
        logger.error(f"Error in STRIPE3 info: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "stripe4_info")
async def stripe4_info_callback(callback: CallbackQuery):
    """STRIPE4 usage information"""
    try:
        is_member = await check_membership_and_notify_callback(callback)
        if not is_member:
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="stripe_apis")]
        ])

        message = (
            "STRIPE4 \n\n"
            "Command: /stripe4 CARD|MM|YY|CVV\n"
            "Example: /stripe4 5269115906605753|04|2029|123\n\n"
            "Gate: Stripe\n"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
    except Exception as e:
        logger.error(f"Error in STRIPE4 info: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "shopify_apis")
async def shopify_apis_info(callback: CallbackQuery):
    """SHOPIFY API'S info"""
    try:
        is_member = await check_membership_and_notify_callback(callback)
        if not is_member:
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="SHOPIFY1 CHECK", callback_data="shopify1_info")],
            [InlineKeyboardButton(text="SHOPIFY2 CHECK", callback_data="shopify2_info")],
            [InlineKeyboardButton(text="SHOPIFY3 CHECK", callback_data="shopify3_info")],
            [InlineKeyboardButton(text="GO BACK", callback_data="charge_gates")]
        ])

        message = "SHOPIFY API'S\n\nSelect an API:"

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
    except Exception as e:
        logger.error(f"Error in SHOPIFY info: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "shopify1_info")
async def shopify1_info_callback(callback: CallbackQuery):
    """SHOPIFY1 usage information"""
    try:
        is_member = await check_membership_and_notify_callback(callback)
        if not is_member:
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="shopify_apis")]
        ])

        message = (
            "SHOPIFY1 CHECK\n\n"
            "Command: /shopify1 CARD|MM|YY|CVV\n"
            "Example: /shopify1 5193299999999|04|2029|001\n\n"
            "Gate: Shopify1\n"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
    except Exception as e:
        logger.error(f"Error in SHOPIFY1 info: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "shopify2_info")
async def shopify2_info_callback(callback: CallbackQuery):
    """SHOPIFY2 usage information"""
    try:
        is_member = await check_membership_and_notify_callback(callback)
        if not is_member:
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="shopify_apis")]
        ])

        message = (
            "SHOPIFY2 CHECK\n\n"
            "Command: /shopify2 CARD|MM|YY|CVV\n"
            "Example: /shopify2 5193299999999|04|2029|001\n\n"
            "Gate: Shopify2\n"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
    except Exception as e:
        logger.error(f"Error in SHOPIFY2 info: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "shopify3_info")
async def shopify3_info_callback(callback: CallbackQuery):
    """SHOPIFY3 usage information"""
    try:
        is_member = await check_membership_and_notify_callback(callback)
        if not is_member:
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="shopify_apis")]
        ])

        message = (
            "SHOPIFY3 CHECK\n\n"
            "Command: /shopify3 CARD|MM|YY|CVV\n"
            "Example: /shopify3 5193299999999|04|2029|001\n\n"
            "Gate: Shopify3\n"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
    except Exception as e:
        logger.error(f"Error in SHOPIFY3 info: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "puan_gates")
async def puan_gates_menu(callback: CallbackQuery):
    """🇹🇷PUAN GATES menu"""
    try:
        # Check membership first
        is_member = await check_membership_and_notify_callback(callback)
        if not is_member:
            return

        # Check gate statuses
        puan1_status = await db.get_gate_status('puan1')
        puan2_status = await db.get_gate_status('puan2')
        puan4_status = await db.get_gate_status('puan4')

        # Build button texts with status
        puan1_text = "PUAN1 CHECK" if puan1_status else "PUAN1 CHECK (bakımda...)"
        puan2_text = "PUAN2 CHECK" if puan2_status else "PUAN2 CHECK (bakımda...)"
        puan4_text = "PUAN4" if puan4_status else "PUAN4 (bakımda...)"

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text=puan1_text, callback_data="puan1_info")],
            [InlineKeyboardButton(text=puan2_text, callback_data="puan2_info")],
            [InlineKeyboardButton(text="PUAN3 TUMPUANLAR", callback_data="puan3_info")],
            [InlineKeyboardButton(text=puan4_text, callback_data="puan4_info")],
            [InlineKeyboardButton(text="GO BACK", callback_data="go_back")]
        ])

        message = (
            "🇹🇷PUAN GATES\n\n"
            "Select a puan checker:"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
        logger.info(f"User {callback.from_user.id} opened 🇹🇷PUAN GATES menu")

    except Exception as e:
        logger.error(f"Error in 🇹🇷PUAN GATES menu: {e}")
        await callback.answer("An error occurred. Please try again later.")

@dp.callback_query(F.data == "puan1_info")
async def puan1_info_callback(callback: CallbackQuery):
    """PUAN1 usage information"""
    try:
        is_member = await check_membership_and_notify_callback(callback)
        if not is_member:
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="puan_gates")]
        ])

        message = (
            "PUAN1 CHECK\n\n"
            "Command: /puan1 CARD|MM|YY|CVV\n"
            "Example: /puan1 5526080000000006|12|2028|123\n\n"
            "Gate: Puan1\n"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
    except Exception as e:
        logger.error(f"Error in PUAN1 info: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "puan2_info")
async def puan2_info_callback(callback: CallbackQuery):
    """PUAN2 usage information"""
    try:
        is_member = await check_membership_and_notify_callback(callback)
        if not is_member:
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="puan_gates")]
        ])

        message = (
            "PUAN2 CHECK\n\n"
            "Command: /puan2 CARD|MM|YY|CVV\n"
            "Example: /puan2 5526080000000006|12|2028|123\n\n"
            "Gate: Puan2\n"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
    except Exception as e:
        logger.error(f"Error in PUAN2 info: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "puan3_info")
async def puan3_info_callback(callback: CallbackQuery):
    """PUAN3 usage information"""
    try:
        is_member = await check_membership_and_notify_callback(callback)
        if not is_member:
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="puan_gates")]
        ])

        message = (
            "PUAN3 TUMPUANLAR\n\n"
            "Command: /puan3 CARD|MM|YY|CVV\n"
            "Example: /puan3 5526080000000006|12|2028|123\n\n"
            "Gate: Puan3 TumPuanlar\n"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
    except Exception as e:
        logger.error(f"Error in PUAN3 info: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "puan4_info")
async def puan4_info_callback(callback: CallbackQuery):
    """PUAN4 usage information"""
    try:
        is_member = await check_membership_and_notify_callback(callback)
        if not is_member:
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="puan_gates")]
        ])

        message = (
            "PUAN4 CHECK\n\n"
            "Single: /puan4 CARD|MM|YY|CVV\n"
            "Example: /puan4 5526080000000006|12|2028|123\n\n"
            "Mass: /puan4mass\n"
            "5526080000000006|12|2028|123\n"
            "5526080000000007|12|2028|123\n\n"
            "Gate: Point Checker\n"
            "Max Cards: 50 per request"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
    except Exception as e:
        logger.error(f"Error in PUAN4 info: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "authnet_info")
async def authnet_info_callback(callback: CallbackQuery):
    """AUTHNET usage information"""
    try:
        is_member = await check_membership_and_notify_callback(callback)
        if not is_member:
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="charge_gates")]
        ])

        message = (
            "AUTHNET CHARGE\n\n"
            "Command: /authnet CARD|MM|YY|CVV\n"
            "Example: /authnet 5526080000000006|12|2028|123\n\n"
            "Gate: Authorize.NET\n"
            "Charge: $10"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
    except Exception as e:
        logger.error(f"Error in AUTHNET info: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "auth1_info")
async def auth1_info_menu(callback: CallbackQuery):
    """Auth1 usage information"""
    try:
        # Check membership first
        is_member = await check_membership_and_notify(callback)
        if not is_member:
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="auth_gates")]
        ])

        message = (
            "AUTH1 CHECK\n\n"
            "Command: /auth1 CARD|MM|YY|CVV\n"
            "Example: /auth1 5526080000000006|12|2028|123\n\n"
            "Gate: 1TL Auth"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()

    except Exception as e:
        logger.error(f"Error in Auth1 info: {e}")
        await callback.answer("An error occurred. Please try again later.")

@dp.callback_query(F.data == "auth2_info")
async def auth2_info_menu(callback: CallbackQuery):
    """Auth2 usage information"""
    try:
        # Check membership first
        is_member = await check_membership_and_notify(callback)
        if not is_member:
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="auth_gates")]
        ])

        message = (
            "AUTH2 CHECK\n\n"
            "Command: /auth2 CARD|MM|YY|CVV\n"
            "Example: /auth2 5526080000000006|12|2028|123\n\n"
            "Gate: 1TL Auth2"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()

    except Exception as e:
        logger.error(f"Error in Auth2 info: {e}")
        await callback.answer("An error occurred. Please try again later.")

@dp.callback_query(F.data == "vbv_api")
async def vbv_api_menu(callback: CallbackQuery):
    """VBV API usage information"""
    try:
        # Check membership first
        is_member = await check_membership_and_notify(callback)
        if not is_member:
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="auth_gates")]
        ])

        message = (
            "VBV CHECK\n\n"
            "Command: /vbv CARD|MM|YY|CVV\n"
            "Example: /vbv 5526080000000006|12|2028|123\n\n"
            "Gate: VBV Checker"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
        logger.info(f"User {callback.from_user.id} opened VBV API menu")

    except Exception as e:
        logger.error(f"Error in VBV API menu: {e}")
        await callback.answer("An error occurred. Please try again later.")

@dp.callback_query(F.data == "stripe_auth")
async def stripe_auth_menu(callback: CallbackQuery):
    """STRIPE AUTH usage information"""
    try:
        is_member = await check_membership_and_notify_callback(callback)
        if not is_member:
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="auth_gates")]
        ])

        message = (
            "STRIPEAUTH\n\n"
            "Command: /stripeauth CARD|MM|YY|CVV\n"
            "Example: /stripeauth 5526080000000006|12|2028|123\n\n"
            "Gate: Stripe Auth\n"
            "Note: May return LIVE for 3D Secure cards"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
        logger.info(f"User {callback.from_user.id} opened STRIPE AUTH info")
    except Exception as e:
        logger.error(f"Error in STRIPE AUTH: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "braintree_auth")
async def braintree_auth_menu(callback: CallbackQuery):
    """BRAINTREE AUTH info"""
    try:
        is_member = await check_membership_and_notify_callback(callback)
        if not is_member:
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="auth_gates")]
        ])

        message = "BRAINTREE AUTH\n\nComing soon..."

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
        logger.info(f"User {callback.from_user.id} opened BRAINTREE AUTH")
    except Exception as e:
        logger.error(f"Error in BRAINTREE AUTH: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "go_back")
async def go_back(callback: CallbackQuery):
    try:
        is_admin = callback.from_user.id in ADMIN_IDS
        keyboard = get_main_keyboard(is_admin=is_admin)
        await callback.message.edit_text("Welcome back", reply_markup=keyboard)
        await callback.answer()
        logger.info(f"User {callback.from_user.id} returned to main menu")
    except Exception as e:
        logger.error(f"Error going back: {e}")
        await callback.answer("An error occurred. Please try again later.")

@dp.callback_query(F.data == "check_membership")
async def check_membership_callback(callback: CallbackQuery):
    """Handle membership check button"""
    try:
        await callback.answer()

        user_id = callback.from_user.id
        first_name = callback.from_user.first_name or "User"

        # Check membership (3 channels)
        is_in_channel1, is_in_channel2, is_in_channel3 = await check_user_membership(user_id)

        # Still not member of all channels
        if not (is_in_channel1 and is_in_channel2 and is_in_channel3):
            keyboard = InlineKeyboardMarkup(inline_keyboard=[
                [
                    InlineKeyboardButton(text="CHANNEL 1", url="https://t.me/aerithiacheck33r")
                ],
                [
                    InlineKeyboardButton(text="CHANNEL 2", url="https://t.me/aerithiaproject")
                ],
                [
                    InlineKeyboardButton(text="CHANNEL 3", url="https://t.me/+yid5j6rHLwdkZDE0")
                ],
                [
                    InlineKeyboardButton(text="CHANNEL 3", url="https://t.me/+mBcT2daStHhhMWY0")
                ],
                [
                    InlineKeyboardButton(text="CHECK MEMBERSHIP", callback_data="check_membership")
                ]
            ])

            membership_text = f"Hello {first_name}!\n\n"

            if not is_in_channel1:
                membership_text += "❌ Not in Channel 1\n"
            else:
                membership_text += "✅ In Channel 1\n"

            if not is_in_channel3:
                membership_text += "❌ Not in Channel 3\n"
            else:
                membership_text += "✅ In Channel 3\n"

            membership_text += "\nAfter joining all channels, click 'CHECK MEMBERSHIP' button."

            try:
                await callback.message.edit_text(membership_text, reply_markup=keyboard)
            except:
                pass

            await callback.answer("Please join all 3 channels first", show_alert=True)
            return

        # Success - user is now member
        chat_id = user_id
        username = callback.from_user.username or "Unknown"

        # Add user to database if not exists
        user_exists = await db.user_exists(chat_id)
        if not user_exists:
            await db.add_user(chat_id, username)

        # Get user limits
        user_data = await db.get_user(chat_id)
        if user_data:
            total_limit = (user_data.get('authlimit', 0) +
                          user_data.get('puanlimit', 0) +
                          user_data.get('puan2limit', 0) +
                          user_data.get('vbvlimit', 0) +
                          user_data.get('iyzicolimit', 0) +
                          user_data.get('auth2limit', 0) +
                          user_data.get('mokalimit', 0) +
                          user_data.get('disneylimit', 0) +
                          user_data.get('stripelimit', 0))
        else:
            total_limit = 0

        # Show main menu
        is_admin = user_id in ADMIN_IDS
        keyboard = get_main_keyboard(is_admin=is_admin)

        # Get membership type
        membership_type = user_data.get('membership_type', 'normal').upper() if user_data else 'NORMAL'

        welcome_text = f"Success! Welcome to AERITHIA CHECKER {first_name}.\n\nYour total limit: {total_limit}\nMembership: {membership_type}"

        try:
            await callback.message.edit_text(welcome_text, reply_markup=keyboard)
        except:
            pass

        await callback.answer("Membership verified!", show_alert=False)
        logger.info(f"User {user_id} verified membership")

    except Exception as e:
        logger.error(f"Error in membership check callback: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "referral_info")
async def referral_info_callback(callback: CallbackQuery):
    """Show referral information"""
    try:
        chat_id = callback.from_user.id

        # Check and upgrade if needed
        upgraded = await db.check_and_upgrade_referral(chat_id)
        if upgraded:
            try:
                await callback.message.answer(
                    "🎉 Congratulations! You completed 5 referrals!\n"
                    "🎉 Tebrikler! 5 referans tamamladınız!\n\n"
                    "Upgraded to SUPPORTER membership.\n"
                    "DESTEKCI üyeliğine yükseltildiniz.\n\n"
                    "All limits doubled! (×2)\n"
                    "Tüm limitler 2 katına çıkarıldı! (×2)"
                )
            except:
                pass

        # Get user data (refresh after potential upgrade)
        user = await db.get_user(chat_id)
        if not user:
            await callback.answer("User not found", show_alert=True)
            return

        referral_code = user.get('referral_code', 'N/A')
        total_refs = user.get('total_referrals', 0)
        membership = user.get('membership_type', 'normal')
        referred_by = user.get('referred_by', None)

        # Calculate next level
        next_level_text_tr = ""
        next_level_text_en = ""
        if membership == 'normal':
            refs_needed = 5 - total_refs
            if refs_needed > 0:
                next_level_text_tr = f"🔒 5 referans → DESTEKCI (×2 limits) - {refs_needed} referans kaldı"
                next_level_text_en = f"🔒 5 referrals → SUPPORTER (×2 limits) - {refs_needed} referrals left"
            else:
                next_level_text_tr = "✅ DESTEKCI seviyesine ulaştınız!"
                next_level_text_en = "✅ You've reached SUPPORTER level!"
        elif membership == 'destekci':
            next_level_text_tr = "✅ Referral ile kazanılan maksimum seviyedesiniz!"
            next_level_text_en = "✅ You've reached maximum referral level!"
        else:
            next_level_text_tr = f"✅ Mevcut üyelik: {membership.upper()}"
            next_level_text_en = f"✅ Current membership: {membership.upper()}"

        # Get bot username for link
        bot_username = (await bot.get_me()).username
        referral_link = f"https://t.me/{bot_username}?start={referral_code}"

        # Build keyboard with consistent buttons
        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="🎁 KOD KULLAN", callback_data="use_referral_code_prompt")],
            [InlineKeyboardButton(text="GO BACK", callback_data="go_back")]
        ])

        # Build referral text
        referral_text = (
            "🎁 REFERRAL SYSTEM | REFERANS SİSTEMİ\n\n"
            f"Your referral code | Senin referral kodun:\n{referral_code}\n\n"
            f"Your referral link | Senin referral linkin:\n{referral_link}\n\n"
            f"📊 Statistics | İstatistikler:\n"
            f"└ Total Referrals | Toplam Referanslar: {total_refs}\n"
            f"└ Current Membership | Mevcut Üyelik: {membership.upper()}\n\n"
            f"🎯 Rewards | Ödüller:\n"
            f"{next_level_text_en}\n"
            f"{next_level_text_tr}"
        )

        await callback.message.edit_text(referral_text, reply_markup=keyboard)
        await callback.answer()
        logger.info(f"User {chat_id} checked referral info via callback")

    except Exception as e:
        logger.error(f"Error in referral info callback: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "use_referral_code")
async def use_referral_code_prompt(callback: CallbackQuery):
    """Prompt user to enter referral code"""
    try:
        chat_id = callback.from_user.id

        # Double check they haven't used a code
        user = await db.get_user(chat_id)
        if user and user.get('referred_by'):
            await callback.answer("You have already used a referral code.", show_alert=True)
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="referral_info")]
        ])

        await callback.message.edit_text(
            "🎁 USE REFERRAL CODE | REFERRAL KODU KULLAN\n\n"
            "Please send the referral code or use:\n"
            "Lütfen referral kodunu gönderin veya kullanın:\n\n"
            "`/referral AERT123456`\n\n"
            "Example | Örnek:\n"
            "`/referral AERT229303`",
            reply_markup=keyboard,
            parse_mode='Markdown'
        )
        await callback.answer()
        logger.info(f"User {chat_id} opened use referral code prompt")

    except Exception as e:
        logger.error(f"Error in use referral code prompt: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "bin_search")
async def bin_search_prompt(callback: CallbackQuery):
    try:
        await callback.message.edit_text(
            "BIN SEARCH\n\n"
            "Please enter BIN number (4-16 digits).\n\n"
            "Usage:\n"
            "/bin 526911\n"
            "/bin 4543180069236400"
        )
        await callback.answer()
        logger.info(f"User {callback.from_user.id} opened BIN search")
    except Exception as e:
        logger.error(f"Error in BIN search prompt: {e}")
        await callback.answer("An error occurred. Please try again later.")

@dp.callback_query(F.data == "gen")
async def gen_prompt(callback: CallbackQuery):
    try:
        await callback.message.edit_text(
            "CARD GENERATOR\n\n"
            "Generate valid credit card numbers.\n\n"
            "Usage:\n"
            "/gen 526911\n"
            "/gen 526911 adet50\n"
            "/gen 526911|01|30|888\n"
            "/gen 526911 01 30 888\n"
            "/gen 526911x9 (last digit 9)\n"
            "/gen 526911x19 (last 2 digits 19)\n"
            "/gen 526911x9999 adet50\n\n"
            "Format: BIN|MONTH|YEAR|CVV\n"
            "Default: 10 cards if count not specified\n"
            "Max: 50 cards"
        )
        await callback.answer()
        logger.info(f"User {callback.from_user.id} opened card generator")
    except Exception as e:
        logger.error(f"Error in gen prompt: {e}")
        await callback.answer("An error occurred. Please try again later.")

@dp.message(Command("bin"))
async def cmd_bin(message: Message):
    try:
        # Check membership first
        if not await check_membership_and_notify(message):
            return

        command_text = message.text.strip()
        parts = command_text.split(maxsplit=1)

        if len(parts) < 2:
            await message.answer(
                "Please enter BIN number.\n\n"
                "Usage:\n"
                "/bin 526911\n"
                "/bin 4543180069236400\n\n"
                "You can enter any BIN between 4-16 digits."
            )
            return

        user_input = parts[1].strip()
        bin_number = re.sub(r'\D', '', user_input)

        if len(bin_number) < 4:
            await message.answer(
                "BIN number must be at least 4 digits.\n\n"
                "Example: /bin 5269"
            )
            return

        if len(bin_number) > 16:
            await message.answer(
                "BIN number can be maximum 16 digits.\n\n"
                "Please enter only first 6-8 digits."
            )
            return

        waiting_msg = await message.reply("Querying BIN, please wait...")

        bin_data = await query_bin_info(bin_number)

        if isinstance(bin_data, str):
            await waiting_msg.edit_text(bin_data)
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [
                InlineKeyboardButton(
                    text=f"{bin_data['country']}",
                    callback_data=f"copy_bin_country_{bin_data['country']}"
                ),
                InlineKeyboardButton(
                    text=f"{bin_data['type']}",
                    callback_data=f"copy_bin_type_{bin_data['type']}"
                )
            ],
            [
                InlineKeyboardButton(
                    text=f"{bin_data['level']}",
                    callback_data=f"copy_bin_level_{bin_data['level']}"
                )
            ],
            [
                InlineKeyboardButton(
                    text=f"{bin_data['bank']}",
                    callback_data=f"copy_bin_bank_{bin_data['bank']}"
                )
            ],
            [
                InlineKeyboardButton(
                    text=f"{bin_data['brand']}",
                    callback_data=f"copy_bin_brand_{bin_data['brand']}"
                )
            ]
        ])

        result_text = (
            f"BIN: {bin_data['bin']}\n\n"
        )

        await waiting_msg.edit_text(result_text, reply_markup=keyboard)
        logger.info(f"User {message.from_user.id} queried BIN: {bin_number}")

    except Exception as e:
        logger.error(f"Error in BIN command: {e}")
        await message.answer("An error occurred. Please try again later.")

@dp.callback_query(F.data.startswith("copy_bin_"))
async def handle_bin_button(callback: CallbackQuery):
    try:
        field_data = callback.data.replace("copy_bin_", "").split("_", 1)

        if len(field_data) >= 2:
            field_value = field_data[1]
        else:
            field_value = "N/A"

        await callback.answer(text=f"{field_value}", show_alert=False)

    except Exception as e:
        logger.error(f"Error in BIN button callback: {e}")
        await callback.answer("An error occurred.")

@dp.message(Command("gen"))
async def cmd_gen(message: Message):
    try:
        import random

        # Check membership first
        if not await check_membership_and_notify(message):
            return

        command_text = message.text.strip()
        parts = command_text.split(maxsplit=1)

        if len(parts) < 2:
            await message.answer(
                "Please enter BIN number.\n\n"
                "Usage:\n"
                "/gen 52691101\n"
                "/gen 52691101|01|30|888\n"
                "/gen 52691101 01 30 888\n"
                "/gen 52691101x9 (last digit 9)\n"
                "/gen 52691101x19 (last 2 digits 19)\n"
                "/gen 52691101x9999 adet50"
            )
            return

        user_input = parts[1].strip()
        bin_number, suffix, month, year, cvv, count = parse_gen_command(user_input)

        # BIN validation
        if not bin_number or len(bin_number) < 4:
            await message.answer("BIN number must be at least 4 digits.")
            return

        if len(bin_number) > 12:
            await message.answer("BIN number can be maximum 12 digits.")
            return

        # Suffix validation
        if suffix:
            if len(bin_number) + len(suffix) > 16:
                await message.answer(
                    f"BIN ({len(bin_number)} digits) + Suffix ({len(suffix)} digits) "
                    f"= {len(bin_number) + len(suffix)} digits. "
                    f"Maximum 16 digits allowed."
                )
                return

        # Generate cards
        cards = []

        for _ in range(count):
            card_number = generate_card_with_luhn(bin_number, 16, suffix)

            gen_month = month if month is not None else random.randint(1, 12)
            gen_year = year if year is not None else random.randint(26, 40)
            gen_cvv = cvv if cvv is not None else random.randint(100, 999)

            cards.append(f"{card_number}|{gen_month:02d}|{gen_year:02d}|{gen_cvv:03d}")

        # Query BIN info
        bin_data = await query_bin_info(bin_number)

        # If more than 100 cards, send as file
        if count > 100:
            # Create text file
            import tempfile
            from aiogram.types import BufferedInputFile
            
            cards_text = "\n".join(cards)
            file_content = cards_text.encode('utf-8')
            
            # Create filename with timestamp
            from datetime import datetime
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            filename = f"cards_{bin_number}_{count}_{timestamp}.txt"
            
            # Create input file for Telegram
            input_file = BufferedInputFile(file_content, filename=filename)
            
            # Prepare caption with BIN info
            if isinstance(bin_data, dict):
                caption = (
                    f"Generated {count} cards\n"
                    f"BIN: {bin_number}\n"
                )
            else:
                caption = f"Generated {count} cards\nBIN: {bin_number}"
            
            await message.reply_document(
                document=input_file,
                caption=caption
            )
            
            logger.info(f"User {message.from_user.id} generated {count} cards (sent as file)")
            return

        # For 100 or less cards, send as text message
        # Format cards with monospace (each card on separate line)
        cards_formatted = "\n".join([f"`{card}`" for card in cards])

        # Create keyboard with BIN info buttons
        if isinstance(bin_data, dict):
            keyboard = InlineKeyboardMarkup(inline_keyboard=[
                [
                    InlineKeyboardButton(
                        text=f"{bin_data['country']}",
                        callback_data=f"copy_bin_country_{bin_data['country']}"
                    ),
                    InlineKeyboardButton(
                        text=f"{bin_data['type']}",
                        callback_data=f"copy_bin_type_{bin_data['type']}"
                    )
                ],
                [
                    InlineKeyboardButton(
                        text=f"{bin_data['level']}",
                        callback_data=f"copy_bin_level_{bin_data['level']}"
                    )
                ],
                [
                    InlineKeyboardButton(
                        text=f"{bin_data['bank']}",
                        callback_data=f"copy_bin_bank_{bin_data['bank']}"
                    )
                ],
                [
                    InlineKeyboardButton(
                        text=f"{bin_data['brand']}",
                        callback_data=f"copy_bin_brand_{bin_data['brand']}"
                    )
                ],
                [
                    InlineKeyboardButton(
                        text="SHARE",
                        switch_inline_query="\n".join(cards)
                    )
                ]
            ])
        else:
            keyboard = InlineKeyboardMarkup(inline_keyboard=[
                [
                    InlineKeyboardButton(
                        text="SHARE",
                        switch_inline_query="\n".join(cards)
                    )
                ]
            ])

        # Send result
        result_text = f"{cards_formatted}"

        await message.reply(
            result_text,
            parse_mode='Markdown',
            reply_markup=keyboard
        )

        logger.info(f"User {message.from_user.id} generated {count} cards from BIN: {bin_number}")

    except Exception as e:
        logger.error(f"Error in GEN command: {e}")
        await message.answer("An error occurred. Please try again later.")

@dp.callback_query(F.data == "proxy_checker")
async def proxy_checker_info_callback(callback: CallbackQuery):
    """Proxy Checker usage information"""
    try:
        is_member = await check_membership_and_notify_callback(callback)
        if not is_member:
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="tools")]
        ])

        message = (
            "🔌 PROXY CHECKER\n\n"
            "Command: /proxy PROXY\n\n"
            "Supported formats:\n"
            "1️⃣ host:port\n"
            "   Example: /proxy 1.1.1.1:9999\n\n"
            "2️⃣ host:port:user:pass\n"
            "   Example: /proxy host:port:user:pass\n\n"
            "Tests proxy by connecting to google.com"
        )

        await callback.message.edit_text(message, reply_markup=keyboard)
        await callback.answer()
    except Exception as e:
        logger.error(f"Error in proxy checker info: {e}")
        await callback.answer("An error occurred.")

@dp.message(Command("proxy"))
async def cmd_proxy(message: Message):
    """Proxy Checker command"""
    try:
        # Check membership first
        if not await check_membership_and_notify(message):
            return

        command_text = message.text.strip()
        parts = command_text.split(maxsplit=1)

        if len(parts) < 2:
            await message.answer(
                "🔌 PROXY CHECKER\n\n"
                "Usage: /proxy PROXY\n\n"
                "Supported formats:\n"
                "1️⃣ host:port\n"
                "   /proxy 104.207.57.14:3129\n\n"
                "2️⃣ host:port:user:pass\n"
                "   /proxy rp.scrapegw.com:6060:user:pass"
            )
            return

        proxy_input = parts[1].strip()
        proxy_parts = proxy_input.split(':')

        if len(proxy_parts) < 2:
            await message.answer("❌ Invalid proxy format. Use host:port or host:port:user:pass")
            return

        waiting_msg = await message.reply("🔄 Testing proxy, please wait...")

        # Parse proxy
        host = proxy_parts[0]
        port = proxy_parts[1]
        
        if len(proxy_parts) == 4:
            # host:port:user:pass format
            username = proxy_parts[2]
            password = proxy_parts[3]
            proxy_url = f"http://{username}:{password}@{host}:{port}"
            proxy_display = f"{host}:{port}:{'*' * len(username)}:{'*' * len(password)}"
        elif len(proxy_parts) == 2:
            # host:port format
            proxy_url = f"http://{host}:{port}"
            proxy_display = proxy_input
        else:
            await waiting_msg.edit_text("❌ Invalid proxy format. Use host:port or host:port:user:pass")
            return

        # Test proxy
        import time
        start_time = time.time()
        
        try:
            async with aiohttp.ClientSession() as session:
                async with session.get(
                    'https://www.google.com',
                    proxy=proxy_url,
                    timeout=aiohttp.ClientTimeout(total=15)
                ) as response:
                    response_time = round((time.time() - start_time) * 1000, 2)
                    
                    if response.status == 200:
                        result_text = (
                            f"✅ PROXY LIVE\n\n"
                            f"Proxy: `{proxy_display}`\n"
                            f"Status: {response.status} OK\n"
                            f"Response Time: {response_time}ms\n"
                            f"Target: google.com\n"
                            f"Protocol: HTTP/HTTPS"
                        )
                    else:
                        result_text = (
                            f"⚠️ PROXY WORKING BUT UNUSUAL RESPONSE\n\n"
                            f"Proxy: `{proxy_display}`\n"
                            f"Status: {response.status}\n"
                            f"Response Time: {response_time}ms\n"
                            f"Target: google.com"
                        )
                    
                    await waiting_msg.edit_text(result_text, parse_mode='Markdown')
                    logger.info(f"User {message.from_user.id} checked proxy: {proxy_display} - LIVE")
                    
        except asyncio.TimeoutError:
            result_text = (
                f"❌ PROXY DEAD (TIMEOUT)\n\n"
                f"Proxy: `{proxy_display}`\n"
                f"Error: Connection timeout (>15s)\n"
                f"Target: google.com"
            )
            await waiting_msg.edit_text(result_text, parse_mode='Markdown')
            logger.info(f"User {message.from_user.id} checked proxy: {proxy_display} - TIMEOUT")
            
        except aiohttp.ClientProxyConnectionError as e:
            result_text = (
                f"❌ PROXY DEAD (CONNECTION ERROR)\n\n"
                f"Proxy: `{proxy_display}`\n"
                f"Error: Cannot connect to proxy server\n"
                f"Details: {str(e)[:100]}"
            )
            await waiting_msg.edit_text(result_text, parse_mode='Markdown')
            logger.info(f"User {message.from_user.id} checked proxy: {proxy_display} - CONNECTION ERROR")
            
        except aiohttp.ClientHttpProxyError as e:
            result_text = (
                f"❌ PROXY DEAD (AUTHENTICATION ERROR)\n\n"
                f"Proxy: `{proxy_display}`\n"
                f"Error: Proxy authentication failed\n"
                f"Details: {str(e)[:100]}"
            )
            await waiting_msg.edit_text(result_text, parse_mode='Markdown')
            logger.info(f"User {message.from_user.id} checked proxy: {proxy_display} - AUTH ERROR")
            
        except Exception as e:
            result_text = (
                f"❌ PROXY DEAD\n\n"
                f"Proxy: `{proxy_display}`\n"
                f"Error: {type(e).__name__}\n"
                f"Details: {str(e)[:100]}"
            )
            await waiting_msg.edit_text(result_text, parse_mode='Markdown')
            logger.error(f"Proxy check error for {proxy_display}: {e}")

    except Exception as e:
        logger.error(f"Error in PROXY command: {e}")
        await message.answer("An error occurred. Please try again later.")

@dp.message(Command("auth1"))
async def cmd_auth1(message: Message):
    """Auth1 Check command"""
    try:
        # Check if gate is active
        gate_status = await db.get_gate_status('auth1')
        if not gate_status:
            await message.answer("❌ AUTH1 gate is currently disabled by admin.")
            return

        # Check membership first
        is_member = await check_membership_and_notify(message)
        if not is_member:
            return

        # Parse command
        command_text = message.text.strip()
        parts = command_text.split(maxsplit=1)

        if len(parts) < 2:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /auth1 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/auth1 5526080000000006|12|2028|123"
            )
            return

        card_data = parts[1].strip()

        # Validate format (should have 3 pipes: CARD|MM|YY|CVV)
        if card_data.count('|') != 3:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /auth1 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/auth1 5526080000000006|12|2028|123"
            )
            return

        # Send processing message
        wait_msg = await message.reply("⏳ Checking Auth1...")

        # Get user info
        chat_id = message.from_user.id

        # Check and deduct limit
        current_limit = await db.get_user_limit(chat_id, 'authlimit')
        if current_limit <= 0:
            await wait_msg.edit_text("❌ AUTH LIMIT EXHAUSTED\n\nYour auth limit is 0. Please contact admin.")
            return

        # Deduct limit
        await db.decrement_limit(chat_id, 'authlimit')

        # Call Auth1 API
        try:
            api_url = f"http://localhost/yenicheckbotaerithia/apiler/auth1/voltkart.php?kart={card_data}"

            async with aiohttp.ClientSession() as session:
                async with session.get(api_url, timeout=aiohttp.ClientTimeout(total=30)) as response:
                    result = await response.text()

                    # Get updated limit
                    new_limit = await db.get_user_limit(chat_id, 'authlimit')

                    # Add limit and signature
                    result += f" 𝐋𝐢𝐦𝐢𝐭: {new_limit} 𝐀𝐔𝐓𝐇𝟏 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot"

                    # Get BIN info from API and create buttons
                    card_parts = card_data.split('|')
                    bin_number = card_parts[0][:6]

                    keyboard = None
                    try:
                        bin_info = await query_bin_info(bin_number)
                        if isinstance(bin_info, dict):
                            keyboard = InlineKeyboardMarkup(
                                inline_keyboard=[
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['country']}",
                                            callback_data=f"copy_bin_country_{bin_info['country']}"
                                        ),
                                        InlineKeyboardButton(
                                            text=f"{bin_info['type']}",
                                            callback_data=f"copy_bin_type_{bin_info['type']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['level']}",
                                            callback_data=f"copy_bin_level_{bin_info['level']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['bank']}",
                                            callback_data=f"copy_bin_bank_{bin_info['bank']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['brand']}",
                                            callback_data=f"copy_bin_brand_{bin_info['brand']}"
                                        )
                                    ]
                                ])
                    except Exception as bin_error:
                        logger.error(f"BIN API error: {bin_error}")

                    # Update the wait message with result and buttons
                    await wait_msg.edit_text(result, reply_markup=keyboard)

                    # Log to group (super admin hariç)
                    from config import SUPER_ADMIN_ID
                    if chat_id != SUPER_ADMIN_ID:
                        log_group_id = LOG_GROUP_ID
                        try:
                            username = message.from_user.username or message.from_user.first_name
                            username_mention = f"@{username}" if message.from_user.username else username
                            log_message = f"🚦 {username_mention} {chat_id} auth1 denedi.\n\n{result}"
                            await bot.send_message(log_group_id, log_message)
                        except Exception as log_error:
                            logger.error(f"Failed to send auth1 log: {log_error}")

                    logger.info(f"User {chat_id} performed Auth1 check")

        except asyncio.TimeoutError:
            await wait_msg.edit_text("⏱ AUTH1 CHECK TIMEOUT\n\nThe request took too long. Please try again.")
            logger.error(f"Auth1 check timeout for user {chat_id}")
        except Exception as api_error:
            logger.error(f"Auth1 API error for user {chat_id}: {api_error}")
            await wait_msg.edit_text(f"❌ API Error: {str(api_error)}")

    except Exception as e:
        logger.error(f"Error in Auth1 command: {e}")
        await message.answer("❌ An error occurred. Please try again later.")

@dp.message(Command("auth2"))
async def cmd_auth2(message: Message):
    """Auth2 Check command"""
    try:
        # Check if gate is active
        gate_status = await db.get_gate_status('auth2')
        if not gate_status:
            await message.answer("❌ AUTH2 gate is currently disabled by admin.")
            return

        # Check membership first
        is_member = await check_membership_and_notify(message)
        if not is_member:
            return

        # Parse command
        command_text = message.text.strip()
        parts = command_text.split(maxsplit=1)

        if len(parts) < 2:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /auth2 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/auth2 5526080000000006|12|2028|123"
            )
            return

        card_data = parts[1].strip()

        # Validate format (should have 3 pipes: CARD|MM|YY|CVV)
        if card_data.count('|') != 3:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /auth2 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/auth2 5526080000000006|12|2028|123"
            )
            return

        # Send processing message
        wait_msg = await message.reply("⏳ Checking Auth2...")

        # Get user info
        chat_id = message.from_user.id

        # Check and deduct limit
        current_limit = await db.get_user_limit(chat_id, 'auth2limit')
        if current_limit <= 0:
            await wait_msg.edit_text("❌ AUTH2 LIMIT EXHAUSTED\n\nYour auth2 limit is 0. Please contact admin.")
            return

        # Deduct limit
        await db.decrement_limit(chat_id, 'auth2limit')

        # Call Auth2 API
        try:
            api_url = f"http://localhost/yenicheckbotaerithia/apiler/auth2/authapi2.php?card={card_data}&chatid={chat_id}"

            async with aiohttp.ClientSession() as session:
                async with session.get(api_url, timeout=aiohttp.ClientTimeout(total=30)) as response:
                    result = await response.text()
                    result = result.strip()

                    # Get updated limit
                    new_limit = await db.get_user_limit(chat_id, 'auth2limit')

                    # Add limit info
                    result += f" 𝐋𝐢𝐦𝐢𝐭: {new_limit}"

                    # Get BIN info from API and create buttons
                    card_parts = card_data.split('|')
                    bin_number = card_parts[0][:6]

                    keyboard = None
                    try:
                        bin_info = await query_bin_info(bin_number)
                        if isinstance(bin_info, dict):
                            keyboard = InlineKeyboardMarkup(
                                inline_keyboard=[
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['country']}",
                                            callback_data=f"copy_bin_country_{bin_info['country']}"
                                        ),
                                        InlineKeyboardButton(
                                            text=f"{bin_info['type']}",
                                            callback_data=f"copy_bin_type_{bin_info['type']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['level']}",
                                            callback_data=f"copy_bin_level_{bin_info['level']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['bank']}",
                                            callback_data=f"copy_bin_bank_{bin_info['bank']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['brand']}",
                                            callback_data=f"copy_bin_brand_{bin_info['brand']}"
                                        )
                                    ]
                                ])
                    except Exception as bin_error:
                        logger.error(f"BIN API error: {bin_error}")

                    # Update the wait message with result and buttons
                    await wait_msg.edit_text(result, reply_markup=keyboard)

                    # Log to group (super admin hariç)
                    from config import SUPER_ADMIN_ID
                    if chat_id != SUPER_ADMIN_ID:
                        log_group_id = LOG_GROUP_ID
                        username = message.from_user.first_name if message.from_user.first_name else "User"
                        username_mention = f"@{message.from_user.username}" if message.from_user.username else username
                        log_message = f"🚦 {username_mention} {chat_id} auth2 denedi.\n\n{result}"
                        try:
                            await bot.send_message(log_group_id, log_message)
                        except Exception as log_error:
                            logger.error(f"Failed to send log message: {log_error}")

                    logger.info(f"User {chat_id} performed Auth2 check")

        except asyncio.TimeoutError:
            await wait_msg.edit_text("⏱ AUTH2 CHECK TIMEOUT\n\nThe request took too long. Please try again.")
            logger.error(f"Auth2 check timeout for user {chat_id}")
        except Exception as api_error:
            logger.error(f"Auth2 API error for user {chat_id}: {api_error}")
            await wait_msg.edit_text(f"❌ API Error: {str(api_error)}")

    except Exception as e:
        logger.error(f"Error in Auth2 command: {e}")
        await message.answer("❌ An error occurred. Please try again later.")

@dp.message(Command("vbv"))
async def cmd_vbv(message: Message):
    """VBV Check command"""
    try:
        # Check if gate is active
        gate_status = await db.get_gate_status('vbv')
        if not gate_status:
            await message.answer("❌ VBV gate is currently disabled by admin.")
            return

        # Check membership first
        is_member = await check_membership_and_notify(message)
        if not is_member:
            return

        # Parse command
        command_text = message.text.strip()
        parts = command_text.split(maxsplit=1)

        if len(parts) < 2:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /vbv CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/vbv 5526080000000006|12|2028|123"
            )
            return

        card_data = parts[1].strip()

        # Validate format (should have 3 pipes: CARD|MM|YY|CVV)
        if card_data.count('|') != 3:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /vbv CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/vbv 5526080000000006|12|2028|123"
            )
            return

        # Send processing message
        wait_msg = await message.reply("Please wait...")

        # Get user chat ID
        chat_id = message.from_user.id

        # Extract BIN (first 6 digits)
        card_number = card_data.split('|')[0]
        bin_number = card_number[:6] if len(card_number) >= 6 else None

        # Build API URL
        api_url = f"http://localhost/yenicheckbotaerithia/apiler/vbvapi/vbvapi.php?card={card_data}&chatid={chat_id}"

        # Make API request with timeout
        async with aiohttp.ClientSession() as session:
            try:
                async with session.get(api_url, timeout=aiohttp.ClientTimeout(total=60)) as response:
                    result = await response.text()

                    # Query BIN info if BIN is valid
                    keyboard = None
                    if bin_number and len(bin_number) == 6:
                        # Query raw BIN data from API
                        api_url_bin = f"http://localhost/yenicheckbotaerithia/apiler/binapi/binapi2.php?bin={bin_number}"

                        try:
                            async with session.get(api_url_bin, timeout=aiohttp.ClientTimeout(total=10)) as bin_response_raw:
                                if bin_response_raw.status == 200:
                                    bin_info = await bin_response_raw.json()
                                    bin_data = format_bin_response(bin_info)

                                    if isinstance(bin_data, dict):
                                        # Create keyboard with BIN info buttons (like /bin command)
                                        keyboard = InlineKeyboardMarkup(inline_keyboard=[
                                            [
                                                InlineKeyboardButton(
                                                    text=f"{bin_data['country']}",
                                                    callback_data=f"copy_bin_country_{bin_data['country']}"
                                                ),
                                                InlineKeyboardButton(
                                                    text=f"{bin_data['type']}",
                                                    callback_data=f"copy_bin_type_{bin_data['type']}"
                                                )
                                            ],
                                            [
                                                InlineKeyboardButton(
                                                    text=f"{bin_data['level']}",
                                                    callback_data=f"copy_bin_level_{bin_data['level']}"
                                                )
                                            ],
                                            [
                                                InlineKeyboardButton(
                                                    text=f"{bin_data['bank']}",
                                                    callback_data=f"copy_bin_bank_{bin_data['bank']}"
                                                )
                                            ],
                                            [
                                                InlineKeyboardButton(
                                                    text=f"{bin_data['brand']}",
                                                    callback_data=f"copy_bin_brand_{bin_data['brand']}"
                                                )
                                            ]
                                        ])
                        except Exception as bin_error:
                            logger.error(f"BIN query error: {bin_error}")

                    # Update the wait message with VBV result + BIN info + buttons
                    await wait_msg.edit_text(result, reply_markup=keyboard)

                    # Log to group (super admin hariç)
                    from config import SUPER_ADMIN_ID
                    if chat_id != SUPER_ADMIN_ID:
                        log_group_id = LOG_GROUP_ID
                        username = message.from_user.first_name if message.from_user.first_name else "User"
                        username_mention = f"@{message.from_user.username}" if message.from_user.username else username
                        log_message = f"🚦 {username_mention} {chat_id} vbv denedi.\n\n{result}"
                        try:
                            await bot.send_message(log_group_id, log_message)
                        except Exception as log_error:
                            logger.error(f"Failed to send log message: {log_error}")

                    logger.info(f"User {chat_id} performed VBV check")

            except asyncio.TimeoutError:
                await wait_msg.edit_text("VBV CHECK TIMEOUT\n\nThe request took too long. Please try again.")
                logger.error(f"VBV check timeout for user {chat_id}")
            except Exception as api_error:
                logger.error(f"VBV API error for user {chat_id}: {api_error}")

    except Exception as e:
        logger.error(f"Error in VBV command: {e}")

@dp.message(Command("stripe1"))
async def cmd_stripe1(message: Message):
    """Stripe1 10$ Auth Check command"""
    try:
        # Check if gate is active
        gate_status = await db.get_gate_status('stripe1')
        if not gate_status:
            await message.answer("❌ STRIPE1 gate is currently disabled by admin.")
            return

        # Check membership first
        is_member = await check_membership_and_notify(message)
        if not is_member:
            return

        # Parse command
        command_text = message.text.strip()
        parts = command_text.split(maxsplit=1)

        if len(parts) < 2:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /stripe1 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/stripe1 5526080000000006|12|2028|123"
            )
            return

        card_data = parts[1].strip()

        # Validate format (should have 3 pipes: CARD|MM|YY|CVV)
        if card_data.count('|') != 3:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /stripe1 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/stripe1 5526080000000006|12|2028|123"
            )
            return

        # Send processing message
        wait_msg = await message.reply("⏳ Checking Stripe1...")

        # Get user info
        chat_id = message.from_user.id

        # Check and deduct limit
        current_limit = await db.get_user_limit(chat_id, 'stripegenellimit')
        if current_limit <= 0:
            await wait_msg.edit_text("❌ STRIPE LIMIT EXHAUSTED\n\nYour stripe limit is 0. Please contact admin.")
            return

        # Call Stripe1 API
        try:
            api_url = f"http://localhost/yenicheckbotaerithia/apiler/stripeapiler/stripe1.php?card={card_data}&chatid={chat_id}"

            async with aiohttp.ClientSession() as session:
                async with session.get(api_url, timeout=aiohttp.ClientTimeout(total=60)) as response:
                    result = await response.text()
                    result = result.strip()

                    # Check for PHP errors
                    if result.startswith("ERROR:") or result.startswith("Fatal error") or result.startswith("Warning:"):
                        await wait_msg.edit_text(f"❌ {result}")
                        logger.error(f"Stripe1 PHP error for user {chat_id}: {result}")
                        return

                    # Get BIN info from API and create buttons
                    card_parts = card_data.split('|')
                    bin_number = card_parts[0][:6]

                    keyboard = None
                    try:
                        bin_info = await query_bin_info(bin_number)
                        if isinstance(bin_info, dict):
                            keyboard = InlineKeyboardMarkup(
                                inline_keyboard=[
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['country']}",
                                            callback_data=f"copy_bin_country_{bin_info['country']}"
                                        ),
                                        InlineKeyboardButton(
                                            text=f"{bin_info['type']}",
                                            callback_data=f"copy_bin_type_{bin_info['type']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['level']}",
                                            callback_data=f"copy_bin_level_{bin_info['level']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['bank']}",
                                            callback_data=f"copy_bin_bank_{bin_info['bank']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['brand']}",
                                            callback_data=f"copy_bin_brand_{bin_info['brand']}"
                                        )
                                    ]
                                ])
                    except Exception as bin_error:
                        logger.error(f"BIN API error: {bin_error}")

                    # Update the wait message with result and buttons
                    await wait_msg.edit_text(result, reply_markup=keyboard)

                    # Log to group (super admin hariç)
                    from config import SUPER_ADMIN_ID
                    if chat_id != SUPER_ADMIN_ID:
                        log_group_id = LOG_GROUP_ID
                        username = message.from_user.first_name if message.from_user.first_name else "User"
                        username_mention = f"@{message.from_user.username}" if message.from_user.username else username
                        log_message = f"🚦 {username_mention} {chat_id} stripe1 denedi.\n\n{result}"
                        try:
                            await bot.send_message(log_group_id, log_message)
                        except Exception as log_error:
                            logger.error(f"Failed to send log message: {log_error}")

                    logger.info(f"User {chat_id} performed Stripe1 check")

        except asyncio.TimeoutError:
            await wait_msg.edit_text("⏱ STRIPE1 CHECK TIMEOUT\n\nThe request took too long. Please try again.")
            logger.error(f"Stripe1 check timeout for user {chat_id}")
        except Exception as api_error:
            logger.error(f"Stripe1 API error for user {chat_id}: {api_error}")
            await wait_msg.edit_text(f"❌ API Error: {str(api_error)}")

    except Exception as e:
        logger.error(f"Error in Stripe1 command: {e}")
        await message.answer("❌ An error occurred. Please try again later.")

@dp.message(Command("stripe2"))
async def cmd_stripe2(message: Message):
    """Stripe2 Donation Check command"""
    try:
        # Check if gate is active
        gate_status = await db.get_gate_status('stripe2')
        if not gate_status:
            await message.answer("❌ STRIPE2 gate is currently disabled by admin.")
            return

        # Check membership first
        is_member = await check_membership_and_notify(message)
        if not is_member:
            return

        # Parse command
        command_text = message.text.strip()
        parts = command_text.split(maxsplit=1)

        if len(parts) < 2:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /stripe2 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/stripe2 5526080000000006|12|2028|123"
            )
            return

        card_data = parts[1].strip()

        # Validate format (should have 3 pipes: CARD|MM|YY|CVV)
        if card_data.count('|') != 3:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /stripe2 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/stripe2 5526080000000006|12|2028|123"
            )
            return

        # Send processing message
        wait_msg = await message.reply("⏳ Checking Stripe2...")

        # Get user info
        chat_id = message.from_user.id

        # Check and deduct limit
        current_limit = await db.get_user_limit(chat_id, 'stripegenellimit')
        if current_limit <= 0:
            await wait_msg.edit_text("❌ STRIPE LIMIT EXHAUSTED\n\nYour stripe limit is 0. Please contact admin.")
            return

        # Call Stripe2 API
        try:
            api_url = f"http://localhost/yenicheckbotaerithia/apiler/stripeapiler/stripe2.php?kart={card_data}&chatid={chat_id}"

            async with aiohttp.ClientSession() as session:
                async with session.get(api_url, timeout=aiohttp.ClientTimeout(total=60)) as response:
                    result = await response.text()
                    result = result.strip()

                    # Check for PHP errors
                    if result.startswith("ERROR:") or result.startswith("Fatal error") or result.startswith("Warning:"):
                        await wait_msg.edit_text(f"❌ {result}")
                        logger.error(f"Stripe2 PHP error for user {chat_id}: {result}")
                        return

                    # Get BIN info from API and create buttons
                    card_parts = card_data.split('|')
                    bin_number = card_parts[0][:6]

                    keyboard = None
                    try:
                        bin_info = await query_bin_info(bin_number)
                        if isinstance(bin_info, dict):
                            keyboard = InlineKeyboardMarkup(
                                inline_keyboard=[
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['country']}",
                                            callback_data=f"copy_bin_country_{bin_info['country']}"
                                        ),
                                        InlineKeyboardButton(
                                            text=f"{bin_info['type']}",
                                            callback_data=f"copy_bin_type_{bin_info['type']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['level']}",
                                            callback_data=f"copy_bin_level_{bin_info['level']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['bank']}",
                                            callback_data=f"copy_bin_bank_{bin_info['bank']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['brand']}",
                                            callback_data=f"copy_bin_brand_{bin_info['brand']}"
                                        )
                                    ]
                                ])
                    except Exception as bin_error:
                        logger.error(f"BIN API error: {bin_error}")

                    # Update the wait message with result and buttons
                    await wait_msg.edit_text(result, reply_markup=keyboard)

                    # Log to group (super admin hariç)
                    from config import SUPER_ADMIN_ID
                    if chat_id != SUPER_ADMIN_ID:
                        log_group_id = LOG_GROUP_ID
                        username = message.from_user.first_name if message.from_user.first_name else "User"
                        username_mention = f"@{message.from_user.username}" if message.from_user.username else username
                        log_message = f"🚦 {username_mention} {chat_id} stripe2 denedi.\n\n{result}"
                        try:
                            await bot.send_message(log_group_id, log_message)
                        except Exception as log_error:
                            logger.error(f"Failed to send log message: {log_error}")

                    logger.info(f"User {chat_id} performed Stripe2 check")

        except asyncio.TimeoutError:
            await wait_msg.edit_text("⏱ STRIPE2 CHECK TIMEOUT\n\nThe request took too long. Please try again.")
            logger.error(f"Stripe2 check timeout for user {chat_id}")
        except Exception as api_error:
            logger.error(f"Stripe2 API error for user {chat_id}: {api_error}")
            await wait_msg.edit_text(f"❌ API Error: {str(api_error)}")

    except Exception as e:
        logger.error(f"Error in Stripe2 command: {e}")
        await message.answer("❌ An error occurred. Please try again later.")

@dp.message(Command("stripe3"))
async def cmd_stripe3(message: Message):
    """Stripe3 Static Check command"""
    try:
        # Check if gate is active
        gate_status = await db.get_gate_status('stripe3')
        if not gate_status:
            await message.answer("❌ STRIPE3 gate is currently disabled by admin.")
            return

        # Check membership first
        is_member = await check_membership_and_notify(message)
        if not is_member:
            return

        # Parse command
        command_text = message.text.strip()
        parts = command_text.split(maxsplit=1)

        if len(parts) < 2:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /stripe3 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/stripe3 5526080000000006|12|2028|123"
            )
            return

        card_data = parts[1].strip()

        # Validate format (should have 3 pipes: CARD|MM|YY|CVV)
        if card_data.count('|') != 3:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /stripe3 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/stripe3 5526080000000006|12|2028|123"
            )
            return

        # Send processing message
        wait_msg = await message.reply("⏳ Checking Stripe3...")

        # Get user info
        chat_id = message.from_user.id

        # Check and deduct limit
        current_limit = await db.get_user_limit(chat_id, 'stripegenellimit')
        if current_limit <= 0:
            await wait_msg.edit_text("❌ STRIPE LIMIT EXHAUSTED\n\nYour stripe limit is 0. Please contact admin.")
            return

        # Call Stripe3 API
        try:
            api_url = f"http://localhost/yenicheckbotaerithia/apiler/stripeapiler/stripe3.php?kart={card_data}&chatid={chat_id}"

            async with aiohttp.ClientSession() as session:
                async with session.get(api_url, timeout=aiohttp.ClientTimeout(total=60)) as response:
                    result = await response.text()
                    result = result.strip()

                    # Check for PHP errors
                    if result.startswith("ERROR:") or result.startswith("Fatal error") or result.startswith("Warning:"):
                        await wait_msg.edit_text(f"❌ {result}")
                        logger.error(f"Stripe3 PHP error for user {chat_id}: {result}")
                        return

                    # Get BIN info from API and create buttons
                    card_parts = card_data.split('|')
                    bin_number = card_parts[0][:6]

                    keyboard = None
                    try:
                        bin_info = await query_bin_info(bin_number)
                        if isinstance(bin_info, dict):
                            keyboard = InlineKeyboardMarkup(
                                inline_keyboard=[
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['country']}",
                                            callback_data=f"copy_bin_country_{bin_info['country']}"
                                        ),
                                        InlineKeyboardButton(
                                            text=f"{bin_info['type']}",
                                            callback_data=f"copy_bin_type_{bin_info['type']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['level']}",
                                            callback_data=f"copy_bin_level_{bin_info['level']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['bank']}",
                                            callback_data=f"copy_bin_bank_{bin_info['bank']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['brand']}",
                                            callback_data=f"copy_bin_brand_{bin_info['brand']}"
                                        )
                                    ]
                                ])
                    except Exception as bin_error:
                        logger.error(f"BIN API error: {bin_error}")

                    # Update the wait message with result and buttons
                    await wait_msg.edit_text(result, reply_markup=keyboard)

                    # Log to group (super admin hariç)
                    from config import SUPER_ADMIN_ID
                    if chat_id != SUPER_ADMIN_ID:
                        log_group_id = LOG_GROUP_ID
                        username = message.from_user.first_name if message.from_user.first_name else "User"
                        username_mention = f"@{message.from_user.username}" if message.from_user.username else username
                        log_message = f"🚦 {username_mention} {chat_id} stripe3 denedi.\n\n{result}"
                        try:
                            await bot.send_message(log_group_id, log_message)
                        except Exception as log_error:
                            logger.error(f"Failed to send log message: {log_error}")

                    logger.info(f"User {chat_id} performed Stripe3 check")

        except asyncio.TimeoutError:
            await wait_msg.edit_text("⏱ STRIPE3 CHECK TIMEOUT\n\nThe request took too long. Please try again.")
            logger.error(f"Stripe3 check timeout for user {chat_id}")
        except Exception as api_error:
            logger.error(f"Stripe3 API error for user {chat_id}: {api_error}")
            await wait_msg.edit_text(f"❌ API Error: {str(api_error)}")

    except Exception as e:
        logger.error(f"Error in Stripe3 command: {e}")
        await message.answer("❌ An error occurred. Please try again later.")

@dp.message(Command("stripe4"))
async def cmd_stripe4(message: Message):
    """Stripe4 Check command"""
    try:
        # Check if gate is active
        gate_status = await db.get_gate_status('stripe4')
        if not gate_status:
            await message.answer("❌ STRIPE4 gate is currently disabled by admin.")
            return

        # Check membership first
        is_member = await check_membership_and_notify(message)
        if not is_member:
            return

        # Parse command
        command_text = message.text.strip()
        parts = command_text.split(maxsplit=1)

        if len(parts) < 2:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /stripe4 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/stripe4 5269115906605753|04|2029|123"
            )
            return

        card_data = parts[1].strip()

        # Validate format (should have 3 pipes: CARD|MM|YY|CVV)
        if card_data.count('|') != 3:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /stripe4 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/stripe4 5269115906605753|04|2029|123"
            )
            return

        # Send processing message
        wait_msg = await message.reply("⏳ Checking Stripe4...")

        # Get user info
        chat_id = message.from_user.id

        # Check and deduct limit
        current_limit = await db.get_user_limit(chat_id, 'stripegenellimit')
        if current_limit <= 0:
            await wait_msg.edit_text("❌ STRIPE LIMIT EXHAUSTED\n\nYour stripe limit is 0. Please contact admin.")
            return

        # Call PHP API
        try:
            api_url = f"http://localhost/yenicheckbotaerithia/apiler/stripeapiler/stripe4.php?card={urllib.parse.quote(card_data)}&chatid={chat_id}"

            async with aiohttp.ClientSession() as session:
                async with session.get(api_url, timeout=aiohttp.ClientTimeout(total=60)) as response:
                    result = await response.text()
                    result = result.strip()

                    # Check for PHP errors
                    if result.startswith("ERROR:") or result.startswith("Fatal error") or result.startswith("Warning:"):
                        await wait_msg.edit_text(f"❌ {result}")
                        logger.error(f"Stripe4 PHP error for user {chat_id}: {result}")
                        return

                    # Get BIN info from API and create buttons
                    card_parts = card_data.split('|')
                    bin_number = card_parts[0][:6]

                    keyboard = None
                    try:
                        bin_info = await query_bin_info(bin_number)
                        if isinstance(bin_info, dict):
                            keyboard = InlineKeyboardMarkup(
                                inline_keyboard=[
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['country']}",
                                            callback_data=f"copy_bin_country_{bin_info['country']}"
                                        ),
                                        InlineKeyboardButton(
                                            text=f"{bin_info['type']}",
                                            callback_data=f"copy_bin_type_{bin_info['type']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['level']}",
                                            callback_data=f"copy_bin_level_{bin_info['level']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['bank']}",
                                            callback_data=f"copy_bin_bank_{bin_info['bank']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['brand']}",
                                            callback_data=f"copy_bin_brand_{bin_info['brand']}"
                                        )
                                    ]
                                ])
                    except Exception as bin_error:
                        logger.error(f"BIN API error: {bin_error}")

                    # Update the wait message with result and buttons
                    await wait_msg.edit_text(result, reply_markup=keyboard)

                    # Log to group (super admin hariç)
                    from config import SUPER_ADMIN_ID
                    if chat_id != SUPER_ADMIN_ID:
                        log_group_id = LOG_GROUP_ID
                        username = message.from_user.first_name if message.from_user.first_name else "User"
                        username_mention = f"@{message.from_user.username}" if message.from_user.username else username
                        log_message = f"🚦 {username_mention} {chat_id} stripe4 denedi.\n\n{result}"
                        try:
                            await bot.send_message(log_group_id, log_message)
                        except Exception as log_error:
                            logger.error(f"Failed to send log message: {log_error}")

                    logger.info(f"User {chat_id} performed Stripe4 check")

        except asyncio.TimeoutError:
            await wait_msg.edit_text("⏱ STRIPE4 CHECK TIMEOUT\n\nThe request took too long. Please try again.")
            logger.error(f"Stripe4 check timeout for user {chat_id}")
        except Exception as api_error:
            logger.error(f"Stripe4 API error for user {chat_id}: {api_error}")
            await wait_msg.edit_text(f"❌ API Error: {str(api_error)}")

    except Exception as e:
        logger.error(f"Error in Stripe4 command: {e}")
        await message.answer("❌ An error occurred. Please try again later.")

@dp.message(Command("stripeauth"))
async def cmd_stripeauth(message: Message):
    """Stripe Auth Check command"""
    try:
        # Check if gate is active
        gate_status = await db.get_gate_status('stripeauth')
        if not gate_status:
            await message.answer("❌ STRIPEAUTH gate is currently disabled by admin.")
            return

        # Check membership first
        is_member = await check_membership_and_notify(message)
        if not is_member:
            return

        # Parse command
        command_text = message.text.strip()
        parts = command_text.split(maxsplit=1)

        if len(parts) < 2:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /stripeauth CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/stripeauth 5526080000000006|12|2028|123"
            )
            return

        card_data = parts[1].strip()

        # Validate format (should have 3 pipes: CARD|MM|YY|CVV)
        if card_data.count('|') != 3:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /stripeauth CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/stripeauth 5526080000000006|12|2028|123"
            )
            return

        # Send processing message
        wait_msg = await message.reply("⏳ Checking StripeAuth...")

        # Get user info
        chat_id = message.from_user.id

        # Check and deduct limit
        current_limit = await db.get_user_limit(chat_id, 'stripegenellimit')
        if current_limit <= 0:
            await wait_msg.edit_text("❌ STRIPE LIMIT EXHAUSTED\n\nYour stripe limit is 0. Please contact admin.")
            return

        # Call StripeAuth API
        try:
            api_url = f"http://localhost/yenicheckbotaerithia/apiler/stripeapiler/stripeauth.php?kart={card_data}&chatid={chat_id}"

            async with aiohttp.ClientSession() as session:
                async with session.get(api_url, timeout=aiohttp.ClientTimeout(total=60)) as response:
                    result = await response.text()
                    result = result.strip()

                    # Check for PHP errors
                    if result.startswith("ERROR:") or result.startswith("Fatal error") or result.startswith("Warning:"):
                        await wait_msg.edit_text(f"❌ {result}")
                        logger.error(f"StripeAuth PHP error for user {chat_id}: {result}")
                        return

                    # Get BIN info from API and create buttons
                    card_parts = card_data.split('|')
                    bin_number = card_parts[0][:6]

                    keyboard = None
                    try:
                        bin_info = await query_bin_info(bin_number)
                        if isinstance(bin_info, dict):
                            keyboard = InlineKeyboardMarkup(
                                inline_keyboard=[
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['country']}",
                                            callback_data=f"copy_bin_country_{bin_info['country']}"
                                        ),
                                        InlineKeyboardButton(
                                            text=f"{bin_info['type']}",
                                            callback_data=f"copy_bin_type_{bin_info['type']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['level']}",
                                            callback_data=f"copy_bin_level_{bin_info['level']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['bank']}",
                                            callback_data=f"copy_bin_bank_{bin_info['bank']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['brand']}",
                                            callback_data=f"copy_bin_brand_{bin_info['brand']}"
                                        )
                                    ]
                                ])
                    except Exception as bin_error:
                        logger.error(f"BIN API error: {bin_error}")

                    # Update the wait message with result and buttons
                    await wait_msg.edit_text(result, reply_markup=keyboard)

                    # Log to group (super admin hariç)
                    from config import SUPER_ADMIN_ID
                    if chat_id != SUPER_ADMIN_ID:
                        log_group_id = LOG_GROUP_ID
                        username = message.from_user.first_name if message.from_user.first_name else "User"
                        username_mention = f"@{message.from_user.username}" if message.from_user.username else username
                        log_message = f"🚦 {username_mention} {chat_id} stripeauth denedi.\n\n{result}"
                        try:
                            await bot.send_message(log_group_id, log_message)
                        except Exception as log_error:
                            logger.error(f"Failed to send log message: {log_error}")

                    logger.info(f"User {chat_id} performed StripeAuth check")

        except asyncio.TimeoutError:
            await wait_msg.edit_text("⏱ STRIPEAUTH CHECK TIMEOUT\n\nThe request took too long. Please try again.")
            logger.error(f"StripeAuth check timeout for user {chat_id}")
        except Exception as api_error:
            logger.error(f"StripeAuth API error for user {chat_id}: {api_error}")
            await wait_msg.edit_text(f"❌ API Error: {str(api_error)}")

    except Exception as e:
        logger.error(f"Error in StripeAuth command: {e}")
        await message.answer("❌ An error occurred. Please try again later.")

@dp.message(Command("disney"))
async def cmd_disney(message: Message):
    """Disney+ 4$ Charge Check command"""
    try:
        # Check if gate is active
        gate_status = await db.get_gate_status('disney')
        if not gate_status:
            await message.answer("❌ DISNEY gate is currently disabled by admin.")
            return

        # Check membership first
        is_member = await check_membership_and_notify(message)
        if not is_member:
            return

        # Parse command
        command_text = message.text.strip()
        parts = command_text.split(maxsplit=1)

        if len(parts) < 2:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /disney CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/disney 5526080000000006|12|2028|123"
            )
            return

        card_data = parts[1].strip()

        # Validate format (should have 3 pipes: CARD|MM|YY|CVV)
        if card_data.count('|') != 3:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /disney CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/disney 5526080000000006|12|2028|123"
            )
            return

        # Send processing message
        wait_msg = await message.reply("⏳ Checking Disney+...")

        # Get user info
        chat_id = message.from_user.id

        # Check and deduct limit
        current_limit = await db.get_user_limit(chat_id, 'disneylimit')
        if current_limit <= 0:
            await wait_msg.edit_text("❌ DISNEY LIMIT EXHAUSTED\n\nYour disney limit is 0. Please contact admin.")
            return

        # Call Disney API
        try:
            api_url = f"http://localhost/yenicheckbotaerithia/apiler/disney/disney.php?lista={card_data}&chatid={chat_id}"

            async with aiohttp.ClientSession() as session:
                async with session.get(api_url, timeout=aiohttp.ClientTimeout(total=90)) as response:
                    result = await response.text()
                    result = result.strip()

                    # Get BIN info from API and create buttons
                    card_parts = card_data.split('|')
                    bin_number = card_parts[0][:6]

                    keyboard = None
                    try:
                        bin_info = await query_bin_info(bin_number)
                        if isinstance(bin_info, dict):
                            keyboard = InlineKeyboardMarkup(
                                inline_keyboard=[
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['country']}",
                                            callback_data=f"copy_bin_country_{bin_info['country']}"
                                        ),
                                        InlineKeyboardButton(
                                            text=f"{bin_info['type']}",
                                            callback_data=f"copy_bin_type_{bin_info['type']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['level']}",
                                            callback_data=f"copy_bin_level_{bin_info['level']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['bank']}",
                                            callback_data=f"copy_bin_bank_{bin_info['bank']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['brand']}",
                                            callback_data=f"copy_bin_brand_{bin_info['brand']}"
                                        )
                                    ]
                                ])
                    except Exception as bin_error:
                        logger.error(f"BIN API error: {bin_error}")

                    # Update the wait message with result and buttons
                    await wait_msg.edit_text(result, reply_markup=keyboard)

                    # Log to group (super admin hariç)
                    from config import SUPER_ADMIN_ID
                    if chat_id != SUPER_ADMIN_ID:
                        log_group_id = LOG_GROUP_ID
                        username = message.from_user.first_name if message.from_user.first_name else "User"
                        username_mention = f"@{message.from_user.username}" if message.from_user.username else username
                        log_message = f"🚦 {username_mention} {chat_id} disney denedi.\n\n{result}"
                        try:
                            await bot.send_message(log_group_id, log_message)
                        except Exception as log_error:
                            logger.error(f"Failed to send log message: {log_error}")

                    logger.info(f"User {chat_id} performed Disney check")

        except asyncio.TimeoutError:
            await wait_msg.edit_text("⏱ DISNEY CHECK TIMEOUT\n\nThe request took too long. Please try again.")
            logger.error(f"Disney check timeout for user {chat_id}")
        except Exception as api_error:
            logger.error(f"Disney API error for user {chat_id}: {api_error}")
            await wait_msg.edit_text(f"❌ API Error: {str(api_error)}")

    except Exception as e:
        logger.error(f"Error in Disney command: {e}")
        await message.answer("❌ An error occurred. Please try again later.")

@dp.message(Command("shopify1"))
async def cmd_shopify1(message: Message):
    """Shopify1 Check command"""
    try:
        # Check if gate is active
        gate_status = await db.get_gate_status('shopify1')
        if not gate_status:
            await message.answer("❌ SHOPIFY1 gate is currently disabled by admin.")
            return

        # Check membership first
        is_member = await check_membership_and_notify(message)
        if not is_member:
            return

        # Parse command
        command_text = message.text.strip()
        parts = command_text.split(maxsplit=1)

        if len(parts) < 2:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /shopify1 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/shopify1 5526080000000006|12|28|123"
            )
            return

        card_data = parts[1].strip()

        # Validate format (should have 3 pipes: CARD|MM|YY|CVV)
        if card_data.count('|') != 3:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /shopify1 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/shopify1 5526080000000006|12|28|123"
            )
            return

        # Send processing message
        wait_msg = await message.reply("⏳ Checking Shopify1...")

        # Get user info
        chat_id = message.from_user.id

        # Check and deduct limit
        current_limit = await db.get_user_limit(chat_id, 'shopifylimit')
        if current_limit <= 0:
            await wait_msg.edit_text("❌ SHOPIFY LIMIT EXHAUSTED\n\nYour shopify limit is 0. Please contact admin.")
            return

        # Call Shopify1 API
        try:
            api_url = f"http://localhost/yenicheckbotaerithia/apiler/shopify/shopify1.php?lista={card_data}&chatid={chat_id}"

            async with aiohttp.ClientSession() as session:
                async with session.get(api_url, timeout=aiohttp.ClientTimeout(total=60)) as response:
                    result = await response.text()
                    result = result.strip()

                    # Get BIN info from API and create buttons
                    card_parts = card_data.split('|')
                    bin_number = card_parts[0][:6]

                    keyboard = None
                    try:
                        bin_info = await query_bin_info(bin_number)
                        if isinstance(bin_info, dict):
                            keyboard = InlineKeyboardMarkup(
                                inline_keyboard=[
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['country']}",
                                            callback_data=f"copy_bin_country_{bin_info['country']}"
                                        ),
                                        InlineKeyboardButton(
                                            text=f"{bin_info['type']}",
                                            callback_data=f"copy_bin_type_{bin_info['type']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['level']}",
                                            callback_data=f"copy_bin_level_{bin_info['level']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['bank']}",
                                            callback_data=f"copy_bin_bank_{bin_info['bank']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['brand']}",
                                            callback_data=f"copy_bin_brand_{bin_info['brand']}"
                                        )
                                    ]
                                ])
                    except Exception as bin_error:
                        logger.error(f"BIN API error: {bin_error}")

                    # Update the wait message with result and buttons
                    await wait_msg.edit_text(result, reply_markup=keyboard)

                    # Log to group (super admin hariç)
                    from config import SUPER_ADMIN_ID
                    if chat_id != SUPER_ADMIN_ID:
                        log_group_id = LOG_GROUP_ID
                        username = message.from_user.first_name if message.from_user.first_name else "User"
                        username_mention = f"@{message.from_user.username}" if message.from_user.username else username
                        log_message = f"🚦 {username_mention} {chat_id} shopify1 denedi.\n\n{result}"
                        try:
                            await bot.send_message(log_group_id, log_message)
                        except Exception as log_error:
                            logger.error(f"Failed to send log message: {log_error}")

                    logger.info(f"User {chat_id} performed Shopify1 check")

        except asyncio.TimeoutError:
            await wait_msg.edit_text("⏱ SHOPIFY1 CHECK TIMEOUT\n\nThe request took too long. Please try again.")
            logger.error(f"Shopify1 check timeout for user {chat_id}")
        except Exception as api_error:
            logger.error(f"Shopify1 API error for user {chat_id}: {api_error}")
            await wait_msg.edit_text(f"❌ API Error: {str(api_error)}")

    except Exception as e:
        logger.error(f"Error in Shopify1 command: {e}")
        await message.answer("❌ An error occurred. Please try again later.")

@dp.message(Command("shopify2"))
async def cmd_shopify2(message: Message):
    """Shopify2 Check command"""
    try:
        # Check if gate is active
        gate_status = await db.get_gate_status('shopify2')
        if not gate_status:
            await message.answer("❌ SHOPIFY2 gate is currently disabled by admin.")
            return

        # Check membership first
        is_member = await check_membership_and_notify(message)
        if not is_member:
            return

        # Parse command
        command_text = message.text.strip()
        parts = command_text.split(maxsplit=1)

        if len(parts) < 2:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /shopify2 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/shopify2 5526080000000006|12|28|123"
            )
            return

        card_data = parts[1].strip()

        # Validate format (should have 3 pipes: CARD|MM|YY|CVV)
        if card_data.count('|') != 3:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /shopify2 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/shopify2 5526080000000006|12|28|123"
            )
            return

        # Send processing message
        wait_msg = await message.reply("⏳ Checking Shopify2...")

        # Get user info
        chat_id = message.from_user.id

        # Check and deduct limit
        current_limit = await db.get_user_limit(chat_id, 'shopifylimit')
        if current_limit <= 0:
            await wait_msg.edit_text("❌ SHOPIFY LIMIT EXHAUSTED\n\nYour shopify limit is 0. Please contact admin.")
            return

        # Call Shopify2 API
        try:
            api_url = f"http://localhost/yenicheckbotaerithia/apiler/shopify/shopify2.php?kart={card_data}&chatid={chat_id}"

            async with aiohttp.ClientSession() as session:
                async with session.get(api_url, timeout=aiohttp.ClientTimeout(total=60)) as response:
                    result = await response.text()
                    result = result.strip()

                    # Get BIN info from API and create buttons
                    card_parts = card_data.split('|')
                    bin_number = card_parts[0][:6]

                    keyboard = None
                    try:
                        bin_info = await query_bin_info(bin_number)
                        if isinstance(bin_info, dict):
                            keyboard = InlineKeyboardMarkup(
                                inline_keyboard=[
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['country']}",
                                            callback_data=f"copy_bin_country_{bin_info['country']}"
                                        ),
                                        InlineKeyboardButton(
                                            text=f"{bin_info['type']}",
                                            callback_data=f"copy_bin_type_{bin_info['type']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['level']}",
                                            callback_data=f"copy_bin_level_{bin_info['level']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['bank']}",
                                            callback_data=f"copy_bin_bank_{bin_info['bank']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['brand']}",
                                            callback_data=f"copy_bin_brand_{bin_info['brand']}"
                                        )
                                    ]
                                ])
                    except Exception as bin_error:
                        logger.error(f"BIN API error: {bin_error}")

                    # Update the wait message with result and buttons
                    await wait_msg.edit_text(result, reply_markup=keyboard)

                    # Log to group (super admin hariç)
                    from config import SUPER_ADMIN_ID
                    if chat_id != SUPER_ADMIN_ID:
                        log_group_id = LOG_GROUP_ID
                        username = message.from_user.first_name if message.from_user.first_name else "User"
                        username_mention = f"@{message.from_user.username}" if message.from_user.username else username
                        log_message = f"🚦 {username_mention} {chat_id} shopify2 denedi.\n\n{result}"
                        try:
                            await bot.send_message(log_group_id, log_message)
                        except Exception as log_error:
                            logger.error(f"Failed to send log message: {log_error}")

                    logger.info(f"User {chat_id} performed Shopify2 check")

        except asyncio.TimeoutError:
            await wait_msg.edit_text("⏱ SHOPIFY2 CHECK TIMEOUT\n\nThe request took too long. Please try again.")
            logger.error(f"Shopify2 check timeout for user {chat_id}")
        except Exception as api_error:
            logger.error(f"Shopify2 API error for user {chat_id}: {api_error}")
            await wait_msg.edit_text(f"❌ API Error: {str(api_error)}")

    except Exception as e:
        logger.error(f"Error in Shopify2 command: {e}")
        await message.answer("❌ An error occurred. Please try again later.")

@dp.message(Command("shopify3"))
async def cmd_shopify3(message: Message):
    """Shopify3 Check command"""
    try:
        # Check if gate is active
        gate_status = await db.get_gate_status('shopify3')
        if not gate_status:
            await message.answer("❌ SHOPIFY3 gate is currently disabled by admin.")
            return

        # Check membership first
        is_member = await check_membership_and_notify(message)
        if not is_member:
            return

        # Parse command
        command_text = message.text.strip()
        parts = command_text.split(maxsplit=1)

        if len(parts) < 2:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /shopify3 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/shopify3 5526080000000006|12|28|123"
            )
            return

        card_data = parts[1].strip()

        # Validate format (should have 3 pipes: CARD|MM|YY|CVV)
        if card_data.count('|') != 3:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /shopify3 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/shopify3 5526080000000006|12|28|123"
            )
            return

        # Send processing message
        wait_msg = await message.reply("⏳ Checking Shopify3...")

        # Get user info
        chat_id = message.from_user.id

        # Check and deduct limit
        current_limit = await db.get_user_limit(chat_id, 'shopifylimit')
        if current_limit <= 0:
            await wait_msg.edit_text("❌ SHOPIFY LIMIT EXHAUSTED\n\nYour shopify limit is 0. Please contact admin.")
            return

        # Call Shopify3 API
        try:
            api_url = f"http://localhost/yenicheckbotaerithia/apiler/shopify/shopify3.php?kart={card_data}&chatid={chat_id}"

            async with aiohttp.ClientSession() as session:
                async with session.get(api_url, timeout=aiohttp.ClientTimeout(total=60)) as response:
                    result = await response.text()
                    result = result.strip()

                    # Get BIN info from API and create buttons
                    card_parts = card_data.split('|')
                    bin_number = card_parts[0][:6]

                    keyboard = None
                    try:
                        bin_info = await query_bin_info(bin_number)
                        if isinstance(bin_info, dict):
                            keyboard = InlineKeyboardMarkup(
                                inline_keyboard=[
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['country']}",
                                            callback_data=f"copy_bin_country_{bin_info['country']}"
                                        ),
                                        InlineKeyboardButton(
                                            text=f"{bin_info['type']}",
                                            callback_data=f"copy_bin_type_{bin_info['type']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['level']}",
                                            callback_data=f"copy_bin_level_{bin_info['level']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['bank']}",
                                            callback_data=f"copy_bin_bank_{bin_info['bank']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['brand']}",
                                            callback_data=f"copy_bin_brand_{bin_info['brand']}"
                                        )
                                    ]
                                ])
                    except Exception as bin_error:
                        logger.error(f"BIN API error: {bin_error}")

                    # Update the wait message with result and buttons
                    await wait_msg.edit_text(result, reply_markup=keyboard)

                    # Log to group (super admin hariç)
                    from config import SUPER_ADMIN_ID
                    if chat_id != SUPER_ADMIN_ID:
                        log_group_id = LOG_GROUP_ID
                        username = message.from_user.first_name if message.from_user.first_name else "User"
                        username_mention = f"@{message.from_user.username}" if message.from_user.username else username
                        log_message = f"🚦 {username_mention} {chat_id} shopify3 denedi.\n\n{result}"
                        try:
                            await bot.send_message(log_group_id, log_message)
                        except Exception as log_error:
                            logger.error(f"Failed to send log message: {log_error}")

                    logger.info(f"User {chat_id} performed Shopify3 check")

        except asyncio.TimeoutError:
            await wait_msg.edit_text("⏱ SHOPIFY3 CHECK TIMEOUT\n\nThe request took too long. Please try again.")
            logger.error(f"Shopify3 check timeout for user {chat_id}")
        except Exception as api_error:
            logger.error(f"Shopify3 API error for user {chat_id}: {api_error}")
            await wait_msg.edit_text(f"❌ API Error: {str(api_error)}")

    except Exception as e:
        logger.error(f"Error in Shopify3 command: {e}")
        await message.answer("❌ An error occurred. Please try again later.")

@dp.message(Command("authnet"))
async def cmd_authnet(message: Message):
    """Authorize.NET Check command"""
    try:
        # Check if gate is active
        gate_status = await db.get_gate_status('authnet')
        if not gate_status:
            await message.answer("❌ AUTHNET gate is currently disabled by admin.")
            return

        # Check membership first
        is_member = await check_membership_and_notify(message)
        if not is_member:
            return

        # Parse command
        command_text = message.text.strip()
        parts = command_text.split(maxsplit=1)

        if len(parts) < 2:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /authnet CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/authnet 5526080000000006|12|2028|123"
            )
            return

        card_data = parts[1].strip()

        # Validate format (should have 3 pipes: CARD|MM|YY|CVV)
        if card_data.count('|') != 3:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /authnet CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/authnet 5526080000000006|12|2028|123"
            )
            return

        # Send processing message
        wait_msg = await message.reply("⏳ Checking Authorize.NET...")

        # Get user info
        chat_id = message.from_user.id

        # Check and deduct limit
        current_limit = await db.get_user_limit(chat_id, 'authnetlimit')
        if current_limit <= 0:
            await wait_msg.edit_text("❌ AUTHNET LIMIT EXHAUSTED\n\nYour authnet limit is 0. Please contact admin.")
            return

        # Call Authnet API
        try:
            api_url = f"http://localhost/yenicheckbotaerithia/apiler/authorizenet/authnet.php?card={card_data}&chatid={chat_id}"

            async with aiohttp.ClientSession() as session:
                async with session.get(api_url, timeout=aiohttp.ClientTimeout(total=60)) as response:
                    result = await response.text()

                    # Extract BIN for button
                    card_number = card_data.split('|')[0]
                    bin_number = card_number[:6] if len(card_number) >= 6 else None

                    # Create keyboard with BIN button
                    keyboard = InlineKeyboardMarkup(inline_keyboard=[])

                    if bin_number:
                        try:
                            bin_info = await query_bin_info(bin_number)
                            if bin_info:
                                keyboard = InlineKeyboardMarkup(inline_keyboard=[
                                    [
                                        InlineKeyboardButton(
                                            text=f"BIN: {bin_number}",
                                            callback_data=f"copy_bin_{bin_number}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['country']} | {bin_info['type']}",
                                            callback_data=f"copy_bin_country_{bin_info['country']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['bank']}",
                                            callback_data=f"copy_bin_bank_{bin_info['bank']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['brand']}",
                                            callback_data=f"copy_bin_brand_{bin_info['brand']}"
                                        )
                                    ]
                                ])
                        except Exception as bin_error:
                            logger.error(f"BIN API error: {bin_error}")

                    # Update the wait message with result and buttons
                    await wait_msg.edit_text(result, reply_markup=keyboard)

                    # Log to group (super admin hariç)
                    from config import SUPER_ADMIN_ID
                    if chat_id != SUPER_ADMIN_ID:
                        log_group_id = LOG_GROUP_ID
                        username = message.from_user.first_name if message.from_user.first_name else "User"
                        username_mention = f"@{message.from_user.username}" if message.from_user.username else username
                        log_message = f"🚦 {username_mention} {chat_id} authnet denedi.\n\n{result}"
                        try:
                            await bot.send_message(log_group_id, log_message)
                        except Exception as log_error:
                            logger.error(f"Failed to send log message: {log_error}")

                    logger.info(f"User {chat_id} performed Authnet check")

        except asyncio.TimeoutError:
            await wait_msg.edit_text("⏱ AUTHNET CHECK TIMEOUT\n\nThe request took too long. Please try again.")
            logger.error(f"Authnet check timeout for user {chat_id}")
        except Exception as api_error:
            logger.error(f"Authnet API error for user {chat_id}: {api_error}")
            await wait_msg.edit_text(f"❌ API Error: {str(api_error)}")

    except Exception as e:
        logger.error(f"Error in Authnet command: {e}")
        await message.answer("❌ An error occurred. Please try again later.")

@dp.message(Command("iyzico1"))
async def cmd_iyzico1(message: Message):
    """İYZİCO1 Charge Check command"""
    try:
        # Check if gate is active
        gate_status = await db.get_gate_status('iyzico1')
        if not gate_status:
            await message.answer("❌ İYZİCO1 gate is currently disabled by admin.")
            return

        # Check membership first
        is_member = await check_membership_and_notify(message)
        if not is_member:
            return

        # Parse command
        command_text = message.text.strip()
        parts = command_text.split(maxsplit=1)

        if len(parts) < 2:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /iyzico1 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/iyzico1 5526080000000006|12|2028|123"
            )
            return

        card_data = parts[1].strip()

        # Validate format (should have 3 pipes: CARD|MM|YY|CVV)
        if card_data.count('|') != 3:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /iyzico1 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/iyzico1 5526080000000006|12|2028|123"
            )
            return

        # Send processing message
        wait_msg = await message.reply("⏳ Checking İYZİCO1...")

        # Get user info
        chat_id = message.from_user.id

        # Check and deduct limit
        current_limit = await db.get_user_limit(chat_id, 'iyzicolimit')
        if current_limit <= 0:
            await wait_msg.edit_text("❌ İYZİCO LIMIT EXHAUSTED\n\nYour iyzico limit is 0. Please contact admin.")
            return

        # Call İyzico1 API
        try:
            api_url = f"http://localhost/yenicheckbotaerithia/apiler/iyzicoapiler/iyzico1.php?kart={card_data}&chatid={chat_id}"

            async with aiohttp.ClientSession() as session:
                async with session.get(api_url, timeout=aiohttp.ClientTimeout(total=60)) as response:
                    result = await response.text()

                    # Extract BIN for button
                    card_number = card_data.split('|')[0]
                    bin_number = card_number[:6] if len(card_number) >= 6 else None

                    # Create keyboard with BIN button
                    keyboard = InlineKeyboardMarkup(inline_keyboard=[])

                    if bin_number:
                        try:
                            bin_info = await query_bin_info(bin_number)
                            if bin_info:
                                keyboard = InlineKeyboardMarkup(inline_keyboard=[
                                    [
                                        InlineKeyboardButton(
                                            text=f"BIN: {bin_number}",
                                            callback_data=f"copy_bin_{bin_number}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['country']} | {bin_info['type']}",
                                            callback_data=f"copy_bin_country_{bin_info['country']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['bank']}",
                                            callback_data=f"copy_bin_bank_{bin_info['bank']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['brand']}",
                                            callback_data=f"copy_bin_brand_{bin_info['brand']}"
                                        )
                                    ]
                                ])
                        except Exception as bin_error:
                            logger.error(f"BIN API error: {bin_error}")

                    # Update the wait message with result and buttons
                    await wait_msg.edit_text(result, reply_markup=keyboard)

                    # Log to group (super admin hariç)
                    from config import SUPER_ADMIN_ID
                    if chat_id != SUPER_ADMIN_ID:
                        log_group_id = LOG_GROUP_ID
                        username = message.from_user.first_name if message.from_user.first_name else "User"
                        username_mention = f"@{message.from_user.username}" if message.from_user.username else username
                        log_message = f"🚦 {username_mention} {chat_id} iyzico1 denedi.\n\n{result}"
                        try:
                            await bot.send_message(log_group_id, log_message)
                        except Exception as log_error:
                            logger.error(f"Failed to send log message: {log_error}")

                    logger.info(f"User {chat_id} performed İyzico1 check")

        except asyncio.TimeoutError:
            await wait_msg.edit_text("⏱ İYZİCO1 CHECK TIMEOUT\n\nThe request took too long. Please try again.")
            logger.error(f"İyzico1 check timeout for user {chat_id}")
        except Exception as api_error:
            logger.error(f"İyzico1 API error for user {chat_id}: {api_error}")
            await wait_msg.edit_text(f"❌ API Error: {str(api_error)}")

    except Exception as e:
        logger.error(f"Error in İyzico1 command: {e}")
        await message.answer("❌ An error occurred. Please try again later.")

@dp.message(Command("iyzico2"))
async def cmd_iyzico2(message: Message):
    """İYZİCO2 395₺ Charge Check command"""
    try:
        # Check if gate is active
        gate_status = await db.get_gate_status('iyzico2')
        if not gate_status:
            await message.answer("❌ İYZİCO2 gate is currently disabled by admin.")
            return

        # Check membership first
        is_member = await check_membership_and_notify(message)
        if not is_member:
            return

        # Parse command
        command_text = message.text.strip()
        parts = command_text.split(maxsplit=1)

        if len(parts) < 2:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /iyzico2 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/iyzico2 5526080000000006|12|2028|123"
            )
            return

        card_data = parts[1].strip()

        # Validate format (should have 3 pipes: CARD|MM|YY|CVV)
        if card_data.count('|') != 3:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /iyzico2 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/iyzico2 5526080000000006|12|2028|123"
            )
            return

        # Send processing message
        wait_msg = await message.reply("⏳ Checking İYZİCO2...")

        # Get user info
        chat_id = message.from_user.id

        # Check and deduct limit
        current_limit = await db.get_user_limit(chat_id, 'iyzicolimit')
        if current_limit <= 0:
            await wait_msg.edit_text("❌ İYZİCO LIMIT EXHAUSTED\n\nYour iyzico limit is 0. Please contact admin.")
            return

        # Call İyzico2 API
        try:
            api_url = f"http://localhost/yenicheckbotaerithia/apiler/iyzicoapiler/iyzico2.php?kart={card_data}&chatid={chat_id}"

            async with aiohttp.ClientSession() as session:
                async with session.get(api_url, timeout=aiohttp.ClientTimeout(total=60)) as response:
                    result = await response.text()

                    # Extract BIN for button
                    card_number = card_data.split('|')[0]
                    bin_number = card_number[:6] if len(card_number) >= 6 else None

                    # Create keyboard with BIN button
                    keyboard = InlineKeyboardMarkup(inline_keyboard=[])

                    if bin_number:
                        try:
                            bin_info = await query_bin_info(bin_number)
                            if bin_info:
                                keyboard = InlineKeyboardMarkup(inline_keyboard=[
                                    [
                                        InlineKeyboardButton(
                                            text=f"BIN: {bin_number}",
                                            callback_data=f"copy_bin_{bin_number}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['country']} | {bin_info['type']}",
                                            callback_data=f"copy_bin_country_{bin_info['country']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['bank']}",
                                            callback_data=f"copy_bin_bank_{bin_info['bank']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['brand']}",
                                            callback_data=f"copy_bin_brand_{bin_info['brand']}"
                                        )
                                    ]
                                ])
                        except Exception as bin_error:
                            logger.error(f"BIN API error: {bin_error}")

                    # Update the wait message with result and buttons
                    await wait_msg.edit_text(result, reply_markup=keyboard)

                    # Log to group (super admin hariç)
                    from config import SUPER_ADMIN_ID
                    if chat_id != SUPER_ADMIN_ID:
                        log_group_id = LOG_GROUP_ID
                        username = message.from_user.first_name if message.from_user.first_name else "User"
                        username_mention = f"@{message.from_user.username}" if message.from_user.username else username
                        log_message = f"🚦 {username_mention} {chat_id} iyzico2 denedi.\n\n{result}"
                        try:
                            await bot.send_message(log_group_id, log_message)
                        except Exception as log_error:
                            logger.error(f"Failed to send log message: {log_error}")

                    logger.info(f"User {chat_id} performed İyzico2 check")

        except asyncio.TimeoutError:
            await wait_msg.edit_text("⏱ İYZİCO2 CHECK TIMEOUT\n\nThe request took too long. Please try again.")
            logger.error(f"İyzico2 check timeout for user {chat_id}")
        except Exception as api_error:
            logger.error(f"İyzico2 API error for user {chat_id}: {api_error}")
            await wait_msg.edit_text(f"❌ API Error: {str(api_error)}")

    except Exception as e:
        logger.error(f"Error in İyzico2 command: {e}")
        await message.answer("❌ An error occurred. Please try again later.")

@dp.message(Command("iyzico3"))
async def cmd_iyzico3(message: Message):
    """İYZİCO3 267.40₺ Charge Check command"""
    try:
        # Check if gate is active
        gate_status = await db.get_gate_status('iyzico3')
        if not gate_status:
            await message.answer("❌ İYZİCO3 gate is currently disabled by admin.")
            return

        # Check membership first
        is_member = await check_membership_and_notify(message)
        if not is_member:
            return

        # Parse command
        command_text = message.text.strip()
        parts = command_text.split(maxsplit=1)

        if len(parts) < 2:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /iyzico3 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/iyzico3 5526080000000006|12|2028|123"
            )
            return

        card_data = parts[1].strip()

        # Validate format (should have 3 pipes: CARD|MM|YY|CVV)
        if card_data.count('|') != 3:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /iyzico3 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/iyzico3 5526080000000006|12|2028|123"
            )
            return

        # Send processing message
        wait_msg = await message.reply("⏳ Checking İYZİCO3...")

        # Get user info
        chat_id = message.from_user.id

        # Check and deduct limit
        current_limit = await db.get_user_limit(chat_id, 'iyzicolimit')
        if current_limit <= 0:
            await wait_msg.edit_text("❌ İYZİCO LIMIT EXHAUSTED\n\nYour iyzico limit is 0. Please contact admin.")
            return

        # Call İyzico3 API
        try:
            api_url = f"http://localhost/yenicheckbotaerithia/apiler/iyzicoapiler/iyzico3.php?kart={card_data}&chatid={chat_id}"

            async with aiohttp.ClientSession() as session:
                async with session.get(api_url, timeout=aiohttp.ClientTimeout(total=60)) as response:
                    result = await response.text()

                    # Extract BIN for button
                    card_number = card_data.split('|')[0]
                    bin_number = card_number[:6] if len(card_number) >= 6 else None

                    # Create keyboard with BIN button
                    keyboard = InlineKeyboardMarkup(inline_keyboard=[])

                    if bin_number:
                        try:
                            bin_info = await query_bin_info(bin_number)
                            if bin_info:
                                keyboard = InlineKeyboardMarkup(inline_keyboard=[
                                    [
                                        InlineKeyboardButton(
                                            text=f"BIN: {bin_number}",
                                            callback_data=f"copy_bin_{bin_number}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['country']} | {bin_info['type']}",
                                            callback_data=f"copy_bin_country_{bin_info['country']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['bank']}",
                                            callback_data=f"copy_bin_bank_{bin_info['bank']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['brand']}",
                                            callback_data=f"copy_bin_brand_{bin_info['brand']}"
                                        )
                                    ]
                                ])
                        except Exception as bin_error:
                            logger.error(f"BIN API error: {bin_error}")

                    # Update the wait message with result and buttons
                    await wait_msg.edit_text(result, reply_markup=keyboard)

                    # Log to group (super admin hariç)
                    from config import SUPER_ADMIN_ID
                    if chat_id != SUPER_ADMIN_ID:
                        log_group_id = LOG_GROUP_ID
                        username = message.from_user.first_name if message.from_user.first_name else "User"
                        username_mention = f"@{message.from_user.username}" if message.from_user.username else username
                        log_message = f"🚦 {username_mention} {chat_id} iyzico3 denedi.\n\n{result}"
                        try:
                            await bot.send_message(log_group_id, log_message)
                        except Exception as log_error:
                            logger.error(f"Failed to send log message: {log_error}")

                    logger.info(f"User {chat_id} performed İyzico3 check")

        except asyncio.TimeoutError:
            await wait_msg.edit_text("⏱ İYZİCO3 CHECK TIMEOUT\n\nThe request took too long. Please try again.")
            logger.error(f"İyzico3 check timeout for user {chat_id}")
        except Exception as api_error:
            logger.error(f"İyzico3 API error for user {chat_id}: {api_error}")
            await wait_msg.edit_text(f"❌ API Error: {str(api_error)}")

    except Exception as e:
        logger.error(f"Error in İYZİCO3 check command: {e}")
        await message.answer("An error occurred. Please try again.")

@dp.message(Command("iyzico4"))
async def cmd_iyzico4(message: Message):
    """İYZİCO4 1020₺ Charge Check command"""
    try:
        # Check membership first
        is_member = await check_membership_and_notify(message)
        if not is_member:
            return

        # Parse command
        command_text = message.text.strip()
        parts = command_text.split(maxsplit=1)

        if len(parts) < 2:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /iyzico4 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/iyzico4 5526080000000006|12|2028|123"
            )
            return

        card_data = parts[1].strip()

        # Validate format (should have 3 pipes: CARD|MM|YY|CVV)
        if card_data.count('|') != 3:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /iyzico4 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/iyzico4 5526080000000006|12|2028|123"
            )
            return

        # Send processing message
        wait_msg = await message.reply("⏳ Checking İYZİCO4...")

        # Get user info
        chat_id = message.from_user.id

        # Check and deduct limit
        current_limit = await db.get_user_limit(chat_id, 'iyzicolimit')
        if current_limit <= 0:
            await wait_msg.edit_text("❌ İYZİCO LIMIT EXHAUSTED\n\nYour iyzico limit is 0. Please contact admin.")
            return

        # Call İyzico4 API
        try:
            api_url = f"http://localhost/yenicheckbotaerithia/apiler/iyzicoapiler/iyzico4.php?kart={card_data}&chatid={chat_id}"

            async with aiohttp.ClientSession() as session:
                async with session.get(api_url, timeout=aiohttp.ClientTimeout(total=60)) as response:
                    result = await response.text()

                    # Extract BIN for button
                    card_number = card_data.split('|')[0]
                    bin_number = card_number[:6] if len(card_number) >= 6 else None

                    # Create keyboard with BIN button
                    keyboard = InlineKeyboardMarkup(inline_keyboard=[])

                    if bin_number:
                        try:
                            bin_info = await query_bin_info(bin_number)
                            if bin_info:
                                keyboard = InlineKeyboardMarkup(inline_keyboard=[
                                    [
                                        InlineKeyboardButton(
                                            text=f"BIN: {bin_number}",
                                            callback_data=f"copy_bin_{bin_number}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['country']} | {bin_info['type']}",
                                            callback_data=f"copy_bin_country_{bin_info['country']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['bank']}",
                                            callback_data=f"copy_bin_bank_{bin_info['bank']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['brand']}",
                                            callback_data=f"copy_bin_brand_{bin_info['brand']}"
                                        )
                                    ]
                                ])
                        except Exception as bin_error:
                            logger.error(f"BIN API error: {bin_error}")

                    # Update the wait message with result and buttons
                    await wait_msg.edit_text(result, reply_markup=keyboard)

                    # Log to group (super admin hariç)
                    from config import SUPER_ADMIN_ID
                    if chat_id != SUPER_ADMIN_ID:
                        log_group_id = LOG_GROUP_ID
                        username = message.from_user.first_name if message.from_user.first_name else "User"
                        username_mention = f"@{message.from_user.username}" if message.from_user.username else username
                        log_message = f"🚦 {username_mention} {chat_id} iyzico4 denedi.\n\n{result}"
                        try:
                            await bot.send_message(log_group_id, log_message)
                        except Exception as log_error:
                            logger.error(f"Failed to send log message: {log_error}")

                    logger.info(f"User {chat_id} performed İyzico4 check")

        except asyncio.TimeoutError:
            await wait_msg.edit_text("⏱ İYZİCO4 CHECK TIMEOUT\n\nThe request took too long. Please try again.")
            logger.error(f"İyzico4 check timeout for user {chat_id}")
        except Exception as api_error:
            logger.error(f"İyzico4 API error for user {chat_id}: {api_error}")
            await wait_msg.edit_text(f"❌ API Error: {str(api_error)}")

    except Exception as e:
        logger.error(f"Error in İyzico3 command: {e}")
        await message.answer("❌ An error occurred. Please try again later.")

@dp.message(Command("puan4"))
async def cmd_puan4(message: Message):
    """PUAN4 Check command"""
    try:
        # Check if gate is active
        gate_status = await db.get_gate_status('puan4')
        if not gate_status:
            await message.answer("❌ PUAN4 gate is currently disabled by admin.")
            return

        # Check membership first
        is_member = await check_membership_and_notify(message)
        if not is_member:
            return

        # Parse command
        command_text = message.text.strip()
        parts = command_text.split(maxsplit=1)

        if len(parts) < 2:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /puan4 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/puan4 5526080000000006|12|2028|123"
            )
            return

        card_data = parts[1].strip()

        # Validate format (should have 3 pipes: CARD|MM|YY|CVV)
        if card_data.count('|') != 3:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /puan4 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/puan4 5526080000000006|12|2028|123"
            )
            return

        # Send processing message
        wait_msg = await message.reply("⏳ Checking PUAN4...")

        # Get user info
        chat_id = message.from_user.id

        # Check and deduct limit
        current_limit = await db.get_user_limit(chat_id, 'puanlimit')
        if current_limit <= 0:
            await wait_msg.edit_text("❌ PUAN LIMIT EXHAUSTED\n\nYour puan limit is 0. Please contact admin.")
            return

        # Call Puan4 API
        try:
            api_url = f"http://localhost/yenicheckbotaerithia/apiler/puanapiler/puan4.php?card={card_data}&chatid={chat_id}"

            async with aiohttp.ClientSession() as session:
                async with session.get(api_url, timeout=aiohttp.ClientTimeout(total=60)) as response:
                    result = await response.text()

                    # Extract BIN for button
                    card_number = card_data.split('|')[0]
                    bin_number = card_number[:6] if len(card_number) >= 6 else None

                    # Create keyboard with BIN button
                    keyboard = InlineKeyboardMarkup(inline_keyboard=[])

                    if bin_number:
                        try:
                            bin_info = await query_bin_info(bin_number)
                            if bin_info:
                                keyboard = InlineKeyboardMarkup(inline_keyboard=[
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['country']}",
                                            callback_data=f"copy_bin_country_{bin_info['country']}"
                                        ),
                                        InlineKeyboardButton(
                                            text=f"{bin_info['type']}",
                                            callback_data=f"copy_bin_type_{bin_info['type']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['level']}",
                                            callback_data=f"copy_bin_level_{bin_info['level']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['bank']}",
                                            callback_data=f"copy_bin_bank_{bin_info['bank']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['brand']}",
                                            callback_data=f"copy_bin_brand_{bin_info['brand']}"
                                        )
                                    ]
                                ])
                        except Exception as bin_error:
                            logger.error(f"BIN API error: {bin_error}")

                    # Update the wait message with result and buttons
                    await wait_msg.edit_text(result, reply_markup=keyboard)

                    # Log to group (super admin hariç)
                    from config import SUPER_ADMIN_ID
                    if chat_id != SUPER_ADMIN_ID:
                        log_group_id = LOG_GROUP_ID
                        username = message.from_user.first_name if message.from_user.first_name else "User"
                        username_mention = f"@{message.from_user.username}" if message.from_user.username else username
                        log_message = f"🚦 {username_mention} {chat_id} puan4 denedi.\n\n{result}"
                        try:
                            await bot.send_message(log_group_id, log_message)
                        except Exception as log_error:
                            logger.error(f"Failed to send log message: {log_error}")

                    logger.info(f"User {chat_id} performed Puan4 check")

        except asyncio.TimeoutError:
            await wait_msg.edit_text("⏱ PUAN4 CHECK TIMEOUT\n\nThe request took too long. Please try again.")
            logger.error(f"Puan4 check timeout for user {chat_id}")
        except Exception as api_error:
            logger.error(f"Puan4 API error for user {chat_id}: {api_error}")
            await wait_msg.edit_text(f"❌ API Error: {str(api_error)}")

    except Exception as e:
        logger.error(f"Error in Puan4 command: {e}")
        await message.answer("❌ An error occurred. Please try again later.")

@dp.message(Command("puan1"))
async def cmd_puan1(message: Message):
    """PUAN1 Check command"""
    try:
        # Check if gate is active
        gate_status = await db.get_gate_status('puan1')
        if not gate_status:
            await message.answer("❌ PUAN1 gate is currently disabled by admin.")
            return

        # Check membership first
        is_member = await check_membership_and_notify(message)
        if not is_member:
            return

        # Parse command
        command_text = message.text.strip()
        parts = command_text.split(maxsplit=1)

        if len(parts) < 2:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /puan1 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/puan1 5526080000000006|12|2028|123"
            )
            return

        card_data = parts[1].strip()

        # Validate format (should have 3 pipes: CARD|MM|YY|CVV)
        if card_data.count('|') != 3:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /puan1 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/puan1 5526080000000006|12|2028|123"
            )
            return

        # Send processing message
        wait_msg = await message.reply("⏳ Checking PUAN1...")

        # Get user info
        chat_id = message.from_user.id

        # Check and deduct limit
        current_limit = await db.get_user_limit(chat_id, 'puanlimit')
        if current_limit <= 0:
            await wait_msg.edit_text("❌ PUAN LIMIT EXHAUSTED\n\nYour puan limit is 0. Please contact admin.")
            return

        # Call Puan1 API
        try:
            api_url = f"http://localhost/yenicheckbotaerithia/apiler/puanapiler/puanapi1.php?card={card_data}&chatid={chat_id}"

            async with aiohttp.ClientSession() as session:
                async with session.get(api_url, timeout=aiohttp.ClientTimeout(total=60)) as response:
                    result = await response.text()

                    # Extract BIN for button
                    card_number = card_data.split('|')[0]
                    bin_number = card_number[:6] if len(card_number) >= 6 else None

                    # Create keyboard with BIN button
                    keyboard = InlineKeyboardMarkup(inline_keyboard=[])

                    if bin_number:
                        try:
                            bin_info = await query_bin_info(bin_number)
                            if bin_info:
                                keyboard = InlineKeyboardMarkup(inline_keyboard=[
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['country']}",
                                            callback_data=f"copy_bin_country_{bin_info['country']}"
                                        ),
                                        InlineKeyboardButton(
                                            text=f"{bin_info['type']}",
                                            callback_data=f"copy_bin_type_{bin_info['type']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['level']}",
                                            callback_data=f"copy_bin_level_{bin_info['level']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['bank']}",
                                            callback_data=f"copy_bin_bank_{bin_info['bank']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['brand']}",
                                            callback_data=f"copy_bin_brand_{bin_info['brand']}"
                                        )
                                    ]
                                ])
                        except Exception as bin_error:
                            logger.error(f"BIN API error: {bin_error}")

                    # Update the wait message with result and buttons
                    await wait_msg.edit_text(result, reply_markup=keyboard)

                    # Log to group (super admin hariç)
                    from config import SUPER_ADMIN_ID
                    if chat_id != SUPER_ADMIN_ID:
                        log_group_id = LOG_GROUP_ID
                        username = message.from_user.first_name if message.from_user.first_name else "User"
                        username_mention = f"@{message.from_user.username}" if message.from_user.username else username
                        log_message = f"🚦 {username_mention} {chat_id} puan1 denedi.\n\n{result}"
                        try:
                            await bot.send_message(log_group_id, log_message)
                        except Exception as log_error:
                            logger.error(f"Failed to send log message: {log_error}")

                    logger.info(f"User {chat_id} performed Puan1 check")

        except asyncio.TimeoutError:
            await wait_msg.edit_text("⏱ PUAN1 CHECK TIMEOUT\n\nThe request took too long. Please try again.")
            logger.error(f"Puan1 check timeout for user {chat_id}")
        except Exception as api_error:
            logger.error(f"Puan1 API error for user {chat_id}: {api_error}")
            await wait_msg.edit_text(f"❌ API Error: {str(api_error)}")

    except Exception as e:
        logger.error(f"Error in Puan1 command: {e}")
        await message.answer("❌ An error occurred. Please try again later.")

@dp.message(Command("puan2"))
async def cmd_puan2(message: Message):
    """PUAN2 Check command"""
    try:
        # Check if gate is active
        gate_status = await db.get_gate_status('puan2')
        if not gate_status:
            await message.answer("❌ PUAN2 gate is currently disabled by admin.")
            return

        # Check membership first
        is_member = await check_membership_and_notify(message)
        if not is_member:
            return

        # Parse command
        command_text = message.text.strip()
        parts = command_text.split(maxsplit=1)

        if len(parts) < 2:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /puan2 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/puan2 5526080000000006|12|2028|123"
            )
            return

        card_data = parts[1].strip()

        # Validate format (should have 3 pipes: CARD|MM|YY|CVV)
        if card_data.count('|') != 3:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /puan2 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/puan2 5526080000000006|12|2028|123"
            )
            return

        # Send processing message
        wait_msg = await message.reply("⏳ Checking PUAN2...")

        # Get user info
        chat_id = message.from_user.id

        # Check and deduct limit
        current_limit = await db.get_user_limit(chat_id, 'puanlimit')
        if current_limit <= 0:
            await wait_msg.edit_text("❌ PUAN2 LIMIT EXHAUSTED\n\nYour puan limit is 0. Please contact admin.")
            return

        # Call Puan2 API
        try:
            api_url = f"http://localhost/yenicheckbotaerithia/apiler/puanapiler/puan2.php?card={card_data}&chatid={chat_id}"

            async with aiohttp.ClientSession() as session:
                async with session.get(api_url, timeout=aiohttp.ClientTimeout(total=60)) as response:
                    result = await response.text()

                    # Extract BIN for button
                    card_number = card_data.split('|')[0]
                    bin_number = card_number[:6] if len(card_number) >= 6 else None

                    # Create keyboard with BIN button
                    keyboard = InlineKeyboardMarkup(inline_keyboard=[])

                    if bin_number:
                        try:
                            bin_info = await query_bin_info(bin_number)
                            if bin_info:
                                keyboard = InlineKeyboardMarkup(inline_keyboard=[
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['country']}",
                                            callback_data=f"copy_bin_country_{bin_info['country']}"
                                        ),
                                        InlineKeyboardButton(
                                            text=f"{bin_info['type']}",
                                            callback_data=f"copy_bin_type_{bin_info['type']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['level']}",
                                            callback_data=f"copy_bin_level_{bin_info['level']}"
                                        )
                                    ]
                                ])
                        except Exception as bin_error:
                            logger.error(f"Error getting BIN info: {bin_error}")

                    await wait_msg.edit_text(result, reply_markup=keyboard)

                    # Log to group (super admin hariç)
                    from config import SUPER_ADMIN_ID
                    if chat_id != SUPER_ADMIN_ID:
                        log_group_id = LOG_GROUP_ID
                        try:
                            username = message.from_user.username or message.from_user.first_name
                            username_mention = f"@{username}" if message.from_user.username else username
                            log_message = f"🚦 {username_mention} {chat_id} puan2 denedi.\n\n{result}"
                            await bot.send_message(log_group_id, log_message)
                        except Exception as log_error:
                            logger.error(f"Failed to send puan2 log: {log_error}")

                    logger.info(f"User {chat_id} performed PUAN2 check on {card_data}")

        except Exception as e:
            logger.error(f"Error calling PUAN2 API: {e}")
            await wait_msg.edit_text("❌ API error occurred. Please try again later.")

    except Exception as e:
        logger.error(f"Error in Puan2 command: {e}")
        await message.answer("❌ An error occurred. Please try again later.")

@dp.message(Command("puan3"))
async def cmd_puan3(message: Message):
    """PUAN3 Check command"""
    try:
        # Check membership first
        is_member = await check_membership_and_notify(message)
        if not is_member:
            return

        # Parse command
        command_text = message.text.strip()
        parts = command_text.split(maxsplit=1)

        if len(parts) < 2:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /puan3 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/puan3 5526080000000006|12|2028|123"
            )
            return

        card_data = parts[1].strip()

        # Validate format (should have 3 pipes: CARD|MM|YY|CVV)
        if card_data.count('|') != 3:
            await message.answer(
                "INVALID FORMAT\n\n"
                "Usage: /puan3 CARD|MM|YY|CVV\n\n"
                "Example:\n"
                "/puan3 5526080000000006|12|2028|123"
            )
            return

        # Send processing message
        wait_msg = await message.reply("⏳ Checking PUAN3...")

        # Get user info
        chat_id = message.from_user.id

        # Call Puan3 API
        try:
            api_url = f"http://localhost/yenicheckbotaerithia/apiler/puanapiler/puan3.php?card={card_data}&chatid={chat_id}"

            async with aiohttp.ClientSession() as session:
                async with session.get(api_url, timeout=aiohttp.ClientTimeout(total=60)) as response:
                    result = await response.text()

                    # Extract BIN for button
                    card_number = card_data.split('|')[0]
                    bin_number = card_number[:6] if len(card_number) >= 6 else None

                    # Create keyboard with BIN button
                    keyboard = InlineKeyboardMarkup(inline_keyboard=[])

                    if bin_number:
                        try:
                            bin_info = await query_bin_info(bin_number)
                            if bin_info:
                                keyboard = InlineKeyboardMarkup(inline_keyboard=[
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['country']}",
                                            callback_data=f"copy_bin_country_{bin_info['country']}"
                                        ),
                                        InlineKeyboardButton(
                                            text=f"{bin_info['type']}",
                                            callback_data=f"copy_bin_type_{bin_info['type']}"
                                        )
                                    ],
                                    [
                                        InlineKeyboardButton(
                                            text=f"{bin_info['level']}",
                                            callback_data=f"copy_bin_level_{bin_info['level']}"
                                        )
                                    ]
                                ])
                        except Exception as bin_error:
                            logger.error(f"Error getting BIN info: {bin_error}")

                    await wait_msg.edit_text(result, reply_markup=keyboard)

                    # Log to group (super admin hariç)
                    from config import SUPER_ADMIN_ID
                    if chat_id != SUPER_ADMIN_ID:
                        log_group_id = LOG_GROUP_ID
                        try:
                            username = message.from_user.username or message.from_user.first_name
                            username_mention = f"@{username}" if message.from_user.username else username
                            log_message = f"🚦 {username_mention} {chat_id} puan3 denedi.\n\n{result}"
                            await bot.send_message(log_group_id, log_message)
                        except Exception as log_error:
                            logger.error(f"Failed to send puan3 log: {log_error}")

                    logger.info(f"User {chat_id} performed PUAN3 check on {card_data}")

        except Exception as e:
            logger.error(f"Error calling PUAN3 API: {e}")
            await wait_msg.edit_text("❌ API error occurred. Please try again later.")

    except Exception as e:
        logger.error(f"Error in Puan3 command: {e}")
        await message.answer("❌ An error occurred. Please try again later.")

@dp.message(Command("auth1mass"))
async def cmd_auth1_mass(message: Message):
    """TRAUTH1 Mass Check command"""
    try:
        # Check if gate is active
        gate_status = await db.get_gate_status('auth1mass')
        if not gate_status:
            await message.answer("❌ TRAUTH1 MASS gate is currently disabled by admin.")
            return

        # Check membership first
        is_member = await check_membership_and_notify(message)
        if not is_member:
            return

        # Parse command
        command_text = message.text.strip()
        lines = command_text.split('\n')

        if len(lines) < 2:
            await message.answer(
                "❌ INVALID FORMAT\n\n"
                "Usage: /auth1mass followed by cards (one per line)\n\n"
                "Example:\n"
                "/auth1mass\n"
                "5430811586252701|08|28|217\n"
                "5430811586252702|08|28|217\n"
                "5430811586252703|08|28|217"
            )
            return

        # Extract cards (skip first line which is the command)
        cards = []
        for line in lines[1:]:
            line = line.strip()
            if line and line.count('|') == 3:
                cards.append(line)

        if not cards:
            await message.answer("❌ No valid cards found. Format: CARD|MM|YY|CVV")
            return

        # Check card limit (max 20 cards per request)
        if len(cards) > 20:
            await message.answer(f"❌ Maximum 20 cards allowed per request. You provided {len(cards)} cards.")
            return

        # Get user chat ID
        chat_id = message.from_user.id

        # Check total auth limit
        current_limit = await db.get_user_limit(chat_id, 'authlimit')
        if current_limit < len(cards):
            await message.answer(f"❌ Not enough Auth limit. Need {len(cards)}, have {current_limit}")
            return

        # Send initial message
        status_msg = await message.reply(
            f"𝐀𝐔𝐓𝐇𝟏 𝐌𝐀𝐒𝐒 𝐒𝐓𝐀𝐑𝐓𝐄𝐃\n\n"
            f"Processing {len(cards)} cards...\n\n"
            f"Please wait..."
        )

        # Process cards one by one
        results = []
        live_count = 0
        declined_count = 0
        total_cards = len(cards)

        async with aiohttp.ClientSession() as session:
            for idx, card in enumerate(cards):
                # Deduct limit before processing
                await db.decrement_limit(chat_id, 'authlimit')

                # Call API for single card
                api_url = f"http://localhost/yenicheckbotaerithia/apiler/auth1/voltkart.php?kart={card}"

                try:
                    async with session.get(api_url, timeout=aiohttp.ClientTimeout(total=30)) as response:
                        result_text = await response.text()

                        # Extract just the card line (first line before any newlines)
                        result_line = result_text.split('\n')[0] if result_text else f"{card} | ❌Error"
                        results.append(result_line)

                        # Count live vs declined
                        if "✅" in result_line or "LIVE" in result_line.upper():
                            live_count += 1
                        else:
                            declined_count += 1

                except Exception as e:
                    results.append(f"{card} | ❌Error")
                    declined_count += 1
                    logger.error(f"Error checking card {card}: {e}")

                # Update message after each card
                current_limit = await db.get_user_limit(chat_id, 'authlimit')
                current_processed = idx + 1

                results_text = f"𝐀𝐔𝐓𝐇𝟏 𝐌𝐀𝐒𝐒 𝐑𝐄𝐒𝐔𝐋𝐓:\n\n{current_processed}/{total_cards}\n\n" + "\n".join(results)
                results_text += f"\n\n✅𝐋𝐈𝐕𝐄:{live_count} | ❌𝐃𝐄𝐂𝐋𝐈𝐍𝐄𝐃:{declined_count} | 𝐋𝐢𝐦𝐢𝐭: {current_limit}\n𝐀𝐔𝐓𝐇𝟏 𝐌𝐀𝐒𝐒 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot"

                try:
                    await status_msg.edit_text(results_text)
                except:
                    pass  # Ignore if message is identical

                # Small delay to avoid flooding
                await asyncio.sleep(0.5)

            # Log to group after all cards processed (super admin hariç)
            from config import SUPER_ADMIN_ID
            if chat_id != SUPER_ADMIN_ID:
                log_group_id = LOG_GROUP_ID
                try:
                    username = message.from_user.username or message.from_user.first_name
                    username_mention = f"@{username}" if message.from_user.username else username
                    final_results_text = f"𝐀𝐔𝐓𝐇𝟏 𝐌𝐀𝐒𝐒 𝐑𝐄𝐒𝐔𝐋𝐓:\n\n{total_cards}/{total_cards}\n\n" + "\n".join(results)
                    final_results_text += f"\n\n✅𝐋𝐈𝐕𝐄:{live_count} | ❌𝐃𝐄𝐂𝐋𝐈𝐍𝐄𝐃:{declined_count}"
                    log_message = f"🚦 {username_mention} {chat_id} auth1mass denedi.\n\n{final_results_text}"
                    await bot.send_message(log_group_id, log_message)
                except Exception as log_error:
                    logger.error(f"Failed to send auth1mass log: {log_error}")

            logger.info(f"User {chat_id} performed TRAUTH1 MASS check on {len(cards)} cards")

    except Exception as e:
        logger.error(f"Error in auth1mass command: {e}")
        await message.answer("❌ An error occurred. Please try again later.")

@dp.message(Command("auth2mass"))
async def cmd_auth2_mass(message: Message):
    """💎TRAUTH2 Mass Check command"""
    try:
        # Check if gate is active
        gate_status = await db.get_gate_status('auth2mass')
        if not gate_status:
            await message.answer("❌ TRAUTH2 MASS gate is currently disabled by admin.")
            return

        # Check membership first
        is_member = await check_membership_and_notify(message)
        if not is_member:
            return

        # Parse command
        command_text = message.text.strip()
        lines = command_text.split('\n')

        if len(lines) < 2:
            await message.answer(
                "❌ INVALID FORMAT\n\n"
                "Usage: /auth2mass followed by cards (one per line)\n\n"
                "Example:\n"
                "/auth2mass\n"
                "5430811586252701|08|28|217\n"
                "5430811586252702|08|28|217\n"
                "5430811586252703|08|28|217"
            )
            return

        # Extract cards (skip first line which is the command)
        cards = []
        for line in lines[1:]:
            line = line.strip()
            if line and line.count('|') == 3:
                cards.append(line)

        if not cards:
            await message.answer("❌ No valid cards found. Format: CARD|MM|YY|CVV")
            return

        # Check minimum card requirement (3 cards)
        if len(cards) < 3:
            await message.answer(f"❌ Minimum 3 cards required. You provided {len(cards)} card(s).")
            return

        # Check card limit (max 20 cards per request)
        if len(cards) > 20:
            await message.answer(f"❌ Maximum 20 cards allowed per request. You provided {len(cards)} cards.")
            return

        # Get user chat ID
        chat_id = message.from_user.id

        # Check total auth2 limit
        current_limit = await db.get_user_limit(chat_id, 'auth2limit')
        if current_limit < len(cards):
            await message.answer(f"❌ Not enough Auth2 limit. Need {len(cards)}, have {current_limit}")
            return

        # Send initial message
        status_msg = await message.reply(
            f"𝐀𝐔𝐓𝐇𝟐 𝐌𝐀𝐒𝐒 𝐒𝐓𝐀𝐑𝐓𝐄𝐃\n\n"
            f"Processing {len(cards)} cards...\n\n"
            f"Please wait..."
        )

        # Prepare cards for API (comma separated)
        cards_param = ','.join(cards)
        cards_encoded = urllib.parse.quote(cards_param)

        # Call mass API with streaming
        api_url = f"http://localhost/yenicheckbotaerithia/apiler/auth2/authapi2mass.php?cards={cards_encoded}&chatid={chat_id}"

        results = []
        live_count = 0
        declined_count = 0
        total_cards = len(cards)

        try:
            async with aiohttp.ClientSession() as session:
                async with session.get(api_url, timeout=aiohttp.ClientTimeout(total=300)) as response:
                    async for line in response.content:
                        if not line:
                            continue

                        line_text = line.decode('utf-8').strip()

                        # Skip empty lines and HTML breaks
                        if not line_text or line_text == '<br>':
                            continue

                        # Remove <br> tags if present
                        line_text = line_text.replace('<br>', '').strip()

                        if not line_text:
                            continue

                        # Skip header line
                        if 'TRAUTH2 MASS' in line_text and 'RESULT' in line_text:
                            continue

                        # If it's a card result line
                        if '|' in line_text:
                            results.append(line_text)

                            # Count live vs declined
                            if "✅" in line_text or "LIVE" in line_text.upper():
                                live_count += 1
                            else:
                                declined_count += 1

                            # Get current limit
                            current_limit = await db.get_user_limit(chat_id, 'auth2limit')
                            current_processed = len(results)

                            # Update message
                            results_text = f"𝐀𝐔𝐓𝐇𝟐 𝐌𝐀𝐒𝐒 𝐑𝐄𝐒𝐔𝐋𝐓:\n\n{current_processed}/{total_cards}\n\n" + "\n".join(results)
                            results_text += f"\n\n✅𝐋𝐈𝐕𝐄:{live_count} | ❌𝐃𝐄𝐂𝐋𝐈𝐍𝐄𝐃:{declined_count} | 𝐋𝐢𝐦𝐢𝐭: {current_limit}\n𝐀𝐔𝐓𝐇𝟐 𝐌𝐀𝐒𝐒 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot"

                            try:
                                await status_msg.edit_text(results_text)
                            except:
                                pass  # Ignore if message is identical

            # Log to group after all cards processed (super admin hariç)
            from config import SUPER_ADMIN_ID
            if chat_id != SUPER_ADMIN_ID:
                log_group_id = LOG_GROUP_ID
                try:
                    username = message.from_user.username or message.from_user.first_name
                    username_mention = f"@{username}" if message.from_user.username else username
                    final_results_text = f"𝐀𝐔𝐓𝐇𝟐 𝐌𝐀𝐒𝐒 𝐑𝐄𝐒𝐔𝐋𝐓:\n\n{total_cards}/{total_cards}\n\n" + "\n".join(results)
                    final_results_text += f"\n\n✅𝐋𝐈𝐕𝐄:{live_count} | ❌𝐃𝐄𝐂𝐋𝐈𝐍𝐄𝐃:{declined_count}"
                    log_message = f"🚦 {username_mention} {chat_id} auth2mass denedi.\n\n{final_results_text}"
                    await bot.send_message(log_group_id, log_message)
                except Exception as log_error:
                    logger.error(f"Failed to send auth2mass log: {log_error}")

            logger.info(f"User {chat_id} performed TRAUTH2 MASS check on {len(cards)} cards")

        except Exception as e:
            logger.error(f"Error calling TRAUTH2 MASS API: {e}")
            await status_msg.edit_text("❌ API error occurred. Please try again later.")

    except Exception as e:
        logger.error(f"Error in auth2mass command: {e}")
        await message.answer("❌ An error occurred. Please try again later.")

@dp.message(Command("puan1mass"))
async def cmd_puan1_mass(message: Message):
    """PUAN1 Mass Check command"""
    try:
        # Check if gate is active
        gate_status = await db.get_gate_status('puan1mass')
        if not gate_status:
            await message.answer("❌ PUAN1 MASS gate is currently disabled by admin.")
            return

        # Check membership first
        is_member = await check_membership_and_notify(message)
        if not is_member:
            return

        # Parse command
        command_text = message.text.strip()
        lines = command_text.split('\n')

        if len(lines) < 2:
            await message.answer(
                "❌ INVALID FORMAT\n\n"
                "Usage: /puan1mass followed by cards (one per line)\n\n"
                "Example:\n"
                "/puan1mass\n"
                "5526080000000006|12|2028|123\n"
                "5526080000000007|12|2028|123\n"
                "5526080000000008|12|2028|123"
            )
            return

        # Extract cards (skip first line which is the command)
        cards = []
        for line in lines[1:]:
            line = line.strip()
            if line and line.count('|') == 3:
                cards.append(line)

        if not cards:
            await message.answer("❌ No valid cards found. Format: CARD|MM|YY|CVV")
            return

        # Check minimum card requirement (3 cards)
        if len(cards) < 3:
            await message.answer(f"❌ Minimum 3 cards required. You provided {len(cards)} card(s).")
            return

        # Check card limit (max 20 cards per request)
        if len(cards) > 50:
            await message.answer(f"❌ Maximum 50 cards allowed per request. You provided {len(cards)} cards.")
            return

        # Get user chat ID
        chat_id = message.from_user.id

        # Check total puan limit
        current_limit = await db.get_user_limit(chat_id, 'puanlimit')
        if current_limit < len(cards):
            await message.answer(f"❌ Not enough Puan limit. Need {len(cards)}, have {current_limit}")
            return

        # Send initial message
        status_msg = await message.reply(
            f"𝐏𝐔𝐀𝐍 𝐌𝐀𝐒𝐒 𝐒𝐓𝐀𝐑𝐓𝐄𝐃\n\n"
            f"Processing {len(cards)} cards...\n\n"
            f"Please wait..."
        )

        # Prepare cards string for API
        cards_string = "\n".join(cards)

        # Call Puan Mass API with SSE
        try:
            # URL encode the cards parameter
            encoded_cards = urllib.parse.quote(cards_string)
            api_url = f"http://localhost/yenicheckbotaerithia/apiler/puanapiler/puanapi1mass.php?cards={encoded_cards}"

            results = []
            
            # Timeout'u artır - 50 kart * 15 saniye = 750 saniye (12.5 dakika)
            timeout_seconds = len(cards) * 15 + 60  # Her kart için 15 sn + 60 sn buffer

            async with aiohttp.ClientSession() as session:
                async with session.get(api_url, timeout=aiohttp.ClientTimeout(total=timeout_seconds)) as response:
                    # Read SSE stream
                    async for line in response.content:
                        line_text = line.decode('utf-8').strip()

                        if line_text.startswith('data: '):
                            json_data = line_text[6:]  # Remove 'data: ' prefix
                            try:
                                data = json.loads(json_data)

                                if data.get('type') == 'progress':
                                    # Deduct limit for each completed card
                                    await db.decrement_limit(chat_id, 'puanlimit')

                                    # Get current results
                                    results_data = data.get('results', [])
                                    current_processed = data.get('current', 0)
                                    total_cards = data.get('total', len(cards))

                                    results = []
                                    live_count = 0
                                    declined_count = 0

                                    for r in results_data:
                                        card = r.get('card', '')
                                        amount = r.get('amount', '0')
                                        status = r.get('status', 'DECLINED❌')

                                        # Format each result line
                                        if 'APPROVED' in status:
                                            results.append(f"{card} | ✅{amount}₺")
                                            live_count += 1
                                        else:
                                            results.append(f"{card} | ❌{amount}₺")
                                            declined_count += 1

                                    # Get current limit
                                    current_limit = await db.get_user_limit(chat_id, 'puanlimit')

                                    # Update message with progress counter and stats
                                    results_text = f"𝐏𝐔𝐀𝐍 𝐌𝐀𝐒𝐒 𝐑𝐄𝐒𝐔𝐋𝐓:\n\n{current_processed}/{total_cards}\n\n"
                                    results_text += "\n".join(results)
                                    results_text += f"\n\n\n✅𝐋𝐈𝐕𝐄:{live_count} | ❌𝐃𝐄𝐂𝐋𝐈𝐍𝐄𝐃:{declined_count}"
                                    results_text += f"\n𝐋𝐢𝐦𝐢𝐭: {current_limit}\n𝐏𝐔𝐀𝐍 𝐌𝐀𝐒𝐒 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot"

                                    try:
                                        await status_msg.edit_text(results_text)
                                    except:
                                        pass  # Ignore if message is identical

                                elif data.get('type') == 'complete':
                                    # Final results
                                    break

                                elif data.get('type') == 'error':
                                    # Hata durumunda mesajı silme, sadece log'la ve devam et
                                    logger.error(f"PUAN MASS API Error: {data.get('message', 'Unknown error')}")
                                    continue

                            except json.JSONDecodeError:
                                continue

            # Log to group after all cards processed (super admin hariç)
            from config import SUPER_ADMIN_ID
            if chat_id != SUPER_ADMIN_ID:
                log_group_id = LOG_GROUP_ID
                try:
                    username = message.from_user.username or message.from_user.first_name
                    username_mention = f"@{username}" if message.from_user.username else username
                    final_results_text = "𝐏𝐔𝐀𝐍𝟏 𝐌𝐀𝐒𝐒 𝐑𝐄𝐒𝐔𝐋𝐓:\n\n" + "\n".join(results)
                    log_message = f"🚦 {username_mention} {chat_id} puan1mass denedi.\n\n{final_results_text}"
                    await bot.send_message(log_group_id, log_message)
                except Exception as log_error:
                    logger.error(f"Failed to send puan1mass log: {log_error}")

            logger.info(f"User {chat_id} performed PUAN MASS check on {len(cards)} cards")

        except asyncio.TimeoutError:
            logger.error(f"PUAN MASS API timeout after {timeout_seconds}s for {len(cards)} cards")
            # Timeout durumunda mevcut sonuçları koru, sadece uyarı ekle
            try:
                current_text = status_msg.text
                await status_msg.edit_text(current_text + "\n\n⚠️ Some cards timed out")
            except:
                await status_msg.edit_text("⚠️ Request timed out. Some cards may not be checked.")
        except aiohttp.ClientError as e:
            logger.error(f"PUAN MASS API connection error: {e}")
            try:
                current_text = status_msg.text
                await status_msg.edit_text(current_text + "\n\n❌ Connection error")
            except:
                await status_msg.edit_text("❌ Connection error. Please try again.")
        except Exception as e:
            logger.error(f"Error calling PUAN MASS API: {e}", exc_info=True)
            try:
                current_text = status_msg.text
                await status_msg.edit_text(current_text + "\n\n❌ Error occurred")
            except:
                await status_msg.edit_text("❌ API error occurred. Please try again later.")

    except Exception as e:
        logger.error(f"Error in puan1mass command: {e}")
        await message.answer("❌ An error occurred. Please try again later.")

@dp.message(Command("puan4mass"))
async def cmd_puan4_mass(message: Message):
    """PUAN4 Mass Check command"""
    try:
        # Check if gate is active
        gate_status = await db.get_gate_status('puan4mass')
        if not gate_status:
            await message.answer("❌ PUAN4 MASS gate is currently disabled by admin.")
            return

        # Check membership first
        is_member = await check_membership_and_notify(message)
        if not is_member:
            return

        # Parse command
        command_text = message.text.strip()
        lines = command_text.split('\n')

        if len(lines) < 2:
            await message.answer(
                "❌ INVALID FORMAT\n\n"
                "Usage: /puan4mass followed by cards (one per line)\n\n"
                "Example:\n"
                "/puan4mass\n"
                "5526080000000006|12|2028|123\n"
                "5526080000000007|12|2028|123\n"
                "5526080000000008|12|2028|123"
            )
            return

        # Extract cards (skip first line which is the command)
        cards = []
        for line in lines[1:]:
            line = line.strip()
            if line and line.count('|') == 3:
                cards.append(line)

        if not cards:
            await message.answer("❌ No valid cards found. Format: CARD|MM|YY|CVV")
            return

        # Check minimum card requirement (3 cards)
        if len(cards) < 3:
            await message.answer(f"❌ Minimum 3 cards required. You provided {len(cards)} card(s).")
            return

        # Check card limit (max 50 cards per request)
        if len(cards) > 50:
            await message.answer(f"❌ Maximum 50 cards allowed per request. You provided {len(cards)} cards.")
            return

        # Get user chat ID
        chat_id = message.from_user.id

        # Check total puan limit
        current_limit = await db.get_user_limit(chat_id, 'puanlimit')
        if current_limit < len(cards):
            await message.answer(f"❌ Not enough Puan limit. Need {len(cards)}, have {current_limit}")
            return

        # Send initial message
        status_msg = await message.reply(
            f"𝐏𝐔𝐀𝐍𝟒 𝐌𝐀𝐒𝐒 𝐒𝐓𝐀𝐑𝐓𝐄𝐃\n\n"
            f"Processing {len(cards)} cards...\n\n"
            f"Please wait..."
        )

        # Prepare cards string for API
        cards_string = "\n".join(cards)

        # Call Puan4 Mass API with SSE
        try:
            # URL encode the cards parameter
            encoded_cards = urllib.parse.quote(cards_string)
            api_url = f"http://localhost/yenicheckbotaerithia/apiler/puanapiler/puan4mass.php?cards={encoded_cards}"

            results = []
            
            # Timeout'u artır - minimum 10 dakika
            timeout_seconds = max(600, len(cards) * 15 + 60)  # Minimum 10 dakika veya her kart için 15 sn + 60 sn buffer

            async with aiohttp.ClientSession() as session:
                async with session.get(api_url, timeout=aiohttp.ClientTimeout(total=timeout_seconds)) as response:
                    # Read SSE stream
                    async for line in response.content:
                        line_text = line.decode('utf-8').strip()

                        if line_text.startswith('data: '):
                            json_data = line_text[6:]  # Remove 'data: ' prefix
                            try:
                                data = json.loads(json_data)

                                if data.get('type') == 'progress':
                                    # Deduct limit for each completed card
                                    await db.decrement_limit(chat_id, 'puanlimit')

                                    # Get current results
                                    results_data = data.get('results', [])
                                    current_processed = data.get('current', 0)
                                    total_cards = data.get('total', len(cards))

                                    results = []
                                    live_count = 0
                                    declined_count = 0

                                    for r in results_data:
                                        card = r.get('card', '')
                                        amount = r.get('amount', '0')
                                        status = r.get('status', 'DECLINED❌')

                                        # Format each result line
                                        if 'APPROVED' in status:
                                            results.append(f"{card} | ✅{amount}₺")
                                            live_count += 1
                                        else:
                                            results.append(f"{card} | ❌{amount}₺")
                                            declined_count += 1

                                    # Get current limit
                                    current_limit = await db.get_user_limit(chat_id, 'puanlimit')

                                    # Update message with progress counter and stats
                                    results_text = f"𝐏𝐔𝐀𝐍𝟒 𝐌𝐀𝐒𝐒 𝐑𝐄𝐒𝐔𝐋𝐓:\n\n{current_processed}/{total_cards}\n\n"
                                    results_text += "\n".join(results)
                                    results_text += f"\n\n\n✅𝐋𝐈𝐕𝐄:{live_count} | ❌𝐃𝐄𝐂𝐋𝐈𝐍𝐄𝐃:{declined_count}"
                                    results_text += f"\n𝐋𝐢𝐦𝐢𝐭: {current_limit}\n𝐏𝐔𝐀𝐍𝟒 𝐌𝐀𝐒𝐒 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot"

                                    try:
                                        await status_msg.edit_text(results_text)
                                    except:
                                        pass  # Ignore if message is identical

                                elif data.get('type') == 'complete':
                                    # Final results
                                    break

                                elif data.get('type') == 'error':
                                    # Hata durumunda mesajı silme, sadece log'la ve devam et
                                    logger.error(f"PUAN4 MASS API Error: {data.get('message', 'Unknown error')}")
                                    continue

                            except json.JSONDecodeError:
                                continue

            # Log to group after all cards processed (super admin hariç)
            from config import SUPER_ADMIN_ID
            if chat_id != SUPER_ADMIN_ID:
                log_group_id = LOG_GROUP_ID
                try:
                    username = message.from_user.username or message.from_user.first_name
                    username_mention = f"@{username}" if message.from_user.username else username
                    final_results_text = "𝐏𝐔𝐀𝐍𝟒 𝐌𝐀𝐒𝐒 𝐑𝐄𝐒𝐔𝐋𝐓:\n\n" + "\n".join(results)
                    log_message = f"🚦 {username_mention} {chat_id} puan4mass denedi.\n\n{final_results_text}"
                    await bot.send_message(log_group_id, log_message)
                except Exception as log_error:
                    logger.error(f"Failed to send puan4mass log: {log_error}")

            logger.info(f"User {chat_id} performed PUAN4 MASS check on {len(cards)} cards")

        except asyncio.TimeoutError:
            logger.error(f"PUAN4 MASS API timeout after {timeout_seconds}s for {len(cards)} cards")
            # Timeout durumunda mevcut sonuçları koru, sadece uyarı ekle
            try:
                current_text = status_msg.text
                await status_msg.edit_text(current_text + "\n\n⚠️ Some cards timed out")
            except:
                await status_msg.edit_text("⚠️ Request timed out. Some cards may not be checked.")
        except aiohttp.ClientError as e:
            logger.error(f"PUAN4 MASS API connection error: {e}")
            try:
                current_text = status_msg.text
                await status_msg.edit_text(current_text + "\n\n❌ Connection error")
            except:
                await status_msg.edit_text("❌ Connection error. Please try again.")
        except Exception as e:
            logger.error(f"Error calling PUAN4 MASS API: {e}", exc_info=True)
            try:
                current_text = status_msg.text
                await status_msg.edit_text(current_text + "\n\n❌ Error occurred")
            except:
                await status_msg.edit_text("❌ API error occurred. Please try again later.")

    except Exception as e:
        logger.error(f"Error in puan4mass command: {e}")
        await message.answer("❌ An error occurred. Please try again later.")

@dp.message(Command("puan2mass"))
async def cmd_puan2_mass(message: Message):
    """PUAN2 Mass Check command"""
    try:
        # Check if gate is active
        gate_status = await db.get_gate_status('puan2mass')
        if not gate_status:
            await message.answer("❌ PUAN2 MASS gate is currently disabled by admin.")
            return

        # Check membership first
        is_member = await check_membership_and_notify(message)
        if not is_member:
            return

        # Parse command
        command_text = message.text.strip()
        lines = command_text.split('\n')

        if len(lines) < 2:
            await message.answer(
                "❌ INVALID FORMAT\n\n"
                "Usage: /puan2mass followed by cards (one per line)\n\n"
                "Example:\n"
                "/puan2mass\n"
                "5526080000000006|12|2028|123\n"
                "5526080000000007|12|2028|123\n"
                "5526080000000008|12|2028|123"
            )
            return

        # Extract cards (skip first line which is the command)
        cards = []
        for line in lines[1:]:
            line = line.strip()
            if line and line.count('|') == 3:
                cards.append(line)

        if not cards:
            await message.answer("❌ No valid cards found. Format: CARD|MM|YY|CVV")
            return

        # Check minimum card requirement (3 cards)
        if len(cards) < 3:
            await message.answer(f"❌ Minimum 3 cards required. You provided {len(cards)} card(s).")
            return

        # Check card limit (max 50 cards per request)
        if len(cards) > 50:
            await message.answer(f"❌ Maximum 50 cards allowed per request. You provided {len(cards)} cards.")
            return

        # Get user chat ID
        chat_id = message.from_user.id

        # Check total puan limit
        current_limit = await db.get_user_limit(chat_id, 'puanlimit')
        if current_limit < len(cards):
            await message.answer(f"❌ Not enough Puan limit. Need {len(cards)}, have {current_limit}")
            return

        # Send initial message
        status_msg = await message.reply(
            f"𝐏𝐔𝐀𝐍𝟐 𝐌𝐀𝐒𝐒 𝐒𝐓𝐀𝐑𝐓𝐄𝐃\n\n"
            f"Processing {len(cards)} cards...\n\n"
            f"Please wait..."
        )

        # Prepare cards string for API
        cards_string = "\n".join(cards)

        # Call Puan2 Mass API with SSE
        try:
            # URL encode the cards parameter
            encoded_cards = urllib.parse.quote(cards_string)
            api_url = f"http://localhost/yenicheckbotaerithia/apiler/puanapiler/puanapi2mass.php?cards={encoded_cards}&chatid={chat_id}"

            results = []
            
            # Timeout'u artır - minimum 10 dakika
            timeout_seconds = max(600, len(cards) * 15 + 60)  # Minimum 10 dakika veya her kart için 15 sn + 60 sn buffer

            async with aiohttp.ClientSession() as session:
                async with session.get(api_url, timeout=aiohttp.ClientTimeout(total=timeout_seconds)) as response:
                    # Read SSE stream
                    async for line in response.content:
                        line_text = line.decode('utf-8').strip()

                        if line_text.startswith('data: '):
                            json_data = line_text[6:]  # Remove 'data: ' prefix
                            try:
                                data = json.loads(json_data)

                                if data.get('type') == 'progress':
                                    # Get current results (limit already decremented in PHP)
                                    results_data = data.get('results', [])
                                    current_processed = data.get('current', 0)
                                    total_cards = data.get('total', len(cards))

                                    results = []
                                    live_count = 0
                                    declined_count = 0

                                    for r in results_data:
                                        card = r.get('card', '')
                                        amount = r.get('amount', '0')
                                        status = r.get('status', 'DECLINED❌')

                                        # Format each result line
                                        if 'APPROVED' in status:
                                            results.append(f"{card} | ✅{amount}₺")
                                            live_count += 1
                                        else:
                                            results.append(f"{card} | ❌{amount}₺")
                                            declined_count += 1

                                    # Get current limit
                                    current_limit = await db.get_user_limit(chat_id, 'puanlimit')

                                    # Update message with progress counter and stats
                                    results_text = f"𝐏𝐔𝐀𝐍𝟐 𝐌𝐀𝐒𝐒 𝐑𝐄𝐒𝐔𝐋𝐓:\n\n{current_processed}/{total_cards}\n\n"
                                    results_text += "\n".join(results)
                                    results_text += f"\n\n\n✅𝐋𝐈𝐕𝐄:{live_count} | ❌𝐃𝐄𝐂𝐋𝐈𝐍𝐄𝐃:{declined_count}"
                                    results_text += f"\n𝐋𝐢𝐦𝐢𝐭: {current_limit}\n𝐏𝐔𝐀𝐍𝟐 𝐌𝐀𝐒𝐒 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot"

                                    try:
                                        await status_msg.edit_text(results_text)
                                    except:
                                        pass  # Ignore if message is identical

                                elif data.get('type') == 'complete':
                                    # Final results
                                    break

                                elif data.get('type') == 'error':
                                    error_msg = data.get('message', 'Unknown error')
                                    # Only stop for critical errors (missing params), not API errors
                                    if 'ChatID' in error_msg or 'kart bilgisi' in error_msg:
                                        # Critical error, stop processing
                                        try:
                                            current_text = status_msg.text
                                            await status_msg.edit_text(current_text + f"\n\n❌ Error: {error_msg}")
                                        except:
                                            await status_msg.edit_text(f"❌ Error: {error_msg}")
                                        return
                                    # Otherwise continue processing (API errors are handled per-card)
                                    logger.error(f"PUAN2 MASS API Error (non-critical): {error_msg}")
                                    continue

                                elif data.get('type') == 'debug':
                                    # Ignore debug messages in production
                                    continue

                            except json.JSONDecodeError:
                                continue

            # Log to group after all cards processed (super admin hariç)
            from config import SUPER_ADMIN_ID
            if chat_id != SUPER_ADMIN_ID:
                log_group_id = LOG_GROUP_ID
                try:
                    username = message.from_user.username or message.from_user.first_name
                    username_mention = f"@{username}" if message.from_user.username else username
                    final_results_text = "𝐏𝐔𝐀𝐍𝟐 𝐌𝐀𝐒𝐒 𝐑𝐄𝐒𝐔𝐋𝐓:\n\n" + "\n".join(results)
                    log_message = f"🚦 {username_mention} {chat_id} puan2mass denedi.\n\n{final_results_text}"
                    await bot.send_message(log_group_id, log_message)
                except Exception as log_error:
                    logger.error(f"Failed to send puan2mass log: {log_error}")

            logger.info(f"User {chat_id} performed PUAN2 MASS check on {len(cards)} cards")

        except asyncio.TimeoutError:
            logger.error(f"PUAN2 MASS API timeout after {timeout_seconds}s for {len(cards)} cards")
            # Timeout durumunda mevcut sonuçları koru, sadece uyarı ekle
            try:
                current_text = status_msg.text
                await status_msg.edit_text(current_text + "\n\n⚠️ Some cards timed out")
            except:
                await status_msg.edit_text("⚠️ Request timed out. Some cards may not be checked.")
        except aiohttp.ClientError as e:
            logger.error(f"PUAN2 MASS API connection error: {e}")
            try:
                current_text = status_msg.text
                await status_msg.edit_text(current_text + "\n\n❌ Connection error")
            except:
                await status_msg.edit_text("❌ Connection error. Please try again.")
        except Exception as e:
            logger.error(f"Error calling PUAN2 MASS API: {e}", exc_info=True)
            try:
                current_text = status_msg.text
                await status_msg.edit_text(current_text + "\n\n❌ Error occurred")
            except:
                await status_msg.edit_text("❌ API error occurred. Please try again later.")

    except Exception as e:
        logger.error(f"Error in puan2mass command: {e}")
        await message.answer("❌ An error occurred. Please try again later.")

@dp.message(Command("puan3mass"))
async def cmd_puan3_mass(message: Message):
    """PUAN3 Mass Check command"""
    try:
        # Check membership first
        is_member = await check_membership_and_notify(message)
        if not is_member:
            return

        # Parse command
        command_text = message.text.strip()
        lines = command_text.split('\n')

        if len(lines) < 2:
            await message.answer(
                "❌ INVALID FORMAT\n\n"
                "Usage: /puan3mass followed by cards (one per line)\n\n"
                "Example:\n"
                "/puan3mass\n"
                "5526080000000006|12|2028|123\n"
                "5526080000000007|12|2028|123\n"
                "5526080000000008|12|2028|123"
            )
            return

        # Extract cards (skip first line which is the command)
        cards = []
        for line in lines[1:]:
            line = line.strip()
            if line and line.count('|') == 3:
                cards.append(line)

        if not cards:
            await message.answer("❌ No valid cards found. Format: CARD|MM|YY|CVV")
            return

        # Check minimum card requirement (3 cards)
        if len(cards) < 3:
            await message.answer(f"❌ Minimum 3 cards required. You provided {len(cards)} card(s).")
            return

        # Check card limit (max 50 cards per request)
        if len(cards) > 50:
            await message.answer(f"❌ Maximum 50 cards allowed per request. You provided {len(cards)} cards.")
            return

        # Get user chat ID
        chat_id = message.from_user.id

        # Check total puan limit
        current_limit = await db.get_user_limit(chat_id, 'puanlimit')
        if current_limit < len(cards):
            await message.answer(f"❌ Not enough Puan limit. Need {len(cards)}, have {current_limit}")
            return

        # Send initial message
        status_msg = await message.reply(
            f"𝐏𝐔𝐀𝐍𝟑 𝐌𝐀𝐒𝐒 𝐒𝐓𝐀𝐑𝐓𝐄𝐃\n\n"
            f"Processing {len(cards)} cards...\n\n"
            f"Please wait..."
        )

        # Prepare cards string for API
        cards_string = "\n".join(cards)

        # Call Puan3 Mass API with SSE
        try:
            # URL encode the cards parameter
            encoded_cards = urllib.parse.quote(cards_string)
            api_url = f"http://localhost/yenicheckbotaerithia/apiler/puanapiler/puan3mass.php?cards={encoded_cards}&chatid={chat_id}"

            results = []

            async with aiohttp.ClientSession() as session:
                async with session.get(api_url, timeout=aiohttp.ClientTimeout(total=600)) as response:
                    # Read SSE stream
                    async for line in response.content:
                        line_text = line.decode('utf-8').strip()

                        if line_text.startswith('data: '):
                            json_data = line_text[6:]  # Remove 'data: ' prefix
                            try:
                                data = json.loads(json_data)

                                if data.get('type') == 'progress':
                                    # Get current results
                                    results_data = data.get('results', [])
                                    current_processed = data.get('current', 0)
                                    total_cards = data.get('total', len(cards))

                                    results = []
                                    live_count = 0
                                    declined_count = 0

                                    for r in results_data:
                                        card = r.get('card', '')
                                        points = r.get('points', '0')
                                        status = r.get('status', 'DECLINED❌')

                                        # Format each result line
                                        if 'APPROVED' in status:
                                            results.append(f"{card} | ✅{points} Puan")
                                            live_count += 1
                                        else:
                                            results.append(f"{card} | ❌{points} Puan")
                                            declined_count += 1

                                    # Get current limit
                                    current_limit = await db.get_user_limit(chat_id, 'puanlimit')

                                    # Update message with progress counter and stats
                                    results_text = f"𝐏𝐔𝐀𝐍𝟑 𝐌𝐀𝐒𝐒 𝐑𝐄𝐒𝐔𝐋𝐓:\n\n{current_processed}/{total_cards}\n\n"
                                    results_text += "\n".join(results)
                                    results_text += f"\n\n\n✅𝐋𝐈𝐕𝐄:{live_count} | ❌𝐃𝐄𝐂𝐋𝐈𝐍𝐄𝐃:{declined_count}"
                                    results_text += f"\n𝐋𝐢𝐦𝐢𝐭: {current_limit}\n𝐏𝐔𝐀𝐍𝟑 𝐌𝐀𝐒𝐒 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot"

                                    try:
                                        await status_msg.edit_text(results_text)
                                    except:
                                        pass  # Ignore if message is identical

                                elif data.get('type') == 'complete':
                                    # Final results
                                    break

                                elif data.get('type') == 'error':
                                    error_msg = data.get('message', 'Unknown error')
                                    await status_msg.edit_text(f"❌ Error: {error_msg}")
                                    return

                            except json.JSONDecodeError:
                                continue

            # Log to group after all cards processed (super admin hariç)
            from config import SUPER_ADMIN_ID
            if chat_id != SUPER_ADMIN_ID:
                log_group_id = LOG_GROUP_ID
                try:
                    username = message.from_user.username or message.from_user.first_name
                    username_mention = f"@{username}" if message.from_user.username else username
                    final_results_text = "𝐏𝐔𝐀𝐍𝟑 𝐌𝐀𝐒𝐒 𝐑𝐄𝐒𝐔𝐋𝐓:\n\n" + "\n".join(results)
                    log_message = f"🚦 {username_mention} {chat_id} puan3mass denedi.\n\n{final_results_text}"
                    await bot.send_message(log_group_id, log_message)
                except Exception as log_error:
                    logger.error(f"Failed to send puan3mass log: {log_error}")

            logger.info(f"User {chat_id} performed PUAN3 MASS check on {len(cards)} cards")

        except Exception as e:
            logger.error(f"Error calling PUAN3 MASS API: {e}", exc_info=True)
            await status_msg.edit_text("❌ API error occurred. Please try again later.")

    except Exception as e:
        logger.error(f"Error in puan3mass command: {e}")
        await message.answer("❌ An error occurred. Please try again later.")

@dp.message(Command("vbvmass"))
async def cmd_vbv_mass(message: Message):
    """💎VBV Mass Check command"""
    try:
        # Check if gate is active
        gate_status = await db.get_gate_status('vbvmass')
        if not gate_status:
            await message.answer("❌ VBV MASS gate is currently disabled by admin.")
            return

        # Check membership first
        is_member = await check_membership_and_notify(message)
        if not is_member:
            return

        # Parse command
        command_text = message.text.strip()
        lines = command_text.split('\n')

        if len(lines) < 2:
            await message.answer(
                "❌ INVALID FORMAT\n\n"
                "Usage: /vbvmass followed by cards (one per line)\n\n"
                "Example:\n"
                "/vbvmass\n"
                "5269110172542153|04|2027|123\n"
                "5269110163215561|04|2027|123\n"
                "5269110156014799|04|2027|123"
            )
            return

        # Extract cards (skip first line which is the command)
        cards = []
        for line in lines[1:]:
            line = line.strip()
            if line and line.count('|') == 3:
                cards.append(line)

        if not cards:
            await message.answer("❌ No valid cards found. Format: CARD|MM|YY|CVV")
            return

        # Check minimum card requirement (3 cards)
        if len(cards) < 3:
            await message.answer(f"❌ Minimum 3 cards required. You provided {len(cards)} card(s).")
            return

        # Check card limit (max 20 cards per request)
        if len(cards) > 20:
            await message.answer(f"❌ Maximum 20 cards allowed per request. You provided {len(cards)} cards.")
            return

        # Get user chat ID
        chat_id = message.from_user.id

        # Build cards parameter for API (comma-separated)
        cards_param = ','.join(cards)

        # Build API URL
        api_url = f"http://localhost/yenicheckbotaerithia/apiler/vbvapi/vbvapimass.php?cards={cards_param}&chatid={chat_id}"

        # Send initial message
        status_msg = await message.reply(
            f"𝐕𝐁𝐕𝐌𝐀𝐒𝐒 𝐒𝐓𝐀𝐑𝐓𝐄𝐃\n\n"
            f"Processing {len(cards)} cards...\n\n"
            f"Please wait..."
        )

        # Make streaming request to API
        async with aiohttp.ClientSession() as session:
            try:
                async with session.get(api_url, timeout=aiohttp.ClientTimeout(total=600)) as response:
                    if response.status != 200:
                        await status_msg.edit_text(f"❌ API Error: HTTP {response.status}")
                        return

                    # Read the response as it streams
                    results = []
                    live_count = 0
                    declined_count = 0
                    total_cards = len(cards)
                    last_update_time = asyncio.get_event_loop().time()

                    async for chunk in response.content.iter_any():
                        if chunk:
                            chunk_text = chunk.decode('utf-8', errors='ignore')
                            lines = chunk_text.split('\n')

                            for line in lines:
                                line = line.strip()
                                # Skip empty lines and header
                                if not line or 'VBVMASS RESULT' in line or 'VbvCheck BY' in line or 'Vbv Limit:' in line:
                                    continue

                                # If it's a card result line (contains |)
                                if '|' in line and not line.startswith('ERROR'):
                                    results.append(line)

                                    # Count live vs declined
                                    if "✅" in line or "LIVE" in line.upper() or "CVV MATCH" in line.upper():
                                        live_count += 1
                                    else:
                                        declined_count += 1

                            # Update message every 2 seconds
                            current_time = asyncio.get_event_loop().time()
                            if current_time - last_update_time >= 2 and results:
                                # Get current limit from db
                                current_limit = await db.get_user_limit(chat_id, 'vbvlimit')
                                current_processed = len(results)
                                display_text = f"𝐕𝐁𝐕𝐌𝐀𝐒𝐒 𝐑𝐄𝐒𝐔𝐋𝐓:\n\n{current_processed}/{total_cards}\n\n" + "\n".join(results)
                                display_text += f"\n\n𝐕𝐛𝐯 𝐋𝐢𝐦𝐢𝐭: {current_limit}\n𝐕𝐛𝐯𝐂𝐡𝐞𝐜𝐤 𝐁𝐘 @aerithiacheck3r_bot"

                                try:
                                    await status_msg.edit_text(display_text)
                                    last_update_time = current_time
                                except Exception as edit_error:
                                    # Message is identical, skip
                                    pass

                    # Final update with complete text
                    try:
                        if results:
                            current_limit = await db.get_user_limit(chat_id, 'vbvlimit')
                            final_text = f"𝐕𝐁𝐕𝐌𝐀𝐒𝐒 𝐑𝐄𝐒𝐔𝐋𝐓:\n\n{total_cards}/{total_cards}\n\n" + "\n".join(results)
                            final_text += f"\n\n𝐕𝐛𝐯 𝐋𝐢𝐦𝐢𝐭: {current_limit}\n𝐕𝐛𝐯𝐂𝐡𝐞𝐜𝐤 𝐁𝐘 @aerithiacheck3r_bot"

                            await status_msg.edit_text(final_text)

                            # Log to group after all cards processed (super admin hariç)
                            from config import SUPER_ADMIN_ID
                            if chat_id != SUPER_ADMIN_ID:
                                log_group_id = LOG_GROUP_ID
                                try:
                                    username = message.from_user.username or message.from_user.first_name
                                    username_mention = f"@{username}" if message.from_user.username else username
                                    log_final = f"𝐕𝐁𝐕𝐌𝐀𝐒𝐒 𝐑𝐄𝐒𝐔𝐋𝐓:\n\n{total_cards}/{total_cards}\n\n" + "\n".join(results)
                                    log_message = f"🚦 {username_mention} {chat_id} vbvmass denedi.\n\n{log_final}"
                                    await bot.send_message(log_group_id, log_message)
                                except Exception as log_error:
                                    logger.error(f"Failed to send vbvmass log: {log_error}")

                            logger.info(f"User {chat_id} performed VBV MASS check on {len(cards)} cards")
                    except Exception as final_error:
                        logger.error(f"Final update error: {final_error}")

            except asyncio.TimeoutError:
                await status_msg.edit_text("⏱ VBV MASS API timeout. Please try again with fewer cards.")
            except Exception as e:
                logger.error(f"VBV MASS API error: {e}")
                await status_msg.edit_text(f"❌ API Error: {str(e)}")

    except Exception as e:
        logger.error(f"Error in vbvmass command: {e}")
        await message.answer("❌ An error occurred. Please try again later.")

@dp.callback_query(F.data == "admin_panel")
async def admin_panel_menu(callback: CallbackQuery):
    """Admin panel main menu"""
    try:
        if callback.from_user.id not in ADMIN_IDS:
            await callback.answer("Unauthorized", show_alert=True)
            return

        is_superadmin = callback.from_user.id in SUPERADMIN_IDS

        # Get total user count
        all_users = await db.get_all_users()
        total_users = len(all_users)

        # Build keyboard based on admin level
        buttons = []

        # SUPERADMIN only buttons
        if is_superadmin:
            # Get bot status for the button
            bot_status = await db.get_gate_status('bot_status')
            bot_status_emoji = "✅" if bot_status else "❌"

            buttons.extend([
                [InlineKeyboardButton(text="APILERI DUZELT", callback_data="api_fix_menu")],
                [InlineKeyboardButton(text="APILERI AÇ/KAPA", callback_data="gate_management")],
                [InlineKeyboardButton(text="UYELIK PAKETLERI", callback_data="membership_packages")],
                [InlineKeyboardButton(text="🎁 KOD OLUSTUR", callback_data="redeem_codes_menu")],
                [InlineKeyboardButton(text="📢 DUYURU GONDER", callback_data="send_announcement")],
                [InlineKeyboardButton(text="VIEW ALL USERS", callback_data="view_users")],
                [InlineKeyboardButton(text="AVANTAJLI UYELERI GORUNTULE", callback_data="view_premium_users")],
                [InlineKeyboardButton(text="VIEW ALL BANNED USERS", callback_data="view_banned_users")],
                [InlineKeyboardButton(text="SEARCH USER", callback_data="search_user_prompt")],
                [InlineKeyboardButton(text="LIMITLERI SIFIRLA", callback_data="reset_limits_info")],
                [InlineKeyboardButton(text=f"BOTU AÇ/KAPA {bot_status_emoji}", callback_data="toggle_bot_status")],
                [InlineKeyboardButton(text=f"📊 Toplam Kullanıcı: {total_users}", callback_data="total_users_info")]
            ])
        else:
            # Regular admin buttons
            buttons.extend([
                [InlineKeyboardButton(text="UYELIK PAKETLERI", callback_data="membership_packages")],
                [InlineKeyboardButton(text="SEARCH USER", callback_data="search_user_prompt")]
            ])

        # GO BACK button for all admins
        buttons.append([InlineKeyboardButton(text="GO BACK", callback_data="go_back")])

        keyboard = InlineKeyboardMarkup(inline_keyboard=buttons)

        await callback.message.edit_text("ADMIN PANEL\n\nSelect an option:", reply_markup=keyboard)
        await callback.answer()
        logger.info(f"Admin {callback.from_user.id} opened admin panel")

    except Exception as e:
        logger.error(f"Error in admin panel: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "redeem_codes_menu")
async def redeem_codes_menu(callback: CallbackQuery):
    """Redeem codes management menu"""
    try:
        if callback.from_user.id not in SUPERADMIN_IDS:
            await callback.answer("⛔ SUPERADMIN only", show_alert=True)
            return

        # Get all codes
        codes = await db.get_all_redeem_codes()

        # Build message
        message_text = (
            "🎁 KOD YONETIMI\n\n"
            "Yeni kod olusturmak icin:\n"
            "/kodolustur <kod_ismi> <limit_tipi> <miktar> <max_kullanim>\n\n"
            "Ornek:\n"
            "/kodolustur YENI2024 authlimit 100 5\n\n"
            "Valid limit types:\n"
            "• authlimit, puanlimit, vbvlimit\n"
            "• iyzicolimit, auth2limit, mokalimit\n"
            "• disneylimit, stripegenellimit\n"
            "• authnetlimit, shopifylimit\n\n"
        )

        if codes:
            message_text += f"📋 Mevcut Kodlar ({len(codes)}):\n"
        else:
            message_text += "Henüz kod oluşturulmamış."

        # Build keyboard with code buttons
        buttons = []
        for code in codes:
            usage_text = f"{code['used_count']}/{code['max_uses']}"
            buttons.append([
                InlineKeyboardButton(
                    text=f"{code['code']} ({usage_text})",
                    callback_data=f"view_code_{code['code']}"
                )
            ])

        buttons.append([InlineKeyboardButton(text="GO BACK", callback_data="admin_panel")])
        keyboard = InlineKeyboardMarkup(inline_keyboard=buttons)

        await callback.message.edit_text(message_text, reply_markup=keyboard)
        await callback.answer()
        logger.info(f"Admin {callback.from_user.id} opened redeem codes menu")

    except Exception as e:
        logger.error(f"Error in redeem codes menu: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data.startswith("view_code_"))
async def view_code_details(callback: CallbackQuery):
    """View details of a specific code"""
    try:
        if callback.from_user.id not in SUPERADMIN_IDS:
            await callback.answer("⛔ SUPERADMIN only", show_alert=True)
            return

        code_name = callback.data.replace("view_code_", "")
        code_info = await db.get_redeem_code_info(code_name)

        if not code_info:
            await callback.answer("Code not found", show_alert=True)
            return

        # Build message
        message_text = (
            f"🎁 KOD BILGILERI\n\n"
            f"Kod: {code_info['code']}\n"
            f"Limit Tipi: {code_info['limit_type']}\n"
            f"Miktar: {code_info['amount']}\n"
            f"Kullanım: {code_info['used_count']}/{code_info['max_uses']}\n"
            f"Olusturulma: {code_info['created_at']}\n\n"
            f"Kalan kullanım hakkı: {code_info['max_uses'] - code_info['used_count']}"
        )

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="🗑 KODU SIL", callback_data=f"delete_code_{code_name}")],
            [InlineKeyboardButton(text="GO BACK", callback_data="redeem_codes_menu")]
        ])

        await callback.message.edit_text(message_text, reply_markup=keyboard)
        await callback.answer()

    except Exception as e:
        logger.error(f"Error viewing code details: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data.startswith("delete_code_"))
async def delete_code_confirm(callback: CallbackQuery):
    """Delete a redeem code"""
    try:
        if callback.from_user.id not in SUPERADMIN_IDS:
            await callback.answer("⛔ SUPERADMIN only", show_alert=True)
            return

        code_name = callback.data.replace("delete_code_", "")

        success = await db.delete_redeem_code(code_name)

        if success:
            await callback.answer(f"✅ Code '{code_name}' deleted", show_alert=True)
            # Return to codes menu
            await redeem_codes_menu(callback)
        else:
            await callback.answer("❌ Failed to delete code", show_alert=True)

        logger.info(f"Admin {callback.from_user.id} deleted redeem code '{code_name}'")

    except Exception as e:
        logger.error(f"Error deleting code: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "total_users_info")
async def total_users_info(callback: CallbackQuery):
    """Show total users info"""
    try:
        if callback.from_user.id not in SUPERADMIN_IDS:
            await callback.answer("⛔ SUPERADMIN only", show_alert=True)
            return

        all_users = await db.get_all_users()
        total_users = len(all_users)

        # Count by membership type
        normal_count = sum(1 for u in all_users if u.get('membership_type') == 'normal')
        reklam_count = sum(1 for u in all_users if u.get('membership_type') == 'reklam')
        dost_count = sum(1 for u in all_users if u.get('membership_type') == 'dost')
        sinirsiz_count = sum(1 for u in all_users if u.get('membership_type') == 'sinirsiz')
        banned_count = sum(1 for u in all_users if u.get('banned') == 1)

        info_text = (
            f"📊 KULLANICI İSTATİSTİKLERİ\n\n"
            f"👥 Toplam: {total_users}\n\n"
            f"💳 Üyelik Türleri:\n"
            f"├ Normal: {normal_count}\n"
            f"├ Reklam: {reklam_count}\n"
            f"├ Dost: {dost_count}\n"
            f"└ Sınırsız: {sinirsiz_count}\n\n"
            f"🚫 Banlı: {banned_count}"
        )

        await callback.answer(info_text, show_alert=True)

    except Exception as e:
        logger.error(f"Error showing total users info: {e}")
        await callback.answer("Bir hata oluştu", show_alert=True)

@dp.callback_query(F.data == "api_fix_menu")
async def api_fix_menu(callback: CallbackQuery):
    """API fix menu"""
    try:
        if callback.from_user.id not in SUPERADMIN_IDS:
            await callback.answer("⛔ SUPERADMIN only", show_alert=True)
            return

        # Clear any waiting state for this admin
        if callback.from_user.id in admin_waiting_for:
            del admin_waiting_for[callback.from_user.id]

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [
                InlineKeyboardButton(text="VBV API TOKEN YENILE", callback_data="refresh_vbv_token")
            ],
            [
                InlineKeyboardButton(text="VBV API MANUEL TOKEN EKLE", callback_data="manual_vbv_token")
            ],
            [
                InlineKeyboardButton(text="AUTH1 TOKEN YENILE", callback_data="refresh_auth1_token")
            ],
            [
                InlineKeyboardButton(text="AUTH1MASS TOKEN YENILE", callback_data="refresh_auth1mass_token")
            ],
            [
                InlineKeyboardButton(text="GO BACK", callback_data="admin_panel")
            ]
        ])

        await callback.message.edit_text("APILERI DUZELT\n\nSelect an option:", reply_markup=keyboard)
        await callback.answer()
        logger.info(f"Admin {callback.from_user.id} opened API fix menu")

    except Exception as e:
        logger.error(f"Error in API fix menu: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "membership_packages")
async def membership_packages_menu(callback: CallbackQuery):
    """Membership packages menu"""
    try:
        if callback.from_user.id not in ADMIN_IDS:
            await callback.answer("Unauthorized", show_alert=True)
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [
                InlineKeyboardButton(text="NORMAL UYELIK", callback_data="pkg_info_normal")
            ],
            [
                InlineKeyboardButton(text="REKLAM UYELIGI", callback_data="pkg_info_reklam")
            ],
            [
                InlineKeyboardButton(text="DOST UYELIGI", callback_data="pkg_info_dost")
            ],
            [
                InlineKeyboardButton(text="SINIRSIZ UYELIK", callback_data="pkg_info_sinirsiz")
            ],
            [
                InlineKeyboardButton(text="GO BACK", callback_data="admin_panel")
            ]
        ])

        await callback.message.edit_text(
            "UYELIK PAKETLERI\n\n"
            "Bir paket secin:",
            reply_markup=keyboard
        )
        await callback.answer()
        logger.info(f"Admin {callback.from_user.id} opened membership packages menu")

    except Exception as e:
        logger.error(f"Error in membership packages menu: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data.startswith("pkg_info_"))
async def membership_package_info(callback: CallbackQuery):
    """Show membership package info"""
    try:
        if callback.from_user.id not in ADMIN_IDS:
            await callback.answer("Unauthorized", show_alert=True)
            return

        pkg_type = callback.data.replace("pkg_info_", "")

        from config import (DEFAULT_AUTH_LIMIT, DEFAULT_PUAN_LIMIT,
                           DEFAULT_VBV_LIMIT, DEFAULT_IYZICO_LIMIT, DEFAULT_AUTH2_LIMIT)

        if pkg_type == "normal":
            info_text = (
                "NORMAL UYELIK\n\n"
                "Default limitler:\n"
                f"Auth: {DEFAULT_AUTH_LIMIT}\n"
                f"Puan: {DEFAULT_PUAN_LIMIT}\n"
                f"VBV: {DEFAULT_VBV_LIMIT}\n"
                f"Iyzico: {DEFAULT_IYZICO_LIMIT}\n"
                f"Auth2: {DEFAULT_AUTH2_LIMIT}\n\n"
                "Kullanim: /normal <chatid or username>"
            )
        elif pkg_type == "reklam":
            info_text = (
                "REKLAM UYELIGI\n\n"
                "Default limitlerin 2 kati:\n"
                f"Auth: {DEFAULT_AUTH_LIMIT * 2}\n"
                f"Puan: {DEFAULT_PUAN_LIMIT * 2}\n"
                f"VBV: {DEFAULT_VBV_LIMIT * 2}\n"
                f"Iyzico: {DEFAULT_IYZICO_LIMIT * 2}\n"
                f"Auth2: {DEFAULT_AUTH2_LIMIT * 2}\n\n"
                "Kullanim: /reklam <chatid or username>"
            )
        elif pkg_type == "dost":
            info_text = (
                "DOST UYELIGI\n\n"
                "Default limitlerin 3 kati:\n"
                f"Auth: {DEFAULT_AUTH_LIMIT * 3}\n"
                f"Puan: {DEFAULT_PUAN_LIMIT * 3}\n"
                f"VBV: {DEFAULT_VBV_LIMIT * 3}\n"
                f"Iyzico: {DEFAULT_IYZICO_LIMIT * 3}\n"
                f"Auth2: {DEFAULT_AUTH2_LIMIT * 3}\n\n"
                "Kullanim: /dost <chatid or username>"
            )
        elif pkg_type == "sinirsiz":
            info_text = (
                "SINIRSIZ UYELIK\n\n"
                "Tum limitler sinirsiz (999999):\n"
                "Auth: 999999\n"
                "Puan: 999999\n"
                "VBV: 999999\n"
                "Iyzico: 999999\n"
                "Auth2: 999999\n\n"
                "Kullanim: /sinirsiz <chatid or username>"
            )
        else:
            info_text = "Unknown package"

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="membership_packages")]
        ])

        await callback.message.edit_text(info_text, reply_markup=keyboard)
        await callback.answer()

    except Exception as e:
        logger.error(f"Error showing package info: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "reset_limits_info")
async def reset_limits_info(callback: CallbackQuery):
    """Show reset limits info"""
    try:
        if callback.from_user.id not in SUPERADMIN_IDS:
            await callback.answer("⛔ SUPERADMIN only", show_alert=True)
            return

        from config import (DEFAULT_AUTH_LIMIT, DEFAULT_PUAN_LIMIT,
                           DEFAULT_VBV_LIMIT, DEFAULT_IYZICO_LIMIT, DEFAULT_AUTH2_LIMIT,
                           DEFAULT_MOKA_LIMIT, DEFAULT_DISNEY_LIMIT, DEFAULT_STRIPE_LIMIT)

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="admin_panel")]
        ])

        info_text = (
            "LIMITLERI SIFIRLA\n\n"
            "Bu komut NORMAL, DESTEKCI, REKLAM ve DOST uyeliklerinin\n"
            "limitlerini default degerlere sifirlar.\n\n"
            "NORMAL limitleri:\n"
            f"Auth: {DEFAULT_AUTH_LIMIT}, Puan: {DEFAULT_PUAN_LIMIT}\n"
            f"VBV: {DEFAULT_VBV_LIMIT}, Disney: {DEFAULT_DISNEY_LIMIT}, Stripe: {DEFAULT_STRIPE_LIMIT}\n\n"
            "DESTEKCI/REKLAM limitleri (×2):\n"
            f"Auth: {DEFAULT_AUTH_LIMIT * 2}, Puan: {DEFAULT_PUAN_LIMIT * 2}\n"
            f"VBV: {DEFAULT_VBV_LIMIT * 2}, Stripe: {DEFAULT_STRIPE_LIMIT * 2}\n\n"
            "DOST limitleri (×5):\n"
            f"Auth: {DEFAULT_AUTH_LIMIT * 5}, Puan: {DEFAULT_PUAN_LIMIT * 5}\n"
            f"VBV: {DEFAULT_VBV_LIMIT * 5}, Stripe: {DEFAULT_STRIPE_LIMIT * 5}\n\n"
            "Kullanim: /resetlimits\n\n"
            "Not: SINIRSIZ ve ADMIN uyelikleri etkilenmez."
        )

        await callback.message.edit_text(info_text, reply_markup=keyboard)
        await callback.answer()

    except Exception as e:
        logger.error(f"Error showing reset limits info: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "referral_stats")
async def referral_stats_callback(callback: CallbackQuery):
    """Show referral system statistics"""
    try:
        if callback.from_user.id not in SUPERADMIN_IDS:
            await callback.answer("⛔ SUPERADMIN only", show_alert=True)
            return

        # Get statistics from database
        async with db.pool.acquire() as conn:
            async with conn.cursor(aiomysql.DictCursor) as cursor:
                # Total users
                await cursor.execute("SELECT COUNT(*) as total FROM users")
                total_users = (await cursor.fetchone())['total']

                # Users with referrals
                await cursor.execute("SELECT COUNT(*) as total FROM users WHERE total_referrals > 0")
                users_with_refs = (await cursor.fetchone())['total']

                # Total referrals made
                await cursor.execute("SELECT SUM(total_referrals) as total FROM users")
                total_referrals = (await cursor.fetchone())['total'] or 0

                # DESTEKCI members from referral
                await cursor.execute("SELECT COUNT(*) as total FROM users WHERE membership_type = 'destekci'")
                destekci_count = (await cursor.fetchone())['total']

                # Top referrers
                await cursor.execute(
                    "SELECT chatid, username, total_referrals, membership_type FROM users "
                    "WHERE total_referrals > 0 ORDER BY total_referrals DESC LIMIT 5"
                )
                top_referrers = await cursor.fetchall()

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="admin_panel")]
        ])

        top_list = "\n".join([
            f"{i+1}. @{r['username']} - {r['total_referrals']} refs ({r['membership_type']})"
            for i, r in enumerate(top_referrers)
        ]) if top_referrers else "Henüz yok"

        stats_text = (
            "📊 REFERRAL SİSTEMİ İSTATİSTİKLERİ\n\n"
            f"👥 Toplam Kullanıcı: {total_users}\n"
            f"🎁 Referral Yapan: {users_with_refs}\n"
            f"🔗 Toplam Referans: {total_referrals}\n"
            f"⭐ DESTEKCI Üye: {destekci_count}\n\n"
            f"🏆 TOP 5 REFERRER:\n{top_list}"
        )

        await callback.message.edit_text(stats_text, reply_markup=keyboard)
        await callback.answer()

        logger.info(f"Admin {callback.from_user.id} viewed referral stats")

    except Exception as e:
        logger.error(f"Error showing referral stats: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "refresh_vbv_token")
async def refresh_vbv_token(callback: CallbackQuery):
    """Refresh VBV API token by running external script"""
    try:
        if callback.from_user.id not in SUPERADMIN_IDS:
            await callback.answer("⛔ SUPERADMIN only", show_alert=True)
            return

        # Show processing message
        await callback.answer("Processing... This may take up to 3 minutes.", show_alert=True)
        await callback.message.edit_text("VBV TOKEN YENILENIYOR...\n\nPlease wait, this may take up to 3 minutes.")

        # Run the Python script with 3 minute timeout using thread executor
        import asyncio
        import sys
        from concurrent.futures import ThreadPoolExecutor
        import importlib.util

        # Get absolute paths
        base_dir = os.path.dirname(os.path.abspath(__file__))
        script_path = os.path.join(base_dir, "apiler", "vbvapi", "vbvtokenyenile.py")
        script_dir = os.path.join(base_dir, "apiler", "vbvapi")
        token_file = os.path.join(script_dir, "vbvapitoken.txt")

        # Function to run the script
        def run_token_script():
            import subprocess
            import os
            import sys
            import platform

            try:
                # Prepare environment
                env = os.environ.copy()

                # Linux-specific environment variables
                if platform.system() == 'Linux':
                    # Add display for headless Chrome
                    env['DISPLAY'] = ':99'  # Xvfb display if available

                    # Add chromedriver to PATH if needed
                    chromedriver_paths = [
                        '/usr/bin',
                        '/usr/local/bin',
                        '/opt/chromedriver'
                    ]
                    if 'PATH' in env:
                        env['PATH'] = ':'.join(chromedriver_paths) + ':' + env['PATH']
                    else:
                        env['PATH'] = ':'.join(chromedriver_paths)

                # Use subprocess to run the script with proper environment
                # This ensures Chrome/Selenium has access to all necessary paths
                result = subprocess.run(
                    [sys.executable, script_path],
                    cwd=script_dir,
                    capture_output=True,
                    text=True,
                    timeout=180,
                    env=env
                )

                output = result.stdout + result.stderr

                if result.returncode == 0:
                    return True, output
                else:
                    return False, f"Exit code {result.returncode}: {output}"
            except subprocess.TimeoutExpired:
                return False, "Script timeout (180 seconds)"
            except Exception as e:
                return False, str(e)

        # Get old token timestamp
        old_token_time = 0
        old_token_content = ""
        try:
            if os.path.exists(token_file):
                old_token_time = os.path.getmtime(token_file)
                with open(token_file, 'r') as f:
                    old_token_content = f.read().strip()
        except:
            pass

        try:
            # Run script in thread pool executor
            loop = asyncio.get_event_loop()
            executor = ThreadPoolExecutor(max_workers=1)

            # Start the script execution in background thread
            future = loop.run_in_executor(executor, run_token_script)

            # Monitor token file for changes while script runs
            max_wait = 180  # 3 minutes
            check_interval = 5
            elapsed = 0
            token_updated = False
            script_result = None
            script_error = None

            await callback.message.edit_text(
                "VBV TOKEN YENILENIYOR...\n\n"
                "Script execution started in background thread...\n"
                f"Timeout: {max_wait} seconds"
            )

            while elapsed < max_wait:
                await asyncio.sleep(check_interval)
                elapsed += check_interval

                # Check if script finished
                if future.done():
                    script_result, script_error = future.result()

                # Check if token file was modified
                try:
                    if os.path.exists(token_file):
                        with open(token_file, 'r') as f:
                            new_token_content = f.read().strip()

                        # Check if content changed (not just timestamp)
                        if new_token_content != old_token_content and len(new_token_content) > 10:
                            token_updated = True
                            new_token = new_token_content
                            break
                except Exception as e:
                    logger.error(f"Error checking token file: {e}")

                # Update progress message every 15 seconds
                if elapsed % 15 == 0:
                    status_msg = "Script running in background thread...\n"
                    if script_result is not None:
                        status_msg = f"Script finished: {script_error}\n"

                    await callback.message.edit_text(
                        "VBV TOKEN YENILENIYOR...\n\n"
                        f"{status_msg}"
                        f"Time elapsed: {elapsed}/{max_wait} seconds\n"
                        "Waiting for token update..."
                    )

            # Cancel future if still running
            if not future.done():
                future.cancel()

            # Format response based on result
            if token_updated:
                response = (
                    "VBV TOKEN YENILEME BASARILI\n\n"
                    f"Token updated successfully after {elapsed} seconds.\n\n"
                    f"New Token (preview): {new_token[:50]}...\n\n"
                    f"Full token saved to: vbvapitoken.txt"
                )
            else:
                # Check script result
                if script_result is not None:
                    if script_result:
                        response = (
                            "VBV TOKEN YENILEME TAMAMLANDI\n\n"
                            f"Script executed successfully but token file was not updated.\n"
                            f"Time: {elapsed} seconds\n\n"
                            "Check vbvapitoken.txt file manually."
                        )
                    else:
                        response = (
                            "VBV TOKEN YENILEME HATASI\n\n"
                            f"Script encountered an error:\n{script_error}\n\n"
                            "Try running manually: python apiler/vbvapi/vbvtokenyenile.py"
                        )
                else:
                    response = (
                        "VBV TOKEN YENILEME TIMEOUT\n\n"
                        f"No token update detected after {max_wait} seconds.\n\n"
                        "The script may still be running in the background.\n"
                        "Check vbvapitoken.txt file later."
                    )

            # Limit response length
            if len(response) > 4000:
                response = response[:4000] + "\n\n... (output truncated)"

        except asyncio.TimeoutError:
            response = "VBV TOKEN YENILEME TIMEOUT\n\nThe script took longer than 3 minutes to complete."
            logger.error(f"VBV token refresh timeout for admin {callback.from_user.id}")
        except FileNotFoundError:
            response = f"VBV TOKEN YENILEME HATASI\n\nScript not found: {script_path}"
            logger.error(f"VBV script not found: {script_path}")
        except Exception as script_error:
            response = f"VBV TOKEN YENILEME HATASI\n\n{str(script_error)}"
            logger.error(f"Error running VBV script: {script_error}")

        # Add go back button
        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="api_fix_menu")]
        ])

        await callback.message.edit_text(response, reply_markup=keyboard)
        logger.info(f"Admin {callback.from_user.id} refreshed VBV token")

    except Exception as e:
        logger.error(f"Error refreshing VBV token: {e}")
        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="api_fix_menu")]
        ])
        await callback.message.edit_text(f"An error occurred: {str(e)}", reply_markup=keyboard)

@dp.callback_query(F.data == "manual_vbv_token")
async def manual_vbv_token(callback: CallbackQuery):
    """Manually add VBV API token"""
    try:
        if callback.from_user.id not in SUPERADMIN_IDS:
            await callback.answer("⛔ SUPERADMIN only", show_alert=True)
            return

        # Mark this admin as waiting for token input
        admin_waiting_for[callback.from_user.id] = "vbv_token"

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="İPTAL", callback_data="api_fix_menu")]
        ])

        await callback.message.edit_text(
            "VBV API MANUEL TOKEN EKLE\n\n"
            "Örnek: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...\n\n"
            "İptal etmek için İPTAL butonuna basın.",
            reply_markup=keyboard
        )
        await callback.answer()
        logger.info(f"Admin {callback.from_user.id} started manual VBV token entry")

    except Exception as e:
        logger.error(f"Error in manual VBV token entry: {e}")
        await callback.answer("Bir hata oluştu.", show_alert=True)

@dp.callback_query(F.data == "refresh_auth1_token")
async def refresh_auth1_token(callback: CallbackQuery):
    """Refresh AUTH1 token by calling volt.php"""
    try:
        if callback.from_user.id not in SUPERADMIN_IDS:
            await callback.answer("⛔ SUPERADMIN only", show_alert=True)
            return

        # Show processing message
        await callback.answer("Processing...", show_alert=True)
        await callback.message.edit_text("AUTH1 TOKEN YENILENIYOR...\n\nPlease wait...")

        # Call the API
        api_url = "http://localhost/yenicheckbotaerithia/apiler/auth1/volt.php"

        try:
            async with aiohttp.ClientSession() as session:
                async with session.get(api_url, timeout=aiohttp.ClientTimeout(total=60)) as response:
                    result = await response.text()

                    # Format response
                    keyboard = InlineKeyboardMarkup(inline_keyboard=[
                        [InlineKeyboardButton(text="GO BACK", callback_data="api_fix_menu")]
                    ])

                    response_text = (
                        "AUTH1 TOKEN YENILEME SONUCU:\n\n"
                        f"{result}\n\n"
                        "Token yenileme işlemi tamamlandı."
                    )

                    await callback.message.edit_text(response_text, reply_markup=keyboard)
                    logger.info(f"Admin {callback.from_user.id} refreshed AUTH1 token")

        except Exception as e:
            logger.error(f"Error calling AUTH1 API: {e}")
            keyboard = InlineKeyboardMarkup(inline_keyboard=[
                [InlineKeyboardButton(text="GO BACK", callback_data="api_fix_menu")]
            ])
            await callback.message.edit_text(f"API Error: {str(e)}", reply_markup=keyboard)

    except Exception as e:
        logger.error(f"Error refreshing AUTH1 token: {e}")
        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="api_fix_menu")]
        ])
        await callback.message.edit_text(f"An error occurred: {str(e)}", reply_markup=keyboard)

@dp.callback_query(F.data == "refresh_auth1mass_token")
async def refresh_auth1mass_token(callback: CallbackQuery):
    """Refresh AUTH1MASS token by calling voltmass.php"""
    try:
        if callback.from_user.id not in SUPERADMIN_IDS:
            await callback.answer("⛔ SUPERADMIN only", show_alert=True)
            return

        # Show processing message
        await callback.answer("Processing...", show_alert=True)
        await callback.message.edit_text("AUTH1MASS TOKEN YENILENIYOR...\n\nPlease wait...")

        # Call the API
        api_url = "http://localhost/yenicheckbotaerithia/apiler/auth1/voltmass.php"

        try:
            async with aiohttp.ClientSession() as session:
                async with session.get(api_url, timeout=aiohttp.ClientTimeout(total=60)) as response:
                    result = await response.text()

                    # Format response
                    keyboard = InlineKeyboardMarkup(inline_keyboard=[
                        [InlineKeyboardButton(text="GO BACK", callback_data="api_fix_menu")]
                    ])

                    response_text = (
                        "AUTH1MASS TOKEN YENILEME SONUCU:\n\n"
                        f"{result}\n\n"
                        "Token yenileme işlemi tamamlandı."
                    )

                    await callback.message.edit_text(response_text, reply_markup=keyboard)
                    logger.info(f"Admin {callback.from_user.id} refreshed AUTH1MASS token")

        except Exception as e:
            logger.error(f"Error calling AUTH1MASS API: {e}")
            keyboard = InlineKeyboardMarkup(inline_keyboard=[
                [InlineKeyboardButton(text="GO BACK", callback_data="api_fix_menu")]
            ])
            await callback.message.edit_text(f"API Error: {str(e)}", reply_markup=keyboard)

    except Exception as e:
        logger.error(f"Error refreshing AUTH1MASS token: {e}")
        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="api_fix_menu")]
        ])
        await callback.message.edit_text(f"An error occurred: {str(e)}", reply_markup=keyboard)

@dp.callback_query(F.data == "gate_management")
async def gate_management_menu(callback: CallbackQuery):
    """Gate Management menu - Enable/Disable gates"""
    try:
        if callback.from_user.id not in SUPERADMIN_IDS:
            await callback.answer("⛔ SUPERADMIN only", show_alert=True)
            return

        # Get all gates with their status
        gates = await db.get_all_gates()

        # Create a dictionary for easy access
        gate_dict = {gate['gate_name']: gate['is_active'] for gate in gates}

        # Create buttons in 2-column layout
        buttons = []

        # Helper function to create button
        def make_button(gate_name):
            is_active = gate_dict.get(gate_name, 1)
            status_emoji = "✅" if is_active else "❌"
            button_text = f"{gate_name.upper()} {status_emoji}"
            return InlineKeyboardButton(
                text=button_text,
                callback_data=f"toggle_gate_{gate_name}"
            )

        # Get all gate names except bot_status (we handle that separately)
        gate_names = [gate['gate_name'] for gate in gates if gate['gate_name'] != 'bot_status']

        # Dynamically pair gates: base gates with their 'mass' counterparts
        # Sort to maintain consistent ordering
        gate_names_sorted = sorted(gate_names)

        # Separate base gates and mass gates
        base_gates = [g for g in gate_names_sorted if not g.endswith('mass')]
        mass_gates = [g for g in gate_names_sorted if g.endswith('mass')]

        # Create pairs where mass gate matches base gate
        paired_gates = set()
        for base_gate in base_gates:
            mass_gate = f"{base_gate}mass"
            row = []

            if base_gate in gate_dict:
                row.append(make_button(base_gate))
                paired_gates.add(base_gate)

            if mass_gate in gate_dict:
                row.append(make_button(mass_gate))
                paired_gates.add(mass_gate)

            if row:  # Only add row if at least one gate exists
                buttons.append(row)

        # Add any remaining unpaired gates (2 per row)
        remaining_gates = [g for g in gate_names_sorted if g not in paired_gates]
        for i in range(0, len(remaining_gates), 2):
            row = []
            row.append(make_button(remaining_gates[i]))
            if i + 1 < len(remaining_gates):
                row.append(make_button(remaining_gates[i + 1]))
            buttons.append(row)

        # Add back button
        buttons.append([InlineKeyboardButton(text="GO BACK", callback_data="admin_panel")])

        keyboard = InlineKeyboardMarkup(inline_keyboard=buttons)

        message_text = (
            "GATE YÖNETIMI\n\n"
            "✅ = Aktif (Açık)\n"
            "❌ = Disabled (Kapalı)\n\n"
            "Bir gate'i açmak/kapatmak için tıklayın:"
        )

        await callback.message.edit_text(message_text, reply_markup=keyboard)
        await callback.answer()
        logger.info(f"Admin {callback.from_user.id} opened gate management")

    except Exception as e:
        logger.error(f"Error in gate management menu: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data.startswith("toggle_gate_"))
async def toggle_gate(callback: CallbackQuery):
    """Toggle a specific gate on/off"""
    try:
        if callback.from_user.id not in SUPERADMIN_IDS:
            await callback.answer("⛔ SUPERADMIN only", show_alert=True)
            return

        # Extract gate name from callback data
        gate_name = callback.data.replace("toggle_gate_", "")

        # Toggle the gate status
        new_status = await db.toggle_gate_status(gate_name)

        if new_status is not None:
            status_text = "AKTIF" if new_status else "DISABLED"
            await callback.answer(f"{gate_name.upper()} {status_text}", show_alert=True)

            # Refresh the menu to show updated status
            await gate_management_menu(callback)

            logger.info(f"Admin {callback.from_user.id} toggled {gate_name} to {status_text}")
        else:
            await callback.answer("Error updating gate status", show_alert=True)

    except Exception as e:
        logger.error(f"Error toggling gate: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "send_announcement")
async def send_announcement_prompt(callback: CallbackQuery):
    """Prompt for announcement message"""
    try:
        if callback.from_user.id not in SUPERADMIN_IDS:
            await callback.answer("⛔ SUPERADMIN only", show_alert=True)
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="İPTAL", callback_data="admin_panel")]
        ])

        await callback.message.edit_text(
            "📢 DUYURU GÖNDER\n\n"
            "Göndermek istediğiniz duyuruyu yazın:\n\n"
            "Kullanım: /duyuru <mesajınız>\n\n"
            "Örnek:\n"
            "/duyuru Bot bakımda! 1 saat sonra tekrar aktif olacak.",
            reply_markup=keyboard
        )
        await callback.answer()

    except Exception as e:
        logger.error(f"Error in send announcement prompt: {e}")
        await callback.answer("Bir hata oluştu")

@dp.message(Command("duyuru"))
async def cmd_announcement(message: Message):
    """Send announcement to all users"""
    try:
        if message.from_user.id not in SUPERADMIN_IDS:
            await message.answer("⛔ Bu komutu kullanma yetkiniz yok!")
            return

        # Get announcement text
        command_parts = message.text.split(maxsplit=1)
        if len(command_parts) < 2:
            await message.answer(
                "❌ Kullanım: /duyuru <mesajınız>\n\n"
                "Örnek:\n"
                "/duyuru Bot bakımda! 1 saat sonra tekrar aktif olacak."
            )
            return

        announcement_text = command_parts[1]

        # Get all users
        all_users = await db.get_all_users()

        if not all_users:
            await message.answer("❌ Hiç kullanıcı bulunamadı!")
            return

        # Send confirmation
        confirm_msg = await message.answer(
            f"📢 DUYURU GÖNDERİLİYOR...\n\n"
            f"Toplam {len(all_users)} kullanıcıya gönderilecek.\n\n"
            f"Mesaj:\n{announcement_text}"
        )

        # Send to all users
        success_count = 0
        fail_count = 0

        for user in all_users:
            try:
                chat_id = user.get('chatid')
                if chat_id:
                    await bot.send_message(chat_id, announcement_text)
                    success_count += 1
                    await asyncio.sleep(0.05)  # Rate limit protection
            except Exception as e:
                fail_count += 1
                logger.error(f"Failed to send announcement to {chat_id}: {e}")

        # Send result
        await confirm_msg.edit_text(
            f"✅ DUYURU GÖNDERİLDİ!\n\n"
            f"✅ Başarılı: {success_count}\n"
            f"❌ Başarısız: {fail_count}\n"
            f"📊 Toplam: {len(all_users)}"
        )

        logger.info(f"Admin {message.from_user.id} sent announcement to {success_count}/{len(all_users)} users")

    except Exception as e:
        logger.error(f"Error in announcement command: {e}")
        await message.answer("❌ Bir hata oluştu!")

@dp.callback_query(F.data == "toggle_bot_status")
async def toggle_bot_status(callback: CallbackQuery):
    """Toggle bot on/off (maintenance mode)"""
    try:
        if callback.from_user.id not in SUPERADMIN_IDS:
            await callback.answer("⛔ SUPERADMIN only", show_alert=True)
            return

        # Toggle bot status
        new_status = await db.toggle_gate_status('bot_status')

        if new_status is not None:
            status_text = "AÇIK ✅" if new_status else "KAPALI ❌"

            await callback.answer(f"BOT {status_text}", show_alert=True)

            # Refresh admin panel to show updated emoji
            await admin_panel_menu(callback)

            logger.info(f"Admin {callback.from_user.id} toggled bot to {status_text}")
        else:
            await callback.answer("Error updating bot status", show_alert=True)

    except Exception as e:
        logger.error(f"Error toggling bot status: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "view_users")
async def view_all_users(callback: CallbackQuery):
    """View all users"""
    try:
        if callback.from_user.id not in SUPERADMIN_IDS:
            await callback.answer("⛔ SUPERADMIN only", show_alert=True)
            return

        users = await db.get_all_users()

        if not users:
            keyboard = InlineKeyboardMarkup(inline_keyboard=[
                [InlineKeyboardButton(text="GO BACK", callback_data="admin_panel")]
            ])
            await callback.message.edit_text("No users found.", reply_markup=keyboard)
            await callback.answer()
            return

        # Format user list (compact)
        user_list = "ALL USERS:\n\n"
        for user in users:
            total_limit = (user.get('chargelimit', 0) + user.get('authlimit', 0) +
                          user.get('puanlimit', 0) + user.get('vbvlimit', 0) +
                          user.get('iyzicolimit', 0) + user.get('auth2limit', 0))

            user_list += f"{user['chatid']} @{user.get('username', 'N/A')} Limit: {total_limit}\n"

        # Add go back button
        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="admin_panel")]
        ])

        # Split into multiple messages if too long
        if len(user_list) > 4000:
            chunks = [user_list[i:i+4000] for i in range(0, len(user_list), 4000)]
            for i, chunk in enumerate(chunks):
                if i == 0:
                    await callback.message.edit_text(chunk, reply_markup=keyboard)
                else:
                    await callback.message.answer(chunk)
        else:
            await callback.message.edit_text(user_list, reply_markup=keyboard)

        await callback.answer()
        logger.info(f"Admin {callback.from_user.id} viewed all users")

    except Exception as e:
        logger.error(f"Error viewing users: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "view_banned_users")
async def view_banned_users(callback: CallbackQuery):
    """View all banned users"""
    try:
        if callback.from_user.id not in SUPERADMIN_IDS:
            await callback.answer("⛔ SUPERADMIN only", show_alert=True)
            return

        users = await db.get_all_users()

        # Filter banned users only
        banned_users = [user for user in users if user.get('banned', 0) == 1]

        if not banned_users:
            keyboard = InlineKeyboardMarkup(inline_keyboard=[
                [InlineKeyboardButton(text="GO BACK", callback_data="admin_panel")]
            ])
            await callback.message.edit_text("No banned users found.", reply_markup=keyboard)
            await callback.answer()
            return

        # Format banned user list (compact)
        user_list = "BANNED USERS:\n\n"
        for user in banned_users:
            total_limit = (user.get('chargelimit', 0) + user.get('authlimit', 0) +
                          user.get('puanlimit', 0) + user.get('vbvlimit', 0) +
                          user.get('iyzicolimit', 0) + user.get('auth2limit', 0))

            user_list += f"{user['chatid']} @{user.get('username', 'N/A')} Limit: {total_limit}\n"

        # Add go back button
        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="admin_panel")]
        ])

        # Split into multiple messages if too long
        if len(user_list) > 4000:
            chunks = [user_list[i:i+4000] for i in range(0, len(user_list), 4000)]
            for i, chunk in enumerate(chunks):
                if i == 0:
                    await callback.message.edit_text(chunk, reply_markup=keyboard)
                else:
                    await callback.message.answer(chunk)
        else:
            await callback.message.edit_text(user_list, reply_markup=keyboard)

        await callback.answer()
        logger.info(f"Admin {callback.from_user.id} viewed banned users")

    except Exception as e:
        logger.error(f"Error viewing banned users: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "view_premium_users")
async def view_premium_users(callback: CallbackQuery):
    """View all premium/advantageous members (non-normal membership)"""
    try:
        if callback.from_user.id not in SUPERADMIN_IDS:
            await callback.answer("⛔ SUPERADMIN only", show_alert=True)
            return

        users = await db.get_all_users()

        # Filter premium users (membership_type not null and not 'normal')
        premium_users = [user for user in users
                        if user.get('membership_type')
                        and user.get('membership_type') not in ['normal', 'None', None]]

        if not premium_users:
            keyboard = InlineKeyboardMarkup(inline_keyboard=[
                [InlineKeyboardButton(text="GO BACK", callback_data="admin_panel")]
            ])
            await callback.message.edit_text("No premium users found.", reply_markup=keyboard)
            await callback.answer()
            return

        # Format premium user list
        user_list = f"AVANTAJLI UYELER ({len(premium_users)}):\n\n"

        for user in premium_users:
            membership = user.get('membership_type', 'N/A').upper()
            username = user.get('username', 'N/A')
            chat_id = user['chatid']

            # Calculate total limits
            stripe_limit = user.get('stripegenellimit', 0)
            auth_limit = user.get('authlimit', 0)
            puan_limit = user.get('puanlimit', 0)
            shopify_limit = user.get('shopifylimit', 0)

            user_list += f"👤 {chat_id} @{username}\n"
            user_list += f"   📦 Üyelik: {membership}\n"
            user_list += f"   🎫 Stripe: {stripe_limit} | Auth: {auth_limit} | Puan: {puan_limit} | Shopify: {shopify_limit}\n\n"

        # Add go back button
        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="admin_panel")]
        ])

        # Split into multiple messages if too long
        if len(user_list) > 4000:
            chunks = [user_list[i:i+4000] for i in range(0, len(user_list), 4000)]
            for i, chunk in enumerate(chunks):
                if i == 0:
                    await callback.message.edit_text(chunk, reply_markup=keyboard)
                else:
                    await callback.message.answer(chunk)
        else:
            await callback.message.edit_text(user_list, reply_markup=keyboard)

        await callback.answer()
        logger.info(f"Superadmin {callback.from_user.id} viewed premium users")

    except Exception as e:
        logger.error(f"Error viewing premium users: {e}")
        await callback.answer("An error occurred.")

@dp.callback_query(F.data == "search_user_prompt")
async def search_user_prompt(callback: CallbackQuery):
    """Prompt for user search"""
    try:
        if callback.from_user.id not in ADMIN_IDS:
            await callback.answer("Unauthorized", show_alert=True)
            return

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="GO BACK", callback_data="admin_panel")]
        ])

        await callback.message.edit_text(
            "SEARCH USER\n\n"
            "Use command: /search <chatid or username>\n\n"
            "Example:\n"
            "/search 123456789\n"
            "/search john",
            reply_markup=keyboard
        )
        await callback.answer()

    except Exception as e:
        logger.error(f"Error in search prompt: {e}")
        await callback.answer("An error occurred.")

@dp.message(Command("ban"))
async def cmd_ban(message: Message):
    """Ban a user"""
    try:
        if message.from_user.id not in ADMIN_IDS:
            return

        parts = message.text.strip().split(maxsplit=1)

        if len(parts) < 2:
            await message.answer("Usage: /ban <chatid>")
            return

        try:
            chat_id_to_ban = int(parts[1])
        except ValueError:
            await message.answer("Invalid chat ID. Must be a number.")
            return

        # Check if user exists
        user = await db.get_user(chat_id_to_ban)
        if not user:
            await message.answer("User not found in database.")
            return

        # Ban user
        success = await db.ban_user(chat_id_to_ban)

        if success:
            await message.answer(f"User {chat_id_to_ban} (@{user.get('username', 'N/A')}) has been banned.")
            logger.info(f"Admin {message.from_user.id} banned user {chat_id_to_ban}")
        else:
            await message.answer("Failed to ban user.")

    except Exception as e:
        logger.error(f"Error in ban command: {e}")
        await message.answer("An error occurred.")

@dp.message(Command("unban"))
async def cmd_unban(message: Message):
    """Unban a user"""
    try:
        if message.from_user.id not in ADMIN_IDS:
            return

        parts = message.text.strip().split(maxsplit=1)

        if len(parts) < 2:
            await message.answer("Usage: /unban <chatid>")
            return

        try:
            chat_id_to_unban = int(parts[1])
        except ValueError:
            await message.answer("Invalid chat ID. Must be a number.")
            return

        # Check if user exists
        user = await db.get_user(chat_id_to_unban)
        if not user:
            await message.answer("User not found in database.")
            return

        # Unban user
        success = await db.unban_user(chat_id_to_unban)

        if success:
            await message.answer(f"User {chat_id_to_unban} (@{user.get('username', 'N/A')}) has been unbanned.")
            logger.info(f"Admin {message.from_user.id} unbanned user {chat_id_to_unban}")
        else:
            await message.answer("Failed to unban user.")

    except Exception as e:
        logger.error(f"Error in unban command: {e}")
        await message.answer("An error occurred.")

@dp.message(Command("search"))
async def cmd_search(message: Message):
    """Search for a user"""
    try:
        if message.from_user.id not in ADMIN_IDS:
            return

        parts = message.text.strip().split(maxsplit=1)

        if len(parts) < 2:
            await message.answer("Usage: /search <chatid or username>")
            return

        search_term = parts[1]
        users = await db.search_user(search_term)

        if not users:
            await message.answer("No users found.")
            return

        # Format search results (compact)
        result_text = f"SEARCH RESULTS FOR '{search_term}':\n\n"
        for user in users:
            total_limit = (user.get('chargelimit', 0) + user.get('authlimit', 0) +
                          user.get('puanlimit', 0) + user.get('vbvlimit', 0) +
                          user.get('iyzicolimit', 0) + user.get('auth2limit', 0))

            result_text += f"{user['chatid']} @{user.get('username', 'N/A')} Limit: {total_limit}\n"

        await message.answer(result_text)
        logger.info(f"Admin {message.from_user.id} searched for: {search_term}")

    except Exception as e:
        logger.error(f"Error in search command: {e}")
        await message.answer("An error occurred.")

@dp.message(Command("reklam"))
async def cmd_reklam_membership(message: Message):
    """Set REKLAM membership"""
    try:
        if message.from_user.id not in ADMIN_IDS:
            return

        parts = message.text.strip().split(maxsplit=1)

        if len(parts) < 2:
            await message.answer("Usage: /reklam <chatid or username>")
            return

        search_term = parts[1]
        users = await db.search_user(search_term)

        if not users:
            await message.answer("User not found.")
            return

        user = users[0]
        chat_id = user['chatid']

        from config import (DEFAULT_AUTH_LIMIT, DEFAULT_PUAN_LIMIT,
                           DEFAULT_VBV_LIMIT, DEFAULT_IYZICO_LIMIT, DEFAULT_AUTH2_LIMIT,
                           DEFAULT_MOKA_LIMIT, DEFAULT_DISNEY_LIMIT, DEFAULT_STRIPE_LIMIT)

        # Set limits to 2x default
        success = await db.set_membership(
            chat_id, 'reklam',
            DEFAULT_AUTH_LIMIT * 2, DEFAULT_PUAN_LIMIT * 2,
            DEFAULT_VBV_LIMIT * 2, DEFAULT_IYZICO_LIMIT * 2, DEFAULT_AUTH2_LIMIT * 2,
            DEFAULT_AUTH_LIMIT * 2, DEFAULT_DISNEY_LIMIT * 2, DEFAULT_STRIPE_LIMIT * 2
        )

        if success:
            await message.answer(
                f"User {chat_id} (@{user.get('username', 'N/A')}) upgraded to REKLAM membership.\n\n"
                f"New limits:\n"
                f"Auth: {DEFAULT_AUTH_LIMIT * 2}\n"
                f"Puan: {DEFAULT_PUAN_LIMIT * 2}\n"
                f"VBV: {DEFAULT_VBV_LIMIT * 2}\n"
                f"Iyzico: {DEFAULT_IYZICO_LIMIT * 2}\n"
                f"Auth2: {DEFAULT_AUTH2_LIMIT * 2}\n"
                f"Moka: {DEFAULT_AUTH_LIMIT * 2}\n"
                f"Disney: {DEFAULT_DISNEY_LIMIT * 2}\n"
                f"Stripe: {DEFAULT_STRIPE_LIMIT * 2}"
            )
            logger.info(f"Admin {message.from_user.id} set REKLAM membership for user {chat_id}")
        else:
            await message.answer("Failed to upgrade user.")

    except Exception as e:
        logger.error(f"Error in reklam command: {e}")
        await message.answer("An error occurred.")

@dp.message(Command("dost"))
async def cmd_dost_membership(message: Message):
    """Set DOST membership"""
    try:
        if message.from_user.id not in ADMIN_IDS:
            return

        parts = message.text.strip().split(maxsplit=1)

        if len(parts) < 2:
            await message.answer("Usage: /dost <chatid or username>")
            return

        search_term = parts[1]
        users = await db.search_user(search_term)

        if not users:
            await message.answer("User not found.")
            return

        user = users[0]
        chat_id = user['chatid']

        from config import (DEFAULT_AUTH_LIMIT, DEFAULT_PUAN_LIMIT,
                           DEFAULT_VBV_LIMIT, DEFAULT_IYZICO_LIMIT, DEFAULT_AUTH2_LIMIT,
                           DEFAULT_MOKA_LIMIT, DEFAULT_DISNEY_LIMIT, DEFAULT_STRIPE_LIMIT)

        # Set limits to 3x default
        success = await db.set_membership(
            chat_id, 'dost',
            DEFAULT_AUTH_LIMIT * 3, DEFAULT_PUAN_LIMIT * 3,
            DEFAULT_VBV_LIMIT * 3, DEFAULT_IYZICO_LIMIT * 3, DEFAULT_AUTH2_LIMIT * 3,
            DEFAULT_AUTH_LIMIT * 3, DEFAULT_DISNEY_LIMIT * 3, DEFAULT_STRIPE_LIMIT * 3
        )

        if success:
            await message.answer(
                f"User {chat_id} (@{user.get('username', 'N/A')}) upgraded to DOST membership.\n\n"
                f"New limits:\n"
                f"Auth: {DEFAULT_AUTH_LIMIT * 3}\n"
                f"Puan: {DEFAULT_PUAN_LIMIT * 3}\n"
                f"VBV: {DEFAULT_VBV_LIMIT * 3}\n"
                f"Iyzico: {DEFAULT_IYZICO_LIMIT * 3}\n"
                f"Auth2: {DEFAULT_AUTH2_LIMIT * 3}\n"
                f"Moka: {DEFAULT_AUTH_LIMIT * 3}\n"
                f"Disney: {DEFAULT_DISNEY_LIMIT * 3}\n"
                f"Stripe: {DEFAULT_STRIPE_LIMIT * 3}"
            )
            logger.info(f"Admin {message.from_user.id} set DOST membership for user {chat_id}")
        else:
            await message.answer("Failed to upgrade user.")

    except Exception as e:
        logger.error(f"Error in dost command: {e}")
        await message.answer("An error occurred.")

@dp.message(Command("sinirsiz"))
async def cmd_sinirsiz_membership(message: Message):
    """Set SINIRSIZ membership"""
    try:
        if message.from_user.id not in ADMIN_IDS:
            return

        parts = message.text.strip().split(maxsplit=1)

        if len(parts) < 2:
            await message.answer("Usage: /sinirsiz <chatid or username>")
            return

        search_term = parts[1]
        users = await db.search_user(search_term)

        if not users:
            await message.answer("User not found.")
            return

        user = users[0]
        chat_id = user['chatid']

        # Set all limits to 999999
        success = await db.set_membership(
            chat_id, 'sinirsiz',
            999999, 999999, 999999, 999999, 999999, 999999, 999999, 999999
        )

        if success:
            await message.answer(
                f"User {chat_id} (@{user.get('username', 'N/A')}) upgraded to SINIRSIZ membership.\n\n"
                f"New limits: ALL UNLIMITED (999999)"
            )
            logger.info(f"Admin {message.from_user.id} set SINIRSIZ membership for user {chat_id}")
        else:
            await message.answer("Failed to upgrade user.")

    except Exception as e:
        logger.error(f"Error in sinirsiz command: {e}")
        await message.answer("An error occurred.")

@dp.message(Command("normal"))
async def cmd_normal_membership(message: Message):
    """Set NORMAL membership (default limits)"""
    try:
        if message.from_user.id not in ADMIN_IDS:
            return

        parts = message.text.strip().split(maxsplit=1)

        if len(parts) < 2:
            await message.answer("Usage: /normal <chatid or username>")
            return

        search_term = parts[1]
        users = await db.search_user(search_term)

        if not users:
            await message.answer("User not found.")
            return

        user = users[0]
        chat_id = user['chatid']

        from config import (DEFAULT_AUTH_LIMIT, DEFAULT_PUAN_LIMIT,
                           DEFAULT_VBV_LIMIT, DEFAULT_IYZICO_LIMIT, DEFAULT_AUTH2_LIMIT,
                           DEFAULT_STRIPEGENEL_LIMIT)

        # Set all limits to default values
        success = await db.set_membership(
            chat_id, 'normal',
            DEFAULT_AUTH_LIMIT, DEFAULT_PUAN_LIMIT, DEFAULT_VBV_LIMIT,
            DEFAULT_IYZICO_LIMIT, DEFAULT_AUTH2_LIMIT, DEFAULT_AUTH_LIMIT,
            5, DEFAULT_STRIPEGENEL_LIMIT
        )

        if success:
            await message.answer(
                f"User {chat_id} (@{user.get('username', 'N/A')}) set to NORMAL membership.\n\n"
                f"New limits:\n"
                f"Auth: {DEFAULT_AUTH_LIMIT}\n"
                f"Puan: {DEFAULT_PUAN_LIMIT}\n"
                f"VBV: {DEFAULT_VBV_LIMIT}\n"
                f"Iyzico: {DEFAULT_IYZICO_LIMIT}\n"
                f"Auth2: {DEFAULT_AUTH2_LIMIT}\n"
                f"Stripe: {DEFAULT_STRIPEGENEL_LIMIT}"
            )
            logger.info(f"Admin {message.from_user.id} set NORMAL membership for user {chat_id}")
        else:
            await message.answer("Failed to set user to normal membership.")

    except Exception as e:
        logger.error(f"Error in normal command: {e}")
        await message.answer("An error occurred.")

@dp.message(Command("referral"))
async def cmd_referral(message: Message):
    """Show user's referral information"""
    try:
        chat_id = message.from_user.id

        # Check membership
        is_member = await check_membership_direct(chat_id)
        if not is_member:
            await message.answer("Please join our channel and chat first. Use /start")
            return

        # Check and upgrade if needed
        upgraded = await db.check_and_upgrade_referral(chat_id)
        if upgraded:
            try:
                await message.answer(
                    "🎉 Congratulations! You completed 5 referrals!\n"
                    "🎉 Tebrikler! 5 referans tamamladınız!\n\n"
                    "Upgraded to SUPPORTER membership.\n"
                    "DESTEKCI üyeliğine yükseltildiniz.\n\n"
                    "All limits doubled! (×2)\n"
                    "Tüm limitler 2 katına çıkarıldı! (×2)"
                )
            except:
                pass

        # Get user data (refresh after potential upgrade)
        user = await db.get_user(chat_id)
        if not user:
            await message.answer("User not found. Please use /start first.")
            return

        referral_code = user.get('referral_code', 'N/A')
        total_refs = user.get('total_referrals', 0)
        membership = user.get('membership_type', 'normal')

        bot_username = (await bot.get_me()).username
        referral_link = f"https://t.me/{bot_username}?start={referral_code}"

        # Calculate next level
        next_level_text_tr = ""
        next_level_text_en = ""
        if membership == 'normal':
            refs_needed = 5 - total_refs
            if refs_needed > 0:
                next_level_text_tr = f"🔒 5 referans → DESTEKCI (×2 limits) - {refs_needed} referans kaldı"
                next_level_text_en = f"🔒 5 referrals → SUPPORTER (×2 limits) - {refs_needed} referrals left"
            else:
                next_level_text_tr = "✅ DESTEKCI seviyesine ulaştınız!"
                next_level_text_en = "✅ You've reached SUPPORTER level!"
        elif membership == 'destekci':
            next_level_text_tr = "✅ Referral ile kazanılan maksimum seviyedesiniz!"
            next_level_text_en = "✅ You've reached maximum referral level!"
        else:
            next_level_text_tr = f"✅ Mevcut üyelik: {membership.upper()}"
            next_level_text_en = f"✅ Current membership: {membership.upper()}"

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="🎁 KOD KULLAN", callback_data="use_referral_code_prompt")],
            [InlineKeyboardButton(text="MAIN MENU", callback_data="go_back")]
        ])

        referral_text = (
            "🎁 REFERRAL SYSTEM | REFERANS SİSTEMİ\n\n"
            f"Your referral code | Senin referral kodun:\n{referral_code}\n\n"
            f"Your referral link | Senin referral linkin:\n{referral_link}\n\n"
            f"📊 Statistics | İstatistikler:\n"
            f"└ Total Referrals | Toplam Referanslar: {total_refs}\n"
            f"└ Current Membership | Mevcut Üyelik: {membership.upper()}\n\n"
            f"🎯 Rewards | Ödüller:\n"
            f"{next_level_text_en}\n"
            f"{next_level_text_tr}"
        )

        await message.answer(referral_text, reply_markup=keyboard)
        logger.info(f"User {chat_id} checked referral info")

    except Exception as e:
        logger.error(f"Error in referral command: {e}")
        await message.answer("An error occurred.")

@dp.callback_query(F.data == "generate_referral_link")
async def generate_referral_link_callback(callback: CallbackQuery):
    """Generate and send referral link"""
    try:
        chat_id = callback.from_user.id

        # Get user data
        user = await db.get_user(chat_id)
        if not user:
            await callback.answer("User not found. Please use /start first.", show_alert=True)
            return

        referral_code = user.get('referral_code', 'N/A')
        total_refs = user.get('total_referrals', 0)

        bot_username = (await bot.get_me()).username
        referral_link = f"https://t.me/{bot_username}?start={referral_code}"

        link_text = (
            "🔗 YOUR PERSONAL REFERRAL LINK\n"
            "🔗 SENİN KİŞİSEL DAVET LİNKİN\n\n"
            f"📎 Link:\n{referral_link}\n\n"
            f"📊 Current Referrals | Mevcut Referanslar: {total_refs}\n\n"
            "💡 Share this link with friends!\n"
            "💡 Bu linki arkadaşlarınla paylaş!\n\n"
            "✅ When someone joins using your link, you'll get notified!\n"
            "✅ Birisi senin linkinle katıldığında bildirim alacaksın!"
        )

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="🔙 BACK", callback_data="go_back")]
        ])

        await callback.message.edit_text(link_text, reply_markup=keyboard)
        await callback.answer()
        logger.info(f"User {chat_id} generated referral link")

    except Exception as e:
        logger.error(f"Error generating referral link: {e}")
        await callback.answer("An error occurred.", show_alert=True)

@dp.callback_query(F.data == "use_referral_code_prompt")
async def use_referral_code_prompt(callback: CallbackQuery):
    """Prompt user to enter referral code"""
    try:
        prompt_text = (
            "🎁 USE REFERRAL CODE | REFERRAL KOD KULLAN\n\n"
            "Please send the referral code in this format:\n"
            "Lütfen referral kodunu bu formatta gönderin:\n\n"
            "/referralcode AERT123456\n\n"
            "Example | Örnek:\n"
            "/referralcode AERT700168"
        )

        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="🔙 BACK", callback_data="go_back")]
        ])

        await callback.message.edit_text(prompt_text, reply_markup=keyboard)
        await callback.answer()

    except Exception as e:
        logger.error(f"Error in use referral code prompt: {e}")
        await callback.answer("An error occurred.", show_alert=True)

@dp.message(Command("referralcode"))
async def cmd_use_referral_code(message: Message):
    """Handle referral code usage"""
    try:
        chat_id = message.from_user.id

        # Check membership
        if not await check_membership_and_notify(message):
            return

        # Parse command
        command_text = message.text.strip()
        parts = command_text.split(maxsplit=1)

        if len(parts) < 2:
            await message.answer(
                "❌ Please provide a referral code.\n\n"
                "Usage: /referralcode AERT123456",
            )
            return

        referral_code = parts[1].strip().upper()

        # Validate format (AERT + 6 digits)
        if not referral_code.startswith('AERT') or len(referral_code) != 10:
            await message.answer(
                "❌ Invalid referral code format.\n\n"
                "Code should be: AERT + 6 digits\n"
                "Example: AERT229303"
            )
            return

        # Try to use the code
        success, message_text = await db.use_referral_code(chat_id, referral_code)

        if message_text == "quota_full":
            await message.answer(
                "❌ Referral Quota Full | Referral Kotası Dolu\n\n"
                "This user has already reached maximum referrals (5/5).\n"
                "Bu kullanıcı maksimum referral sayısına ulaştı (5/5).\n\n"
                "Please try a different referral code.\n"
                "Lütfen farklı bir referral kodu deneyin."
            )
            return

        if success:
            # Get updated referrer info (after database increment)
            referrer = await db.get_user_by_referral_code(referral_code)
            if referrer:
                # Get user info who used the code
                user_username = message.from_user.username or message.from_user.first_name
                user_mention = f"@{user_username}" if message.from_user.username else user_username

                # Send notification to referrer with UPDATED count
                try:
                    referrer_notification = (
                        f"🎉 New Referral | Yeni Referans!\n\n"
                        f"✅ {user_mention} used your referral code!\n"
                        f"✅ {user_mention} senin referral kodunu kullandı!\n\n"
                        f"Total referrals | Toplam referanslar: {referrer.get('total_referrals', 0)}"
                    )
                    await bot.send_message(referrer['chatid'], referrer_notification)
                except Exception as notif_error:
                    logger.error(f"Failed to send referral notification: {notif_error}")

                # Check and upgrade the referrer
                upgraded = await db.check_and_upgrade_referral(referrer['chatid'])
                if upgraded:
                    try:
                        await bot.send_message(
                            referrer['chatid'],
                            "🎉 Congratulations! You completed 5 referrals!\n"
                            "🎉 Tebrikler! 5 referans tamamladınız!\n\n"
                            "Upgraded to SUPPORTER membership.\n"
                            "DESTEKCI üyeliğine yükseltildiniz.\n\n"
                            "All limits doubled! (×2)\n"
                            "Tüm limitler 2 katına çıkarıldı! (×2)"
                        )
                    except:
                        pass

            await message.answer(f"✅ {message_text}")
            logger.info(f"User {chat_id} successfully used referral code {referral_code}")
        else:
            await message.answer(f"❌ {message_text}")

    except Exception as e:
        logger.error(f"Error in referralcode command: {e}")
        await message.answer("❌ An error occurred.")

@dp.message(Command("limittakip"))
async def cmd_limit_takip(message: Message):
    """Check next automatic limit reset time (admin only)"""
    try:
        if message.from_user.id not in ADMIN_IDS:
            return

        next_reset = db.read_next_reset_time()
        now = datetime.now()

        time_until_reset = next_reset - now
        hours_left = time_until_reset.total_seconds() / 3600

        # Format message
        if hours_left < 0:
            status = "⚠️ Reset is OVERDUE! Will reset within the next hour check."
        elif hours_left < 1:
            minutes_left = int(time_until_reset.total_seconds() / 60)
            status = f"⏰ Next reset in: {minutes_left} minutes"
        else:
            status = f"⏰ Next reset in: {hours_left:.1f} hours"

        response = (
            f"📊 LIMIT RESET TRACKER | LIMIT SIFIRLAMA TAKİP\n\n"
            f"{status}\n\n"
            f"📅 Next reset time | Sonraki sıfırlama:\n"
            f"{next_reset.strftime('%Y-%m-%d %H:%M:%S')}\n\n"
            f"ℹ️ Auto-reset applies to:\n"
            f"└ NORMAL users (1x limits)\n"
            f"└ DESTEKCI users (2x limits)\n\n"
            f"⚙️ Checker runs every hour\n"
            f"📝 Tracking file: limittakip.txt"
        )

        await message.answer(response)
        logger.info(f"Admin {message.from_user.id} checked limit reset time")

    except Exception as e:
        logger.error(f"Error in limittakip command: {e}")
        await message.answer("An error occurred.")

@dp.message(Command("resetlimits"))
async def cmd_reset_limits(message: Message):
    """Reset limits for normal, destekci, reklam and dost membership users"""
    try:
        if message.from_user.id not in ADMIN_IDS:
            return

        from config import (DEFAULT_AUTH_LIMIT, DEFAULT_PUAN_LIMIT,
                           DEFAULT_VBV_LIMIT, DEFAULT_IYZICO_LIMIT, DEFAULT_AUTH2_LIMIT,
                           DEFAULT_MOKA_LIMIT, DEFAULT_DISNEY_LIMIT, DEFAULT_STRIPE_LIMIT)

        # Reset NORMAL users
        reset_normal_query = """
            UPDATE users
            SET authlimit = %s, puanlimit = %s,
                vbvlimit = %s, iyzicolimit = %s, auth2limit = %s, mokalimit = %s,
                disneylimit = %s, stripelimit = %s
            WHERE membership_type = 'normal'
        """

        # Reset DESTEKCI users (×2 limits)
        reset_destekci_query = """
            UPDATE users
            SET authlimit = %s, puanlimit = %s,
                vbvlimit = %s, iyzicolimit = %s, auth2limit = %s, mokalimit = %s,
                disneylimit = %s, stripelimit = %s
            WHERE membership_type = 'destekci'
        """

        # Reset REKLAM users (×2 limits)
        reset_reklam_query = """
            UPDATE users
            SET authlimit = %s, puanlimit = %s,
                vbvlimit = %s, iyzicolimit = %s, auth2limit = %s, mokalimit = %s,
                disneylimit = %s, stripelimit = %s
            WHERE membership_type = 'reklam'
        """

        # Reset DOST users (×5 limits)
        reset_dost_query = """
            UPDATE users
            SET authlimit = %s, puanlimit = %s,
                vbvlimit = %s, iyzicolimit = %s, auth2limit = %s, mokalimit = %s,
                disneylimit = %s, stripelimit = %s
            WHERE membership_type = 'dost'
        """

        total_affected = 0

        async with db.pool.acquire() as conn:
            async with conn.cursor() as cursor:
                # Reset NORMAL
                await cursor.execute(
                    reset_normal_query,
                    (DEFAULT_AUTH_LIMIT, DEFAULT_PUAN_LIMIT,
                     DEFAULT_VBV_LIMIT, DEFAULT_IYZICO_LIMIT, DEFAULT_AUTH2_LIMIT, DEFAULT_MOKA_LIMIT,
                     DEFAULT_DISNEY_LIMIT, DEFAULT_STRIPE_LIMIT)
                )
                normal_count = cursor.rowcount
                total_affected += normal_count

                # Reset DESTEKCI (×2)
                await cursor.execute(
                    reset_destekci_query,
                    (DEFAULT_AUTH_LIMIT * 2, DEFAULT_PUAN_LIMIT * 2,
                     DEFAULT_VBV_LIMIT * 2, DEFAULT_IYZICO_LIMIT * 2, DEFAULT_AUTH2_LIMIT * 2,
                     DEFAULT_AUTH_LIMIT * 2, DEFAULT_DISNEY_LIMIT * 2, DEFAULT_STRIPE_LIMIT * 2)
                )
                destekci_count = cursor.rowcount
                total_affected += destekci_count

                # Reset REKLAM (×2)
                await cursor.execute(
                    reset_reklam_query,
                    (DEFAULT_AUTH_LIMIT * 2, DEFAULT_PUAN_LIMIT * 2,
                     DEFAULT_VBV_LIMIT * 2, DEFAULT_IYZICO_LIMIT * 2, DEFAULT_AUTH2_LIMIT * 2,
                     DEFAULT_AUTH_LIMIT * 2, DEFAULT_DISNEY_LIMIT * 2, DEFAULT_STRIPE_LIMIT * 2)
                )
                reklam_count = cursor.rowcount
                total_affected += reklam_count

                # Reset DOST (×5)
                await cursor.execute(
                    reset_dost_query,
                    (DEFAULT_AUTH_LIMIT * 5, DEFAULT_PUAN_LIMIT * 5,
                     DEFAULT_VBV_LIMIT * 5, DEFAULT_IYZICO_LIMIT * 5, DEFAULT_AUTH2_LIMIT * 5,
                     DEFAULT_AUTH_LIMIT * 5, DEFAULT_DISNEY_LIMIT * 5, DEFAULT_STRIPE_LIMIT * 5)
                )
                dost_count = cursor.rowcount
                total_affected += dost_count

        await message.answer(
            f"Limitler sifirlandi!\n\n"
            f"NORMAL: {normal_count} kullanici\n"
            f"DESTEKCI: {destekci_count} kullanici\n"
            f"REKLAM: {reklam_count} kullanici\n"
            f"DOST: {dost_count} kullanici\n"
            f"Toplam: {total_affected} kullanici\n\n"
            f"Yeni limitler:\n"
            f"NORMAL - Auth: {DEFAULT_AUTH_LIMIT}, VBV: {DEFAULT_VBV_LIMIT}\n"
            f"DESTEKCI/REKLAM - Auth: {DEFAULT_AUTH_LIMIT * 2}, VBV: {DEFAULT_VBV_LIMIT * 2}\n"
            f"DOST - Auth: {DEFAULT_AUTH_LIMIT * 5}, VBV: {DEFAULT_VBV_LIMIT * 5}"
        )

        logger.info(f"Admin {message.from_user.id} reset limits: {normal_count} normal, {destekci_count} destekci, {reklam_count} reklam, {dost_count} dost")

    except Exception as e:
        logger.error(f"Error in resetlimits command: {e}")
        await message.answer("An error occurred.")

@dp.message(Command("kodkullan"))
async def cmd_use_redeem_code(message: Message):
    """Use a redeem code (normal/reklam/dost users)"""
    try:
        # Check membership
        user = await db.get_user(message.from_user.id)
        if not user:
            await message.answer("❌ Please /start first")
            return

        membership = user.get('membership_type', 'normal')
        if membership not in ['normal', 'reklam', 'dost']:
            await message.answer("❌ Only normal, reklam, and dost members can use codes")
            return

        parts = message.text.strip().split()

        if len(parts) != 2:
            await message.answer(
                "❌ INVALID FORMAT\n\n"
                "Usage: /kodkullan <code_name>\n\n"
                "Example:\n"
                "/kodkullan YENI2024"
            )
            return

        code_name = parts[1]

        # Use the code
        success, result = await db.use_redeem_code(message.from_user.id, code_name)

        if not success:
            await message.answer(f"❌ {result}")
            return

        # Success - result is code_info
        code_info = result
        remaining = code_info['max_uses'] - code_info['used_count'] - 1

        await message.answer(
            f"✅ CODE REDEEMED SUCCESSFULLY!\n\n"
            f"Code: {code_info['code']}\n"
            f"Limit Type: {code_info['limit_type']}\n"
            f"Amount Added: +{code_info['amount']}\n\n"
            f"Your new {code_info['limit_type']} has been updated!"
        )

        # Send notification to SUPERADMIN
        for admin_id in SUPERADMIN_IDS:
            try:
                username = message.from_user.username if message.from_user.username else "NoUsername"
                user_id = message.from_user.id
                notification = (
                    f"🎁 KOD KULLANIMI\n\n"
                    f"User: @{username} ({user_id})\n"
                    f"Code: {code_info['code']}\n"
                    f"Limit: {code_info['limit_type']}\n"
                    f"Amount: +{code_info['amount']}\n\n"
                    f"Remaining uses: {remaining}/{code_info['max_uses']}"
                )
                await bot.send_message(admin_id, notification)
            except Exception as notify_error:
                logger.error(f"Failed to notify admin {admin_id}: {notify_error}")

        logger.info(f"User {message.from_user.id} used redeem code '{code_name}'")

    except Exception as e:
        logger.error(f"Error in kodkullan command: {e}")
        await message.answer("An error occurred.")

@dp.message(Command("kodolustur"))
async def cmd_create_redeem_code(message: Message):
    """Create a redeem code (SUPERADMIN only)"""
    try:
        if message.from_user.id not in SUPERADMIN_IDS:
            return

        parts = message.text.strip().split()

        if len(parts) != 5:
            await message.answer(
                "❌ INVALID FORMAT\n\n"
                "Usage: /kodolustur <code_name> <limit_type> <amount> <max_uses>\n\n"
                "Example:\n"
                "/kodolustur YENI2024 authlimit 100 5\n\n"
                "Valid limit types:\n"
                "• authlimit\n"
                "• puanlimit\n"
                "• vbvlimit\n"
                "• iyzicolimit\n"
                "• auth2limit\n"
                "• mokalimit\n"
                "• disneylimit\n"
                "• stripegenellimit\n"
                "• authnetlimit\n"
                "• shopifylimit\n\n"
                "Amount: 1-50000\n"
                "Max uses: 1-10"
            )
            return

        code_name = parts[1]
        limit_type = parts[2]

        # Validate limit type
        valid_limits = [
            'authlimit', 'puanlimit', 'vbvlimit', 'iyzicolimit',
            'auth2limit', 'mokalimit', 'disneylimit', 'stripegenellimit',
            'authnetlimit', 'shopifylimit'
        ]

        if limit_type not in valid_limits:
            await message.answer(f"❌ Invalid limit type: {limit_type}")
            return

        try:
            amount = int(parts[3])
            max_uses = int(parts[4])
        except ValueError:
            await message.answer("❌ Amount and max_uses must be numbers")
            return

        if not (1 <= amount <= 50000):
            await message.answer("❌ Amount must be between 1 and 50000")
            return

        if not (1 <= max_uses <= 10):
            await message.answer("❌ Max uses must be between 1 and 10")
            return

        # Create code
        success = await db.create_redeem_code(
            code_name, limit_type, amount, max_uses, message.from_user.id
        )

        if success:
            await message.answer(
                f"✅ Redeem code created successfully!\n\n"
                f"Code: {code_name}\n"
                f"Limit Type: {limit_type}\n"
                f"Amount: {amount}\n"
                f"Max Uses: {max_uses}\n\n"
                f"Users can redeem with: /kodkullan {code_name}"
            )
            logger.info(f"Admin {message.from_user.id} created redeem code '{code_name}'")
        else:
            await message.answer("❌ Failed to create code. Code name may already exist.")

    except Exception as e:
        logger.error(f"Error in kodolustur command: {e}")
        await message.answer("An error occurred.")

async def daily_limit_reset_scheduler():
    """Background task to check and reset limits every hour"""
    while True:
        try:
            await asyncio.sleep(3600)  # Check every hour

            # Read next reset time
            next_reset = db.read_next_reset_time()
            now = datetime.now()

            # Check if it's time to reset (if current time >= next reset time)
            if now >= next_reset:
                logger.info("Daily limit reset triggered")
                success, normal_count, destekci_count = await db.reset_daily_limits()

                if success:
                    # Send notification to log group
                    try:
                        notification = (
                            f"🔄 DAILY LIMIT RESET | GÜNLÜKLİMİT SIFIRLANDI\n\n"
                            f"✅ {normal_count} NORMAL users reset\n"
                            f"✅ {destekci_count} DESTEKCI users reset\n\n"
                            f"⏰ Next reset: {(now + timedelta(hours=24)).strftime('%Y-%m-%d %H:%M:%S')}"
                        )
                        await bot.send_message(LOG_GROUP_ID, notification)
                    except Exception as notify_error:
                        logger.error(f"Failed to send reset notification: {notify_error}")

                    logger.info(f"Daily limits reset: {normal_count} normal, {destekci_count} destekci users")
                else:
                    logger.error("Daily limit reset failed")
            else:
                time_until_reset = next_reset - now
                hours_left = time_until_reset.total_seconds() / 3600
                logger.info(f"Next limit reset in {hours_left:.1f} hours")

        except Exception as e:
            logger.error(f"Error in daily limit reset scheduler: {e}")
            await asyncio.sleep(3600)  # Continue checking even if error occurs

@dp.message(F.text)
async def handle_admin_input(message: Message):
    """Handle admin text input for various actions"""
    try:
        user_id = message.from_user.id

        # Check if this admin is waiting for input
        if user_id in admin_waiting_for:
            action = admin_waiting_for[user_id]

            # VBV Token manual entry
            if action == "vbv_token":
                if user_id not in SUPERADMIN_IDS:
                    return

                token = message.text.strip()

                # Validate token is not empty and has reasonable length
                if len(token) < 10:
                    await message.answer("❌ Token çok kısa! Lütfen geçerli bir token girin.")
                    return

                # Save token to file
                try:
                    base_dir = os.path.dirname(os.path.abspath(__file__))
                    token_file = os.path.join(base_dir, "apiler", "vbvapi", "vbvapitoken.txt")

                    with open(token_file, 'w') as f:
                        f.write(token)

                    # Clear waiting state
                    del admin_waiting_for[user_id]

                    keyboard = InlineKeyboardMarkup(inline_keyboard=[
                        [InlineKeyboardButton(text="GO BACK", callback_data="api_fix_menu")]
                    ])

                    await message.answer(
                        "✅ VBV TOKEN BAŞARIYLA KAYDEDILDI\n\n"
                        f"Token preview: {token[:50]}...\n\n"
                        f"Token dosyaya yazıldı: vbvapitoken.txt\n"
                        f"Token uzunluğu: {len(token)} karakter",
                        reply_markup=keyboard
                    )

                    logger.info(f"Admin {user_id} manually saved VBV token ({len(token)} chars)")

                except Exception as e:
                    await message.answer(f"❌ Token kaydedilirken hata oluştu: {str(e)}")
                    logger.error(f"Error saving VBV token: {e}")

                return

    except Exception as e:
        logger.error(f"Error in admin input handler: {e}")

async def main():
    try:
        logger.info("Starting bot...")

        await db.connect()
        await worker_manager.start()

        # Start daily limit reset scheduler in background
        asyncio.create_task(daily_limit_reset_scheduler())
        logger.info("Daily limit reset scheduler started")

        logger.info("Bot is running. Press Ctrl+C to stop.")
        await dp.start_polling(bot)

    except Exception as e:
        logger.error(f"Fatal error: {e}")

    finally:
        await worker_manager.stop()
        await db.close()
        await bot.session.close()
        logger.info("Bot stopped")

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        logger.info("Bot stopped by user")