from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.views import View
from django.utils import timezone
from .models import Application, Subscription
from django.contrib import messages

from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth.decorators import user_passes_test
from django.shortcuts import get_object_or_404
from dateutil.relativedelta import relativedelta
from django.contrib.auth.mixins import LoginRequiredMixin

class ApplicationView(LoginRequiredMixin,View):
    def get(self, request):
        # Render the form with default values for the application
        return render(request, 'Main/apply.html')

    def post(self, request):
        # Retrieve application type from the form
        application_type = request.POST.get('application_type')
        
        # Map the application type to the respective amount and currency
        amount_mapping = {
            'type_1': 500,
            'type_2': 1000,
            'type_3': 2000
        }
        currency = 'BDT'
        amount = amount_mapping.get(application_type)

        # Create a new application instance with the amount and currency
        application = Application(
            user=request.user,
            application_type=application_type,
            name=request.user.get_full_name(),
            amount=amount,
            currency=currency
        )
        application.save()
        messages.success(request, 'Your application has been submitted successfully!')

        # Pass the application details to the context
        context = {
            'application': application,
            'user': request.user,
        }
        
        return render(request, 'Main/invoice.html', context)



@staff_member_required
def approve_application(request, application_id):
    application = get_object_or_404(Application, id=application_id)

    if application.is_approved:
        messages.warning(request, 'This application has already been approved.')
    else:
        # Approve the application
        application.is_approved = True
        application.save()

        # Set the duration for subscription based on the application type
        duration_mapping = {
            'type_1': {'years': 1},
            'type_2': {'years': 3},
            'type_3': {'years': 5},
        }
        duration = duration_mapping.get(application.application_type)

        # Create or update the subscription
        start_date = timezone.now()
        end_date = start_date + relativedelta(**duration)
        subscription, created = Subscription.objects.get_or_create(
            user=application.user,
            defaults={'start_date': start_date, 'end_date': end_date}
        )
        
        # Extend existing subscription if already present
        if not created:
            subscription.extend_subscription(**duration)
        
        messages.success(request, f"{application.user.first_name}'s application has been approved.")

    return redirect('application_list')


@user_passes_test(lambda u: u.is_superuser)  # Ensures only superusers can access
def application_list_view(request):
    applications = Application.objects.all()
    return render(request, 'Main/application_list.html', {'applications': applications})