from django.shortcuts import render
from django.utils import timezone
from datetime import timedelta
from .models import *
from django.http import JsonResponse

# Create your views here.

# Create your tests here.

def create_charges_for_recurring_services(request):
    today = timezone.now().date()
    active_recurring_services = Service.objects.filter(active=True, recurring=True)

    for service in active_recurring_services:
        # Get the last charge for the service
        last_charge = service.charge_set.order_by('-due_date').first()

        if last_charge and last_charge.due_date <= today:
            # Calculate the new due date for the charge based on the recurring cycle
            new_due_date = today + timedelta(days=service.recurring_cycle.number_of_months * 30)

            # Create a new charge for the service
            Charge.objects.create(
                service=service,
                amount=service.amount,
                due_date=new_due_date
            )
    return JsonResponse({'status': 'success'})