// Payment form functionality
document.addEventListener('DOMContentLoaded', function() {
    const paymentForms = document.querySelectorAll('form');
    
    paymentForms.forEach(form => {
        const amountField = form.querySelector('input[name="amount"]');
        const paymentTypeFields = form.querySelectorAll('input[name="payment_type"]');
        
        // Get balance from data attribute
        let currentBalance = 0;
        const balanceElement = document.getElementById('current-balance');
        
        if (balanceElement && balanceElement.dataset.balance) {
            currentBalance = parseFloat(balanceElement.dataset.balance) || 0;
        } else if (amountField && amountField.value) {
            // Fallback to amount field value
            currentBalance = parseFloat(amountField.value) || 0;
        }
        
        console.log('Payment form detected:', {
            amountField: amountField,
            paymentTypeFields: paymentTypeFields.length,
            balanceElement: balanceElement,
            currentBalance: currentBalance,
            initialAmount: amountField ? amountField.value : 'none'
        });
        
        if (amountField && paymentTypeFields.length > 0) {
            
            // Function to update amount field based on payment type
            function updateAmountField() {
                const selectedPaymentType = form.querySelector('input[name="payment_type"]:checked');
                console.log('Payment type changed:', {
                    selectedType: selectedPaymentType ? selectedPaymentType.value : 'none',
                    currentBalance: currentBalance
                });
                
                if (selectedPaymentType && selectedPaymentType.value === 'full' && currentBalance > 0) {
                    // Customer owes money - set full payment amount and disable editing
                    amountField.value = currentBalance.toFixed(2);
                    amountField.setAttribute('max', currentBalance.toFixed(2));
                    amountField.disabled = true;
                    amountField.style.backgroundColor = '#f3f4f6';
                    amountField.style.cursor = 'not-allowed';
                    console.log('Full payment set:', currentBalance.toFixed(2));
                } else if (selectedPaymentType && selectedPaymentType.value === 'full' && currentBalance <= 0) {
                    // Customer has credit - clear amount and show warning
                    amountField.value = '';
                    amountField.placeholder = 'Customer has credit - cannot process full payment';
                    amountField.style.borderColor = '#dc2626';
                    amountField.disabled = true;
                    amountField.style.backgroundColor = '#fef2f2';
                    amountField.style.cursor = 'not-allowed';
                    console.log('Full payment blocked - customer has credit');
                } else {
                    // Partial payment - enable editing and set to zero
                    amountField.removeAttribute('max');
                    amountField.style.borderColor = '';
                    amountField.disabled = false;
                    amountField.style.backgroundColor = '';
                    amountField.style.cursor = '';
                    if (selectedPaymentType && selectedPaymentType.value === 'partial') {
                        amountField.value = '0.00';
                        amountField.placeholder = 'Enter partial payment amount';
                        console.log('Partial payment set to 0.00');
                    }
                }
            }
            
            // Update amount field when payment type changes
            paymentTypeFields.forEach(field => {
                field.addEventListener('change', updateAmountField);
            });
            
            // Set initial amount for full payment
            updateAmountField();
            
            // Validate amount on form submission
            form.addEventListener('submit', function(e) {
                const amount = parseFloat(amountField.value);
                const selectedPaymentType = form.querySelector('input[name="payment_type"]:checked');
                
                // Check if customer has credit and trying to do full payment
                if (selectedPaymentType && selectedPaymentType.value === 'full' && currentBalance <= 0) {
                    e.preventDefault();
                    alert('Customer has credit balance. Cannot process full payment.');
                    return false;
                }
                
                if (selectedPaymentType && selectedPaymentType.value === 'full' && currentBalance > 0 && Math.abs(amount - currentBalance) > 0.01) {
                    e.preventDefault();
                    alert('For full payment, amount must match the current balance exactly.');
                    return false;
                }
                
                if (amount <= 0) {
                    e.preventDefault();
                    alert('Payment amount must be greater than 0.');
                    return false;
                }
                
                if (currentBalance > 0 && amount > currentBalance + 0.01) {
                    e.preventDefault();
                    alert('Payment amount cannot exceed the current balance.');
                    return false;
                }
            });
        }
    });
    
    // Add helpful hints
    const amountFields = document.querySelectorAll('input[name="amount"]');
    amountFields.forEach(field => {
        field.addEventListener('focus', function() {
            const paymentType = document.querySelector('input[name="payment_type"]:checked');
            if (paymentType && paymentType.value === 'partial') {
                this.placeholder = 'Enter partial payment amount';
            }
        });
    });
    
    // Handle custom radio button styling
    const paymentTypeOptions = document.querySelectorAll('.payment-type-option');
    paymentTypeOptions.forEach(option => {
        const radio = option.querySelector('input[type="radio"]');
        
        // Set initial selected state
        if (radio.checked) {
            option.classList.add('selected');
        }
        
        // Handle radio button changes
        radio.addEventListener('change', function() {
            // Remove selected class from all options
            paymentTypeOptions.forEach(opt => opt.classList.remove('selected'));
            
            // Add selected class to current option
            if (this.checked) {
                option.classList.add('selected');
            }
        });
        
        // Handle option click
        option.addEventListener('click', function() {
            const radio = this.querySelector('input[type="radio"]');
            radio.checked = true;
            radio.dispatchEvent(new Event('change'));
        });
    });
});
