from django.shortcuts import render, get_object_or_404, redirect
from .models import Deal, Lead
from django.contrib import messages
from django.utils import timezone

def home(request):
    """Render the landing page with published deals."""
    published_deals = Deal.objects.filter(is_published=True).order_by('-created_at')[:6]
    
    # Simple check for sample data
    if not published_deals.exists():
        _create_sample_deals()
        published_deals = Deal.objects.filter(is_published=True).order_by('-created_at')[:6]

    context = {
        "deals": published_deals,
        "current_time": timezone.now(),
    }
    return render(request, "core/index.html", context)

def deal_detail(request, pk):
    """Render a single deal and handle lead submissions."""
    deal = get_object_or_404(Deal, pk=pk)
    
    if request.method == "POST":
        name = request.POST.get("name")
        email = request.POST.get("email")
        message = request.POST.get("message")
        
        if name and email:
            Lead.objects.create(deal=deal, name=name, email=email, message=message)
            messages.success(request, "Your request has been sent! We will contact you soon.")
            return redirect('deal_detail', pk=pk)
        else:
            messages.error(request, "Please fill in all required fields.")

    return render(request, "core/deal_detail.html", {"deal": deal})

def _create_sample_deals():
    """Seed the database with sample deals if empty."""
    deals = [
        {
            "title": "Unreal Points Deal: London to NYC",
            "deal_type": "points",
            "destination": "New York, USA",
            "points_required": 15000,
            "description": "Virgin Atlantic points deal. Unbeatable value for Business Class upgrade.",
            "image_url": "https://images.pexels.com/photos/466685/pexels-photo-466685.jpeg?auto=compress&cs=tinysrgb&w=800",
            "is_published": True
        },
        {
            "title": "Flight Drop: Bali Flash Sale",
            "deal_type": "flight",
            "destination": "Bali, Indonesia",
            "current_price": 450.00,
            "original_price": 890.00,
            "description": "Round trip from LAX. Limited seats available for March/April travel.",
            "image_url": "https://images.pexels.com/photos/2166553/pexels-photo-2166553.jpeg?auto=compress&cs=tinysrgb&w=800",
            "is_published": True
        },
        {
            "title": "Business Class: Paris for Less",
            "deal_type": "flight",
            "destination": "Paris, France",
            "current_price": 1200.00,
            "original_price": 2500.00,
            "description": "Lufthansa luxury at half the price. Multi-city options available.",
            "image_url": "https://images.pexels.com/photos/338515/pexels-photo-338515.jpeg?auto=compress&cs=tinysrgb&w=800",
            "is_published": True
        },
    ]
    for d in deals:
        Deal.objects.get_or_create(title=d['title'], defaults=d)