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

class ServiceManagementView(LoginRequiredMixin, View):
    def get(self, request):
        services = Service.objects.all()
        return render(request, 'pages/service-management/service_management.html', {'services': services})

class ServiceCreateView(LoginRequiredMixin, View):
    def get(self, request):
        return render(request, 'pages/service-management/service_create.html')

    def post(self, request):
        # Gather conditions as list of dicts
        keys = request.POST.getlist('condition_key[]')
        values = request.POST.getlist('condition_value[]')
        conditions = []
        for k, v in zip(keys, values):
            if k.strip() or v.strip():
                conditions.append({'key': k, 'value': v})
        Service.objects.create(
            service_name=request.POST.get('service_name'),
            description=request.POST.get('description'),
            image=request.FILES.get('image'),
            status=request.POST.get('status'),
            conditions=conditions,
        )
        messages.success(request, 'Service created successfully!')
        return redirect('service-management')

class ServiceDetailViewWeb(LoginRequiredMixin, View):
    def get(self, request, pk):
        service = get_object_or_404(Service, pk=pk)
        return render(request, 'pages/service-management/service_detail.html', {'service': service})

class ServiceEditView(LoginRequiredMixin, View):
    def get(self, request, pk):
        service = get_object_or_404(Service, pk=pk)
        return render(request, 'pages/service-management/service_edit.html', {'service': service})

    def post(self, request, pk):
        service = get_object_or_404(Service, pk=pk)
        service.service_name = request.POST.get('service_name')
        service.description = request.POST.get('description')
        if request.FILES.get('image'):
            service.image = request.FILES.get('image')
        service.status = request.POST.get('status')
        # Gather conditions as list of dicts
        keys = request.POST.getlist('condition_key[]')
        values = request.POST.getlist('condition_value[]')
        conditions = []
        for k, v in zip(keys, values):
            if k.strip() or v.strip():
                conditions.append({'key': k, 'value': v})
        service.conditions = conditions
        service.save()
        messages.success(request, 'Service updated successfully!')
        return redirect('service-management')

class ServiceDeleteView(LoginRequiredMixin, View):
    def post(self, request, pk):
        service = get_object_or_404(Service, pk=pk)
        service.delete()
        messages.success(request, 'Service deleted successfully!')
        return redirect('service-management')
