# create this file if you don't have it yet
from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib.auth import get_user_model
from django.core.paginator import Paginator
from django.db.models import Q
from django.shortcuts import render

User = get_user_model()

@login_required
@user_passes_test(lambda u: u.is_staff)
def user_list(request):
    q = (request.GET.get("q") or "").strip()
    qs = User.objects.all().order_by("-date_joined")
    if q:
        qs = qs.filter(
            Q(username__icontains=q) |
            Q(email__icontains=q) |
            Q(first_name__icontains=q) |
            Q(last_name__icontains=q)
        )
    page_obj = Paginator(qs, 20).get_page(request.GET.get("page"))
    return render(request, "adminpanel/user_list.html", {"page_obj": page_obj, "q": q})
# storefront/admin_views.py  (append)
from django.contrib.auth.decorators import login_required, user_passes_test
from django.shortcuts import render, get_object_or_404, redirect
from django.core.paginator import Paginator
from django.db.models import Q
from catalog.models import Order, OrderItem
from .forms import OrderStatusForm

@login_required
@user_passes_test(lambda u: u.is_staff)
def order_list(request):
    q = (request.GET.get("q") or "").strip()
    status = (request.GET.get("status") or "").strip()
    qs = Order.objects.all().order_by("-created_at")
    if status:
        qs = qs.filter(status=status)
    if q:
        qs = qs.filter(
            Q(id__icontains=q) |
            Q(name__icontains=q) |
            Q(email__icontains=q) |
            Q(phone__icontains=q)
        )
    page_obj = Paginator(qs, 20).get_page(request.GET.get("page"))
    return render(request, "adminpanel/order_list.html", {"page_obj": page_obj, "q": q, "status": status})

@login_required
@user_passes_test(lambda u: u.is_staff)
def order_detail(request, order_id):
    order = get_object_or_404(Order.objects.prefetch_related("items__product"), id=order_id)
    if request.method == "POST":
        form = OrderStatusForm(request.POST, instance=order)
        if form.is_valid():
            form.save()
            return redirect("admin_order_detail", order_id=order.id)
    else:
        form = OrderStatusForm(instance=order)
    return render(request, "adminpanel/order_detail.html", {"order": order, "form": form})
