// assets/js/pages/credit-note.js

document.addEventListener('DOMContentLoaded', function() {
    // Initialize elements
    const form = document.getElementById('creditNoteForm');
    const corporateSelect = document.getElementById('corporate');
    const creditTypeSelect = document.getElementById('creditType');
    const debitNoteSelect = document.getElementById('debitNote');
    const memberSelect = document.getElementById('member');
    const exitDateInput = document.getElementById('exitDate');
    const memberSection = document.getElementById('memberSection');
    const creditItemsTable = document.getElementById('creditItemsTable').getElementsByTagName('tbody')[0];

    // Initialize Select2
    $('#corporate, #debitNote, #member').select2({
        width: '100%',
        placeholder: 'Select...',
        allowClear: true
    });

    // Handle credit type change
    creditTypeSelect.addEventListener('change', function() {
        memberSection.style.display = this.value === 'MEMBER_EXIT' ? 'flex' : 'none';
        
        if (this.value === 'MEMBER_EXIT') {
            memberSelect.required = true;
            exitDateInput.required = true;
        } else {
            memberSelect.required = false;
            exitDateInput.required = false;
            memberSelect.value = '';
            exitDateInput.value = '';
        }
    });

    // Handle corporate selection
    corporateSelect.addEventListener('change', function() {
        const corpId = this.value;
        debitNoteSelect.disabled = !corpId;
        
        if (!corpId) {
            resetForm();
            return;
        }

        // Fetch debit notes
        fetchDebitNotes(corpId);

        // If member exit, fetch members
        if (creditTypeSelect.value === 'MEMBER_EXIT') {
            fetchMembers(corpId);
        }
    });

    // Handle debit note selection
    debitNoteSelect.addEventListener('change', function() {
        const debitId = this.value;
        if (!debitId) {
            creditItemsTable.innerHTML = '';
            updateTotalCredit();
            return;
        }

        fetchDebitItems(debitId);
    });

    // Handle member selection for exits
    memberSelect.addEventListener('change', function() {
        if (creditTypeSelect.value === 'MEMBER_EXIT' && this.value && exitDateInput.value) {
            calculateExitCredit();
        }
    });

    // Handle exit date change
    exitDateInput.addEventListener('change', function() {
        if (creditTypeSelect.value === 'MEMBER_EXIT' && memberSelect.value && this.value) {
            calculateExitCredit();
        }
    });

    // Fetch debit notes for corporate
    function fetchDebitNotes(corpId) {
        debitNoteSelect.disabled = true;
        debitNoteSelect.innerHTML = '<option value="">Loading...</option>';

        fetch('get_corporate_debits.php?corp_id=' + encodeURIComponent(corpId))
            .then(response => response.json())
            .then(data => {
                debitNoteSelect.innerHTML = '<option value="">Select Debit Note</option>';

                if (data.success && data.debits && data.debits.length > 0) {
                    data.debits.forEach(debit => {
                        const option = new Option(
                            `${debit.debit_no} (${debit.debit_date}) - Available: ${debit.available_amount}`,
                            debit.debit_id
                        );
                        debitNoteSelect.appendChild(option);
                    });
                } else {
                    debitNoteSelect.innerHTML += '<option value="" disabled>No debit notes available</option>';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showError('Failed to fetch debit notes');
            })
            .finally(() => {
                debitNoteSelect.disabled = false;
            });
    }

    // Fetch members for corporate
    function fetchMembers(corpId) {
        memberSelect.disabled = true;
        memberSelect.innerHTML = '<option value="">Loading...</option>';

        fetch('get_corporate_members.php?corp_id=' + encodeURIComponent(corpId))
            .then(response => response.json())
            .then(data => {
                memberSelect.innerHTML = '<option value="">Select Member</option>';

                if (data.success && data.members && data.members.length > 0) {
                    data.members.forEach(member => {
                        const option = new Option(
                            `${member.surname} ${member.first_name} (${member.member_no})`,
                            member.member_no
                        );
                        memberSelect.appendChild(option);
                    });
                } else {
                    memberSelect.innerHTML += '<option value="" disabled>No members found</option>';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showError('Failed to fetch members');
            })
            .finally(() => {
                memberSelect.disabled = false;
            });
    }

    // Calculate exit credit
    function calculateExitCredit() {
        const data = {
            debit_id: debitNoteSelect.value,
            member_no: memberSelect.value,
            exit_date: exitDateInput.value
        };

        fetch('calculate_exit_credit.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        })
        .then(response => response.json())
        .then(data => {
            if (!data.success) {
                throw new Error(data.error);
            }
            updateCreditItems(data.items);
        })
        .catch(error => {
            console.error('Error:', error);
            showError('Failed to calculate exit credit');
        });
    }

    // Update credit items table
    function updateCreditItems(items) {
        creditItemsTable.innerHTML = '';
        let total = 0;

        items.forEach(item => {
            const row = creditItemsTable.insertRow();
            
            row.innerHTML = `
                <td>${item.benefit_name}</td>
                <td>${item.member_no}</td>
                <td class="text-end">${formatAmount(item.original_amount)}</td>
                <td class="text-end">${formatAmount(item.credit_amount)}</td>
                <td>${item.description}</td>
            `;

            total += parseFloat(item.credit_amount);
        });

        updateTotalCredit(total);
    }

    // Handle form submission
    form.addEventListener('submit', function(e) {
        e.preventDefault();

        if (!validateForm()) {
            return;
        }

        const formData = new FormData(this);

        Swal.fire({
            title: 'Confirm Credit Note',
            text: 'Are you sure you want to issue this credit note?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Yes, Issue Credit Note',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                submitCreditNote(formData);
            }
        });
    });

    // Helper functions
    function formatAmount(amount) {
        return parseFloat(amount).toLocaleString('en-KE', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
        });
    }

    function updateTotalCredit(total = 0) {
        document.getElementById('totalCredit').textContent = formatAmount(total);
    }

    function resetForm() {
        form.reset();
        creditItemsTable.innerHTML = '';
        updateTotalCredit();
        debitNoteSelect.innerHTML = '<option value="">Select Debit Note</option>';
        memberSelect.innerHTML = '<option value="">Select Member</option>';
        memberSection.style.display = 'none';
    }

    function showError(message) {
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: message
        });
    }

    function validateForm() {
        // Add your validation logic here
        return true;
    }

    function submitCreditNote(formData) {
        // Show loading state
        Swal.fire({
            title: 'Processing...',
            text: 'Please wait while we process the credit note',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        fetch('save_credit_note.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (!data.success) {
                throw new Error(data.error);
            }

            Swal.fire({
                icon: 'success',
                title: 'Success',
                text: 'Credit note issued successfully!',
                confirmButtonText: 'View Credit Note'
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = `view_credit_note.php?id=${data.credit_id}`;
                }
            });
        })
        .catch(error => {
            console.error('Error:', error);
            showError('Failed to save credit note: ' + error.message);
        });
    }
});