# payslips/serializers.py

from rest_framework import serializers
from django.db import models
from django.utils import timezone
from django.db import IntegrityError
from decimal import Decimal
from people.models import Teacher
from people.serializers import SimpleTeacherSerializer
from .models import (
    TeacherPayStructure,
    MonthlyPaySlip,
    PaymentTransaction,
    PaySlipTemplate
)


# =====================================================
# TEACHER PAY STRUCTURE SERIALIZERS
# =====================================================


class TeacherPayStructureSerializer(serializers.ModelSerializer):
    """Complete Teacher Pay Structure Serializer"""
    
    teacher_name = serializers.CharField(source='teacher.full_name', read_only=True)
    teacher_employee_id = serializers.CharField(source='teacher.employee_id', read_only=True)
    created_by_name = serializers.CharField(source='created_by.full_name', read_only=True, default=None)
    total_monthly_fixed_earnings = serializers.DecimalField(
        max_digits=12, decimal_places=2, read_only=True
    )
    
    class Meta:
        model = TeacherPayStructure
        fields = [
            'id',
            'teacher',
            'teacher_name',
            'teacher_employee_id',
            'effective_from',
            'effective_to',
            'base_salary',
            'dearness_allowance',
            'house_rent_allowance',
            'city_compensatory_allowance',
            'travel_allowance',
            'medical_allowance',
            'special_allowance',
            'education_allowance',
            'telephone_allowance',
            'provident_fund_percentage',
            'esi_percentage',
            'professional_tax_fixed',
            'default_performance_incentive',
            'default_special_class_incentive',
            'default_subject_expert_incentive',
            'default_leadership_allowance',
            'total_monthly_fixed_earnings',
            'is_active',
            'created_by',
            'created_by_name',
            'created_at',
            'updated_at',
        ]
        read_only_fields = ['created_at', 'updated_at']
    
    def validate_teacher(self, value):
        """Ensure teacher doesn't already have an active pay structure"""
        if not self.instance:
            existing = TeacherPayStructure.objects.filter(
                teacher=value,
                is_active=True
            ).first()
            if existing:
                raise serializers.ValidationError(
                    f"Teacher already has an active pay structure. "
                    f"Deactivate the existing one first."
                )
        return value
    
    def validate(self, data):
        """Validate effective dates"""
        effective_from = data.get('effective_from')
        effective_to = data.get('effective_to')
        
        if effective_from and effective_to and effective_from > effective_to:
            raise serializers.ValidationError(
                "Effective from date cannot be after effective to date"
            )
        
        return data

class TeacherPayStructureListSerializer(serializers.ModelSerializer):
    """List view Teacher Pay Structure Serializer with all fields"""
    
    teacher_name = serializers.CharField(source='teacher.full_name', read_only=True)
    teacher_employee_id = serializers.CharField(source='teacher.employee_id', read_only=True)
    created_by_name = serializers.CharField(source='created_by.full_name', read_only=True, default=None)
    total_monthly_fixed_earnings = serializers.DecimalField(
        max_digits=12, decimal_places=2, read_only=True
    )
    
    class Meta:
        model = TeacherPayStructure
        fields = [
            'id',
            'teacher',
            'teacher_name',
            'teacher_employee_id',
            'effective_from',
            'effective_to',
            'base_salary',
            'dearness_allowance',
            'house_rent_allowance',
            'city_compensatory_allowance',
            'travel_allowance',
            'medical_allowance',
            'special_allowance',
            'education_allowance',
            'telephone_allowance',
            'provident_fund_percentage',
            'esi_percentage',
            'professional_tax_fixed',
            'default_performance_incentive',
            'default_special_class_incentive',
            'default_subject_expert_incentive',
            'default_leadership_allowance',
            'total_monthly_fixed_earnings',
            'is_active',
            'created_by',
            'created_by_name',
            'created_at',
            'updated_at',
        ]
# =====================================================
# MONTHLY PAY SLIP SERIALIZERS
# =====================================================


class MonthlyPaySlipSerializer(serializers.ModelSerializer):
    """Base Monthly Pay Slip Serializer"""
    
    teacher_name = serializers.CharField(source='teacher.full_name', read_only=True)
    teacher_employee_id = serializers.CharField(source='teacher.employee_id', read_only=True)
    created_by_name = serializers.CharField(source='created_by.full_name', read_only=True, default=None)
    approved_by_name = serializers.CharField(source='approved_by.full_name', read_only=True, default=None)
    month_name = serializers.SerializerMethodField()
    
    class Meta:
        model = MonthlyPaySlip
        fields = [
            'id',
            'pay_slip_number',
            'teacher',
            'teacher_name',
            'teacher_employee_id',
            'month',
            'month_name',
            'year',
            'status',
            'base_salary',
            'dearness_allowance',
            'house_rent_allowance',
            'city_compensatory_allowance',
            'travel_allowance',
            'medical_allowance',
            'special_allowance',
            'education_allowance',
            'telephone_allowance',
            'performance_incentive',
            'special_class_incentive',
            'subject_expert_incentive',
            'leadership_allowance',
            'festival_bonus',
            'annual_bonus',
            'overtime_allowance',
            'variable_pay',
            'additional_earnings',
            'other_allowances',
            'provident_fund_employee',
            'provident_fund_employer',
            'esi_deduction',
            'professional_tax',
            'income_tax',
            'loan_deduction',
            'advance_deduction',
            'attendance_deduction',
            'other_deductions',
            'casual_leave_taken',
            'sick_leave_taken',
            'earned_leave_taken',
            'unpaid_leave_days',
            'total_working_days',
            'days_present',
            'days_absent',
            'late_days',
            'total_earnings',
            'total_deductions',
            'net_pay',
            'remarks',
            'hr_remarks',
            'created_by',
            'created_by_name',
            'approved_by',
            'approved_by_name',
            'approved_at',
            'is_acknowledged',
            'acknowledged_at',
            'created_at',
            'updated_at',
        ]
        read_only_fields = ['pay_slip_number', 'created_at', 'updated_at', 'total_earnings', 'total_deductions', 'net_pay']
    
    def get_month_name(self, obj):
        """Get month name"""
        months = [
            'January', 'February', 'March', 'April', 'May', 'June',
            'July', 'August', 'September', 'October', 'November', 'December'
        ]
        return months[obj.month - 1] if 1 <= obj.month <= 12 else str(obj.month)
    
    def validate(self, data):
        """Validate month and year uniqueness"""
        teacher = data.get('teacher')
        month = data.get('month')
        year = data.get('year')
        
        if not self.instance:
            existing = MonthlyPaySlip.objects.filter(
                teacher=teacher,
                month=month,
                year=year,
                is_active=True
            ).first()
            if existing:
                raise serializers.ValidationError(
                    f"Pay slip already exists for {month}/{year}"
                )
        
        return data


class MonthlyPaySlipListSerializer(serializers.ModelSerializer):
    """List view Monthly Pay Slip Serializer"""
    
    teacher_name = serializers.CharField(source='teacher.full_name', read_only=True)
    teacher_employee_id = serializers.CharField(source='teacher.employee_id', read_only=True)
    month_name = serializers.SerializerMethodField()
    total_paid = serializers.SerializerMethodField()
    
    class Meta:
        model = MonthlyPaySlip
        fields = [
            'id',
            'pay_slip_number',
            'teacher',
            'teacher_name',
            'teacher_employee_id',
            'month',
            'month_name',
            'year',
            'status',
            'net_pay',
            'total_paid',
            'is_acknowledged',
            'created_at',
        ]
    
    def get_month_name(self, obj):
        months = [
            'January', 'February', 'March', 'April', 'May', 'June',
            'July', 'August', 'September', 'October', 'November', 'December'
        ]
        return months[obj.month - 1] if 1 <= obj.month <= 12 else str(obj.month)
    
    def get_total_paid(self, obj):
        """Get total amount paid for this pay slip"""
        total = obj.payment_transactions.filter(
            status='COMPLETED'
        ).aggregate(total=models.Sum('amount'))['total']
        return float(total) if total else 0


class MonthlyPaySlipDetailSerializer(MonthlyPaySlipSerializer):
    """Detailed Monthly Pay Slip Serializer with payment transactions"""
    
    payment_transactions = serializers.SerializerMethodField()
    remaining_balance = serializers.SerializerMethodField()
    
    class Meta(MonthlyPaySlipSerializer.Meta):
        fields = MonthlyPaySlipSerializer.Meta.fields + [
            'pay_structure_snapshot',
            'payment_transactions',
            'remaining_balance',
        ]
    
    def get_payment_transactions(self, obj):
        """Get all payment transactions for this pay slip"""
        # Remove is_active filter - PaymentTransaction doesn't have this field
        transactions = obj.payment_transactions.all()  # Changed from filter(is_active=True)
        return PaymentTransactionListSerializer(transactions, many=True).data
    
    def get_remaining_balance(self, obj):
        """Calculate remaining balance to be paid"""
        total_paid = obj.payment_transactions.filter(
            status='COMPLETED'
        ).aggregate(total=models.Sum('amount'))['total'] or 0
        remaining = float(obj.net_pay) - float(total_paid)
        return max(remaining, 0)
# =====================================================
# PAYMENT TRANSACTION SERIALIZERS
# =====================================================


class PaymentTransactionSerializer(serializers.ModelSerializer):
    """Complete Payment Transaction Serializer"""
    
    pay_slip_number = serializers.CharField(source='pay_slip.pay_slip_number', read_only=True)
    teacher_name = serializers.CharField(source='teacher.full_name', read_only=True)
    teacher_employee_id = serializers.CharField(source='teacher.employee_id', read_only=True)
    recorded_by_name = serializers.CharField(source='recorded_by.full_name', read_only=True, default=None)
    payment_method_display = serializers.CharField(source='get_payment_method_display', read_only=True)
    payment_type_display = serializers.CharField(source='get_payment_type_display', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    
    class Meta:
        model = PaymentTransaction
        fields = [
            'id',
            'pay_slip',
            'pay_slip_number',
            'teacher',
            'teacher_name',
            'teacher_employee_id',
            'payment_type',
            'payment_type_display',
            'amount',
            'payment_method',
            'payment_method_display',
            'payment_date',
            'transaction_id',
            'bank_reference',
            'cheque_number',
            'upi_id',
            'bank_name',
            'bank_account_number',
            'bank_ifsc_code',
            'status',
            'status_display',
            'remarks',
            'recorded_by',
            'recorded_by_name',
            'created_at',
            'updated_at',
        ]
        read_only_fields = ['created_at', 'updated_at']
    
    def validate_amount(self, value):
        """Validate amount is positive"""
        if value <= 0:
            raise serializers.ValidationError("Amount must be greater than zero")
        return value
    
    def validate(self, data):
        """Validate payment doesn't exceed pay slip balance"""
        pay_slip = data.get('pay_slip')
        amount = data.get('amount')
        
        if pay_slip and amount:
            total_paid = PaymentTransaction.objects.filter(
                pay_slip=pay_slip,
                status='COMPLETED'
            ).exclude(id=self.instance.id if self.instance else None).aggregate(
                total=models.Sum('amount')
            )['total'] or 0
            
            remaining = float(pay_slip.net_pay) - float(total_paid)
            
            if float(amount) > remaining:
                raise serializers.ValidationError(
                    f"Amount exceeds remaining balance. Remaining: {remaining}"
                )
        
        return data


class PaymentTransactionListSerializer(serializers.ModelSerializer):
    """List view Payment Transaction Serializer"""
    
    pay_slip_number = serializers.CharField(source='pay_slip.pay_slip_number', read_only=True)
    payment_method_display = serializers.CharField(source='get_payment_method_display', read_only=True)
    payment_type_display = serializers.CharField(source='get_payment_type_display', read_only=True)
    
    class Meta:
        model = PaymentTransaction
        fields = [
            'id',
            'pay_slip',
            'pay_slip_number',
            'payment_type',
            'payment_type_display',
            'amount',
            'payment_method',
            'payment_method_display',
            'payment_date',
            'transaction_id',
            'status',
            'created_at',
        ]


# =====================================================
# PAY SLIP TEMPLATE SERIALIZERS
# =====================================================


class PaySlipTemplateSerializer(serializers.ModelSerializer):
    """Complete Pay Slip Template Serializer"""
    
    created_by_name = serializers.CharField(source='created_by.full_name', read_only=True, default=None)
    applicable_teachers_count = serializers.SerializerMethodField()
    applicable_teachers_list = serializers.SerializerMethodField()
    
    class Meta:
        model = PaySlipTemplate
        fields = [
            'id',
            'name',
            'description',
            'applicable_teachers',
            'applicable_teachers_count',
            'applicable_teachers_list',
            'designation',
            'base_salary',
            'dearness_allowance',
            'house_rent_allowance',
            'city_compensatory_allowance',
            'travel_allowance',
            'medical_allowance',
            'special_allowance',
            'education_allowance',
            'telephone_allowance',
            'provident_fund_percentage',
            'esi_percentage',
            'professional_tax_fixed',
            'is_active',
            'created_by',
            'created_by_name',
            'created_at',
            'updated_at',
        ]
        read_only_fields = ['created_at', 'updated_at']
    
    def get_applicable_teachers_count(self, obj):
        """Get count of teachers this template applies to"""
        return obj.applicable_teachers.filter(is_active=True).count()
    
    def get_applicable_teachers_list(self, obj):
        """Get list of applicable teachers"""
        teachers = obj.applicable_teachers.filter(is_active=True)[:10]
        return [{'id': t.id, 'name': t.full_name, 'employee_id': t.employee_id} for t in teachers]


class PaySlipTemplateListSerializer(serializers.ModelSerializer):
    """List view Pay Slip Template Serializer"""
    
    applicable_teachers_count = serializers.SerializerMethodField()
    
    class Meta:
        model = PaySlipTemplate
        fields = [
            'id',
            'name',
            'description',
            'designation',
            'base_salary',
            'applicable_teachers_count',
            'is_active',
            'created_at',
        ]
    
    def get_applicable_teachers_count(self, obj):
        """Get count of teachers this template applies to"""
        return obj.applicable_teachers.filter(is_active=True).count()


# =====================================================
# REQUEST/ACTION SERIALIZERS
# =====================================================


class GeneratePaySlipSerializer(serializers.Serializer):
    """Serializer for generating a single pay slip"""
    
    teacher_id = serializers.IntegerField()
    month = serializers.IntegerField(min_value=1, max_value=12)
    year = serializers.IntegerField(min_value=2000, max_value=2100)
    
    def validate(self, data):
        """Check if pay slip already exists"""
        teacher_id = data['teacher_id']
        month = data['month']
        year = data['year']
        
        existing = MonthlyPaySlip.objects.filter(
            teacher_id=teacher_id,
            month=month,
            year=year,
            is_active=True
        ).first()
        
        if existing:
            raise serializers.ValidationError(
                f"Pay slip already exists for {month}/{year}"
            )
        
        # Check if teacher has pay structure
        pay_structure = TeacherPayStructure.objects.filter(
            teacher_id=teacher_id,
            is_active=True
        ).first()
        
        if not pay_structure:
            raise serializers.ValidationError(
                "Teacher does not have an active pay structure"
            )
        
        return data


class BulkPaySlipGenerateSerializer(serializers.Serializer):
    """Serializer for generating multiple pay slips"""
    
    teacher_ids = serializers.ListField(
        child=serializers.IntegerField(),
        min_length=1
    )
    month = serializers.IntegerField(min_value=1, max_value=12)
    year = serializers.IntegerField(min_value=2000, max_value=2100)


class PaySlipUpdateSerializer(serializers.Serializer):
    """Serializer for updating pay slip components"""
    
    performance_incentive = serializers.DecimalField(max_digits=12, decimal_places=2, required=False, allow_null=True)
    special_class_incentive = serializers.DecimalField(max_digits=12, decimal_places=2, required=False, allow_null=True)
    subject_expert_incentive = serializers.DecimalField(max_digits=12, decimal_places=2, required=False, allow_null=True)
    leadership_allowance = serializers.DecimalField(max_digits=12, decimal_places=2, required=False, allow_null=True)
    festival_bonus = serializers.DecimalField(max_digits=12, decimal_places=2, required=False, allow_null=True)
    annual_bonus = serializers.DecimalField(max_digits=12, decimal_places=2, required=False, allow_null=True)
    overtime_allowance = serializers.DecimalField(max_digits=12, decimal_places=2, required=False, allow_null=True)
    variable_pay = serializers.DecimalField(max_digits=12, decimal_places=2, required=False, allow_null=True)
    additional_earnings = serializers.DecimalField(max_digits=12, decimal_places=2, required=False, allow_null=True)
    other_allowances = serializers.JSONField(required=False, allow_null=True)
    loan_deduction = serializers.DecimalField(max_digits=12, decimal_places=2, required=False, allow_null=True)
    advance_deduction = serializers.DecimalField(max_digits=12, decimal_places=2, required=False, allow_null=True)
    attendance_deduction = serializers.DecimalField(max_digits=12, decimal_places=2, required=False, allow_null=True)
    other_deductions = serializers.JSONField(required=False, allow_null=True)
    casual_leave_taken = serializers.DecimalField(max_digits=5, decimal_places=1, required=False, allow_null=True)
    sick_leave_taken = serializers.DecimalField(max_digits=5, decimal_places=1, required=False, allow_null=True)
    earned_leave_taken = serializers.DecimalField(max_digits=5, decimal_places=1, required=False, allow_null=True)
    unpaid_leave_days = serializers.DecimalField(max_digits=5, decimal_places=1, required=False, allow_null=True)
    total_working_days = serializers.IntegerField(required=False, allow_null=True)
    days_present = serializers.IntegerField(required=False, allow_null=True)
    days_absent = serializers.IntegerField(required=False, allow_null=True)
    late_days = serializers.IntegerField(required=False, allow_null=True)
    remarks = serializers.CharField(required=False, allow_blank=True)


class PaySlipApprovalSerializer(serializers.Serializer):
    """Serializer for pay slip approval"""
    
    approved = serializers.BooleanField()
    remarks = serializers.CharField(required=False, allow_blank=True)


class PaySlipSummarySerializer(serializers.Serializer):
    """Serializer for pay slip summary statistics"""
    
    total_pay_slips = serializers.IntegerField()
    total_draft = serializers.IntegerField()
    total_pending = serializers.IntegerField()
    total_approved = serializers.IntegerField()
    total_paid = serializers.IntegerField()
    total_cancelled = serializers.IntegerField()
    total_net_pay = serializers.DecimalField(max_digits=15, decimal_places=2, allow_null=True)
    average_net_pay = serializers.DecimalField(max_digits=15, decimal_places=2, allow_null=True)


class TeacherPaySummarySerializer(serializers.Serializer):
    """Serializer for teacher pay summary"""
    
    teacher_id = serializers.IntegerField()
    year = serializers.IntegerField()
    total_earned = serializers.DecimalField(max_digits=15, decimal_places=2)
    monthly_data = serializers.ListField()


# =====================================================
# IMPORT FOR MODELS (to avoid circular imports)
# =====================================================
# Add these to your existing serializers.py

class PaymentTransactionSerializer(serializers.ModelSerializer):
    """Complete Payment Transaction Serializer"""
    
    pay_slip_number = serializers.CharField(source='pay_slip.pay_slip_number', read_only=True)
    teacher_name = serializers.CharField(source='teacher.full_name', read_only=True)
    teacher_employee_id = serializers.CharField(source='teacher.employee_id', read_only=True)
    recorded_by_name = serializers.CharField(source='recorded_by.full_name', read_only=True, default=None)
    payment_method_display = serializers.CharField(source='get_payment_method_display', read_only=True)
    payment_type_display = serializers.CharField(source='get_payment_type_display', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    
    class Meta:
        model = PaymentTransaction
        fields = [
            'id',
            'pay_slip',
            'pay_slip_number',
            'teacher',
            'teacher_name',
            'teacher_employee_id',
            'payment_type',
            'payment_type_display',
            'amount',
            'payment_method',
            'payment_method_display',
            'payment_date',
            'transaction_id',
            'bank_reference',
            'cheque_number',
            'upi_id',
            'bank_name',
            'bank_account_number',
            'bank_ifsc_code',
            'status',
            'status_display',
            'remarks',
            'recorded_by',
            'recorded_by_name',
            'created_at',
            'updated_at',
        ]
        read_only_fields = ['created_at', 'updated_at']
    
    def validate_amount(self, value):
        if value <= 0:
            raise serializers.ValidationError("Amount must be greater than zero")
        return value
    
    def validate(self, data):
        pay_slip = data.get('pay_slip')
        amount = data.get('amount')
        
        if pay_slip and amount:
            total_paid = PaymentTransaction.objects.filter(
                pay_slip=pay_slip,
                status='COMPLETED'
            ).exclude(id=self.instance.id if self.instance else None).aggregate(
                total=models.Sum('amount')
            )['total'] or 0
            
            remaining = float(pay_slip.net_pay) - float(total_paid)
            
            if float(amount) > remaining:
                raise serializers.ValidationError(
                    f"Amount exceeds remaining balance. Remaining: {remaining}"
                )
        
        return data


class PaymentTransactionListSerializer(serializers.ModelSerializer):
    """List view Payment Transaction Serializer"""
    
    pay_slip_number = serializers.CharField(source='pay_slip.pay_slip_number', read_only=True)
    teacher_name = serializers.CharField(source='teacher.full_name', read_only=True)
    payment_method_display = serializers.CharField(source='get_payment_method_display', read_only=True)
    payment_type_display = serializers.CharField(source='get_payment_type_display', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    
    class Meta:
        model = PaymentTransaction
        fields = [
            'id',
            'pay_slip',
            'pay_slip_number',
            'teacher',
            'teacher_name',
            'payment_type',
            'payment_type_display',
            'amount',
            'payment_method',
            'payment_method_display',
            'payment_date',
            'transaction_id',
            'status',
            'status_display',
            'created_at',
        ]


class RecordPaymentSerializer(serializers.Serializer):
    """Serializer for recording a payment"""
    
    pay_slip_id = serializers.IntegerField()
    amount = serializers.DecimalField(max_digits=12, decimal_places=2)
    payment_method = serializers.CharField(max_length=20)
    payment_type = serializers.CharField(max_length=20, required=False, default='FULL')
    transaction_id = serializers.CharField(required=False, allow_blank=True, allow_null=True)
    bank_reference = serializers.CharField(required=False, allow_blank=True, allow_null=True)
    cheque_number = serializers.CharField(required=False, allow_blank=True, allow_null=True)
    upi_id = serializers.CharField(required=False, allow_blank=True, allow_null=True)
    bank_name = serializers.CharField(required=False, allow_blank=True, allow_null=True)
    bank_account_number = serializers.CharField(required=False, allow_blank=True, allow_null=True)
    bank_ifsc_code = serializers.CharField(required=False, allow_blank=True, allow_null=True)
    remarks = serializers.CharField(required=False, allow_blank=True, allow_null=True)
    
    def validate_amount(self, value):
        if value <= 0:
            raise serializers.ValidationError("Amount must be greater than zero")
        return value
    
    def validate(self, data):
        from .models import MonthlyPaySlip, PaymentTransaction
        
        pay_slip_id = data.get('pay_slip_id')
        amount = data.get('amount')
        
        try:
            pay_slip = MonthlyPaySlip.objects.get(id=pay_slip_id)
        except MonthlyPaySlip.DoesNotExist:
            raise serializers.ValidationError({"pay_slip_id": "Pay slip not found"})
        
        if pay_slip.status != 'APPROVED':
            raise serializers.ValidationError(
                f"Pay slip must be approved before payment. Current status: {pay_slip.status}"
            )
        
        total_paid = PaymentTransaction.objects.filter(
            pay_slip=pay_slip,
            status='COMPLETED'
        ).aggregate(total=models.Sum('amount'))['total'] or 0
        
        remaining = float(pay_slip.net_pay) - float(total_paid)
        
        if float(amount) > remaining:
            raise serializers.ValidationError(
                f"Amount exceeds remaining balance. Remaining: {remaining}"
            )
        
        data['pay_slip'] = pay_slip
        data['remaining_balance'] = remaining
        return data
    
    
# Add these to your existing serializers.py

class PaySlipTemplateSerializer(serializers.ModelSerializer):
    """Complete Pay Slip Template Serializer"""
    
    created_by_name = serializers.CharField(source='created_by.full_name', read_only=True, default=None)
    applicable_teachers_count = serializers.SerializerMethodField()
    applicable_teachers_list = serializers.SerializerMethodField()
    total_monthly_earnings = serializers.SerializerMethodField()
    
    class Meta:
        model = PaySlipTemplate
        fields = [
            'id',
            'name',
            'description',
            'applicable_teachers',
            'applicable_teachers_count',
            'applicable_teachers_list',
            'designation',
            'base_salary',
            'dearness_allowance',
            'house_rent_allowance',
            'city_compensatory_allowance',
            'travel_allowance',
            'medical_allowance',
            'special_allowance',
            'education_allowance',
            'telephone_allowance',
            'provident_fund_percentage',
            'esi_percentage',
            'professional_tax_fixed',
            'total_monthly_earnings',
            'is_active',
            'created_by',
            'created_by_name',
            'created_at',
            'updated_at',
        ]
        read_only_fields = ['created_at', 'updated_at']
    
    def get_applicable_teachers_count(self, obj):
        """Get count of teachers this template applies to"""
        return obj.applicable_teachers.filter(is_active=True).count()
    
    def get_applicable_teachers_list(self, obj):
        """Get list of applicable teachers"""
        teachers = obj.applicable_teachers.filter(is_active=True)[:10]
        return [{'id': t.id, 'name': t.full_name, 'employee_id': t.employee_id} for t in teachers]
    
    def get_total_monthly_earnings(self, obj):
        """Calculate total monthly earnings from template"""
        total = float(obj.base_salary or 0)
        total += float(obj.dearness_allowance or 0)
        total += float(obj.house_rent_allowance or 0)
        total += float(obj.city_compensatory_allowance or 0)
        total += float(obj.travel_allowance or 0)
        total += float(obj.medical_allowance or 0)
        total += float(obj.special_allowance or 0)
        total += float(obj.education_allowance or 0)
        total += float(obj.telephone_allowance or 0)
        return round(total, 2)


class PaySlipTemplateListSerializer(serializers.ModelSerializer):
    """List view Pay Slip Template Serializer"""
    
    applicable_teachers_count = serializers.SerializerMethodField()
    total_monthly_earnings = serializers.SerializerMethodField()
    
    class Meta:
        model = PaySlipTemplate
        fields = [
            'id',
            'name',
            'description',
            'designation',
            'base_salary',
            'total_monthly_earnings',
            'applicable_teachers_count',
            'is_active',
            'created_at',
        ]
    
    def get_applicable_teachers_count(self, obj):
        """Get count of teachers this template applies to"""
        return obj.applicable_teachers.filter(is_active=True).count()
    
    def get_total_monthly_earnings(self, obj):
        """Calculate total monthly earnings from template"""
        total = float(obj.base_salary or 0)
        total += float(obj.dearness_allowance or 0)
        total += float(obj.house_rent_allowance or 0)
        total += float(obj.city_compensatory_allowance or 0)
        total += float(obj.travel_allowance or 0)
        total += float(obj.medical_allowance or 0)
        total += float(obj.special_allowance or 0)
        total += float(obj.education_allowance or 0)
        total += float(obj.telephone_allowance or 0)
        return round(total, 2)