from flask import render_template, redirect, session, flash, request, url_for, jsonify
from . import web_bp
from app_server.extensions import db
from app_server.models import (
    Product,
    Category,
    Order,
    OrderItem,
    User,
    Expense,
    FinancePayment,
    DailyProfit,
)
from datetime import datetime
from sqlalchemy import func, or_, and_
from app_server.extensions import socketio
from app_server.api.routes import (
    WHATSAPP_TWILIO_ENABLED,
    send_sms_notification,
    send_whatsapp_twilio,
)
from app_server.utils.security import (
    hash_password,
    needs_password_rehash,
    verify_password,
)
from app_server.utils.admin_reports import build_reports_page_context
from app_server.utils.registration import (
    create_verified_customer,
    registration_payload,
    registration_pending_matches,
    send_registration_otps,
    validate_registration_payload,
    verify_registration_otps,
)


def _orders_for_customer_account(user_id):
    """
    Orders for the logged-in customer: by user_id, plus legacy web rows where user_id
    was never set but email/phone matches (older checkouts).
    """
    user = User.query.get(user_id)
    if not user:
        return []

    clauses = [Order.user_id == user_id]
    if user.email and str(user.email).strip():
        em = str(user.email).strip()
        clauses.append(and_(Order.user_id.is_(None), Order.customer_email == em))
    if user.phone and str(user.phone).strip():
        ph = str(user.phone).strip()
        clauses.append(and_(Order.user_id.is_(None), Order.customer_phone == ph))

    return (
        Order.query.filter(or_(*clauses))
        .order_by(Order.date.desc())
        .all()
    )


def _customer_can_access_order(order, user_id):
    """Whether the logged-in user may view this order (invoice / reviews)."""
    user = User.query.get(user_id)
    if not user:
        return False
    if order.user_id == user_id:
        return True
    if order.user_id is not None:
        return False
    if user.email and (order.customer_email or "").strip() == str(user.email).strip():
        return True
    if user.phone and (order.customer_phone or "").strip() == str(user.phone).strip():
        return True
    return False


@web_bp.app_context_processor
def inject_global_data():
    from app_server.models import Category, Product, Wishlist
    categories = Category.query.all()
    
    # Calculate cart total for the sidebar
    cart = session.get('cart', {})
    total_price = sum(item['price'] * item['qty'] for item in cart.values())
    
    user_wishlist_ids = []
    current_user = None
    is_admin = False
    if 'user_id' in session:
        current_user = User.query.get(session['user_id'])
        is_admin = bool(current_user and current_user.role == 'admin')
        user_wishs = Wishlist.query.filter_by(user_id=session['user_id']).all()
        user_wishlist_ids = [w.product_id for w in user_wishs]
        
    # Smart Recommendations logic
    cart_cat_ids = []
    cart_prod_ids = []
    for pid, item in cart.items():
        cart_prod_ids.append(int(pid))
        p = Product.query.get(int(pid))
        if p and p.category_id:
            cart_cat_ids.append(p.category_id)
            
    recommendations = []
    if cart_cat_ids:
        recommendations = Product.query.filter(
            Product.category_id.in_(list(set(cart_cat_ids))),
            ~Product.id.in_(cart_prod_ids),
            Product.stock > 0
        ).order_by(db.func.random()).limit(3).all()
    
    return {
        'categories': categories,
        'total_price': total_price,
        'user_wishlist_ids': user_wishlist_ids,
        'recommendations': recommendations,
        'current_user': current_user,
        'is_admin': is_admin,
    }


# --- HOME PAGE ---
@web_bp.route('/')
def home():
    from app_server.models import Category, Product
    
    def get_deduped_products(filter_flag):
        """Helper to get 1 product per category for a specific section flag"""
        all_items = Product.query.filter_by(**{filter_flag: True})\
                            .filter(Product.stock > 0)\
                            .order_by(Product.id.desc()).all()
        seen = set()
        deduped = []
        for p in all_items:
            if p.category_id not in seen:
                deduped.append(p)
                seen.add(p.category_id)
        return deduped

    # Apply 1-product-per-category rule to ALL sections as per user request
    recent_products = get_deduped_products('show_in_recent')
    gift_products = get_deduped_products('show_in_gifts')
    deal_products = get_deduped_products('show_in_deals')
    video_products = get_deduped_products('show_in_video')
    
    physical_sale_products = Product.query.filter(Product.physical_sale_video != None, Product.physical_sale_video != '').filter(Product.stock > 0).all()
    
    return render_template('web/index.html', 
                           recent_products=recent_products,
                           gift_products=gift_products,
                           deal_products=deal_products,
                           video_products=video_products,
                           physical_sale_products=physical_sale_products)

@web_bp.route('/collection')
def collection():
    # URL Filters
    cat_id = request.args.get('cat_id', type=int)
    brand = request.args.get('brand')
    min_price = request.args.get('min_price', type=float)
    max_price = request.args.get('max_price', type=float)
    on_sale = request.args.get('on_sale') == 'true'
    
    # Base query
    products_query = Product.query.filter(Product.stock > 0)
    
    # 1. Category Filter
    if cat_id:
        products_query = products_query.filter_by(category_id=cat_id)
    
    # 2. Brand Filter
    if brand:
        products_query = products_query.filter_by(brand=brand)
        
    # 3. Price Filter
    if min_price is not None:
        products_query = products_query.filter(Product.price >= min_price)
    if max_price is not None:
        products_query = products_query.filter(Product.price <= max_price)
        
    # 4. On Sale / Deals Filter
    if on_sale:
        # User requested Flash Sale to be different from Shop All.
        # Now it strictly shows items manually marked as "Deals" in Desktop App.
        products_query = products_query.filter(Product.show_in_deals == True)
    products = products_query.all()
    categories = Category.query.all()
    
    # Get unique brands for the filter dropdown
    brands = db.session.query(Product.brand).filter(Product.brand != None).distinct().all()
    brands = [b[0] for b in brands]
    
    cart = session.get('cart', {})
    total_price = sum(item['price'] * item['qty'] for item in cart.values())

    # Find Top 6 best sellers based on OrderItem sales
    top_sel = db.session.query(
        OrderItem.product_name, func.sum(OrderItem.quantity).label('total')
    ).group_by(OrderItem.product_name).order_by(func.sum(OrderItem.quantity).desc()).limit(6).all()
    top_seller_names = [t[0] for t in top_sel]

    physical_sale_products = []
    if request.args.get('on_sale') == 'true':
        physical_sale_products = Product.query.filter(Product.physical_sale_video != None, Product.physical_sale_video != '').filter(Product.stock > 0).all()

    return render_template('web/collection.html', 
                           products=products, 
                           categories=categories, 
                           brands=brands,
                           total_price=total_price,
                           current_filters=request.args,
                           top_seller_names=top_seller_names,
                           physical_sale_products=physical_sale_products)

# --- REAL-TIME SEARCH ---
@web_bp.route('/search')
def search():
    query = request.args.get('q', '').strip()
    cat_id = request.args.get('cat_id')
    
    # ✅ Hamesha stock check filter laga rahega
    products_query = Product.query.filter(Product.stock > 0)

    # Agar Category filter laga ho
    if cat_id:
        products_query = products_query.filter_by(category_id=cat_id)
    
    # Agar Search query bhi ho
    if query:
        products_query = products_query.filter(Product.name.icontains(query))

    products = products_query.all()

    results = []
    for p in products:
        results.append({
            "id": p.id,
            "name": p.name,
            "price": p.price,
            "image": p.image_file if p.image_file else 'default.png',
            "stock": p.stock
        })
    
    return jsonify({"products": results})

# --- ADD TO CART ---
@web_bp.route('/add-to-cart/<int:product_id>')
def add_to_cart(product_id):
    product = Product.query.get_or_404(product_id)
    
    if 'cart' not in session:
        session['cart'] = {}

    cart = session['cart']
    prod_id = str(product_id)

    if prod_id in cart:
        if cart[prod_id]['qty'] < product.stock:
            cart[prod_id]['qty'] += 1
            flash(f"Added another {product.name} to cart.", "success")
        else:
            flash(f"Not enough stock for {product.name}.", "danger")
    else:
        cart[prod_id] = {
            "name": product.name,
            "price": product.price,
            "qty": 1,
            "image": product.image_file if product.image_file else 'default.png'
        }
        flash(f"{product.name} added to cart!", "success")
        # Send WhatsApp via Twilio if phone is stored in session and not empty
        if session.get('customer_phone'):
            phone = session['customer_phone']
            # Ensure phone is in international format
            formatted = phone if phone.startswith('+') else '+92' + phone.lstrip('0')
            msg = f"🛒 {product.name} has been added to your cart. Continue shopping or checkout!"
            if WHATSAPP_TWILIO_ENABLED:
                send_whatsapp_twilio(formatted, msg)

    session.modified = True
    return redirect(url_for('web.home'))

# --- VIEW CART ---
@web_bp.route('/cart')
def view_cart():
    cart = session.get('cart', {})
    total = sum(item['price'] * item['qty'] for item in cart.values())
    return render_template('web/cart.html', cart=cart, total=total)

# --- REMOVE FROM CART ---
@web_bp.route('/remove-from-cart/<product_id>')
def remove_from_cart(product_id):
    cart = session.get('cart', {})
    if str(product_id) in cart:
        del cart[str(product_id)]
        session.modified = True
        flash("Item removed from cart.", "info")
    return redirect(url_for('web.view_cart'))

# --- CHECKOUT ---
@web_bp.route('/checkout', methods=['GET', 'POST'])
def checkout():
    cart = session.get('cart', {})
    # 🛑 SECURITY CHECK: Agar user login nahi hai toh order place nahi kar sakta
    if 'user_id' not in session:
        flash("Please login or create an account to place your order.", "warning")
        # 'next' parameter use kar rahe hain taake login ke baad user wapis checkout par aaye
        return redirect(url_for('web.login', next=request.url))

    cart = session.get('cart', {})
    if not cart:
        flash("Your cart is empty!", "warning")
        return redirect(url_for('web.home'))

    total = sum(item['price'] * item['qty'] for item in cart.values())
    
    # Check for applied coupon
    coupon_data = session.get('coupon', None)
    discount = coupon_data['discount'] if coupon_data else 0
    final_total = max(0, total - discount)
    
    # Login user ka data fetch karein
    current_user = User.query.get(session['user_id'])

    if request.method == 'POST':
        name = request.form.get('name')
        phone = request.form.get('phone')
        email = request.form.get('email')
        address = request.form.get('address')

        order_count = Order.query.count()
        new_order_id = f"WEB-10{order_count + 1}"

        new_order = Order(
            id=new_order_id,
            customer_name=name,
            customer_phone=phone,
            customer_email=email,
            subtotal=total,
            discount=discount,
            final_total=final_total,
            payment_method="Cash on Delivery",
            source="Web",
            status="Online_Pending",
            user_id=session.get("user_id"),
        )
        db.session.add(new_order)
        db.session.flush()

        for prod_id, item in cart.items():
            product = Product.query.get(int(prod_id))
            if product:
                product.stock -= item['qty'] 
            
            oi = OrderItem(order_id=new_order.id, product_name=item['name'], price=item['price'], quantity=item['qty'])
            db.session.add(oi)

        db.session.commit()
        session.pop('cart', None)
        session.pop('coupon', None)
        
        socketio.emit('new_online_order', {
            'order_id': new_order_id,
            'customer': name,
            'total': total
        }, namespace='/')

        # ✅ SMS Notification for Web Placement
        if phone:
            formatted_phone = phone
            if not formatted_phone.startswith('+'):
                formatted_phone = "+92" + formatted_phone.lstrip('0')
            
            msg = (f"Thank you for shopping with SwiftCart.\n"
                   f"Your order #{new_order_id} has been placed successfully.\n"
                   f"Total: Rs. {total:,.2f}")
            
            send_sms_notification(formatted_phone, msg, new_order_id)
        
        flash(f"Order Placed Successfully! Your Order ID is {new_order_id}", "success")
        return redirect(url_for('web.home'))

    # current_user template ko bhej rahe hain
    return render_template('web/checkout.html', total=total, discount=discount, final_total=final_total, current_user=current_user, coupon=coupon_data)

# --- COUPONS ---
@web_bp.route('/apply-coupon', methods=['POST'])
def apply_coupon():
    code = request.form.get('code', '').strip().upper()
    coupon = Coupon.query.filter_by(code=code, active=True).first()
    if coupon:
        session['coupon'] = {'code': coupon.code, 'discount': coupon.discount}
        flash(f"Promo Code '{code}' applied! You saved Rs. {coupon.discount:,.0f}", "success")
    else:
        flash("Invalid or expired promo code.", "warning")
    return redirect(url_for('web.checkout'))

@web_bp.route('/remove-coupon')
def remove_coupon():
    session.pop('coupon', None)
    flash("Promo Code removed.", "info")
    return redirect(url_for('web.checkout'))

#signup routes
@web_bp.route('/signup/send-otp', methods=['POST'])
def signup_send_otp():
    payload = registration_payload(request.form)
    error = validate_registration_payload(payload)
    if error:
        return jsonify({"ok": False, "message": error}), 400

    try:
        sent, result = send_registration_otps(payload)
        if not sent:
            return jsonify({"ok": False, "message": result}), 503

        session["signup_pending"] = result
        return jsonify({
            "ok": True,
            "message": "Email verification code sent.",
        })
    except ValueError as exc:
        return jsonify({"ok": False, "message": str(exc)}), 429
    except Exception:
        db.session.rollback()
        return jsonify({"ok": False, "message": "Could not send verification codes."}), 500


@web_bp.route('/signup', methods=['GET', 'POST'])
def signup():
    if request.method == 'POST':
        pending = session.get("signup_pending")
        payload = registration_payload(request.form)
        matches, message = registration_pending_matches(pending, payload)
        if not matches:
            flash(message, "warning")
            return redirect(url_for('web.signup'))

        email_otp = (request.form.get("email_otp") or "").strip()
        verified, message = verify_registration_otps(pending, payload, email_otp)
        if not verified:
            flash(message, "danger")
            return redirect(url_for('web.signup'))

        error = validate_registration_payload(payload)
        if error:
            flash(error, "danger")
            return redirect(url_for('web.signup'))

        user, message = create_verified_customer(payload)
        if not user:
            flash(message, "danger")
            return redirect(url_for('web.signup'))

        session.pop("signup_pending", None)
        flash("Account created! Please login.", "success")
        return redirect(url_for('web.login'))
        
    return render_template('web/signup.html')

@web_bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        identifier = request.form.get('email') # This can be email or username
        password = request.form.get('password')
        
        # Try both email and username for better UX
        user = User.query.filter(
            (User.email == identifier) | (User.username == identifier),
        ).first()
        
        if user and verify_password(user.password, password):
            if needs_password_rehash(user.password):
                user.password = hash_password(password)
                db.session.commit()
            session['user_id'] = user.id
            session['username'] = user.username
            session['user_role'] = user.role
            # Store phone for WhatsApp notifications
            session['customer_phone'] = user.phone if hasattr(user, 'phone') else ''
            flash(f"Welcome back, {user.username}!", "success")
            if user.role == 'admin':
                return redirect(url_for('web.admin_overview'))
            return redirect(url_for('web.home'))
        else:
            flash("Invalid email or password", "danger")
            
    return render_template('web/login.html')

@web_bp.route('/logout')
def logout():
    session.pop('user_id', None)
    session.pop('username', None)
    session.pop('user_role', None)
    session.pop('customer_phone', None)
    session.pop('signup_pending', None)
    flash("You have been logged out.", "info")
    return redirect(url_for('web.home'))

# --- MY ORDERS ---
@web_bp.route('/my-orders')
def my_orders():
    from app_server.models import Product
    if 'user_id' not in session:
        flash("Please login to view your orders.", "warning")
        return redirect(url_for('web.login'))
    
    user_id = session.get('user_id')
    orders = _orders_for_customer_account(user_id)
    
    # Map product names to IDs so we can show review buttons
    all_products = Product.query.all()
    prod_map = {p.name: p.id for p in all_products}
    
    return render_template('web/my_orders.html', orders=orders, prod_map=prod_map)

# --- DOWNLOAD INVOICE ---
@web_bp.route('/download-invoice/<order_id>')
def download_invoice(order_id):
    if 'user_id' not in session:
        return redirect(url_for('web.login', next=request.url))
        
    order = Order.query.get_or_404(order_id)
    if not _customer_can_access_order(order, session["user_id"]):
        flash("You do not have access to this order.", "danger")
        return redirect(url_for("web.my_orders"))

    # Generate an elegant, print-ready HTML template 
    # instead of heavy PDF libraries for broader compatibility
    return render_template('web/invoice.html', order=order)

# --- MY KHATA / LEDGER ---
@web_bp.route('/my-khata')
def my_khata():
    from app_server.models import KhataAccount
    if 'user_id' not in session:
        flash("Please login to view your Khata Account.", "warning")
        return redirect(url_for('web.login'))
        
    current_user = User.query.get(session['user_id'])
    
    # Safely handle missing phone
    phone = current_user.phone
    
    khata = None
    transactions = []
    
    if phone:
        khata = KhataAccount.query.filter_by(phone=phone.strip()).first()
        if khata:
            transactions = khata.transactions
            # Sort desc
            transactions = sorted(transactions, key=lambda x: x.id, reverse=True)
            
    return render_template('web/my_khata.html', user=current_user, khata=khata, transactions=transactions)

# ==========================================
# ❤️ WISHLIST SYSTEM
# ==========================================
@web_bp.route('/wishlist/toggle/<int:product_id>')
def toggle_wishlist(product_id):
    from app_server.models import Wishlist
    if 'user_id' not in session:
        flash("Please login to use the Wishlist.", "info")
        return redirect(url_for('web.login', next=request.url))
    
    user_id = session['user_id']
    existing = Wishlist.query.filter_by(user_id=user_id, product_id=product_id).first()
    
    if existing:
        db.session.delete(existing)
        db.session.commit()
        flash("Removed from Wishlist", "info")
    else:
        new_w = Wishlist(user_id=user_id, product_id=product_id)
        db.session.add(new_w)
        db.session.commit()
        flash("Added to Wishlist ❤️", "success")
        
    return redirect(request.referrer or url_for('web.home'))

@web_bp.route('/wishlist')
def view_wishlist():
    from app_server.models import Wishlist
    if 'user_id' not in session:
        flash("Please login to view your Wishlist.", "warning")
        return redirect(url_for('web.login'))
        
    wishlist_items = Wishlist.query.filter_by(user_id=session['user_id']).order_by(Wishlist.date_added.desc()).all()
    return render_template('web/wishlist.html', wishlist_items=wishlist_items)

# ==========================================
# ⭐ REVIEWS SYSTEM
# ==========================================
@web_bp.route('/add-review/<int:product_id>', methods=['POST'])
def add_review(product_id):
    from app_server.models import Review, Order
    if 'user_id' not in session:
        flash("Please login to review.", "warning")
        return redirect(url_for('web.login'))
        
    rating = int(request.form.get('rating', 5))
    comment = request.form.get('comment', '')
    user_id = session['user_id']
    
    # Check if user has bought product and order is completed
    user_orders = [o for o in _orders_for_customer_account(user_id) if o.status == "Completed"]
    product = Product.query.get(product_id)
    has_bought = False
    for o in user_orders:
        for i in o.items:
            if product and i.product_name == product.name:
                has_bought = True
                break
                
    if not has_bought:
        flash("You can only review products that you have received (Completed Order).", "warning")
        return redirect(request.referrer or url_for('web.home'))
        
    existing = Review.query.filter_by(user_id=user_id, product_id=product_id).first()
    if existing:
        existing.rating = rating
        existing.comment = comment
        flash("Review updated!", "success")
    else:
        new_rev = Review(user_id=user_id, product_id=product_id, rating=rating, comment=comment)
        db.session.add(new_rev)
        flash("Review posted successfully! ⭐", "success")
        
    db.session.commit()
    return redirect(request.referrer or url_for('web.home'))

# ==========================================
# 📊 CLOUD ADMIN (sidebar + pages)

ADMIN_ORDER_STATUSES = (
    "Online_Pending",
    "Dispatched",
    "Completed",
    "Refunded",
    "Cancelled",
)


def _admin_user_or_redirect():
    """Return (user, None) or (None, redirect_response)."""
    if "user_id" not in session:
        flash("Please login first", "danger")
        return None, redirect(url_for("web.login"))
    user = User.query.get(session["user_id"])
    if not user or user.role != "admin":
        flash("Access Denied: Admins only!", "danger")
        return None, redirect(url_for("web.home"))
    return user, None


def _build_admin_context():
    """Shared stats for all admin pages (single query batch)."""
    from datetime import timedelta

    total_sales = (
        db.session.query(func.sum(Order.final_total)).filter(Order.status != "Refunded").scalar()
        or 0
    )
    total_orders = Order.query.filter(Order.status != "Refunded").count()
    orders_all_count = Order.query.count()
    low_stock_count = Product.query.filter(Product.stock <= Product.min_stock).count()

    online_customers = (
        User.query.filter(User.role == "customer")
        .order_by(User.created_at.desc())
        .limit(100)
        .all()
    )
    online_customers_count = User.query.filter(User.role == "customer").count()

    today_start = datetime.combine(datetime.utcnow().date(), datetime.min.time())
    today_orders = [
        o for o in Order.query.filter(Order.date >= today_start).all() if o.status != "Refunded"
    ]
    today_sales_total = sum(o.final_total for o in today_orders)
    today_web = sum(o.final_total for o in today_orders if (o.source or "") == "Web")
    today_pos = sum(o.final_total for o in today_orders if (o.source or "") != "Web")

    cash_sales = bank_sales = credit_sales = 0.0
    for o in today_orders:
        pm = (o.payment_method or "cash").lower()
        if "credit" in pm or "udhaar" in pm:
            credit_sales += o.final_total
        elif pm in ("card", "online", "bank"):
            bank_sales += o.final_total
        else:
            cash_sales += o.final_total

    today_d = datetime.utcnow().date()
    today_expenses = (
        db.session.query(func.sum(Expense.amount)).filter(Expense.date == today_d).scalar() or 0
    )

    recent_finance = FinancePayment.query.order_by(FinancePayment.date.desc()).limit(15).all()
    daily_profit_rows = DailyProfit.query.order_by(DailyProfit.date.desc()).limit(14).all()

    active_web_orders = (
        Order.query.filter(
            Order.source == "Web",
            Order.status.notin_(["Completed", "Refunded"]),
        )
        .order_by(Order.date.desc())
        .limit(50)
        .all()
    )

    recent_orders = Order.query.order_by(Order.date.desc()).limit(25).all()

    today = datetime.utcnow().date()
    labels = []
    web_data = []
    pos_data = []

    for i in range(6, -1, -1):
        d = today - timedelta(days=i)
        labels.append(d.strftime("%d %b"))
        day_start = datetime.combine(d, datetime.min.time())
        day_end = day_start + timedelta(days=1)

        w = (
            db.session.query(func.sum(Order.final_total)).filter(
                Order.date >= day_start,
                Order.date < day_end,
                Order.source == "Web",
                Order.status != "Refunded",
            ).scalar()
            or 0
        )
        web_data.append(float(w))

        p = (
            db.session.query(func.sum(Order.final_total)).filter(
                Order.date >= day_start,
                Order.date < day_end,
                Order.source == "POS",
                Order.status != "Refunded",
            ).scalar()
            or 0
        )
        pos_data.append(float(p))

    low_stock_products = (
        Product.query.filter(Product.stock <= Product.min_stock).order_by(Product.stock.asc()).all()
    )

    return {
        "sales": total_sales,
        "orders": total_orders,
        "orders_all_count": orders_all_count,
        "low_stock": low_stock_count,
        "online_customers": online_customers,
        "online_customers_count": online_customers_count,
        "today_sales_total": today_sales_total,
        "today_web": today_web,
        "today_pos": today_pos,
        "cash_sales": cash_sales,
        "bank_sales": bank_sales,
        "credit_sales": credit_sales,
        "today_expenses": today_expenses,
        "recent_finance": recent_finance,
        "daily_profit_rows": daily_profit_rows,
        "active_web_orders": active_web_orders,
        "recent_orders": recent_orders,
        "datetime": datetime,
        "labels": labels,
        "web_data": web_data,
        "pos_data": pos_data,
        "low_stock_products": low_stock_products,
    }


def _render_admin(template_name, admin_section, **extra):
    ctx = _build_admin_context()
    ctx["admin_section"] = admin_section
    ctx["admin_order_statuses"] = ADMIN_ORDER_STATUSES
    ctx.update(extra)
    return render_template(template_name, **ctx)


@web_bp.route("/low-stock")
def low_stock():
    """Display products with low stock (<= min_stock)."""
    low_stock_products = Product.query.filter(Product.stock <= Product.min_stock).order_by(
        Product.stock.asc()
    ).all()
    return render_template("web/low_stock.html", products=low_stock_products)


@web_bp.route("/admin-dashboard")
def admin_dashboard():
    """Legacy URL → overview."""
    return redirect(url_for("web.admin_overview"))


@web_bp.route("/admin")
@web_bp.route("/admin/overview")
def admin_overview():
    _, redir = _admin_user_or_redirect()
    if redir:
        return redir
    return _render_admin("web/admin/overview.html", "overview")


@web_bp.route("/admin/sales")
def admin_sales():
    _, redir = _admin_user_or_redirect()
    if redir:
        return redir
    return _render_admin("web/admin/sales.html", "sales")


@web_bp.route("/admin/finance")
def admin_finance():
    _, redir = _admin_user_or_redirect()
    if redir:
        return redir
    return _render_admin("web/admin/finance.html", "finance")


@web_bp.route("/admin/orders")
def admin_orders():
    _, redir = _admin_user_or_redirect()
    if redir:
        return redir
    return _render_admin("web/admin/orders.html", "orders")


@web_bp.route("/admin/customers")
def admin_customers():
    _, redir = _admin_user_or_redirect()
    if redir:
        return redir
    return _render_admin("web/admin/customers.html", "customers")


@web_bp.route("/admin/orders/<order_id>/status", methods=["POST"])
def admin_update_order_status(order_id):
    _, redir = _admin_user_or_redirect()
    if redir:
        return redir

    from app_server.utils.order_notifications import apply_order_status_update

    new_status = (request.form.get("status") or "").strip()
    if new_status not in ADMIN_ORDER_STATUSES:
        flash("Invalid order status.", "danger")
        return redirect(url_for("web.admin_orders"))

    order = Order.query.get(order_id)
    if not order:
        flash("Order not found.", "warning")
        return redirect(url_for("web.admin_orders"))

    apply_order_status_update(order, new_status)
    db.session.commit()
    flash(f"Order {order_id} updated to {new_status}.", "success")
    return redirect(url_for("web.admin_orders"))


@web_bp.route("/admin/reports")
def admin_reports():
    _, redir = _admin_user_or_redirect()
    if redir:
        return redir
    extra = build_reports_page_context(request)
    return _render_admin("web/admin/reports.html", "reports", **extra)


@web_bp.route("/admin/inventory")
def admin_inventory():
    _, redir = _admin_user_or_redirect()
    if redir:
        return redir
    return _render_admin("web/admin/inventory.html", "inventory")