/**
 * Payment Registration Module
 * Handles customer payment registration against outstanding invoices
 */

(function() {
    'use strict';

    let outstandingInvoices = [];
    let selectedCustomerId = null;

    // Initialize on document ready
    $(document).ready(function() {
        initPaymentRegistration();
    });

    function initPaymentRegistration() {
        // Load customers into dropdown
        loadCustomers();

        // Event: Load Outstanding Bills
        $('#btnLoadOutstanding').on('click', async function() {
            const customerId = $('#paymentCustomerSelect').val();
            if (!customerId) {
                await MsgBox.alert('Please select a customer first');
                return;
            }
            loadOutstandingInvoices(customerId);
        });

        // Event: Customer Selection Change
        $('#paymentCustomerSelect').on('change', function() {
            const customerId = $(this).val();
            selectedCustomerId = customerId;
            
            if (customerId) {
                const selectedOption = $(this).find('option:selected');
                $('#paymentCustomerName').text(selectedOption.data('name'));
                $('#paymentCustomerCode').text(selectedOption.data('code'));
                $('#paymentCustomerInfo').slideDown();
                $('#btnLoadOutstanding').prop('disabled', false);
            } else {
                $('#paymentCustomerInfo').slideUp();
                $('#outstandingInvoicesSection').slideUp();
                $('#btnLoadOutstanding').prop('disabled', true);
                $('#btnSavePayment').prop('disabled', true);
            }
        });

        // Event: Select All Invoices
        $('#selectAllInvoices').on('change', function() {
            const isChecked = $(this).is(':checked');
            $('.invoice-checkbox').prop('checked', isChecked);
            updatePaymentSummary();
        });

        // Event: Individual Invoice Selection
        $(document).on('change', '.invoice-checkbox', function() {
            updatePaymentSummary();
            
            // Update select all checkbox
            const totalCheckboxes = $('.invoice-checkbox').length;
            const checkedCheckboxes = $('.invoice-checkbox:checked').length;
            $('#selectAllInvoices').prop('checked', totalCheckboxes === checkedCheckboxes);
        });

        // Event: Payment Amount Change
        $(document).on('input', '.payment-amount-input', function() {
            const row = $(this).closest('tr');
            const invoiceId = row.data('invoice-id');
            const outstanding = parseFloat(row.find('.outstanding-amount').text().replace(/[₹,]/g, '')) || 0;
            let paymentAmount = parseFloat($(this).val()) || 0;

            // Ensure payment doesn't exceed outstanding
            if (paymentAmount > outstanding) {
                paymentAmount = outstanding;
                $(this).val(paymentAmount.toFixed(2));
            }

            // Auto-check if payment amount > 0
            if (paymentAmount > 0) {
                row.find('.invoice-checkbox').prop('checked', true);
            } else {
                row.find('.invoice-checkbox').prop('checked', false);
            }

            updatePaymentSummary();
        });

        // Event: Payment Mode Change per Invoice
        $(document).on('change', '.payment-mode-select', function() {
            // Optional: Handle payment mode specific logic
        });

        // Event: Save Payment
        $('#btnSavePayment').on('click', function() {
            savePaymentRegistration();
        });

        // Modal close event - reset form
        $('#paymentRegistrationModal').on('hidden.bs.modal', function() {
            resetPaymentForm();
        });
    }

    function loadCustomers() {
        $.ajax({
            url: '../api/get-customers.php',
            method: 'GET',
            dataType: 'json',
            success: function(response) {
                if (response.success && response.customers) {
                    const select = $('#paymentCustomerSelect');
                    select.empty();
                    select.append('<option value="">-- Select Customer --</option>');
                    
                    response.customers.forEach(function(customer) {
                        select.append(
                            $('<option></option>')
                                .val(customer.ID)
                                .text(customer.CustomerCode + ' - ' + customer.CustomerName)
                                .data('name', customer.CustomerName)
                                .data('code', customer.CustomerCode)
                                .data('mobile', customer.Mobile || '')
                        );
                    });
                }
            },
            error: function() {
                MsgBox.alert('Error loading customers');
            }
        });
    }

    function loadOutstandingInvoices(customerId) {
        // Show loading
        $('#outstandingInvoicesList').html(
            '<tr><td colspan="8" class="text-center"><i class="fas fa-spinner fa-spin"></i> Loading...</td></tr>'
        );
        $('#outstandingInvoicesSection').slideDown();

        $.ajax({
            url: 'api/get-outstanding-invoices.php',
            method: 'POST',
            data: { customerId: customerId },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    outstandingInvoices = response.invoices || [];
                    displayOutstandingInvoices(outstandingInvoices);
                    
                    // Update total outstanding
                    const totalOutstanding = outstandingInvoices.reduce((sum, inv) => {
                        return sum + parseFloat(inv.Outstanding || 0);
                    }, 0);
                    $('#paymentTotalOutstanding').text('₹' + totalOutstanding.toFixed(2));
                } else {
                    $('#outstandingInvoicesList').html(
                        '<tr><td colspan="8" class="text-center text-muted"><i class="fas fa-info-circle"></i> ' + 
                        (response.message || 'No outstanding invoices found') + '</td></tr>'
                    );
                }
            },
            error: function(xhr, status, error) {
                console.error('Error loading invoices:', {
                    status: status,
                    error: error,
                    response: xhr.responseText
                });
                
                let errorMessage = 'Error loading invoices';
                try {
                    const response = JSON.parse(xhr.responseText);
                    if (response.message) {
                        errorMessage = response.message;
                    }
                } catch(e) {
                    // Response is not JSON, show raw error
                    if (xhr.responseText) {
                        errorMessage = xhr.responseText.substring(0, 200);
                    }
                }
                
                $('#outstandingInvoicesList').html(
                    '<tr><td colspan="8" class="text-center text-danger">' +
                    '<i class="fas fa-exclamation-triangle"></i> ' + errorMessage + 
                    '</td></tr>'
                );
            }
        });
    }

    function displayOutstandingInvoices(invoices) {
        const tbody = $('#outstandingInvoicesList');
        tbody.empty();

        if (invoices.length === 0) {
            tbody.html(
                '<tr><td colspan="8" class="text-center text-muted">' +
                '<i class="fas fa-check-circle text-success"></i> No outstanding invoices for this customer</td></tr>'
            );
            return;
        }

        invoices.forEach(function(invoice) {
            const outstanding = parseFloat(invoice.Outstanding) || 0;
            const invoiceAmount = parseFloat(invoice.InvoiceAmount) || 0;
            const paidAmount = parseFloat(invoice.PaidAmount) || 0;

            const row = $('<tr></tr>')
                .data('invoice-id', invoice.InvoiceID)
                .data('outstanding', outstanding);

            row.append(
                '<td class="text-center">' +
                '<input type="checkbox" class="invoice-checkbox" value="' + invoice.InvoiceID + '">' +
                '</td>' +
                '<td>' + invoice.InvoiceNumber + '</td>' +
                '<td>' + formatDate(invoice.InvoiceDate) + '</td>' +
                '<td class="text-right">₹' + invoiceAmount.toFixed(2) + '</td>' +
                '<td class="text-right">₹' + paidAmount.toFixed(2) + '</td>' +
                '<td class="text-right outstanding-amount text-danger font-weight-bold">₹' + outstanding.toFixed(2) + '</td>' +
                '<td class="text-right">' +
                '<input type="number" class="form-control form-control-sm text-right payment-amount-input" ' +
                'step="0.01" min="0" max="' + outstanding + '" placeholder="0.00" value="0">' +
                '</td>' +
                '<td>' +
                '<select class="form-control form-control-sm payment-mode-select">' +
                '<option value="Cash">Cash</option>' +
                '<option value="UPI">UPI</option>' +
                '<option value="Card">Card</option>' +
                '<option value="Cheque">Cheque</option>' +
                '<option value="Bank Transfer">Bank Transfer</option>' +
                '</select>' +
                '</td>'
            );

            tbody.append(row);
        });
    }

    function updatePaymentSummary() {
        let selectedCount = 0;
        let totalOutstanding = 0;
        let totalPayment = 0;

        $('.invoice-checkbox:checked').each(function() {
            const row = $(this).closest('tr');
            const outstanding = parseFloat(row.data('outstanding')) || 0;
            const payment = parseFloat(row.find('.payment-amount-input').val()) || 0;

            selectedCount++;
            totalOutstanding += outstanding;
            totalPayment += payment;
        });

        const remaining = totalOutstanding - totalPayment;

        $('#selectedInvoicesCount').text(selectedCount);
        $('#selectedOutstandingAmount').text('₹' + totalOutstanding.toFixed(2));
        $('#totalPaymentAmount').text('₹' + totalPayment.toFixed(2));
        $('#remainingOutstanding').text('₹' + remaining.toFixed(2));

        // Enable/disable save button
        if (selectedCount > 0 && totalPayment > 0) {
            $('#btnSavePayment').prop('disabled', false);
        } else {
            $('#btnSavePayment').prop('disabled', true);
        }
    }

    async function savePaymentRegistration() {
        const customerId = $('#paymentCustomerSelect').val();
        const paymentDate = $('#paymentDate').val();
        const defaultPaymentMode = $('#paymentMode').val();
        const paymentReference = $('#paymentReference').val();
        const paymentNotes = $('#paymentNotes').val();

        if (!customerId) {
            await MsgBox.alert('Please select a customer');
            return;
        }

        if (!paymentDate) {
            await MsgBox.alert('Please select payment date');
            return;
        }

        // Collect selected invoices with payment details
        const paymentDetails = [];
        $('.invoice-checkbox:checked').each(function() {
            const row = $(this).closest('tr');
            const invoiceId = row.data('invoice-id');
            const paymentAmount = parseFloat(row.find('.payment-amount-input').val()) || 0;
            const paymentMode = row.find('.payment-mode-select').val() || defaultPaymentMode;

            if (paymentAmount > 0) {
                paymentDetails.push({
                    invoiceId: invoiceId,
                    paymentAmount: paymentAmount,
                    paymentMode: paymentMode
                });
            }
        });

        if (paymentDetails.length === 0) {
            await MsgBox.alert('Please enter payment amount for at least one invoice');
            return;
        }

        // Confirm before saving
        const totalPayment = paymentDetails.reduce((sum, p) => sum + p.paymentAmount, 0);
        const confirmed = await MsgBox.confirm('Register payment of ₹' + totalPayment.toFixed(2) + ' for ' + paymentDetails.length + ' invoice(s)?');
        if (!confirmed) {
            return;
        }

        // Disable button and show loading
        const btnSave = $('#btnSavePayment');
        btnSave.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Saving...');

        // Prepare data
        const data = {
            customerId: customerId,
            paymentDate: paymentDate,
            paymentReference: paymentReference,
            paymentNotes: paymentNotes,
            payments: paymentDetails
        };

        $.ajax({
            url: 'api/save-payment-registration.php',
            method: 'POST',
            data: JSON.stringify(data),
            contentType: 'application/json',
            dataType: 'json',
            success: async function(response) {
                if (response.success) {
                    await MsgBox.alert('Payment registered successfully!');
                    $('#paymentRegistrationModal').modal('hide');
                    resetPaymentForm();
                    
                    // Optionally reload customer balance if on sales page
                    if (typeof loadCustomerDetails === 'function') {
                        loadCustomerDetails(customerId);
                    }
                } else {
                    await MsgBox.alert('Error: ' + (response.message || 'Failed to register payment'));
                    btnSave.prop('disabled', false).html('<i class="fas fa-save"></i> Register Payment');
                }
            },
            error: async function(xhr, status, error) {
                await MsgBox.alert('Error saving payment: ' + error);
                btnSave.prop('disabled', false).html('<i class="fas fa-save"></i> Register Payment');
            }
        });
    }

    function resetPaymentForm() {
        selectedCustomerId = null;
        outstandingInvoices = [];
        
        $('#paymentCustomerSelect').val('');
        $('#paymentCustomerInfo').slideUp();
        $('#outstandingInvoicesSection').slideUp();
        $('#outstandingInvoicesList').empty();
        $('#paymentDate').val(getTodayDate());
        $('#paymentMode').val('Cash');
        $('#paymentReference').val('');
        $('#paymentNotes').val('');
        
        $('#selectedInvoicesCount').text('0');
        $('#selectedOutstandingAmount').text('₹0.00');
        $('#totalPaymentAmount').text('₹0.00');
        $('#remainingOutstanding').text('₹0.00');
        $('#paymentTotalOutstanding').text('₹0.00');
        
        $('#btnSavePayment').prop('disabled', true).html('<i class="fas fa-save"></i> Register Payment');
        $('#selectAllInvoices').prop('checked', false);
    }

    function formatDate(dateString) {
        if (!dateString) return '-';
        const date = new Date(dateString);
        const day = String(date.getDate()).padStart(2, '0');
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const year = date.getFullYear();
        return day + '-' + month + '-' + year;
    }

    function getTodayDate() {
        const today = new Date();
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, '0');
        const day = String(today.getDate()).padStart(2, '0');
        return year + '-' + month + '-' + day;
    }

})();
