from django.shortcuts import render, redirect
from django.contrib import messages
from apps.blog.models import Post
from apps.products.models import Category, Product
from .models import Enquiry, GalleryImage


def home(request):
    if request.method == 'POST':
        enquiry = Enquiry.objects.create(
            title=request.POST.get('title', ''),
            customer_name=request.POST.get('customer_name'),
            business_name=request.POST.get('business_name', ''),
            email=request.POST.get('email'),
            phone_country=request.POST.get('phone_country', '+971'),
            phone_number=request.POST.get('phone_number'),
            country=request.POST.get('country', 'AE'),
            vin_chasis_number=request.POST.get('vin_chasis_number', ''),
            comments=request.POST.get('comments'),
        )
        
        
        messages.success(request, 'Your enquiry has been submitted successfully!')
        return redirect('home:index')
    
    latest_posts = Post.objects.filter(
        status=Post.Status.PUBLISHED
    ).select_related('author', 'category')[:3]
    
    featured_categories = Category.objects.filter(is_active=True, parent__isnull=True)
    
    top_rated_products = Product.objects.filter(
        status=Product.Status.ACTIVE,
        is_top_rated=True
    ).select_related('category', 'brand')[:3]
    
    context = {
        'latest_posts': latest_posts,
        'featured_categories': featured_categories,
        'top_rated_products': top_rated_products,
    }
    return render(request, 'home/index.html', context)


def about(request):
    return render(request, 'home/about.html')


def services(request):
    return render(request, 'home/services.html')


def gallery(request):
    images = GalleryImage.objects.all()
    return render(request, 'home/gallery.html', {'images': images})