from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from .models import Product, Category, Order, OrderItem
from django.contrib import messages

def index(request):
    query = request.GET.get('q')
    category_id = request.GET.get('category')
    
    products = Product.objects.all().order_by('-created_at')
    categories = Category.objects.all()
    
    if query:
        products = products.filter(title__icontains=query) | products.filter(description__icontains=query)
    
    if category_id:
        products = products.filter(category_id=category_id)
        
    context = {
        'products': products,
        'categories': categories,
        'selected_category': int(category_id) if category_id and category_id.isdigit() else None,
        'query': query
    }
    return render(request, 'core/index.html', context)

def product_detail(request, pk):
    product = get_object_or_404(Product, pk=pk)
    related_products = Product.objects.filter(category=product.category).exclude(pk=pk)[:4]
    return render(request, 'core/product_detail.html', {
        'product': product,
        'related_products': related_products
    })

def add_to_cart(request, pk):
    product = get_object_or_404(Product, pk=pk)
    cart = request.session.get('cart', {})
    
    product_id = str(pk)
    if product_id in cart:
        cart[product_id]['quantity'] += 1
    else:
        cart[product_id] = {
            'title': product.title,
            'price': str(product.price),
            'quantity': 1,
            'image_url': product.image_url
        }
    
    request.session['cart'] = cart
    messages.success(request, f"{product.title} added to cart.")
    return redirect('cart_detail')

def cart_detail(request):
    cart = request.session.get('cart', {})
    total = sum(float(item['price']) * item['quantity'] for item in cart.values())
    return render(request, 'core/cart.html', {'cart': cart, 'total': total})

def remove_from_cart(request, pk):
    cart = request.session.get('cart', {})
    product_id = str(pk)
    if product_id in cart:
        del cart[product_id]
        request.session['cart'] = cart
        messages.info(request, "Item removed from cart.")
    return redirect('cart_detail')

@login_required
def checkout(request):
    cart = request.session.get('cart', {})
    if not cart:
        messages.warning(request, "Your cart is empty.")
        return redirect('index')
    
    total = sum(float(item['price']) * item['quantity'] for item in cart.values())
    
    # Create Order
    order = Order.objects.create(user=request.user, total_amount=total)
    
    # Create OrderItems
    for product_id, item in cart.items():
        product = get_object_or_404(Product, pk=product_id)
        OrderItem.objects.create(
            order=order,
            product=product,
            quantity=item['quantity'],
            price=item['price']
        )
        # Update stock
        if product.stock >= item['quantity']:
            product.stock -= item['quantity']
            product.save()
            
    # Clear cart
    request.session['cart'] = {}
    
    return render(request, 'core/checkout_success.html', {'order': order})
