from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import ListView, CreateView

from common.models import CompanyModel
from containers.models import Container
from payments.forms import PaymentCreateForm
from payments.models import Payment


# Create your views here.
class PaymentCreateView(CreateView):
    model = Payment
    form_class = PaymentCreateForm
    template_name = 'employee/payment-create.html'
    success_url = reverse_lazy('payment-list')

    def form_valid(self, form):
        container_ids = self.request.POST.getlist('containers')
        payment = form.save(commit=False)
        payment.save()
        payment.containers.set(container_ids)
        return super().form_valid(form)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        container_ids = self.request.GET.get('containers', '').split(',')
        # Filter only valid IDs (non-empty strings that can be converted to int)
        container_ids = [int(id) for id in container_ids if id.strip().isdigit()]

        if container_ids:
            # Get selected containers
            context['containers'] = Container.objects.filter(
                id__in=container_ids,
                expedited=True,
                payment_containers__isnull=True
            ).order_by('-expedited_on')
        return context

    def get_form(self, form_class=None):
        form = super().get_form(form_class)
        company_pk = self.request.GET.get('company', '')
        form.fields['company'].initial = company_pk

        # container_ids = [int(id) for id in container_ids if id.strip().isdigit()]
        # form.fields['containers'].initial = container_ids
        return form