// POS Sales System - Keyboard Friendly (Excel-like)
// Global cart variable for access by other modules
let cart = [];

// Navigation flag to prevent change events during keyboard navigation
let isNavigating = false;

// Batch update queue for fast scanning
let batchUpdateQueue = [];
let batchUpdateTimer = null;
const BATCH_UPDATE_DELAY = 100; // Process batch updates every 100ms

/**
 * Add item to batch update queue for optimized processing
 */
function queueBatchUpdate(updateFn) {
    batchUpdateQueue.push(updateFn);
    
    if (batchUpdateTimer) {
        clearTimeout(batchUpdateTimer);
    }
    
    batchUpdateTimer = setTimeout(() => {
        processBatchUpdates();
    }, BATCH_UPDATE_DELAY);
}

/**
 * Process all queued batch updates
 */
function processBatchUpdates() {
    if (batchUpdateQueue.length === 0) return;
    
    // Execute all queued updates
    batchUpdateQueue.forEach(updateFn => updateFn());
    batchUpdateQueue = [];
    
    // Single display update after all changes
    updateDisplay();
}

// Helper functions to sync desktop and mobile fields
function setRateValue(value) {
    $('#rate').val(value);
    $('#rateMobile').val(value);
}

function setQuantityValue(value) {
    $('#quantity').val(value);
    $('#quantityMobile').val(value);
}

function getRateValue() {
    return $('#rate').val() || $('#rateMobile').val();
}

function getQuantityValue() {
    return $('#quantity').val() || $('#quantityMobile').val();
}

$(document).ready(function() {
    // Cart data (cart is now global)
    let suggestionIndex = -1;
    let suggestions = [];
    let customerSuggestionIndex = -1;
    let customerSuggestions = [];
    let supplierSuggestionIndex = -1;
    let supplierSuggestions = [];
    let allCustomers = [];
    let allSuppliers = [];
    
    // Expose cart globally for access by BillDiscountManager
    window.cart = cart;
    
    // Expose update functions globally for GST Type Manager
    window.updateDisplay = updateDisplay;
    window.updateCartTable = updateCartTable;
    window.updateTotals = updateTotals;

    // Initialize
    initializeEventListeners();
    loadAllCustomers();
    loadAllSuppliers();
    updateDisplay();

    // Event Listeners
    function initializeEventListeners() {
        // Price Type Selector
        $('#priceTypeSelector button').on('click', function() {
            const priceType = $(this).data('price-type');
            $('#selectedPriceType').val(priceType);
            
            // Update button styles
            $('#priceTypeSelector button').removeClass('active');
            $(this).addClass('active');
            
            // Update price if product is already selected
            updatePriceBySelectedType();
        });
        
        // Customer Search - Show all on focus
        $('#customerSearch').on('focus', function() {
            if (allCustomers.length > 0) {
                displayCustomerSuggestions(allCustomers);
            }
        });

        // Customer Search
        $('#customerSearch').on('input', function() {
            const query = $(this).val().trim();
            if (query.length >= 1) {
                searchCustomers(query);
            } else {
                // Show all customers when search is cleared
                displayCustomerSuggestions(allCustomers);
            }
        });

        // Customer Search - Keyboard navigation
        $('#customerSearch').on('keydown', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                if (customerSuggestionIndex >= 0 && customerSuggestions.length > 0) {
                    selectCustomer(customerSuggestions[customerSuggestionIndex]);
                }
                return false;
            } else if (e.key === 'ArrowDown') {
                e.preventDefault();
                navigateCustomerSuggestions('down');
            } else if (e.key === 'ArrowUp') {
                e.preventDefault();
                navigateCustomerSuggestions('up');
            } else if (e.key === 'Escape') {
                $('#customerSuggestions').hide().empty();
                customerSuggestionIndex = -1;
            }
        });

        // Customer Search - Hide on blur
        $('#customerSearch').on('blur', function() {
            setTimeout(function() {
                $('#customerSuggestions').hide();
            }, 200);
        });

        // Supplier Search - Show all on focus
        $('#supplierSearch').on('focus', function() {
            if (allSuppliers.length > 0) {
                displaySupplierSuggestions(allSuppliers);
            }
        });

        // Supplier Search
        $('#supplierSearch').on('input', function() {
            const query = $(this).val().trim();
            if (query.length >= 1) {
                searchSuppliers(query);
            } else {
                // Show all suppliers when search is cleared
                displaySupplierSuggestions(allSuppliers);
            }
        });

        // Supplier Search - Keyboard navigation
        $('#supplierSearch').on('keydown', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                if (supplierSuggestionIndex >= 0 && supplierSuggestions.length > 0) {
                    selectSupplier(supplierSuggestions[supplierSuggestionIndex]);
                }
                return false;
            } else if (e.key === 'ArrowDown') {
                e.preventDefault();
                navigateSupplierSuggestions('down');
            } else if (e.key === 'ArrowUp') {
                e.preventDefault();
                navigateSupplierSuggestions('up');
            } else if (e.key === 'Escape') {
                $('#supplierSuggestions').hide().empty();
                supplierSuggestionIndex = -1;
            }
        });

        // Supplier Search - Hide on blur
        $('#supplierSearch').on('blur', function() {
            setTimeout(function() {
                $('#supplierSuggestions').hide();
            }, 200);
        });
        $('#productCode').on('focus', function() {
            const query = $(this).val().trim();
            if (query.length >= 1) {
                searchProducts(query);
            } else {
                // Show all products when empty
                searchProducts('');
            }
        });

        // Product Code - Auto-suggest
        $('#productCode').on('input', function() {
            const query = $(this).val().trim();
            if (query.length >= 1) {
                searchProducts(query);
            } else {
                searchProducts(''); // Show all when cleared
            }
        });

        // Product Code - Enter key
        $('#productCode').on('keydown', async function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                if (suggestionIndex >= 0 && suggestions.length > 0) {
                    selectSuggestion(suggestionIndex);
                } else {
                    // Try to find exact match
                    const code = $(this).val().trim().toUpperCase();
                    if (code) {
                        // Check if quantity and rate are already filled (manual entry)
                        const hasRate = $('#rate').val() && parseFloat($('#rate').val()) > 0;
                        const hasQuantity = $('#quantity').val() && parseFloat($('#quantity').val()) > 0;
                        
                        // If both rate and quantity are filled, add to cart directly
                        if (hasRate && hasQuantity) {
                            await addToCart();
                        } else {
                            // Check barcode scan mode
                            const autoScanEnabled = $('#barcodeScanMode').is(':checked');
                            // Auto-add if barcode scan mode is enabled
                            await searchProductByCode(code, autoScanEnabled);
                        }
                    } else {
                        // If empty, just move to rate
                        $('#productSuggestions').hide().empty();
                        $('#rate').focus().select();
                    }
                }
                return false;
            } else if (e.key === 'ArrowDown') {
                e.preventDefault();
                // Check if Auto Scan is enabled
                const autoScanEnabled = $('#barcodeScanMode').is(':checked');
                
                if (autoScanEnabled) {
                    // Focus on first cart item quantity if cart has items
                    const $firstQtyInput = $('#cartItems tr:first .cart-qty-input');
                    if ($firstQtyInput.length) {
                        $firstQtyInput.focus().select();
                    }
                } else {
                    // Normal suggestion navigation
                    navigateSuggestions('down');
                }
            } else if (e.key === 'ArrowUp') {
                e.preventDefault();
                navigateSuggestions('up');
            } else if (e.key === 'ArrowRight') {
                // Right Arrow - Move to Rate (if no suggestions visible and code is not empty)
                const code = $(this).val().trim();
                if (!$('#productSuggestions').is(':visible') && code) {
                    e.preventDefault();
                    $('#rate').focus().select();
                }
            } else if (e.key === 'Escape') {
                $('#productSuggestions').hide().empty();
                suggestionIndex = -1;
            }
        });

        // Product Code - Hide suggestions on blur
        $('#productCode').on('blur', function() {
            // Delay to allow click on suggestion
            setTimeout(function() {
                $('#productSuggestions').hide();
            }, 200);
        });

        // Rate - Enter key to move to quantity
        $('#rate').on('keydown', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                // Hide suggestions if still visible
                $('#productSuggestions').hide().empty();
                $('#quantity').focus().select();
                return false;
            }
            // Left Arrow - Move to Product Code
            if (e.key === 'ArrowLeft') {
                e.preventDefault();
                $('#productCode').focus().select();
                return false;
            }
            // Right Arrow - Move to Quantity
            if (e.key === 'ArrowRight') {
                e.preventDefault();
                $('#quantity').focus().select();
                return false;
            }
        });

        // Rate - Prevent focus if product code is empty
        $('#rate').on('focus', function(e) {
            $('#productSuggestions').hide().empty();
            
            // Check if product code is empty
            const productCode = $('#productCode').val().trim();
            if (!productCode) {
                e.preventDefault();
                $(this).blur();
                $('#productCode').focus();
                return false;
            }
        });

        // Rate - Auto calculate
        $('#rate').on('input', function() {
            calculateCurrentItemTotal();
        });

        // Quantity - Enter key to add to cart
        $('#quantity').on('keydown', async function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                // Hide suggestions if still visible
                $('#productSuggestions').hide().empty();
                
                // If quantity is 0 or empty, set to 1
                const qty = parseFloat($(this).val()) || 0;
                if (qty <= 0) {
                    $(this).val('1');
                    calculateCurrentItemTotal();
                }
                
                await addToCart();
                return false;
            }
            // Left Arrow - Move to Rate
            if (e.key === 'ArrowLeft') {
                e.preventDefault();
                $('#rate').focus().select();
                return false;
            }
        });

        // Quantity - Prevent focus if product code is empty
        $('#quantity').on('focus', function(e) {
            $('#productSuggestions').hide();
            
            // Check if product code is empty
            const productCode = $('#productCode').val().trim();
            if (!productCode) {
                e.preventDefault();
                $(this).blur();
                $('#productCode').focus();
                return false;
            }
        });
        $('#quantity').on('focus', function() {
            $('#productSuggestions').hide().empty();
        });

        // Quantity - Auto calculate
        $('#quantity').on('input', function() {
            calculateCurrentItemTotal();
        });

        // Add to Cart button
        $('#addToCart').click(async function() {
            await addToCart();
        });

        // Cooli Amount - Auto update total
        $('#cooliAmount').on('input', function() {
            updateTotals();
        });
        
        // Transport GST Configuration Button
        $('#btnTransportGST').click(function() {
            openTransportGSTModal();
        });
        
        // Transport GST Modal Events
        $('#transportGSTPercentage').on('input', function() {
            calculateTransportGST();
        });
        
        $('input[name="transportGSTType"]').on('change', function() {
            calculateTransportGST();
        });
        
        $('#btnApplyTransportGST').click(function() {
            applyTransportGST();
        });
        
        $('#btnResetTransportGST').click(function() {
            resetTransportGST();
        });
        
        // Cash Amount - Auto calculate UPI + Credit
        $('#cashAmount').on('input', function() {
            updatePaymentDistribution('cash');
        });
        
        // UPI Amount - Auto calculate Cash + Credit
        $('#upiAmount').on('input', function() {
            updatePaymentDistribution('upi');
        });
        
        // Credit Amount - Auto calculate Cash + UPI
        $('#creditAmount').on('input', function() {
            updatePaymentDistribution('credit');
        });
        
        // Payment Amount field removed - payment registration moved to separate modal
        // $('#paymentAmount').on('input', function() {
        //     updatePaymentDistribution('payment');
        //     updateRemainingBalance();
        // });

        // Customer Selection
        $('#customerSelect').change(function() {
            const balance = $(this).find(':selected').data('balance');
            const customerName = $(this).find(':selected').data('name');
            
            // Update search box with selected customer
            if ($(this).val()) {
                $('#customerSearch').val(customerName);
                $('#btnViewLedger').prop('disabled', false);
            } else {
                $('#customerSearch').val('');
                $('#btnViewLedger').prop('disabled', true);
            }
            
            if (balance && balance > 0) {
                $('#customerBalance').text('₹' + parseFloat(balance).toFixed(2));
                $('#customerBalanceDisplay').slideDown();
            } else {
                $('#customerBalanceDisplay').slideUp();
            }
        });

        // Save Sale
        $('#saveSale').click(async function() {
            await saveSale();
        });
        
        // Previous Bill
        $('#btnPrevious').click(async function() {
            await navigateBill('previous');
        });
        
        // Next Bill
        $('#btnNext').click(async function() {
            await navigateBill('next');
        });
        
        // Delete Bill
        $('#btnDeleteBill').click(async function() {
            await deleteSale();
        });
        
        // Add Supplier Button
        $('#btnAddSupplier').click(function() {
            $('#addSupplierModal').modal('show');
            $('#newSupplierName').focus();
        });
        
        // View Ledger Button
        $('#btnViewLedger').click(async function() {
            const supplierId = $('#supplierSelect').val();
            if (supplierId) {
                // Open supplier ledger report with current month as default
                const today = new Date();
                const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
                const startDate = formatDateForInput(firstDay);
                const endDate = formatDateForInput(today);
                
                window.open('supplier-ledger-report.php?supplierId=' + supplierId + '&startDate=' + startDate + '&endDate=' + endDate, '_blank');
            } else {
                await MsgBox.alert(t('selectSupplier'));
            }
        });
        
        // Helper function to format date for URL
        function formatDateForInput(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        }
        
        // Save New Supplier
        $('#btnSaveSupplier').click(async function() {
            await saveNewSupplier();
        });

        // Clear Cart
        $('#clearCart').click(async function() {
            if (await MsgBox.confirm(t('confirmClearCart'))) {
                clearCart();
            }
        });

        // New Sale
        $('#newSale').click(async function() {
            if (cart.length > 0) {
                if (await MsgBox.confirm(t('confirmNewSale'))) {
                    location.reload();
                }
            } else {
                location.reload();
            }
        });

        // Global Keyboard Shortcuts
        $(document).keydown(function(e) {
            // F2 - Focus to Product Code
            if (e.key === 'F2') {
                e.preventDefault();
                $('#productCode').focus().select();
                return false;
            }
            // F7 - Focus to Cash Amount
            if (e.key === 'F7') {
                e.preventDefault();
                $('#cashAmount').focus().select();
                return false;
            }
            // F8 - Focus to UPI Amount
            if (e.key === 'F8') {
                e.preventDefault();
                $('#upiAmount').focus().select();
                return false;
            }
            // F10 - Save Sale
            if (e.key === 'F10') {
                e.preventDefault();
                if (!$('#saveSale').prop('disabled')) {
                    (async () => {
                        await saveSale();
                    })();
                }
                return false;
            }
            // Delete - Remove selected cart item
            if (e.key === 'Delete' || e.keyCode === 46) {
                // Check if we're not in an input field
                if (!$(e.target).is('input, textarea, select')) {
                    const selectedRow = $('#cartTable tbody tr.selected');
                    if (selectedRow.length > 0) {
                        e.preventDefault();
                        const index = selectedRow.index();
                        if (cart[index]) {
                            cart.splice(index, 1);
                            updateDisplay();
                        }
                        return false;
                    }
                }
            }
            // Escape - Clear cart and start new sale
            if (e.key === 'Escape' || e.keyCode === 27) {
                // Check if we're not in a modal or input field with content
                if (!$(e.target).closest('.modal').length) {
                    e.preventDefault();
                    // Only clear if there's something in the cart or fields
                    if (cart.length > 0 || $('#cashAmount').val() !== '0.00' || $('#upiAmount').val() !== '0.00') {
                        (async () => {
                            if (await MsgBox.confirm('Clear cart and start new sale?')) {
                                clearCart();
                                $('#productCode').focus();
                                showNotification('Cart cleared. Ready for new sale.', 'success');
                            }
                        })();
                    }
                    return false;
                }
            }
        });

        // Click outside to hide suggestions
        $(document).click(function(e) {
            if (!$(e.target).closest('#productCode, #productSuggestions').length) {
                $('#productSuggestions').hide();
            }
            if (!$(e.target).closest('#customerSearch, #customerSuggestions').length) {
                $('#customerSuggestions').hide();
            }
            if (!$(e.target).closest('#supplierSearch, #supplierSuggestions').length) {
                $('#supplierSuggestions').hide();
            }
        });
    }

    // Update Payment Distribution
    function updatePaymentDistribution(changedField) {
        const billAmount = parseFloat($('#grandTotal').text().replace('₹', '')) || 0;
        
        if (billAmount === 0) {
            $('#cashAmount').val('0.00');
            $('#upiAmount').val('0.00');
            $('#creditAmount').val('0.00');
            return;
        }
        
        if (changedField === 'payment') {
            // Payment amount field removed - no longer updating
            return;
        } else if (changedField === 'billAmount') {
            // Bill amount changed - set full amount to Cash by default
            $('#cashAmount').val(billAmount.toFixed(2));
            $('#upiAmount').val('0.00');
            $('#creditAmount').val('0.00');
            
            updateTotalPayment();
        } else {
            // User manually changed Cash or UPI - auto-calculate Credit
            const cashAmount = parseFloat($('#cashAmount').val()) || 0;
            const upiAmount = parseFloat($('#upiAmount').val()) || 0;
            
            // Credit = Bill Amount - (Cash + UPI)
            const creditAmount = Math.max(0, billAmount - cashAmount - upiAmount);
            $('#creditAmount').val(creditAmount.toFixed(2));
            
            updateTotalPayment();
        }
    }
    
    // Update Total Payment (internal calculation only)
    function updateTotalPayment() {
        const cashAmount = parseFloat($('#cashAmount').val()) || 0;
        const upiAmount = parseFloat($('#upiAmount').val()) || 0;
        const creditAmount = parseFloat($('#creditAmount').val()) || 0;
        const billAmount = parseFloat($('#grandTotal').text().replace('₹', '')) || 0;
        const totalPaid = cashAmount + upiAmount;
        const totalPayment = cashAmount + upiAmount + creditAmount;
        
        // Calculate change/balance
        const changeAmount = totalPaid - billAmount;
        
        if (changeAmount > 0) {
            // Show change to return
            $('#changeAmountDisplay').slideDown();
            $('#changeAmount').text('₹' + changeAmount.toFixed(2));
        } else {
            // Hide change display if no overpayment
            $('#changeAmountDisplay').slideUp();
        }
        
        // Payment amount field removed, but keep calculation for backend
        // $('#paymentAmount').val(totalPayment.toFixed(2));
    }

    // Load All Customers
    function loadAllCustomers() {
        $('#customerSelect option').each(function() {
            if ($(this).val()) {
                allCustomers.push({
                    id: $(this).val(),
                    name: $(this).data('name'),
                    code: $(this).data('code'),
                    phone: $(this).data('phone'),
                    balance: $(this).data('balance')
                });
            }
        });
        
        // Set initial customer if selected
        const selectedCustomerId = $('#customerSelect').val();
        if (selectedCustomerId) {
            const selectedCustomer = allCustomers.find(c => c.id == selectedCustomerId);
            if (selectedCustomer) {
                $('#customerSearch').val(selectedCustomer.name);
                $('#customerSelect').trigger('change');
            }
        }
    }

    // Load All Suppliers
    function loadAllSuppliers() {
        $('#supplierSelect option').each(function() {
            if ($(this).val()) {
                allSuppliers.push({
                    id: $(this).val(),
                    name: $(this).data('name'),
                    code: $(this).data('code'),
                    phone: $(this).data('phone'),
                    balance: $(this).data('balance')
                });
            }
        });
        
        // Set initial supplier if selected
        const selectedSupplierId = $('#supplierSelect').val();
        if (selectedSupplierId) {
            const selectedSupplier = allSuppliers.find(s => s.id == selectedSupplierId);
            if (selectedSupplier) {
                $('#supplierSearch').val(selectedSupplier.name);
                $('#supplierSelect').trigger('change');
            }
        }
    }

    // Search Customers
    function searchCustomers(query) {
        query = query.toLowerCase();
        customerSuggestions = allCustomers.filter(customer => {
            return customer.name.toLowerCase().includes(query) ||
                   customer.code.toLowerCase().includes(query) ||
                   (customer.phone && String(customer.phone).toLowerCase().includes(query));
        });

        if (customerSuggestions.length > 0) {
            displayCustomerSuggestions(customerSuggestions);
        } else {
            $('#customerSuggestions').hide().empty();
        }
    }

    // Search Suppliers
    function searchSuppliers(query) {
        query = query.toLowerCase();
        supplierSuggestions = allSuppliers.filter(supplier => {
            return supplier.name.toLowerCase().includes(query) ||
                   supplier.code.toLowerCase().includes(query) ||
                   (supplier.phone && String(supplier.phone).toLowerCase().includes(query));
        });

        if (supplierSuggestions.length > 0) {
            displaySupplierSuggestions(supplierSuggestions);
        } else {
            $('#supplierSuggestions').hide().empty();
        }
    }

    // Display Customer Suggestions
    function displayCustomerSuggestions(customers) {
        customerSuggestionIndex = -1;
        customerSuggestions = customers.slice();

        let html = '';
        customers.forEach(function(customer, index) {
            html += '<div class="customer-suggestion-item" data-index="' + index + '" data-customer-id="' + customer.id + '">';
            html += '<span class="customer-name-only">' + customer.name + '</span>';
            html += '</div>';
        });

        $('#customerSuggestions').html(html).show();

        // Use event delegation for better click handling
        $('#customerSuggestions').off('click').on('click', '.customer-suggestion-item', function(e) {
            e.preventDefault();
            e.stopPropagation();
            const index = $(this).data('index');
            selectCustomer(customerSuggestions[index]);
        });
    }

    // Display Supplier Suggestions
    function displaySupplierSuggestions(suppliers) {
        supplierSuggestionIndex = -1;
        supplierSuggestions = suppliers.slice();

        let html = '';
        suppliers.forEach(function(supplier, index) {
            html += '<div class="supplier-suggestion-item" data-index="' + index + '" data-supplier-id="' + supplier.id + '">';
            html += '<span class="supplier-name-only">' + supplier.name + '</span>';
            html += '</div>';
        });

        $('#supplierSuggestions').html(html).show();

        // Use event delegation for better click handling
        $('#supplierSuggestions').off('click').on('click', '.supplier-suggestion-item', function(e) {
            e.preventDefault();
            e.stopPropagation();
            const index = $(this).data('index');
            selectSupplier(supplierSuggestions[index]);
        });
    }

    // Navigate Customer Suggestions
    function navigateCustomerSuggestions(direction) {
        if (customerSuggestions.length === 0) return;
        
        $('.customer-suggestion-item').removeClass('active');
        
        if (direction === 'down') {
            customerSuggestionIndex++;
            if (customerSuggestionIndex >= customerSuggestions.length) {
                customerSuggestionIndex = 0;
            }
        } else if (direction === 'up') {
            customerSuggestionIndex--;
            if (customerSuggestionIndex < 0) {
                customerSuggestionIndex = customerSuggestions.length - 1;
            }
        }
        
        $('.customer-suggestion-item').eq(customerSuggestionIndex).addClass('active');
    }

    // Navigate Supplier Suggestions
    function navigateSupplierSuggestions(direction) {
        if (supplierSuggestions.length === 0) return;
        
        $('.supplier-suggestion-item').removeClass('active');
        
        if (direction === 'down') {
            supplierSuggestionIndex++;
            if (supplierSuggestionIndex >= supplierSuggestions.length) {
                supplierSuggestionIndex = 0;
            }
        } else if (direction === 'up') {
            supplierSuggestionIndex--;
            if (supplierSuggestionIndex < 0) {
                supplierSuggestionIndex = supplierSuggestions.length - 1;
            }
        }
        
        $('.supplier-suggestion-item').eq(supplierSuggestionIndex).addClass('active');
    }

    // Select Customer
    function selectCustomer(customer) {
        console.log('Selecting customer:', customer);
        $('#customerSelect').val(customer.id);
        $('#customerSearch').val(customer.name);
        $('#customerSuggestions').hide().empty();
        customerSuggestionIndex = -1;
        customerSuggestions = [];
        
        // Enable ledger button
        $('#btnViewLedger').prop('disabled', false);
        
        // Update balance displays
        const balance = parseFloat(customer.balance) || 0;
        // Old balance field removed
        
        if (balance > 0) {
            $('#customerBalance').text('₹' + balance.toFixed(2));
            $('#customerBalanceDisplay').slideDown();
        } else {
            $('#customerBalanceDisplay').slideUp();
        }
        
        // Outstanding calculation removed - handled by payment registration module
        
        // Enable save button if cart has items
        if (cart.length > 0) {
            $('#saveSale').prop('disabled', false);
        }
        
        // Focus to product code
        setTimeout(function() {
            $('#productCode').focus();
        }, 100);
    }

    // Select Supplier
    function selectSupplier(supplier) {
        console.log('Selecting supplier:', supplier);
        $('#supplierSelect').val(supplier.id);
        $('#supplierSearch').val(supplier.name);
        $('#supplierSuggestions').hide().empty();
        supplierSuggestionIndex = -1;
        supplierSuggestions = [];
        
        // Enable ledger button
        $('#btnViewLedger').prop('disabled', false);
        
        // Update balance displays
        const balance = parseFloat(supplier.balance) || 0;
        
        if (balance > 0) {
            $('#supplierBalance').text('₹' + balance.toFixed(2));
            $('#supplierBalanceDisplay').slideDown();
        } else {
            $('#supplierBalanceDisplay').slideUp();
        }
        
        // Enable save button if cart has items
        if (cart.length > 0) {
            $('#saveSale').prop('disabled', false);
        }
        
        // Focus to product code
        setTimeout(function() {
            $('#productCode').focus();
        }, 100);
    }
    function searchProducts(query) {
        $.ajax({
            url: 'api/search-product.php',
            method: 'POST',
            data: { query: query },
            dataType: 'json',
            success: function(response) {
                if (response.success && response.products.length > 0) {
                    displaySuggestions(response.products);
                } else {
                    $('#productSuggestions').hide().empty();
                }
            }
        });
    }

    // Display Suggestions
    function displaySuggestions(products) {
        // Check if Auto Scan mode is enabled
        const autoScanEnabled = $('#barcodeScanMode').is(':checked');
        
        // Don't show suggestions if Auto Scan is ON
        if (autoScanEnabled) {
            $('#productSuggestions').hide().empty();
            return;
        }
        
        suggestions = products;
        suggestionIndex = -1;
        
        let html = '';
        products.forEach(function(product, index) {
            const stock = parseFloat(product.CurrentStock || 0);
            const alertQty = parseFloat(product.AlertQuantity || 0);
            const stockClass = stock <= alertQty ? 'low' : '';
            const mrp = parseFloat(product.MRP || 0);
            
            html += '<div class="suggestion-item" data-index="' + index + '">';
            html += '<span class="suggestion-code">' + product.ProductCode + '</span>';
            html += '<span class="suggestion-name">' + product.ProductName + '</span>';
            html += '<span class="suggestion-stock ' + stockClass + '">Stock: ' + stock.toFixed(0) + '</span>';
            if (mrp > 0) {
                html += '<span class="suggestion-mrp">MRP: ₹' + mrp.toFixed(2) + '</span>';
            }
            html += '<span class="suggestion-rate">₹' + parseFloat(product.Rate).toFixed(2) + '</span>';
            html += '</div>';
        });
        
        $('#productSuggestions').html(html).show();
        
        // Click handler for suggestions
        $('.suggestion-item').click(function() {
            const index = $(this).data('index');
            selectSuggestion(index);
        });
    }

    // Navigate Suggestions
    function navigateSuggestions(direction) {
        if (suggestions.length === 0) return;
        
        $('.suggestion-item').removeClass('active');
        
        if (direction === 'down') {
            suggestionIndex++;
            if (suggestionIndex >= suggestions.length) {
                suggestionIndex = 0;
            }
        } else if (direction === 'up') {
            suggestionIndex--;
            if (suggestionIndex < 0) {
                suggestionIndex = suggestions.length - 1;
            }
        }
        
        $('.suggestion-item').eq(suggestionIndex).addClass('active');
    }

    // Select Suggestion
    function selectSuggestion(index) {
        if (index < 0 || index >= suggestions.length) return;
        
        const product = suggestions[index];
        $('#productId').val(product.ID);
        $('#productCode').val(product.ProductCode);
        $('#productName').text(product.ProductName);
        
        // Store all price types
        const prices = {
            SalesPrice: parseFloat(product.SalesPrice || product.Rate || 0),
            ShopRate: parseFloat(product.ShopRate || 0),
            WholesaleRate: parseFloat(product.WholesaleRate || 0),
            MRP: parseFloat(product.MRP || 0)
        };
        $('#availablePrices').val(JSON.stringify(prices));
        
        // Set rate based on selected price type
        const selectedPriceType = $('#selectedPriceType').val();
        let selectedRate = prices[selectedPriceType] || prices.SalesPrice || parseFloat(product.Rate);
        setRateValue(selectedRate.toFixed(2));
        
        // Store purchase price, HSN and tax rate for later use
        $('#productCode').data('purchasePrice', parseFloat(product.PurchasePrice || 0));
        $('#productCode').data('hsn', product.HSNCode || '-');
        $('#productCode').data('taxRate', parseFloat(product.TaxRate || 0));
        
        // Hide suggestions immediately
        $('#productSuggestions').hide().empty();
        suggestionIndex = -1;
        suggestions = [];
        
        // Focus to rate
        $('#rate').focus().select();
    }

    // Search Product by Code
    async function searchProductByCode(code, autoAddToCart = false) {
        // Hide suggestions immediately
        $('#productSuggestions').hide().empty();
        suggestionIndex = -1;
        suggestions = [];
        
        // Parse barcode format: PRODUCT_CODE$WEIGHT_IN_GRAMS
        // Convert weight from grams to kg and set as quantity
        let productCode = code;
        let weightInKg = null;
        
        if (code.includes('$')) {
            const parts = code.split('$');
            if (parts.length === 2) {
                productCode = parts[0].trim();
                const weightInGrams = parseFloat(parts[1].trim());
                if (!isNaN(weightInGrams) && weightInGrams > 0) {
                    // Convert grams to kg (divide by 1000)
                    weightInKg = weightInGrams / 1000;
                }
            }
        }
        
        try {
            const response = await $.ajax({
                url: 'api/get-product.php',
                method: 'POST',
                data: { code: productCode },
                dataType: 'json'
            });

            if (response.success) {
                // Check if multiple products found
                if (response.multiple && response.products && response.products.length > 1) {
                    // Show product selection modal
                    showProductSelectionModal(response.products, autoAddToCart, weightInKg);
                } else {
                    // Single product - proceed as normal
                    $('#productId').val(response.product.ID);
                    $('#productCode').val(response.product.ProductCode);
                    $('#productName').text(response.product.ProductName);
                    
                    // Store all price types
                    const prices = {
                        SalesPrice: parseFloat(response.product.SalesPrice || response.product.Rate || 0),
                        ShopRate: parseFloat(response.product.ShopRate || 0),
                        WholesaleRate: parseFloat(response.product.WholesaleRate || 0),
                        MRP: parseFloat(response.product.MRP || 0)
                    };
                    $('#availablePrices').val(JSON.stringify(prices));
                    
                    // Set rate based on selected price type
                    const selectedPriceType = $('#selectedPriceType').val();
                    let selectedRate = prices[selectedPriceType] || prices.SalesPrice || parseFloat(response.product.Rate);
                    setRateValue(selectedRate.toFixed(2));
                    
                    // Store purchase price for later use
                    $('#productCode').data('purchasePrice', parseFloat(response.product.PurchasePrice || 0));
                    
                    // Store HSN and tax rate for GST calculation
                    $('#productCode').data('hsn', response.product.HSNCode || '-');
                    $('#productCode').data('taxRate', parseFloat(response.product.TaxRate || 0));
                    
                    // If autoAddToCart is true (from barcode scanner), auto-fill quantity and add
                    if (autoAddToCart) {
                        // Set quantity from barcode weight or default to 1
                        const quantity = weightInKg || 1;
                        setQuantityValue(quantity.toFixed(2));
                        
                        // Calculate item total
                        calculateCurrentItemTotal();
                        
                        // Automatically add to cart after a short delay to show what was scanned
                        setTimeout(async () => {
                            await addToCart();
                            // Keep focus on product code for next scan
                            setTimeout(function() {
                                $('#productCode').focus().select();
                            }, 50);
                        }, 100);
                    } else {
                        // Barcode scan mode disabled - set quantity to 1 and move to quantity field for manual entry
                        setQuantityValue('1');
                        calculateCurrentItemTotal();
                        $('#quantity').focus().select();
                    }
                }
            } else {
                await MsgBox.alert(t('productNotFound'));
                $('#productCode').focus().select();
            }
        } catch (error) {
            console.error("Error searching for product:", error);
            await MsgBox.alert(t('errorCommunicatingWithServer'));
        }
    }

    // Show Product Selection Modal
    function showProductSelectionModal(products, autoAddToCart, weightInKg = null) {
        const tbody = $('#productSelectionList');
        tbody.empty();
        
        products.forEach(function(product) {
            const row = `
                <tr>
                    <td><strong>${product.ProductCode}</strong></td>
                    <td>${product.ProductName}</td>
                    <td>${product.BrandName || '-'}</td>
                    <td>${product.CategoryName || '-'}</td>
                    <td class="text-right"><strong>₹${parseFloat(product.Rate).toFixed(2)}</strong></td>
                    <td class="text-center">
                        <span class="badge ${product.CurrentStock > product.AlertQuantity ? 'badge-success' : 'badge-warning'}">
                            ${product.CurrentStock}
                        </span>
                    </td>
                    <td class="text-center">
                        <button class="btn btn-sm btn-primary select-product-btn" 
                                data-product-id="${product.ID}"
                                data-product-code="${product.ProductCode}"
                                data-product-name="${product.ProductName}"
                                data-product-rate="${product.Rate}"
                                data-sales-price="${product.SalesPrice || product.Rate}"
                                data-shop-rate="${product.ShopRate || 0}"
                                data-wholesale-rate="${product.WholesaleRate || 0}"
                                data-mrp="${product.MRP || 0}"
                                data-purchase-price="${product.PurchasePrice || 0}"
                                data-hsn="${product.HSNCode || '-'}"
                                data-tax-rate="${product.TaxRate || 0}"
                                data-auto-add="${autoAddToCart}"
                                data-weight-kg="${weightInKg || ''}">
                            <i class="fas fa-check"></i> Select
                        </button>
                    </td>
                </tr>
            `;
            tbody.append(row);
        });
        
        // Bind click handler for select buttons
        $('.select-product-btn').off('click').on('click', function() {
            const productId = $(this).data('product-id');
            const productCode = $(this).data('product-code');
            const productName = $(this).data('product-name');
            const productRate = $(this).data('product-rate');
            const salesPrice = $(this).data('sales-price');
            const shopRate = $(this).data('shop-rate');
            const wholesaleRate = $(this).data('wholesale-rate');
            const mrp = $(this).data('mrp');
            const purchasePrice = $(this).data('purchase-price') || 0;
            const hsnCode = $(this).data('hsn') || '-';
            const taxRate = $(this).data('tax-rate') || 0;
            const shouldAutoAdd = $(this).data('auto-add');
            const barcodeWeightInKg = $(this).data('weight-kg');
            
            // Fill the form with selected product
            $('#productId').val(productId);
            $('#productCode').val(productCode);
            $('#productName').text(productName);
            
            // Store all price types
            const prices = {
                SalesPrice: parseFloat(salesPrice),
                ShopRate: parseFloat(shopRate),
                WholesaleRate: parseFloat(wholesaleRate),
                MRP: parseFloat(mrp)
            };
            $('#availablePrices').val(JSON.stringify(prices));
            
            // Set rate based on selected price type
            const selectedPriceType = $('#selectedPriceType').val();
            let selectedRate = prices[selectedPriceType] || prices.SalesPrice || parseFloat(productRate);
            setRateValue(selectedRate.toFixed(2));
            
            // Store purchase price, HSN and tax rate for later use
            $('#productCode').data('purchasePrice', parseFloat(purchasePrice));
            $('#productCode').data('hsn', hsnCode);
            $('#productCode').data('taxRate', parseFloat(taxRate));
            
            // Close modal
            $('#productSelectionModal').modal('hide');
            
            // If autoAddToCart, add to cart automatically
            if (shouldAutoAdd) {
                // Set quantity from barcode weight or default to 1
                const quantity = barcodeWeightInKg || 1;
                setQuantityValue(quantity.toFixed(2));
                calculateCurrentItemTotal();
                setTimeout(function() {
                    addToCart();
                }, 100);
            } else {
                // Normal flow - focus to rate
                $('#rate').focus().select();
            }
        });
        
        // Show modal
        $('#productSelectionModal').modal('show');
    }

    // Update Price by Selected Type
    function updatePriceBySelectedType() {
        const availablePrices = $('#availablePrices').val();
        if (!availablePrices) return;
        
        try {
            const prices = JSON.parse(availablePrices);
            const selectedPriceType = $('#selectedPriceType').val();
            let selectedRate = prices[selectedPriceType];
            
            // Fallback to SalesPrice if selected type is not available or is 0
            if (!selectedRate || selectedRate === 0) {
                selectedRate = prices.SalesPrice || prices.MRP || 0;
            }
            
            if (selectedRate > 0) {
                setRateValue(selectedRate.toFixed(2));
                calculateCurrentItemTotal();
            }
        } catch (e) {
            console.error('Error parsing available prices:', e);
        }
    }

    // Calculate Current Item Total
    function calculateCurrentItemTotal() {
        const rate = parseFloat(getRateValue()) || 0;
        const qty = parseFloat(getQuantityValue()) || 0;
        const total = rate * qty;
        $('#currentItemTotal').text('₹' + total.toFixed(2));
    }

    // Add to Cart
    async function addToCart(product) {
        // If product object is passed directly (from scanner), use it
        if (product && typeof product === 'object' && product.id) {
            addProductToCart(product);
            return;
        }

        // Original manual entry logic
        const productId = $('#productId').val();
        const productCode = $('#productCode').val().trim();
        const productName = $('#productName').text().trim();
        const rate = parseFloat(getRateValue()) || 0;
        const purchaseRate = parseFloat($('#productCode').data('purchasePrice')) || 0;
        let quantity = parseFloat(getQuantityValue()) || 0;

        // If quantity is 0 or empty, set to 1
        if (quantity <= 0) {
            quantity = 1;
            setQuantityValue('1');
            calculateCurrentItemTotal();
        }

        // Validation
        if (!productCode) {
            await MsgBox.alert(t('enterProductCode'));
            $('#productCode').focus();
            return;
        }
        if (rate <= 0) {
            await MsgBox.alert(t('enterValidPrice'));
            $('#rate').focus();
            return;
        }

        const amount = rate * quantity;

        // Check if same product with same rate exists in cart
        const existingIndex = cart.findIndex(item => 
            item.productCode === productCode && item.rate === rate
        );
        
        if (existingIndex !== -1) {
            // Update existing item with same rate
            cart[existingIndex].quantity += quantity;
            cart[existingIndex].amount = cart[existingIndex].rate * cart[existingIndex].quantity;
            
            // Show visual feedback for updated quantity
            showNotification(productName + ' - ' + t('quantityUpdated') + cart[existingIndex].quantity.toFixed(2), 'success');
        } else {
            // Add new item (even if same product code but different rate) with discount fields
            // Get HSN and tax info from the product data stored earlier
            const hsnCode = $('#productCode').data('hsn') || '-';
            const taxRate = parseFloat($('#productCode').data('taxRate')) || 0;
            
            console.log('=== Adding item to cart ===');
            console.log('Product:', productName);
            console.log('HSN Code:', hsnCode);
            console.log('Tax Rate:', taxRate);
            
            cart.push({
                productId: productId,
                productCode: productCode,
                productName: productName,
                rate: rate,
                purchaseRate: purchaseRate,
                quantity: quantity,
                discount: 0,
                discountType: 'PERCENTAGE',
                billDiscountPortion: 0, // Portion of bill discount allocated to this item
                amount: amount,
                hsnCode: hsnCode,
                taxRate: taxRate
            });
            
            // Show visual feedback for new item
            showNotification(productName + ' - ' + t('addedToCart'), 'success');
        }

        // Clear form
        clearEntryForm();
        
        // Update display
        updateDisplay();
        
        // Focus back to product code
        $('#productCode').focus();
    }

    /**
     * Add product to cart (optimized for scanner)
     */
    function addProductToCart(product) {
        const productCode = product.code || product.barcode;
        const productName = product.name;
        const rate = parseFloat(product.price) || 0;
        const quantity = 1; // Default quantity for scanned items
        const amount = rate * quantity;

        // Check if same product exists in cart
        const existingIndex = cart.findIndex(item => 
            item.productCode === productCode && item.rate === rate
        );
        
        if (existingIndex !== -1) {
            // Update existing item quantity
            queueBatchUpdate(() => {
                cart[existingIndex].quantity += quantity;
                cart[existingIndex].amount = cart[existingIndex].rate * cart[existingIndex].quantity;
            });
            
            // Show visual feedback for updated quantity
            showNotification(productName + ' - ' + t('quantityUpdated') + cart[existingIndex].quantity.toFixed(2), 'success');
        } else {
            // Add new item
            queueBatchUpdate(() => {
                cart.push({
                    productId: product.id,
                    productCode: productCode,
                    productName: productName,
                    rate: rate,
                    purchaseRate: parseFloat(product.purchase_price) || 0,
                    quantity: quantity,
                    discount: 0,
                    discountType: 'PERCENTAGE',
                    billDiscountPortion: 0,
                    amount: amount,
                    hsnCode: product.hsn || '-',
                    taxRate: parseFloat(product.tax) || 0
                });
            });
            
            // Show visual feedback for new item
            showNotification(productName + ' - ' + t('addedToCart'), 'success');
        }

        // Clear barcode input for next scan
        $('#productCode').val('').focus();
    }

    // Clear Entry Form
    function clearEntryForm() {
        $('#productId').val('');
        $('#productCode').val('');
        $('#productName').text('-');
        setRateValue('');
        setQuantityValue('');
        $('#currentItemTotal').text('₹0.00');
        $('#productSuggestions').hide().empty();
    }

    // Update Display
    function updateDisplay() {
        updateCartTable();
        updateTotals();
        
        // Also trigger bill discount calculation to sync product discounts
        if (window.SalesEnhancements && window.SalesEnhancements.BillDiscountManager) {
            window.SalesEnhancements.BillDiscountManager.calculateBillDiscount();
        }
    }

    // Update Cart Table
    function updateCartTable() {
        const tbody = $('#cartItems');
        tbody.empty();

        if (cart.length === 0) {
            tbody.append(
                '<tr class="empty-cart">' +
                '<td colspan="8" class="text-center text-muted py-4">' +
                '<i class="fas fa-shopping-cart fa-3x mb-2"></i>' +
                '<p data-translate="emptyCart">' + t('emptyCart') + '</p>' +
                '</td>' +
                '</tr>'
            );
            $('#saveSale').prop('disabled', true);
        } else {
            // Get current GST type
            const gstType = window.GSTTypeManager ? window.GSTTypeManager.getGSTType() : 'inclusive';
            
            cart.forEach(function(item, index) {
                const itemBaseAmount = item.rate * item.quantity;
                
                // Calculate product-level discount amount
                let productDiscountAmount = 0;
                if (item.discount && item.discount > 0) {
                    if (item.discountType === 'PERCENTAGE') {
                        productDiscountAmount = (itemBaseAmount * item.discount) / 100;
                    } else {
                        productDiscountAmount = item.discount;
                    }
                }
                
                // Get bill-level discount portion for this item
                const billDiscountPortion = item.billDiscountPortion || 0;
                
                // Total discount for this item
                const totalItemDiscount = productDiscountAmount + billDiscountPortion;
                
                // Calculate amount after discounts (before tax consideration)
                let amountAfterDiscount = itemBaseAmount - totalItemDiscount;
                
                // Calculate tax if exclusive mode
                let itemTaxAmount = 0;
                const taxRate = item.taxRate || item.taxPercent || 0;
                if (gstType === 'exclusive' && taxRate > 0) {
                    itemTaxAmount = (amountAfterDiscount * taxRate) / 100;
                }
                
                // Calculate final amount (with tax if exclusive)
                const finalAmount = amountAfterDiscount + itemTaxAmount;
                
                // Update item amount with total discount applied
                item.amount = finalAmount;
                
                // Display discount text - show both if applicable
                let discountDisplay = '-';
                if (totalItemDiscount > 0) {
                    let discountParts = [];
                    
                    // Product discount
                    if (productDiscountAmount > 0) {
                        if (item.discountType === 'PERCENTAGE') {
                            discountParts.push('<span class="text-primary" title="Product Discount">' + item.discount.toFixed(2) + '%</span>');
                        } else {
                            discountParts.push('<span class="text-primary" title="Product Discount">₹' + item.discount.toFixed(2) + '</span>');
                        }
                    }
                    
                    // Bill discount portion
                    if (billDiscountPortion > 0) {
                        discountParts.push('<span class="text-info" title="Bill Discount Portion">₹' + billDiscountPortion.toFixed(2) + '</span>');
                    }
                    
                    discountDisplay = discountParts.join(' + ') + '<br><small class="text-danger font-weight-bold">(-₹' + totalItemDiscount.toFixed(2) + ')</small>';
                }
                
                // Show tax info in total column if exclusive mode
                let totalDisplay = '₹' + finalAmount.toFixed(2);
                if (gstType === 'exclusive' && itemTaxAmount > 0) {
                    totalDisplay = '<small class="d-block">₹' + amountAfterDiscount.toFixed(2) + '</small>' +
                                   '<small class="text-success d-block">+Tax: ₹' + itemTaxAmount.toFixed(2) + ' (' + taxRate + '%)</small>' +
                                   '<strong>₹' + finalAmount.toFixed(2) + '</strong>';
                }
                
                // Calculate Basic Rate based on GST type and apply discount
                let basicRate = item.rate;
                let basicRateAfterDiscount = basicRate;
                
                // Use stored basicRate if available (set by GSTTypeManager), otherwise calculate
                if (item.basicRate) {
                    basicRate = item.basicRate;
                } else {
                    // Calculate basic rate
                    if (gstType === 'inclusive' && taxRate > 0) {
                        // INCLUSIVE: Extract basic rate from inclusive price
                        basicRate = item.rate / (1 + (taxRate / 100));
                        item.basicRate = basicRate; // Store it
                    } else if (gstType === 'exclusive') {
                        // EXCLUSIVE: Rate in cart is already inclusive, extract basic
                        basicRate = item.rate / (1 + (taxRate / 100));
                        item.basicRate = basicRate; // Store it
                    } else {
                        basicRate = item.rate;
                        item.basicRate = basicRate;
                    }
                }
                
                basicRateAfterDiscount = basicRate;
                
                // Apply discount to basic rate
                if (totalItemDiscount > 0) {
                    // Calculate discount per unit
                    const discountPerUnit = totalItemDiscount / item.quantity;
                    
                    if (gstType === 'inclusive' && taxRate > 0) {
                        // For inclusive, extract discount's basic portion
                        const discountBasicPortion = discountPerUnit / (1 + (taxRate / 100));
                        basicRateAfterDiscount = basicRate - discountBasicPortion;
                    } else {
                        // For exclusive, full discount applies to basic rate
                        basicRateAfterDiscount = basicRate - discountPerUnit;
                    }
                }
                
                // Display basic rate with strikethrough if discounted
                let basicRateDisplay = '';
                if (totalItemDiscount > 0) {
                    basicRateDisplay = '<small class="text-muted"><del>₹' + basicRate.toFixed(2) + '</del></small><br>' +
                                      '<small class="text-success font-weight-bold">₹' + basicRateAfterDiscount.toFixed(2) + '</small>';
                } else {
                    basicRateDisplay = '<small class="text-muted">₹' + basicRate.toFixed(2) + '</small>';
                }
                
                const row = '<tr>' +
                    '<td>' + (index + 1) + '</td>' +
                    '<td class="cart-item-code">' + item.productCode + '</td>' +
                    '<td class="cart-item-name">' + 
                    item.productName + 
                    ' <button class="btn btn-sm btn-link p-0 ml-1 btn-edit-discount" data-index="' + index + '" title="Edit Discount">' +
                    '<i class="fas fa-edit text-info"></i>' +
                    '</button>' +
                    '</td>' +
                    '<td class="text-right">' + basicRateDisplay + '</td>' +
                    '<td class="text-right">' +
                    '<div class="input-group input-group-sm">' +
                    '<div class="input-group-prepend"><span class="input-group-text">₹</span></div>' +
                    '<input type="number" class="form-control form-control-sm text-right cart-rate-input" ' +
                    'data-index="' + index + '" value="' + item.rate.toFixed(2) + '" step="0.01" min="0">' +
                    '</div>' +
                    '</td>' +
                    '<td class="text-right">' +
                    '<input type="number" class="form-control form-control-sm text-right cart-qty-input" ' +
                    'data-index="' + index + '" value="' + item.quantity.toFixed(2) + '" step="0.01" min="0.01">' +
                    '</td>' +
                    '<td class="text-right text-danger small">' + discountDisplay + '</td>' +
                    '<td class="text-right font-weight-bold">' + totalDisplay + '</td>' +
                    '<td class="text-center">' +
                    '<button class="btn btn-danger btn-sm btn-delete-item" data-index="' + index + '">' +
                    '<i class="fas fa-trash"></i>' +
                    '</button>' +
                    '</td>' +
                    '</tr>';
                tbody.append(row);
            });
            $('#saveSale').prop('disabled', false);

            // Edit discount button handler
            $('.btn-edit-discount').click(function() {
                const index = $(this).data('index');
                openProductDiscountModal(index);
            });

            // Delete button handler
            $('.btn-delete-item').click(function() {
                const index = $(this).data('index');
                cart.splice(index, 1);
                updateDisplay();
            });

            // Row selection handler
            tbody.on('click', 'tr', function(e) {
                // Don't select row if clicking on input, button, or interactive elements
                if ($(e.target).is('input, button, .btn-delete-item, .btn-edit-discount') || $(e.target).closest('input, button').length) {
                    return;
                }
                
                // Remove previous selection
                $('#cartTable tbody tr').removeClass('selected');
                
                // Add selection to clicked row
                $(this).addClass('selected');
            });

            // Rate input change handler - only on blur/change, not on every keystroke
            tbody.on('change blur', '.cart-rate-input', function() {
                // Skip if we're in the middle of navigation
                if (isNavigating) return;
                
                const index = $(this).data('index');
                const newRate = parseFloat($(this).val()) || 0;
                if (newRate >= 0) {
                    cart[index].rate = newRate;
                    cart[index].amount = cart[index].rate * cart[index].quantity;
                    updateDisplay();
                }
            });
            
            // Rate input focus handler - prevent row selection
            tbody.on('focus', '.cart-rate-input', function(e) {
                e.stopPropagation();
            });
            
            // Rate input click handler - prevent row selection
            tbody.on('click', '.cart-rate-input', function(e) {
                e.stopPropagation();
            });
            
            // Rate input keyboard navigation
            tbody.on('keydown', '.cart-rate-input', function(e) {
                const index = $(this).data('index');
                const $currentRow = $(this).closest('tr');
                
                if (e.key === 'ArrowRight') {
                    e.preventDefault();
                    isNavigating = true;
                    // Move to quantity input in same row
                    $currentRow.find('.cart-qty-input').focus().select();
                    setTimeout(() => { isNavigating = false; }, 100);
                } else if (e.key === 'ArrowDown') {
                    e.preventDefault();
                    isNavigating = true;
                    // Move to rate input in next row
                    const $nextRow = $currentRow.next('tr');
                    if ($nextRow.length) {
                        $nextRow.find('.cart-rate-input').focus().select();
                    }
                    setTimeout(() => { isNavigating = false; }, 100);
                } else if (e.key === 'ArrowUp') {
                    e.preventDefault();
                    isNavigating = true;
                    // Move to rate input in previous row
                    const $prevRow = $currentRow.prev('tr');
                    if ($prevRow.length) {
                        $prevRow.find('.cart-rate-input').focus().select();
                    } else {
                        // If first row, go back to product code
                        $('#productCode').focus().select();
                    }
                    setTimeout(() => { isNavigating = false; }, 100);
                } else if (e.key === 'Enter') {
                    e.preventDefault();
                    // Apply changes and move to quantity
                    $(this).blur();
                    $currentRow.find('.cart-qty-input').focus().select();
                }
            });

            // Quantity input change handler - only on blur/change, not on every keystroke
            tbody.on('change blur', '.cart-qty-input', function() {
                // Skip if we're in the middle of navigation
                if (isNavigating) return;
                
                const index = $(this).data('index');
                const newQty = parseFloat($(this).val()) || 0;
                if (newQty > 0) {
                    cart[index].quantity = newQty;
                    cart[index].amount = cart[index].rate * cart[index].quantity;
                    updateDisplay();
                }
            });
            
            // Quantity input focus handler - prevent row selection
            tbody.on('focus', '.cart-qty-input', function(e) {
                e.stopPropagation();
            });
            
            // Quantity input click handler - prevent row selection
            tbody.on('click', '.cart-qty-input', function(e) {
                e.stopPropagation();
            });
            
            // Quantity input keyboard navigation
            tbody.on('keydown', '.cart-qty-input', function(e) {
                const index = $(this).data('index');
                const $currentRow = $(this).closest('tr');
                
                if (e.key === 'ArrowLeft') {
                    e.preventDefault();
                    isNavigating = true;
                    // Move to rate input in same row
                    $currentRow.find('.cart-rate-input').focus().select();
                    setTimeout(() => { isNavigating = false; }, 100);
                } else if (e.key === 'ArrowDown') {
                    e.preventDefault();
                    isNavigating = true;
                    // Move to quantity input in next row
                    const $nextRow = $currentRow.next('tr');
                    if ($nextRow.length) {
                        $nextRow.find('.cart-qty-input').focus().select();
                    } else {
                        // If last row, stay focused
                        $(this).select();
                    }
                    setTimeout(() => { isNavigating = false; }, 100);
                } else if (e.key === 'ArrowUp') {
                    e.preventDefault();
                    isNavigating = true;
                    // Move to quantity input in previous row
                    const $prevRow = $currentRow.prev('tr');
                    if ($prevRow.length) {
                        $prevRow.find('.cart-qty-input').focus().select();
                    } else {
                        // If first row, go back to product code
                        $('#productCode').focus().select();
                    }
                    setTimeout(() => { isNavigating = false; }, 100);
                } else if (e.key === 'Enter') {
                    e.preventDefault();
                    // Apply changes and move to next row qty, or stay on current if last row
                    $(this).blur();
                    $(this).trigger('change'); // Ensure value is saved
                    const $nextRow = $currentRow.next('tr');
                    if ($nextRow.length) {
                        // Move to next row's quantity
                        setTimeout(() => {
                            $nextRow.find('.cart-qty-input').focus().select();
                        }, 150);
                    } else {
                        // Last row, go back to product code for new entry
                        setTimeout(() => {
                            $('#productCode').focus().select();
                        }, 150);
                    }
                }
            });
        }
    }
    
    // Expose updateCartTable globally for use by BillDiscountManager
    window.updateCartTable = updateCartTable;

    // Update Totals
    function updateTotals() {
        // Calculate base subtotal (sum of rate × quantity, before any discounts)
        let baseSubTotal = 0;
        cart.forEach(function(item) {
            baseSubTotal += item.rate * item.quantity;
        });

        // Calculate total discount amount (product + bill discounts)
        let totalProductDiscounts = 0;
        cart.forEach(function(item) {
            if (item.discount && item.discount > 0) {
                const itemBaseAmount = item.rate * item.quantity;
                if (item.discountType === 'PERCENTAGE') {
                    totalProductDiscounts += (itemBaseAmount * item.discount) / 100;
                } else {
                    totalProductDiscounts += item.discount;
                }
            }
        });

        // Get bill discount portion (already distributed to items)
        let totalBillDiscount = 0;
        cart.forEach(function(item) {
            totalBillDiscount += (item.billDiscountPortion || 0);
        });

        // Total discount = product discounts + bill discount
        const totalDiscount = totalProductDiscounts + totalBillDiscount;

        // Subtotal after all discounts (before tax consideration)
        let subTotalBeforeTax = baseSubTotal - totalDiscount;

        // ===== GST CALCULATION BASED ON TYPE =====
        let totalTaxAmount = 0;
        let actualSubTotal = 0; // This will be the sum of all item final amounts
        const gstType = window.GSTTypeManager ? window.GSTTypeManager.getGSTType() : 'inclusive';
        
        if (gstType === 'exclusive') {
            // EXCLUSIVE: Add tax on top of subtotal
            cart.forEach(function(item) {
                const itemBaseAmount = item.rate * item.quantity;
                let productDiscount = 0;
                if (item.discount && item.discount > 0) {
                    if (item.discountType === 'PERCENTAGE') {
                        productDiscount = (itemBaseAmount * item.discount) / 100;
                    } else {
                        productDiscount = item.discount;
                    }
                }
                const billDiscount = item.billDiscountPortion || 0;
                const itemAfterDiscount = itemBaseAmount - productDiscount - billDiscount;
                
                const taxRate = item.taxRate || item.taxPercent || 0;
                const itemTax = (itemAfterDiscount * taxRate) / 100;
                totalTaxAmount += itemTax;
                
                // For exclusive, final amount = amount after discount + tax
                actualSubTotal += itemAfterDiscount + itemTax;
            });
        } else {
            // INCLUSIVE: Tax is already in the price
            // SubTotal = sum of (rate × quantity - discount) for each item
            // Tax is calculated from within the price, not added
            cart.forEach(function(item) {
                const itemBaseAmount = item.rate * item.quantity;
                let productDiscount = 0;
                if (item.discount && item.discount > 0) {
                    if (item.discountType === 'PERCENTAGE') {
                        productDiscount = (itemBaseAmount * item.discount) / 100;
                    } else {
                        productDiscount = item.discount;
                    }
                }
                const billDiscount = item.billDiscountPortion || 0;
                const itemFinalAmount = itemBaseAmount - productDiscount - billDiscount;
                
                // For inclusive mode, calculate tax from within the price
                const taxRate = item.taxRate || item.taxPercent || 0;
                if (taxRate > 0) {
                    const taxMultiplier = (100 + taxRate) / 100;
                    const taxableAmount = itemFinalAmount / taxMultiplier;
                    const itemTax = itemFinalAmount - taxableAmount;
                    totalTaxAmount += itemTax;
                }
                
                actualSubTotal += itemFinalAmount;
            });
        }
        // =========================================

        const cooliAmount = parseFloat($('#cooliAmount').val()) || 0;
        let grandTotal = actualSubTotal + cooliAmount;
        
        // Calculate round off (to nearest rupee)
        const roundedTotal = Math.round(grandTotal);
        const roundOffAmount = roundedTotal - grandTotal;
        
        // Apply round off to grand total
        grandTotal = roundedTotal;

        // Display actual subtotal (sum of all item final amounts including tax)
        $('#subTotal').text('₹' + actualSubTotal.toFixed(2));
        
        // Update bill discount display (if using BillDiscountManager)
        if (window.SalesEnhancements && window.SalesEnhancements.BillDiscountManager) {
            // The discount value is already calculated by BillDiscountManager
            // Just ensure it's showing the combined total
            $('#billDiscountValue').text('-₹' + totalDiscount.toFixed(2));
        }
        
        // Show tax amount if exclusive mode and tax > 0
        if (gstType === 'exclusive' && totalTaxAmount > 0) {
            // Update or create tax display row
            if ($('#taxAmountRow').length === 0) {
                const taxRow = '<tr id="taxAmountRow" class="bg-light-green">' +
                    '<td class="text-left text-success" data-translate="taxAmount">Tax Amount:</td>' +
                    '<td class="text-right font-weight-bold text-success" id="taxAmountDisplay">₹0.00</td>' +
                    '</tr>';
                $('#cooliDisplay').closest('tr').after(taxRow);
            }
            $('#taxAmountDisplay').text('₹' + totalTaxAmount.toFixed(2));
            $('#taxAmountRow').show();
        } else {
            $('#taxAmountRow').hide();
        }
        
        $('#cooliDisplay').text('₹' + cooliAmount.toFixed(2));
        $('#roundOffDisplay').text((roundOffAmount >= 0 ? '+' : '') + '₹' + roundOffAmount.toFixed(2));
        $('#grandTotal').text('₹' + grandTotal.toFixed(2));
        
        // Auto-update payment amounts when cart changes
        if (cart.length > 0) {
            const currentCash = parseFloat($('#cashAmount').val()) || 0;
            const currentUPI = parseFloat($('#upiAmount').val()) || 0;
            const currentCredit = parseFloat($('#creditAmount').val()) || 0;
            const currentTotal = currentCash + currentUPI + currentCredit;
            
            // If payments are empty, set cash to full amount by default
            if (currentTotal === 0) {
                // No payment entered yet - set cash to full amount
                $('#cashAmount').val(grandTotal.toFixed(2));
                $('#upiAmount').val('0.00');
                $('#creditAmount').val('0.00');
                updateTotalPayment();
            }
            // If user has already entered amounts, don't auto-update - let them manually adjust
        }
        
        // Update outstanding
        updateOutstanding();
        
        // Trigger bill discount recalculation to sync with new totals
        // This ensures bill discount is applied with correct GST type
        if (window.SalesEnhancements && window.SalesEnhancements.BillDiscountManager) {
            const currentDiscount = parseFloat($('#billDiscount').val()) || 0;
            if (currentDiscount > 0) {
                window.SalesEnhancements.BillDiscountManager.calculateBillDiscount();
            }
        }
    }
    
    // Update Outstanding Amount - DEPRECATED
    // Outstanding calculation moved to Payment Registration module
    function updateOutstanding() {
        // No longer used - payment registration handled separately
        return;
    }
    
    // Update Remaining Balance - DEPRECATED
    // Payment tracking moved to Payment Registration module
    function updateRemainingBalance() {
        // No longer used - payment registration handled separately
        return;
    }

    // Clear Cart
    function clearCart() {
        cart = [];
        clearEntryForm();
        updateDisplay();
        $('#cooliAmount').val('0');
        $('#cashAmount').val('0.00');
        $('#upiAmount').val('0.00');
        // Payment amount field removed
        $('#notes').val('');
        
        // Reset shipping data if function exists
        if (typeof resetShippingData === 'function') {
            resetShippingData();
        }
    }

    // Save Sale
    async function saveSale() {
        const supplierId = $('#supplierSelect').val();
        if (!supplierId) {
            await MsgBox.alert(t('selectSupplier'));
            $('#supplierSelect').focus();
            return;
        }

        if (cart.length === 0) {
            await MsgBox.alert(t('noItemsInCart'));
            return;
        }

        // Get payment amounts
        const cashAmount = parseFloat($('#cashAmount').val()) || 0;
        const upiAmount = parseFloat($('#upiAmount').val()) || 0;
        const creditAmount = parseFloat($('#creditAmount').val()) || 0;
        const totalPaid = cashAmount + upiAmount;
        const totalPayment = cashAmount + upiAmount + creditAmount;
        
        // Get the final amount (grand total after all calculations)
        const grandTotal = parseFloat($('#grandTotal').text().replace('₹', '')) || 0;
        
        // Determine payment status
        let paymentStatus = 'Paid';
        if (creditAmount > 0) {
            if (totalPaid === 0) {
                paymentStatus = 'Unpaid'; // Full credit
            } else if (totalPaid < grandTotal) {
                paymentStatus = 'Partial'; // Partial payment
            } else {
                paymentStatus = 'Paid'; // Fully paid
            }
        }
        
        // Create payment mode summary
        let paymentModeSummary = '';
        let paymentParts = [];
        
        if (cashAmount > 0) {
            paymentParts.push(`Cash:₹${cashAmount.toFixed(2)}`);
        }
        if (upiAmount > 0) {
            paymentParts.push(`UPI:₹${upiAmount.toFixed(2)}`);
        }
        if (creditAmount > 0) {
            paymentParts.push(`Credit:₹${creditAmount.toFixed(2)}`);
        }
        
        if (paymentParts.length === 0) {
            paymentModeSummary = 'Cash';
        } else if (paymentParts.length === 1) {
            // Single payment mode - extract just the name
            paymentModeSummary = paymentParts[0].split(':')[0];
        } else {
            // Multiple payment modes
            paymentModeSummary = paymentParts.join(' + ');
        }
        
        const saleData = {
            invoiceNumber: $('#invoiceNumber').val(),
            supplierId: supplierId,
            purchaseDate: new Date().toISOString().split('T')[0],
            purchaseType: $('#purchaseType').val() || $('#currentPurchaseType').val() || 'GST',
            purchaseInvoiceNumber: $('#purchaseInvoiceNumber').val() || '',
            purchaseInvoiceDate: $('#purchaseInvoiceDate').val() || '',
            items: cart,
            subTotal: parseFloat($('#subTotal').text().replace('₹', '')) || 0,
            cooliAmount: parseFloat($('#cooliAmount').val()) || 0,
            transportName: $('#transportNameValue').val() || '',
            vehicleNumber: $('#vehicleNumberValue').val() || '',
            transportGSTPercent: parseFloat($('#transportGSTPercent').val()) || 0,
            transportGSTType: $('#transportGSTTypeValue').val() || 'inclusive',
            transportGSTAmount: parseFloat($('#transportGSTAmount').val()) || 0,
            roundOffAmount: parseFloat($('#roundOffDisplay').text().replace('₹', '').replace('+', '')) || 0,
            totalAmount: grandTotal,
            finalAmount: grandTotal,
            paymentMode: paymentModeSummary,
            paymentAmount: totalPaid,
            paymentStatus: paymentStatus,
            cashAmount: cashAmount,
            upiAmount: upiAmount,
            creditAmount: creditAmount,
            notes: $('#notes').val(),
            userId: $('#userId').val(),
            editingPurchaseId: $('#editingSaleId').val() || 0,
            redeemedPoints: parseFloat($('#redeemedPoints').val()) || 0,
            billDiscountType: $('#billDiscountType').val() || 'PERCENTAGE'
        };
        
        console.log('Sending sale data:', saleData);

        // Show loading
        showLoading();

        $.ajax({
            url: 'api/save-purchase.php',
            method: 'POST',
            data: JSON.stringify(saleData),
            contentType: 'application/json',
            dataType: 'json',
            success: function(response) {
                hideLoading();
                console.log('Server response:', response);
                if (response.success) {
                    const isEditMode = $('#isEditMode').val() === '1';
                    const invoiceNumber = response.invoiceNumber || saleData.invoiceNumber;
                    const saleId = response.saleId || $('#editingSaleId').val();
                    
                    // Save GST details
                    if (saleId && invoiceNumber) {
                        const supplierGST = $('#supplierSelect option:selected').data('gst') || '';
                        saveGSTDetails(saleId, invoiceNumber, cart, supplierGST);
                    }
                    
                    let message = isEditMode ? 
                        t('saleUpdated') + invoiceNumber :
                        t('saleSaved') + invoiceNumber;
                    
                    // Add loyalty points info if available
                    if (response.loyaltyPoints && response.loyaltyPoints.earned > 0) {
                        message += '\n\n🎉 Loyalty Points Earned: ' + response.loyaltyPoints.earned;
                        message += '\n💰 New Balance: ' + response.loyaltyPoints.newBalance + ' points';
                    }
                    
                    // Add points redeemed info if available
                    if (response.pointsRedeemed && response.pointsRedeemed.points > 0) {
                        message += '\n\n⭐ Points Redeemed: ' + response.pointsRedeemed.points;
                        message += '\n💳 Remaining Balance: ' + response.pointsRedeemed.newBalance + ' points';
                    }
                    
                    alert(message);
                    
                    // Print option - add small delay to ensure DB commit is visible
                    if (confirm(t('printBill'))) {
                        setTimeout(function() {
                            window.open('print-invoice.php?invoice=' + invoiceNumber, '_blank');
                        }, 300);
                    }
                    
                    // If in edit mode, ask if user wants new bill
                    if (isEditMode) {
                        if (confirm(t('createNewBill'))) {
                            location.reload();
                        } else {
                            // Stay in edit mode with updated data
                            $('#saveSale').html('<i class="fas fa-edit"></i> <span data-translate="updateAndPrint">' + t('updateAndPrint') + '</span>');
                            showNotification(t('billUpdated'), 'success');
                        }
                    } else {
                        // New sale - reload for next sale
                        setTimeout(function() {
                            location.reload();
                        }, 1000);
                    }
                } else {
                    let errorMsg = t('error') + response.message;
                    if (response.debug) {
                        errorMsg += '\n\nDebug Info: ' + JSON.stringify(response.debug);
                    }
                    alert(errorMsg);
                    console.error('Save failed:', response);
                }
            },
            error: function(xhr, status, error) {
                hideLoading();
                console.error('AJAX Error:', {xhr: xhr, status: status, error: error});
                console.error('Response Text:', xhr.responseText);
                alert(t('serverError') + (xhr.responseText || error));
            }
        });
    }

    // Show Loading
    function showLoading() {
        $('body').append(
            '<div class="loading-overlay">' +
            '<div class="spinner"></div>' +
            '</div>'
        );
    }

    // Hide Loading
    function hideLoading() {
        $('.loading-overlay').remove();
    }
    
    // Navigate Bill (Previous/Next)
    function navigateBill(direction) {
        const currentSaleId = $('#editingSaleId').val() || 0;
        
        console.log('Navigating bill:', direction, 'Current ID:', currentSaleId);
        
        // If direction is 'current', reload the same bill
        if (direction === 'current' && currentSaleId > 0) {
            showLoading();
            $.ajax({
                url: 'api/navigate-bill.php',
                method: 'POST',
                data: {
                    direction: 'next',
                    currentSaleId: currentSaleId - 1 // This will return the current bill
                },
                dataType: 'json',
                success: function(response) {
                    hideLoading();
                    console.log('Navigate response:', response);
                    if (response.success) {
                        loadBillForEdit(response.sale, response.items);
                    }
                },
                error: function(xhr, status, error) {
                    hideLoading();
                    console.error('Navigate error:', xhr.responseText);
                }
            });
            return;
        }
        
        showLoading();
        
        $.ajax({
            url: 'api/navigate-bill.php',
            method: 'POST',
            data: {
                direction: direction,
                currentSaleId: currentSaleId
            },
            dataType: 'json',
            success: function(response) {
                hideLoading();
                console.log('Navigate response:', response);
                if (response.success) {
                    loadBillForEdit(response.sale, response.items);
                } else {
                    alert(response.message || t('billNotFound'));
                }
            },
            error: function(xhr, status, error) {
                hideLoading();
                console.error('Navigate error:', xhr.responseText);
                alert(t('error') + (xhr.responseText || error));
            }
        });
    }
    
    // Load Bill for Edit
    function loadBillForEdit(sale, items) {
        console.log('Loading bill for edit:', sale);
        
        // Set edit mode
        $('#editingSaleId').val(sale.id);
        $('#isEditMode').val('1');
        
        // Update invoice number display
        $('#currentInvoiceNumber').text(sale.invoiceNumber);
        $('#invoiceNumber').val(sale.invoiceNumber);
        
        // Set supplier - update both select and search box
        $('#supplierSelect').val(sale.supplierId);
        $('#supplierSearch').val(sale.supplierName);
        
        // Enable ledger button
        $('#btnViewLedger').prop('disabled', false);
        
        // Update supplier balance display
        if (sale.supplierBalance && sale.supplierBalance > 0) {
            $('#supplierBalance').text('₹' + parseFloat(sale.supplierBalance).toFixed(2));
            $('#supplierBalanceDisplay').slideDown();
        } else {
            $('#supplierBalanceDisplay').slideUp();
        }
        
        // Set purchase type if available
        if (sale.purchaseType) {
            $('#purchaseType').val(sale.purchaseType);
            $('#currentPurchaseType').val(sale.purchaseType);
        }
        
        // Load purchase invoice number and date
        if (sale.purchaseInvoiceNumber) {
            $('#purchaseInvoiceNumber').val(sale.purchaseInvoiceNumber);
        }
        if (sale.purchaseInvoiceDate) {
            $('#purchaseInvoiceDate').val(sale.purchaseInvoiceDate);
        }
        
        // Clear current cart
        cart = [];
        
        // Load items into cart with all discount information
        items.forEach(function(item) {
            console.log('Loading item:', item);
            cart.push({
                productId: item.productId || 0,
                productCode: item.productCode,
                productName: item.productName,
                rate: parseFloat(item.rate),
                purchaseRate: parseFloat(item.purchaseRate || 0),
                quantity: parseFloat(item.quantity),
                discount: parseFloat(item.discount || 0),
                discountType: item.discountType || 'PERCENTAGE',
                billDiscountPortion: 0, // Will be recalculated
                amount: parseFloat(item.amount),
                hsnCode: item.hsnCode || '-',
                taxRate: parseFloat(item.taxRate || 0)
            });
        });
        
        console.log('Cart loaded:', cart);
        
        // Set freight/cooli amount (check both fields for compatibility)
        const freightAmount = parseFloat(sale.freightAmount || sale.cooli || 0);
        $('#cooliAmount').val(freightAmount.toFixed(2));
        
        // Set transport details
        if (sale.transportName) {
            $('#transportNameValue').val(sale.transportName);
        }
        if (sale.vehicleNumber) {
            $('#vehicleNumberValue').val(sale.vehicleNumber);
        }
        if (sale.transportGSTPercent) {
            $('#transportGSTPercent').val(parseFloat(sale.transportGSTPercent));
        }
        if (sale.transportGSTType) {
            $('#transportGSTTypeValue').val(sale.transportGSTType);
        }
        if (sale.transportGSTAmount) {
            $('#transportGSTAmount').val(parseFloat(sale.transportGSTAmount));
        }
        
        // Set bill discount if available
        if (sale.billDiscount && sale.billDiscount > 0) {
            $('#billDiscount').val(parseFloat(sale.billDiscount));
            $('#billDiscountType').val(sale.billDiscountType || 'PERCENTAGE');
        }
        
        // Parse and set payment amounts
        const paymentMode = sale.paymentMethod || 'Cash';
        const paymentAmount = sale.paymentAmount ? parseFloat(sale.paymentAmount) : 0;
        
        let cashAmount = 0;
        let upiAmount = 0;
        let creditAmount = 0;
        
        // Check if we have the individual amounts from database
        if (sale.cashAmount !== undefined || sale.upiAmount !== undefined || sale.creditAmount !== undefined) {
            // Use the saved individual amounts
            cashAmount = sale.cashAmount ? parseFloat(sale.cashAmount) : 0;
            upiAmount = sale.upiAmount ? parseFloat(sale.upiAmount) : 0;
            creditAmount = sale.creditAmount ? parseFloat(sale.creditAmount) : 0;
        } else {
            // Fallback: Parse from paymentMode string for old records
            // Check if it's a combined payment (contains '+')
            if (paymentMode.includes('+')) {
                // Parse combined payment like "Cash:₹500.00 + UPI:₹300.00"
                const methods = paymentMode.split('+').map(m => m.trim());
                methods.forEach(function(methodStr) {
                    const parts = methodStr.split(':₹');
                    if (parts.length === 2) {
                        const method = parts[0].trim();
                        const amount = parseFloat(parts[1].replace(',', ''));
                        if (method === 'Cash') {
                            cashAmount = amount;
                        } else if (method === 'UPI') {
                            upiAmount = amount;
                        } else if (method === 'Credit') {
                            creditAmount = amount;
                        }
                    }
                });
            } else {
                // Single payment method
                if (paymentMode === 'UPI') {
                    upiAmount = paymentAmount;
                    cashAmount = 0;
                } else if (paymentMode === 'Cash') {
                    cashAmount = paymentAmount;
                    upiAmount = 0;
                } else if (paymentMode === 'Credit') {
                    creditAmount = paymentAmount;
                    cashAmount = 0;
                    upiAmount = 0;
                } else {
                    // Other payment methods, put in cash
                    cashAmount = paymentAmount;
                    upiAmount = 0;
                }
            }
        }
        
        // Set the payment amounts
        $('#cashAmount').val(cashAmount.toFixed(2));
        $('#upiAmount').val(upiAmount.toFixed(2));
        $('#creditAmount').val(creditAmount.toFixed(2));
        $('#paymentAmount').val(paymentAmount.toFixed(2));
        
        // Set notes
        $('#notes').val(sale.notes || '');
        
        // Load shipping details if function exists
        if (typeof loadShippingDetails === 'function') {
            loadShippingDetails(sale.invoiceNumber);
        }
        
        // Update display
        updateDisplay();
        
        // Change save button text
        $('#saveSale').html('<i class="fas fa-edit"></i> <span data-translate="updateAndPrint">' + t('updateAndPrint') + '</span>');
        
        // Show delete button when editing
        $('#btnDeleteBill').show();
        
        // Show notification
        showNotification(t('billLoadedForEdit') + sale.invoiceNumber, 'info');
    }
    
    // Save New Supplier
    function saveNewSupplier() {
        const supplierName = $('#newSupplierName').val().trim();
        const phone = $('#newSupplierPhone').val().trim();
        const contactPerson = $('#newContactPerson').val().trim();
        const email = $('#newSupplierEmail').val().trim();
        const address = $('#newSupplierAddress').val().trim();
        const city = $('#newSupplierCity').val().trim();
        const state = $('#newSupplierState').val().trim();
        const pinCode = $('#newSupplierPinCode').val().trim();
        const gstNumber = $('#newSupplierGST').val().trim();
        const panNumber = $('#newSupplierPAN').val().trim();
        const supplierType = $('#newSupplierType').val();
        const creditLimit = $('#newCreditLimit').val() || 0;
        const creditDays = $('#newCreditDays').val() || 0;
        
        if (!supplierName) {
            alert(t('enterSupplierName'));
            $('#newSupplierName').focus();
            return;
        }
        
        if (!phone) {
            alert(t('enterPhoneNumber'));
            $('#newSupplierPhone').focus();
            return;
        }
        
        showLoading();
        
        $.ajax({
            url: 'api/add-supplier.php',
            method: 'POST',
            data: {
                supplierName: supplierName,
                phone: phone,
                contactPerson: contactPerson,
                email: email,
                address: address,
                city: city,
                state: state,
                pinCode: pinCode,
                gstNumber: gstNumber,
                panNumber: panNumber,
                supplierType: supplierType,
                creditLimit: creditLimit,
                creditDays: creditDays
            },
            dataType: 'json',
            success: function(response) {
                hideLoading();
                if (response.success) {
                    // Add to select dropdown
                    const option = $('<option></option>')
                        .val(response.supplier.id)
                        .text(response.supplier.code + ' - ' + response.supplier.name)
                        .data('balance', response.supplier.balance)
                        .data('name', response.supplier.name)
                        .data('code', response.supplier.code)
                        .data('phone', response.supplier.phone)
                        .data('gst', response.supplier.gst || '');
                    
                    $('#supplierSelect').append(option);
                    
                    // Add to allSuppliers array
                    allSuppliers.push({
                        id: response.supplier.id,
                        name: response.supplier.name,
                        code: response.supplier.code,
                        phone: response.supplier.phone,
                        balance: response.supplier.balance,
                        gst: response.supplier.gst || ''
                    });
                    
                    // Select the new supplier
                    $('#supplierSelect').val(response.supplier.id);
                    $('#supplierSearch').val(response.supplier.name);
                    $('#supplierBalanceDisplay').slideUp();
                    
                    // Clear form and close modal
                    $('#addSupplierForm')[0].reset();
                    $('#addSupplierModal').modal('hide');
                    
                    showNotification(t('supplierAddedSuccessfully'), 'success');
                    
                    // Focus to product code
                    setTimeout(function() {
                        $('#productCode').focus();
                    }, 500);
                } else {
                    alert(t('error') + response.message);
                }
            },
            error: function(xhr, status, error) {
                hideLoading();
                console.error('Error:', xhr.responseText);
                alert(t('error') + (xhr.responseText || error));
            }
        });
    }
    
    // Show Notification
    function showNotification(message, type) {
        const bgColor = type === 'info' ? '#3498db' : type === 'success' ? '#2ecc71' : '#e74c3c';
        
        $('body').append(
            '<div class="notification-toast" style="position: fixed; top: 80px; right: 20px; ' +
            'background: ' + bgColor + '; color: white; padding: 15px 20px; border-radius: 8px; ' +
            'box-shadow: 0 4px 12px rgba(0,0,0,0.3); z-index: 9999; animation: slideIn 0.3s;">' +
            message +
            '</div>'
        );
        
        setTimeout(function() {
            $('.notification-toast').fadeOut(300, function() {
                $(this).remove();
            });
        }, 3000);
    }
    
    // Delete Sale
    function deleteSale() {
        const saleId = $('#editingSaleId').val();
        const invoiceNumber = $('#currentInvoiceNumber').text();
        
        if (!saleId || saleId == 0) {
            alert(t('selectBillToDelete'));
            return;
        }
        
        if (!confirm(t('confirmDeleteBill') + invoiceNumber + t('cannotUndo'))) {
            return;
        }
        
        showLoading();
        
        $.ajax({
            url: 'api/delete-purchase.php',
            method: 'POST',
            data: {
                saleId: saleId
            },
            dataType: 'json',
            success: function(response) {
                hideLoading();
                if (response.success) {
                    alert(t('billDeletedSuccessfully') + response.invoiceNumber);
                    // Reload page to start fresh
                    location.reload();
                } else {
                    alert(t('error') + response.message);
                }
            },
            error: function(xhr, status, error) {
                hideLoading();
                console.error('Delete error:', xhr.responseText);
                alert(t('error') + (xhr.responseText || error));
            }
        });
    }

    // ============================================
    // Product Discount Modal Functions
    // ============================================
    
    // Open Product Discount Modal
    function openProductDiscountModal(index) {
        const item = cart[index];
        
        // Set hidden index
        $('#editDiscountIndex').val(index);
        
        // Populate product info
        $('#editProductName').text(item.productName);
        $('#editProductCode').text(item.productCode);
        $('#editProductPrice').text('₹' + item.rate.toFixed(2));
        $('#editProductQty').text(item.quantity.toFixed(2));
        
        // Set current discount values
        $('#editDiscountAmount').val(item.discount || 0);
        
        // Set discount type radio buttons
        if (item.discountType === 'AMOUNT') {
            $('#editDiscAmount').prop('checked', true);
            $('#editDiscAmount').parent().addClass('active');
            $('#editDiscPercentage').parent().removeClass('active');
        } else {
            $('#editDiscPercentage').prop('checked', true);
            $('#editDiscPercentage').parent().addClass('active');
            $('#editDiscAmount').parent().removeClass('active');
        }
        
        // Calculate and display preview
        updateDiscountPreview();
        
        // Show modal
        $('#productDiscountModal').modal('show');
    }
    
    // Update Discount Preview
    function updateDiscountPreview() {
        const index = $('#editDiscountIndex').val();
        if (index === '') return;
        
        const item = cart[index];
        const discountAmount = parseFloat($('#editDiscountAmount').val()) || 0;
        const discountType = $('input[name="editDiscType"]:checked').val();
        
        const subtotal = item.rate * item.quantity;
        let discountValue = 0;
        
        if (discountType === 'PERCENTAGE') {
            discountValue = (subtotal * discountAmount) / 100;
        } else {
            discountValue = discountAmount;
        }
        
        const finalAmount = subtotal - discountValue;
        
        // Update display
        $('#editSubtotal').text('₹' + subtotal.toFixed(2));
        $('#editDiscountValue').text('- ₹' + discountValue.toFixed(2));
        $('#editFinalAmount').text('₹' + finalAmount.toFixed(2));
    }
    
    // Discount modal input handlers
    $('#editDiscountAmount').on('input', function() {
        updateDiscountPreview();
    });
    
    $('input[name="editDiscType"]').on('change', function() {
        updateDiscountPreview();
    });
    
    // Save Product Discount
    $('#btnSaveProductDiscount').click(function() {
        const index = parseInt($('#editDiscountIndex').val());
        const discountAmount = parseFloat($('#editDiscountAmount').val()) || 0;
        const discountType = $('input[name="editDiscType"]:checked').val();
        
        // Update cart item
        cart[index].discount = discountAmount;
        cart[index].discountType = discountType;
        
        // Update display
        updateDisplay();
        
        // Sync product discounts to bill discount display
        if (window.SalesEnhancements && window.SalesEnhancements.BillDiscountManager) {
            window.SalesEnhancements.BillDiscountManager.calculateBillDiscount();
        }
        
        // Close modal
        $('#productDiscountModal').modal('hide');
        
        showNotification(t('discountApplied'), 'success');
    });
    
    // Remove Product Discount
    $('#btnRemoveDiscount').click(function() {
        const index = parseInt($('#editDiscountIndex').val());
        
        // Remove discount
        cart[index].discount = 0;
        cart[index].discountType = 'PERCENTAGE';
        
        // Update display
        updateDisplay();
        
        // Sync product discounts to bill discount display
        if (window.SalesEnhancements && window.SalesEnhancements.BillDiscountManager) {
            window.SalesEnhancements.BillDiscountManager.calculateBillDiscount();
        }
        
        // Close modal
        $('#productDiscountModal').modal('hide');
        
        showNotification(t('discountRemoved'), 'success');
    });

    // ========================================
    // Transport GST Functions
    // ========================================
    
    function openTransportGSTModal() {
        const transportAmount = parseFloat($('#cooliAmount').val()) || 0;
        const gstPercent = parseFloat($('#transportGSTPercent').val()) || 0;
        const gstType = $('#transportGSTTypeValue').val() || 'inclusive';
        const transportName = $('#transportNameValue').val() || '';
        const vehicleNumber = $('#vehicleNumberValue').val() || '';
        
        // Set modal values
        $('#transportGSTAmount').val(transportAmount);
        $('#transportGSTPercentage').val(gstPercent);
        $('#transportName').val(transportName);
        $('#vehicleNumber').val(vehicleNumber);
        
        // Set GST type radio buttons
        if (gstType === 'exclusive') {
            $('#gstExclusive').prop('checked', true).parent().addClass('active');
            $('#gstInclusive').prop('checked', false).parent().removeClass('active');
        } else {
            $('#gstInclusive').prop('checked', true).parent().addClass('active');
            $('#gstExclusive').prop('checked', false).parent().removeClass('active');
        }
        
        // Calculate and show preview
        calculateTransportGST();
        
        // Show modal
        $('#transportGSTModal').modal('show');
    }
    
    function calculateTransportGST() {
        const transportAmount = parseFloat($('#transportGSTAmount').val()) || 0;
        const gstPercent = parseFloat($('#transportGSTPercentage').val()) || 0;
        const gstType = $('input[name="transportGSTType"]:checked').val() || 'inclusive';
        
        let baseAmount = 0;
        let gstAmount = 0;
        let totalAmount = 0;
        
        if (gstType === 'inclusive') {
            // GST is included in the transport amount
            totalAmount = transportAmount;
            baseAmount = transportAmount / (1 + (gstPercent / 100));
            gstAmount = totalAmount - baseAmount;
            
            $('#transportBaseLabel').text('Base Amount (excl. GST):');
            $('#transportTotalLabel').text('Total Amount (incl. GST):');
        } else {
            // GST is exclusive, will be added to transport amount
            baseAmount = transportAmount;
            gstAmount = baseAmount * (gstPercent / 100);
            totalAmount = baseAmount + gstAmount;
            
            $('#transportBaseLabel').text('Base Amount:');
            $('#transportTotalLabel').text('Total Amount (incl. GST):');
        }
        
        // Update display
        $('#transportBaseAmount').text('₹' + baseAmount.toFixed(2));
        $('#transportGSTValue').text('₹' + gstAmount.toFixed(2));
        $('#transportTotalAmount').text('₹' + totalAmount.toFixed(2));
        $('#gstRateDisplay').text(gstPercent.toFixed(2));
    }
    
    function applyTransportGST() {
        const transportAmount = parseFloat($('#transportGSTAmount').val()) || 0;
        const gstPercent = parseFloat($('#transportGSTPercentage').val()) || 0;
        const gstType = $('input[name="transportGSTType"]:checked').val() || 'inclusive';
        const transportName = $('#transportName').val() || '';
        const vehicleNumber = $('#vehicleNumber').val() || '';
        
        // Calculate GST amount
        let gstAmount = 0;
        let totalAmount = 0;
        
        if (gstType === 'inclusive') {
            totalAmount = transportAmount;
            const baseAmount = transportAmount / (1 + (gstPercent / 100));
            gstAmount = totalAmount - baseAmount;
        } else {
            gstAmount = transportAmount * (gstPercent / 100);
            totalAmount = transportAmount + gstAmount;
        }
        
        // Store configuration in hidden fields
        $('#transportNameValue').val(transportName);
        $('#vehicleNumberValue').val(vehicleNumber);
        $('#transportGSTPercent').val(gstPercent);
        $('#transportGSTTypeValue').val(gstType);
        
        // Store the TOTAL transport amount (the value entered by user)
        // This is what gets used in calculations
        $('#transportGSTAmount').val(transportAmount.toFixed(2));
        
        // Update the cooliAmount field to reflect the total with GST
        // This ensures the invoice calculation uses the correct amount
        if (gstType === 'exclusive') {
            // For exclusive, update the cooli amount to include GST
            $('#cooliAmount').val(totalAmount.toFixed(2));
        }
        
        // Trigger bill discount recalculation to update all totals
        if (window.SalesEnhancements && window.SalesEnhancements.BillDiscountManager) {
            window.SalesEnhancements.BillDiscountManager.calculateBillDiscount();
        } else {
            // Fallback to updateTotals if BillDiscountManager not available
            updateTotals();
        }
        
        // Close modal
        $('#transportGSTModal').modal('hide');
        
        // Show notification
        if (gstPercent > 0) {
            showNotification('Transport details saved: ' + gstPercent + '% (' + gstType + ')', 'success');
        } else {
            showNotification('Transport details saved', 'success');
        }
    }
    
    function resetTransportGST() {
        // Reset all GST settings
        $('#transportGSTPercentage').val(0);
        $('#gstInclusive').prop('checked', true).parent().addClass('active');
        $('#gstExclusive').prop('checked', false).parent().removeClass('active');
        
        // Reset hidden fields
        $('#transportGSTPercent').val(0);
        $('#transportGSTTypeValue').val('inclusive');
        $('#transportGSTAmount').val(0);
        
        // Recalculate
        calculateTransportGST();
        
        showNotification('Transport GST reset', 'info');
    }

    // Initialize customer balance if already selected
    if ($('#customerSelect').val()) {
        $('#customerSelect').trigger('change');
    }
});

// Add calculateTotals function for compatibility with purchase module
function calculateTotals() {
    updateTotals();
}
