from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from .models import CarAuction, Bid
from django.db.models import Max

def home(request):
    """Render the landing screen with featured auctions."""
    query = request.GET.get('q')
    if query:
        auctions = CarAuction.objects.filter(title__icontains=query, end_date__gt=timezone.now())
    else:
        auctions = CarAuction.objects.filter(end_date__gt=timezone.now()).order_by('end_date')[:6]
    
    context = {
        "auctions": auctions,
        "query": query,
    }
    return render(request, "core/index.html", context)

def auction_detail(request, pk):
    """Render the auction detail page."""
    auction = get_object_or_404(CarAuction, pk=pk)
    bids = auction.bids.all()
    
    context = {
        "auction": auction,
        "bids": bids,
    }
    return render(request, "core/auction_detail.html", context)