import os

files = {}

# 1. افزودن جدول کدهای تخفیف به دیتابیس
files["database.py"] = """import aiosqlite
from datetime import datetime, timedelta
from config import DB_PATH, REFERRAL_REWARD
import os

async def init_db():
    os.makedirs(os.path.dirname(DB_PATH) if os.path.dirname(DB_PATH) else ".", exist_ok=True)
    async with aiosqlite.connect(DB_PATH) as db:
        await db.execute("CREATE TABLE IF NOT EXISTS bot_starters (user_id INTEGER PRIMARY KEY, joined_at TEXT)")
        await db.execute("CREATE TABLE IF NOT EXISTS users (user_id INTEGER PRIMARY KEY, username TEXT, first_name TEXT, age INTEGER, height REAL, weight REAL, neck_cm REAL, waist_cm REAL, activity_level TEXT, goal TEXT, training_place TEXT, injury TEXT, bmi REAL, body_fat REAL, bmr REAL, tdee REAL, created_at TEXT, updated_at TEXT, wallet_balance INTEGER DEFAULT 0, invited_by INTEGER DEFAULT NULL, gender TEXT DEFAULT 'مرد')")
        await db.execute("CREATE TABLE IF NOT EXISTS subscriptions (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL, plan_key TEXT NOT NULL, start_date TEXT NOT NULL, end_date TEXT NOT NULL, is_active INTEGER DEFAULT 1, activated_by INTEGER, payment_amount INTEGER DEFAULT 0, notes TEXT, created_at TEXT NOT NULL)")
        await db.execute("CREATE TABLE IF NOT EXISTS payment_requests (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL, plan_key TEXT NOT NULL, amount INTEGER NOT NULL, status TEXT DEFAULT 'pending', receipt_file_id TEXT, admin_note TEXT, created_at TEXT NOT NULL, reviewed_at TEXT)")
        await db.execute("CREATE TABLE IF NOT EXISTS withdraw_requests (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL, amount INTEGER NOT NULL, card_info TEXT NOT NULL, status TEXT DEFAULT 'pending', created_at TEXT NOT NULL)")
        await db.execute("CREATE TABLE IF NOT EXISTS admins (user_id INTEGER PRIMARY KEY, added_at TEXT NOT NULL)")
        # جدول کدهای تخفیف
        await db.execute("CREATE TABLE IF NOT EXISTS discount_codes (code TEXT PRIMARY KEY, percent INTEGER NOT NULL, max_uses INTEGER DEFAULT 1, used_count INTEGER DEFAULT 0, created_at TEXT NOT NULL)")
        await db.commit()

async def record_start(user_id: int):
    async with aiosqlite.connect(DB_PATH) as db:
        await db.execute("INSERT OR IGNORE INTO bot_starters (user_id, joined_at) VALUES (?, ?)", (user_id, datetime.now().isoformat()))
        await db.commit()

async def get_all_starters() -> list:
    async with aiosqlite.connect(DB_PATH) as db:
        c = await db.execute("SELECT user_id FROM bot_starters")
        return [r[0] for r in await c.fetchall()]

async def save_user(user_data: dict):
    async with aiosqlite.connect(DB_PATH) as db:
        now = datetime.now().isoformat()
        cursor = await db.execute("SELECT user_id FROM users WHERE user_id = ?", (user_data["user_id"],))
        if await cursor.fetchone():
            await db.execute("UPDATE users SET username=?, first_name=?, gender=?, age=?, height=?, weight=?, neck_cm=?, waist_cm=?, activity_level=?, goal=?, training_place=?, injury=?, bmi=?, body_fat=?, bmr=?, tdee=?, updated_at=? WHERE user_id=?", (user_data.get("username"), user_data.get("first_name"), user_data.get("gender"), user_data.get("age"), user_data.get("height"), user_data.get("weight"), user_data.get("neck_cm"), user_data.get("waist_cm"), user_data.get("activity_level"), user_data.get("goal"), user_data.get("training_place"), user_data.get("injury"), user_data.get("bmi"), user_data.get("body_fat"), user_data.get("bmr"), user_data.get("tdee"), now, user_data["user_id"]))
        else:
            invited_by = user_data.get("invited_by")
            await db.execute("INSERT INTO users (user_id, username, first_name, gender, age, height, weight, neck_cm, waist_cm, activity_level, goal, training_place, injury, bmi, body_fat, bmr, tdee, created_at, updated_at, invited_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", (user_data["user_id"], user_data.get("username"), user_data.get("first_name"), user_data.get("gender"), user_data.get("age"), user_data.get("height"), user_data.get("weight"), user_data.get("neck_cm"), user_data.get("waist_cm"), user_data.get("activity_level"), user_data.get("goal"), user_data.get("training_place"), user_data.get("injury"), user_data.get("bmi"), user_data.get("body_fat"), user_data.get("bmr"), user_data.get("tdee"), now, now, invited_by))
        await db.commit()

async def get_user(user_id: int) -> dict | None:
    async with aiosqlite.connect(DB_PATH) as db:
        db.row_factory = aiosqlite.Row
        c = await db.execute("SELECT * FROM users WHERE user_id = ?", (user_id,))
        r = await c.fetchone()
        return dict(r) if r else None

async def add_wallet_balance(u, a):
    async with aiosqlite.connect(DB_PATH) as db:
        await db.execute("UPDATE users SET wallet_balance = wallet_balance + ? WHERE user_id = ?", (a, u)); await db.commit()

async def get_active_subscription(u):
    async with aiosqlite.connect(DB_PATH) as db:
        db.row_factory = aiosqlite.Row
        c = await db.execute("SELECT * FROM subscriptions WHERE user_id = ? AND is_active = 1 AND end_date > ? ORDER BY end_date DESC LIMIT 1", (u, datetime.now().isoformat()))
        r = await c.fetchone()
        return dict(r) if r else None

async def activate_subscription(u, p, d, a, admin, notes=""):
    referrer_id = None
    async with aiosqlite.connect(DB_PATH) as db:
        now = datetime.now()
        c = await db.execute("SELECT COUNT(*) FROM subscriptions WHERE user_id = ?", (u,))
        if (await c.fetchone())[0] == 0:
            c_u = await db.execute("SELECT invited_by FROM users WHERE user_id = ?", (u,))
            u_row = await c_u.fetchone()
            if u_row and u_row[0]:
                referrer_id = u_row[0]
                await db.execute("UPDATE users SET wallet_balance = wallet_balance + ? WHERE user_id = ?", (REFERRAL_REWARD, referrer_id))

        ex = await get_active_subscription(u)
        sd = datetime.fromisoformat(ex["end_date"]) if ex and datetime.fromisoformat(ex["end_date"]) > now else now
        ed = sd + timedelta(days=d)
        await db.execute("UPDATE subscriptions SET is_active = 0 WHERE user_id = ? AND is_active = 1", (u,))
        await db.execute("INSERT INTO subscriptions (user_id, plan_key, start_date, end_date, is_active, activated_by, payment_amount, notes, created_at) VALUES (?, ?, ?, ?, 1, ?, ?, ?, ?)", (u, p, sd.isoformat(), ed.isoformat(), admin, a, notes, now.isoformat()))
        await db.commit()
        return {"user_id": u, "end_date": ed.isoformat(), "duration_days": d, "referrer_id": referrer_id}

async def create_payment_request(u, p, a, f):
    async with aiosqlite.connect(DB_PATH) as db:
        c = await db.execute("INSERT INTO payment_requests (user_id, plan_key, amount, receipt_file_id, created_at) VALUES (?, ?, ?, ?, ?)", (u, p, a, f, datetime.now().isoformat()))
        await db.commit(); return c.lastrowid

async def get_subscription_stats():
    async with aiosqlite.connect(DB_PATH) as db:
        c = await db.execute("SELECT COUNT(*) FROM bot_starters"); ts = (await c.fetchone())[0]
        c = await db.execute("SELECT COUNT(*) FROM users"); tu = (await c.fetchone())[0]
        c = await db.execute("SELECT COUNT(*) FROM subscriptions WHERE is_active = 1 AND end_date > ?", (datetime.now().isoformat(),)); asub = (await c.fetchone())[0]
        c = await db.execute("SELECT COALESCE(SUM(payment_amount), 0) FROM subscriptions"); tr = (await c.fetchone())[0]
        c = await db.execute("SELECT COUNT(*) FROM payment_requests WHERE status = 'pending'"); pr = (await c.fetchone())[0]
        c = await db.execute("SELECT COUNT(*) FROM withdraw_requests WHERE status = 'pending'"); pw = (await c.fetchone())[0]
        return {"total_starts": ts, "registered_users": tu, "active_subs": asub, "total_revenue": tr, "pending_requests": pr, "pending_withdraws": pw}

async def get_pending_requests():
    async with aiosqlite.connect(DB_PATH) as db:
        db.row_factory = aiosqlite.Row
        c = await db.execute("SELECT pr.*, u.username, u.first_name FROM payment_requests pr LEFT JOIN users u ON pr.user_id = u.user_id WHERE pr.status = 'pending' ORDER BY pr.created_at ASC")
        return [dict(r) for r in await c.fetchall()]

async def approve_payment(r_id, admin):
    async with aiosqlite.connect(DB_PATH) as db:
        db.row_factory = aiosqlite.Row
        c = await db.execute("SELECT * FROM payment_requests WHERE id = ? AND status = 'pending'", (r_id,))
        req = await c.fetchone()
        if not req: return None
        req = dict(req)
        await db.execute("UPDATE payment_requests SET status = 'approved', reviewed_at = ? WHERE id = ?", (datetime.now().isoformat(), r_id))
        await db.commit()
    from config import SUBSCRIPTION_PLANS
    p = SUBSCRIPTION_PLANS.get(req["plan_key"])
    s = await activate_subscription(req["user_id"], req["plan_key"], p["duration_days"], req["amount"], admin, f"Req #{r_id}")
    return {**s, "request_id": r_id}

async def reject_payment(r_id, reason=""):
    async with aiosqlite.connect(DB_PATH) as db:
        await db.execute("UPDATE payment_requests SET status = 'rejected', admin_note = ?, reviewed_at = ? WHERE id = ? AND status='pending'", (reason, datetime.now().isoformat(), r_id))
        await db.commit()

async def create_withdraw_request(u, a, c_info):
    async with aiosqlite.connect(DB_PATH) as db:
        c = await db.execute("INSERT INTO withdraw_requests (user_id, amount, card_info, created_at) VALUES (?, ?, ?, ?)", (u, a, c_info, datetime.now().isoformat()))
        await db.execute("UPDATE users SET wallet_balance = wallet_balance - ? WHERE user_id = ?", (a, u)); await db.commit()
        return c.lastrowid

async def get_pending_withdraws():
    async with aiosqlite.connect(DB_PATH) as db:
        db.row_factory = aiosqlite.Row
        c = await db.execute("SELECT w.*, u.username, u.first_name FROM withdraw_requests w LEFT JOIN users u ON w.user_id = u.user_id WHERE w.status = 'pending' ORDER BY w.created_at ASC")
        return [dict(r) for r in await c.fetchall()]

async def process_withdraw(r_id, status):
    async with aiosqlite.connect(DB_PATH) as db:
        db.row_factory = aiosqlite.Row
        c = await db.execute("SELECT * FROM withdraw_requests WHERE id = ?", (r_id,))
        req = await c.fetchone()
        if req:
            await db.execute("UPDATE withdraw_requests SET status = ? WHERE id = ?", (status, r_id))
            if status == "rejected": await db.execute("UPDATE users SET wallet_balance = wallet_balance + ? WHERE user_id = ?", (req["amount"], req["user_id"]))
            await db.commit(); return dict(req)
        return None

# --- توابع مدیریت کدهای تخفیف ---
async def create_discount_code(code: str, percent: int, max_uses: int):
    async with aiosqlite.connect(DB_PATH) as db:
        await db.execute("INSERT OR REPLACE INTO discount_codes (code, percent, max_uses, used_count, created_at) VALUES (?, ?, ?, 0, ?)", (code.upper(), percent, max_uses, datetime.now().isoformat()))
        await db.commit()

async def get_discount_code(code: str) -> dict | None:
    async with aiosqlite.connect(DB_PATH) as db:
        db.row_factory = aiosqlite.Row
        c = await db.execute("SELECT * FROM discount_codes WHERE code = ?", (code.upper(),))
        r = await c.fetchone()
        return dict(r) if r else None

async def use_discount_code(code: str):
    async with aiosqlite.connect(DB_PATH) as db:
        await db.execute("UPDATE discount_codes SET used_count = used_count + 1 WHERE code = ?", (code.upper(),))
        await db.commit()

async def get_all_discount_codes() -> list:
    async with aiosqlite.connect(DB_PATH) as db:
        db.row_factory = aiosqlite.Row
        c = await db.execute("SELECT * FROM discount_codes ORDER BY created_at DESC")
        return [dict(r) for r in await c.fetchall()]

async def add_admin_db(u):
    async with aiosqlite.connect(DB_PATH) as db:
        await db.execute("INSERT OR IGNORE INTO admins (user_id, added_at) VALUES (?, ?)", (u, datetime.now().isoformat())); await db.commit()
async def remove_admin_db(u):
    async with aiosqlite.connect(DB_PATH) as db:
        await db.execute("DELETE FROM admins WHERE user_id = ?", (u,)); await db.commit()
async def get_all_admins():
    async with aiosqlite.connect(DB_PATH) as db:
        db.row_factory = aiosqlite.Row
        c = await db.execute("SELECT * FROM admins"); return [dict(r) for r in await c.fetchall()]
"""

# 2. آپدیت استیت‌ها برای دریافت کد تخفیف
files["states.py"] = """from aiogram.fsm.state import State, StatesGroup
class RegistrationStates(StatesGroup):
    waiting_for_gender = State(); waiting_for_age = State(); waiting_for_height = State(); waiting_for_weight = State()
    waiting_for_neck = State(); waiting_for_waist = State(); waiting_for_activity = State()
    waiting_for_goal = State(); waiting_for_place = State(); waiting_for_injury = State()
class PaymentStates(StatesGroup):
    waiting_for_receipt = State(); waiting_for_discount = State()
class WithdrawStates(StatesGroup): waiting_for_card = State()
class AdminStates(StatesGroup):
    waiting_reject_reason = State(); waiting_manual_user_id = State(); waiting_manual_plan = State()
    waiting_for_new_admin = State(); waiting_for_remove_admin = State()
    waiting_for_broadcast_msg = State()
    waiting_for_discount_code = State(); waiting_for_discount_percent = State(); waiting_for_discount_uses = State()
class AssessmentStates(StatesGroup):
    waiting_for_pushups = State(); waiting_for_squats = State(); waiting_for_plank = State()
"""

# 3. آپدیت کیبوردها
files["keyboards.py"] = """from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardRemove
from config import SUBSCRIPTION_PLANS, ADMIN_USERNAME

def get_main_menu_keyboard(is_premium: bool = False):
    lock = "" if is_premium else "🔒 "
    keyboard = [
        [KeyboardButton(text="🏋️ برنامه ورزشی من"), KeyboardButton(text="💪 ارزیابی قدرت بدنی")],
        [KeyboardButton(text=f"{lock}🥗 برنامه تغذیه"), KeyboardButton(text=f"{lock}🩹 توانبخشی و افزایش قد")],
        [KeyboardButton(text="📊 وضعیت بدن من"), KeyboardButton(text="📖 راهنمای اصطلاحات")],
        [KeyboardButton(text="⭐ اشتراک ویژه" if not is_premium else "⭐ اشتراک من"), KeyboardButton(text="📝 پروفایل و اطلاعات")],
        [KeyboardButton(text="🎁 دعوت و کسب درآمد"), KeyboardButton(text="🛒 تجهیزات ورزشی")],
        [KeyboardButton(text="📞 پشتیبانی")]
    ]
    return ReplyKeyboardMarkup(keyboard=keyboard, resize_keyboard=True, is_persistent=True)

def get_gender_keyboard(): return ReplyKeyboardMarkup(keyboard=[[KeyboardButton(text="👨 آقا / مرد")], [KeyboardButton(text="👩 خانم / زن")]], resize_keyboard=True)
def get_skip_keyboard(): return ReplyKeyboardMarkup(keyboard=[[KeyboardButton(text="⏩ رد کردن")]], resize_keyboard=True, one_time_keyboard=True)
def get_activity_keyboard(): return ReplyKeyboardMarkup(keyboard=[[KeyboardButton(text="🔴 کم")], [KeyboardButton(text="🟡 متوسط")], [KeyboardButton(text="🟢 زیاد")]], resize_keyboard=True)
def get_goal_keyboard(): return ReplyKeyboardMarkup(keyboard=[[KeyboardButton(text="💪 عریض کردن شانه‌ها و فرم مردانه")], [KeyboardButton(text="🔥 چربی‌سوزی و کات")], [KeyboardButton(text="🏋️ افزایش حجم عضله")], [KeyboardButton(text="🧍 اصلاح قوز و فرم بدن")]], resize_keyboard=True)
def get_place_keyboard(): return ReplyKeyboardMarkup(keyboard=[[KeyboardButton(text="🏠 خانه بدون وسیله")], [KeyboardButton(text="🏠🎗 خانه با کش و دمبل")], [KeyboardButton(text="🏋️‍♂️ باشگاه")]], resize_keyboard=True)
def get_injury_keyboard(): return ReplyKeyboardMarkup(keyboard=[[KeyboardButton(text="✅ ندارم")], [KeyboardButton(text="🦴 کمردرد")], [KeyboardButton(text="🦵 زانو درد")], [KeyboardButton(text="💆 گردن‌درد / قوز")], [KeyboardButton(text="🤕 آسیب شانه")]], resize_keyboard=True)

def get_subscription_plans_keyboard():
    buttons = []
    for plan_key, plan in SUBSCRIPTION_PLANS.items():
        badge = f" (-{plan['save_percent']}%)" if plan["save_percent"] > 0 else ""
        if plan_key == "12month": badge += " 🔥"
        buttons.append([InlineKeyboardButton(text=f"{plan['name']} — {plan['price_display']}{badge}", callback_data=f"buy_plan_{plan_key}")])
    buttons.append([InlineKeyboardButton(text="❌ بستن", callback_data="close_menu")])
    return InlineKeyboardMarkup(inline_keyboard=buttons)

def get_payment_keyboard(plan_key: str, can_pay_wallet: bool = False, has_discount: bool = False):
    buttons = []
    if not has_discount:
        buttons.append([InlineKeyboardButton(text="🎟 اعمال کد تخفیف", callback_data=f"apply_discount_{plan_key}")])
    buttons.append([InlineKeyboardButton(text="📸 ارسال رسید واریز کارت", callback_data=f"send_receipt_{plan_key}")])
    if can_pay_wallet:
        buttons.append([InlineKeyboardButton(text="🎁 پرداخت از موجودی کیف پول", callback_data=f"wallet_pay_{plan_key}")])
    buttons.append([InlineKeyboardButton(text="🔙 بازگشت به پلن‌ها", callback_data="subscription")])
    return InlineKeyboardMarkup(inline_keyboard=buttons)

def get_wallet_keyboard(can_withdraw: bool = False):
    buttons = [[InlineKeyboardButton(text="🔗 دریافت لینک دعوت من", callback_data="get_ref_link")]]
    if can_withdraw: buttons.append([InlineKeyboardButton(text="💳 درخواست تسویه حساب", callback_data="req_withdraw")])
    buttons.append([InlineKeyboardButton(text="❌ بستن", callback_data="close_menu")])
    return InlineKeyboardMarkup(inline_keyboard=buttons)

def get_admin_panel_keyboard(is_superadmin: bool = False):
    buttons = [
        [InlineKeyboardButton(text="📊 آمار کلی و مالی", callback_data="admin_stats")],
        [InlineKeyboardButton(text="🎟 مدیریت کدهای تخفیف", callback_data="admin_discounts")],
        [InlineKeyboardButton(text="💳 تسویه حساب‌ها", callback_data="admin_withdraws"), InlineKeyboardButton(text="📋 فیش‌های واریزی", callback_data="admin_pending")],
        [InlineKeyboardButton(text="📢 ارسال پیام همگانی", callback_data="admin_broadcast")]
    ]
    if is_superadmin:
        buttons.append([InlineKeyboardButton(text="👮‍♂️ مدیریت ادمین‌ها", callback_data="admin_manage_admins")])
    buttons.append([InlineKeyboardButton(text="❌ بستن پنل", callback_data="close_menu")])
    return InlineKeyboardMarkup(inline_keyboard=buttons)

def get_discount_admin_keyboard():
    return InlineKeyboardMarkup(inline_keyboard=[
        [InlineKeyboardButton(text="➕ ساخت کد تخفیف جدید", callback_data="admin_create_discount")],
        [InlineKeyboardButton(text="📋 لیست کدهای فعال", callback_data="admin_list_discounts")],
        [InlineKeyboardButton(text="🔙 بازگشت به پنل", callback_data="back_to_admin_main")]
    ])

def get_broadcast_confirm_keyboard(): return InlineKeyboardMarkup(inline_keyboard=[[InlineKeyboardButton(text="✅ بله، ارسال کن", callback_data="confirm_broadcast")], [InlineKeyboardButton(text="❌ لغو", callback_data="cancel_broadcast")]])
def get_manage_admins_keyboard(): return InlineKeyboardMarkup(inline_keyboard=[[InlineKeyboardButton(text="➕ افزودن ادمین جدید", callback_data="admin_add_admin")], [InlineKeyboardButton(text="📋 لیست ادمین‌ها", callback_data="admin_list_admins")], [InlineKeyboardButton(text="➖ حذف ادمین", callback_data="admin_remove_admin")], [InlineKeyboardButton(text="🔙 بازگشت به پنل", callback_data="back_to_admin_main")]])
def get_payment_review_keyboard(request_id: int): return InlineKeyboardMarkup(inline_keyboard=[[InlineKeyboardButton(text="✅ تأیید", callback_data=f"admin_approve_{request_id}"), InlineKeyboardButton(text="❌ رد", callback_data=f"admin_reject_{request_id}")]])
def get_withdraw_review_keyboard(request_id: int): return InlineKeyboardMarkup(inline_keyboard=[[InlineKeyboardButton(text="✅ پرداخت شد", callback_data=f"admin_w_approve_{request_id}"), InlineKeyboardButton(text="❌ رد درخواست", callback_data=f"admin_w_reject_{request_id}")]])
def get_week_selector_keyboard(is_premium: bool = False):
    lock = "" if is_premium else "🔒 "
    return InlineKeyboardMarkup(inline_keyboard=[[InlineKeyboardButton(text="🆓 فاز ۱ (هفته ۱-۲) — رایگان", callback_data="week_1")], [InlineKeyboardButton(text=f"{lock}فاز ۲ (هفته ۳-۴) — حجم", callback_data="week_2" if is_premium else "need_premium")], [InlineKeyboardButton(text=f"{lock}فاز ۳ (هفته ۵-۶) — قدرت", callback_data="week_3" if is_premium else "need_premium")], [InlineKeyboardButton(text=f"{lock}فاز ۴ (هفته ۷-۸) — چالش", callback_data="week_4" if is_premium else "need_premium")], [InlineKeyboardButton(text="❌ بستن", callback_data="close_menu")]])
def get_exercise_buttons(exercise_ids: list[str], is_premium: bool = False):
    from data.exercises import EXERCISES_DB
    from config import FREE_EXERCISE_IDS
    buttons = []
    for ex_id in exercise_ids:
        ex = EXERCISES_DB.get(ex_id)
        if not ex: continue
        is_free = ex_id in FREE_EXERCISE_IDS
        if is_free or is_premium: buttons.append([InlineKeyboardButton(text=f"🎬 {ex['name_fa']}", callback_data=f"exercise_{ex_id}")])
        else: buttons.append([InlineKeyboardButton(text=f"🔒 {ex['name_fa']} (ویژه)", callback_data=f"locked_exercise_{ex_id}")])
    buttons.append([InlineKeyboardButton(text="🔙 بازگشت به فازها", callback_data="my_workout")])
    return InlineKeyboardMarkup(inline_keyboard=buttons)
def get_premium_required_keyboard(): return InlineKeyboardMarkup(inline_keyboard=[[InlineKeyboardButton(text="⭐ خرید اشتراک", callback_data="subscription")], [InlineKeyboardButton(text="❌ متوجه شدم", callback_data="close_menu")]])
def get_products_keyboard():
    from config import ADMIN_USERNAME
    return InlineKeyboardMarkup(inline_keyboard=[[InlineKeyboardButton(text="🎗 کش مقاومتی حلقه‌ای", callback_data="product_band")], [InlineKeyboardButton(text="🏋️ دمبل قابل تنظیم", callback_data="product_dumbbell")], [InlineKeyboardButton(text="🧱 مت یوگا ضخیم", callback_data="product_mat")], [InlineKeyboardButton(text="🤸 بارفیکس درب‌نصب", callback_data="product_pullup_bar")], [InlineKeyboardButton(text="📩 استعلام قیمت و خرید", url=f"https://t.me/{ADMIN_USERNAME}")], [InlineKeyboardButton(text="❌ بستن", callback_data="close_menu")]])
"""

# 4. آپدیت خرید اشتراک (پردازش کد تخفیف)
files["handlers/subscription.py"] = """from aiogram import Router, F, Bot
from aiogram.types import Message, CallbackQuery
from aiogram.fsm.context import FSMContext
from states import PaymentStates
from keyboards import get_subscription_plans_keyboard, get_payment_keyboard
from config import SUBSCRIPTION_PLANS, PAYMENT_CARD_NUMBER, PAYMENT_CARD_OWNER
from database import create_payment_request, get_user, activate_subscription, add_wallet_balance, get_discount_code, use_discount_code
from utils.subscription_utils import is_premium_user, get_subscription_info

router = Router()

@router.message(F.text.contains("اشتراک"))
async def show_sub_msg(message: Message):
    premium = await is_premium_user(message.from_user.id)
    if premium:
        sub_info = await get_subscription_info(message.from_user.id)
        text = f"⭐ <b>اشتراک VIP شما فعال است</b>\\n\\n⏳ روزهای باقی‌مانده: <b>{sub_info['remaining_days']} روز</b>\\n📅 تاریخ پایان: {sub_info['end_date_jalali']}"
    else:
        text = "⭐ <b>خرید اشتراک مربیگری</b>\\n\\nبا تهیه اشتراک، ربات تبدیل به مربی شخصی شما می‌شود!\\n👇 یکی از پلن‌های اقتصادی زیر را انتخاب کنید:"
    await message.answer(text, parse_mode="HTML", reply_markup=get_subscription_plans_keyboard())

@router.callback_query(F.data == "subscription")
async def sub_callback(callback: CallbackQuery):
    await show_sub_msg(callback.message)
    await callback.message.delete()

@router.callback_query(F.data.startswith("buy_plan_"))
async def buy_plan(callback: CallbackQuery, state: FSMContext):
    plan_key = callback.data.replace("buy_plan_", "")
    plan = SUBSCRIPTION_PLANS.get(plan_key)
    if not plan: return
    await state.update_data(selected_plan=plan_key, current_price=plan['price'])
    
    user = await get_user(callback.from_user.id)
    bal = user.get('wallet_balance', 0) if user else 0
    can_pay_wallet = bal >= plan['price']

    text = f"💳 <b>درخواست خرید {plan['name']}</b>\\n\\n💰 مبلغ قابل پرداخت: <b>{plan['price_display']}</b>\\n\\n💳 شماره کارت:\\n<code>{PAYMENT_CARD_NUMBER}</code>\\n👤 به نام: {PAYMENT_CARD_OWNER}\\n\\n👇 پس از کارت‌به‌کارت، دکمه ارسال رسید را بزنید."
    if can_pay_wallet:
        text += f"\\n\\n🎁 <b>موجودی کیف پول شما کافیست ({bal:,} تومان). می‌توانید مستقیماً از کیف پول پرداخت کنید!</b>"

    await callback.message.edit_text(text, parse_mode="HTML", reply_markup=get_payment_keyboard(plan_key, can_pay_wallet, has_discount=False))

# زدن دکمه اعمال کد تخفیف
@router.callback_query(F.data.startswith("apply_discount_"))
async def prompt_discount(callback: CallbackQuery, state: FSMContext):
    await callback.message.edit_text("🎟 <b>کد تخفیف خود را وارد کنید:</b>", parse_mode="HTML")
    await state.set_state(PaymentStates.waiting_for_discount)

@router.message(PaymentStates.waiting_for_discount)
async def process_discount(message: Message, state: FSMContext):
    code_text = message.text.strip().upper()
    discount = await get_discount_code(code_text)
    
    if not discount or discount['used_count'] >= discount['max_uses']:
        await message.answer("❌ کد تخفیف نامعتبر است یا ظرفیت آن به پایان رسیده.")
        return
        
    data = await state.get_data()
    plan_key = data.get("selected_plan", "1month")
    plan = SUBSCRIPTION_PLANS.get(plan_key)
    
    orig_price = plan['price']
    percent = discount['percent']
    new_price = int(orig_price * (100 - percent) / 100)
    
    await state.update_data(current_price=new_price, applied_code=code_text)
    
    user = await get_user(message.from_user.id)
    bal = user.get('wallet_balance', 0) if user else 0
    can_pay_wallet = bal >= new_price

    text = f"🎉 <b>کد تخفیف {percent}% با موفقیت اعمال شد!</b>\\n\\n<s>مبلغ قبلی: {orig_price:,} تومان</s>\\n💰 <b>مبلغ نهایی با تخفیف: {new_price:,} تومان</b>\\n\\n💳 شماره کارت:\\n<code>{PAYMENT_CARD_NUMBER}</code>\\n👤 به نام: {PAYMENT_CARD_OWNER}\\n\\n👇 دکمه ارسال رسید را بزنید."
    if can_pay_wallet:
        text += f"\\n\\n🎁 <b>موجودی کیف پول شما برای این مبلغ کافیست!</b>"
        
    await message.answer(text, parse_mode="HTML", reply_markup=get_payment_keyboard(plan_key, can_pay_wallet, has_discount=True))

@router.callback_query(F.data.startswith("wallet_pay_"))
async def wallet_pay(callback: CallbackQuery, state: FSMContext):
    plan_key = callback.data.replace("wallet_pay_", "")
    plan = SUBSCRIPTION_PLANS.get(plan_key)
    data = await state.get_data()
    price = data.get("current_price", plan['price'])
    
    user = await get_user(callback.from_user.id)
    if user.get('wallet_balance', 0) < price:
        await callback.answer("موجودی کافی نیست!", show_alert=True)
        return
        
    applied_code = data.get("applied_code")
    if applied_code:
        await use_discount_code(applied_code)
        
    await add_wallet_balance(callback.from_user.id, -price)
    await activate_subscription(callback.from_user.id, plan_key, plan['duration_days'], price, callback.from_user.id, "Wallet Pay")
    await callback.message.edit_text("🎉 <b>پرداخت موفق! اشتراک شما فعال شد.</b>", parse_mode="HTML")
    await callback.answer()
    await state.clear()

@router.callback_query(F.data.startswith("send_receipt_"))
async def req_receipt(callback: CallbackQuery, state: FSMContext):
    await callback.message.edit_text("📸 لطفاً عکس فیش واریزی را بفرستید:")
    await state.set_state(PaymentStates.waiting_for_receipt)

@router.message(PaymentStates.waiting_for_receipt)
async def process_receipt(message: Message, state: FSMContext, bot: Bot):
    file_id = message.photo[-1].file_id if message.photo else (message.document.file_id if message.document else None)
    if not file_id: return
    data = await state.get_data()
    plan_key = data.get("selected_plan", "1month")
    plan = SUBSCRIPTION_PLANS.get(plan_key, SUBSCRIPTION_PLANS["1month"])
    price = data.get("current_price", plan['price'])
    applied_code = data.get("applied_code")
    
    if applied_code:
        await use_discount_code(applied_code)
        
    req_id = await create_payment_request(message.from_user.id, plan_key, price, file_id)
    
    from keyboards import get_payment_review_keyboard
    from utils.admin_utils import notify_all_admins
    admin_msg = f"🔔 <b>رسید جدید #{req_id}</b>\\n👤 @{message.from_user.username}\\n📋 {plan['name']} (مبلغ: {price:,} تومان)"
    await notify_all_admins(bot, admin_msg, reply_markup=get_payment_review_keyboard(req_id), photo=file_id if message.photo else None, document=file_id if message.document else None)
    
    await message.answer("✅ رسید شما ارسال شد.")
    await state.clear()
"""

# 5. آپدیت پنل ادمین (مدیریت کدهای تخفیف)
files["handlers/admin.py"] = """from aiogram import Router, F, Bot
from aiogram.types import Message, CallbackQuery
from aiogram.filters import Command
from aiogram.fsm.context import FSMContext
import asyncio
from config import ADMIN_ID, SUBSCRIPTION_PLANS, REFERRAL_REWARD
from keyboards import get_admin_panel_keyboard, get_payment_review_keyboard, get_withdraw_review_keyboard, get_discount_admin_keyboard
from database import get_subscription_stats, get_pending_requests, approve_payment, reject_payment, get_pending_withdraws, process_withdraw, add_admin_db, remove_admin_db, get_all_admins, get_user, get_all_starters, create_discount_code, get_all_discount_codes
from utils.admin_utils import is_admin, is_super_admin
from states import AdminStates

router = Router()

@router.message(Command("admin"))
async def cmd_admin(message: Message):
    if not await is_admin(message.from_user.id): return
    super_admin = await is_super_admin(message.from_user.id)
    stats = await get_subscription_stats()
    text = f"🔧 <b>پنل مدیریت ربات</b>\\n\\n👥 کل افرادی که استارت زدند: <b>{stats['total_starts']} نفر</b>\\n📝 افرادی که فرم پر کردند: <b>{stats['registered_users']} نفر</b>\\n⭐ اشتراک‌های فعال: <b>{stats['active_subs']}</b>\\n\\n📋 فیش‌های در انتظار: <b>{stats['pending_requests']}</b>\\n💳 درخواست‌های تسویه: <b>{stats['pending_withdraws']}</b>"
    await message.answer(text, parse_mode="HTML", reply_markup=get_admin_panel_keyboard(is_superadmin=super_admin))

@router.callback_query(F.data == "back_to_admin_main")
async def back_to_admin_main(callback: CallbackQuery):
    if not await is_admin(callback.from_user.id): return
    super_admin = await is_super_admin(callback.from_user.id)
    stats = await get_subscription_stats()
    text = f"🔧 <b>پنل مدیریت ربات</b>\\n\\n👥 کل افرادی که استارت زدند: <b>{stats['total_starts']} نفر</b>\\n📝 افرادی که فرم پر کردند: <b>{stats['registered_users']} نفر</b>\\n⭐ اشتراک‌های فعال: <b>{stats['active_subs']}</b>\\n\\n📋 فیش‌های در انتظار: <b>{stats['pending_requests']}</b>\\n💳 درخواست‌های تسویه: <b>{stats['pending_withdraws']}</b>"
    await callback.message.edit_text(text, parse_mode="HTML", reply_markup=get_admin_panel_keyboard(is_superadmin=super_admin))

# --- مدیریت کدهای تخفیف ---
@router.callback_query(F.data == "admin_discounts")
async def discounts_menu(callback: CallbackQuery):
    if not await is_admin(callback.from_user.id): return
    await callback.message.edit_text("🎟 <b>مدیریت کدهای تخفیف</b>\\n\\nاز این بخش می‌توانید کد تخفیف جدید برای کمپین‌های تبلیغاتی بسازید.", parse_mode="HTML", reply_markup=get_discount_admin_keyboard())

@router.callback_query(F.data == "admin_create_discount")
async def start_create_discount(callback: CallbackQuery, state: FSMContext):
    if not await is_admin(callback.from_user.id): return
    await callback.message.edit_text("🎟 <b>ساخت کد تخفیف جدید</b>\\n\\nلطفاً <b>نام کد تخفیف</b> را بفرستید:\\n<i>(مثال: OFF50 یا FIRST14)</i>", parse_mode="HTML")
    await state.set_state(AdminStates.waiting_for_discount_code)

@router.message(AdminStates.waiting_for_discount_code)
async def proc_code_name(message: Message, state: FSMContext):
    if not await is_admin(message.from_user.id): return
    code = message.text.strip().upper()
    await state.update_data(new_code=code)
    await message.answer(f"کد: <b>{code}</b>\\n\\nحالا <b>درصد تخفیف</b> را به عدد بفرستید (مثلاً 50 یعنی ۵۰ درصد):", parse_mode="HTML")
    await state.set_state(AdminStates.waiting_for_discount_percent)

@router.message(AdminStates.waiting_for_discount_percent)
async def proc_code_percent(message: Message, state: FSMContext):
    if not await is_admin(message.from_user.id): return
    try: percent = int(message.text.strip())
    except:
        await message.answer("⚠️ لطفاً یک عدد بفرستید (مثلاً 30).")
        return
    await state.update_data(new_percent=percent)
    await message.answer("حالا <b>تعداد ظرفیت استفاده (چند نفر بخرن؟)</b> را بفرستید:\\n<i>(مثلاً 1 یعنی یکبارمصرف، 14 یعنی ۱۴ نفر اول)</i>:", parse_mode="HTML")
    await state.set_state(AdminStates.waiting_for_discount_uses)

@router.message(AdminStates.waiting_for_discount_uses)
async def proc_code_uses(message: Message, state: FSMContext):
    if not await is_admin(message.from_user.id): return
    try: uses = int(message.text.strip())
    except:
        await message.answer("⚠️ لطفاً یک عدد بفرستید.")
        return
    data = await state.get_data()
    code = data['new_code']
    percent = data['new_percent']
    
    await create_discount_code(code, percent, uses)
    await state.clear()
    
    await message.answer(f"🎉 <b>کد تخفیف با موفقیت ساخته شد!</b>\\n\\n🎟 کد: <code>{code}</code>\\n🎁 تخفیف: <b>{percent}%</b>\\n👥 ظرفیت: <b>{uses} نفر</b>", parse_mode="HTML", reply_markup=get_discount_admin_keyboard())

@router.callback_query(F.data == "admin_list_discounts")
async def list_discounts(callback: CallbackQuery):
    if not await is_admin(callback.from_user.id): return
    codes = await get_all_discount_codes()
    if not codes:
        text = "📋 هیچ کد تخفیف فعالی وجود ندارد."
    else:
        text = "📋 <b>لیست کدهای تخفیف:</b>\\n\\n"
        for c in codes:
            text += f"🎟 <code>{c['code']}</code> | <b>{c['percent']}%</b> | استفاده شده: {c['used_count']}/{c['max_uses']}\\n"
    await callback.message.edit_text(text, parse_mode="HTML", reply_markup=get_discount_admin_keyboard())

# --- آمار و پیام همگانی ---
@router.callback_query(F.data == "admin_stats")
async def show_stats(callback: CallbackQuery):
    if not await is_admin(callback.from_user.id): return
    stats = await get_subscription_stats()
    text = f"📊 <b>آمار کامل و مالی</b>\\n\\n👥 کل استارت‌ها: {stats['total_starts']}\\n📝 پروفایل تکمیل شده: {stats['registered_users']}\\n⭐ اشتراک‌های فعال: {stats['active_subs']}\\n\\n💰 درآمد کل سیستم: {stats['total_revenue']:,} تومان\\n\\n📋 منتظر تایید: {stats['pending_requests']}\\n💳 منتظر تسویه: {stats['pending_withdraws']}"
    super_admin = await is_super_admin(callback.from_user.id)
    await callback.message.edit_text(text, parse_mode="HTML", reply_markup=get_admin_panel_keyboard(is_superadmin=super_admin))

@router.callback_query(F.data == "admin_broadcast")
async def start_broadcast(callback: CallbackQuery, state: FSMContext):
    if not await is_admin(callback.from_user.id): return
    await callback.message.edit_text("📢 <b>ارسال پیام همگانی</b>\\n\\nپیام خود را بفرستید:", parse_mode="HTML")
    await state.set_state(AdminStates.waiting_for_broadcast_msg)

@router.message(AdminStates.waiting_for_broadcast_msg)
async def confirm_broadcast(message: Message, state: FSMContext):
    if not await is_admin(message.from_user.id): return
    await state.update_data(broadcast_msg_id=message.message_id)
    from keyboards import get_broadcast_confirm_keyboard
    await message.reply("ارسال به تمام اعضا تایید می‌شود؟", reply_markup=get_broadcast_confirm_keyboard())

@router.callback_query(F.data == "cancel_broadcast")
async def cancel_broadcast(callback: CallbackQuery, state: FSMContext):
    await state.clear()
    await callback.message.edit_text("❌ لغو شد.")

@router.callback_query(F.data == "confirm_broadcast")
async def execute_broadcast(callback: CallbackQuery, state: FSMContext, bot: Bot):
    if not await is_admin(callback.from_user.id): return
    data = await state.get_data()
    msg_id = data.get("broadcast_msg_id")
    await state.clear()
    if not msg_id: return
    users = await get_all_starters()
    await callback.message.edit_text(f"⏳ در حال ارسال به {len(users)} نفر...")
    success = 0
    import asyncio
    for uid in users:
        try:
            await bot.copy_message(chat_id=uid, from_chat_id=callback.from_user.id, message_id=msg_id)
            success += 1
            await asyncio.sleep(0.05)
        except: pass
    await callback.message.reply(f"✅ پیام به {success} نفر ارسال شد.")

# --- بقیه هندلرها (تأیید فیش و تسویه) ---
@router.callback_query(F.data == "admin_manage_admins")
async def manage_admins_menu(callback: CallbackQuery):
    if not await is_super_admin(callback.from_user.id): return
    from keyboards import get_manage_admins_keyboard
    await callback.message.edit_text("👮‍♂️ <b>مدیریت ادمین‌ها</b>", parse_mode="HTML", reply_markup=get_manage_admins_keyboard())

@router.callback_query(F.data == "admin_add_admin")
async def add_admin_btn(callback: CallbackQuery, state: FSMContext):
    if not await is_super_admin(callback.from_user.id): return
    await callback.message.edit_text("➕ آیدی عددی را بفرستید:", parse_mode="HTML")
    await state.set_state(AdminStates.waiting_for_new_admin)

@router.message(AdminStates.waiting_for_new_admin)
async def process_new_admin(message: Message, state: FSMContext):
    if not await is_super_admin(message.from_user.id): return
    if message.text and message.text.isdigit():
        await add_admin_db(int(message.text))
        from keyboards import get_manage_admins_keyboard
        await message.answer("✅ ادمین اضافه شد.", reply_markup=get_manage_admins_keyboard())
    await state.clear()

@router.callback_query(F.data == "admin_list_admins")
async def list_admins_btn(callback: CallbackQuery):
    if not await is_super_admin(callback.from_user.id): return
    admins = await get_all_admins()
    text = "📋 <b>لیست ادمین‌ها:</b>\\n\\n" + "\\n".join([f"👤 {a['user_id']}" for a in admins]) if admins else "خالی"
    from keyboards import get_manage_admins_keyboard
    await callback.message.edit_text(text, parse_mode="HTML", reply_markup=get_manage_admins_keyboard())

@router.callback_query(F.data == "admin_remove_admin")
async def remove_admin_btn(callback: CallbackQuery, state: FSMContext):
    if not await is_super_admin(callback.from_user.id): return
    await callback.message.edit_text("➖ آیدی عددی را بفرستید:", parse_mode="HTML")
    await state.set_state(AdminStates.waiting_for_remove_admin)

@router.message(AdminStates.waiting_for_remove_admin)
async def process_remove_admin(message: Message, state: FSMContext):
    if not await is_super_admin(message.from_user.id): return
    if message.text and message.text.isdigit():
        await remove_admin_db(int(message.text))
        from keyboards import get_manage_admins_keyboard
        await message.answer("✅ حذف شد.", reply_markup=get_manage_admins_keyboard())
    await state.clear()

@router.message(F.animation | F.video | F.sticker | F.document)
async def get_file_id_handler(message: Message):
    if not await is_admin(message.from_user.id): return
    file_id = message.animation.file_id if message.animation else (message.video.file_id if message.video else (message.sticker.file_id if message.sticker else message.document.file_id))
    await message.reply(f"🎬 <b>شناسه فایل:</b>\\n\\n<code>{file_id}</code>", parse_mode="HTML")

@router.callback_query(F.data == "admin_pending")
async def admin_pending(callback: CallbackQuery):
    if not await is_admin(callback.from_user.id): return
    reqs = await get_pending_requests()
    if not reqs:
        await callback.message.edit_text("✅ درخواست فیش جدیدی نیست.", reply_markup=get_admin_panel_keyboard(await is_super_admin(callback.from_user.id)))
        return
    r = reqs[0]
    p = SUBSCRIPTION_PLANS.get(r["plan_key"], {})
    await callback.message.edit_text(f"📋 <b>رسید #{r['id']}</b>\\n👤 @{r.get('username')}\\n💰 {p.get('price_display')}", parse_mode="HTML", reply_markup=get_payment_review_keyboard(r['id']))

@router.callback_query(F.data == "admin_withdraws")
async def admin_withdraws(callback: CallbackQuery):
    if not await is_admin(callback.from_user.id): return
    reqs = await get_pending_withdraws()
    if not reqs:
        await callback.message.edit_text("✅ درخواست تسویه جدیدی نیست.", reply_markup=get_admin_panel_keyboard(await is_super_admin(callback.from_user.id)))
        return
    r = reqs[0]
    await callback.message.edit_text(f"💳 <b>تسویه #{r['id']}</b>\\n👤 ID: {r['user_id']}\\n💰 مبلغ: {r['amount']:,} تومان\\n💳 کارت: <code>{r['card_info']}</code>", parse_mode="HTML", reply_markup=get_withdraw_review_keyboard(r['id']))

@router.callback_query(F.data.startswith("admin_approve_"))
async def admin_approve(callback: CallbackQuery, bot: Bot):
    if not await is_admin(callback.from_user.id): return
    req_id = int(callback.data.replace("admin_approve_", ""))
    res = await approve_payment(req_id, callback.from_user.id)
    if res:
        await callback.message.edit_text(f"✅ درخواست #{req_id} تایید شد.", reply_markup=get_admin_panel_keyboard(await is_super_admin(callback.from_user.id)))
        try: await bot.send_message(res["user_id"], "🎉 <b>اشتراک شما فعال شد!</b>", parse_mode="HTML")
        except: pass

@router.callback_query(F.data.startswith("admin_reject_"))
async def admin_reject(callback: CallbackQuery):
    if not await is_admin(callback.from_user.id): return
    req_id = int(callback.data.replace("admin_reject_", ""))
    await reject_payment(req_id)
    await callback.message.edit_text(f"❌ درخواست #{req_id} رد شد.", reply_markup=get_admin_panel_keyboard(await is_super_admin(callback.from_user.id)))

@router.callback_query(F.data.startswith("admin_w_approve_"))
async def w_approve(callback: CallbackQuery, bot: Bot):
    if not await is_admin(callback.from_user.id): return
    req_id = int(callback.data.replace("admin_w_approve_", ""))
    res = await process_withdraw(req_id, "approved")
    if res:
        await callback.message.edit_text(f"✅ تسویه #{req_id} انجام شد.", reply_markup=get_admin_panel_keyboard(await is_super_admin(callback.from_user.id)))
        try: await bot.send_message(res["user_id"], f"💳 مبلغ {res['amount']:,} تومان به حساب شما واریز شد!", parse_mode="HTML")
        except: pass

@router.callback_query(F.data.startswith("admin_w_reject_"))
async def w_reject(callback: CallbackQuery, bot: Bot):
    if not await is_admin(callback.from_user.id): return
    req_id = int(callback.data.replace("admin_w_reject_", ""))
    res = await process_withdraw(req_id, "rejected")
    if res:
        await callback.message.edit_text(f"❌ تسویه #{req_id} رد شد.", reply_markup=get_admin_panel_keyboard(await is_super_admin(callback.from_user.id)))
        try: await bot.send_message(res["user_id"], f"❌ درخواست تسویه شما رد شد و {res['amount']:,} تومان به کیف پولتان برگشت.", parse_mode="HTML")
        except: pass
"""

for path, content in files.items():
    with open(path, "w", encoding="utf-8") as f: f.write(content)
print("✅ سیستم مدیریت کدهای تخفیف با موفقیت اضافه شد!")
