import mysql.connector
import calendar
import re
from telegram import Update, ReplyKeyboardMarkup, ReplyKeyboardRemove, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import (
    MessageHandler, filters, ContextTypes, ConversationHandler, CommandHandler
)

# مراحل الحوار
(START_ACTION, RE_REGISTER, FIRST_NAME, FATHER_NAME, GRANDFATHER_NAME, FAMILY_NAME, 
 GENDER, BIRTH_YEAR, BIRTH_MONTH, BIRTH_DAY, COUNTRY, QURAN_HIFZ, 
 BRANCH, PREV_SAVE, TELEGRAM_NUMBER, EDUCATION_LEVEL, SPECIALIZATION, JOB, QURAN_ACTIVITY) = range(19)

# --- القوائم المرتبة أبجدياً ---
GENDER_OPTIONS = ['أنثى', 'ذكر']
years_list = [str(y) for y in range(1945, 2012)]
MONTHS_LIST = [str(m) for m in range(1, 13)]
hifz_list = ["سور متفرقة", "جزء واحد", "جزئين"] + [f"{i} أجزاء" for i in range(3, 11)] + [f"{i} جزء" for i in range(11, 30)] + ["كل القرآن"]
EDU_OPTIONS_LIST = ['إعدادية', 'متوسطة', 'ابتدائية', 'ماجستير', 'بكالوريوس', 'معهد (دبلوم)', 'حوزوي', 'دكتوراه']
BRANCH_OPTIONS_LIST = ['التفسير والحفظ', 'التفسير فقط']
YES_NO_OPTIONS = ['لا', 'نعم']

COUNTRIES_LIST = sorted([
    "أذربايجان", "أستراليا", "أفغانستان", "أفريقيا الوسطى", "ألبانيا", "ألمانيا", "أمريكا", "أوغندا", "أيرلندا", "إريتيريا",
    "إسبانيا", "إكوادور", "إندونيسيا", "إيران", "إيطاليا", "الأرجنتين", "الأردن", "الإمارات", "البحرين", "البرازيل",
    "البرتغال", "البلجيك", "البلغار", "البوسنة والهرسك", "التشيك", "الجزائر", "الدنمارك", "السعودية", "السنغال", "السودان",
    "السويد", "الصومال", "الصين", "العراق", "الفلبين", "الكويت", "المجر", "المغرب", "المكسيك", "النرويج",
    "النمسا", "النيجر", "الهند", "اليابان", "اليمن", "اليونان", "باكستان", "بريطانيا", "بلجيكا", "بلغاريا",
    "بنغلاديش", "بولندا", "تركيا", "تشيلي", "تنزانيا", "تونس", "جنوب أفريقيا", "جيبوتي", "روسيا", "رومانيا",
    "ساحل العاج", "سريلانكا", "سلوفاكيا", "سوريا", "سويسرا", "عمان", "غانا", "غينيا", "فرنسا", "فلسطين",
    "فنزويلا", "فنلندا", "قطر", "كندا", "كوبا", "كينيا", "لبنان", "ليبيا", "مالي", "ماليزيا",
    "مدغشقر", "مصر", "موريتانيا", "نيجيريا", "نيوزلندا", "هولندا"
])

# --- الدوال مع التحقق الصارم ---

async def start_reg_flow(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("يرجى كتابة اسمك الشخصي فقط، بدون اسم الأب أو الجد أو العائلة:", reply_markup=ReplyKeyboardRemove())
    return FIRST_NAME

async def get_first_name(update: Update, context: ContextTypes.DEFAULT_TYPE):
    context.user_data['first_name'] = update.message.text
    await update.message.reply_text("يرجى كتابة اسم الأب فقط، بدون اسم الجد أو العائلة:")
    return FATHER_NAME

async def get_father_name(update: Update, context: ContextTypes.DEFAULT_TYPE):
    context.user_data['father_name'] = update.message.text
    await update.message.reply_text("يرجى كتابة اسم الجد فقط:")
    return GRANDFATHER_NAME

async def get_grandfather_name(update: Update, context: ContextTypes.DEFAULT_TYPE):
    context.user_data['grandfather_name'] = update.message.text
    await update.message.reply_text("يرجى كتابة اللقب (الاسم العائلي):")
    return FAMILY_NAME

async def get_family_name(update: Update, context: ContextTypes.DEFAULT_TYPE):
    context.user_data['family_name'] = update.message.text
    reply_markup = ReplyKeyboardMarkup([GENDER_OPTIONS], resize_keyboard=True, one_time_keyboard=True)
    await update.message.reply_text("يرجى اختيار الجنس:", reply_markup=reply_markup)
    return GENDER

async def get_gender(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if update.message.text not in GENDER_OPTIONS:
        await update.message.reply_text("⚠️ يرجى الاختيار من الأزرار (أنثى / ذكر) فقط.")
        return GENDER
    context.user_data['gender'] = update.message.text
    YEARS_KB = [years_list[i:i + 4][::-1] for i in range(0, len(years_list), 4)]
    await update.message.reply_text("اختر سنة ميلادك:", reply_markup=ReplyKeyboardMarkup(YEARS_KB, resize_keyboard=True))
    return BIRTH_YEAR

async def get_year(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if update.message.text not in years_list:
        await update.message.reply_text("⚠️ يرجى اختيار سنة من الأزرار الظاهرة.")
        return BIRTH_YEAR
    context.user_data['b_year'] = int(update.message.text)
    MONTHS_KB = [[str(m) for m in range(i, i + 4)][::-1] for i in range(1, 13, 4)]
    await update.message.reply_text("اختر شهر ميلادك:", reply_markup=ReplyKeyboardMarkup(MONTHS_KB, resize_keyboard=True))
    return BIRTH_MONTH

async def get_month(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if update.message.text not in MONTHS_LIST:
        await update.message.reply_text("⚠️ يرجى اختيار شهر من الأزرار الظاهرة.")
        return BIRTH_MONTH
    context.user_data['b_month'] = int(update.message.text)
    num_days = calendar.monthrange(context.user_data['b_year'], context.user_data['b_month'])[1]
    valid_days = [str(d) for d in range(1, num_days + 1)]
    context.user_data['valid_days'] = valid_days
    DAYS_KB = [valid_days[i:i + 7][::-1] for i in range(0, len(valid_days), 7)]
    await update.message.reply_text("اختر يوم ميلادك:", reply_markup=ReplyKeyboardMarkup(DAYS_KB, resize_keyboard=True))
    return BIRTH_DAY

async def get_day(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if update.message.text not in context.user_data.get('valid_days', []):
        await update.message.reply_text("⚠️ يرجى اختيار اليوم من الأزرار الظاهرة فقط.")
        return BIRTH_DAY
    context.user_data['birth_date'] = f"{context.user_data['b_year']}-{context.user_data['b_month']}-{update.message.text}"
    COUNTRY_KB = [COUNTRIES_LIST[i:i + 2] for i in range(0, len(COUNTRIES_LIST), 2)]
    await update.message.reply_text("يرجى اختيار دولتك من القائمة:", reply_markup=ReplyKeyboardMarkup(COUNTRY_KB, resize_keyboard=True))
    return COUNTRY

async def get_country(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if update.message.text not in COUNTRIES_LIST:
        await update.message.reply_text("⚠️ يرجى اختيار دولة من القائمة الظاهرة.")
        return COUNTRY
    context.user_data['country'] = update.message.text
    HIFZ_KB = [hifz_list[i:i + 3][::-1] for i in range(0, len(hifz_list), 3)]
    await update.message.reply_text("كم تحفظون حالياً من القرآن الكريم؟", reply_markup=ReplyKeyboardMarkup(HIFZ_KB, resize_keyboard=True))
    return QURAN_HIFZ

async def get_hifz(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if update.message.text not in hifz_list:
        await update.message.reply_text("⚠️ يرجى الاختيار من قائمة مستويات الحفظ.")
        return QURAN_HIFZ
    context.user_data['quran_hifz'] = update.message.text
    await update.message.reply_text("تشاركون في هذه الدورة في:", reply_markup=ReplyKeyboardMarkup([BRANCH_OPTIONS_LIST], resize_keyboard=True))
    return BRANCH

async def get_branch(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if update.message.text not in BRANCH_OPTIONS_LIST:
        await update.message.reply_text("⚠️ يرجى اختيار أحد الفرعين المتاحين.")
        return BRANCH
    context.user_data['participation_branch'] = update.message.text
    await update.message.reply_text("هل حفظتم سابقاً سورة لقمان؟", reply_markup=ReplyKeyboardMarkup([YES_NO_OPTIONS], resize_keyboard=True))
    return PREV_SAVE

async def get_prev_save(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if update.message.text not in YES_NO_OPTIONS:
        await update.message.reply_text("⚠️ يرجى اختيار (نعم) أو (لا).")
        return PREV_SAVE
    context.user_data['is_saved_before'] = update.message.text
    await update.message.reply_text("يرجى كتابة رقم التلجرام الخاص بك (مع مفتاح الدولة):", reply_markup=ReplyKeyboardRemove())
    return TELEGRAM_NUMBER

async def get_telegram_number(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if not re.match(r'^\+?\d+$', update.message.text):
        await update.message.reply_text("⚠️ عذراً، يرجى إدخال رقم هاتف صحيح (أرقام فقط).")
        return TELEGRAM_NUMBER
    context.user_data['telegram_number'] = update.message.text
    EDU_KB = [['إعدادية', 'متوسطة', 'ابتدائية'], ['ماجستير', 'بكالوريوس', 'معهد (دبلوم)'], ['حوزوي', 'دكتوراه']]
    await update.message.reply_text("ما هو مستواكم الدراسي؟", reply_markup=ReplyKeyboardMarkup(EDU_KB, resize_keyboard=True))
    return EDUCATION_LEVEL

async def get_edu(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if update.message.text not in EDU_OPTIONS_LIST:
        await update.message.reply_text("⚠️ يرجى اختيار المستوى الدراسي من الأزرار فقط.")
        return EDUCATION_LEVEL
    context.user_data['education_level'] = update.message.text
    await update.message.reply_text("يرجى كتابة التخصص الدراسي (مثال: تربية عربي، طب أسنان..)، أو (لا يوجد):", reply_markup=ReplyKeyboardRemove())
    return SPECIALIZATION

async def get_spec(update: Update, context: ContextTypes.DEFAULT_TYPE):
    context.user_data['specialization'] = update.message.text
    await update.message.reply_text("يرجى كتابة العمل الحالي، أو عبارة (لا يوجد):")
    return JOB

async def get_job(update: Update, context: ContextTypes.DEFAULT_TYPE):
    context.user_data['job'] = update.message.text
    await update.message.reply_text("نبذة عن نشاطكم القرآني كالتدريس والمشاركة في المحافل، أو عبارة (لا يوجد):")
    return QURAN_ACTIVITY

async def finish_registration(update: Update, context: ContextTypes.DEFAULT_TYPE):
    context.user_data['quran_activity'] = update.message.text
    d = context.user_data
    try:
        # --- استبدل المعلومات أدناه ببيانات الهوست الجديدة ---
        db = mysql.connector.connect(
            host="localhost",
            user="sooraapps_Mustafa",
            password= "Fihpoz-kahwep-8dubde",
            database="sooraapps_Markaz_Class_01",
            charset='utf8mb4'
        )
        cursor = db.cursor()
        sql = "INSERT INTO participants (telegram_id, first_name, father_name, grandfather_name, family_name, gender, birth_date, country, quran_hifz, participation_branch, is_saved_before, telegram_number, education_level, specialization, job, quran_activity) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
        cursor.execute(sql, (update.effective_user.id, d['first_name'], d['father_name'], d['grandfather_name'], d['family_name'], d['gender'], d['birth_date'], d['country'], d['quran_hifz'], d['participation_branch'], d['is_saved_before'], d['telegram_number'], d['education_level'], d['specialization'], d['job'], d['quran_activity']))
        db.commit()
        db.close()
        
        await update.message.reply_text("✅ تم التسجيل بنجاح! بارك الله فيكم.")
        channel_message = "يرجى الانضمام إلى قناة الدورة، وقراءة ما يرد فيها بدقة بشكل يومي.\n\nhttps://t.me/+wMpGC4R8LBw2ZjBi"
        keyboard = [[InlineKeyboardButton("💬 التواصل مع إدارة الدورة", url="https://t.me/iqrc5_class")]]
        await update.message.reply_text(channel_message, reply_markup=InlineKeyboardMarkup(keyboard))
    except Exception as e:
        await update.message.reply_text(f"❌ خطأ: {e}")
    
    context.user_data.clear()
    return ConversationHandler.END

# --- معالج الحوار الرئيسي ---
registration_conv = ConversationHandler(
    entry_points=[
        MessageHandler(filters.Regex('^📝 بدء التسجيل$'), start_reg_flow),
        MessageHandler(filters.Regex('^نعم، تسجيل مشارك آخر$'), start_reg_flow)
    ],
    states={
        FIRST_NAME: [MessageHandler(filters.TEXT & ~filters.COMMAND, get_first_name)],
        FATHER_NAME: [MessageHandler(filters.TEXT & ~filters.COMMAND, get_father_name)],
        GRANDFATHER_NAME: [MessageHandler(filters.TEXT & ~filters.COMMAND, get_grandfather_name)],
        FAMILY_NAME: [MessageHandler(filters.TEXT & ~filters.COMMAND, get_family_name)],
        GENDER: [MessageHandler(filters.TEXT & ~filters.COMMAND, get_gender)],
        BIRTH_YEAR: [MessageHandler(filters.TEXT & ~filters.COMMAND, get_year)],
        BIRTH_MONTH: [MessageHandler(filters.TEXT & ~filters.COMMAND, get_month)],
        BIRTH_DAY: [MessageHandler(filters.TEXT & ~filters.COMMAND, get_day)],
        COUNTRY: [MessageHandler(filters.TEXT & ~filters.COMMAND, get_country)],
        QURAN_HIFZ: [MessageHandler(filters.TEXT & ~filters.COMMAND, get_hifz)],
        BRANCH: [MessageHandler(filters.TEXT & ~filters.COMMAND, get_branch)],
        PREV_SAVE: [MessageHandler(filters.TEXT & ~filters.COMMAND, get_prev_save)],
        TELEGRAM_NUMBER: [MessageHandler(filters.TEXT & ~filters.COMMAND, get_telegram_number)],
        EDUCATION_LEVEL: [MessageHandler(filters.TEXT & ~filters.COMMAND, get_edu)],
        SPECIALIZATION: [MessageHandler(filters.TEXT & ~filters.COMMAND, get_spec)],
        JOB: [MessageHandler(filters.TEXT & ~filters.COMMAND, get_job)],
        QURAN_ACTIVITY: [MessageHandler(filters.TEXT & ~filters.COMMAND, finish_registration)],
    },
    fallbacks=[CommandHandler('cancel', lambda u, c: ConversationHandler.END)],
)