import sqlite3
import datetime
import urllib.request
import urllib.parse
import json
import time

TOKEN = "772739384:XxuaQcxiltrMWu5pKvrI_6Nfg9YCWnloNtE"
BASE_URL = f"https://tapi.bale.ai/bot{TOKEN}/"
ADMIN_ID = 1119443231
CARD_NUMBER = "6219861957342016"
CARD_HOLDER = "ابوالفضل فنایی"
REQUIRED_CHANNEL = "@calldyoty"

def api_request(method, payload):
    url = BASE_URL + method
    data = json.dumps(payload).encode('utf-8')
    req = urllib.request.Request(url, data=data, headers={'Content-Type': 'application/json'})
    try:
        with urllib.request.urlopen(req) as response:
            return json.loads(response.read().decode('utf-8'))
    except Exception as e:
        print(f"Error in {method}: {e}")
        return None

def send_message(chat_id, text, reply_markup=None):
    payload = {"chat_id": chat_id, "text": text, "parse_mode": "Markdown"}
    if reply_markup:
        payload["reply_markup"] = reply_markup
    return api_request("sendMessage", payload)

def check_membership(user_id):
    if user_id == ADMIN_ID:
        return True
    res = api_request("getChatMember", {"chat_id": REQUIRED_CHANNEL, "user_id": user_id})
    if res and res.get("ok") and res.get("result"):
        status = res["result"].get("status")
        if status in ["creator", "administrator", "member"]:
            return True
    return False

def init_db():
    conn = sqlite3.connect("call_of_duty_bot.db")
    cursor = conn.cursor()
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS users (
        user_id INTEGER PRIMARY KEY,
        full_name TEXT,
        points INTEGER DEFAULT 0,
        tokens INTEGER DEFAULT 0,
        weekly_chances INTEGER DEFAULT 0,
        monthly_chances INTEGER DEFAULT 0,
        is_vip INTEGER DEFAULT 0,
        vip_expire_date TEXT,
        lang TEXT DEFAULT 'fa',
        joined_date TEXT,
        is_banned INTEGER DEFAULT 0
    )
    ''')
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS accounts (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        account_data TEXT,
        is_claimed INTEGER DEFAULT 0,
        claimed_by INTEGER DEFAULT NULL,
        added_date TEXT
    )
    ''')
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS news (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        title TEXT,
        content TEXT,
        media_type TEXT,
        media_id TEXT,
        created_at TEXT
    )
    ''')
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS settings (
        key TEXT PRIMARY KEY,
        value TEXT
    )
    ''')
    default_settings = [
        ('weekly_chance_price', '50000'),
        ('monthly_chance_price', '30000'),
        ('token_value', '100'),
        ('daily_mining_rate', '5'),
        ('weekly_jackpot', '0'),
        ('monthly_jackpot', '0')
    ]
    for key, val in default_settings:
        cursor.execute("INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)", (key, val))
    conn.commit()
    conn.close()

init_db()

def get_main_keyboard(user_id):
    keyboard = [
        [{"text": "🎮 دریافت اکانت رایگان"}, {"text": "📰 اخبار"}],
        [{"text": "🎲 گردونه هفتگی"}, {"text": "🎲 گردونه ماهانه"}],
        [{"text": "💎 سیستم VIP"}, {"text": "🪙 سیستم توکن (CDT)"}],
        [{"text": "🏆 رنکینگ کاربران"}, {"text": "🌍 تنظیمات زبان"}],
        [{"text": "ℹ️ اطلاعات کاربری"}]
    ]
    if user_id == ADMIN_ID:
        keyboard.append([{"text": "⚙️ پنل مدیریت"}])
    return {"keyboard": keyboard, "resize_keyboard": True}

def get_admin_keyboard():
    keyboard = [
        [{"text": "📊 داشبورد مدیریتی"}, {"text": "➕ افزودن اکانت رایگان"}],
        [{"text": "📰 افزودن خبر"}, {"text": "📢 پیام همگانی"}],
        [{"text": "🏆 اجرای گردونه"}, {"text": "📊 آمار کامل"}],
        [{"text": "📈 گزارش پیشرفته"}, {"text": "💰 سیستم مالی"}],
        [{"text": "👥 مدیریت کاربران"}, {"text": "🎯 سیستم ماموریت‌ها"}],
        [{"text": "📢 اطلاع‌رسانی هوشمند"}, {"text": "🔄 سیستم بکاپ"}],
        [{"text": "📈 تحلیل داده‌ها"}, {"text": "🎮 رویدادهای ویژه"}],
        [{"text": "🏆 جایزه‌های ویژه"}, {"text": "🔒 مدیریت امنیت"}],
        [{"text": "🔗 سیستم همکاری"}, {"text": "📝 نظرسنجی"}],
        [{"text": "🎨 شخصی‌سازی"}, {"text": "📚 سیستم آموزش"}],
        [{"text": "⚡ خودکارسازی"}, {"text": "🔧 تنظیمات پیشرفته"}],
        [{"text": "📋 تاریخچه پیام‌ها"}, {"text": "🏠 منوی اصلی"}]
    ]
    return {"keyboard": keyboard, "resize_keyboard": True}

def get_join_keyboard():
    inline_keyboard = [
        [{"text": "📢 عضویت در کانال سازنده", "url": "https://ble.ir/calldyoty"}],
        [{"text": "✅ بررسی عضویت", "callback_data": "check_join"}]
    ]
    return {"inline_keyboard": inline_keyboard}

def process_message(message):
    chat_id = message["chat"]["id"]
    user_id = message["from"]["id"]
    text = message.get("text", "")
    first_name = message["from"].get("first_name", "کاربر")

    if not check_membership(user_id):
        join_text = f"❌ **دسترسی محدود شد!**\n\nجهت استفاده از خدمات ربات، باید ابتدا در کانال سازنده عضو شوید:\n{REQUIRED_CHANNEL}\n\n⚠️ **پس از عضویت، دکمه «✅ بررسی عضویت» را بزنید.**"
        send_message(chat_id, join_text, get_join_keyboard())
        return

    conn = sqlite3.connect("call_of_duty_bot.db")
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM users WHERE user_id = ?", (user_id,))
    user = cursor.fetchone()

    if not user:
        now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        cursor.execute("INSERT INTO users (user_id, full_name, joined_date) VALUES (?, ?, ?)",
                       (user_id, first_name, now))
        conn.commit()

    if text == "/start":
        send_message(
            chat_id,
            "🎮 به ربات Call of Duty خوش آمدید!\nلطفاً از منوی زیر بخش مورد نظر خود را انتخاب کنید:",
            get_main_keyboard(user_id)
        )

    elif text == "🎮 دریافت اکانت رایگان":
        cursor.execute("SELECT * FROM accounts WHERE is_claimed = 0 LIMIT 1")
        acc = cursor.fetchone()
        if acc:
            acc_id, acc_data, _, _, _ = acc
            cursor.execute("UPDATE accounts SET is_claimed = 1, claimed_by = ? WHERE id = ?", (user_id, acc_id))
            cursor.execute("UPDATE users SET points = points + 10 WHERE user_id = ?", (user_id,))
            conn.commit()
            send_message(chat_id, f"🎁 اکانت رایگان شما:\n`{acc_data}`\n\n🎉 +۱۰ امتیاز به حساب شما اضافه شد!")
        else:
            send_message(chat_id, "❌ در حال حاضر اکانت رایگانی موجود نیست. لطفا بعداً تلاش کنید.")

    elif text == "📰 اخبار":
        cursor.execute("SELECT title, content, created_at FROM news ORDER BY id DESC LIMIT 10")
        news_list = cursor.fetchall()
        if news_list:
            res = "📰 **آخرین اخبار کالاف دیوتی:**\n\n"
            for n in news_list:
                res += f"🔹 **{n[0]}** ({n[2]})\n{n[1]}\n-------------------\n"
            send_message(chat_id, res)
        else:
            send_message(chat_id, "📰 هیچ خبری ثبت نشده است.")

    elif text == "🎲 گردونه هفتگی":
        cursor.execute("SELECT value FROM settings WHERE key = 'weekly_chance_price'")
        price = cursor.fetchone()[0]
        msg = (
            "🎲 **گردونه هفتگی**\n\n"
            f"💰 قیمت هر شانس: {price} تومان\n"
            "🎫 حداکثر شانس: ۲۰ عدد\n"
            "🎯 جایزه: اکانت پریمیوم + ۵۰,۰۰۰ تومان\n"
            "💎 تخفیف VIP: ۲۰٪\n"
            "📅 زمان قرعه‌کشی: هر جمعه\n\n"
            f"💳 جهت خرید، مبلغ را به کارت زیر واریز کرده و فیش را ارسال کنید:\n`{CARD_NUMBER}`\nبه نام: {CARD_HOLDER}"
        )
        send_message(chat_id, msg)

    elif text == "🎲 گردونه ماهانه":
        cursor.execute("SELECT value FROM settings WHERE key = 'monthly_chance_price'")
        price = cursor.fetchone()[0]
        msg = (
            "🎲 **گردونه ماهانه**\n\n"
            f"💰 قیمت هر شانس: {price} تومان\n"
            "🎫 حداکثر شانس: ۲۰ عدد\n"
            "🎯 جایزه: اکانت پریمیوم + ۲۰۰,۰۰۰ تومان\n"
            "💎 تخفیف VIP: ۲۰٪\n"
            "📅 زمان قرعه‌کشی: ۲۸ هر ماه\n\n"
            f"💳 جهت خرید، مبلغ را به کارت زیر واریز کرده و فیش را ارسال کنید:\n`{CARD_NUMBER}`\nبه نام: {CARD_HOLDER}"
        )
        send_message(chat_id, msg)

    elif text == "💎 سیستم VIP":
        msg = (
            "💎 **اشتراک ویژه (VIP)**\n\n"
            "پلن‌ها:\n"
            "1️⃣ ماهانه: ۱۰۰,۰۰۰ تومان\n"
            "2️⃣ سه‌ماهه: ۲۵۰,۰۰۰ تومان (۱۰٪ تخفیف)\n"
            "3️⃣ شش‌ماهه: ۴۵۰,۰۰۰ تومان (۲۰٪ تخفیف)\n\n"
            "مزایا:\n"
            "✅ تخفیف ۲۰٪ در تمام خریدها\n"
            "✅ اکانت رایگان هر ماه\n"
            "✅ اخبار اختصاصی\n"
            "✅ بدج اختصاصی 👑 کنار نام"
        )
        send_message(chat_id, msg)

    elif text == "🪙 سیستم توکن (CDT)":
        cursor.execute("SELECT tokens FROM users WHERE user_id = ?", (user_id,))
        user_tokens = cursor.fetchone()[0]
        msg = (
            f"🪙 **کیف پول توکن (CDT)**\n\n"
            f"💰 موجودی شما: {user_tokens} CDT\n"
            "💰 ارزش هر توکن: ۱۰۰ تومان\n"
            "⛏️ ماینینگ روزانه: ۵ توکن\n\n"
            "✨ راه‌های کسب توکن:\n"
            "• ماینینگ روزانه\n"
            "• شرکت در چالش‌ها"
        )
        send_message(chat_id, msg)

    elif text == "🏆 رنکینگ کاربران":
        cursor.execute("SELECT full_name, points FROM users ORDER BY points DESC LIMIT 10")
        top_users = cursor.fetchall()
        res = "🏆 **۱۰ کاربر برتر ربات:**\n\n"
        ranks = ["🥇", "🥈", "🥉", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"]
        for idx, u in enumerate(top_users):
            res += f"{ranks[idx]} {u[0]} — {u[1]} امتیاز\n"
        send_message(chat_id, res)

    elif text == "🌍 تنظیمات زبان":
        send_message(chat_id, "🌍 **انتخاب زبان / Select Language:**\n\n🇮🇷 فارسی\n🇬🇧 English\n🇸🇦 العربية")

    elif text == "ℹ️ اطلاعات کاربری":
        cursor.execute("SELECT full_name, points, tokens, weekly_chances, monthly_chances, is_vip, joined_date FROM users WHERE user_id = ?", (user_id,))
        u = cursor.fetchone()
        vip_status = "👑 VIP" if u[5] == 1 else "کاربر عادی"
        msg = (
            f"ℹ️ **اطلاعات کاربری شما:**\n\n"
            f"🆔 آیدی: `{user_id}`\n"
            f"👤 نام: {u[0]}\n"
            f"💎 وضعیت VIP: {vip_status}\n"
            f"⭐ امتیاز کل: {u[1]}\n"
            f"🪙 تعداد توکن‌ها: {u[2]}\n"
            f"🎫 شانس هفتگی: {u[3]}\n"
            f"🎫 شانس ماهانه: {u[4]}\n"
            f"📅 تاریخ عضویت: {u[6]}"
        )
        send_message(chat_id, msg)

    elif text == "⚙️ پنل مدیریت" and user_id == ADMIN_ID:
        send_message(chat_id, "⚙️ به پنل مدیریت خوش آمدید. لطفا یک بخش را انتخاب کنید:", get_admin_keyboard())

    elif text == "🏠 منوی اصلی":
        send_message(chat_id, "🏠 به منوی اصلی بازگشتید.", get_main_keyboard(user_id))

    elif user_id == ADMIN_ID:
        if text == "📊 داشبورد مدیریتی":
            cursor.execute("SELECT COUNT(*) FROM users")
            total_u = cursor.fetchone()[0]
            cursor.execute("SELECT COUNT(*) FROM users WHERE is_vip = 1")
            vip_u = cursor.fetchone()[0]
            send_message(chat_id, f"📊 **داشبورد مدیریتی**\n\n👥 کل کاربران: {total_u}\n💎 کاربران VIP: {vip_u}\n💰 درآمد امروز: ۰ تومان")

        elif text == "➕ افزودن اکانت رایگان":
            send_message(chat_id, "📝 جهت افزودن اکانت، فرمت را به این شکل ارسال کنید:\n`account: email:password`")

        elif text.startswith("account:"):
            acc_data = text.replace("account:", "").strip()
            now = datetime.datetime.now().strftime("%Y-%m-%d")
            cursor.execute("INSERT INTO accounts (account_data, added_date) VALUES (?, ?)", (acc_data, now))
            conn.commit()
            send_message(chat_id, "✅ اکانت جدید با موفقیت اضافه شد.")

        elif text == "📰 افزودن خبر":
            send_message(chat_id, "📝 جهت افزودن خبر، فرمت را به این شکل ارسال کنید:\n`news: عنوان|متن خبر`")

        elif text.startswith("news:"):
            raw = text.replace("news:", "").strip()
            if "|" in raw:
                title, content = raw.split("|", 1)
                now = datetime.datetime.now().strftime("%Y-%m-%d")
                cursor.execute("INSERT INTO news (title, content, created_at) VALUES (?, ?, ?)", (title, content, now))
                conn.commit()
                send_message(chat_id, "✅ خبر جدید با موفقیت ثبت شد.")

        elif text == "📢 پیام همگانی":
            send_message(chat_id, "📝 جهت ارسال پیام همگانی، متن را به این شکل بفرستید:\n`broadcast: متن پیام`")

        elif text.startswith("broadcast:"):
            bc_msg = text.replace("broadcast:", "").strip()
            cursor.execute("SELECT user_id FROM users")
            all_users = cursor.fetchall()
            count = 0
            for u in all_users:
                if send_message(u[0], f"📢 **پیام همگانی:**\n\n{bc_msg}"):
                    count += 1
            send_message(chat_id, f"✅ پیام همگانی با موفقیت به {count} کاربر ارسال شد.")

        elif text == "🏆 اجرای گردونه":
            send_message(chat_id, "🏆 قرعه‌کشی اجرا شد و برندگان مشخص شدند.")

        elif text == "📊 آمار کامل":
            cursor.execute("SELECT COUNT(*) FROM users")
            total_u = cursor.fetchone()[0]
            cursor.execute("SELECT COUNT(*) FROM accounts")
            total_acc = cursor.fetchone()[0]
            send_message(chat_id, f"📊 **آمار کامل ربات:**\n\n👥 کل کاربران: {total_u}\n🎮 تعداد کل اکانت‌ها: {total_acc}")

        elif text == "📈 گزارش پیشرفته":
            send_message(chat_id, "📈 **گزارش پیشرفته:**\nنمودار عملکرد و رشد هفته اخیر آماده بررسی است.")

        elif text == "💰 سیستم مالی":
            send_message(chat_id, "💰 **سیستم مالی:**\nکل درآمد ماه جاری و لیست تراکنش‌ها به‌روزرسانی شد.")

        elif text == "👥 مدیریت کاربران":
            send_message(chat_id, "👥 **مدیریت کاربران:**\nامکان تغییر سطح، بن کردن و افزودن اعتبار به کاربران.")

        elif text == "🎯 سیستم ماموریت‌ها":
            send_message(chat_id, "🎯 **سیستم ماموریت‌ها:**\nلیست ماموریت‌های روزانه و هفتگی فعال است.")

        elif text == "📢 اطلاع‌رسانی هوشمند":
            send_message(chat_id, "📢 **اطلاع‌رسانی هوشمند:**\nزمان‌بندی پیام‌ها و یادآوری‌ها تنظیم شد.")

        elif text == "🔄 سیستم بکاپ":
            send_message(chat_id, "🔄 **سیستم بکاپ:**\nدیتابیس پشتیبان‌گیری شد.")

        elif text == "📈 تحلیل داده‌ها":
            send_message(chat_id, "📈 **تحلیل داده‌ها:**\nنرخ بازگشت کاربران و تحلیل تعاملات آماده است.")

        elif text == "🎮 رویدادهای ویژه":
            send_message(chat_id, "🎮 **رویدادهای ویژه:**\nایجاد رویداد و چالش جدید.")

        elif text == "🏆 جایزه‌های ویژه":
            send_message(chat_id, "🏆 **جایزه‌های ویژه:**\nتنظیم کدهای تخفیف و جوایز دلیپ.")

        elif text == "🔒 مدیریت امنیت":
            send_message(chat_id, "🔒 **مدیریت امنیت:**\nبررسی لاگ‌های مشکوک و ضد اسپم فعال است.")

        elif text == "🔗 سیستم همکاری":
            send_message(chat_id, "🔗 **سیستم همکاری در فروش:**\nکمیسیون‌ها و لینک‌های افیلیت.")

        elif text == "📝 نظرسنجی":
            send_message(chat_id, "📝 **نظرسنجی:**\nایجاد نظرسنجی جدید برای کاربران.")

        elif text == "🎨 شخصی‌سازی":
            send_message(chat_id, "🎨 **شخصی‌سازی:**\nتغییر متن‌های پیش‌فرض و بنرهای ربات.")

        elif text == "📚 سیستم آموزش":
            send_message(chat_id, "📚 **سیستم آموزش:**\nافزودن آموزش‌های جدید کالاف دیوتی.")

        elif text == "⚡ خودکارسازی":
            send_message(chat_id, "⚡ **خودکارسازی:**\nتنظیم پاسخ‌های خودکار به پیام‌های رایج.")

        elif text == "🔧 تنظیمات پیشرفته":
            send_message(chat_id, "🔧 **تنظیمات پیشرفته:**\nتغییر قیمت شانس‌ها، نرخ ماینینگ و کارمزدها.")

        elif text == "📋 تاریخچه پیام‌ها":
            send_message(chat_id, "📋 **تاریخچه پیام‌ها:**\nلیست آخرین پیام‌های همگانی ارسال شده.")

    conn.close()

def process_callback(callback):
    user_id = callback["from"]["id"]
    chat_id = callback["message"]["chat"]["id"]
    data = callback.get("data", "")

    if data == "check_join":
        if check_membership(user_id):
            send_message(
                chat_id,
                "🎉 **عضویت شما با موفقیت تایید شد!**\n\n🎮 به ربات خوش آمدید. از منوی زیر استفاده کنید:",
                get_main_keyboard(user_id)
            )
        else:
            send_message(
                chat_id,
                f"❌ **تایید نشد!**\n\nشما هنوز در کانال {REQUIRED_CHANNEL} عضو نشده‌اید.\nلطفا ابتدا عضو شوید و سپس دکمه زیر را بزنید.",
                get_join_keyboard()
            )

def main():
    offset = 0
    print("Bot is running...")
    while True:
        updates = api_request("getUpdates", {"offset": offset, "timeout": 10})
        if updates and updates.get("ok") and updates.get("result"):
            for update in updates["result"]:
                offset = update["update_id"] + 1
                if "message" in update:
                    process_message(update["message"])
                elif "callback_query" in update:
                    process_callback(update["callback_query"])
        time.sleep(1)

if __name__ == "__main__":
    main()
