import os
import smtplib
from datetime import datetime
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from telegram import Update, ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import (
    Application, CommandHandler, MessageHandler, CallbackQueryHandler,
    filters, ContextTypes, ConversationHandler
)

TELEGRAM_TOKEN = "8934036091:AAG_oJAsJ0dzO4khL9ig6lGA1YO0YTDkQA0"

ALLOWED_USERS = {
    8951484493,
    5566521544,
    8815575448,
}

SENDERS = [
    {"email": "ssb.gameplays1@gmail.com", "password": "joio idzg swdd lfxs"},
    {"email": "kasraramezanpour001@gmail.com", "password": "spyp wdja jezi uvsd"},
    {"email": "bwbw07639@gmail.com", "password": "tijp ctwa hnpq qcom"},
    {"email": "winstonlite127@gmail.com", "password": "wpyj okkn zqxw fjdv"},
    {"email": "henrywilson12892@gmail.com", "password": "unmv jteb dtwu xeaw"},
    {"email": "oliver.mitchellmen@gmail.com", "password": "xszw qfra mydg kgxz"},
    {"email": "jenazemoteharek@gmail.com", "password": "cuxg ceac shsm gfad"},
    {"email": "zeyusetujo318@gmail.com", "password": "bqze lzpj pxdf guqi"},
    {"email": "aobi27590@gmail.com", "password": "tzxf zmrz fhcx swyw"},
    {"email": "ethanparker20033@gmail.com", "password": "finw rdbq reux tgon"},
    {"email": "tomas.alexander2186@gmail.com", "password": "yfep sdyd auvi tqit"},
    {"email": "bgaret23@gmail.com", "password": "qgvi wvci jexp ggnb"},
    {"email": "holabala954@gmail.com", "password": "yblc nmmo fdyu hras"},
    {"email": "michaelcarter5369@gmail.com", "password": "zdnc vghz nlsk sunr"},
    {"email": "arasb77499@gmail.com", "password": "hazw sxkn vqke fjbb"},
    {"email": "Alex123789md8@gmail.com", "password": "ahdq bxcs dqgn fghm"},
    {"email": "mahan123dalir@gmail.com", "password": "zthb pgoj hjxp yxoj"},
    {"email": "Jamesanderson526525@gmail.com", "password": "knzd acdm nakk mukv"},
    {"email": "jamesaa71t@gmail.com", "password": "rasf wwsj ypml eupj"},
    {"email": "emilyaa37@gmail.com", "password": "neeu kziw pbps zamr"},
]

ADMIN_ID = 8951484493
TOTAL_ORDERS = 0

user_data_store = {}
user_lang = {}

(
    MAIN_MENU, ORDER_TYPE, GET_ACCOUNT_COUNT, GET_TIMES,
    GET_SUBJECT, GET_BODY, GET_RECIPIENT, CONFIRM,
    SUPPORT_MENU, WAIT_REPORT, WAIT_SUGGEST, WAIT_ADMIN
) = range(12)

TEXTS = {
    "fa": {
        "welcome": "سلام خوش آمدید.\nلطفاً یکی از گزینه‌های زیر را انتخاب کنید:",
        "no_access": "شما اجازه استفاده از خدمات ربات را ندارید.",
        "choose_order_type": "لطفاً نوع سفارش را انتخاب کنید:",
        "email_sender": "ایمیل سندر",
        "orders_count": "شما تا الان {} سفارش ثبت کرده‌اید.",
        "account_info": "💡 اطلاعات حساب شما در ربات ریپورتر:\n\n👤 شناسه شما : {}\n🔰 سطح حساب : ⭐️ کاربر ویژه\n🗓 تاریخ عضویت : {}\n\n🛍 تعداد سفارشات : {}\n\n🤖 @GODTM_ReporterBot",
        "faq_choose": "لطفاً یک گزینه را انتخاب کنید:",
        "rules_btn": "قوانین",
        "support_title": "بخش پشتیبانی:",
        "report_problem": "گزارش مشکل",
        "send_suggestion": "ارسال پیشنهادات",
        "other_items": "سایر موارد",
        "back_main": "بازگشت به منوی اصلی",
        "enter_account_count": "ارسال ایمیل تعداد بالا به آدرس ایمیل موردنظر شما ،\nکه به دلیل تعداد بالا تاثیر بسیار زیادی دارد.\n\n🔢 تعداد ایمیل (1 تا {}):\n\nلطفاً تعداد درخواستی خود را وارد کنید 👇🏻",
        "enter_times": "👇🏻 تعداد ایمیل‌هایی که هر حساب باید ارسال کند را وارد کنید:",
        "registered": "تعداد {} اکانت ایمیل و ارسال {} ایمیل با هر اکانت ثبت شد.",
        "enter_subject": "👇🏻 موضوع ایمیل (Subject) را وارد کنید:",
        "enter_body": "👇🏻 متن بدنه ایمیل (Body) را وارد کنید:",
        "enter_recipient": "👇🏻 ایمیل مقصدی که قرار است پیام دریافت کند را وارد کنید:",
        "invalid_email": "ایمیل نامعتبر است. دوباره وارد کنید:",
        "summary": "🧾 خلاصه سفارش #ایمیل\n\n• تعداد حساب‌ها: {}\n• ارسال هر حساب: {}\n• گیرنده: {}\n• موضوع: {}",
        "confirm_ask": "آیا اطلاعات بالا مورد تأیید است؟",
        "confirm_yes": "تأیید ✅",
        "confirm_no": "انصراف ❌",
        "cancelled": "لغو شد.",
        "back_to_main": "به منوی اصلی بازگشتید.",
        "order_registered": "✅ سفارش شما با کد {} ثبت شد.",
        "order_started": "♻️ سفارش ایمیل شما با کد ( {} ) شروع شد.\n\nموضوع ایمیل: {}\n\nتعداد {} اکانت و هر اکانت {} بار به حساب ({}) ایمیل می‌زنند.",
        "order_finished": "✅ سفارش ایمیل شما با شناسه ( {} ) تکمیل شد.\n\nموضوع ایمیل: {}\nگیرنده: {}\nتعداد ارسال شده : ({}/{})",
        "invalid_number": "لطفاً یک عدد معتبر وارد کنید:",
        "use_buttons": "لطفاً از دکمه‌های موجود استفاده کنید.",
        "lang_btn": "زبان",
        "lang_changed": "زبان به فارسی تغییر کرد.",
    },
    "en": {
        "welcome": "Welcome.\nPlease choose one of the options below:",
        "no_access": "You do not have permission to use the bot services.",
        "choose_order_type": "Please select the order type:",
        "email_sender": "Email Sender",
        "orders_count": "You have placed {} orders so far.",
        "account_info": "💡 Your account info in Reporter Bot:\n\n👤 Your ID : {}\n🔰 Account Level : ⭐️ Special User\n🗓 Join Date : {}\n\n🛍 Total Orders : {}\n\n🤖 @GODTM_ReporterBot",
        "faq_choose": "Please select an option:",
        "rules_btn": "Rules",
        "support_title": "Support section:",
        "report_problem": "Report a Problem",
        "send_suggestion": "Send Suggestions",
        "other_items": "Other Items",
        "back_main": "Back to Main Menu",
        "enter_account_count": "Send a large number of emails to your desired address,\nwhich has a very high impact due to the high volume.\n\n🔢 Number of emails (1 to {}):\n\nPlease enter the requested number 👇🏻",
        "enter_times": "👇🏻 Enter how many times each account should send:",
        "registered": "{} email accounts and {} emails per account registered.",
        "enter_subject": "👇🏻 Enter the email subject:",
        "enter_body": "👇🏻 Enter the email body:",
        "enter_recipient": "👇🏻 Enter the destination email address:",
        "invalid_email": "Invalid email. Please enter again:",
        "summary": "🧾 Order Summary #Email\n\n• Number of accounts: {}\n• Sends per account: {}\n• Recipient: {}\n• Subject: {}",
        "confirm_ask": "Are the above details correct?",
        "confirm_yes": "Confirm ✅",
        "confirm_no": "Cancel ❌",
        "cancelled": "Cancelled.",
        "back_to_main": "Returned to main menu.",
        "order_registered": "✅ Your order with code {} has been registered.",
        "order_started": "♻️ Your email order with code ( {} ) has started.\n\nSubject: {}\n\n{} accounts will each send {} times to ({}).",
        "order_finished": "✅ Your email order with ID ( {} ) has been completed.\n\nSubject: {}\nRecipient: {}\nSent count : ({}/{})",
        "invalid_number": "Please enter a valid number:",
        "use_buttons": "Please use the available buttons.",
        "lang_btn": "Language",
        "lang_changed": "Language changed to English.",
    }
}

def t(user_id, key, *args):
    lang = user_lang.get(user_id, "fa")
    text = TEXTS[lang].get(key, key)
    if args:
        return text.format(*args)
    return text

def is_allowed(user_id):
    return user_id in ALLOWED_USERS

def get_user_info(user_id):
    if user_id not in user_data_store:
        user_data_store[user_id] = {
            "join_date": datetime.now().strftime("%Y/%m/%d"),
            "orders": 0
        }
    return user_data_store[user_id]

def main_keyboard(user_id):
    lang = user_lang.get(user_id, "fa")
    if lang == "fa":
        keyboard = [
            [KeyboardButton("👨‍💻 ثبت سفارش", style="success"), KeyboardButton("🧾 سفارش‌های من", style="success")],
            [KeyboardButton("👤 حساب کاربری", style="primary"), KeyboardButton("🤔 سوال‌های متداول", style="primary")],
            [KeyboardButton("⁉️ پشتیبانی", style="danger"), KeyboardButton("زبان", style="primary")]
        ]
    else:
        keyboard = [
            [KeyboardButton("👨‍💻 Place Order", style="success"), KeyboardButton("🧾 My Orders", style="success")],
            [KeyboardButton("👤 My Account", style="primary"), KeyboardButton("🤔 FAQ", style="primary")],
            [KeyboardButton("⁉️ Support", style="danger"), KeyboardButton("Language", style="primary")]
        ]
    return ReplyKeyboardMarkup(keyboard, resize_keyboard=True)

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user = update.effective_user
    if user.id not in user_lang:
        user_lang[user.id] = "fa"
    get_user_info(user.id)
    await update.message.reply_text(t(user.id, "welcome"), reply_markup=main_keyboard(user.id))
    return MAIN_MENU

async def language_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user_id = update.effective_user.id
    current = user_lang.get(user_id, "fa")
    user_lang[user_id] = "en" if current == "fa" else "fa"
    await update.message.reply_text(t(user_id, "lang_changed"), reply_markup=main_keyboard(user_id))
    return MAIN_MENU

async def main_menu_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
    text = (update.message.text or "").lower()
    user_id = update.effective_user.id

    if "زبان" in text or "language" in text:
        return await language_cmd(update, context)

    if "ثبت سفارش" in text or "place order" in text:
        if not is_allowed(user_id):
            await update.message.reply_text(t(user_id, "no_access"), reply_markup=main_keyboard(user_id))
            return MAIN_MENU
        keyboard = [[InlineKeyboardButton(t(user_id, "email_sender"), callback_data="email_sender", style="primary")]]
        await update.message.reply_text(t(user_id, "choose_order_type"), reply_markup=InlineKeyboardMarkup(keyboard))
        return ORDER_TYPE

    elif ("سفارش" in text and "من" in text) or "my orders" in text:
        info = get_user_info(user_id)
        await update.message.reply_text(t(user_id, "orders_count", info["orders"]), reply_markup=main_keyboard(user_id))
        return MAIN_MENU

    elif "حساب کاربری" in text or "my account" in text:
        info = get_user_info(user_id)
        msg = t(user_id, "account_info", user_id, info["join_date"], info["orders"])
        await update.message.reply_text(msg, reply_markup=main_keyboard(user_id))
        return MAIN_MENU

    elif "سوال" in text or "متداول" in text or "faq" in text:
        keyboard = [[InlineKeyboardButton(t(user_id, "rules_btn"), callback_data="rules", style="danger")]]
        await update.message.reply_text(t(user_id, "faq_choose"), reply_markup=InlineKeyboardMarkup(keyboard))
        return MAIN_MENU

    elif "پشتیبانی" in text or "support" in text:
        if user_lang.get(user_id, "fa") == "fa":
            keyboard = [
                [KeyboardButton("گزارش مشکل", style="danger")],
                [KeyboardButton("ارسال پیشنهادات", style="primary")],
                [KeyboardButton("سایر موارد", style="primary")],
                [KeyboardButton("بازگشت به منوی اصلی", style="danger")]
            ]
        else:
            keyboard = [
                [KeyboardButton("Report a Problem", style="danger")],
                [KeyboardButton("Send Suggestions", style="primary")],
                [KeyboardButton("Other Items", style="primary")],
                [KeyboardButton("Back to Main Menu", style="danger")]
            ]
        await update.message.reply_text(t(user_id, "support_title"), reply_markup=ReplyKeyboardMarkup(keyboard, resize_keyboard=True))
        return SUPPORT_MENU

    else:
        await update.message.reply_text(t(user_id, "use_buttons"), reply_markup=main_keyboard(user_id))
        return MAIN_MENU

async def order_type_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()
    user_id = query.from_user.id

    if query.data == "email_sender":
        try:
            await query.message.delete()
        except:
            pass
        total = len(SENDERS)
        await context.bot.send_message(chat_id=query.message.chat_id, text=t(user_id, "enter_account_count", total))
        return GET_ACCOUNT_COUNT

async def get_account_count(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user_id = update.effective_user.id
    text = update.message.text.strip()
    if not text.isdigit() or int(text) < 1:
        await update.message.reply_text(t(user_id, "invalid_number"))
        return GET_ACCOUNT_COUNT
    count = min(int(text), len(SENDERS))
    context.user_data["account_count"] = count
    await update.message.reply_text(t(user_id, "enter_times"))
    return GET_TIMES

async def get_times(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user_id = update.effective_user.id
    text = update.message.text.strip()
    if not text.isdigit() or int(text) < 1:
        await update.message.reply_text(t(user_id, "invalid_number"))
        return GET_TIMES
    times = int(text)
    context.user_data["times"] = times
    acc = context.user_data["account_count"]
    await update.message.reply_text(t(user_id, "registered", acc, times))
    await update.message.reply_text(t(user_id, "enter_subject"))
    return GET_SUBJECT

async def get_subject(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user_id = update.effective_user.id
    context.user_data["subject"] = update.message.text
    await update.message.reply_text(t(user_id, "enter_body"))
    return GET_BODY

async def get_body(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user_id = update.effective_user.id
    context.user_data["body"] = update.message.text
    await update.message.reply_text(t(user_id, "enter_recipient"))
    return GET_RECIPIENT

async def get_recipient(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user_id = update.effective_user.id
    email = update.message.text.strip()
    if "@" not in email:
        await update.message.reply_text(t(user_id, "invalid_email"))
        return GET_RECIPIENT
    context.user_data["recipient"] = email

    summary = t(user_id, "summary",
                context.user_data["account_count"],
                context.user_data["times"],
                email,
                context.user_data["subject"])
    await update.message.reply_text(summary)

    keyboard = [[
        InlineKeyboardButton(t(user_id, "confirm_yes"), callback_data="confirm_yes", style="success"),
        InlineKeyboardButton(t(user_id, "confirm_no"), callback_data="confirm_no", style="danger")
    ]]
    await update.message.reply_text(t(user_id, "confirm_ask"), reply_markup=InlineKeyboardMarkup(keyboard))
    return CONFIRM

async def confirm_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
    global TOTAL_ORDERS
    query = update.callback_query
    await query.answer()
    user_id = query.from_user.id

    if query.data == "confirm_no":
        await query.edit_message_text(t(user_id, "cancelled"))
        context.user_data.clear()
        await query.message.reply_text(t(user_id, "back_to_main"), reply_markup=main_keyboard(user_id))
        return MAIN_MENU

    if query.data == "confirm_yes":
        TOTAL_ORDERS += 1
        order_id = TOTAL_ORDERS

        await query.edit_message_text(t(user_id, "order_registered", order_id))

        recipient = context.user_data["recipient"]
        subject = context.user_data["subject"]
        body = context.user_data["body"]
        acc_count = context.user_data["account_count"]
        times = context.user_data["times"]
        requested = acc_count * times

        await query.message.reply_text(
            t(user_id, "order_started", order_id, subject, acc_count, times, recipient)
        )

        selected = SENDERS[:acc_count]
        total_success = 0

        for sender in selected:
            try:
                server = smtplib.SMTP_SSL("smtp.gmail.com", 465, timeout=30)
                server.login(sender["email"], sender["password"])
                for _ in range(times):
                    msg = MIMEMultipart()
                    msg["From"] = sender["email"]
                    msg["To"] = recipient
                    msg["Subject"] = subject
                    msg.attach(MIMEText(body, "plain", "utf-8"))
                    server.sendmail(sender["email"], recipient, msg.as_string())
                    total_success += 1
                server.quit()
            except Exception:
                pass

        info = get_user_info(user_id)
        info["orders"] += 1

        await query.message.reply_text(
            t(user_id, "order_finished", order_id, subject, recipient, requested, total_success),
            reply_markup=main_keyboard(user_id)
        )
        context.user_data.clear()
        return MAIN_MENU

async def rules_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()
    user_id = query.from_user.id
    if query.data == "rules":
        rules = """📌 قوانین استفاده از ربات:

1. استفاده از ربات برای ارسال گزارش‌های نامربوط یا هرگونه سوء‌استفاده از کاربران دیگر ممنوع است.
2. در صورتی که ربات نتواند خدماتی ارائه دهد، پس از ۳ ماه می‌توانید موجودی خود را به‌صورت ارز دیجیتال برداشت کنید.
3. ربات ریپورتر صرفاً وظیفه‌ی تأمین اکانت و تکمیل گزارش را بر عهده دارد.
4. هیچ‌گونه متن گزارش توسط ربات ما یا تیم پشتیبانی فروخته نمی‌شود.
5. هرگونه سوء‌استفاده از باگ‌ها منجر به مسدود شدن دائمی خواهد شد.
6. تأیید قوانین به معنای مطالعه و پذیرش کامل قوانین است.
7. برای مشکلات با تیم پشتیبانی (@Kabothar) یا @G0DD1 تماس بگیرید.

👈 تاریخ بروزرسانی قوانین: 1405/7/8"""
        keyboard = [[InlineKeyboardButton(t(user_id, "back_main"), callback_data="back_to_main", style="danger")]]
        await query.edit_message_text(rules, reply_markup=InlineKeyboardMarkup(keyboard))

async def back_to_main(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()
    user_id = query.from_user.id
    try:
        await query.message.delete()
    except:
        pass
    await context.bot.send_message(chat_id=query.message.chat_id, text=t(user_id, "welcome"), reply_markup=main_keyboard(user_id))
    return MAIN_MENU

async def support_menu_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
    text = (update.message.text or "").lower()
    user_id = update.effective_user.id

    if "گزارش مشکل" in text or "report" in text:
        await update.message.reply_text("⚠️ لطفاً متن مشکل خود را ارسال کنید:")
        return WAIT_REPORT
    elif "پیشنهاد" in text or "suggest" in text:
        await update.message.reply_text("⚠️ لطفاً متن پیشنهاد خود را ارسال کنید:")
        return WAIT_SUGGEST
    elif "سایر" in text or "other" in text:
        keyboard = [[InlineKeyboardButton("مدیریت اصلی" if user_lang.get(user_id,"fa")=="fa" else "Main Admin", callback_data="admin_msg", style="primary")]]
        await update.message.reply_text("بخش مدیریت اصلی:", reply_markup=InlineKeyboardMarkup(keyboard))
        return SUPPORT_MENU
    elif "بازگشت" in text or "back" in text:
        await update.message.reply_text(t(user_id, "back_to_main"), reply_markup=main_keyboard(user_id))
        return MAIN_MENU

async def admin_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()
    await query.edit_message_text("پیام خود را ارسال کنید:")
    return WAIT_ADMIN

async def receive_report(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user = update.effective_user
    try:
        await context.bot.send_message(ADMIN_ID, f"گزارش از {user.full_name} ({user.id}):\n\n{update.message.text}")
    except:
        pass
    await update.message.reply_text("پیام شما ثبت شد.", reply_markup=main_keyboard(user.id))
    return MAIN_MENU

async def receive_suggest(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user = update.effective_user
    try:
        await context.bot.send_message(ADMIN_ID, f"پیشنهاد از {user.full_name} ({user.id}):\n\n{update.message.text}")
    except:
        pass
    await update.message.reply_text("پیام شما ثبت شد.", reply_markup=main_keyboard(user.id))
    return MAIN_MENU

async def receive_admin(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user = update.effective_user
    try:
        await context.bot.send_message(ADMIN_ID, f"پیام مستقیم از {user.full_name} ({user.id}):\n\n{update.message.text}")
    except:
        pass
    await update.message.reply_text("پیام ارسال شد.", reply_markup=main_keyboard(user.id))
    return MAIN_MENU

async def cancel(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user_id = update.effective_user.id
    context.user_data.clear()
    await update.message.reply_text(t(user_id, "cancelled"), reply_markup=main_keyboard(user_id))
    return MAIN_MENU

def main():
    app = Application.builder().token(TELEGRAM_TOKEN).build()

    conv = ConversationHandler(
        entry_points=[CommandHandler("start", start), CommandHandler("language", language_cmd)],
        states={
            MAIN_MENU: [
                MessageHandler(filters.TEXT, main_menu_handler),
                CallbackQueryHandler(rules_handler, pattern="^rules$"),
                CallbackQueryHandler(back_to_main, pattern="^back_to_main$")
            ],
            ORDER_TYPE: [CallbackQueryHandler(order_type_handler)],
            GET_ACCOUNT_COUNT: [MessageHandler(filters.TEXT, get_account_count)],
            GET_TIMES: [MessageHandler(filters.TEXT, get_times)],
            GET_SUBJECT: [MessageHandler(filters.TEXT, get_subject)],
            GET_BODY: [MessageHandler(filters.TEXT, get_body)],
            GET_RECIPIENT: [MessageHandler(filters.TEXT, get_recipient)],
            CONFIRM: [CallbackQueryHandler(confirm_handler)],
            SUPPORT_MENU: [
                MessageHandler(filters.TEXT, support_menu_handler),
                CallbackQueryHandler(admin_callback, pattern="^admin_msg$")
            ],
            WAIT_REPORT: [MessageHandler(filters.TEXT, receive_report)],
            WAIT_SUGGEST: [MessageHandler(filters.TEXT, receive_suggest)],
            WAIT_ADMIN: [MessageHandler(filters.TEXT, receive_admin)],
        },
        fallbacks=[CommandHandler("cancel", cancel), CommandHandler("start", start), CommandHandler("language", language_cmd)],
        allow_reentry=True
    )

    app.add_handler(conv)
    print("ربات روشن شد...")
    app.run_polling()

if name == "main":
    main()