import json
import re
from flask import Blueprint, current_app, flash, redirect, render_template, request, session, url_for
from services.garage_service import admin_extend_hold, admin_update_dispatch_request, sync_expired_holds
from services.order_service import (
    ORDER_STATUSES,
    get_allowed_admin_transitions,
    get_order_full_details,
    order_garage_dispatch_allowed,
    review_payment,
    update_order_status,
)
from services.product_service import (
    _matches_word_token,
    adjust_inventory,
    get_product_by_identifier,
    list_brands,
    list_categories,
    query_products,
)
from services.settings_service import (
    get_gallery_photos,
    get_homepage_sections,
    get_store_settings,
    get_testimonials,
    get_vehicle_maker_strips,
)
from utils.db import get_db, transaction
from utils.formatting import (
    fetch_instagram_thumbnail,
    format_inr,
    parse_instagram_post_info,
    parse_json_safe,
    rupees_to_paise,
    slugify,
)
from utils.security import (
    ACTIVITY_LOG_RETENTION_DAYS,
    admin_login_required,
    check_rate_limit,
    csrf_protect,
    get_current_admin,
    hash_password,
    log_admin_action,
    prune_old_admin_audit_logs,
    save_uploaded_image,
    save_uploaded_media,
    verify_password,
)

admin_bp = Blueprint("admin", __name__, url_prefix="/admin")


@admin_bp.route("/login", methods=["GET", "POST"])
@csrf_protect
def login():
    if get_current_admin():
        return redirect(url_for("admin.dashboard"))

    if request.method == "POST":
        if not check_rate_limit("admin_login", 15, 300):
            flash("Too many admin login attempts. Please wait a few minutes.", "error")
            return render_template("admin/login.html"), 429

        username = (request.form.get("username") or "").strip()
        password = request.form.get("password") or ""
        db = get_db()
        user = db.execute(
            "SELECT * FROM admin_users WHERE (username = ? OR email = ? COLLATE NOCASE) AND is_active = 1",
            (username, username),
        ).fetchone()
        if not user or not verify_password(user["password_hash"], password):
            flash("Invalid admin credentials.", "error")
            return render_template("admin/login.html"), 401

        with transaction(db) as conn:
            conn.execute("UPDATE admin_users SET last_login_at = datetime('now') WHERE id = ?", (user["id"],))
            log_admin_action(conn, dict(user), "admin_login", "admin_user", user["id"])
        session["admin_id"] = user["id"]
        session["admin_session_version"] = int(user["session_version"] or 1)
        next_url = request.args.get("next") or request.form.get("next") or url_for("admin.dashboard")
        if not next_url.startswith("/admin"):
            next_url = url_for("admin.dashboard")
        return redirect(next_url)

    return render_template("admin/login.html")


@admin_bp.route("/logout", methods=["POST"])
@admin_login_required
@csrf_protect
def logout():
    admin = get_current_admin()
    with transaction() as conn:
        log_admin_action(conn, admin, "admin_logout", "admin_user", admin["id"])
    session.pop("admin_id", None)
    session.pop("admin_session_version", None)
    flash("Signed out of Admin Panel.", "success")
    return redirect(url_for("admin.login"))


@admin_bp.route("/")
@admin_login_required
def dashboard():
    db = get_db()
    sync_expired_holds()

    total_orders = db.execute("SELECT COUNT(*) FROM orders").fetchone()[0]
    total_sales_paise = db.execute(
        "SELECT COALESCE(SUM(total_paise), 0) FROM orders WHERE status NOT IN ('Cancelled', 'Refunded')"
    ).fetchone()[0]
    pending_verify = db.execute(
        "SELECT COUNT(*) FROM orders WHERE status = 'Payment Verification Pending'"
    ).fetchone()[0]
    paid_orders = db.execute(
        "SELECT COUNT(*) FROM payments WHERE status = 'Verified'"
    ).fetchone()[0]
    processing_orders = db.execute(
        "SELECT COUNT(*) FROM orders WHERE status IN ('Order Confirmed', 'Processing', 'Packed')"
    ).fetchone()[0]
    awaiting_shipment = db.execute(
        "SELECT COUNT(*) FROM orders WHERE status IN ('Payment Verified', 'Order Confirmed', 'Processing', 'Packed')"
    ).fetchone()[0]
    delivered_orders = db.execute(
        "SELECT COUNT(*) FROM orders WHERE status = 'Delivered'"
    ).fetchone()[0]
    preorders_count = db.execute("SELECT COUNT(*) FROM pre_orders").fetchone()[0]
    garage_req_count = db.execute(
        "SELECT COUNT(*) FROM garage_dispatch_requests WHERE status IN ('Pending', 'Approved', 'Packed')"
    ).fetchone()[0]
    active_holds_count = db.execute(
        "SELECT COUNT(*) FROM garage_holds WHERE hold_status = 'active'"
    ).fetchone()[0]
    total_products = db.execute("SELECT COUNT(*) FROM products").fetchone()[0]
    low_stock_count = db.execute(
        """
        SELECT COUNT(*) FROM products p
        JOIN inventory i ON i.product_id = p.id
        WHERE (i.stock_qty - i.reserved_qty) > 0 AND (i.stock_qty - i.reserved_qty) <= i.low_stock_threshold
        """
    ).fetchone()[0]
    out_of_stock_count = db.execute(
        """
        SELECT COUNT(*) FROM products p
        JOIN inventory i ON i.product_id = p.id
        WHERE p.is_sold_out = 1 OR (p.is_pre_order = 0 AND (i.stock_qty - i.reserved_qty) <= 0)
        """
    ).fetchone()[0]

    recent_orders = []
    for r in db.execute(
        """
        SELECT o.*, pay.status AS payment_status
        FROM orders o
        LEFT JOIN payments pay ON pay.id = (SELECT id FROM payments WHERE order_id = o.id ORDER BY id DESC LIMIT 1)
        ORDER BY o.id DESC
        LIMIT 10
        """
    ).fetchall():
        d = dict(r)
        d["total_formatted"] = format_inr(d["total_paise"])
        recent_orders.append(d)

    stats = {
        "total_orders": total_orders,
        "total_sales_formatted": format_inr(total_sales_paise),
        "pending_verify": pending_verify,
        "paid_orders": paid_orders,
        "processing_orders": processing_orders,
        "awaiting_shipment": awaiting_shipment,
        "delivered_orders": delivered_orders,
        "preorders_count": preorders_count,
        "garage_req_count": garage_req_count,
        "active_holds_count": active_holds_count,
        "total_products": total_products,
        "low_stock_count": low_stock_count,
        "out_of_stock_count": out_of_stock_count,
    }
    return render_template("admin/dashboard.html", stats=stats, recent_orders=recent_orders)


# ==========================================================================
# MODULE A: PRODUCT MANAGEMENT
# ==========================================================================
@admin_bp.route("/products")
@admin_login_required
def products_list():
    search = request.args.get("q", "").strip()
    brand = request.args.get("brand", "all")
    category = request.args.get("category", "all")
    availability = request.args.get("status", "all")
    sort = request.args.get("sort", "newest")
    page = request.args.get("page", 1, type=int)

    res = query_products(
        search=search,
        brand=brand,
        category=category,
        availability=availability,
        sort=sort,
        page=page,
        per_page=25,
        include_hidden=True,
    )
    return render_template(
        "admin/products.html",
        result=res,
        brands=list_brands(active_only=False),
        categories=list_categories(active_only=False),
        filters={"q": search, "brand": brand, "category": category, "status": availability, "sort": sort},
    )


PRESET_BADGES = [
    "In Stock",
    "Pre-Order",
    "New Arrival",
    "Bestseller",
    "Hot Drop",
    "Limited Edition",
    "Events Exclusive",
    "Opening Hood",
    "Opening Doors",
    "Chase Variant",
    "RLC Exclusive",
    "Official Licensed",
    "Diecast Collectible",
    "Rare Grail",
    "1:64 Scale",
    "1:43 Scale",
    "1:18 Scale",
    "Factory Sealed",
    "Back in Stock",
    "Sold Out",
    "Discontinued",
]


def _generate_next_sku(conn=None) -> str:
    db = conn or get_db()
    rows = db.execute("SELECT sku FROM products").fetchall()
    max_num = 0
    for r in rows:
        m = re.match(r"^DWI-(\d+)$", (r["sku"] or "").strip(), flags=re.IGNORECASE)
        if m:
            max_num = max(max_num, int(m.group(1)))
    cand = f"DWI-{max_num + 1:03d}"
    while db.execute("SELECT 1 FROM products WHERE sku = ? COLLATE NOCASE", (cand,)).fetchone():
        max_num += 1
        cand = f"DWI-{max_num + 1:03d}"
    return cand


def _split_badges(badge_str: str) -> tuple[list[str], str]:
    preset_map = {b.lower(): b for b in PRESET_BADGES}
    selected: list[str] = []
    custom: list[str] = []
    for part in (badge_str or "").split(","):
        clean = part.strip()
        if not clean:
            continue
        if clean.lower() in preset_map:
            canonical = preset_map[clean.lower()]
            if canonical not in selected:
                selected.append(canonical)
        else:
            custom.append(clean)
    return selected, ", ".join(custom)


_STATUS_BADGE_MAP = {
    "in_stock": "stock-in",
    "hot_drop": "hot-drop",
    "pre_order": "pre-order",
    "sold_out": "hot-drop",
    "discontinued": "stock-in",
}

_COMMON_MANUFACTURERS = [
    "TSM Model",
    "Kaido House",
    "Kaido House / Mini GT",
    "Mini GT",
    "Pop Race",
    "Inno64",
    "Mattel / Hot Wheels",
    "Hot Wheels",
    "Tarmac Works",
    "Almost Real",
    "Bburago",
    "Solido",
    "Ignition Model",
    "BBR Models",
    "Spark",
    "CM Model",
    "Time Micro",
    "LCD Models",
    "GreenLight",
    "PosterCars",
    "Takara Tomy",
    "Welly",
    "TINY",
    "GCD",
    "Para64",
    "Hobby Japan",
    "Motor Helix",
    "Stance Hunters",
    "Kinsmart",
    "Massdi",
    "RMZ City",
    "Diecast Masters",
    "NZG",
    "Rastar",
    "More Art",
    "Morepost",
    "Diecast World India",
]


def _list_manufacturers() -> list[str]:
    db = get_db()
    seen: set[str] = set()
    ordered: list[str] = []

    def _push(val: str) -> None:
        clean = (val or "").strip()
        if not clean or clean.lower() in seen:
            return
        seen.add(clean.lower())
        ordered.append(clean)

    for item in _COMMON_MANUFACTURERS:
        _push(item)
    for r in db.execute("SELECT DISTINCT manufacturer FROM products WHERE TRIM(manufacturer) != '' ORDER BY manufacturer ASC").fetchall():
        _push(r["manufacturer"])
    for b in list_brands(active_only=False):
        _push(b["name"])
    return ordered


def _resolve_vehicle_maker_entry(identifier: str, vehicle_makers: list[dict] | None = None) -> dict | None:
    clean = (identifier or "").strip()
    if not clean:
        return None
    makers = vehicle_makers if vehicle_makers is not None else get_vehicle_maker_strips()
    low = clean.lower()
    for m in makers:
        if m["key"].lower() == low or m["name"].lower() == low:
            return m
    return None


def _detect_vehicle_maker(prod: dict | None, vehicle_makers: list[dict]) -> dict | None:
    if not prod:
        return None
    hay = f"{prod.get('vehicle_model', '')} {prod.get('name', '')} {prod.get('tags', '')}"
    for m in vehicle_makers:
        tokens = [t.strip().lower() for t in m.get("tokens", []) if t and t.strip()]
        if any(_matches_word_token(hay, tok) for tok in tokens):
            return m
    return None


def _build_auto_description(
    brand_name: str,
    name: str,
    vehicle_model: str,
    manufacturer: str,
    scale: str,
    condition: str,
    specs: dict,
    is_pre_order: int,
) -> str:
    maker_label = manufacturer or brand_name or "authorized diecast maker"
    chassis = specs.get("chassis", "Diecast Metal")
    wheels = specs.get("wheels", "Real Rider Rubber")
    opening = specs.get("opening", "Fixed (Precision Sealed)")
    packaging = specs.get("packaging", "Collector Box")
    model_phrase = f" ({vehicle_model})" if vehicle_model and vehicle_model.lower() not in name.lower() else ""
    lead = f"{name}{model_phrase} — {scale or '1:64'} scale {chassis.lower()} collectible by {maker_label}, featuring {opening.lower()} and {wheels.lower()}."
    if is_pre_order:
        return f"{lead} Open for collector pre-order booking; delivered in {packaging} ({condition})."
    return f"{lead} Delivered in {packaging} ({condition} condition)."


def _save_product_from_form(existing_id: int | None = None) -> int:
    admin = get_current_admin()
    f = request.form
    sku = (f.get("sku") or "").strip().upper()
    if existing_id is None and not sku:
        sku = _generate_next_sku()
    name = (f.get("name") or "").strip()
    if not sku or not name:
        raise ValueError("SKU and Product Name are required.")

    brand_id = int(f.get("brand_id"))
    category_id = int(f.get("category_id"))
    manufacturer = (f.get("manufacturer") or "").strip()
    vehicle_model = (f.get("vehicle_model") or "").strip()
    scale = (f.get("scale") or "1:64").strip()
    price_paise = rupees_to_paise(f.get("price_inr", "0"))
    mrp_paise = rupees_to_paise(f.get("mrp_inr", "0"))
    if mrp_paise < price_paise:
        mrp_paise = price_paise

    disc_raw = (f.get("discount_percent") or "").strip()
    if disc_raw.isdigit():
        discount_percent = max(0, min(100, int(disc_raw)))
    else:
        discount_percent = round(((mrp_paise - price_paise) / mrp_paise) * 100) if mrp_paise > price_paise else 0

    availability_status = f.get("availability_status", "in_stock")
    if availability_status not in ("in_stock", "hot_drop", "pre_order", "sold_out", "discontinued"):
        availability_status = "in_stock"

    is_discontinued = 1 if (f.get("is_discontinued") == "1" or availability_status == "discontinued") else 0
    is_featured = 1 if f.get("is_featured") == "1" else 0
    is_limited_edition = 1 if f.get("is_limited_edition") == "1" else 0
    is_sold_out = 1 if (f.get("is_sold_out") == "1" or availability_status == "sold_out") else 0
    is_pre_order = 1 if (f.get("is_pre_order") == "1" or availability_status == "pre_order") else 0
    if is_discontinued:
        availability_status = "discontinued"
    elif is_pre_order and availability_status == "in_stock":
        availability_status = "pre_order"
    garage_hold_eligible = 1 if f.get("garage_hold_eligible") == "1" else 0
    is_visible = 1 if f.get("is_visible") == "1" else 0

    selected_badges = [b.strip() for b in f.getlist("badge_choices") if b and b.strip()]
    custom_badge_raw = (f.get("badge_text") or "").strip()
    custom_badges = [b.strip() for b in custom_badge_raw.split(",") if b.strip()]
    combined_badges: list[str] = []
    for b in [*selected_badges, *custom_badges]:
        if b.lower() not in {x.lower() for x in combined_badges}:
            combined_badges.append(b)
    badge_text = ", ".join(combined_badges)
    badge_type = (f.get("badge_type") or "").strip()
    if badge_type not in ("stock-in", "hot-drop", "pre-order", "chase-tag", "discontinued-tag"):
        badge_type = _STATUS_BADGE_MAP.get(availability_status, "stock-in")
    description = (f.get("description") or "").strip()
    condition = (f.get("condition") or "Mint / Factory Sealed").strip()
    tags = (f.get("tags") or "").strip()

    vm_entry = _resolve_vehicle_maker_entry(f.get("vehicle_maker") or "")
    if vm_entry:
        if not vehicle_model:
            vehicle_model = vm_entry["name"]
        vm_tokens = [t.strip().lower() for t in vm_entry.get("tokens", []) if t and t.strip()]
        hay = f"{vehicle_model} {name} {tags}"
        if vm_tokens and not any(_matches_word_token(hay, tok) for tok in vm_tokens):
            existing_tags = [t.strip() for t in tags.split(",") if t.strip()]
            existing_tags.append(vm_tokens[0])
            tags = ", ".join(existing_tags)

    specs = {
        "chassis": (f.get("spec_chassis") or "Diecast Metal").strip(),
        "wheels": (f.get("spec_wheels") or "Real Rider Rubber").strip(),
        "opening": (f.get("spec_opening") or "Fixed (Precision Sealed)").strip(),
        "packaging": (f.get("spec_packaging") or "Collector Box").strip(),
    }

    if not description:
        b_row = get_db().execute("SELECT name FROM brands WHERE id = ?", (brand_id,)).fetchone()
        b_name = b_row["name"] if b_row else ""
        description = _build_auto_description(
            brand_name=b_name,
            name=name,
            vehicle_model=vehicle_model,
            manufacturer=manufacturer,
            scale=scale,
            condition=condition,
            specs=specs,
            is_pre_order=is_pre_order,
        )

    expected_release_date = (f.get("expected_release_date") or "").strip()
    expected_arrival_date = (f.get("expected_arrival_date") or "").strip()
    raw_token_inr = (f.get("pre_order_token_inr") or "").strip()
    parsed_token_paise = rupees_to_paise(raw_token_inr or "0")
    pre_order_token_paise = 19900 if (is_pre_order and parsed_token_paise == 0) else parsed_token_paise
    pre_order_allocation = max(0, int(f.get("pre_order_allocation") or 0))
    pre_order_limit = max(1, int(f.get("pre_order_limit_per_customer") or 2))
    pre_order_closing_date = (f.get("pre_order_closing_date") or "").strip()

    stock_qty = max(0, int(f.get("stock_qty") or 0))
    low_stock_threshold = max(0, int(f.get("low_stock_threshold") or 3))

    slug = f"{slugify(sku)}-{slugify(name)[:60]}"

    with transaction() as conn:
        if existing_id is None:
            dup = conn.execute("SELECT id FROM products WHERE sku = ? COLLATE NOCASE", (sku,)).fetchone()
            if dup:
                raise ValueError(f"SKU {sku} already exists.")
            cur = conn.execute(
                """
                INSERT INTO products (
                    sku, slug, name, brand_id, category_id, manufacturer, vehicle_model,
                    scale, price_paise, mrp_paise, discount_percent, badge_text, badge_type,
                    description, specifications_json, condition, availability_status, tags,
                    is_featured, is_limited_edition, is_sold_out, is_pre_order,
                    garage_hold_eligible, expected_release_date, expected_arrival_date,
                    pre_order_token_paise, pre_order_allocation, pre_order_limit_per_customer,
                    pre_order_closing_date, is_visible
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                """,
                (
                    sku, slug, name, brand_id, category_id, manufacturer, vehicle_model,
                    scale, price_paise, mrp_paise, discount_percent, badge_text, badge_type,
                    description, json.dumps(specs), condition, availability_status, tags,
                    is_featured, is_limited_edition, is_sold_out, is_pre_order,
                    garage_hold_eligible, expected_release_date, expected_arrival_date,
                    pre_order_token_paise, pre_order_allocation, pre_order_limit,
                    pre_order_closing_date, is_visible,
                ),
            )
            product_id = cur.lastrowid
            conn.execute(
                "INSERT INTO inventory (product_id, stock_qty, reserved_qty, low_stock_threshold) VALUES (?, ?, 0, ?)",
                (product_id, stock_qty, low_stock_threshold),
            )
            conn.execute(
                """
                INSERT INTO inventory_history (product_id, change_qty, previous_qty, new_qty, change_type, note, actor_type, actor_id)
                VALUES (?, ?, 0, ?, 'initial', 'Product created in admin', 'admin', ?)
                """,
                (product_id, stock_qty, stock_qty, admin["id"]),
            )
            log_admin_action(conn, admin, "product_created", "product", product_id, {"sku": sku, "name": name})
        else:
            product_id = existing_id
            dup = conn.execute(
                "SELECT id FROM products WHERE sku = ? COLLATE NOCASE AND id != ?",
                (sku, product_id),
            ).fetchone()
            if dup:
                raise ValueError(f"Another product already uses SKU {sku}.")
            conn.execute(
                """
                UPDATE products
                SET sku = ?, slug = ?, name = ?, brand_id = ?, category_id = ?, manufacturer = ?,
                    vehicle_model = ?, scale = ?, price_paise = ?, mrp_paise = ?, discount_percent = ?,
                    badge_text = ?, badge_type = ?, description = ?, specifications_json = ?,
                    condition = ?, availability_status = ?, tags = ?, is_featured = ?,
                    is_limited_edition = ?, is_sold_out = ?, is_pre_order = ?,
                    garage_hold_eligible = ?, expected_release_date = ?, expected_arrival_date = ?,
                    pre_order_token_paise = ?, pre_order_allocation = ?, pre_order_limit_per_customer = ?,
                    pre_order_closing_date = ?, is_visible = ?, updated_at = datetime('now')
                WHERE id = ?
                """,
                (
                    sku, slug, name, brand_id, category_id, manufacturer,
                    vehicle_model, scale, price_paise, mrp_paise, discount_percent,
                    badge_text, badge_type, description, json.dumps(specs),
                    condition, availability_status, tags, is_featured,
                    is_limited_edition, is_sold_out, is_pre_order,
                    garage_hold_eligible, expected_release_date, expected_arrival_date,
                    pre_order_token_paise, pre_order_allocation, pre_order_limit,
                    pre_order_closing_date, is_visible, product_id,
                ),
            )
            inv = conn.execute("SELECT stock_qty, reserved_qty FROM inventory WHERE product_id = ?", (product_id,)).fetchone()
            if inv:
                if stock_qty < int(inv["reserved_qty"]):
                    raise ValueError(f"Stock cannot be less than reserved units ({inv['reserved_qty']}).")
                prev_qty = int(inv["stock_qty"])
                conn.execute(
                    "UPDATE inventory SET stock_qty = ?, low_stock_threshold = ?, updated_at = datetime('now') WHERE product_id = ?",
                    (stock_qty, low_stock_threshold, product_id),
                )
                if stock_qty != prev_qty:
                    conn.execute(
                        """
                        INSERT INTO inventory_history (product_id, change_qty, previous_qty, new_qty, change_type, note, actor_type, actor_id)
                        VALUES (?, ?, ?, ?, 'adjustment', 'Edited via product form', 'admin', ?)
                        """,
                        (product_id, stock_qty - prev_qty, prev_qty, stock_qty, admin["id"]),
                    )
            log_admin_action(conn, admin, "product_updated", "product", product_id, {"sku": sku, "name": name})
            if not is_visible:
                conn.execute(
                    "UPDATE homepage_sections SET is_active = 0, updated_at = datetime('now') WHERE link_product_sku = ? COLLATE NOCASE",
                    (sku,),
                )
            if not is_visible or availability_status == "discontinued":
                conn.execute("DELETE FROM cart_items WHERE product_id = ?", (product_id,))
                conn.execute("DELETE FROM garage_shelf_items WHERE product_id = ?", (product_id,))

        # Apply staged image deletions only when Save Changes is submitted
        delete_ids = [
            int(val) for val in f.getlist("delete_image_ids") if str(val).strip().isdigit()
        ]
        if existing_id is not None and delete_ids:
            placeholders = ",".join("?" * len(delete_ids))
            conn.execute(
                f"DELETE FROM product_images WHERE product_id = ? AND id IN ({placeholders})",
                (product_id, *delete_ids),
            )
            log_admin_action(
                conn, admin, "product_images_deleted", "product", product_id, {"image_ids": delete_ids}
            )

        # Handle optional image URL field
        image_url_input = (f.get("image_url") or "").strip()
        if image_url_input:
            has_primary = conn.execute(
                "SELECT 1 FROM product_images WHERE product_id = ? AND is_primary = 1",
                (product_id,),
            ).fetchone()
            conn.execute(
                "INSERT INTO product_images (product_id, image_url, is_primary, sort_order, alt_text) VALUES (?, ?, ?, 0, ?)",
                (product_id, image_url_input, 0 if has_primary else 1, name),
            )

        # Handle uploaded product images (multiple)
        uploaded_files = request.files.getlist("product_images")
        max_sort_row = conn.execute(
            "SELECT COALESCE(MAX(sort_order), -1) AS ms FROM product_images WHERE product_id = ?",
            (product_id,),
        ).fetchone()
        base_sort = int(max_sort_row["ms"]) + 1 if max_sort_row else 0
        for idx, file_storage in enumerate(uploaded_files):
            if not file_storage or not file_storage.filename:
                continue
            fname, _mime, _size = save_uploaded_image(
                file_storage, current_app.config["PRODUCT_UPLOADS_DIR"], prefix="prod"
            )
            img_url = f"/uploads/products/{fname}"
            has_primary = conn.execute(
                "SELECT 1 FROM product_images WHERE product_id = ? AND is_primary = 1",
                (product_id,),
            ).fetchone()
            conn.execute(
                "INSERT INTO product_images (product_id, image_url, is_primary, sort_order, alt_text) VALUES (?, ?, ?, ?, ?)",
                (product_id, img_url, 0 if has_primary else 1, base_sort + idx, name),
            )

        # Apply staged primary image selection (or ensure one remaining image is primary)
        staged_primary_raw = (f.get("primary_image_id") or "").strip()
        if staged_primary_raw.isdigit():
            staged_pid = int(staged_primary_raw)
            exists = conn.execute(
                "SELECT 1 FROM product_images WHERE id = ? AND product_id = ?",
                (staged_pid, product_id),
            ).fetchone()
            if exists:
                conn.execute("UPDATE product_images SET is_primary = 0 WHERE product_id = ?", (product_id,))
                conn.execute(
                    "UPDATE product_images SET is_primary = 1 WHERE id = ? AND product_id = ?",
                    (staged_pid, product_id),
                )
        rem_primary = conn.execute(
            "SELECT id FROM product_images WHERE product_id = ? AND is_primary = 1 LIMIT 1",
            (product_id,),
        ).fetchone()
        if not rem_primary:
            fallback_img = conn.execute(
                "SELECT id FROM product_images WHERE product_id = ? ORDER BY sort_order ASC, id ASC LIMIT 1",
                (product_id,),
            ).fetchone()
            if fallback_img:
                conn.execute("UPDATE product_images SET is_primary = 1 WHERE id = ?", (fallback_img["id"],))

    return product_id


@admin_bp.route("/products/new", methods=["GET", "POST"])
@admin_login_required
@csrf_protect
def product_new():
    if request.method == "POST":
        try:
            pid = _save_product_from_form(None)
            flash("Product created successfully.", "success")
            return redirect(url_for("admin.product_edit", product_id=pid))
        except ValueError as exc:
            flash(str(exc), "error")
    vehicle_makers = get_vehicle_maker_strips()
    return render_template(
        "admin/product_form.html",
        product=None,
        next_sku=_generate_next_sku(),
        preset_badges=PRESET_BADGES,
        selected_badges=[],
        custom_badge_text="",
        brands=list_brands(active_only=False),
        categories=list_categories(active_only=False),
        manufacturers=_list_manufacturers(),
        vehicle_makers=vehicle_makers,
        selected_vehicle_maker=None,
    )


@admin_bp.route("/products/<int:product_id>/edit", methods=["GET", "POST"])
@admin_login_required
@csrf_protect
def product_edit(product_id: int):
    prod = get_product_by_identifier(str(product_id), include_hidden=True)
    if not prod:
        flash("Product not found.", "error")
        return redirect(url_for("admin.products_list"))
    if request.method == "POST":
        try:
            _save_product_from_form(product_id)
            flash("Product updated successfully.", "success")
            return redirect(url_for("admin.product_edit", product_id=product_id))
        except ValueError as exc:
            flash(str(exc), "error")
    selected_badges, custom_badge_text = _split_badges(prod.get("badge_text", ""))
    vehicle_makers = get_vehicle_maker_strips()
    return render_template(
        "admin/product_form.html",
        product=prod,
        next_sku=prod["sku"],
        preset_badges=PRESET_BADGES,
        selected_badges=selected_badges,
        custom_badge_text=custom_badge_text,
        brands=list_brands(active_only=False),
        categories=list_categories(active_only=False),
        manufacturers=_list_manufacturers(),
        vehicle_makers=vehicle_makers,
        selected_vehicle_maker=_detect_vehicle_maker(prod, vehicle_makers),
    )


@admin_bp.route("/products/<int:product_id>/images/<int:image_id>/primary", methods=["POST"])
@admin_login_required
@csrf_protect
def product_set_primary_image(product_id: int, image_id: int):
    flash("Image changes are staged locally — click Save Changes on the product form to apply.", "info")
    return redirect(url_for("admin.product_edit", product_id=product_id))


@admin_bp.route("/products/<int:product_id>/images/<int:image_id>/delete", methods=["POST"])
@admin_login_required
@csrf_protect
def product_delete_image(product_id: int, image_id: int):
    flash("Image removals are staged locally — click Save Changes on the product form to apply.", "info")
    return redirect(url_for("admin.product_edit", product_id=product_id))


@admin_bp.route("/products/<int:product_id>/delete", methods=["POST"])
@admin_login_required
@csrf_protect
def product_delete(product_id: int):
    admin = get_current_admin()
    db = get_db()
    prod = db.execute("SELECT id, sku, name FROM products WHERE id = ?", (product_id,)).fetchone()
    if not prod:
        flash("Product not found.", "error")
        return redirect(url_for("admin.products_list"))
    sku = prod["sku"]
    used_in_order = db.execute("SELECT 1 FROM order_items WHERE product_id = ? LIMIT 1", (product_id,)).fetchone()
    with transaction(db) as conn:
        if used_in_order:
            conn.execute(
                "UPDATE products SET is_visible = 0, availability_status = 'discontinued', updated_at = datetime('now') WHERE id = ?",
                (product_id,),
            )
            conn.execute(
                "UPDATE homepage_sections SET is_active = 0, updated_at = datetime('now') WHERE link_product_sku = ? COLLATE NOCASE",
                (sku,),
            )
            conn.execute("DELETE FROM cart_items WHERE product_id = ?", (product_id,))
            conn.execute("DELETE FROM wishlist WHERE product_id = ?", (product_id,))
            conn.execute("DELETE FROM garage_shelf_items WHERE product_id = ?", (product_id,))
            log_admin_action(conn, admin, "product_archived", "product", product_id, {"sku": sku})
            flash("Product has existing orders; archived, hidden everywhere & muted from homepage feeds.", "success")
        else:
            conn.execute("DELETE FROM homepage_sections WHERE link_product_sku = ? COLLATE NOCASE", (sku,))
            conn.execute("DELETE FROM products WHERE id = ?", (product_id,))
            log_admin_action(conn, admin, "product_deleted", "product", product_id, {"sku": sku})
            flash("Product deleted from catalog and homepage feeds.", "success")
    return redirect(url_for("admin.products_list"))


# ==========================================================================
# MODULE B: ORDER MANAGEMENT
# ==========================================================================
@admin_bp.route("/orders")
@admin_login_required
def orders_list():
    q = (request.args.get("q") or "").strip()
    status_filter = request.args.get("status", "all")
    clauses = []
    params = []
    if status_filter and status_filter != "all":
        clauses.append("o.status = ?")
        params.append(status_filter)
    if q:
        like = f"%{q}%"
        clauses.append("(o.order_number LIKE ? OR o.customer_name LIKE ? OR o.customer_phone LIKE ? OR o.customer_email LIKE ?)")
        params.extend([like, like, like, like])
    where_sql = ("WHERE " + " AND ".join(clauses)) if clauses else ""
    rows = get_db().execute(
        f"""
        SELECT o.*, pay.status AS payment_status, pay.utr_number,
               s.courier_name, s.tracking_number
        FROM orders o
        LEFT JOIN payments pay ON pay.id = (SELECT id FROM payments WHERE order_id = o.id ORDER BY id DESC LIMIT 1)
        LEFT JOIN shipping s ON s.order_id = o.id
        {where_sql}
        ORDER BY o.id DESC
        LIMIT 200
        """,
        params,
    ).fetchall()
    orders = []
    for r in rows:
        d = dict(r)
        d["total_formatted"] = format_inr(d["total_paise"])
        orders.append(d)
    return render_template(
        "admin/orders.html",
        orders=orders,
        statuses=ORDER_STATUSES,
        filters={"q": q, "status": status_filter},
    )


@admin_bp.route("/orders/<int:order_id>", methods=["GET", "POST"])
@admin_login_required
@csrf_protect
def order_detail(order_id: int):
    admin = get_current_admin()
    if request.method == "POST":
        try:
            update_order_status(
                order_id=order_id,
                new_status=request.form.get("status", ""),
                admin_user=admin,
                note=request.form.get("note", ""),
                courier_name=request.form.get("courier_name", ""),
                tracking_number=request.form.get("tracking_number", ""),
                tracking_url=request.form.get("tracking_url", ""),
                shipping_date=request.form.get("shipping_date", ""),
                delivered_date=request.form.get("delivered_date", ""),
                dispatch_notes=request.form.get("dispatch_notes", ""),
            )
            flash("Order status and history updated.", "success")
            return redirect(url_for("admin.order_detail", order_id=order_id))
        except ValueError as exc:
            flash(str(exc), "error")

    order = get_order_full_details(order_id)
    if not order:
        flash("Order not found.", "error")
        return redirect(url_for("admin.orders_list"))
    allowed_statuses = get_allowed_admin_transitions(order["status"], order=order, db=get_db())
    garage_dispatch_ready = order_garage_dispatch_allowed(get_db(), order)
    return render_template(
        "admin/order_detail.html",
        order=order,
        statuses=ORDER_STATUSES,
        allowed_statuses=allowed_statuses,
        garage_dispatch_ready=garage_dispatch_ready,
    )


# ==========================================================================
# MODULE C: PAYMENT VERIFICATION
# ==========================================================================
@admin_bp.route("/payments")
@admin_login_required
def payments_list():
    status_filter = request.args.get("status", "Verification Pending")
    where = "" if status_filter == "all" else "WHERE p.status = ?"
    params = () if status_filter == "all" else (status_filter,)
    rows = get_db().execute(
        f"""
        SELECT p.*, o.id AS order_id, o.order_number, o.customer_name, o.customer_phone, o.status AS order_status,
               (SELECT file_path FROM payment_proofs pp WHERE pp.payment_id = p.id ORDER BY pp.id DESC LIMIT 1) AS proof_file,
               au.full_name AS verified_by_name
        FROM payments p
        JOIN orders o ON o.id = p.order_id
        LEFT JOIN admin_users au ON au.id = p.verified_by_admin_id
        {where}
        ORDER BY p.id DESC
        LIMIT 200
        """,
        params,
    ).fetchall()
    payments = []
    for r in rows:
        d = dict(r)
        d["amount_formatted"] = format_inr(d["amount_paise"])
        payments.append(d)

    proof_history = [
        dict(r)
        for r in get_db().execute(
            """
            SELECT pp.*, o.order_number, au.full_name AS reviewer_name
            FROM payment_proofs pp
            JOIN orders o ON o.id = pp.order_id
            LEFT JOIN admin_users au ON au.id = pp.reviewed_by_admin_id
            ORDER BY pp.id DESC
            LIMIT 50
            """
        ).fetchall()
    ]
    return render_template(
        "admin/payments.html",
        payments=payments,
        proof_history=proof_history,
        status_filter=status_filter,
    )


@admin_bp.route("/payments/<int:payment_id>/review", methods=["POST"])
@admin_login_required
@csrf_protect
def payment_review(payment_id: int):
    admin = get_current_admin()
    decision = request.form.get("decision", "")
    note = (request.form.get("note") or "").strip()
    cancel_on_reject = request.form.get("cancel_on_reject") == "1"
    try:
        res = review_payment(
            payment_id=payment_id,
            decision=decision,
            admin_user=admin,
            note=note,
            cancel_on_reject=cancel_on_reject,
        )
        flash(f"Payment marked as {res['status']} (Order: {res['order_status']}).", "success")
    except ValueError as exc:
        flash(str(exc), "error")
    next_url = request.form.get("next") or url_for("admin.payments_list")
    return redirect(next_url)


# ==========================================================================
# MODULE D: SHIPPING MANAGEMENT
# ==========================================================================
@admin_bp.route("/shipping", methods=["GET", "POST"])
@admin_login_required
@csrf_protect
def shipping_management():
    admin = get_current_admin()
    if request.method == "POST":
        action = request.form.get("action")
        if action == "update_rules":
            with transaction() as conn:
                updates = {
                    "shipping_charge_paise": str(rupees_to_paise(request.form.get("shipping_charge_inr", "99"))),
                    "garage_dispatch_fee_paise": str(rupees_to_paise(request.form.get("garage_fee_inr", "99"))),
                }
                for k, v in updates.items():
                    conn.execute(
                        "UPDATE store_settings SET value = ?, updated_at = datetime('now') WHERE key = ?",
                        (v, k),
                    )
                log_admin_action(conn, admin, "shipping_rules_updated", "store_settings", "shipping", updates)
            flash("Shipping rules saved.", "success")
            return redirect(url_for("admin.shipping_management"))

    settings = get_store_settings()
    rows = get_db().execute(
        """
        SELECT o.id, o.order_number, o.customer_name, o.customer_phone, o.status, o.total_paise,
               o.shipping_address_json, s.courier_name, s.tracking_number, s.tracking_url, s.shipping_date, s.delivered_date
        FROM orders o
        LEFT JOIN shipping s ON s.order_id = o.id
        WHERE o.status IN ('Payment Verified', 'Order Confirmed', 'Processing', 'Packed', 'Shipped', 'Out for Delivery')
        ORDER BY o.id DESC
        """
    ).fetchall()
    shipments = []
    for r in rows:
        d = dict(r)
        d["address"] = parse_json_safe(d.get("shipping_address_json"), {})
        d["total_formatted"] = format_inr(d["total_paise"])
        shipments.append(d)

    return render_template("admin/shipping.html", settings=settings, shipments=shipments)


# ==========================================================================
# MODULE E: CUSTOMER MANAGEMENT
# ==========================================================================
@admin_bp.route("/customers")
@admin_login_required
def customers_list():
    rows = get_db().execute(
        """
        SELECT cu.id, cu.email, cu.is_active, cu.created_at, cu.last_login_at,
               cp.full_name, cp.phone,
               (SELECT COUNT(*) FROM orders o WHERE o.customer_id = cu.id) AS order_count,
               (SELECT COALESCE(SUM(o.total_paise), 0) FROM orders o WHERE o.customer_id = cu.id AND o.status NOT IN ('Cancelled', 'Refunded')) AS total_spent_paise,
               (SELECT COUNT(*) FROM garage_holds gh WHERE gh.customer_id = cu.id AND gh.hold_status = 'active') AS active_holds
        FROM customer_users cu
        LEFT JOIN customer_profiles cp ON cp.customer_id = cu.id
        ORDER BY cu.id DESC
        """
    ).fetchall()
    customers = []
    for r in rows:
        d = dict(r)
        d["total_spent_formatted"] = format_inr(d["total_spent_paise"])
        customers.append(d)
    return render_template("admin/customers.html", customers=customers)


@admin_bp.route("/customers/<int:customer_id>/toggle", methods=["POST"])
@admin_login_required
@csrf_protect
def customer_toggle(customer_id: int):
    admin = get_current_admin()
    with transaction() as conn:
        row = conn.execute("SELECT is_active FROM customer_users WHERE id = ?", (customer_id,)).fetchone()
        if row:
            new_val = 0 if row["is_active"] else 1
            conn.execute("UPDATE customer_users SET is_active = ? WHERE id = ?", (new_val, customer_id))
            log_admin_action(conn, admin, "customer_status_toggled", "customer", customer_id, {"is_active": new_val})
    flash("Customer account status updated.", "success")
    return redirect(url_for("admin.customers_list"))


# ==========================================================================
# MODULE F: INVENTORY MANAGEMENT
# ==========================================================================
@admin_bp.route("/inventory", methods=["GET", "POST"])
@admin_login_required
@csrf_protect
def inventory_management():
    admin = get_current_admin()
    if request.method == "POST":
        try:
            product_id = int(request.form.get("product_id"))
            new_qty = int(request.form.get("stock_qty"))
            threshold = int(request.form.get("low_stock_threshold", 3))
            note = (request.form.get("note") or "Manual stock adjustment").strip()
            adjust_inventory(
                product_id=product_id,
                new_stock_qty=new_qty,
                note=note,
                actor_type="admin",
                actor_id=admin["id"],
                low_stock_threshold=threshold,
            )
            with transaction() as conn:
                log_admin_action(conn, admin, "inventory_adjusted", "product", product_id, {"new_qty": new_qty, "note": note})
            flash("Inventory updated.", "success")
            return redirect(url_for("admin.inventory_management"))
        except ValueError as exc:
            flash(str(exc), "error")

    items = [
        dict(r)
        for r in get_db().execute(
            """
            SELECT p.id, p.sku, p.name, p.scale, p.availability_status, p.is_sold_out,
                   b.name AS brand_name,
                   i.stock_qty, i.reserved_qty, (i.stock_qty - i.reserved_qty) AS available_qty,
                   i.low_stock_threshold, i.updated_at
            FROM products p
            JOIN brands b ON b.id = p.brand_id
            JOIN inventory i ON i.product_id = p.id
            ORDER BY available_qty ASC, p.id ASC
            """
        ).fetchall()
    ]
    history = [
        dict(r)
        for r in get_db().execute(
            """
            SELECT ih.*, p.sku, p.name AS product_name
            FROM inventory_history ih
            JOIN products p ON p.id = ih.product_id
            ORDER BY ih.id DESC
            LIMIT 60
            """
        ).fetchall()
    ]
    return render_template("admin/inventory.html", items=items, history=history)


# ==========================================================================
# MODULE G: PRE-ORDERS MANAGEMENT
# ==========================================================================
@admin_bp.route("/preorders", methods=["GET", "POST"])
@admin_login_required
@csrf_protect
def preorders_management():
    admin = get_current_admin()
    if request.method == "POST":
        action = request.form.get("action")
        with transaction() as conn:
            if action == "update_preorder_status":
                po_id = int(request.form.get("pre_order_id"))
                new_status = request.form.get("status")
                conn.execute(
                    "UPDATE pre_orders SET status = ?, updated_at = datetime('now') WHERE id = ?",
                    (new_status, po_id),
                )
                log_admin_action(conn, admin, "preorder_status_updated", "pre_order", po_id, {"status": new_status})
                flash("Pre-order status updated.", "success")
            elif action == "update_product_eta":
                pid = int(request.form.get("product_id"))
                eta = (request.form.get("expected_arrival_date") or "").strip()
                rel = (request.form.get("expected_release_date") or "").strip()
                alloc = max(0, int(request.form.get("pre_order_allocation") or 0))
                conn.execute(
                    """
                    UPDATE products
                    SET expected_arrival_date = ?, expected_release_date = ?, pre_order_allocation = ?, updated_at = datetime('now')
                    WHERE id = ?
                    """,
                    (eta, rel, alloc, pid),
                )
                log_admin_action(conn, admin, "preorder_product_updated", "product", pid, {"eta": eta, "allocation": alloc})
                flash("Pre-order schedule updated.", "success")
        return redirect(url_for("admin.preorders_management"))

    po_products = query_products(pre_order_only=True, include_hidden=True, per_page=100)["items"]
    rows = get_db().execute(
        """
        SELECT po.*, o.order_number, o.status AS order_status
        FROM pre_orders po
        JOIN orders o ON o.id = po.order_id
        ORDER BY po.id DESC
        """
    ).fetchall()
    preorders = []
    for r in rows:
        d = dict(r)
        d["token_formatted"] = format_inr(d["total_token_paise"])
        d["balance_formatted"] = format_inr(d["total_balance_paise"])
        d["items"] = [
            dict(it)
            for it in get_db().execute(
                """
                SELECT poi.*, p.sku, p.name AS product_name
                FROM pre_order_items poi
                JOIN products p ON p.id = poi.product_id
                WHERE poi.pre_order_id = ?
                """,
                (r["id"],),
            ).fetchall()
        ]
        preorders.append(d)

    return render_template("admin/preorders.html", po_products=po_products, preorders=preorders)


# ==========================================================================
# MODULE H: GARAGE HOLD MANAGEMENT
# ==========================================================================
@admin_bp.route("/garage", methods=["GET", "POST"])
@admin_login_required
@csrf_protect
def garage_management():
    admin = get_current_admin()
    sync_expired_holds()

    if request.method == "POST":
        action = request.form.get("action")
        try:
            if action == "extend_hold":
                hold_id = int(request.form.get("hold_id"))
                extra_days = int(request.form.get("extra_days", 15))
                note = (request.form.get("note") or "").strip()
                admin_extend_hold(hold_id, extra_days, note, admin)
                flash(f"Hold extended by {extra_days} days.", "success")
            elif action == "update_dispatch":
                req_id = int(request.form.get("request_id"))
                fee_raw = (request.form.get("shipping_fee_inr") or "").strip()
                fee_paise = rupees_to_paise(fee_raw) if fee_raw != "" else None
                admin_update_dispatch_request(
                    request_id=req_id,
                    new_status=request.form.get("status", "Pending"),
                    admin_user=admin,
                    courier_name=(request.form.get("courier_name") or "").strip(),
                    tracking_number=(request.form.get("tracking_number") or "").strip(),
                    tracking_url=(request.form.get("tracking_url") or "").strip(),
                    shipping_fee_paise=fee_paise,
                    admin_notes=(request.form.get("admin_notes") or "").strip(),
                )
                flash("Dispatch request updated.", "success")
            return redirect(url_for("admin.garage_management"))
        except ValueError as exc:
            flash(str(exc), "error")

    holds = [
        dict(r)
        for r in get_db().execute(
            """
            SELECT gh.*, cu.email AS customer_email, cp.full_name AS customer_name, cp.phone AS customer_phone,
                   p.sku, p.name AS product_name, o.order_number,
                   CASE WHEN gh.expires_at IS NOT NULL THEN CAST(julianday(gh.expires_at) - julianday('now') AS INTEGER) ELSE NULL END AS days_remaining
            FROM garage_holds gh
            JOIN customer_users cu ON cu.id = gh.customer_id
            LEFT JOIN customer_profiles cp ON cp.customer_id = cu.id
            JOIN products p ON p.id = gh.product_id
            JOIN orders o ON o.id = gh.order_id
            ORDER BY gh.id DESC
            """
        ).fetchall()
    ]
    dispatch_requests = []
    for r in get_db().execute(
        """
        SELECT gdr.*, cp.full_name AS customer_name, cp.phone AS customer_phone, cu.email AS customer_email
        FROM garage_dispatch_requests gdr
        JOIN customer_users cu ON cu.id = gdr.customer_id
        LEFT JOIN customer_profiles cp ON cp.customer_id = cu.id
        ORDER BY gdr.id DESC
        """
    ).fetchall():
        d = dict(r)
        d["address"] = parse_json_safe(d.get("shipping_address_json"), {})
        d["shipping_fee_formatted"] = format_inr(d["shipping_fee_paise"])
        dispatch_requests.append(d)

    return render_template("admin/garage.html", holds=holds, dispatch_requests=dispatch_requests)


# ==========================================================================
# MODULE I: COUPONS
# ==========================================================================
@admin_bp.route("/coupons", methods=["GET", "POST"])
@admin_login_required
@csrf_protect
def coupons_management():
    admin = get_current_admin()
    if request.method == "POST":
        action = request.form.get("action")
        try:
            with transaction() as conn:
                if action == "create":
                    code = (request.form.get("code") or "").strip().upper()
                    dtype = request.form.get("discount_type", "percent")
                    dval_raw = int(request.form.get("discount_value") or 0)
                    dval = dval_raw if dtype == "percent" else dval_raw * 100
                    min_paise = rupees_to_paise(request.form.get("min_order_inr", "0"))
                    max_paise = rupees_to_paise(request.form.get("max_discount_inr", "0"))
                    ulimit = max(0, int(request.form.get("usage_limit") or 0))
                    plimit = max(0, int(request.form.get("per_customer_limit") or 1))
                    if not code or dval <= 0:
                        raise ValueError("Valid coupon code and discount value are required.")
                    conn.execute(
                        """
                        INSERT INTO coupons (
                            code, description, discount_type, discount_value, min_order_paise,
                            max_discount_paise, usage_limit, per_customer_limit, starts_at, expires_at, is_active
                        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
                        """,
                        (
                            code,
                            (request.form.get("description") or "").strip(),
                            dtype,
                            dval,
                            min_paise,
                            max_paise,
                            ulimit,
                            plimit,
                            (request.form.get("starts_at") or "").strip() or None,
                            (request.form.get("expires_at") or "").strip() or None,
                        ),
                    )
                    log_admin_action(conn, admin, "coupon_created", "coupon", code)
                    flash(f"Coupon {code} created.", "success")
                elif action == "toggle":
                    cid = int(request.form.get("coupon_id"))
                    row = conn.execute("SELECT is_active, code FROM coupons WHERE id = ?", (cid,)).fetchone()
                    if row:
                        nv = 0 if row["is_active"] else 1
                        conn.execute("UPDATE coupons SET is_active = ?, updated_at = datetime('now') WHERE id = ?", (nv, cid))
                        log_admin_action(conn, admin, "coupon_toggled", "coupon", row["code"], {"is_active": nv})
                        flash("Coupon status updated.", "success")
            return redirect(url_for("admin.coupons_management"))
        except Exception as exc:
            flash(str(exc), "error")

    coupons = []
    for r in get_db().execute("SELECT * FROM coupons ORDER BY id DESC").fetchall():
        d = dict(r)
        d["value_display"] = f"{d['discount_value']}%" if d["discount_type"] == "percent" else format_inr(d["discount_value"])
        d["min_formatted"] = format_inr(d["min_order_paise"])
        d["max_formatted"] = format_inr(d["max_discount_paise"]) if d["max_discount_paise"] else "No cap"
        coupons.append(d)
    return render_template("admin/coupons.html", coupons=coupons)


# ==========================================================================
# MODULE J: HOMEPAGE CONTENT
# ==========================================================================
def _handle_gallery_action(conn, admin: dict, action: str) -> bool:
    """Handle gallery add/edit/delete POST actions cleanly for both Gallery & Content tabs."""
    if action == "add_gallery_photo":
        title = (request.form.get("title") or "").strip()
        caption = (request.form.get("caption") or "").strip()
        category_tag = (request.form.get("category_tag") or "Store Showcase").strip()
        sort_order = int(request.form.get("sort_order") or 0)
        uploaded_files = [f for f in request.files.getlist("gallery_images") if f and f.filename]
        img_url = (request.form.get("image_url") or "").strip()
        added_count = 0
        for idx, f_storage in enumerate(uploaded_files):
            fname, _m, _s = save_uploaded_image(
                f_storage, current_app.config["BANNER_UPLOADS_DIR"], prefix="gallery"
            )
            conn.execute(
                """
                INSERT INTO store_gallery_photos (title, caption, category_tag, image_url, sort_order, is_active)
                VALUES (?, ?, ?, ?, ?, 1)
                """,
                (title or "Store & Collector Showcase", caption, category_tag, f"/uploads/banners/{fname}", sort_order + idx),
            )
            added_count += 1
        if added_count == 0:
            if not img_url:
                raise ValueError("Please upload one or more gallery photos or provide an image URL.")
            conn.execute(
                """
                INSERT INTO store_gallery_photos (title, caption, category_tag, image_url, sort_order, is_active)
                VALUES (?, ?, ?, ?, ?, 1)
                """,
                (title or "Store & Collector Showcase", caption, category_tag, img_url, sort_order),
            )
            added_count = 1
        log_admin_action(conn, admin, "gallery_photo_added", "store_gallery", category_tag, {"count": added_count})
        flash(f"Added {added_count} gallery photo(s).", "success")
        return True
    if action == "edit_gallery_photo":
        gid = int(request.form.get("gallery_id"))
        title = (request.form.get("title") or "").strip()
        caption = (request.form.get("caption") or "").strip()
        category_tag = (request.form.get("category_tag") or "Store Showcase").strip()
        sort_order = int(request.form.get("sort_order") or 0)
        is_active = 1 if request.form.get("is_active") == "1" else 0
        conn.execute(
            """
            UPDATE store_gallery_photos
            SET title = ?, caption = ?, category_tag = ?, sort_order = ?, is_active = ?, updated_at = datetime('now')
            WHERE id = ?
            """,
            (title, caption, category_tag, sort_order, is_active, gid),
        )
        log_admin_action(conn, admin, "gallery_photo_edited", "store_gallery", gid)
        flash("Gallery photo updated.", "success")
        return True
    if action == "delete_gallery_photo":
        gid = int(request.form.get("gallery_id"))
        conn.execute("DELETE FROM store_gallery_photos WHERE id = ?", (gid,))
        log_admin_action(conn, admin, "gallery_photo_deleted", "store_gallery", gid)
        flash("Gallery photo deleted.", "success")
        return True
    return False


@admin_bp.route("/gallery", methods=["GET", "POST"])
@admin_login_required
@csrf_protect
def gallery_management():
    admin = get_current_admin()
    if request.method == "POST":
        action = request.form.get("action") or ""
        try:
            with transaction() as conn:
                _handle_gallery_action(conn, admin, action)
            return redirect(url_for("admin.gallery_management"))
        except ValueError as exc:
            flash(str(exc), "error")
    gallery_photos = get_gallery_photos(include_inactive=True)
    return render_template("admin/gallery.html", gallery_photos=gallery_photos)


@admin_bp.route("/content", methods=["GET", "POST"])
@admin_login_required
@csrf_protect
def homepage_content():
    admin = get_current_admin()
    if request.method == "POST":
        action = request.form.get("action")
        try:
            with transaction() as conn:
                if _handle_gallery_action(conn, admin, action):
                    pass
                elif action == "add_section":
                    stype = request.form.get("section_type", "hero_slide")
                    title = (request.form.get("title") or "").strip()
                    subtitle = (request.form.get("subtitle") or "").strip()
                    badge_text = (request.form.get("badge_text") or "").strip()
                    sku = (request.form.get("link_product_sku") or "").strip().upper()
                    sort_order = int(request.form.get("sort_order") or 0)
                    img_url = (request.form.get("image_url") or "").strip()
                    post_url = (request.form.get("instagram_post_url") or "").strip()
                    video_url = ""
                    has_custom_media = False
                    file_storage = request.files.get("banner_image")
                    if file_storage and file_storage.filename:
                        if stype == "instagram_post":
                            fname, _m, _s, is_video = save_uploaded_media(
                                file_storage, current_app.config["BANNER_UPLOADS_DIR"], prefix="insta"
                            )
                            if is_video:
                                video_url = f"/uploads/banners/{fname}"
                                has_custom_media = True
                            else:
                                img_url = f"/uploads/banners/{fname}"
                                has_custom_media = True
                        else:
                            fname, _m, _s = save_uploaded_image(
                                file_storage, current_app.config["BANNER_UPLOADS_DIR"], prefix="banner"
                            )
                            img_url = f"/uploads/banners/{fname}"
                            has_custom_media = True
                    elif img_url:
                        has_custom_media = True

                    meta = {}
                    if stype == "hero_slide":
                        if not img_url:
                            raise ValueError("Image URL or uploaded banner image is required.")
                        chips_raw = (request.form.get("chips") or "").strip()
                        chips = [c.strip() for c in chips_raw.split(",") if c.strip()] or ["Diecast Metal", "Collector Edition"]
                        meta = {"grail_tag": request.form.get("grail_tag", "FEATURED").strip(), "chips": chips}
                    elif stype == "instagram_post":
                        ig_info = parse_instagram_post_info(post_url)
                        if not has_custom_media and not ig_info["post_url"]:
                            raise ValueError("Provide an Instagram Post / Reel link, or upload an image/video.")
                        if img_url.lower().endswith((".mp4", ".webm", ".mov")) and not video_url:
                            video_url = img_url
                        if not has_custom_media and ig_info["embed_url"] and not video_url:
                            cached_thumb = fetch_instagram_thumbnail(
                                ig_info["embed_url"],
                                current_app.config["BANNER_UPLOADS_DIR"],
                                ig_info.get("shortcode", ""),
                            )
                            if cached_thumb:
                                img_url = cached_thumb
                                has_custom_media = True
                        if not img_url and sku:
                            linked = get_product_by_identifier(sku, include_hidden=True)
                            if linked:
                                img_url = linked.get("primary_image", "")
                        if not img_url:
                            img_url = "/static/assets/images/logo.png"
                        media_type = "video" if video_url else ("reel" if ig_info["is_reel"] else ("post" if ig_info["embed_url"] else "image"))
                        meta = {
                            "post_url": ig_info["post_url"],
                            "embed_url": ig_info["embed_url"],
                            "video_url": video_url,
                            "is_reel": bool(video_url or ig_info["is_reel"]),
                            "media_type": media_type,
                            "has_custom_image": bool(has_custom_media and not video_url),
                        }
                        if not title:
                            title = "Instagram Reel Showcase" if meta["is_reel"] else "Instagram Collector Post"
                    else:
                        if not img_url:
                            raise ValueError("Image URL or uploaded banner image is required.")

                    conn.execute(
                        """
                        INSERT INTO homepage_sections (
                            section_type, title, subtitle, badge_text, image_url, link_product_sku, meta_json, sort_order, is_active
                        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1)
                        """,
                        (stype, title, subtitle, badge_text, img_url, sku, json.dumps(meta), sort_order),
                    )
                    log_admin_action(conn, admin, "homepage_section_added", "homepage_section", stype, {"title": title})
                    flash("Homepage item added.", "success")
                elif action == "edit_instagram_link":
                    sid = int(request.form.get("section_id"))
                    post_url = (request.form.get("instagram_post_url") or "").strip()
                    row = conn.execute("SELECT image_url, meta_json, link_product_sku FROM homepage_sections WHERE id = ?", (sid,)).fetchone()
                    if row:
                        meta = parse_json_safe(row["meta_json"], {})
                        ig_info = parse_instagram_post_info(post_url)
                        meta["post_url"] = ig_info["post_url"]
                        meta["embed_url"] = ig_info["embed_url"]
                        if not meta.get("video_url"):
                            meta["is_reel"] = bool(ig_info["is_reel"])
                            meta["media_type"] = "reel" if ig_info["is_reel"] else ("post" if ig_info["embed_url"] else "image")
                        new_sku = (request.form.get("link_product_sku") or row["link_product_sku"] or "").strip().upper()
                        new_img_url = row["image_url"] or ""
                        if ig_info["embed_url"] and not meta.get("video_url"):
                            cached_thumb = fetch_instagram_thumbnail(
                                ig_info["embed_url"],
                                current_app.config["BANNER_UPLOADS_DIR"],
                                ig_info.get("shortcode", ""),
                            )
                            if cached_thumb:
                                new_img_url = cached_thumb
                                meta["has_custom_image"] = True
                        conn.execute(
                            "UPDATE homepage_sections SET image_url = ?, meta_json = ?, link_product_sku = ?, updated_at = datetime('now') WHERE id = ?",
                            (new_img_url, json.dumps(meta), new_sku, sid),
                        )
                        log_admin_action(conn, admin, "instagram_link_updated", "homepage_section", sid, {"post_url": ig_info["post_url"]})
                        flash("Instagram post link updated.", "success")
                elif action == "toggle":
                    sid = int(request.form.get("section_id"))
                    row = conn.execute("SELECT is_active FROM homepage_sections WHERE id = ?", (sid,)).fetchone()
                    if row:
                        nv = 0 if row["is_active"] else 1
                        conn.execute("UPDATE homepage_sections SET is_active = ?, updated_at = datetime('now') WHERE id = ?", (nv, sid))
                        log_admin_action(conn, admin, "homepage_section_toggled", "homepage_section", sid, {"is_active": nv})
                        flash("Visibility updated.", "success")
                elif action == "delete":
                    sid = int(request.form.get("section_id"))
                    conn.execute("DELETE FROM homepage_sections WHERE id = ?", (sid,))
                    log_admin_action(conn, admin, "homepage_section_deleted", "homepage_section", sid)
                    flash("Homepage item deleted.", "success")
                elif action == "add_testimonial":
                    author_name = (request.form.get("author_name") or "").strip()
                    quote_text = (request.form.get("quote_text") or "").strip()
                    subtitle = (request.form.get("subtitle") or "Verified Collector").strip()
                    rating = max(1, min(5, int(request.form.get("rating") or 5)))
                    sort_order = int(request.form.get("sort_order") or 0)
                    if not author_name or not quote_text:
                        raise ValueError("Reviewer name and quote text are required.")
                    conn.execute(
                        """
                        INSERT INTO customer_testimonials (author_name, quote_text, rating, subtitle, sort_order, is_active)
                        VALUES (?, ?, ?, ?, ?, 1)
                        """,
                        (author_name, quote_text, rating, subtitle, sort_order),
                    )
                    log_admin_action(conn, admin, "testimonial_added", "testimonial", author_name)
                    flash("Collector review added.", "success")
                elif action == "edit_testimonial":
                    tid = int(request.form.get("testimonial_id"))
                    author_name = (request.form.get("author_name") or "").strip()
                    quote_text = (request.form.get("quote_text") or "").strip()
                    subtitle = (request.form.get("subtitle") or "").strip()
                    rating = max(1, min(5, int(request.form.get("rating") or 5)))
                    sort_order = int(request.form.get("sort_order") or 0)
                    is_active = 1 if request.form.get("is_active") == "1" else 0
                    if not author_name or not quote_text:
                        raise ValueError("Reviewer name and quote text are required.")
                    conn.execute(
                        """
                        UPDATE customer_testimonials
                        SET author_name = ?, quote_text = ?, subtitle = ?, rating = ?,
                            sort_order = ?, is_active = ?, updated_at = datetime('now')
                        WHERE id = ?
                        """,
                        (author_name, quote_text, subtitle, rating, sort_order, is_active, tid),
                    )
                    log_admin_action(conn, admin, "testimonial_edited", "testimonial", tid, {"author": author_name})
                    flash("Collector review updated.", "success")
                elif action == "delete_testimonial":
                    tid = int(request.form.get("testimonial_id"))
                    conn.execute("DELETE FROM customer_testimonials WHERE id = ?", (tid,))
                    log_admin_action(conn, admin, "testimonial_deleted", "testimonial", tid)
                    flash("Collector review deleted.", "success")
            return redirect(url_for("admin.homepage_content"))
        except ValueError as exc:
            flash(str(exc), "error")

    sections = get_homepage_sections(include_inactive=True)
    testimonials = get_testimonials(include_inactive=True)
    gallery_photos = get_gallery_photos(include_inactive=True)
    sku_rows = get_db().execute("SELECT sku, is_visible, availability_status FROM products").fetchall()
    sku_status_map = {
        (r["sku"] or "").upper(): {
            "exists": True,
            "is_visible": bool(r["is_visible"]),
            "availability_status": r["availability_status"],
        }
        for r in sku_rows
    }
    return render_template(
        "admin/content.html",
        sections=sections,
        testimonials=testimonials,
        gallery_photos=gallery_photos,
        sku_status_map=sku_status_map,
    )


# ==========================================================================
# MODULE K: STORE SETTINGS
# ==========================================================================
@admin_bp.route("/settings", methods=["GET", "POST"])
@admin_login_required
@csrf_protect
def store_settings_page():
    admin = get_current_admin()
    if request.method == "POST":
        try:
            with transaction() as conn:
                text_keys = [
                    "store_name", "store_tagline", "announcement_pill", "announcement_text",
                    "owner_name", "contact_phone", "secondary_phone", "contact_email",
                    "instagram_url", "instagram_handle", "whatsapp_number", "whatsapp_group_url",
                    "upi_id", "upi_payee_name", "upi_instructions",
                    "garage_hold_days",
                ]
                for key in text_keys:
                    if key in request.form:
                        val = request.form.get(key, "").strip()
                        conn.execute(
                            """
                            INSERT INTO store_settings (key, value, updated_at)
                            VALUES (?, ?, datetime('now'))
                            ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = datetime('now')
                            """,
                            (key, val),
                        )
                # Rupee -> paise settings
                for form_key, db_key in [
                    ("shipping_charge_inr", "shipping_charge_paise"),
                    ("free_shipping_threshold_inr", "free_shipping_threshold_paise"),
                    ("garage_dispatch_fee_inr", "garage_dispatch_fee_paise"),
                    ("garage_free_dispatch_threshold_inr", "garage_free_dispatch_threshold_paise"),
                ]:
                    if form_key in request.form:
                        paise_val = str(rupees_to_paise(request.form.get(form_key, "0")))
                        conn.execute(
                            "UPDATE store_settings SET value = ?, updated_at = datetime('now') WHERE key = ?",
                            (paise_val, db_key),
                        )

                # Optional Logo upload
                logo_file = request.files.get("store_logo_file")
                if logo_file and logo_file.filename:
                    fname, _m, _s = save_uploaded_image(
                        logo_file, current_app.config["BANNER_UPLOADS_DIR"], prefix="logo"
                    )
                    conn.execute(
                        """
                        INSERT INTO store_settings (key, value, updated_at)
                        VALUES ('store_logo', ?, datetime('now'))
                        ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = datetime('now')
                        """,
                        (f"/uploads/banners/{fname}",),
                    )

                # Optional UPI QR image upload
                qr_file = request.files.get("upi_qr_file")
                if qr_file and qr_file.filename:
                    fname, _m, _s = save_uploaded_image(
                        qr_file, current_app.config["BANNER_UPLOADS_DIR"], prefix="upiqr"
                    )
                    conn.execute(
                        """
                        INSERT INTO store_settings (key, value, updated_at)
                        VALUES ('upi_qr_image', ?, datetime('now'))
                        ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = datetime('now')
                        """,
                        (f"/uploads/banners/{fname}",),
                    )

                log_admin_action(conn, admin, "store_settings_updated", "store_settings", "global")
            flash("Store settings saved and reflected on storefront.", "success")
            return redirect(url_for("admin.store_settings_page"))
        except ValueError as exc:
            flash(str(exc), "error")

    settings = get_store_settings()
    return render_template("admin/settings.html", settings=settings)


@admin_bp.route("/settings/password", methods=["POST"])
@admin_login_required
@csrf_protect
def change_admin_password():
    admin = get_current_admin()
    current_pw = request.form.get("current_password") or ""
    new_pw = request.form.get("new_password") or ""
    confirm_pw = request.form.get("confirm_password") or ""

    db = get_db()
    row = db.execute("SELECT id, password_hash FROM admin_users WHERE id = ?", (admin["id"],)).fetchone()
    if not row or not verify_password(row["password_hash"], current_pw):
        flash("Current admin password is incorrect.", "error")
        return redirect(url_for("admin.store_settings_page"))
    if len(new_pw) < 8:
        flash("New admin password must be at least 8 characters long.", "error")
        return redirect(url_for("admin.store_settings_page"))
    if new_pw != confirm_pw:
        flash("New passwords do not match.", "error")
        return redirect(url_for("admin.store_settings_page"))
    if verify_password(row["password_hash"], new_pw):
        flash("New password must be different from your current password.", "error")
        return redirect(url_for("admin.store_settings_page"))

    new_hash = hash_password(new_pw)
    with transaction(db) as conn:
        conn.execute(
            "UPDATE admin_users SET password_hash = ?, updated_at = datetime('now') WHERE id = ?",
            (new_hash, admin["id"]),
        )
        # Bump session_version on ALL admin users so every active admin session logs out immediately
        conn.execute(
            "UPDATE admin_users SET session_version = session_version + 1, updated_at = datetime('now')"
        )
        log_admin_action(conn, admin, "admin_password_changed", "admin_user", admin["id"])

    session.pop("admin_id", None)
    session.pop("admin_session_version", None)
    flash("Admin password changed! All active admin sessions have been signed out. Please log in with your new password.", "success")
    return redirect(url_for("admin.login"))


# ==========================================================================
# MODULE L: REPORTS
# ==========================================================================
@admin_bp.route("/reports")
@admin_login_required
def reports():
    db = get_db()
    by_status = [
        {
            "status": r["status"],
            "count": r["cnt"],
            "revenue_formatted": format_inr(r["rev"]),
        }
        for r in db.execute(
            "SELECT status, COUNT(*) AS cnt, COALESCE(SUM(total_paise), 0) AS rev FROM orders GROUP BY status ORDER BY cnt DESC"
        ).fetchall()
    ]
    top_products = [
        {
            "sku": r["sku_snapshot"],
            "name": r["product_name_snapshot"],
            "units": r["units"],
            "revenue_formatted": format_inr(r["rev"]),
        }
        for r in db.execute(
            """
            SELECT oi.sku_snapshot, oi.product_name_snapshot,
                   SUM(oi.quantity) AS units, SUM(oi.line_total_paise) AS rev
            FROM order_items oi
            JOIN orders o ON o.id = oi.order_id
            WHERE o.status NOT IN ('Cancelled', 'Refunded')
            GROUP BY oi.product_id
            ORDER BY units DESC, rev DESC
            LIMIT 15
            """
        ).fetchall()
    ]
    by_brand = [
        {
            "brand": r["brand_snapshot"],
            "units": r["units"],
            "revenue_formatted": format_inr(r["rev"]),
        }
        for r in db.execute(
            """
            SELECT oi.brand_snapshot, SUM(oi.quantity) AS units, SUM(oi.line_total_paise) AS rev
            FROM order_items oi
            JOIN orders o ON o.id = oi.order_id
            WHERE o.status NOT IN ('Cancelled', 'Refunded')
            GROUP BY oi.brand_snapshot
            ORDER BY rev DESC
            """
        ).fetchall()
    ]
    return render_template("admin/reports.html", by_status=by_status, top_products=top_products, by_brand=by_brand)


# ==========================================================================
# MODULE M: ADMIN ACTIVITY LOG
# ==========================================================================
@admin_bp.route("/logs")
@admin_login_required
def activity_logs():
    with transaction() as conn:
        prune_old_admin_audit_logs(conn, ACTIVITY_LOG_RETENTION_DAYS)

    period = (request.args.get("period") or "all").strip().lower()
    date_from = (request.args.get("date_from") or "").strip()
    date_to = (request.args.get("date_to") or "").strip()
    action_filter = (request.args.get("action") or "all").strip()
    q = (request.args.get("q") or "").strip()

    if date_from and not re.match(r"^\d{4}-\d{2}-\d{2}$", date_from):
        date_from = ""
    if date_to and not re.match(r"^\d{4}-\d{2}-\d{2}$", date_to):
        date_to = ""

    clauses = []
    params = []

    if date_from or date_to:
        period = "custom"
        if date_from:
            clauses.append("date(created_at) >= date(?)")
            params.append(date_from)
        if date_to:
            clauses.append("date(created_at) <= date(?)")
            params.append(date_to)
    elif period == "today":
        clauses.append("date(created_at) = date('now')")
    elif period == "7d":
        clauses.append("created_at >= datetime('now', '-7 days')")
    elif period == "30d":
        clauses.append("created_at >= datetime('now', '-30 days')")
    elif period not in ("all", "90d", "custom"):
        period = "all"

    if action_filter and action_filter != "all":
        clauses.append("action = ?")
        params.append(action_filter)

    if q:
        like = f"%{q}%"
        clauses.append(
            "(admin_username LIKE ? COLLATE NOCASE OR action LIKE ? COLLATE NOCASE "
            "OR entity_type LIKE ? COLLATE NOCASE OR entity_id LIKE ? COLLATE NOCASE "
            "OR details_json LIKE ? COLLATE NOCASE OR ip_address LIKE ? COLLATE NOCASE)"
        )
        params.extend([like] * 6)

    where_sql = ("WHERE " + " AND ".join(clauses)) if clauses else ""
    db = get_db()
    logs = [
        dict(r)
        for r in db.execute(
            f"SELECT * FROM admin_audit_logs {where_sql} ORDER BY id DESC LIMIT 250",
            params,
        ).fetchall()
    ]
    actions = [
        r["action"]
        for r in db.execute("SELECT DISTINCT action FROM admin_audit_logs ORDER BY action ASC").fetchall()
    ]
    return render_template(
        "admin/logs.html",
        logs=logs,
        actions=actions,
        retention_days=ACTIVITY_LOG_RETENTION_DAYS,
        filters={
            "period": period,
            "date_from": date_from,
            "date_to": date_to,
            "action": action_filter,
            "q": q,
        },
    )


# ==========================================================================
# MODULE N: DROP ALERT EMAIL SUBSCRIBERS
# ==========================================================================
@admin_bp.route("/subscribers", methods=["GET", "POST"])
@admin_login_required
@csrf_protect
def subscribers_list():
    admin = get_current_admin()
    if request.method == "POST":
        action = (request.form.get("action") or "").strip()
        try:
            with transaction() as conn:
                if action == "toggle":
                    sid = int(request.form.get("subscriber_id"))
                    row = conn.execute("SELECT email, is_active FROM drop_alert_subscribers WHERE id = ?", (sid,)).fetchone()
                    if row:
                        nv = 0 if row["is_active"] else 1
                        conn.execute(
                            "UPDATE drop_alert_subscribers SET is_active = ?, updated_at = datetime('now') WHERE id = ?",
                            (nv, sid),
                        )
                        log_admin_action(conn, admin, "subscriber_toggled", "drop_alert_subscriber", row["email"], {"is_active": nv})
                        flash(f"Updated subscription status for {row['email']}.", "success")
                elif action == "delete":
                    sid = int(request.form.get("subscriber_id"))
                    row = conn.execute("SELECT email FROM drop_alert_subscribers WHERE id = ?", (sid,)).fetchone()
                    if row:
                        conn.execute("DELETE FROM drop_alert_subscribers WHERE id = ?", (sid,))
                        log_admin_action(conn, admin, "subscriber_deleted", "drop_alert_subscriber", row["email"])
                        flash(f"Removed {row['email']} from Drop Alert list.", "success")
                elif action == "add":
                    email = (request.form.get("email") or "").strip().lower()
                    if not email or not re.match(r"^[^@\s]+@[^@\s]+\.[^@\s]+$", email):
                        raise ValueError("Please enter a valid email address.")
                    conn.execute(
                        """
                        INSERT INTO drop_alert_subscribers (email, source, is_active)
                        VALUES (?, 'admin', 1)
                        ON CONFLICT(email) DO UPDATE SET is_active = 1, updated_at = datetime('now')
                        """,
                        (email,),
                    )
                    log_admin_action(conn, admin, "subscriber_added", "drop_alert_subscriber", email)
                    flash(f"Added {email} to Drop Alert list.", "success")
            return redirect(url_for("admin.subscribers_list"))
        except ValueError as exc:
            flash(str(exc), "error")

    q = (request.args.get("q") or "").strip()
    status_filter = (request.args.get("status") or "all").strip().lower()
    clauses = []
    params = []
    if status_filter == "active":
        clauses.append("is_active = 1")
    elif status_filter == "unsubscribed":
        clauses.append("is_active = 0")
    if q:
        clauses.append("email LIKE ? COLLATE NOCASE")
        params.append(f"%{q}%")

    where_sql = ("WHERE " + " AND ".join(clauses)) if clauses else ""
    db = get_db()
    subscribers = [
        dict(r)
        for r in db.execute(
            f"SELECT * FROM drop_alert_subscribers {where_sql} ORDER BY is_active DESC, id DESC",
            params,
        ).fetchall()
    ]
    active_emails = [s["email"] for s in subscribers if s["is_active"]]
    return render_template(
        "admin/subscribers.html",
        subscribers=subscribers,
        active_emails=active_emails,
        filters={"q": q, "status": status_filter},
    )
