import telebot
from telebot import types
import sqlite3
from datetime import datetime, timedelta
from collections import defaultdict
import threading

TOKEN = '8934556701:AAFaUcMz4bP2S_6tafS3ZaULcrkplpumXuM'
ADMINS = [8833140617]  # عددی

bot = telebot.TeleBot(TOKEN)

provinces = [
    'آذربایجان شرقی', 'آذربایجان غربی', 'اردبیل', 'اصفهان', 'البرز', 'ایلام', 'بوشهر', 'تهران', 'چهارمحال و بختیاری',
    'خراسان جنوبی', 'خراسان رضوی', 'خراسان شمالی', 'خوزستان', 'زنجان', 'سمنان', 'سیستان و بلوچستان', 'فارس', 'قزوین',
    'قم', 'کردستان', 'کرمان', 'کرمانشاه', 'کهگیلویه و بویراحمد', 'گلستان', 'گیلان', 'لرستان', 'مازندران',
    'مرکزی', 'هرمزگان', 'همدان', 'یزد'
]

waiting_general_male = []
waiting_general_female = []
waiting_prefer_male = []
waiting_prefer_female = []
waiting_by_province = defaultdict(list)

def init_db():
    conn = sqlite3.connect('anonchat.db')
    cur = conn.cursor()
    cur.execute('''CREATE TABLE IF NOT EXISTS users
                 (user_id INTEGER PRIMARY KEY,
                  username TEXT,
                  first_name TEXT,
                  last_name TEXT,
                  display_name TEXT,
                  join_date TEXT,
                  age INTEGER,
                  education TEXT,
                  location TEXT,
                  gender TEXT,
                  last_seen TEXT)''')

    cur.execute('''CREATE TABLE IF NOT EXISTS chats
                 (chat_id INTEGER PRIMARY KEY AUTOINCREMENT,
                  user1_id INTEGER,
                  user2_id INTEGER,
                  start_time TEXT,
                  end_time TEXT,
                  via_link INTEGER DEFAULT 0)''')

    cur.execute('''CREATE TABLE IF NOT EXISTS required_channels
                 (channel_id INTEGER PRIMARY KEY AUTOINCREMENT,
                  channel_username TEXT UNIQUE)''')

    cur.execute('''CREATE TABLE IF NOT EXISTS blocked_users
                 (user_id INTEGER PRIMARY KEY)''')
    conn.commit()
    conn.close()

init_db()

def get_db_connection():
    return sqlite3.connect('anonchat.db')

def add_user(user):
    conn = get_db_connection()
    cur = conn.cursor()
    cur.execute('''INSERT OR IGNORE INTO users
                   (user_id, username, first_name, last_name, display_name, join_date, age, education, location, gender, last_seen)
                   VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''',
                   (user.id, user.username, user.first_name, user.last_name,
                    user.first_name, datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                    None, None, None, None, None))
    conn.commit()
    conn.close()

def get_user(user_id):
    conn = get_db_connection()
    cur = conn.cursor()
    cur.execute('SELECT * FROM users WHERE user_id = ?', (user_id,))
    row = cur.fetchone()
    conn.close()
    return row

def update_last_seen(user_id):
    conn = get_db_connection()
    cur = conn.cursor()
    now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    cur.execute('UPDATE users SET last_seen = ? WHERE user_id = ?', (now, user_id))
    conn.commit()
    conn.close()

def update_age(user_id, age):
    conn = get_db_connection()
    cur = conn.cursor()
    cur.execute('UPDATE users SET age = ? WHERE user_id = ?', (age, user_id))
    conn.commit()
    conn.close()

def update_education(user_id, education):
    conn = get_db_connection()
    cur = conn.cursor()
    cur.execute('UPDATE users SET education = ? WHERE user_id = ?', (education, user_id))
    conn.commit()
    conn.close()

def update_location(user_id, location):
    conn = get_db_connection()
    cur = conn.cursor()
    cur.execute('UPDATE users SET location = ? WHERE user_id = ?', (location, user_id))
    conn.commit()
    conn.close()

def update_gender(user_id, gender):
    conn = get_db_connection()
    cur = conn.cursor()
    cur.execute('UPDATE users SET gender = ? WHERE user_id = ?', (gender, user_id))
    conn.commit()
    conn.close()

def get_user_gender(user_id):
    row = get_user(user_id)
    return row[9] if row else None

def is_blocked(user_id):
    conn = get_db_connection()
    cur = conn.cursor()
    cur.execute('SELECT * FROM blocked_users WHERE user_id = ?', (user_id,))
    row = cur.fetchone()
    conn.close()
    return row is not None

def block_user(user_id):
    conn = get_db_connection()
    cur = conn.cursor()
    cur.execute('INSERT OR IGNORE INTO blocked_users (user_id) VALUES (?)', (user_id,))
    conn.commit()
    conn.close()

def update_display_name(user_id, new_name):
    conn = get_db_connection()
    cur = conn.cursor()
    cur.execute('UPDATE users SET display_name = ? WHERE user_id = ?', (new_name, user_id))
    conn.commit()
    conn.close()

def is_user_in_chat(user_id):
    conn = get_db_connection()
    cur = conn.cursor()
    cur.execute('''SELECT * FROM chats
                   WHERE (user1_id = ? OR user2_id = ?) AND end_time IS NULL''', (user_id, user_id))
    row = cur.fetchone()
    conn.close()
    return row is not None

def start_chat(user1_id, user2_id, via_link=False):
    conn = get_db_connection()
    cur = conn.cursor()
    start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    cur.execute('''INSERT INTO chats
                   (user1_id, user2_id, start_time, via_link)
                   VALUES (?, ?, ?, ?)''',
                   (user1_id, user2_id, start_time, 1 if via_link else 0))
    conn.commit()
    chat_id = cur.lastrowid
    conn.close()
    return chat_id

def end_chat(chat_id):
    conn = get_db_connection()
    cur = conn.cursor()
    end_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    cur.execute('UPDATE chats SET end_time = ? WHERE chat_id = ?', (end_time, chat_id))
    conn.commit()
    conn.close()

def pair_users(u1, u2):
    chat_id = start_chat(u1, u2)
    active_pairs[u1] = (u2, chat_id)
    active_pairs[u2] = (u1, chat_id)
    bot.send_message(u1, "اتصال برقرار شد! شما با یک کاربر ناشناس چت می‌کنید.\nبرای پایان چت از /cancel استفاده کنید.")
    bot.send_message(u2, "اتصال برقرار شد! شما با یک کاربر ناشناس چت می‌کنید.\nبرای پایان چت از /cancel استفاده کنید.")

def remove_from_waiting(user_id):
    if user_id in waiting_general_male:
        waiting_general_male.remove(user_id)
    if user_id in waiting_general_female:
        waiting_general_female.remove(user_id)
    if user_id in waiting_prefer_male:
        waiting_prefer_male.remove(user_id)
    if user_id in waiting_prefer_female:
        waiting_prefer_female.remove(user_id)
    for key in list(waiting_by_province.keys()):
        if user_id in waiting_by_province[key]:
            waiting_by_province[key].remove(user_id)

def try_pairing(user_id, mode):
    remove_from_waiting(user_id)
    gender = get_user_gender(user_id)
    if not gender:
        return False  # Should not happen, but safety

    paired = False
    if mode == 'general':
        if gender == 'male':
            # Check for female in general or prefer_female
            if waiting_general_female:
                u2 = waiting_general_female.pop(0)
                pair_users(user_id, u2)
                paired = True
            elif waiting_prefer_female:
                u2 = waiting_prefer_female.pop(0)
                pair_users(user_id, u2)
                paired = True
            else:
                waiting_general_male.append(user_id)
        else:  # female
            if waiting_general_male:
                u1 = waiting_general_male.pop(0)
                pair_users(u1, user_id)
                paired = True
            elif waiting_prefer_male:
                u1 = waiting_prefer_male.pop(0)
                pair_users(u1, user_id)
                paired = True
            else:
                waiting_general_female.append(user_id)
    elif mode == 'boy':
        if gender == 'female':
            # Prefer male from general or prefer_male
            if waiting_general_male:
                u2 = waiting_general_male.pop(0)
                pair_users(user_id, u2)
                paired = True
            elif waiting_prefer_male:
                u2 = waiting_prefer_male.pop(0)
                pair_users(user_id, u2)
                paired = True
            else:
                waiting_prefer_male.append(user_id)  # Wait for male
        else:  # male, wait for female preferring boy
            waiting_prefer_male.append(user_id)
    elif mode == 'girl':
        if gender == 'male':
            # Prefer female from general or prefer_female
            if waiting_general_female:
                u2 = waiting_general_female.pop(0)
                pair_users(user_id, u2)
                paired = True
            elif waiting_prefer_female:
                u2 = waiting_prefer_female.pop(0)
                pair_users(user_id, u2)
                paired = True
            else:
                waiting_prefer_female.append(user_id)  # Wait for female
        else:  # female, wait for male preferring girl
            waiting_prefer_female.append(user_id)
    elif mode.startswith('province_'):
        province = mode[9:]
        waiting_by_province[province].append(user_id)
        if len(waiting_by_province[province]) >= 2:
            u1 = waiting_by_province[province].pop(0)
            u2 = waiting_by_province[province].pop(0)
            pair_users(u1, u2)
            paired = True

    # After adding or pairing, check all pending for possible pairs
    if not paired:
        check_pending_pairs()

    return paired

def check_pending_pairs():
    # Check general queues
    while waiting_general_male and waiting_general_female:
        u1 = waiting_general_male.pop(0)
        u2 = waiting_general_female.pop(0)
        pair_users(u1, u2)

    while waiting_prefer_male and waiting_prefer_female:
        u1 = waiting_prefer_male.pop(0)
        u2 = waiting_prefer_female.pop(0)
        pair_users(u1, u2)

    # Cross check prefer with general if possible
    while waiting_prefer_male and waiting_general_female:
        u1 = waiting_prefer_male.pop(0)
        u2 = waiting_general_female.pop(0)
        pair_users(u1, u2)

    while waiting_prefer_female and waiting_general_male:
        u1 = waiting_general_male.pop(0)
        u2 = waiting_prefer_female.pop(0)
        pair_users(u1, u2)

    # Check province queues
    for province in list(waiting_by_province.keys()):
        while len(waiting_by_province[province]) >= 2:
            u1 = waiting_by_province[province].pop(0)
            u2 = waiting_by_province[province].pop(0)
            pair_users(u1, u2)

def get_required_channels():
    conn = get_db_connection()
    cur = conn.cursor()
    cur.execute('SELECT channel_username FROM required_channels')
    rows = cur.fetchall()
    conn.close()
    return [row[0] for row in rows]

def add_required_channel(channel_username):
    conn = get_db_connection()
    cur = conn.cursor()
    try:
        cur.execute('INSERT INTO required_channels (channel_username) VALUES (?)', (channel_username,))
        conn.commit()
        conn.close()
        return True
    except sqlite3.IntegrityError:
        conn.close()
        return False

def remove_required_channel(channel_username):
    conn = get_db_connection()
    cur = conn.cursor()
    cur.execute('DELETE FROM required_channels WHERE channel_username = ?', (channel_username,))
    conn.commit()
    affected = cur.rowcount > 0
    conn.close()
    return affected

def check_channels_membership(user_id):
    required_channels = get_required_channels()
    if not required_channels:
        return True
    for channel in required_channels:
        try:
            member = bot.get_chat_member(channel, user_id)
            if member.status not in ['member', 'administrator', 'creator']:
                return False
        except:
            return False
    return True

def get_online_count():
    conn = get_db_connection()
    cur = conn.cursor()
    five_min_ago = (datetime.now() - timedelta(minutes=5)).strftime("%Y-%m-%d %H:%M:%S")
    cur.execute('SELECT COUNT(*) FROM users WHERE last_seen > ? AND last_seen IS NOT NULL', (five_min_ago,))
    count = cur.fetchone()[0]
    conn.close()
    return count

def get_bot_stats():
    conn = get_db_connection()
    cur = conn.cursor()
    cur.execute('SELECT COUNT(*) FROM users')
    total_users = cur.fetchone()[0]
    cur.execute('SELECT COUNT(*) FROM chats')
    total_chats = cur.fetchone()[0]
    cur.execute('SELECT COUNT(*) FROM chats WHERE end_time IS NULL')
    active_chats = cur.fetchone()[0]
    online = get_online_count()
    conn.close()
    return {
        'total_users': total_users,
        'total_chats': total_chats,
        'active_chats': active_chats,
        'online_users': online
    }

active_pairs = {}

def show_main_menu(chat_id, is_admin=False):
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)
    btn_start = types.KeyboardButton('شروع چت ناشناس 🎭')
    btn_province = types.KeyboardButton('چت با استان 📍')
    btn_boy = types.KeyboardButton('چت با پسر 👦')
    btn_girl = types.KeyboardButton('چت با دختر 👧')
    btn_online = types.KeyboardButton('کاربران آنلاین 👥')
    btn_change = types.KeyboardButton('تغییر نام ✏️')
    btn_link = types.KeyboardButton('لینک دعوت 🔗')
    markup.add(btn_start, btn_province)
    markup.add(btn_boy, btn_girl)
    markup.add(btn_online, btn_change)
    markup.add(btn_link)
    if is_admin:
        btn_admin = types.KeyboardButton('پنل مدیریت 👨‍💻')
        markup.add(btn_admin)
    bot.send_message(chat_id, "به ربات چت ناشناس خوش آمدید!", reply_markup=markup)

@bot.message_handler(commands=['start', 'cancel'])
def handle_start(message):
    user = message.from_user
    user_id = user.id
    add_user(user)
    update_last_seen(user_id)
    
    if is_blocked(user_id):
        bot.send_message(message.chat.id, "متاسفانه حساب شما مسدود شده است.")
        return
    
    if message.text == '/cancel':
        handle_cancel(message)
        return
    
    if len(message.text.split()) > 1:
        handle_private_link(message)
        return
    
    required_channels = get_required_channels()
    if required_channels and not check_channels_membership(user_id):
        show_channel_join_message(message.chat.id)
        return
    
    row = get_user(user_id)
    if row[6] is None:  # age
        start_questionnaire(user_id)
        return
    
    is_admin = user_id in ADMINS
    show_main_menu(message.chat.id, is_admin)

def start_questionnaire(user_id):
    update_last_seen(user_id)
    msg = bot.send_message(user_id, "چند سال دارید؟ (عدد)")
    bot.register_next_step_handler(msg, process_age, user_id)

def process_age(message, user_id):
    update_last_seen(user_id)
    try:
        age = int(message.text)
        update_age(user_id, age)
    except ValueError:
        bot.send_message(user_id, "لطفا یک عدد معتبر وارد کنید.")
        start_questionnaire(user_id)
        return
    msg = bot.send_message(user_id, "میزان تحصیلات شما چیست؟ (مثال: دیپلم، لیسانس)")
    bot.register_next_step_handler(msg, process_education, user_id)

def process_education(message, user_id):
    update_last_seen(user_id)
    education = message.text[:50]
    update_education(user_id, education)
    msg = bot.send_message(user_id, "از کدام استان هستید؟")
    bot.register_next_step_handler(msg, process_location, user_id)

def process_location(message, user_id):
    update_last_seen(user_id)
    location = message.text[:50]
    update_location(user_id, location)
    markup = types.InlineKeyboardMarkup(row_width=1)
    markup.add(types.InlineKeyboardButton("♂ مرد", callback_data=f"gender_male_{user_id}"))
    markup.add(types.InlineKeyboardButton("♀ زن", callback_data=f"gender_female_{user_id}"))
    bot.send_message(user_id, "جنسیت خود را انتخاب کنید:", reply_markup=markup)

@bot.callback_query_handler(func=lambda call: call.data.startswith('gender_'))
def process_gender(call):
    parts = call.data.split('_')
    gender = parts[1]
    user_id = int(parts[2])
    update_gender(user_id, gender)
    update_last_seen(user_id)
    bot.delete_message(call.message.chat.id, call.message.message_id)
    bot.answer_callback_query(call.id)
    show_main_menu(user_id, user_id in ADMINS)

def show_channel_join_message(chat_id):
    required_channels = get_required_channels()
    markup = types.InlineKeyboardMarkup()
    for channel in required_channels:
        markup.add(types.InlineKeyboardButton(
            text=f"عضویت در {channel}",
            url=f"https://t.me/{channel[1:]}"
        ))
    markup.add(types.InlineKeyboardButton(
        text="بررسی عضویت",
        callback_data="check_membership"
    ))
    bot.send_message(
        chat_id,
        "برای استفاده از ربات باید در کانال‌های زیر عضو شوید:",
        reply_markup=markup
    )

@bot.callback_query_handler(func=lambda call: call.data == "check_membership")
def check_membership(call):
    update_last_seen(call.from_user.id)
    if check_channels_membership(call.from_user.id):
        bot.delete_message(call.message.chat.id, call.message.message_id)
        show_main_menu(call.message.chat.id, call.from_user.id in ADMINS)
    else:
        bot.answer_callback_query(call.id, "شما هنوز در همه کانال‌ها عضو نشده‌اید!")

def handle_cancel(message):
    user_id = message.from_user.id
    update_last_seen(user_id)
    remove_from_waiting(user_id)
    conn = get_db_connection()
    cur = conn.cursor()
    cur.execute('''SELECT chat_id, user1_id, user2_id FROM chats
                   WHERE (user1_id = ? OR user2_id = ?) AND end_time IS NULL''',
                   (user_id, user_id))
    chat = cur.fetchone()
    conn.close()
    
    if chat:
        chat_id, user1_id, user2_id = chat
        partner_id = user1_id if user_id == user2_id else user2_id
        
        end_chat(chat_id)
        if user_id in active_pairs:
            del active_pairs[user_id]
        if partner_id in active_pairs:
            del active_pairs[partner_id]
        
        bot.send_message(user_id, "چت شما با موفقیت پایان یافت.")
        try:
            bot.send_message(partner_id, "کاربر مقابل چت را پایان داد.")
        except:
            pass
        
        show_main_menu(user_id, user_id in ADMINS)
        try:
            show_main_menu(partner_id, partner_id in ADMINS)
        except:
            pass
    else:
        bot.send_message(user_id, "شما در حال حاضر در چتی نیستید.")
        show_main_menu(user_id, user_id in ADMINS)

@bot.message_handler(func=lambda message: message.text == 'شروع چت ناشناس 🎭')
def start_anonymous_chat(message):
    user_id = message.from_user.id
    update_last_seen(user_id)
    
    if is_blocked(user_id):
        bot.send_message(user_id, "حساب شما مسدود است.")
        return
    
    if is_user_in_chat(user_id):
        bot.send_message(user_id, "شما هم اکنون در چت هستید! برای پایان چت از /cancel استفاده کنید.")
        return
    
    gender = get_user_gender(user_id)
    if not gender:
        bot.send_message(user_id, "لطفا پروفایل خود را کامل کنید.")
        return
    
    bot.send_message(user_id, "در حال جستجوی کاربر... لطفا صبر کنید.")
    
    try_pairing(user_id, 'general')

@bot.message_handler(func=lambda message: message.text == 'چت با پسر 👦')
def chat_with_boy(message):
    user_id = message.from_user.id
    update_last_seen(user_id)
    
    if is_blocked(user_id):
        bot.send_message(user_id, "حساب شما مسدود است.")
        return
    
    if is_user_in_chat(user_id):
        bot.send_message(user_id, "شما هم اکنون در چت هستید!")
        return
    
    gender = get_user_gender(user_id)
    if not gender:
        bot.send_message(user_id, "لطفا پروفایل خود را کامل کنید.")
        return
    
    bot.send_message(user_id, "در حال جستجوی شریک پسر... لطفا صبر کنید.")
    
    try_pairing(user_id, 'boy')

@bot.message_handler(func=lambda message: message.text == 'چت با دختر 👧')
def chat_with_girl(message):
    user_id = message.from_user.id
    update_last_seen(user_id)
    
    if is_blocked(user_id):
        bot.send_message(user_id, "حساب شما مسدود است.")
        return
    
    if is_user_in_chat(user_id):
        bot.send_message(user_id, "شما هم اکنون در چت هستید!")
        return
    
    gender = get_user_gender(user_id)
    if not gender:
        bot.send_message(user_id, "لطفا پروفایل خود را کامل کنید.")
        return
    
    bot.send_message(user_id, "در حال جستجوی شریک دختر... لطفا صبر کنید.")
    
    try_pairing(user_id, 'girl')

@bot.message_handler(func=lambda message: message.text == 'چت با استان 📍')
def start_province_chat(message):
    user_id = message.from_user.id
    update_last_seen(user_id)
    
    if is_blocked(user_id):
        bot.send_message(user_id, "حساب شما مسدود است.")
        return
    
    if is_user_in_chat(user_id):
        bot.send_message(user_id, "شما هم اکنون در چت هستید!")
        return
    
    markup = types.InlineKeyboardMarkup(row_width=2)
    for i in range(0, len(provinces), 2):
        row = []
        row.append(types.InlineKeyboardButton(provinces[i], callback_data=f"prov_{provinces[i]}"))
        if i + 1 < len(provinces):
            row.append(types.InlineKeyboardButton(provinces[i+1], callback_data=f"prov_{provinces[i+1]}"))
        markup.row(*row)
    bot.send_message(user_id, "استان مورد نظر را انتخاب کنید:", reply_markup=markup)

@bot.callback_query_handler(func=lambda call: call.data.startswith('prov_'))
def select_province(call):
    update_last_seen(call.from_user.id)
    province = call.data[4:]
    user_id = call.from_user.id
    bot.delete_message(call.message.chat.id, call.message.message_id)
    bot.answer_callback_query(call.id)
    bot.send_message(user_id, f"در حال جستجوی کاربر در {province}... لطفا صبر کنید.")
    try_pairing(user_id, f'province_{province}')

@bot.message_handler(func=lambda message: message.text == 'کاربران آنلاین 👥')
def show_online(message):
    user_id = message.from_user.id
    update_last_seen(user_id)
    conn = get_db_connection()
    cur = conn.cursor()
    five_min_ago = (datetime.now() - timedelta(minutes=5)).strftime("%Y-%m-%d %H:%M:%S")
    cur.execute('SELECT display_name FROM users WHERE last_seen > ? AND last_seen IS NOT NULL ORDER BY last_seen DESC LIMIT 20', (five_min_ago,))
    rows = cur.fetchall()
    conn.close()
    names = [row[0] or 'نامشخص' for row in rows]
    text = f"کاربران آنلاین ({len(names)} نفر):\n\n" + '\n'.join(names) if names else "در حال حاضر کاربری آنلاین نیست."
    bot.send_message(user_id, text)

@bot.message_handler(func=lambda message: message.text == 'تغییر نام ✏️')
def set_display_name(message):
    user_id = message.from_user.id
    update_last_seen(user_id)
    msg = bot.send_message(message.chat.id, "لطفا نام نمایشی جدید خود را وارد کنید (حداکثر 20 کاراکتر):")
    bot.register_next_step_handler(msg, process_display_name)

def process_display_name(message):
    user_id = message.from_user.id
    update_last_seen(user_id)
    new_name = message.text[:20]
    update_display_name(user_id, new_name)
    bot.send_message(message.chat.id, f"نام نمایشی شما به '{new_name}' تغییر یافت.")
    show_main_menu(message.chat.id, user_id in ADMINS)

@bot.message_handler(func=lambda message: message.text == 'لینک دعوت 🔗')
def generate_private_link(message):
    user_id = message.from_user.id
    update_last_seen(user_id)
    bot.send_message(
        message.chat.id,
        f"لینک دعوت شما:\nhttps://t.me/{bot.get_me().username}?start=private_{user_id}\n\n"
        "این لینک را برای دوستان خود ارسال کنید تا مستقیماً با شما چت کنند."
    )

@bot.message_handler(func=lambda message: message.text == 'پنل مدیریت 👨‍💻')
def admin_panel_button(message):
    if message.from_user.id in ADMINS:
        show_admin_panel(message.chat.id)
    else:
        bot.send_message(message.chat.id, "⚠️ شما دسترسی به این بخش را ندارید!")

def show_admin_panel(chat_id):
    markup = types.InlineKeyboardMarkup(row_width=2)
    markup.add(
        types.InlineKeyboardButton("📊 آمار ربات", callback_data="admin_stats"),
        types.InlineKeyboardButton("👥 لیست کاربران", callback_data="admin_users")
    )
    markup.add(
        types.InlineKeyboardButton("📢 ارسال همگانی", callback_data="admin_broadcast"),
        types.InlineKeyboardButton("📣 مدیریت کانال‌ها", callback_data="admin_channels")
    )
    markup.add(
        types.InlineKeyboardButton("🚫 مسدود کردن", callback_data="admin_block"),
        types.InlineKeyboardButton("📋 لیست مسدود", callback_data="admin_blocked")
    )
    markup.add(types.InlineKeyboardButton("🔙 بازگشت", callback_data="admin_back"))
    bot.send_message(chat_id, "🔐 پنل مدیریت:", reply_markup=markup)

def handle_private_link(message):
    user_id = message.from_user.id
    update_last_seen(user_id)
    if is_blocked(user_id):
        bot.send_message(user_id, "حساب شما مسدود است.")
        return
    try:
        link_code = message.text.split()[1]
        if link_code.startswith('private_'):
            target_user_id = int(link_code.split('_')[1])
            target_user = get_user(target_user_id)
            if not target_user:
                bot.send_message(user_id, "کاربر مورد نظر یافت نشد!")
                return
            if is_blocked(target_user_id):
                bot.send_message(user_id, "کاربر مورد نظر مسدود است.")
                return
            if is_user_in_chat(target_user_id):
                bot.send_message(user_id, "این کاربر هم اکنون در چت با شخص دیگری است.")
                return
            if user_id == target_user_id:
                bot.send_message(user_id, "شما نمی‌توانید با خودتان چت کنید!")
                return
            if get_user_gender(user_id) is None or get_user_gender(target_user_id) is None:
                bot.send_message(user_id, "یکی از پروفایل‌ها کامل نیست.")
                return
            chat_id = start_chat(user_id, target_user_id, via_link=True)
            active_pairs[user_id] = (target_user_id, chat_id)
            active_pairs[target_user_id] = (user_id, chat_id)
            user_row = get_user(user_id)
            target_row = target_user
            user_name = user_row[4] if user_row else 'نامشخص'
            target_name = target_row[4] if target_row else 'نامشخص'
            bot.send_message(
                user_id,
                f"شما هم اکنون با {target_name} چت می‌کنید.\nبرای پایان چت از /cancel استفاده کنید."
            )
            bot.send_message(
                target_user_id,
                f"یک کاربر با لینک دعوت شما وارد چت شد!\nشما هم اکنون با {user_name} چت می‌کنید.\nبرای پایان چت از /cancel استفاده کنید."
            )
    except Exception as e:
        print(f"Error in handle_private_link: {e}")
        bot.send_message(user_id, "خطایی در برقراری ارتباط رخ داد!")

@bot.message_handler(func=lambda message: True, content_types=['text', 'photo', 'document', 'sticker'])
def handle_messages(message):
    user_id = message.from_user.id
    update_last_seen(user_id)
    
    if user_id in active_pairs:
        partner_id, chat_id = active_pairs[user_id]
        
        conn = get_db_connection()
        cur = conn.cursor()
        cur.execute('SELECT via_link FROM chats WHERE chat_id = ?', (chat_id,))
        via_link = cur.fetchone()[0]
        conn.close()
        
        try:
            if message.content_type == 'text':
                if via_link:
                    user_row = get_user(user_id)
                    user_name = user_row[4] if user_row else 'نامشخص'
                    bot.send_message(partner_id, f"{user_name}: {message.text}")
                else:
                    bot.send_message(partner_id, message.text)
            elif message.content_type == 'photo':
                if via_link:
                    user_row = get_user(user_id)
                    user_name = user_row[4] if user_row else 'نامشخص'
                    caption = f"{user_name}: {message.caption}" if message.caption else None
                    bot.send_photo(partner_id, message.photo[-1].file_id, caption=caption)
                else:
                    bot.send_photo(partner_id, message.photo[-1].file_id, caption=message.caption)
            elif message.content_type == 'document':
                if via_link:
                    user_row = get_user(user_id)
                    user_name = user_row[4] if user_row else 'نامشخص'
                    caption = f"{user_name}: {message.caption}" if message.caption else None
                    bot.send_document(partner_id, message.document.file_id, caption=caption)
                else:
                    bot.send_document(partner_id, message.document.file_id, caption=message.caption)
            elif message.content_type == 'sticker':
                bot.send_sticker(partner_id, message.sticker.file_id)
        except:
            bot.send_message(user_id, "ارسال پیام ناموفق بود. ممکن است کاربر ربات را بلاک کرده باشد.")
            handle_cancel(message)
    else:
        bot.send_message(user_id, "از منوی اصلی استفاده کنید.")

@bot.callback_query_handler(func=lambda call: call.data.startswith('admin_'))
def handle_admin_actions(call):
    user_id = call.from_user.id
    if user_id not in ADMINS:
        return
    update_last_seen(user_id)
    
    action = call.data.split('_')[1]
    
    if action == 'stats':
        stats = get_bot_stats()
        text = (
            "📊 آمار ربات:\n\n"
            f"👥 کاربران کل: {stats['total_users']}\n"
            f"👀 کاربران آنلاین: {stats['online_users']}\n"
            f"💬 چت‌های کل: {stats['total_chats']}\n"
            f"🔛 چت‌های فعال: {stats['active_chats']}"
        )
        bot.edit_message_text(text, call.message.chat.id, call.message.message_id)
    
    elif action == 'users':
        conn = get_db_connection()
        cur = conn.cursor()
        cur.execute('SELECT user_id, display_name, join_date FROM users ORDER BY join_date DESC LIMIT 50')
        users = cur.fetchall()
        conn.close()
        text = "آخرین کاربران:\n\n"
        for user in users:
            text += f"🆔 {user[0]} - {user[1]} - {user[2]}\n"
        bot.edit_message_text(text, call.message.chat.id, call.message.message_id)
    
    elif action == 'broadcast':
        bot.answer_callback_query(call.id)
        msg = bot.send_message(user_id, "پیام همگانی خود را ارسال کنید:")
        bot.register_next_step_handler(msg, process_broadcast)
    
    elif action == 'channels':
        channels = get_required_channels()
        markup = types.InlineKeyboardMarkup()
        if channels:
            text = "کانال‌های اجباری فعلی:\n\n"
            for channel in channels:
                text += f"🔹 {channel}\n"
                markup.add(types.InlineKeyboardButton(
                    f"حذف {channel}",
                    callback_data=f"remove_channel_{channel}"
                ))
        else:
            text = "هیچ کانال اجباری تنظیم نشده است."
        markup.add(types.InlineKeyboardButton("➕ افزودن کانال", callback_data="add_channel"))
        markup.add(types.InlineKeyboardButton("🔙 بازگشت", callback_data="admin_back"))
        bot.edit_message_text(text, call.message.chat.id, call.message.message_id, reply_markup=markup)
    
    elif action == 'block':
        bot.answer_callback_query(call.id)
        msg = bot.send_message(user_id, "ID کاربر را برای مسدود کردن وارد کنید:")
        bot.register_next_step_handler(msg, process_block)
    
    elif action == 'blocked':
        conn = get_db_connection()
        cur = conn.cursor()
        cur.execute('''SELECT u.user_id, u.display_name FROM users u 
                          INNER JOIN blocked_users b ON u.user_id = b.user_id 
                          ORDER BY u.join_date DESC LIMIT 50''')
        rows = cur.fetchall()
        conn.close()
        text = "کاربران مسدود شده:\n\n"
        for row in rows:
            text += f"🆔 {row[0]} - {row[1] or 'نامشخص'}\n"
        if not rows:
            text += "هیچ کاربری مسدود نشده است."
        bot.edit_message_text(text, call.message.chat.id, call.message.message_id)

@bot.callback_query_handler(func=lambda call: call.data == 'admin_back')
def admin_back(call):
    update_last_seen(call.from_user.id)
    show_admin_panel(call.message.chat.id)

@bot.callback_query_handler(func=lambda call: call.data.startswith('remove_channel_'))
def remove_channel(call):
    update_last_seen(call.from_user.id)
    channel_username = call.data.split('_', 2)[2]
    if remove_required_channel(channel_username):
        bot.answer_callback_query(call.id, f"کانال {channel_username} حذف شد")
    else:
        bot.answer_callback_query(call.id, "خطا در حذف کانال")
    handle_admin_actions(call)

@bot.callback_query_handler(func=lambda call: call.data == 'add_channel')
def add_channel(call):
    update_last_seen(call.from_user.id)
    msg = bot.send_message(call.from_user.id, "آیدی کانال را وارد کنید (مثال: @channel_name):")
    bot.register_next_step_handler(msg, process_new_channel)

def process_new_channel(message):
    update_last_seen(message.from_user.id)
    if message.text.startswith('@'):
        if add_required_channel(message.text):
            bot.send_message(message.from_user.id, f"کانال {message.text} با موفقیت اضافه شد")
        else:
            bot.send_message(message.from_user.id, "این کانال قبلاً اضافه شده است")
    else:
        bot.send_message(message.from_user.id, "فرمت آیدی کانال نامعتبر است. باید با @ شروع شود")
    show_admin_panel(message.from_user.id)

def process_block(message):
    admin_id = message.from_user.id
    update_last_seen(admin_id)
    try:
        target_id = int(message.text)
        if target_id == admin_id:
            bot.send_message(admin_id, "نمی‌توانید خود را بلاک کنید!")
            show_admin_panel(admin_id)
            return
        block_user(target_id)
        bot.send_message(admin_id, f"کاربر {target_id} با موفقیت مسدود شد.")
        show_admin_panel(admin_id)
    except ValueError:
        bot.send_message(admin_id, "ID نامعتبر! لطفا عدد وارد کنید.")
        show_admin_panel(admin_id)

def process_broadcast(message):
    admin_id = message.from_user.id
    if admin_id not in ADMINS:
        return
    update_last_seen(admin_id)
    conn = get_db_connection()
    cur = conn.cursor()
    cur.execute('SELECT user_id FROM users')
    users = cur.fetchall()
    conn.close()
    success = 0
    fail = 0
    for user in users:
        try:
            if message.content_type == 'text':
                bot.send_message(user[0], message.text)
            elif message.content_type == 'photo':
                bot.send_photo(user[0], message.photo[-1].file_id, caption=message.caption)
            elif message.content_type == 'document':
                bot.send_document(user[0], message.document.file_id, caption=message.caption)
            success += 1
        except:
            fail += 1
    bot.send_message(
        admin_id,
        f"ارسال همگانی انجام شد:\n✅ موفق: {success}\n❌ ناموفق: {fail}"
    )
    show_admin_panel(admin_id)

# راه‌اندازی ربات
print("Bot is running...")
bot.polling()