(function () {
    'use strict';

    document.addEventListener('DOMContentLoaded', function () {
        const modalEl = document.getElementById('saleReturnModal');
        if (!modalEl) return;

        const dateInput = modalEl.querySelector('#sale-return-date');
        const searchInput = modalEl.querySelector('#sale-return-search');
        const searchBtn = modalEl.querySelector('#sale-return-search-btn');
        const resultsBody = modalEl.querySelector('#sale-return-results');
        const searchSection = modalEl.querySelector('#sale-return-search-section');
        const detailSection = modalEl.querySelector('#sale-return-detail-section');
        const backBtn = modalEl.querySelector('#sale-return-back-btn');
        const processBtn = modalEl.querySelector('#sale-return-process-btn');
        const remarksInput = modalEl.querySelector('#sale-return-remarks');
        const itemsTableBody = modalEl.querySelector('#sale-return-items');
        const returnWholeRadio = modalEl.querySelector('#modal-return-whole');
        const returnItemWiseRadio = modalEl.querySelector('#modal-return-itemwise');
        const statusEl = modalEl.querySelector('#sale-return-status');
        const summaryCountEl = modalEl.querySelector('#sale-return-summary-count');
        const summaryAmountEl = modalEl.querySelector('#sale-return-summary-amount');
        const invoiceEl = modalEl.querySelector('#sale-return-detail-invoice');
        const customerEl = modalEl.querySelector('#sale-return-detail-customer');
        const modeEl = modalEl.querySelector('#sale-return-detail-mode');
        const totalEl = modalEl.querySelector('#sale-return-detail-total');
        const paymentMethodEl = modalEl.querySelector('#sale-return-payment-method');
        const bankWrapperEl = modalEl.querySelector('#sale-return-bank-wrapper');
        const bankAccountEl = modalEl.querySelector('#sale-return-bank-account');

        let currentSale = null;
        let saleItems = [];
        let bankAccounts = [];

        function setDefaultDateIfNeeded() {
            if (!dateInput) return;
            if (!dateInput.value) {
                dateInput.value = getLocalDateString();
            }
        }

        function getLocalDateString(date = new Date()) {
            const tzOffset = date.getTimezoneOffset();
            const local = new Date(date.getTime() - tzOffset * 60 * 1000);
            return local.toISOString().slice(0, 10);
        }

        function setStatus(message, isError = false) {
            if (!statusEl) return;
            statusEl.textContent = message || '';
            statusEl.classList.toggle('text-danger', Boolean(isError));
        }

        function showDetailSection(show) {
            if (show) {
                detailSection.classList.remove('d-none');
                searchSection.classList.add('d-none');
                backBtn.classList.remove('d-none');
            } else {
                detailSection.classList.add('d-none');
                searchSection.classList.remove('d-none');
                backBtn.classList.add('d-none');
                currentSale = null;
                saleItems = [];
                remarksInput.value = '';
                summaryCountEl.textContent = '0';
                summaryAmountEl.textContent = formatAsCurrency(0);
                processBtn.disabled = true;
                // Reset payment method selection
                if (paymentMethodEl) {
                    paymentMethodEl.value = 'cash';
                    toggleBankAccountWrapper();
                }
            }
        }

        function fetchBankAccounts() {
            return fetch('ajax/get_bank_accounts.php')
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.banks) {
                        bankAccounts = data.banks;
                        populateBankDropdown();
                        return bankAccounts;
                    } else {
                        console.error('Failed to load bank accounts:', data.message);
                        bankAccounts = [];
                        return [];
                    }
                })
                .catch(error => {
                    console.error('Error fetching bank accounts:', error);
                    bankAccounts = [];
                    return [];
                });
        }

        function populateBankDropdown() {
            if (!bankAccountEl) return;
            
            // Clear existing options except the first one
            while (bankAccountEl.options.length > 1) {
                bankAccountEl.remove(1);
            }
            
            // Add banks
            bankAccounts.forEach(bank => {
                const option = document.createElement('option');
                option.value = bank.id;
                option.textContent = bank.account_title + (bank.bank_name ? ` (${bank.bank_name})` : '');
                bankAccountEl.appendChild(option);
            });
        }

        function toggleBankAccountWrapper() {
            if (!paymentMethodEl || !bankWrapperEl || !bankAccountEl) return;
            
            const paymentMethod = paymentMethodEl.value;
            const requiresBank = ['bank', 'card', 'upi'].includes(paymentMethod);
            
            if (requiresBank) {
                bankWrapperEl.classList.remove('d-none');
                bankAccountEl.required = true;
                // Fetch banks if not already loaded
                if (bankAccounts.length === 0) {
                    fetchBankAccounts();
                }
            } else {
                bankWrapperEl.classList.add('d-none');
                bankAccountEl.required = false;
                bankAccountEl.value = '';
            }
        }

        function formatAsCurrency(amount) {
            const safeAmount = Number.isFinite(amount) ? amount : 0;
            return 'Rs ' + safeAmount.toLocaleString(undefined, {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            });
        }

        function fetchSales() {
            const dateVal = dateInput.value;
            if (!dateVal) {
                setStatus('Please select a date to search.', true);
                return;
            }

            const query = searchInput.value || '';
            setStatus('Loading invoices...');
            resultsBody.innerHTML = `<tr><td colspan="6" class="text-center py-4"><div class="spinner-border text-primary" role="status"></div></td></tr>`;

            const params = new URLSearchParams({ date: dateVal, search: query });
            fetch(`ajax/get_sale_return_candidates.php?${params.toString()}`)
                .then(response => response.json())
                .then(data => {
                    if (!data.success) {
                        throw new Error(data.message || 'Unable to load invoices.');
                    }
                    renderSales(data.sales || []);
                    setStatus('');
                })
                .catch(error => {
                    console.error('Error loading sale return invoices:', error);
                    resultsBody.innerHTML = `<tr><td colspan="6" class="text-danger text-center py-4">${error.message || 'Failed to load invoices.'}</td></tr>`;
                    setStatus(error.message || 'Failed to load invoices', true);
                });
        }

        function renderSales(sales) {
            if (!sales.length) {
                resultsBody.innerHTML = `<tr><td colspan="6" class="text-center text-muted py-4">No invoices found for the selected filters.</td></tr>`;
                return;
            }

            resultsBody.innerHTML = sales.map(sale => `
                <tr>
                    <td>
                        <strong>${sale.invoice_number}</strong>
                        ${sale.has_return ? '<span class="badge bg-warning text-dark ms-2">Returned</span>' : ''}
                    </td>
                    <td>${sale.sale_date}</td>
                    <td>${sale.customer_name || 'Walk-in Customer'}</td>
                    <td class="text-end">${formatAsCurrency(sale.total_amount)}</td>
                    <td class="text-end">${formatAsCurrency(sale.net_amount)}</td>
                    <td class="text-center">
                        <button type="button" class="btn btn-sm btn-outline-primary sale-return-select" data-sale="${sale.id}">
                            <i class="fas fa-clipboard-check me-1"></i>Select
                        </button>
                    </td>
                </tr>
            `).join('');

            resultsBody.querySelectorAll('.sale-return-select').forEach(button => {
                button.addEventListener('click', () => {
                    const saleId = parseInt(button.getAttribute('data-sale'), 10);
                    if (saleId) {
                        loadSaleDetails(saleId);
                    }
                });
            });
        }

        function loadSaleDetails(saleId) {
            setStatus('Loading sale details...');
            showDetailSection(true);
            itemsTableBody.innerHTML = `<tr><td colspan="5" class="text-center py-4"><div class="spinner-border text-primary" role="status"></div></td></tr>`;

            fetch(`ajax/get_sale_return_details.php?sale_id=${saleId}`)
                .then(response => response.json())
                .then(data => {
                    if (!data.success) {
                        throw new Error(data.message || 'Unable to load sale.');
                    }
                    currentSale = data.sale;
                    saleItems = data.items || [];
                    invoiceEl.textContent = currentSale.invoice_number;
                    customerEl.textContent = currentSale.customer_name || 'Walk-in Customer';
                    modeEl.textContent = currentSale.order_mode ? currentSale.order_mode.replace('_', ' ') : 'walk in';
                    totalEl.textContent = formatAsCurrency(currentSale.total_amount || currentSale.net_amount || 0);
                    renderSaleItems();
                    applyReturnType();
                    setStatus('');
                })
                .catch(error => {
                    console.error('Error loading sale return details:', error);
                    Swal.fire({
                        icon: 'error',
                        title: 'Unable to load sale',
                        text: error.message || 'Please try again.'
                    }).then(() => {
                        showDetailSection(false);
                    });
                    setStatus(error.message || 'Unable to load sale.', true);
                });
        }

        function renderSaleItems() {
            if (!saleItems.length) {
                itemsTableBody.innerHTML = `<tr><td colspan="5" class="text-center text-muted py-4">No items recorded for this sale.</td></tr>`;
                return;
            }

            itemsTableBody.innerHTML = saleItems.map(item => `
                <tr>
                    <td>${item.item_name || 'Item #' + item.item_id}</td>
                    <td class="text-center">${item.quantity}</td>
                    <td class="text-center" style="max-width: 130px;">
                        <input type="number"
                               class="form-control form-control-sm sale-return-qty-input"
                               data-sale-item-id="${item.sale_item_id}"
                               min="0"
                               step="1"
                               max="${item.quantity}"
                               value="0">
                    </td>
                    <td class="text-end">${formatAsCurrency(item.unit_price)}</td>
                    <td class="text-end">
                        <span class="sale-return-line-total" data-sale-item-id="${item.sale_item_id}">${formatAsCurrency(0)}</span>
                    </td>
                </tr>
            `).join('');

            itemsTableBody.querySelectorAll('.sale-return-qty-input').forEach(input => {
                input.addEventListener('input', () => {
                    sanitizeQuantityInput(input);
                    updateSummary();
                });
            });
        }

        function sanitizeQuantityInput(input) {
            const max = parseFloat(input.getAttribute('max')) || 0;
            let value = parseFloat(input.value) || 0;
            if (value < 0) value = 0;
            if (value > max) value = max;
            input.value = value;

            const lineTotalEl = modalEl.querySelector(`.sale-return-line-total[data-sale-item-id="${input.getAttribute('data-sale-item-id')}"]`);
            if (lineTotalEl) {
                const item = saleItems.find(it => String(it.sale_item_id) === input.getAttribute('data-sale-item-id'));
                const lineTotal = item ? item.unit_price * value : 0;
                lineTotalEl.textContent = formatAsCurrency(lineTotal);
            }
        }

        function applyReturnType() {
            const isWhole = returnWholeRadio.checked;
            itemsTableBody.querySelectorAll('.sale-return-qty-input').forEach(input => {
                const max = parseFloat(input.getAttribute('max')) || 0;
                if (isWhole) {
                    input.value = max;
                    input.setAttribute('readonly', 'readonly');
                } else {
                    input.value = '0';
                    input.removeAttribute('readonly');
                }
                sanitizeQuantityInput(input);
            });
            updateSummary();
        }

        function updateSummary() {
            let selectedCount = 0;
            let totalAmount = 0;

            itemsTableBody.querySelectorAll('.sale-return-qty-input').forEach(input => {
                const qty = parseFloat(input.value) || 0;
                const saleItemId = parseInt(input.getAttribute('data-sale-item-id'), 10);
                const item = saleItems.find(it => it.sale_item_id === saleItemId);
                if (qty > 0 && item) {
                    selectedCount += 1;
                    totalAmount += qty * item.unit_price;
                }
            });

            summaryCountEl.textContent = selectedCount;
            summaryAmountEl.textContent = formatAsCurrency(totalAmount);
            processBtn.disabled = selectedCount === 0 || !currentSale;
        }

        function buildPayload() {
            const paymentMethod = paymentMethodEl ? paymentMethodEl.value : 'cash';
            const bankAccountId = paymentMethodEl && ['bank', 'card', 'upi'].includes(paymentMethod) && bankAccountEl ? 
                (bankAccountEl.value ? parseInt(bankAccountEl.value, 10) : null) : null;
            
            // Validate bank account selection
            if (['bank', 'card', 'upi'].includes(paymentMethod) && !bankAccountId) {
                throw new Error('Please select a bank account for the selected payment method.');
            }
            
            const payload = {
                sale_id: currentSale ? currentSale.id : null,
                return_type: returnWholeRadio.checked ? 'whole' : 'itemwise',
                customer_remarks: remarksInput.value || '',
                payment_method: paymentMethod,
                bank_account_id: bankAccountId,
                items: []
            };

            itemsTableBody.querySelectorAll('.sale-return-qty-input').forEach(input => {
                const qty = parseFloat(input.value) || 0;
                const sale_item_id = parseInt(input.getAttribute('data-sale-item-id'), 10);
                if (qty > 0 && sale_item_id) {
                    payload.items.push({
                        sale_item_id,
                        quantity: qty
                    });
                }
            });

            return payload;
        }

        function processReturn() {
            if (!currentSale) return;

            let payload;
            try {
                payload = buildPayload();
            } catch (error) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Validation Error',
                    text: error.message || 'Please check your selections.'
                });
                return;
            }
            
            if (!payload.items.length) {
                Swal.fire({
                    icon: 'warning',
                    title: 'No items selected',
                    text: 'Please select at least one item to return.'
                });
                return;
            }

            processBtn.disabled = true;
            processBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Processing';
            setStatus('Processing return, please wait...');

            fetch('ajax/process_sale_return.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            })
                .then(response => response.json())
                .then(data => {
                    if (!data.success) {
                        throw new Error(data.message || 'Unable to process return.');
                    }
                    Swal.fire({
                        icon: 'success',
                        title: 'Return completed',
                        text: data.message || 'Sale return processed successfully.',
                        timer: 2500
                    });
                    setStatus('Return completed successfully.');
                    showDetailSection(false);
                    fetchSales();
                })
                .catch(error => {
                    console.error('Error processing sale return:', error);
                    Swal.fire({
                        icon: 'error',
                        title: 'Return failed',
                        text: error.message || 'Unable to process return. Please try again.'
                    });
                    setStatus(error.message || 'Unable to process return.', true);
                })
                .finally(() => {
                    processBtn.disabled = false;
                    processBtn.innerHTML = '<i class="fas fa-check-circle me-2"></i>Process Return';
                });
        }

        searchBtn.addEventListener('click', fetchSales);
        searchInput.addEventListener('keyup', function (event) {
            if (event.key === 'Enter') {
                fetchSales();
            }
        });
        dateInput.addEventListener('change', () => {
            if (dateInput.value) {
                fetchSales();
            }
        });
        backBtn.addEventListener('click', () => showDetailSection(false));
        processBtn.addEventListener('click', processReturn);
        returnWholeRadio.addEventListener('change', applyReturnType);
        returnItemWiseRadio.addEventListener('change', applyReturnType);
        
        // Payment method change handler
        if (paymentMethodEl) {
            paymentMethodEl.addEventListener('change', toggleBankAccountWrapper);
        }

        modalEl.addEventListener('shown.bs.modal', () => {
            setDefaultDateIfNeeded();
            showDetailSection(false);
            fetchSales();
            // Pre-fetch bank accounts when modal opens
            fetchBankAccounts();
        });

        modalEl.addEventListener('hidden.bs.modal', () => {
            showDetailSection(false);
            resultsBody.innerHTML = `<tr><td colspan="6" class="text-center text-muted py-4">Use the filters above to load invoices.</td></tr>`;
            statusEl.textContent = '';
        });

        setDefaultDateIfNeeded();
    });
})();

