import os
import re
import json
import math
import sqlite3
import logging
import asyncio
from datetime import datetime, timezone
from decimal import Decimal, ROUND_HALF_UP

import httpx
from dotenv import load_dotenv

from telegram import (
    Update,
    InlineKeyboardButton,
    InlineKeyboardMarkup,
    ReplyKeyboardMarkup,
    KeyboardButton,
    ReplyKeyboardRemove,
)
from telegram.constants import ParseMode
from telegram.ext import (
    Application,
    CommandHandler,
    CallbackQueryHandler,
    MessageHandler,
    ContextTypes,
    filters,
)

# ============================================================
# CONFIGURATION
# ============================================================

load_dotenv()

BOT_TOKEN = os.getenv("BOT_TOKEN", "")
OWNER_ID = int(os.getenv("OWNER_ID", "0"))

ADMIN_IDS = {
    int(x.strip())
    for x in os.getenv("ADMIN_IDS", "").split(",")
    if x.strip().isdigit()
}
ADMIN_IDS.add(OWNER_ID)

SHOP_CHANNEL = os.getenv("SHOP_CHANNEL", "inscription_shop").lstrip("@")
TRUST_CHANNEL = os.getenv("TRUST_CHANNEL", "inscription_trust").lstrip("@")
TRUST_CHANNEL_ID = os.getenv(
    "TRUST_CHANNEL_ID", "@inscription_trust"
)

ADMIN_GROUP_ID = os.getenv("ADMIN_GROUP_ID", "").strip()

BANK_CARD_NUMBER = os.getenv("BANK_CARD_NUMBER", "")
BANK_CARD_NAME = os.getenv("BANK_CARD_NAME", "")
BANK_NAME = os.getenv("BANK_NAME", "")

FX_API_URL = (
    os.getenv("FX_API_URL", "").strip()
    or "https://nerkhara.com/api/v1/latest/usd.json"
)
FX_API_KEY = os.getenv("FX_API_KEY", "")

FALLBACK_USD_TOMAN = Decimal(
    os.getenv("FALLBACK_USD_TOMAN", "120000")
)

DATABASE_PATH = os.getenv(
    "DATABASE_PATH", "inscription_shop.db"
)

REFERRAL_REWARD = int(os.getenv("REFERRAL_REWARD", "0"))
SUPPORT_USERNAME = os.getenv(
    "SUPPORT_USERNAME", "@your_support"
)

FX_UPDATE_SECONDS = max(
    30, int(os.getenv("FX_UPDATE_SECONDS", "120"))
)

# ============================================================
# LOGGING
# ============================================================

logging.basicConfig(
    format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
    level=logging.INFO,
)

logger = logging.getLogger("InscriptionShop")

# ============================================================
# PRODUCTS
# Base costs are USD. Do not change these through the panel.
# ============================================================

PRODUCTS = {
    "stars_50": {
        "name": "۵۰ استارز",
        "category": "stars",
        "usd": Decimal("0.75"),
    },
    "stars_100": {
        "name": "۱۰۰ استارز",
        "category": "stars",
        "usd": Decimal("1.50"),
    },
    "stars_150": {
        "name": "۱۵۰ استارز",
        "category": "stars",
        "usd": Decimal("2.25"),
    },
    "stars_200": {
        "name": "۲۰۰ استارز",
        "category": "stars",
        "usd": Decimal("3.00"),
    },
    "premium_3": {
        "name": "پریمیوم ۳ ماهه",
        "category": "premium",
        "usd": Decimal("12"),
    },
    "premium_6": {
        "name": "پریمیوم ۶ ماهه",
        "category": "premium",
        "usd": Decimal("16"),
    },
    "premium_12": {
        "name": "پریمیوم ۱۲ ماهه",
        "category": "premium",
        "usd": Decimal("29"),
    },
}

STAR_USD_COST = Decimal("0.015")

# Gifts are dynamically retrieved from Telegram.
# If unavailable, gift orders can still be handled manually.
GIFTS_CACHE = []

USD_TOMAN = FALLBACK_USD_TOMAN
LAST_FX_UPDATE = None

# ============================================================
# DATABASE
# ============================================================

db = sqlite3.connect(DATABASE_PATH, check_same_thread=False)
db.row_factory = sqlite3.Row

def init_db():
    db.executescript("""
    CREATE TABLE IF NOT EXISTS users (
        user_id INTEGER PRIMARY KEY,
        username TEXT,
        first_name TEXT,
        phone TEXT,
        verified INTEGER DEFAULT 0,
        referred_by INTEGER,
        created_at TEXT
    );

    CREATE TABLE IF NOT EXISTS orders (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        user_id INTEGER,
        product TEXT,
        product_name TEXT,
        target TEXT,
        quantity INTEGER DEFAULT 0,
        usd_cost TEXT,
        base_toman INTEGER,
        profit_type TEXT,
        profit_value TEXT,
        final_price INTEGER,
        status TEXT DEFAULT 'PENDING_PAYMENT',
        receipt_file_id TEXT,
        created_at TEXT,
        paid_at TEXT,
        delivered_at TEXT,
        reviewed_by INTEGER
    );

    CREATE TABLE IF NOT EXISTS settings (
        key TEXT PRIMARY KEY,
        value TEXT
    );

    CREATE TABLE IF NOT EXISTS referrals (
        user_id INTEGER PRIMARY KEY,
        referrer_id INTEGER,
        reward_paid INTEGER DEFAULT 0
    );
    """)

    db.commit()

def db_get_setting(key, default=None):
    row = db.execute(
        "SELECT value FROM settings WHERE key=?", (key,)
    ).fetchone()
    return row["value"] if row else default

def db_set_setting(key, value):
    db.execute(
        "INSERT OR REPLACE INTO settings(key,value) VALUES(?,?)",
        (key, str(value)),
    )
    db.commit()

def get_admin_ids():
    extra = db_get_setting("extra_admins", "")
    result = set(ADMIN_IDS)
    for item in extra.split(","):
        if item.strip().isdigit():
            result.add(int(item.strip()))
    return result

def is_admin(user_id):
    return user_id in get_admin_ids()

def get_user(user_id):
    return db.execute(
        "SELECT * FROM users WHERE user_id=?", (user_id,)
    ).fetchone()

def save_user(user):
    existing = get_user(user.id)

    if existing:
        db.execute("""
            UPDATE users
            SET username=?, first_name=?
            WHERE user_id=?
        """, (user.username, user.first_name, user.id))
    else:
        db.execute("""
            INSERT INTO users(
                user_id, username, first_name, created_at
            ) VALUES(?,?,?,?)
        """, (
            user.id,
            user.username,
            user.first_name,
            datetime.now(timezone.utc).isoformat(),
        ))

    db.commit()

def set_verified(user_id, phone):
    db.execute("""
        UPDATE users SET verified=1, phone=?
        WHERE user_id=?
    """, (phone, user_id))
    db.commit()

def create_order(
    user_id,
    product,
    product_name,
    target,
    quantity,
    usd_cost,
    base_toman,
    profit_type,
    profit_value,
    final_price,
):
    cur = db.execute("""
        INSERT INTO orders(
            user_id, product, product_name, target, quantity,
            usd_cost, base_toman, profit_type, profit_value,
            final_price, status, created_at
        )
        VALUES(?,?,?,?,?,?,?,?,?,?,?,?)
    """, (
        user_id,
        product,
        product_name,
        target,
        quantity,
        str(usd_cost),
        base_toman,
        profit_type,
        str(profit_value),
        final_price,
        "PENDING_PAYMENT",
        datetime.now(timezone.utc).isoformat(),
    ))

    db.commit()
    return cur.lastrowid

def get_order(order_id):
    return db.execute(
        "SELECT * FROM orders WHERE id=?", (order_id,)
    ).fetchone()

def update_order(order_id, **fields):
    allowed = {
        "status",
        "receipt_file_id",
        "paid_at",
        "delivered_at",
        "reviewed_by",
    }

    fields = {
        k: v for k, v in fields.items() if k in allowed
    }

    if not fields:
        return

    assignments = ", ".join(
        f"{key}=?" for key in fields
    )
    values = list(fields.values()) + [order_id]

    db.execute(
        f"UPDATE orders SET {assignments} WHERE id=?",
        values,
    )
    db.commit()

# ============================================================
# PRICING
# ============================================================

def get_profit(product):
    profit_type = db_get_setting(
        f"profit_type_{product}", "percent"
    )
    profit_value = Decimal(
        db_get_setting(f"profit_value_{product}", "20")
    )
    return profit_type, profit_value

def calculate_price(usd_cost, product):
    base = int(
        (Decimal(str(usd_cost)) * USD_TOMAN).quantize(
            Decimal("1"), rounding=ROUND_HALF_UP
        )
    )

    profit_type, profit_value = get_profit(product)

    if profit_type == "percent":
        profit = int(
            (Decimal(base) * profit_value / 100).quantize(
                Decimal("1"), rounding=ROUND_HALF_UP
            )
        )
    else:
        profit = int(profit_value)

    return base, max(0, base + profit)

def toman(number):
    return f"{int(number):,}"

# ============================================================
# EXCHANGE RATE
#
# Expected API response:
# {"usd": 120000}
#
# Or:
# {"price": 120000}
#
# Or:
# {"result": {"usd": 120000}}
#
# Values must be in TOMAN, not RIAL.
# ============================================================

def extract_rate(data):
    """Read NerkhAra's USD/IRT price. The API value is already toman."""
    if not isinstance(data, dict):
        return None

    item = data.get("item")
    if not isinstance(item, dict):
        return None

    if str(item.get("id", "")).strip().lower() != "usd":
        return None

    unit = str(item.get("unit", "")).strip().upper()
    if unit not in ("IRT", "TOMAN", "TOMANS"):
        return None

    stale = item.get("stale", False)
    if stale is True or str(stale).strip().lower() in ("1", "true", "yes"):
        return None

    raw_price = item.get("price")
    if raw_price is None:
        return None

    try:
        rate = Decimal(str(raw_price).replace(",", "").strip())
    except Exception:
        return None

    if not rate.is_finite() or rate <= 0:
        return None

    return rate

async def refresh_exchange_rate(context=None):
    global USD_TOMAN, LAST_FX_UPDATE

    if not FX_API_URL:
        logger.warning(
            "FX_API_URL is not configured. Using fallback rate."
        )
        return

    headers = {}
    if FX_API_KEY:
        headers["Authorization"] = f"Bearer {FX_API_KEY}"

    try:
        async with httpx.AsyncClient(timeout=15) as client:
            response = await client.get(
                FX_API_URL, headers=headers
            )
            response.raise_for_status()
            data = response.json()

        rate = extract_rate(data)

        if not rate:
            raise ValueError(
                "Could not find a USD/Toman rate in API response."
            )

        # Reject obviously incorrect values.
        if rate < 1000 or rate > 10000000:
            raise ValueError("Exchange rate outside safety bounds.")

        USD_TOMAN = rate
        LAST_FX_UPDATE = datetime.now(timezone.utc)

        logger.info(
            "Exchange rate updated: %s toman per USD",
            USD_TOMAN,
        )

    except Exception:
        logger.exception("Exchange rate update failed.")

# ============================================================
# TELEGRAM HELPERS
# ============================================================

def main_keyboard():
    return ReplyKeyboardMarkup(
        [
            ["🛍️ خرید محصول"],
            ["👤 حساب کاربری", "💳 افزایش موجودی"],
            ["👥 زیرمجموعه‌گیری"],
            ["🎧 پشتیبانی", "⭐ اعتماد"],
        ],
        resize_keyboard=True,
    )

def product_keyboard():
    return InlineKeyboardMarkup([
        [
            InlineKeyboardButton(
                "⭐ استارز", callback_data="category:stars"
            ),
            InlineKeyboardButton(
                "💎 پریمیوم", callback_data="category:premium"
            ),
        ],
        [
            InlineKeyboardButton(
                "💰 رمز ارز 🔒", callback_data="disabled"
            ),
        ],
        [
            InlineKeyboardButton(
                "🎁 گیفت استارزی",
                callback_data="category:gifts",
            ),
            InlineKeyboardButton(
                "✨ ری‌اکشن استارزی",
                callback_data="category:reactions",
            ),
        ],
        [
            InlineKeyboardButton(
                "🚀 بوست تلگرام 🔒", callback_data="disabled"
            ),
        ],
        [
            InlineKeyboardButton(
                "📦 سفارش‌های اخیر من", callback_data="my_orders"
            ),
        ],
        [
            InlineKeyboardButton(
                "🔙 برگشت", callback_data="back"
            ),
        ],
    ])

async def send_home(update, context, text=None):
    message = text or (
        "به فروشگاه Inscription Shop خوش اومدی! 💜\n\n"
        "برای شروع، از منوی زیر گزینه مورد نظرت رو انتخاب کن."
    )

    await update.effective_message.reply_text(
        message,
        reply_markup=main_keyboard(),
    )

async def check_membership(bot, user_id):
    for channel in (SHOP_CHANNEL, TRUST_CHANNEL):
        try:
            member = await bot.get_chat_member(
                f"@{channel}", user_id
            )
            if member.status not in (
                "member", "administrator", "creator"
            ):
                return False
        except Exception:
            logger.exception(
                "Membership check failed for @%s", channel
            )
            return False

    return True

async def is_verified(user_id):
    user = get_user(user_id)
    return bool(user and user["verified"])

# ============================================================
# START / REFERRALS / VERIFICATION
# ============================================================


async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user = update.effective_user
    save_user(user)

    # Handle referral only on first registration.
    if context.args:
        try:
            referrer_id = int(context.args[0])

            if (
                referrer_id != user.id
                and get_user(referrer_id)
                and not db.execute(
                    "SELECT 1 FROM referrals WHERE user_id=?",
                    (user.id,),
                ).fetchone()
            ):
                db.execute("""
                    INSERT INTO referrals(user_id, referrer_id)
                    VALUES(?,?)
                """, (user.id, referrer_id))

                db.execute("""
                    UPDATE users SET referred_by=?
                    WHERE user_id=?
                """, (referrer_id, user.id))

                db.commit()
        except ValueError:
            pass

    # Already verified: go directly to the main menu.
    if await is_verified(user.id):
        await update.message.reply_text(
            "خوش برگشتی! 💜\n\n"
            "به فروشگاه Inscription Shop خوش اومدی.",
            reply_markup=main_keyboard(),
        )
        return

    # First-time verification.
    keyboard = InlineKeyboardMarkup([
        [
            InlineKeyboardButton(
                "📢 کانال فروشگاه",
                url=f"https://t.me/{SHOP_CHANNEL}",
            )
        ],
        [
            InlineKeyboardButton(
                "⭐ کانال اعتماد",
                url=f"https://t.me/{TRUST_CHANNEL}",
            )
        ],
        [
            InlineKeyboardButton(
                "✅ بررسی عضویت",
                callback_data="check_membership",
            )
        ],
    ])

    await update.message.reply_text(
        "سلام! به Inscription Shop خوش اومدی 💜\n\n"
        "برای استفاده از فروشگاه، ابتدا در کانال‌های زیر عضو شو "
        "و سپس عضویتت رو بررسی کن.",
        reply_markup=keyboard,
    )


async def request_contact(update, context):
    if await is_verified(update.effective_user.id):
        await send_home(update, context)
        return

    keyboard = ReplyKeyboardMarkup(
        [[KeyboardButton(
            "📱 ارسال شماره تلفن",
            request_contact=True,
        )]],
        resize_keyboard=True,
        one_time_keyboard=True,
    )

    await update.effective_message.reply_text(
        "برای تأیید حساب کاربری، لطفاً شماره تلفن متصل به "
        "اکانت تلگرامت رو با دکمه زیر ارسال کن.\n\n"
        "شماره باید متعلق به خودت باشه.",
        reply_markup=keyboard,
    )


async def contact_handler(update, context):
    user = update.effective_user
    contact = update.message.contact

    # Verification is persistent: do not ask an already verified user again.
    if await is_verified(user.id):
        await send_home(update, context)
        return

    if not await check_membership(context.bot, user.id):
        await update.message.reply_text(
            "❌ ابتدا باید در هر دو کانال فروشگاه و اعتماد عضو بشی.\n"
            "بعد از عضویت، از دستور /start گزینه بررسی عضویت رو بزن."
        )
        return

    if contact.user_id != user.id:
        await update.message.reply_text(
            "❌ لطفاً فقط شماره تلفن متصل به حساب خودت رو ارسال کن."
        )
        return

    set_verified(user.id, contact.phone_number)

    await update.message.reply_text(
        "✅ حساب کاربری شما با موفقیت تأیید شد.",
        reply_markup=ReplyKeyboardRemove(),
    )

    await send_home(update, context)

async def require_verified(update, context):
    user_id = update.effective_user.id

    if await is_verified(user_id):
        return True

    await update.effective_message.reply_text(
        "برای استفاده از فروشگاه ابتدا باید حساب خودت رو تأیید کنی."
    )

    await request_contact(update, context)
    return False


# ============================================================
# STORE
# ============================================================

async def show_store(update, context):
    await update.effective_message.reply_text(
        "وقتشه محصولت رو انتخاب کنی! 💜\n\n"
        "تمامی سفارشات با بالاترین سرعت و همراه با پشتیبانی "
        "کامل انجام می‌شن تا تجربه‌ای مطمئن و بی‌دغدغه داشته باشی!\n\n"
        "از لیست زیر، گزینه مورد نظرت رو انتخاب کن.",
        reply_markup=product_keyboard(),
    )

async def show_category(query, context, category):
    if category == "stars":
        buttons = []

        for sku, product in PRODUCTS.items():
            if product["category"] != "stars":
                continue

            buttons.append([
                InlineKeyboardButton(
                    product["name"],
                    callback_data=f"buy:{sku}",
                )
            ])

        buttons.append([
            InlineKeyboardButton("🔙 برگشت", callback_data="store")
        ])

        await query.message.reply_text(
            "⭐ یکی از بسته‌های استارز رو انتخاب کن:",
            reply_markup=InlineKeyboardMarkup(buttons),
        )

    elif category == "premium":
        buttons = []

        for sku, product in PRODUCTS.items():
            if product["category"] != "premium":
                continue

            buttons.append([
                InlineKeyboardButton(
                    product["name"],
                    callback_data=f"buy:{sku}",
                )
            ])

        buttons.append([
            InlineKeyboardButton("🔙 برگشت", callback_data="store")
        ])

        await query.message.reply_text(
            "💎 مدت زمان پریمیوم رو انتخاب کن:",
            reply_markup=InlineKeyboardMarkup(buttons),
        )

    elif category == "gifts":
        await show_gifts(query, context)

    elif category == "reactions":
        await query.message.reply_text(
            "✨ تعداد استارز مورد نیاز برای ری‌اکشن رو ارسال کن.\n\n"
            "حداقل تعداد: 1\n\n"
            "مثال: 25",
            reply_markup=InlineKeyboardMarkup([[
                InlineKeyboardButton("🔙 برگشت", callback_data="store")
            ]]),
        )
        context.user_data["awaiting_reaction_quantity"] = True


async def show_gifts(query, context):
    global GIFTS_CACHE

    try:
        result = await context.bot.get_available_gifts()
        GIFTS_CACHE = result.gifts
    except Exception:
        logger.exception("Telegram gift synchronization failed.")

    if not GIFTS_CACHE:
        await query.message.reply_text(
            "فعلاً دریافت لیست هدایا از تلگرام امکان‌پذیر نیست.\n"
            "لطفاً بعداً دوباره تلاش کن یا با پشتیبانی تماس بگیر.",
            reply_markup=InlineKeyboardMarkup([[
                InlineKeyboardButton("🔙 برگشت", callback_data="store")
            ]]),
        )
        return

    buttons = []

    for gift in GIFTS_CACHE:
        stars = gift.star_count
        buttons.append([
            InlineKeyboardButton(
                f"🎁 {stars} استارز",
                callback_data=f"gift:{gift.id}",
            )
        ])

    buttons.append([
        InlineKeyboardButton("🔙 برگشت", callback_data="store")
    ])

    await query.message.reply_text(
        "🎁 هدیه مورد نظرت رو انتخاب کن:\n\n"
        "لیست هدایا از تلگرام دریافت شده.",
        reply_markup=InlineKeyboardMarkup(buttons),
    )

# ============================================================
# ORDER CREATION
# ============================================================

async def begin_product_order(query, context, sku):
    product = PRODUCTS.get(sku)
    if not product:
        await query.message.reply_text("محصول معتبر نیست.")
        return

    base, final_price = calculate_price(product["usd"], sku)

    context.user_data["pending_order"] = {
        "sku": sku,
        "name": product["name"],
        "usd": str(product["usd"]),
        "base": base,
        "price": final_price,
        "quantity": 0,
        "profit_type": get_profit(sku)[0],
        "profit_value": str(get_profit(sku)[1]),
    }

    context.user_data["awaiting_target"] = True

    await query.message.reply_text(
        f"🛍️ محصول انتخابی: {product['name']}\n\n"
        "لطفاً آیدی تلگرام گیرنده رو ارسال کن.\n"
        "مثال: @username"
    )

async def begin_gift_order(query, context, gift_id):
    gift = next(
        (g for g in GIFTS_CACHE if str(g.id) == gift_id),
        None,
    )

    if not gift:
        await query.message.reply_text(
            "این هدیه در دسترس نیست. دوباره لیست هدایا رو باز کن."
        )
        return

    stars = gift.star_count
    usd = STAR_USD_COST * Decimal(stars)
    base, price = calculate_price(usd, "star_gifts")

    context.user_data["pending_order"] = {
        "sku": "star_gifts",
        "name": f"گیفت استارزی ({stars} استارز)",
        "usd": str(usd),
        "base": base,
        "price": price,
        "quantity": stars,
        "profit_type": get_profit("star_gifts")[0],
        "profit_value": str(get_profit("star_gifts")[1]),
    }

    context.user_data["awaiting_target"] = True
    context.user_data["pending_gift_id"] = gift_id

    await query.message.reply_text(
        f"🎁 هدیه انتخابی: {stars} استارز\n\n"
        "آیدی تلگرام گیرنده رو ارسال کن.\n"
        "مثال: @username"
    )

async def create_and_show_payment(update, context, target):
    data = context.user_data.get("pending_order")

    if not data:
        await update.message.reply_text(
            "سفارش نامعتبره. لطفاً دوباره محصول انتخاب کن."
        )
        return

    if not re.fullmatch(r"@[A-Za-z0-9_]{5,32}", target):
        await update.message.reply_text(
            "❌ آیدی معتبر نیست.\n"
            "لطفاً یک آیدی عمومی معتبر با @ ارسال کن."
        )
        return

    order_id = create_order(
        user_id=update.effective_user.id,
        product=data["sku"],
        product_name=data["name"],
        target=target,
        quantity=data["quantity"],
        usd_cost=data["usd"],
        base_toman=data["base"],
        profit_type=data["profit_type"],
        profit_value=data["profit_value"],
        final_price=data["price"],
    )

    context.user_data.pop("pending_order", None)
    context.user_data.pop("awaiting_target", None)

    card = BANK_CARD_NUMBER or "هنوز تنظیم نشده"
    card_name = BANK_CARD_NAME or "هنوز تنظیم نشده"
    bank = BANK_NAME or "هنوز تنظیم نشده"

    await update.message.reply_text(
        f"🧾 <b>اطلاعات سفارش #{order_id}</b>\n\n"
        f"📦 محصول: {data['name']}\n"
        f"👤 گیرنده: {target}\n"
        f"💰 مبلغ قابل پرداخت: <b>{toman(data['price'])} تومان</b>\n\n"
        f"💳 <b>اطلاعات کارت بانکی</b>\n"
        f"شماره کارت: <code>{card}</code>\n"
        f"صاحب کارت: {card_name}\n"
        f"بانک: {bank}\n\n"
        "پس از انتقال وجه، تصویر رسید پرداخت رو ارسال کن.\n"
        "لطفاً مبلغ دقیق سفارش رو پرداخت کن.",
        parse_mode=ParseMode.HTML,
        reply_markup=InlineKeyboardMarkup([[
            InlineKeyboardButton(
                "📤 ارسال رسید پرداخت",
                callback_data=f"receipt:{order_id}",
            )
        ]]),
    )

    context.user_data["awaiting_receipt_order"] = order_id

# ============================================================
# RECEIPTS / ADMIN NOTIFICATIONS
# ============================================================

async def notify_admins(context, order, photo_file_id):
    user_id = order["user_id"]

    user = get_user(user_id)
    username = user["username"] if user else None
    username_text = f"@{username}" if username else "ندارد"

    text = (
        f"🧾 <b>رسید پرداخت جدید</b>\n\n"
        f"شماره سفارش: #{order['id']}\n"
        f"محصول: {order['product_name']}\n"
        f"مبلغ: {toman(order['final_price'])} تومان\n"
        f"گیرنده: {order['target']}\n"
        f"کاربر: {username_text}\n"
        f"شناسه عددی: <code>{user_id}</code>\n\n"
        "لطفاً رسید رو بررسی کن."
    )

    keyboard = InlineKeyboardMarkup([
        [
            InlineKeyboardButton(
                "✅ تأیید پرداخت",
                callback_data=f"approve:{order['id']}",
            ),
            InlineKeyboardButton(
                "❌ رد پرداخت",
                callback_data=f"reject:{order['id']}",
            ),
        ],
    ])

    recipients = get_admin_ids()

    if ADMIN_GROUP_ID:
        try:
            await context.bot.send_photo(
                chat_id=int(ADMIN_GROUP_ID),
                photo=photo_file_id,
                caption=text,
                parse_mode=ParseMode.HTML,
                reply_markup=keyboard,
            )
        except Exception:
            logger.exception("Admin group notification failed.")

    else:
        for admin_id in recipients:
            try:
                await context.bot.send_photo(
                    chat_id=admin_id,
                    photo=photo_file_id,
                    caption=text,
                    parse_mode=ParseMode.HTML,
                    reply_markup=keyboard,
                )
            except Exception:
                logger.warning(
                    "Could not notify admin %s. They may not have started the bot.",
                    admin_id,
                )

async def receipt_handler(update, context):
    user_id = update.effective_user.id
    order_id = context.user_data.get("awaiting_receipt_order")

    if not order_id:
        return

    if not update.message.photo:
        await update.message.reply_text(
            "لطفاً تصویر رسید رو به صورت عکس ارسال کن."
        )
        return

    order = get_order(order_id)

    if not order or order["user_id"] != user_id:
        await update.message.reply_text(
            "سفارش معتبر نیست."
        )
        return

    if order["status"] != "PENDING_PAYMENT":
        await update.message.reply_text(
            "این سفارش در حال بررسی یا قبلاً ثبت شده."
        )
        return

    file_id = update.message.photo[-1].file_id

    update_order(
        order_id,
        receipt_file_id=file_id,
        status="UNDER_REVIEW",
    )

    context.user_data.pop("awaiting_receipt_order", None)

    order = get_order(order_id)

    await notify_admins(context, order, file_id)

    await update.message.reply_text(
        "✅ رسید شما با موفقیت ثبت شد.\n\n"
        "رسید برای تیم مدیریت ارسال شد و پس از بررسی نتیجه "
        "به شما اطلاع داده می‌شه."
    )

# ============================================================
# ADMIN ORDER ACTIONS
# ============================================================

async def admin_approve(query, context, order_id):
    order = get_order(order_id)

    if not order or order["status"] != "UNDER_REVIEW":
        await query.answer("این سفارش قابل تأیید نیست.", show_alert=True)
        return

    update_order(
        order_id,
        status="PAID",
        paid_at=datetime.now(timezone.utc).isoformat(),
        reviewed_by=query.from_user.id,
    )

    await context.bot.send_message(
        order["user_id"],
        f"✅ پرداخت سفارش #{order_id} تأیید شد.\n\n"
        "پرداخت شما با موفقیت انجام شد.\n"
        "لطفاً منتظر تحویل محصول باشید.",
    )

    await query.answer("پرداخت تأیید شد.")
    await query.edit_message_caption(
        caption=(
            f"✅ پرداخت سفارش #{order_id} تأیید شد.\n"
            "برای ثبت تحویل از پنل مدیریت استفاده کن."
        ),
        reply_markup=InlineKeyboardMarkup([[
            InlineKeyboardButton(
                "📦 ثبت تحویل",
                callback_data=f"deliver:{order_id}",
            )
        ]]),
    )

async def admin_reject(query, context, order_id):
    order = get_order(order_id)

    if not order or order["status"] != "UNDER_REVIEW":
        await query.answer("این سفارش قابل رد نیست.", show_alert=True)
        return

    update_order(
        order_id,
        status="REJECTED",
        reviewed_by=query.from_user.id,
    )

    await context.bot.send_message(
        order["user_id"],
        f"❌ رسید سفارش #{order_id} تأیید نشد.\n\n"
        "لطفاً برای پیگیری با پشتیبانی تماس بگیر.",
    )

    await query.answer("رسید رد شد.")
    await query.edit_message_caption(
        caption=f"❌ رسید سفارش #{order_id} رد شد."
    )

async def admin_deliver(query, context, order_id):
    order = get_order(order_id)

    if not order or order["status"] != "PAID":
        await query.answer(
            "این سفارش هنوز پرداخت تأییدشده ندارد.",
            show_alert=True,
        )
        return

    delivered_at = datetime.now(timezone.utc)

    update_order(
        order_id,
        status="DELIVERED",
        delivered_at=delivered_at.isoformat(),
    )

    await context.bot.send_message(
        order["user_id"],
        f"🎉 سفارش #{order_id} با موفقیت تحویل داده شد!\n\n"
        f"محصول: {order['product_name']}\n"
        "از خریدت از Inscription Shop ممنونیم 💜",
    )

    # Mask the numerical Telegram ID.
    user_id = str(order["user_id"])
    masked_id = (
        user_id[:3] + "***" + user_id[-3:]
        if len(user_id) > 6 else "***"
    )

    order_time = order["created_at"]
    price = toman(order["final_price"])

    trust_text = (
        "🎉 <b>سفارش جدید با موفقیت تحویل داده شد!</b>\n\n"
        f"🧾 شماره سفارش: #{order_id}\n"
        f"📦 محصول: {order['product_name']}\n"
        f"💰 مبلغ سفارش: {price} تومان\n"
        f"🕒 زمان ثبت سفارش: {order_time}\n"
        f"🆔 شناسه مشتری: <code>{masked_id}</code>\n"
        f"✅ زمان تحویل: {delivered_at.strftime('%Y-%m-%d %H:%M:%S UTC')}\n\n"
        "Inscription Shop | Trusted Telegram Services 💜"
    )

    try:
        await context.bot.send_message(
            chat_id=TRUST_CHANNEL_ID,
            text=trust_text,
            parse_mode=ParseMode.HTML,
        )
    except Exception:
        logger.exception("Trust channel publication failed.")

    await query.answer("سفارش تحویل داده شد.")
    await query.edit_message_caption(
        caption=f"🎉 سفارش #{order_id} تحویل داده شد."
    )

# ============================================================
# CUSTOMER ACCOUNT / ORDERS
# ============================================================

async def show_account(update, context):
    user_id = update.effective_user.id
    user = get_user(user_id)

    if not user:
        return

    count = db.execute(
        "SELECT COUNT(*) AS c FROM orders WHERE user_id=?",
        (user_id,),
    ).fetchone()["c"]

    delivered = db.execute(
        "SELECT COUNT(*) AS c FROM orders "
        "WHERE user_id=? AND status='DELIVERED'",
        (user_id,),
    ).fetchone()["c"]

    await update.effective_message.reply_text(
        "👤 <b>حساب کاربری</b>\n\n"
        f"شناسه: <code>{user_id}</code>\n"
        f"نام: {user['first_name'] or '-'}\n"
        f"وضعیت تأیید: {'✅ تأیید شده' if user['verified'] else '❌ تأیید نشده'}\n"
        f"تعداد کل سفارشات: {count}\n"
        f"سفارشات تحویل‌شده: {delivered}",
        parse_mode=ParseMode.HTML,
    )

async def show_orders(update, context):
    user_id = update.effective_user.id

    rows = db.execute("""
        SELECT * FROM orders
        WHERE user_id=?
        ORDER BY id DESC LIMIT 10
    """, (user_id,)).fetchall()

    if not rows:
        await update.effective_message.reply_text(
            "هنوز سفارشی ثبت نکردی."
        )
        return

    lines = ["📦 <b>آخرین سفارش‌های شما</b>\n"]

    for order in rows:
        lines.append(
            f"#{order['id']} | {order['product_name']}\n"
            f"مبلغ: {toman(order['final_price'])} تومان\n"
            f"وضعیت: {order['status']}\n"
        )

    await update.effective_message.reply_text(
        "\n".join(lines),
        parse_mode=ParseMode.HTML,
    )

# ============================================================
# REFERRALS
# ============================================================

async def show_referral(update, context):
    user_id = update.effective_user.id

    bot_info = await context.bot.get_me()
    link = f"https://t.me/{bot_info.username}?start={user_id}"

    count = db.execute(
        "SELECT COUNT(*) AS c FROM referrals WHERE referrer_id=?",
        (user_id,),
    ).fetchone()["c"]

    await update.effective_message.reply_text(
        "👥 <b>سیستم زیرمجموعه‌گیری</b>\n\n"
        f"🔗 لینک اختصاصی شما:\n<code>{link}</code>\n\n"
        f"👤 تعداد افراد دعوت‌شده: {count}\n"
        f"🎁 پاداش دعوت: {toman(REFERRAL_REWARD)} تومان\n\n"
        "این لینک رو برای دوستانت ارسال کن.",
        parse_mode=ParseMode.HTML,
    )

# ============================================================
# ADMIN PANEL
# ============================================================

async def admin_panel(update, context):
    if not is_admin(update.effective_user.id):
        await update.effective_message.reply_text(
            "⛔ دسترسی غیرمجاز."
        )
        return

    keyboard = InlineKeyboardMarkup([
        [
            InlineKeyboardButton(
                "📦 سفارش‌های در انتظار",
                callback_data="admin:pending",
            )
        ],
        [
            InlineKeyboardButton(
                "📊 آمار فروش",
                callback_data="admin:stats",
            )
        ],
        [
            InlineKeyboardButton(
                "💰 تنظیم سود",
                callback_data="admin:profits",
            )
        ],
        [
            InlineKeyboardButton(
                "💳 اطلاعات بانکی",
                callback_data="admin:bank",
            )
        ],
        [
            InlineKeyboardButton(
                "👮 مدیران",
                callback_data="admin:admins",
            )
        ],
        [
            InlineKeyboardButton(
                "📈 نرخ دلار",
                callback_data="admin:fx",
            )
        ],
    ])

    await update.effective_message.reply_text(
        "⚙️ <b>پنل مدیریت Inscription Shop</b>\n\n"
        "یکی از بخش‌های زیر رو انتخاب کن.",
        parse_mode=ParseMode.HTML,
        reply_markup=keyboard,
    )

async def admin_pending(query):
    rows = db.execute("""
        SELECT * FROM orders
        WHERE status IN ('UNDER_REVIEW','PAID')
        ORDER BY id DESC LIMIT 20
    """).fetchall()

    if not rows:
        await query.message.reply_text(
            "سفارش در انتظار بررسی وجود نداره."
        )
        return

    for order in rows:
        await query.message.reply_text(
            f"سفارش #{order['id']}\n"
            f"محصول: {order['product_name']}\n"
            f"مبلغ: {toman(order['final_price'])} تومان\n"
            f"وضعیت: {order['status']}",
            reply_markup=InlineKeyboardMarkup([[
                InlineKeyboardButton(
                    "باز کردن سفارش",
                    callback_data=f"admin:order:{order['id']}",
                )
            ]]),
        )

async def admin_stats(query):
    total = db.execute(
        "SELECT COUNT(*) AS c FROM orders"
    ).fetchone()["c"]

    delivered = db.execute(
        "SELECT COUNT(*) AS c FROM orders WHERE status='DELIVERED'"
    ).fetchone()["c"]

    revenue = db.execute("""
        SELECT COALESCE(SUM(final_price),0) AS s
        FROM orders WHERE status='DELIVERED'
    """).fetchone()["s"]

    users = db.execute(
        "SELECT COUNT(*) AS c FROM users"
    ).fetchone()["c"]

    await query.message.reply_text(
        "📊 <b>آمار فروشگاه</b>\n\n"
        f"👥 کاربران: {users}\n"
        f"📦 کل سفارش‌ها: {total}\n"
        f"✅ تحویل‌شده: {delivered}\n"
        f"💰 مجموع مبلغ سفارش‌های تحویل‌شده: {toman(revenue)} تومان",
        parse_mode=ParseMode.HTML,
    )

async def admin_profit_menu(query):
    buttons = []

    for sku, product in PRODUCTS.items():
        profit_type, value = get_profit(sku)
        buttons.append([
            InlineKeyboardButton(
                f"{product['name']} | {profit_type}: {value}",
                callback_data=f"profit:{sku}",
            )
        ])

    for sku, name in (
        ("star_gifts", "گیفت استارزی"),
        ("star_reactions", "ری‌اکشن استارزی"),
    ):
        profit_type, value = get_profit(sku)
        buttons.append([
            InlineKeyboardButton(
                f"{name} | {profit_type}: {value}",
                callback_data=f"profit:{sku}",
            )
        ])

    await query.message.reply_text(
        "💰 محصول مورد نظر رو انتخاب کن تا سودش رو تغییر بدی:",
        reply_markup=InlineKeyboardMarkup(buttons),
    )

async def admin_bank_menu(query):
    await query.message.reply_text(
        "💳 <b>اطلاعات بانکی فعلی</b>\n\n"
        f"شماره کارت: {BANK_CARD_NUMBER or '-'}\n"
        f"نام صاحب کارت: {BANK_CARD_NAME or '-'}\n"
        f"بانک: {BANK_NAME or '-'}\n\n"
        "برای تغییر، از دستور زیر استفاده کن:\n"
        "<code>/setbank CARD_NUMBER|CARD_NAME|BANK_NAME</code>",
        parse_mode=ParseMode.HTML,
    )

async def admin_fx_menu(query):
    await query.message.reply_text(
        f"💵 نرخ فعلی دلار: {toman(USD_TOMAN)} تومان\n"
        f"آخرین بروزرسانی: {LAST_FX_UPDATE or 'هنوز انجام نشده'}\n\n"
        "دستور تنظیم دستی:\n"
        "<code>/setrate 120000</code>",
        parse_mode=ParseMode.HTML,
    )

async def admin_add_admins(update, context):
    if update.effective_user.id != OWNER_ID:
        return

    if not context.args:
        await update.message.reply_text(
            "استفاده: /addadmin TELEGRAM_ID"
        )
        return

    try:
        new_id = int(context.args[0])
    except ValueError:
        await update.message.reply_text("شناسه نامعتبر است.")
        return

    admins = get_admin_ids()
    admins.add(new_id)

    db_set_setting(
        "extra_admins",
        ",".join(str(x) for x in admins if x != OWNER_ID),
    )

    await update.message.reply_text(
        f"✅ مدیر {new_id} اضافه شد."
    )

async def admin_remove_admin(update, context):
    if update.effective_user.id != OWNER_ID:
        return

    if not context.args:
        await update.message.reply_text(
            "استفاده: /removeadmin TELEGRAM_ID"
        )
        return

    try:
        remove_id = int(context.args[0])
    except ValueError:
        await update.message.reply_text("شناسه نامعتبر است.")
        return

    if remove_id == OWNER_ID:
        await update.message.reply_text(
            "امکان حذف مالک اصلی وجود ندارد."
        )
        return

    admins = get_admin_ids()
    admins.discard(remove_id)

    db_set_setting(
        "extra_admins",
        ",".join(str(x) for x in admins if x != OWNER_ID),
    )

    await update.message.reply_text("✅ مدیر حذف شد.")

async def admin_set_profit(update, context):
    if not is_admin(update.effective_user.id):
        return

    if len(context.args) < 3:
        await update.message.reply_text(
            "فرمت:\n"
            "/setprofit SKU percent 20\n"
            "/setprofit SKU fixed 50000\n\n"
            "مثال:\n"
            "/setprofit stars_50 percent 25"
        )
        return

    sku, profit_type, value = context.args[:3]

    if sku not in PRODUCTS and sku not in (
        "star_gifts", "star_reactions"
    ):
        await update.message.reply_text("SKU نامعتبر است.")
        return

    if profit_type not in ("percent", "fixed"):
        await update.message.reply_text(
            "نوع سود باید percent یا fixed باشه."
        )
        return

    try:
        number = Decimal(value)
        if not number.is_finite() or number < 0:
            raise ValueError
    except Exception:
        await update.message.reply_text("مقدار سود نامعتبر است.")
        return

    db_set_setting(f"profit_type_{sku}", profit_type)
    db_set_setting(f"profit_value_{sku}", number)

    await update.message.reply_text(
        f"✅ سود {sku} تغییر کرد.\n"
        f"نوع: {profit_type}\n"
        f"مقدار: {number}"
    )

async def admin_set_rate(update, context):
    global USD_TOMAN

    if not is_admin(update.effective_user.id):
        return

    if not context.args:
        return

    try:
        rate = Decimal(context.args[0])
        if rate < 1000 or rate > 10000000:
            raise ValueError

        USD_TOMAN = rate
        db_set_setting("manual_rate", rate)

        await update.message.reply_text(
            f"✅ نرخ دلار روی {toman(rate)} تومان تنظیم شد."
        )
    except Exception:
        await update.message.reply_text("نرخ نامعتبر است.")

async def admin_set_bank(update, context):
    if update.effective_user.id != OWNER_ID:
        return

    value = " ".join(context.args)
    parts = value.split("|")

    if len(parts) != 3:
        await update.message.reply_text(
            "فرمت:\n"
            "/setbank CARD_NUMBER|CARD_NAME|BANK_NAME"
        )
        return

    card, name, bank = [x.strip() for x in parts]

    if not re.fullmatch(r"\d{16}", card):
        await update.message.reply_text(
            "شماره کارت باید ۱۶ رقم باشه."
        )
        return

    global BANK_CARD_NUMBER, BANK_CARD_NAME, BANK_NAME
    BANK_CARD_NUMBER = card
    BANK_CARD_NAME = name
    BANK_NAME = bank

    db_set_setting("bank_card_number", card)
    db_set_setting("bank_card_name", name)
    db_set_setting("bank_name", bank)

    await update.message.reply_text(
        "✅ اطلاعات بانکی با موفقیت ذخیره و اعمال شد."
    )

# ============================================================
# CALLBACK ROUTER
# ============================================================

async def callback_handler(update, context):
    query = update.callback_query
    await query.answer()

    user_id = query.from_user.id
    data = query.data

    if data == "check_membership":
        if await is_verified(user_id):
            await send_home(update, context)
        elif await check_membership(context.bot, user_id):
            await request_contact(update, context)
        else:
            await query.message.reply_text(
                "❌ هنوز در همه کانال‌ها عضو نشدی.\n"
                "ابتدا عضو شو و دوباره بررسی کن."
            )
        return

    if data == "store":
        if await require_verified(update, context):
            await show_store(update, context)
        return

    if data == "my_orders":
        if await require_verified(update, context):
            await show_orders(update, context)
        return

    if data == "back":
        await send_home(update, context)
        return

    if data == "disabled":
        await query.answer(
            "این بخش به‌زودی فعال می‌شه.",
            show_alert=True,
        )
        return

    if data.startswith("category:"):
        if not await require_verified(update, context):
            return

        category = data.split(":", 1)[1]
        await show_category(query, context, category)
        return

    if data.startswith("buy:"):
        if not await require_verified(update, context):
            return

        sku = data.split(":", 1)[1]
        await begin_product_order(query, context, sku)
        return

    if data.startswith("gift:"):
        if not await require_verified(update, context):
            return

        gift_id = data.split(":", 1)[1]
        await begin_gift_order(query, context, gift_id)
        return

    if data.startswith("receipt:"):
        order_id = int(data.split(":")[1])
        order = get_order(order_id)

        if not order or order["user_id"] != user_id:
            await query.answer("سفارش متعلق به شما نیست.", show_alert=True)
            return

        if order["status"] != "PENDING_PAYMENT":
            await query.answer("وضعیت سفارش اجازه ارسال رسید نمی‌دهد.", show_alert=True)
            return

        context.user_data["awaiting_receipt_order"] = order_id
        await query.message.reply_text(
            "📤 لطفاً تصویر رسید پرداخت رو به صورت عکس ارسال کن."
        )
        return

    # All management actions require admin authorization.
    if data.startswith("admin:") or data.startswith(
        ("approve:", "reject:", "deliver:", "profit:")
    ):
        if not is_admin(user_id):
            await query.answer("دسترسی غیرمجاز.", show_alert=True)
            return

    if data == "admin:pending":
        await admin_pending(query)
        return

    if data == "admin:stats":
        await admin_stats(query)
        return

    if data == "admin:profits":
        await admin_profit_menu(query)
        return

    if data == "admin:bank":
        await admin_bank_menu(query)
        return

    if data == "admin:fx":
        await admin_fx_menu(query)
        return

    if data == "admin:admins":
        admins = get_admin_ids()
        await query.message.reply_text(
            "👮 مدیران:\n\n" +
            "\n".join(str(x) for x in sorted(admins))
        )
        return

    if data.startswith("admin:order:"):
        order_id = int(data.split(":")[2])
        order = get_order(order_id)

        if not order:
            return

        buttons = []

        if order["status"] == "UNDER_REVIEW":
            buttons.append([
                InlineKeyboardButton(
                    "✅ تأیید",
                    callback_data=f"approve:{order_id}",
                ),
                InlineKeyboardButton(
                    "❌ رد",
                    callback_data=f"reject:{order_id}",
                ),
            ])

        elif order["status"] == "PAID":
            buttons.append([
                InlineKeyboardButton(
                    "📦 تحویل",
                    callback_data=f"deliver:{order_id}",
                )
            ])

        await query.message.reply_text(
            f"سفارش #{order_id}\n"
            f"محصول: {order['product_name']}\n"
            f"مبلغ: {toman(order['final_price'])} تومان\n"
            f"وضعیت: {order['status']}",
            reply_markup=InlineKeyboardMarkup(buttons),
        )
        return

    if data.startswith("approve:"):
        await admin_approve(
            query, context, int(data.split(":")[1])
        )
        return

    if data.startswith("reject:"):
        await admin_reject(
            query, context, int(data.split(":")[1])
        )
        return

    if data.startswith("deliver:"):
        await admin_deliver(
            query, context, int(data.split(":")[1])
        )
        return

    if data.startswith("profit:"):
        sku = data.split(":", 1)[1]
        context.user_data["editing_profit"] = sku

        await query.message.reply_text(
            f"تنظیم سود برای {sku}\n\n"
            "یکی از این دو فرمت رو ارسال کن:\n"
            "percent 20\n"
            "fixed 50000\n\n"
            "مثال اول یعنی ۲۰ درصد سود.\n"
            "مثال دوم یعنی ۵۰ هزار تومان سود ثابت."
        )
        return

# ============================================================
# TEXT ROUTER
# ============================================================

async def text_handler(update, context):
    user_id = update.effective_user.id
    text = update.message.text.strip()

    # Admin profit editor
    sku = context.user_data.get("editing_profit")

    if sku and is_admin(user_id):
        parts = text.split()

        if len(parts) != 2 or parts[0] not in (
            "percent", "fixed"
        ):
            await update.message.reply_text(
                "فرمت نامعتبره. مثال: percent 20"
            )
            return

        try:
            value = Decimal(parts[1])
            if not value.is_finite() or value < 0:
                raise ValueError
        except Exception:
            await update.message.reply_text(
                "مقدار نامعتبره."
            )
            return

        db_set_setting(f"profit_type_{sku}", parts[0])
        db_set_setting(f"profit_value_{sku}", value)

        context.user_data.pop("editing_profit", None)

        await update.message.reply_text(
            f"✅ سود {sku} به‌روزرسانی شد."
        )
        return

    # Reaction quantity
    if context.user_data.get("awaiting_reaction_quantity"):
        try:
            quantity = int(text)
            if quantity < 1 or quantity > 10000:
                raise ValueError
        except ValueError:
            await update.message.reply_text(
                "لطفاً یک عدد بین ۱ تا ۱۰۰۰۰ ارسال کن."
            )
            return

        usd = STAR_USD_COST * Decimal(quantity)
        base, price = calculate_price(
            usd, "star_reactions"
        )

        context.user_data["pending_order"] = {
            "sku": "star_reactions",
            "name": f"ری‌اکشن استارزی ({quantity} استارز)",
            "usd": str(usd),
            "base": base,
            "price": price,
            "quantity": quantity,
            "profit_type": get_profit("star_reactions")[0],
            "profit_value": str(get_profit("star_reactions")[1]),
        }

        context.user_data.pop(
            "awaiting_reaction_quantity", None
        )
        context.user_data["awaiting_target"] = True

        await update.message.reply_text(
            f"✨ تعداد: {quantity}\n\n"
            "لطفاً آیدی کانال عمومی مورد نظر رو ارسال کن.\n"
            "مثال: @mychannel"
        )
        return

    # Product recipient
    if context.user_data.get("awaiting_target"):
        await create_and_show_payment(
            update, context, text
        )
        return

    # Main menu
    if text == "🛍️ خرید محصول":
        if not await require_verified(update, context):
            return
        await show_store(update, context)
        return

    if text == "👤 حساب کاربری":
        await show_account(update, context)
        return

    if text == "💳 افزایش موجودی":
        await update.message.reply_text(
            "💳 برای افزایش موجودی حساب، لطفاً با پشتیبانی تماس بگیر.\n"
            "این قابلیت فعلاً از طریق ثبت سفارش مستقیم انجام می‌شه."
        )
        return

    if text == "👥 زیرمجموعه‌گیری":
        await show_referral(update, context)
        return

    if text == "🎧 پشتیبانی":
        await update.message.reply_text(
            f"برای ارتباط با پشتیبانی:\n{SUPPORT_USERNAME}"
        )
        return

    if text == "⭐ اعتماد":
        await update.message.reply_text(
            f"⭐ کانال اعتماد Inscription Shop:\n"
            f"https://t.me/{TRUST_CHANNEL}"
        )
        return

    await update.message.reply_text(
        "از منوی اصلی یک گزینه انتخاب کن.",
        reply_markup=main_keyboard(),
    )

# ============================================================
# BOT INITIALIZATION
# ============================================================

async def post_init(application):
    await refresh_exchange_rate()

    application.job_queue.run_repeating(
        refresh_exchange_rate,
        interval=FX_UPDATE_SECONDS,
        first=FX_UPDATE_SECONDS,
        name="exchange_rate_refresh",
    )

    logger.info("Inscription Shop initialized.")

def main():
    if not BOT_TOKEN:
        raise RuntimeError("BOT_TOKEN is missing from .env")

    if OWNER_ID <= 0:
        raise RuntimeError("OWNER_ID must be configured.")

    init_db()

    # Restore persisted manual exchange rate.
    manual_rate = db_get_setting("manual_rate")
    global USD_TOMAN

    if manual_rate:
        USD_TOMAN = Decimal(manual_rate)

    # Restore persisted bank details.
    global BANK_CARD_NUMBER, BANK_CARD_NAME, BANK_NAME

    BANK_CARD_NUMBER = db_get_setting(
        "bank_card_number", BANK_CARD_NUMBER
    )
    BANK_CARD_NAME = db_get_setting(
        "bank_card_name", BANK_CARD_NAME
    )
    BANK_NAME = db_get_setting(
        "bank_name", BANK_NAME
    )

    application = (
        Application.builder()
        .token(BOT_TOKEN)
        .post_init(post_init)
        .build()
    )

    application.add_handler(CommandHandler("start", start))
    application.add_handler(CommandHandler("admin", admin_panel))

    application.add_handler(
        CommandHandler("addadmin", admin_add_admins)
    )
    application.add_handler(
        CommandHandler("removeadmin", admin_remove_admin)
    )
    application.add_handler(
        CommandHandler("setprofit", admin_set_profit)
    )
    application.add_handler(
        CommandHandler("setrate", admin_set_rate)
    )
    application.add_handler(
        CommandHandler("setbank", admin_set_bank)
    )

    application.add_handler(
        CallbackQueryHandler(callback_handler)
    )

    application.add_handler(
        MessageHandler(
            filters.CONTACT,
            contact_handler,
        )
    )

    application.add_handler(
        MessageHandler(
            filters.PHOTO,
            receipt_handler,
        )
    )

    application.add_handler(
        MessageHandler(
            filters.TEXT & ~filters.COMMAND,
            text_handler,
        )
    )

    logger.info("Starting Inscription Shop...")
    application.run_polling(
        allowed_updates=Update.ALL_TYPES
    )

if __name__ == "__main__":
    main()