import os
from django.shortcuts import render, get_object_or_404
from .models import Category, Product
from django.db.models import Q

def home(request):
    """Render the ShinaStore landing page with products and filters."""
    query = request.GET.get('q')
    category_slug = request.GET.get('category')
    
    categories = Category.objects.all()
    products = Product.objects.all()
    
    if query:
        products = products.filter(
            Q(name__icontains=query) | Q(description__icontains=query)
        )
    
    if category_slug:
        category = get_object_or_404(Category, slug=category_slug)
        products = products.filter(category=category)
        
    featured_products = Product.objects.filter(is_featured=True)[:4]
    
    context = {
        "categories": categories,
        "products": products,
        "featured_products": featured_products,
        "current_category": category_slug,
        "search_query": query or "",
    }
    return render(request, "core/index.html", context)