from rest_framework import serializers
from .models import *
from datetime import datetime
import pytz
from dateutil.relativedelta import relativedelta
from django.db.models import F
from django.db.models.functions import TruncDate
from ledgers.serializers import *
from savings.models import *


class LicensePaymentsSerializer(serializers.ModelSerializer):
    class Meta:
        model=LicensePayments
        fields = '__all__'

class LicenseSubscriptionSerializer(serializers.ModelSerializer):
    license_details = serializers.SerializerMethodField()

    class Meta:
        model = LicenseSubscription
        fields = '__all__'

    def get_license_details(self,obj):
        org_id = obj.organisation.id
        eat_timezone = pytz.timezone("Africa/Nairobi")
        start_date = datetime.strptime(obj.start_date.astimezone(eat_timezone).strftime('%Y-%m-%d'), '%Y-%m-%d')
        transaction_date=datetime.strptime(obj.subcription_date.astimezone(eat_timezone).strftime('%Y-%m-%d'), '%Y-%m-%d')
        current_date =  datetime.strptime(datetime.now().astimezone(eat_timezone).strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S')
        end_date = datetime.strptime(obj.end_date.astimezone(eat_timezone).strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S')
        past_days = ((current_date - end_date).days)
        total_days = 0
        total_paid_amount=0
        amount_due = 0
        actual_amount = 0
        subscription_amount=obj.amount
        revised_amount = obj.revised_amount
        active_members = SavingAccount.objects.filter(customer_branch__branch_organisation=org_id,status='active').count()
        if obj.calculation_types == 'annual-flat':
            actual_amount = subscription_amount
        else:
            actual_amount = subscription_amount*active_members

        payments_list = []
        related_fields = LicensePayments.objects.filter(license_subscription=obj.id).values(
        'payment_method', 'record_date', 'license_subscription__id', 'license_date', 'remaining_balance', 'amount_paid')
        if related_fields:
            for payment in related_fields:
                total_paid_amount = payment['amount_paid'] if payment['amount_paid'] else 0
                payment_entry = {
                    'amount_paid': payment['amount_paid'],
                    'payment_method': payment['payment_method'],
                    'payment_date': payment['record_date'],
                    'license_id': payment['license_subscription__id'],
                    'license_date': payment['license_date'],
                    'balance': payment['remaining_balance'],
                    'actual_amount': actual_amount
                }
                payments_list.append(payment_entry)

        if obj.calculation_types == 'annual-flat':
            amount_due = subscription_amount - total_paid_amount 
        else:
            if obj.revised_members and revised_amount:
                amount_due = (revised_amount * obj.revised_members) - total_paid_amount  if obj.revised_members else subscription_amount - total_paid_amount
            else:
                amount_due = (subscription_amount * active_members) - total_paid_amount  if active_members else subscription_amount - total_paid_amount
        if amount_due <= 0:
            amount_due = total_paid_amount
            if obj.period_type == 'd':
                total_days = (start_date + relativedelta(days=obj.period) - start_date).days
            elif obj.period_type == 'm':
                total_days = (start_date + relativedelta(months=obj.period) - start_date).days

        if obj.period_type == 'd':
            total_days = (transaction_date + relativedelta(days=obj.period) - transaction_date).days
        elif obj.period_type == 'm':
            total_days = (transaction_date + relativedelta(months=obj.period) - transaction_date).days
        organisation = Organisation.objects.filter(pk=org_id)
        company_name = ""
        status = ""
        reg_no = ""
        phone_number = ""
        email = ""
        country = ""
        city = ""
        region = ""
        date_added = ""
        logo_url = ""
        for org in organisation:
            company_name = org.name 
            status       = org.status
            reg_no       = org.registration_no
            phone_number = org.phone_number
            email        = org.email
            country      = org.country
            city         = org.city
            region       = org.region
            date_added   = org.date_added
            logo_url     = org.logo_url
        return {
            "past_days": past_days,
            "total_days": total_days,
            "company_name": company_name,
            "status": status,
            "reg_no": reg_no,
            "phone_number": phone_number,
            "email": email,
            "country": country,
            "city": city,
            "region": region,
            "date_added": date_added,
            "logo_url": logo_url,
            "payments": payments_list,
            "amount_due": amount_due,
            "subscription_amount": obj.amount,
            "actual_amount":actual_amount,
            "total_paid_amount":total_paid_amount,
            "revised_members":obj.revised_members,
            "revised_amount":obj.revised_amount
        }