from django.shortcuts import render, redirect, get_object_or_404
from django.views import View
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib import messages
from .models import Product
from category.models import Category


class ProductManagementView(LoginRequiredMixin, View):
	def get(self, request):
		products = Product.objects.all()
		return render(request, 'pages/product-management/product_management.html', {'products': products})


class ProductCreateView(LoginRequiredMixin, View):
	def get(self, request):
		categories = Category.objects.filter(trash=False)
		return render(request, 'pages/product-management/product_create.html', {'categories': categories})

	def post(self, request):
		category_id = request.POST.get('category')
		category = Category.objects.filter(id=category_id).first() if category_id else None
		Product.objects.create(
			category=category,
			product_name=request.POST.get('product_name'),
			price=request.POST.get('price') or None,
			unit=request.POST.get('unit'),
			description=request.POST.get('description'),
			trash=bool(request.POST.get('trash')),
		)
		messages.success(request, 'Product created successfully!')
		return redirect('product-management')


class ProductDetailViewWeb(LoginRequiredMixin, View):
	def get(self, request, pk):
		product = get_object_or_404(Product, pk=pk)
		return render(request, 'pages/product-management/product_detail.html', {'product': product})


class ProductEditView(LoginRequiredMixin, View):
	def get(self, request, pk):
		product = get_object_or_404(Product, pk=pk)
		categories = Category.objects.filter(trash=False)
		return render(request, 'pages/product-management/product_edit.html', {'product': product, 'categories': categories})

	def post(self, request, pk):
		product = get_object_or_404(Product, pk=pk)
		category_id = request.POST.get('category')
		product.category = Category.objects.filter(id=category_id).first() if category_id else None
		product.product_name = request.POST.get('product_name')
		product.price = request.POST.get('price') or None
		product.unit = request.POST.get('unit')
		product.description = request.POST.get('description')
		product.trash = bool(request.POST.get('trash'))
		product.save()
		messages.success(request, 'Product updated successfully!')
		return redirect('product-management')


class ProductDeleteView(LoginRequiredMixin, View):
	def post(self, request, pk):
		product = get_object_or_404(Product, pk=pk)
		product.trash = True
		product.deleted_at = None
		product.save()
		messages.success(request, 'Product deleted (trashed) successfully!')
		return redirect('product-management')

