from django.shortcuts import render, get_object_or_404, redirect
from .models import Category, Book, Order
from django.db.models import Q
from django.contrib import messages

def home(request):
    featured_books = Book.objects.filter(is_featured=True)[:6]
    if not featured_books.exists():
        featured_books = Book.objects.all()[:6]
    categories = Category.objects.all()
    return render(request, "core/index.html", {
        "featured_books": featured_books,
        "categories": categories,
    })

def book_list(request):
    query = request.GET.get('q')
    category_slug = request.GET.get('category')
    books = Book.objects.all()
    categories = Category.objects.all()

    if query:
        books = books.filter(Q(title__icontains=query) | Q(description__icontains=query))
    if category_slug:
        books = books.filter(category__slug=category_slug)

    return render(request, "core/book_list.html", {
        "books": books,
        "categories": categories,
        "selected_category": category_slug,
    })

def book_detail(request, slug):
    book = get_object_or_404(Book, slug=slug)
    related_books = Book.objects.filter(category=book.category).exclude(id=book.id)[:4]
    return render(request, "core/book_detail.html", {
        "book": book,
        "related_books": related_books,
    })

def checkout(request, slug):
    book = get_object_or_404(Book, slug=slug)
    if request.method == 'POST':
        email = request.POST.get('email')
        transaction_id = request.POST.get('transaction_id')
        screenshot = request.FILES.get('screenshot')

        if email and transaction_id:
            Order.objects.create(
                book=book,
                user_email=email,
                transaction_id=transaction_id,
                payment_screenshot=screenshot
            )
            messages.success(request, "Your order has been submitted. We will verify your payment and email you the download link.")
            return redirect('order_success')
        else:
            messages.error(request, "Please fill in all required fields.")

    return render(request, "core/checkout.html", {"book": book})

def order_success(request):
    return render(request, "core/order_success.html")

def about(request):
    return render(request, "core/about.html")

def contact(request):
    return render(request, "core/contact.html")

def privacy(request):
    return render(request, "core/privacy.html")

def terms(request):
    return render(request, "core/terms.html")