
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 Category
from django.utils import timezone

class CategoryManagementView(LoginRequiredMixin, View):
	def get(self, request):
		categories = Category.objects.all()
		return render(request, 'pages/category-management/category_management.html', {'categories': categories})

class CategoryCreateView(LoginRequiredMixin, View):

	def get(self, request):
		parents = Category.objects.filter(trash=False)
		return render(request, 'pages/category-management/category_create.html', {'parents': parents})

	def post(self, request):
		parent_id = request.POST.get('parent_id')
		parent = Category.objects.filter(id=parent_id).first() if parent_id else None
		Category.objects.create(
			name=request.POST.get('name'),
			parent=parent,
			image=request.FILES.get('image'),
			description=request.POST.get('description'),
			status=request.POST.get('status'),
			trash=bool(request.POST.get('trash')),
		)
		messages.success(request, 'Category created successfully!')
		return redirect('category-management')

class CategoryDetailViewWeb(LoginRequiredMixin, View):
	def get(self, request, pk):
		category = get_object_or_404(Category, pk=pk)
		return render(request, 'pages/category-management/category_detail.html', {'category': category})

class CategoryEditView(LoginRequiredMixin, View):

	def get(self, request, pk):
		category = get_object_or_404(Category, pk=pk)
		parents = Category.objects.exclude(id=pk).filter(trash=False)
		return render(request, 'pages/category-management/category_edit.html', {'category': category, 'parents': parents})

	def post(self, request, pk):
		category = get_object_or_404(Category, pk=pk)
		parent_id = request.POST.get('parent_id')
		category.parent = Category.objects.filter(id=parent_id).first() if parent_id else None
		category.name = request.POST.get('name')
		category.description = request.POST.get('description')
		if request.FILES.get('image'):
			category.image = request.FILES.get('image')
		category.status = request.POST.get('status')
		category.trash = bool(request.POST.get('trash'))
		category.save()
		messages.success(request, 'Category updated successfully!')
		return redirect('category-management')

class CategoryDeleteView(LoginRequiredMixin, View):
	def post(self, request, pk):
		category = get_object_or_404(Category, pk=pk)
		category.trash = True
		category.deleted_at = timezone.now()
		category.save()
		messages.success(request, 'Category deleted (trashed) successfully!')
		return redirect('category-management')

