import os
import json
import time
import telebot
import threading
from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton
from datetime import datetime, timedelta
from functools import wraps

TOKEN = "8055928224:AAEGFAt_cmmJQTKV5udNGTBfnUfn7th27uU"
DATA_FILE = "users.json"
ADMIN_CHANNEL_ID = -1003512076663

DEVELOPER_IDS = [6246579902, 7923164784]
CHANNEL_ID = "-1003006093715"
CHANNEL_USERNAME = "t.me/SourceKodo"
CHANNEL2_ID = "-1001762149483"
CHANNEL2_USERNAME = "t.me/K_K_Es"
DEVELOPER_URL = "https://t.me/Evan1_a  "

bot = telebot.TeleBot(TOKEN)

sending_states = {}
pending_hosting_details = {}
private_message_data = {}

def load_data():
    if not os.path.exists(DATA_FILE):
        return {}
    try:
        with open(DATA_FILE, "r", encoding="utf-8") as f:
            return json.load(f)
    except:
        return {}

def save_data(data):
    with open(DATA_FILE, "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

def ensure_user(data, user_id, name, username=None):
    uid = str(user_id)
    if uid not in data:
        data[uid] = {
            "points": 0,
            "referred_by": None,
            "name": name or "",
            "username": username or "",
            "received_hosting": False
        }
    else:
        data[uid]["name"] = name or data[uid].get("name", "")
        if username:
            data[uid]["username"] = username
        if "received_hosting" not in data[uid]:
            data[uid]["received_hosting"] = False
    return data

def developer_only(func):
    @wraps(func)
    def wrapped(message, *args, **kwargs):
        if message.from_user.id not in DEVELOPER_IDS:
            bot.reply_to(message, "⊱ *عذراً، هذا الأمر مخصص للمطورين فقط*.", parse_mode='Markdown')
            return
        return func(message, *args, **kwargs)
    return wrapped

def developer_callback_only(func):
    @wraps(func)
    def wrapped(call, *args, **kwargs):
        if call.from_user.id not in DEVELOPER_IDS:
            bot.answer_callback_query(call.id, "⊱ عذراً، هذا الأمر مخصص للمطورين فقط.", show_alert=True)
            return
        return func(call, *args, **kwargs)
    return wrapped

def _is_member_of(chat_identifier, user_id):
    try:
        member = bot.get_chat_member(chat_identifier, user_id)
        return member.status in ['member', 'administrator', 'creator']
    except Exception:
        return False

def subscription_status(user_id):
    status1 = _is_member_of(CHANNEL_ID, user_id)
    status2 = _is_member_of(CHANNEL2_ID, user_id)
    return {'ch1': status1, 'ch2': status2}

def check_subscription(user_id):
    s = subscription_status(user_id)
    return s['ch1'] and s['ch2']

def escape_underscore_for_markdown(text: str) -> str:
    if not isinstance(text, str):
        return text
    return text.replace('_', '\\_')

def subscription_required(func):
    @wraps(func)
    def wrapped(message, *args, **kwargs):
        if message.from_user.id in DEVELOPER_IDS:
            return func(message, *args, **kwargs)
        status = subscription_status(message.from_user.id)
        if not status['ch1']:
            channel_link = CHANNEL_USERNAME if CHANNEL_USERNAME.startswith("http") else f"https://{CHANNEL_USERNAME}"
            channel_link_md = escape_underscore_for_markdown(channel_link)
            bot.send_message(message.chat.id, f"⊱ *يجب عليك الاشتراك في القناة قبل استخدام البوت*:\n{channel_link_md}", parse_mode='Markdown')
            return
        if not status['ch2']:
            channel2_link = CHANNEL2_USERNAME if CHANNEL2_USERNAME.startswith("http") else f"https://{CHANNEL2_USERNAME}"
            channel2_link_md = escape_underscore_for_markdown(channel2_link)
            bot.send_message(message.chat.id, f"⊱ *مبروك! تم التحقق من اشتراكك في القناة الأولى.*\n⊱ *الخطوة التالية: الاشتراك في القناة الثانية قبل استخدام البوت*:\n{channel2_link_md}", parse_mode='Markdown')
            return
        return func(message, *args, **kwargs)
    return wrapped

def callback_subscription_required(func):
    @wraps(func)
    def wrapped(call, *args, **kwargs):
        if call.from_user.id in DEVELOPER_IDS:
            return func(call, *args, **kwargs)
        status = subscription_status(call.from_user.id)
        if not status['ch1']:
            channel_link = CHANNEL_USERNAME if CHANNEL_USERNAME.startswith("http") else f"https://{CHANNEL_USERNAME}"
            channel_link_md = escape_underscore_for_markdown(channel_link)
            bot.send_message(call.message.chat.id, f"⊱ *يجب عليك الاشتراك في القناة قبل استخدام البوت*:\n{channel_link_md}", parse_mode='Markdown')
            return
        if not status['ch2']:
            channel2_link = CHANNEL2_USERNAME if CHANNEL2_USERNAME.startswith("http") else f"https://{CHANNEL2_USERNAME}"
            channel2_link_md = escape_underscore_for_markdown(channel2_link)
            bot.send_message(call.message.chat.id, f"⊱ *مبروك! تم التحقق من اشتراكك في القناة الأولى.*\n⊱ *الخطوة التالية: الاشتراك في القناة الثانية قبل استخدام البوت*:\n{channel2_link_md}", parse_mode='Markdown')
            return
        return func(call, *args, **kwargs)
    return wrapped

def build_start_keyboard(user_id, points):
    kb = InlineKeyboardMarkup(row_width=2)
    btn_points = InlineKeyboardButton(text=f"نقاطي: {points}", callback_data="points")
    btn_amsterdam = InlineKeyboardButton(text="موقع امستردام 🇳🇱", callback_data="site_amsterdam")
    btn_australia = InlineKeyboardButton(text="موقع استراليا 🇦🇺", callback_data="site_australia")
    btn_america = InlineKeyboardButton(text="موقع امريكا 🇺🇸", callback_data="site_america")
    btn_referral = InlineKeyboardButton(text="انشاء رابط إحالة", callback_data="create_referral")
    kb.add(btn_points)
    kb.add(btn_amsterdam, btn_australia)
    kb.add(btn_america, btn_referral)
    return kb

def build_insufficient_keyboard():
    kb = InlineKeyboardMarkup(row_width=2)
    kb.add(InlineKeyboardButton(text="انشاء رابط احالة", callback_data="create_referral"),
           InlineKeyboardButton(text="رجوع الى القائمة", callback_data="back_to_menu"))
    return kb

def dev_menu_markup():
    markup = InlineKeyboardMarkup()
    markup.row(
        InlineKeyboardButton("الإحصائيات", callback_data='dev_stats'),
        InlineKeyboardButton("إذاعة بالخاص", callback_data='dev_broadcast_start')
    )
    markup.add(InlineKeyboardButton("المشتركين", callback_data='dev_subscribers'))
    markup.add(InlineKeyboardButton("رسالة خاصة", callback_data='dev_private_msg_start'))
    markup.add(InlineKeyboardButton("الرجوع للقائمة الرئيسية", callback_data='dev_menu'))
    return markup

def send_dev_menu(chat_id, message_id=None):
    text = "عزيزي هذه لوحة المطور الخاصة بك:"
    markup = dev_menu_markup()
    if message_id:
        try:
            bot.edit_message_text(text, chat_id, message_id, reply_markup=markup)
        except:
            bot.send_message(chat_id, text, reply_markup=markup)
    else:
        bot.send_message(chat_id, text, reply_markup=markup)

def get_subscribers_list():
    data = load_data()
    subscribers = []
    for user_id, user_data in data.items():
        if user_data.get("points", 0) != user_data.get("original_points", user_data.get("points", 0)):
            received = user_data.get("received_hosting", False)
            subscribers.append({
                'user_id': user_id,
                'name': user_data.get('name', 'مستخدم غير معروف'),
                'username': user_data.get('username', ''),
                'received': received
            })
    return subscribers

def build_subscribers_keyboard():
    subscribers = get_subscribers_list()
    markup = InlineKeyboardMarkup()
    for subscriber in subscribers:
        if subscriber.get('username'):
            display_label = f"@{subscriber['username']}"
        else:
            display_label = subscriber.get('name', subscriber['user_id'])
        status_emoji = "🟢" if subscriber['received'] else "🔴"
        status_text = "مستلم" if subscriber['received'] else "غير مستلم"
        btn_name = InlineKeyboardButton(display_label, callback_data=f"subscriber_name_{subscriber['user_id']}")
        btn_status = InlineKeyboardButton(f"{status_text} {status_emoji}", callback_data=f"subscriber_status_{subscriber['user_id']}")
        markup.row(btn_name, btn_status)
    markup.add(InlineKeyboardButton("الرجوع للقائمة الرئيسية", callback_data='dev_menu'))
    return markup

def build_subscriber_actions_keyboard(user_id):
    markup = InlineKeyboardMarkup()
    markup.add(InlineKeyboardButton("إرسال الاستضافة", callback_data=f"send_hosting_{user_id}"))
    markup.add(InlineKeyboardButton("رجوع الى القائمة", callback_data='dev_subscribers'))
    return markup

def countdown_and_send(chat_id, message_id, user_id, hosting_details):
    for i in range(5, 0, -1):
        if sending_states.get(chat_id, {}).get('cancelled', False):
            return
        markup = InlineKeyboardMarkup()
        markup.add(InlineKeyboardButton("الغاء العملية", callback_data=f"cancel_sending_{user_id}"))
        try:
            bot.edit_message_text(
                f"⊱ *جاري ارسال المعلومات يرجى الانتضار الوقت المتبقي*: {i}",
                chat_id,
                message_id,
                reply_markup=markup,
                parse_mode='Markdown'
            )
        except:
            pass
        time.sleep(1)
    if sending_states.get(chat_id, {}).get('cancelled', False):
        return
    try:
        bot.send_message(int(user_id), hosting_details)
        data = load_data()
        if user_id not in data:
            data[user_id] = {"points": 0, "referred_by": None, "name": "", "username": "", "received_hosting": True}
        else:
            data[user_id]['received_hosting'] = True
        save_data(data)
        try:
            bot.delete_message(chat_id, message_id)
        except:
            pass
        bot.send_message(chat_id, "⊱ *تم ارسال معلومات الاستضافة الى المستخدم المطلوب*.", parse_mode='Markdown')
    except Exception as e:
        bot.send_message(chat_id, f"⊱ *حدث خطأ في إرسال المعلومات*: {str(e)}")
    if chat_id in sending_states:
        del sending_states[chat_id]
    if chat_id in pending_hosting_details:
        del pending_hosting_details[chat_id]

def edit_or_replace_message(chat_id, message_id, text, reply_markup=None, parse_mode=None):
    try:
        bot.edit_message_text(text, chat_id, message_id, reply_markup=reply_markup, parse_mode=parse_mode)
        return None
    except:
        try:
            bot.delete_message(chat_id, message_id)
        except:
            pass
        return bot.send_message(chat_id, text, reply_markup=reply_markup, parse_mode=parse_mode)

@bot.message_handler(commands=['start'])
@subscription_required
def start(message):
    user_id = message.from_user.id
    name = message.from_user.first_name
    username = message.from_user.username
    
    data = load_data()
    data = ensure_user(data, user_id, name, username)
    
    args = message.text.split()
    if len(args) > 1:
        referrer_id = args[1]
        if referrer_id.isdigit() and int(referrer_id) != user_id:
            if data[str(user_id)]["referred_by"] is None:
                data[str(user_id)]["referred_by"] = int(referrer_id)
                if str(referrer_id) in data:
                    data[str(referrer_id)]["points"] += 10
                    try:
                        bot.send_message(int(referrer_id), f"⊱ *مبروك! لقد حصلت على 10 نقاط من إحالة جديدة* ({name}).", parse_mode='Markdown')
                    except:
                        pass
    
    save_data(data)
    points = data[str(user_id)]["points"]
    
    text = f"⊱ *مرحباً: {name}* 👋🏻.\n\n⊱ *نقدم لك بوت الاستضافة المجانية بالكامل مع دومين خاص بك ولوحة تحكم خاصة بك*.\n\n\n⊱ *كيفية عمل البوت* ⬇️:\n⊱ *يمكنك إنشاء رابط دعوة وارسال الرابط إلى 5 مستخدمين*.\n⊱ *عند ذلك يمكنك الحصول على 50 نقطه*.\n\n\n⊱ *يمكنك شراء أي استضافة من أي موقع، مع دومين خاص بك ولوحة تحكم خاصة بك بمجرد جمع النقا*."
    kb = build_start_keyboard(user_id, points)
    bot.send_message(message.chat.id, text, reply_markup=kb, parse_mode='Markdown')

@bot.message_handler(commands=['help'])
def help_command(message):
    help_text = "⊱ *للحصول على المساعدة، يرجى التواصل مع المطور*:\n" + DEVELOPER_URL
    bot.send_message(message.chat.id, help_text, parse_mode='Markdown')

@bot.message_handler(commands=['dev'])
@developer_only
def dev_panel(message):
    send_dev_menu(message.chat.id)

@bot.callback_query_handler(func=lambda call: True)
@callback_subscription_required
def callback_handler(call):
    uid = str(call.from_user.id)
    callback = call.data
    
    if callback.startswith('dev_'):
        if call.from_user.id not in DEVELOPER_IDS:
            bot.answer_callback_query(call.id, "عذراً، هذا الأمر للمطورين فقط.", show_alert=True)
            return
        
        if callback == 'dev_menu':
            send_dev_menu(call.message.chat.id, call.message.message_id)
            return
            
        if callback == 'dev_stats':
            data = load_data()
            total_users = len(data)
            text = f"إحصائيات البوت:\n\nعدد المشتركين الكلي: {total_users}"
            markup = InlineKeyboardMarkup()
            markup.add(InlineKeyboardButton("الرجوع للقائمة الرئيسية", callback_data='dev_menu'))
            bot.edit_message_text(text, call.message.chat.id, call.message.message_id, reply_markup=markup)
            return

        if callback == 'dev_broadcast_start':
            markup = InlineKeyboardMarkup()
            markup.add(InlineKeyboardButton("إلغاء", callback_data='dev_menu'))
            msg = bot.edit_message_text("أرسل الرسالة التي تريد إذاعتها لجميع المستخدمين:", call.message.chat.id, call.message.message_id, reply_markup=markup)
            bot.register_next_step_handler(msg, process_broadcast_message, msg.message_id)
            return

        if callback == 'dev_subscribers':
            markup = build_subscribers_keyboard()
            bot.edit_message_text("قائمة المشتركين الذين طلبوا استضافة:", call.message.chat.id, call.message.message_id, reply_markup=markup)
            return

        if callback == 'dev_private_msg_start':
            markup = InlineKeyboardMarkup()
            markup.add(InlineKeyboardButton("رجوع", callback_data='dev_menu'))
            bot.send_message(call.message.chat.id, "ارسل ايدي المستخدم لارسال الرسالة الخاصة له:", reply_markup=markup)
            bot.register_next_step_handler(call.message, process_private_msg_id)
            return

        if callback == 'confirm_private_msg':
            bot.answer_callback_query(call.id)
            user_id = private_message_data.get(call.from_user.id, {}).get('target_id')
            msg_text = private_message_data.get(call.from_user.id, {}).get('text')
            if user_id and msg_text:
                try:
                    bot.send_message(user_id, msg_text, parse_mode='Markdown')
                    bot.send_message(call.message.chat.id, "✅ تم إرسال الرسالة بنجاح إلى المستخدم.")
                    time.sleep(1)
                    send_dev_menu(call.message.chat.id)
                except Exception as e:
                    bot.send_message(call.message.chat.id, f"❌ فشل إرسال الرسالة: {str(e)}")
                    time.sleep(1)
                    send_dev_menu(call.message.chat.id)
                if call.from_user.id in private_message_data:
                    del private_message_data[call.from_user.id]
            return

    if callback.startswith('subscriber_name_'):
        if call.from_user.id not in DEVELOPER_IDS: return
        user_id = callback.replace('subscriber_name_', '')
        data = load_data()
        user_info = data.get(user_id, {})
        text = f"معلومات المستخدم:\nالاسم: {user_info.get('name')}\nاليوزر: @{user_info.get('username')}\nالايدي: {user_id}\nالنقاط: {user_info.get('points')}"
        markup = build_subscriber_actions_keyboard(user_id)
        bot.edit_message_text(text, call.message.chat.id, call.message.message_id, reply_markup=markup)
        return

    if callback.startswith('send_hosting_'):
        if call.from_user.id not in DEVELOPER_IDS: return
        user_id = callback.replace('send_hosting_', '')
        markup = InlineKeyboardMarkup()
        markup.add(InlineKeyboardButton("الغاء", callback_data='dev_subscribers'))
        msg = bot.edit_message_text("ارسل معلومات الاستضافة للمستخدم:", call.message.chat.id, call.message.message_id, reply_markup=markup)
        bot.register_next_step_handler(msg, process_hosting_details, user_id, msg.message_id)
        return

    if callback.startswith('cancel_sending_'):
        user_id = callback.replace('cancel_sending_', '')
        sending_states[call.message.chat.id] = {'cancelled': True}
        bot.edit_message_text("تم إلغاء عملية الإرسال.", call.message.chat.id, call.message.message_id)
        time.sleep(1)
        send_dev_menu(call.message.chat.id, call.message.message_id)
        return

    def handle_regular_callback(call):
        uid = str(call.from_user.id)
        callback = call.data
        
        if callback == "points":
            try:
                bot.answer_callback_query(call.id)
            except:
                pass
            data_local = load_data()
            p = data_local.get(uid, {}).get("points", 0)
            bot.send_message(call.message.chat.id, f"⊱ *عدد نقاطك الحالي هو*: {p}", parse_mode='Markdown')
            return

        if callback in ["site_amsterdam", "site_australia", "site_america"]:
            try:
                bot.answer_callback_query(call.id)
            except:
                pass
            site_map = {
                "site_amsterdam": "موقع امستردام",
                "site_australia": "موقع استراليا",
                "site_america": "موقع امريكا"
            }
            site_name = site_map.get(callback, "الموقع المختار")
            
            kb_back = InlineKeyboardMarkup()
            kb_back.add(InlineKeyboardButton(text="رجوع الى القائمة", callback_data="back_to_menu"))
            
            result_msg = edit_or_replace_message(call.message.chat.id, call.message.message_id, "⊱ *يتم التحقق من النقاط الحالية الخاصة بك*. . .", reply_markup=kb_back, parse_mode='Markdown')
            if result_msg:
                target_message_id = result_msg.message_id
            else:
                target_message_id = call.message.message_id
            
            time.sleep(2)
            
            data_local = load_data()
            user_points = int(data_local.get(uid, {}).get("points", 0))
            
            if user_points < 50:
                kb = build_insufficient_keyboard()
                try:
                    bot.edit_message_text(
                        "المعذرة، نقاطك الحالية غير كافية يجب ان تكون نقاطك 50 أو اكثر",
                        call.message.chat.id,
                        target_message_id,
                        reply_markup=kb
                    )
                except:
                    bot.send_message(call.message.chat.id,
                                     "المعذرة، نقاطك الحالية غير كافية يجب ان تكون نقاطك 50 أو اكثر",
                                     reply_markup=kb)
            else:
                kb = InlineKeyboardMarkup(row_width=2)
                kb.add(InlineKeyboardButton(text="تأكيد", callback_data=f"confirm|{callback}"),
                       InlineKeyboardButton(text="رجوع الى القائمة", callback_data="back_to_menu"))
                
                confirmation_text = f"⊱ *الموقع*: {site_name}\n⊱ *المعالج*: 1 CPU\n⊱ *الرام*: 1 GB\n\n⊱ *يرجى تأكيد شراء الاستضافة الخاصة بك*:"
                
                try:
                    bot.edit_message_text(
                        confirmation_text,
                        call.message.chat.id,
                        target_message_id,
                        reply_markup=kb,
                        parse_mode='Markdown'
                    )
                except:
                    bot.send_message(call.message.chat.id,
                                     confirmation_text,
                                     reply_markup=kb,
                                     parse_mode='Markdown')
            return

        if callback == "create_referral":
            try:
                bot.answer_callback_query(call.id)
            except:
                pass
            data_local = load_data()
            user_points = int(data_local.get(uid, {}).get("points", 0))
            
            try:
                me = bot.get_me()
                bot_username = me.username
            except:
                bot_username = None
            if bot_username:
                link = f"https://t.me/{bot_username}?start={call.from_user.id}"
            else:
                link = f"t.me/username?start={call.from_user.id}"
            
            kb_back = InlineKeyboardMarkup()
            kb_back.add(InlineKeyboardButton(text="رجوع الى القائمة", callback_data="back_to_menu"))
            
            referral_text = f"⊱ *عدد نقاطك الحالي*: {user_points}\n⊱ *شارك رابط الإحالة للحصول على نقاط*.\n⊱ *هذا هو رابط الإحالة الخاص بك*:\n{link}"
            
            result_msg = edit_or_replace_message(call.message.chat.id, call.message.message_id, referral_text, reply_markup=kb_back, parse_mode='Markdown')
            return

        if callback.startswith("confirm|"):
            try:
                bot.answer_callback_query(call.id)
            except:
                pass
            parts = callback.split("|", 1)
            site_key = parts[1] if len(parts) > 1 else "site_unknown"
            site_map = {
                "site_amsterdam": "موقع امستردام",
                "site_australia": "موقع استراليا",
                "site_america": "موقع امريكا"
            }
            site_name = site_map.get(site_key, "الموقع المختار")
            data_local = load_data()

            if uid not in data_local:
                uname = call.from_user.username or ""
                data_local[uid] = {"points": 0, "referred_by": None, "name": call.from_user.first_name or "", "username": uname, "received_hosting": False}

            current_points = int(data_local.get(uid, {}).get("points", 0))
            if "original_points" not in data_local[uid]:
                data_local[uid]["original_points"] = current_points
            remaining = current_points - 50
            if remaining < 0:
                remaining = 0
            data_local[uid]["points"] = remaining

            data_local[uid]["received_hosting"] = False

            save_data(data_local)
            
            try:
                bot.delete_message(call.message.chat.id, call.message.message_id)
            except:
                pass
                
            now = datetime.utcnow() + timedelta(hours=3)
            purchase_date = now.strftime("%d/%m/%Y")
            expiry = (now + timedelta(days=60)).strftime("%d/%m/%Y")
            
            purchase_text = f"⊱ *تم شراء الخدمة، اليك التفاصيل*:\n\n⊱ *الموقع*: {site_name}\n⊱ *الرام*: 1GB\n⊱ *الذاكرة*: 1CPU\n⊱ *تاريخ الشراء*: {purchase_date}\n⊱ *تاريخ الانتهاء*: {expiry}\n⊱ *المدة الكاملة للاستضافة: 60 يوم*\n\n⊱ *الرجاء الانتضار حتى يتم ارسال معلومات الاستضافة الخاصة بك*"
            
            bot.send_message(call.message.chat.id, purchase_text, parse_mode='Markdown')
            try:
                admin_username = data_local.get(uid, {}).get('username', '')
                username_display = f"@{admin_username}" if admin_username else "غير متوفر"
                bot.send_message(ADMIN_CHANNEL_ID,
                                 f"طلب شراء جديد:\n\nالمستخدم: {data_local.get(uid,{}).get('name','')}\nاسم المستخدم: {username_display}\nمعرف المستخدم: {uid}\nالموقع: {site_name}\nالرام: 1GB\nالذاكرة: 1CPU\nتاريخ الشراء: {purchase_date}\nتاريخ الانتهاء: {expiry}\nالمدة: 60 يوم")
            except:
                pass
            return

        if callback == "back_to_menu":
            try:
                bot.answer_callback_query(call.id)
            except:
                pass
            if call.from_user.id in DEVELOPER_IDS:
                chat_id = call.message.chat.id
                if chat_id in sending_states:
                    del sending_states[chat_id]
                if chat_id in pending_hosting_details:
                    del pending_hosting_details[chat_id]
            data_local = load_data()
            points = int(data_local.get(uid, {}).get("points", 0))
            name = data_local.get(uid, {}).get("name", call.from_user.first_name or "المستخدم")
            text = f"⊱ *مرحباً: {name}* 👋🏻.\n\n⊱ *نقدم لك بوت الاستضافة المجانية بالكامل مع دومين خاص بك ولوحة تحكم خاصة بك*.\n\n\n⊱ *كيفية عمل البوت* ⬇️:\n⊱ *يمكنك إنشاء رابط دعوة وارسال الرابط إلى 5 مستخدمين*.\n⊱ *عند ذلك يمكنك الحصول على 50 نقطه*.\n\n\n⊱ *يمكنك شراء أي استضافة من أي موقع، مع دومين خاص بك ولوحة تحكم خاصة بك بمجرد جمع النقا*."
            kb = build_start_keyboard(call.from_user.id, points)
            edit_or_replace_message(call.message.chat.id, call.message.message_id, text, reply_markup=kb, parse_mode='Markdown')
            return
    
    handle_regular_callback(call)

def process_private_msg_id(message):
    chat_id = message.chat.id
    if message.from_user.id not in DEVELOPER_IDS: return
    
    user_id_text = message.text
    if not user_id_text or not user_id_text.isdigit():
        markup = InlineKeyboardMarkup()
        markup.add(InlineKeyboardButton("رجوع", callback_data='dev_menu'))
        bot.send_message(chat_id, "❌ الايدي غير صحيح. يرجى إرسال ايدي رقمي فقط:", reply_markup=markup)
        bot.register_next_step_handler(message, process_private_msg_id)
        return

    private_message_data[message.from_user.id] = {'target_id': int(user_id_text)}
    markup = InlineKeyboardMarkup()
    markup.add(InlineKeyboardButton("رجوع", callback_data='dev_menu'))
    bot.send_message(chat_id, "ارسل الرسالة المطلوبة:", reply_markup=markup)
    bot.register_next_step_handler(message, process_private_msg_text)

def process_private_msg_text(message):
    chat_id = message.chat.id
    if message.from_user.id not in DEVELOPER_IDS: return
    
    msg_text = message.text
    if not msg_text:
        markup = InlineKeyboardMarkup()
        markup.add(InlineKeyboardButton("رجوع", callback_data='dev_menu'))
        bot.send_message(chat_id, "❌ يرجى إرسال نص للرسالة:", reply_markup=markup)
        bot.register_next_step_handler(message, process_private_msg_text)
        return

    private_message_data[message.from_user.id]['text'] = msg_text
    markup = InlineKeyboardMarkup()
    markup.add(InlineKeyboardButton("تأكيد", callback_data='confirm_private_msg'),
               InlineKeyboardButton("رجوع", callback_data='dev_menu'))
    bot.send_message(chat_id, "يرجى تأكيد ارسال الرسالة إلى المستخدم", reply_markup=markup)

def process_hosting_details(message, user_id, message_id_to_edit):
    chat_id = message.chat.id
    if message.from_user.id not in DEVELOPER_IDS: return
    hosting_details = message.text
    if not hosting_details:
        bot.send_message(chat_id, "لم يتم إرسال تفاصيل. تم إلغاء العملية.")
        return
    pending_hosting_details[chat_id] = hosting_details
    sending_states[chat_id] = {'cancelled': False}
    threading.Thread(target=countdown_and_send, args=(chat_id, message_id_to_edit, user_id, hosting_details)).start()

def process_broadcast_message(message, message_id_to_edit):
    chat_id = message.chat.id
    if message.from_user.id not in DEVELOPER_IDS:
        bot.send_message(chat_id, "تم إلغاء العملية. هذا الأمر مخصص للمطورين فقط.")
        return
    broadcast_text = message.text
    if not broadcast_text:
        markup = InlineKeyboardMarkup()
        markup.add(InlineKeyboardButton("الرجوع للقائمة الرئيسية", callback_data='dev_menu'))
        try:
            bot.edit_message_text("لم يتم إرسال نص. تم إلغاء الإذاعة.", chat_id, message_id_to_edit, reply_markup=markup)
        except:
            bot.send_message(chat_id, "لم يتم إرسال نص. تم إلغاء الإذاعة.", reply_markup=markup)
        return
    data = load_data()
    total_users = len(data)
    sent_count = 0
    failed_count = 0
    try:
        bot.edit_message_text(f"بدء عملية الإذاعة لـ {total_users} مستخدم...", chat_id, message_id_to_edit)
    except:
        pass
    for user_id_str, user_info in data.items():
        try:
            bot.send_message(int(user_id_str), broadcast_text, parse_mode='Markdown')
            sent_count += 1
            time.sleep(1)
        except Exception:
            failed_count += 1
    result_text = f"**انتهت عملية الإذاعة**:\n\nتم الإرسال بنجاح إلى: *{sent_count}* مستخدم.\nفشل الإرسال إلى: *{failed_count}* مستخدم."
    markup = InlineKeyboardMarkup()
    markup.add(InlineKeyboardButton("الرجوع للقائمة الرئيسية", callback_data='dev_menu'))
    try:
        bot.edit_message_text(result_text, chat_id, message_id_to_edit, reply_markup=markup, parse_mode='Markdown')
    except:
        bot.send_message(chat_id, result_text, reply_markup=markup, parse_mode='Markdown')

if __name__ == "__main__":
    print("starting bot...")
    bot.set_my_commands(
        [
            telebot.types.BotCommand("start", "Start Chat"),
            telebot.types.BotCommand("help", "Request assistance"),
            telebot.types.BotCommand("dev", "Developer Panel"),
        ]
    )
    bot.delete_webhook()
    bot.polling(none_stop=True)
