from django import forms
from .models import Sale, SaleItem

class SaleForm(forms.ModelForm):
    class Meta:
        model = Sale
        fields = [
            'customer', 'payment_method', 'cash_given', 'credit_amount',
            'mpesa_reference', 'cheque_number', 'cheque_date'
        ]

    def clean(self):
        cleaned_data = super().clean()
        payment_method = cleaned_data.get('payment_method')
        cash_given = cleaned_data.get('cash_given')
        credit_amount = cleaned_data.get('credit_amount')
        mpesa_reference = cleaned_data.get('mpesa_reference')
        cheque_number = cleaned_data.get('cheque_number')
        cheque_date = cleaned_data.get('cheque_date')

        # **Validation for different payment methods**
        if payment_method == 'credit' and not credit_amount:
            raise forms.ValidationError("Credit amount is required for credit payments.")

        if payment_method == 'mpesa' and not mpesa_reference:
            raise forms.ValidationError("M-Pesa reference is required for M-Pesa payments.")

        if payment_method == 'cheque' and (not cheque_number or not cheque_date):
            raise forms.ValidationError("Cheque number and date are required for cheque payments.")

        return cleaned_data


class SaleItemForm(forms.ModelForm):
    class Meta:
        model = SaleItem
        fields = ['batch', 'quantity']

    def clean(self):
        cleaned_data = super().clean()
        batch = cleaned_data.get('batch')
        quantity = cleaned_data.get('quantity')

        if batch and quantity:
            if batch.quantity < quantity:
                raise forms.ValidationError("Not enough stock in the selected batch.")
        return cleaned_data
