
function getRowDiscountInfo(row) {
    if (!row) {
        return { type: 'none', value: 0, perUnit: 0, price: 0 };
    }

    const priceAttr = row.getAttribute('data-price');
    let price = parseFloat(priceAttr);
    if (!isFinite(price)) {
        price = parseFloat((priceAttr || '').replace(/[^\d.-]/g, '')) || 0;
    }

    const type = (row.getAttribute('data-item-discount-type') || 'none').toLowerCase();
    const valueAttr = row.getAttribute('data-item-discount-value');
    let value = parseFloat(valueAttr);
    if (!isFinite(value)) {
        value = parseFloat((valueAttr || '').replace(/[^\d.-]/g, '')) || 0;
    }
    let perUnit = parseFloat(row.getAttribute('data-item-discount-per-unit'));

    if (!isFinite(perUnit)) {
        perUnit = 0;
    }

    let computedPerUnit = perUnit;
    if (type === 'percent') {
        computedPerUnit = price * (value / 100);
    } else if (type === 'fixed') {
        computedPerUnit = value;
    } else if (type === 'none') {
        computedPerUnit = 0;
    } else {
        computedPerUnit = Math.max(0, perUnit);
    }

    if (computedPerUnit > price) {
        computedPerUnit = price;
    }

    if (computedPerUnit < 0 || !isFinite(computedPerUnit)) {
        computedPerUnit = 0;
    }

    return {
        type,
        value,
        perUnit: computedPerUnit,
        price
    };
}

function updateRowDiscountAttributes(row, discountInfo) {
    if (!row || !discountInfo) return;

    row.setAttribute('data-item-discount-type', discountInfo.type || 'none');
    row.setAttribute('data-item-discount-value', !isNaN(discountInfo.value) ? discountInfo.value : 0);
    row.setAttribute('data-item-discount-per-unit', !isNaN(discountInfo.perUnit) ? discountInfo.perUnit.toFixed(4) : '0');
}

const POS_QTY_PRECISION = (typeof window !== 'undefined' && window.posQuantityPrecision ? parseInt(window.posQuantityPrecision, 10) : 3) || 3;

if (typeof window !== 'undefined') {
    if (typeof window.unholdOrderId === 'undefined') {
        window.unholdOrderId = null;
    }
    if (typeof window.isHoldCart === 'undefined') {
        window.isHoldCart = false;
    }
    if (typeof window.activeHoldReference === 'undefined') {
        window.activeHoldReference = null;
    }
}
const POS_QTY_MIN = (typeof window !== 'undefined' && window.posQuantityMinimum ? parseFloat(window.posQuantityMinimum) : 0.01) || 0.01;
const POS_QTY_STEP = (typeof window !== 'undefined' && window.posQuantityStep ? parseFloat(window.posQuantityStep) : POS_QTY_MIN) || POS_QTY_MIN;

function normalizeQuantity(value, fallback = POS_QTY_MIN) {
    const parsed = parseFloat(value);
    if (!isFinite(parsed) || parsed <= 0) {
        return fallback;
    }
    return parseFloat(parsed.toFixed(POS_QTY_PRECISION));
}

function incrementQuantity(value, delta = 1) {
    const base = normalizeQuantity(value, POS_QTY_MIN);
    return normalizeQuantity(base + delta, POS_QTY_MIN);
}

function formatQuantity(value) {
    const normalized = normalizeQuantity(value, 0);
    const fixed = normalized.toFixed(POS_QTY_PRECISION);
    if (fixed.indexOf('.') === -1) {
        return fixed;
    }
    return fixed.replace(/\.?0+$/, '') || '0';
}

document.addEventListener("DOMContentLoaded", function () {
    const cartWrap = document.querySelector('.product-wrap');
    const totalDisplay = document.querySelector('.btn-block .btn');
    const subtotalEl = document.getElementById('subtotal');
    const totalEl = document.getElementById('total');
    const taxInput = document.querySelector('input[placeholder="0%"]');
    let selectedPaymentMethod = null;
    let userCanEditPrice = false; // Flag to track if user can edit prices
    let loadQuotationModalInstance = null;
    let activeCartRow = null;

    const loadQuotationBtn = document.getElementById('loadQuotationBtn');
    const loadQuotationModalEl = document.getElementById('loadQuotationModal');
    const quotationTableWrapper = document.getElementById('quotationTableWrapper');
    const quotationLoadingEl = document.getElementById('quotationLoading');
    const quotationErrorEl = document.getElementById('quotationError');
    const quotationEmptyEl = document.getElementById('noQuotationsMessage');
    const quotationListBody = document.getElementById('quotationListBody');

    if (loadQuotationBtn && loadQuotationModalEl) {
        loadQuotationBtn.addEventListener('click', function () {
            resetQuotationModalState();
            if (!loadQuotationModalInstance) {
                loadQuotationModalInstance = new bootstrap.Modal(loadQuotationModalEl);
            }
            loadQuotationModalInstance.show();
            fetchCustomerQuotationsForPOS();
        });

        loadQuotationModalEl.addEventListener('hidden.bs.modal', () => {
            resetQuotationModalState();
        });
    }

    function resetQuotationModalState() {
        if (quotationListBody) {
            quotationListBody.innerHTML = '';
        }
        if (quotationErrorEl) {
            quotationErrorEl.classList.add('d-none');
            quotationErrorEl.textContent = '';
        }
        if (quotationEmptyEl) {
            quotationEmptyEl.classList.add('d-none');
        }
        if (quotationTableWrapper) {
            quotationTableWrapper.classList.add('d-none');
        }
        if (quotationLoadingEl) {
            quotationLoadingEl.classList.remove('d-none');
        }
    }

    function fetchCustomerQuotationsForPOS() {
        if (!quotationLoadingEl) return;

        quotationLoadingEl.classList.remove('d-none');
        if (quotationErrorEl) {
            quotationErrorEl.classList.add('d-none');
            quotationErrorEl.textContent = '';
        }
        if (quotationEmptyEl) {
            quotationEmptyEl.classList.add('d-none');
        }
        if (quotationTableWrapper) {
            quotationTableWrapper.classList.add('d-none');
        }

        fetch('ajax/get_customer_quotations.php', {
            cache: 'no-cache'
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`Failed to fetch quotations (HTTP ${response.status})`);
                }
                return response.json();
            })
            .then(data => {
                quotationLoadingEl.classList.add('d-none');

                if (!data.success) {
                    showQuotationError(data.message || 'Unable to load quotations.');
                    return;
                }

                const quotations = Array.isArray(data.quotations) ? data.quotations : [];
                if (quotations.length === 0) {
                    if (quotationEmptyEl) {
                        quotationEmptyEl.classList.remove('d-none');
                    }
                    return;
                }

                renderQuotationRows(quotations);
            })
            .catch(error => {
                console.error('Error loading quotations:', error);
                quotationLoadingEl.classList.add('d-none');
                showQuotationError('Error fetching quotations. Please try again.');
            });
    }

    function showQuotationError(message) {
        if (quotationErrorEl) {
            quotationErrorEl.textContent = message;
            quotationErrorEl.classList.remove('d-none');
        }
    }

    function renderQuotationRows(quotations) {
        if (!quotationListBody || !quotationTableWrapper) return;

        const rowsHtml = quotations.map((quotation, index) => {
            const status = (quotation.status || '').toLowerCase();
            const statusClass = getQuotationStatusClass(status);
            const total = parseFloat(quotation.net_amount ?? quotation.total_amount ?? 0) || 0;
            const discount = parseFloat(quotation.discount_amount ?? 0) || 0;
            const date = quotation.quotation_date ? new Date(quotation.quotation_date) : null;
            const formattedDate = date ? date.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' }) : '-';
            const quotationNumber = quotation.quotation_number || `#${quotation.id}`;
            const customerName = quotation.customer_name || 'Walk-in Customer';

            return `
                <tr data-quotation-row="${quotation.id}">
                    <td>
                        <strong>${escapeHtml(quotationNumber)}</strong>
                    </td>
                    <td>${escapeHtml(customerName)}</td>
                    <td>${formattedDate}</td>
                    <td><span class="badge bg-${statusClass} text-capitalize">${escapeHtml(status || 'draft')}</span></td>
                    <td class="text-end">Rs ${total.toFixed(2)}</td>
                    <td class="text-end text-danger">Rs ${discount.toFixed(2)}</td>
                    <td class="text-end">
                        <button type="button"
                                class="btn btn-sm btn-primary btn-load-quotation"
                                data-quotation-id="${quotation.id}"
                                data-list-index="${index}">
                            <i data-feather="download"></i> Load
                        </button>
                    </td>
                </tr>
            `;
        }).join('');

        quotationListBody.innerHTML = rowsHtml;
        quotationTableWrapper.classList.remove('d-none');

        if (typeof feather !== 'undefined') {
            feather.replace();
        }

        quotationListBody.querySelectorAll('.btn-load-quotation').forEach(button => {
            button.addEventListener('click', function () {
                const quotationId = parseInt(this.getAttribute('data-quotation-id'), 10);
                if (!quotationId || Number.isNaN(quotationId)) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Invalid Quotation',
                        text: 'Unable to load the selected quotation.'
                    });
                    return;
                }
                loadQuotationIntoCart(quotationId, this);
            });
        });
    }

    function getQuotationStatusClass(status) {
        switch (status) {
            case 'sent':
                return 'primary';
            case 'accepted':
                return 'success';
            case 'rejected':
                return 'danger';
            case 'expired':
                return 'warning';
            case 'converted':
                return 'info';
            default:
                return 'secondary';
        }
    }

    function escapeHtml(value) {
        if (value === null || value === undefined) return '';
        return String(value)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }

    function loadQuotationIntoCart(quotationId, triggerButton) {
        if (triggerButton) {
            triggerButton.disabled = true;
            triggerButton.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Loading';
        }

        fetch('ajax/load_quotation_for_pos.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: new URLSearchParams({
                quotation_id: quotationId
            })
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`Failed to load quotation (HTTP ${response.status})`);
                }
                return response.json();
            })
            .then(data => {
                if (!data.success) {
                    throw new Error(data.message || 'Unable to load quotation.');
                }

                applyQuotationToCart(data);

                if (triggerButton) {
                    triggerButton.blur();
                }

                if (loadQuotationModalInstance) {
                    loadQuotationModalInstance.hide();
                }

                Swal.fire({
                    icon: 'success',
                    title: 'Quotation Loaded',
                    text: 'Quotation items have been added to the cart.',
                    timer: 2000,
                    showConfirmButton: false
                });
            })
            .catch(error => {
                console.error('Error loading quotation for POS:', error);
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: error.message || 'Failed to load quotation. Please try again.'
                });
            })
            .finally(() => {
                if (triggerButton) {
                    triggerButton.disabled = false;
                    triggerButton.innerHTML = '<i data-feather="download"></i> Load';
                    if (typeof feather !== 'undefined') {
                        feather.replace();
                    }
                }
            });
    }

    function applyQuotationToCart(payload) {
        if (!payload || !payload.quotation) return;

        const quotation = payload.quotation;
        const customer = payload.customer || {};
        const items = Array.isArray(payload.items) ? payload.items : [];

        window.loadedQuotationId = quotation.id;
        window.loadedQuotationNumber = quotation.quotation_number || '';
        window.unholdOrderId = null;
        window.isHoldCart = false;
        window.activeHoldReference = null;

        resetCart(false, false);

        const customerSelect = document.getElementById('top-customer-select');
        const formCustomerInput = document.getElementById('form-customer');

        const customerName = customer.name || 'Customer';

        if (customerSelect && customer.id) {
            let customerOption = customerSelect.querySelector(`option[value="${customer.id}"]`);
            const optionLabel = customer.discount_applied === 'Y' && parseFloat(customer.discount_rate) > 0
                ? `${customerName} (${parseFloat(customer.discount_rate).toFixed(2)}%)`
                : customerName;

            if (!customerOption) {
                customerOption = document.createElement('option');
                customerOption.value = customer.id;
                customerSelect.insertBefore(customerOption, customerSelect.firstChild);
            }

            customerOption.textContent = optionLabel;
            customerOption.setAttribute('data-discount-applied', customer.discount_applied || 'N');
            customerOption.setAttribute('data-discount-rate', parseFloat(customer.discount_rate || 0));
            customerOption.setAttribute('data-withholding-rate', parseFloat(customer.withholding_rate || 0));
            customerSelect.value = String(customer.id);

            // Trigger change event to apply discounts if applicable
            customerSelect.dispatchEvent(new Event('change'));
        }

        if (formCustomerInput) {
            formCustomerInput.value = customerName;
        }

        items.forEach((item, index) => {
            const itemId = parseInt(item.item_id, 10) || 0;
            const itemName = item.item_name || `Item ${index + 1}`;
            const unitPrice = parseFloat(item.unit_price) || 0;
            const taxType = item.tax_type || 'excluded';
            const taxRate = parseFloat(item.tax_rate) || 0;
            const quantity = normalizeQuantity(item.quantity ?? 1, POS_QTY_MIN);
            const remarks = item.remarks || '';
            const uniqueCode = `quotation-${quotation.id}-${itemId || 'custom'}-${index}`;

            addItemToCart(itemId, itemName, unitPrice, uniqueCode, taxType, taxRate, []);

            const row = document.querySelector(`.product-list[data-code="${uniqueCode}"]`);
            if (!row) {
                return;
            }

            row.setAttribute('data-price', unitPrice);
            row.setAttribute('data-base-price', unitPrice);
            row.setAttribute('data-item-id', itemId);
            row.setAttribute('data-item-name', itemName);

            const qtyInput = row.querySelector('input[name="qty"]');
            if (qtyInput) {
                qtyInput.value = formatQuantity(quantity);
            }

            if (remarks) {
                row.setAttribute('data-remarks', remarks);
                const remarksSection = row.querySelector('.remarks-section');
                const remarksText = row.querySelector('.remarks-text');
                if (remarksSection && remarksText) {
                    remarksSection.style.display = 'block';
                    remarksText.textContent = remarks;
                }
            }
        });

        if (quotation.discount_amount && parseFloat(quotation.discount_amount) > 0 && discountInput && discountType) {
            discountType.value = 'fixed';
            discountInput.value = parseFloat(quotation.discount_amount).toFixed(2);
        } else if (discountInput && discountType) {
            discountInput.value = '0';
            discountType.value = 'percent';
        }

        updateTotal();

        if (typeof feather !== 'undefined') {
            feather.replace();
        }
    }

    // 🟢 Category filter with subcategory support
    let selectedCategoryId = null;
    let selectedSubcategoryId = null;
    
    // Check user rights for price editing
    checkPriceEditRights();
    
    // Set first category as default active
    const firstCategory = document.querySelector('ul.tabs.pos-category li');
    if (firstCategory) {
        const firstCategoryId = firstCategory.getAttribute('data-category');
        selectedCategoryId = firstCategoryId;
        firstCategory.classList.add('active');
        
        // Hide all products on page load - they should only show when subcategory is selected
        document.querySelectorAll('.product-info.card').forEach(card => {
            const col = card.closest('.col-sm-2, .col-md-6, .col-lg-2, .col-xl-2');
            if (col) col.style.display = 'none';
        });
        
        loadSubcategories(firstCategoryId);
        // Don't show products - only show when subcategory is selected
    } else {
        // Even if no category exists, hide all products on page load
        document.querySelectorAll('.product-info.card').forEach(card => {
            const col = card.closest('.col-sm-2, .col-md-6, .col-lg-2, .col-xl-2');
            if (col) col.style.display = 'none';
        });
    }
    
    document.querySelectorAll('ul.tabs.pos-category li').forEach(category => {
        category.addEventListener('click', function (e) {
            e.preventDefault();
            const selectedId = this.getAttribute('data-category');
            selectedCategoryId = selectedId;
            selectedSubcategoryId = null; // Reset subcategory selection
            
            // Update category active state
            document.querySelectorAll('ul.tabs.pos-category li').forEach(tab => tab.classList.remove('active'));
            this.classList.add('active');
            
            // Clear any active subcategory selection
            document.querySelectorAll('.subcategory-item').forEach(sub => sub.classList.remove('active'));
            
            // Hide all products - they should only show when a subcategory is selected
            document.querySelectorAll('.product-info.card').forEach(card => {
                const col = card.closest('.col-sm-2, .col-md-6, .col-lg-2, .col-xl-2');
                if (col) col.style.display = 'none';
            });
            
            // Load subcategories only - don't show products yet
            loadSubcategories(selectedId);
        });
    });
    
    // Function to load subcategories
    function loadSubcategories(categoryId) {
        const subcategoryContainer = document.getElementById('subcategory-list');
        
        // Show loading state
        subcategoryContainer.innerHTML = `
            <div class="text-center py-4">
                <div class="spinner-border spinner-border-sm text-primary" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
                <p class="mt-2 text-muted">Loading subcategories...</p>
            </div>
        `;
        
        // Fetch subcategories
        fetch(`ajax/get_subcategories.php?category_id=${categoryId}`)
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    subcategoryContainer.innerHTML = `
                        <div class="text-muted text-center py-4">
                            <i data-feather="alert-circle" class="feather-24 mb-2"></i>
                            <p>${data.error}</p>
                        </div>
                    `;
                    return;
                }
                
                if (data.length === 0) {
                    subcategoryContainer.innerHTML = `
                        <div class="text-muted text-center py-4">
                            <i data-feather="inbox" class="feather-24 mb-2"></i>
                            <p>No subcategories found</p>
                        </div>
                    `;
                    return;
                }
                
                // Create subcategory items
                let subcategoryHTML = '';
                data.forEach(subcategory => {
                    const itemCount = getItemCountBySubcategory(subcategory.id);
                    const colorAttr = subcategory.display_color ? `data-color="${subcategory.display_color}"` : '';
                    subcategoryHTML += `
                        <div class="subcategory-item" data-subcategory-id="${subcategory.id}" ${colorAttr}>
                            <div class="subcategory-name">${subcategory.name}</div>
                            <div class="subcategory-count">${itemCount} items</div>
                        </div>
                    `;
                });
                
                subcategoryContainer.innerHTML = subcategoryHTML;
                
                // Add click events to subcategory items
                document.querySelectorAll('.subcategory-item').forEach(item => {
                    item.addEventListener('click', function() {
                        const subcategoryId = this.getAttribute('data-subcategory-id');
                        selectedSubcategoryId = subcategoryId;
                        
                        // Update active state
                        document.querySelectorAll('.subcategory-item').forEach(sub => sub.classList.remove('active'));
                        this.classList.add('active');
                        
                        // Filter products
                        filterProductsByCategoryAndSubcategory(selectedCategoryId, subcategoryId);
                    });
                });
                
                // Initialize feather icons
                if (typeof feather !== 'undefined') {
                    feather.replace();
                }
                
                // Initialize feather icons for the initial state
                if (typeof feather !== 'undefined') {
                    feather.replace();
                }
            })
            .catch(error => {
                console.error('Error loading subcategories:', error);
                subcategoryContainer.innerHTML = `
                    <div class="text-muted text-center py-4">
                        <i data-feather="wifi-off" class="feather-24 mb-2"></i>
                        <p>Error loading subcategories</p>
                    </div>
                `;
            });
    }
    
    // Function to clear subcategories
    function clearSubcategories() {
        const subcategoryContainer = document.getElementById('subcategory-list');
        subcategoryContainer.innerHTML = `
            <div class="text-muted text-center py-4">
                <i data-feather="grid" class="feather-24 mb-2"></i>
                <p>Select a category to view subcategories</p>
            </div>
        `;
    }
    
    // Function to get item count by subcategory
    function getItemCountBySubcategory(subcategoryId) {
        let count = 0;
        document.querySelectorAll('.product-info.card').forEach(card => {
            const cardSubcategoryId = card.getAttribute('data-subcategory-id');
            if (cardSubcategoryId == subcategoryId) {
                count++;
            }
        });
        return count;
    }
    

    
    // Function to show products by category
    function showProductsByCategory(categoryId) {
        document.querySelectorAll('.product-info.card').forEach(card => {
            const cardCategory = card.getAttribute('data-category-id');
            const col = card.closest('.col-sm-2, .col-md-6, .col-lg-3, .col-xl-3');
            const shouldShow = categoryId == cardCategory;
            if (col) col.style.display = shouldShow ? 'block' : 'none';
        });
    }
    
    // Function to filter products by category and subcategory
    function filterProductsByCategoryAndSubcategory(categoryId, subcategoryId) {
        document.querySelectorAll('.product-info.card').forEach(card => {
            const cardCategory = card.getAttribute('data-category-id');
            const cardSubcategory = card.getAttribute('data-subcategory-id');
            const col = card.closest('.col-sm-2, .col-md-6, .col-lg-2, .col-xl-2');
            
            const categoryMatch = categoryId == cardCategory;
            const subcategoryMatch = subcategoryId == cardSubcategory;
            
            const shouldShow = categoryMatch && subcategoryMatch;
            if (col) col.style.display = shouldShow ? 'block' : 'none';
        });
    }


  
// 🟢 Handle Order Mode Buttons
document.querySelectorAll('.order-mode-btn').forEach(btn => {
    btn.addEventListener('click', function (e) {
        const mode = this.dataset.mode;

        // Special handling for delivery mode
        if (mode === 'delivery') {
            e.preventDefault();
            
            // Show delivery management modal instead of setup modal
            const deliveryModal = new bootstrap.Modal(document.getElementById('deliveryModal'));
            deliveryModal.show();
            
            // Don't proceed with normal mode selection
            return;
        }

        // Special handling for take_away mode - let the modal handle it
        if (mode === 'take_away') {
            // The modal will handle setting the mode when "New Order" is clicked
            return;
        }

        // Set global and form values for dine_in mode
        if (mode === 'dine_in') {
            window.selectedOrderMode = mode;
            window.unholdOrderId = null; // Clear any existing order ID for new order
            window.isHoldCart = false;
            window.activeHoldReference = null;
            document.getElementById('selected-order-mode').value = mode;
        }

        // If mode is NOT dine_in, clear table info
        if (mode !== 'dine_in') {
            window.selectedTableId = null;
            window.unholdOrderId = null; // Clear any existing order ID for new order
            window.isHoldCart = false;
            window.activeHoldReference = null;
            document.getElementById('selected-table-id').value = '';
            const tableNameDisplay = document.getElementById('active-table-name');
            if (tableNameDisplay) tableNameDisplay.textContent = '';
        }

        // Optional: visually indicate selected mode
        document.querySelectorAll('.order-mode-btn').forEach(b => b.classList.remove('active'));
        this.classList.add('active');

        // Optional: show mode label
        const label = document.getElementById('active-mode-label');
        if (label) label.textContent = 'Mode: ' + mode.replace('_', ' ').toUpperCase();
    });
});

        // 🟡 When "Hold Orders" modal is shown, fetch and display held orders
    const heldOrdersModal = document.getElementById('orders');
    if (heldOrdersModal) {
        heldOrdersModal.addEventListener('show.bs.modal', function () {
            fetch('get_held_orders.php')
                .then(res => res.json())
                .then(data => {
                    const tbody = document.querySelector('#held-orders-table tbody');
                    tbody.innerHTML = '';

                    if (data.length === 0) {
                        tbody.innerHTML = `
                            <tr>
                                <td colspan="7" class="text-center py-4">
                                    <i data-feather="inbox" class="feather-48 mb-3 text-muted"></i>
                                    <p class="text-muted mb-0">No held orders found</p>
                                </td>
                            </tr>
                        `;
                    } else {
                        data.forEach(order => {
                            const tr = document.createElement('tr');
                            tr.className = 'order-row';
                            tr.setAttribute('data-order-id', order.id);
                            tr.style.cursor = 'pointer';
                            
                            tr.innerHTML = `
    <td><strong>${order.reference}</strong></td>
    <td>${order.customer_name}</td>
    <td><span class="badge bg-primary">${order.order_mode ? order.order_mode.replace(/_/g, ' ').toUpperCase() : 'WALK-IN'}</span></td>
    <td>${order.table_name || '-'}</td>
    <td><strong>Rs ${parseFloat(order.total_amount).toFixed(2)}</strong></td>
    <td>${formatTime(order.created_at)}</td>
    <td>
        <div class="btn-group btn-group-sm">
            <button class="btn btn-outline-info view-details-btn" data-id="${order.id}" title="View Details">
                <i data-feather="eye"></i>
            </button>
            <button class="btn btn-outline-primary print-order-btn" data-id="${order.id}" title="Print KOT">
                <i data-feather="printer"></i>
            </button>
            <button class="btn btn-primary print-proforma-btn" data-id="${order.id}" title="Print Proforma Invoice">
                <i data-feather="file-text"></i>
            </button>
            <button class="btn btn-success resume-order-btn" data-id="${order.id}" title="Resume Order">
                <i data-feather="play"></i>
            </button>
        </div>
    </td>
`;

                            tbody.appendChild(tr);
                        });
                    }

                    // Add click handlers for order rows
                    bindOrderRowHandlers();
                    bindResumeButtons();
                    bindPrintButtons();
                    bindProformaButtons();
                    
                    // Initialize Feather icons
                    if (typeof feather !== 'undefined') {
                        feather.replace();
                    }
                });
        });
    }

        // 🔄 Bind order row click handlers
  function bindOrderRowHandlers() {
    document.querySelectorAll('.order-row').forEach(row => {
        row.addEventListener('click', function(e) {
            // Don't trigger if clicking on buttons
            if (e.target.closest('.btn')) {
                return;
            }
            
            const orderId = this.getAttribute('data-order-id');
            loadOrderDetails(orderId);
            
            // Highlight selected row
            document.querySelectorAll('.order-row').forEach(r => r.classList.remove('table-active'));
            this.classList.add('table-active');
        });
    });
    
    // Bind view details buttons
    document.querySelectorAll('.view-details-btn').forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            const orderId = this.dataset.id;
            loadOrderDetails(orderId);
            
            // Highlight selected row
            document.querySelectorAll('.order-row').forEach(r => r.classList.remove('table-active'));
            this.closest('.order-row').classList.add('table-active');
        });
    });
  }

  // 📋 Load and display order details
  function loadOrderDetails(orderId) {
    const container = document.getElementById('order-details-container');
    
    // Show loading
    container.innerHTML = `
      <div class="text-center py-4">
        <div class="spinner-border text-primary" role="status">
          <span class="visually-hidden">Loading...</span>
        </div>
        <p class="mt-2">Loading order details...</p>
      </div>
    `;
    
    fetch(`load_held_order.php?id=${orderId}`)
        .then(res => res.json())
        .then(data => {
            if (!data.success) {
                throw new Error(data.error || 'Failed to load order details');
            }
            
            renderOrderDetails(data.order, data.items);
        })
        .catch(error => {
            console.error('Error loading order details:', error);
            container.innerHTML = `
              <div class="alert alert-danger">
                <i data-feather="alert-circle" class="me-2"></i>
                Failed to load order details: ${error.message}
              </div>
            `;
            if (typeof feather !== 'undefined') {
                feather.replace();
            }
        });
  }

  // 🎨 Render order details
  function renderOrderDetails(order, items) {
    const container = document.getElementById('order-details-container');
    
    let itemsHtml = '';
    let totalItems = 0;
    
    items.forEach(item => {
        const itemQty = normalizeQuantity(item.quantity || 0, 0);
        totalItems += itemQty;
        const modifiers = item.modifiers && item.modifiers.length > 0 ? 
            item.modifiers.map(m => m.name).join(', ') : '';
        
        itemsHtml += `
          <div class="card mb-2">
            <div class="card-body p-3">
              <div class="d-flex justify-content-between align-items-start">
                <div class="flex-grow-1">
                  <h6 class="mb-1">${item.item_name}</h6>
                  <div class="text-muted small">
                    <span class="badge bg-secondary me-2">Qty: ${formatQuantity(itemQty)}</span>
                    <span class="badge bg-info">Rs ${parseFloat(item.unit_price).toFixed(2)}</span>
                  </div>
                  ${modifiers ? `<div class="text-success small mt-1"><i data-feather="plus" class="feather-12 me-1"></i>${modifiers}</div>` : ''}
                  ${item.remarks ? `<div class="text-warning small mt-1"><i data-feather="message-square" class="feather-12 me-1"></i>${item.remarks}</div>` : ''}
                </div>
                <div class="text-end">
                  <strong>Rs ${(parseFloat(item.unit_price) * itemQty).toFixed(2)}</strong>
                </div>
              </div>
            </div>
          </div>
        `;
    });
    
    const orderTime = formatTime(order.created_at);
    const orderMode = order.order_mode ? order.order_mode.replace(/_/g, ' ').toUpperCase() : 'WALK-IN';
    
    container.innerHTML = `
      <div class="card">
        <div class="card-header bg-light">
          <div class="d-flex justify-content-between align-items-center">
            <h6 class="mb-0">Order Summary</h6>
            <span class="badge bg-primary">${orderMode}</span>
          </div>
        </div>
        <div class="card-body">
          <div class="row mb-3">
            <div class="col-6">
              <small class="text-muted">Customer</small>
              <div><strong>${order.customer_name || 'Walk-in'}</strong></div>
            </div>
            <div class="col-6">
              <small class="text-muted">Table</small>
              <div><strong>${order.table_name || 'N/A'}</strong></div>
            </div>
          </div>
          <div class="row mb-3">
            <div class="col-6">
              <small class="text-muted">Created</small>
              <div><strong>${orderTime}</strong></div>
            </div>
            <div class="col-6">
              <small class="text-muted">Items</small>
            <div><strong>${formatQuantity(totalItems)} items</strong></div>
            </div>
          </div>
          
          <hr>
          
          <h6 class="mb-3">Order Items (${items.length})</h6>
          <div class="order-items-list" style="max-height: 300px; overflow-y: auto;">
            ${itemsHtml}
          </div>
          
          <hr>
          
          <div class="d-flex justify-content-between align-items-center">
            <h5 class="mb-0">Total Amount</h5>
            <h5 class="mb-0 text-primary">Rs ${parseFloat(order.total_amount).toFixed(2)}</h5>
          </div>
        </div>
      </div>
    `;
    
    // Initialize Feather icons
    if (typeof feather !== 'undefined') {
        feather.replace();
    }
  }

  // 🕐 Format time helper
  function formatTime(timestamp) {
    const date = new Date(timestamp);
    const now = new Date();
    const diffMs = now - date;
    const diffMins = Math.floor(diffMs / 60000);
    const diffHours = Math.floor(diffMs / 3600000);
    
    if (diffMins < 1) {
        return 'Just now';
    } else if (diffMins < 60) {
        return `${diffMins}m ago`;
    } else if (diffHours < 24) {
        return `${diffHours}h ${diffMins % 60}m ago`;
    } else {
        return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
    }
  }

        // 🔄 Bind resume button click handler
  function bindResumeButtons() {
    document.querySelectorAll('.resume-order-btn').forEach(button => {
        button.addEventListener('click', function (e) {
            e.preventDefault();
            const holdId = this.dataset.id;
            
            // Disable button to prevent double clicks
            this.disabled = true;
            this.innerHTML = '<i data-feather="loader" class="feather-spin"></i> Loading...';

            fetch(`load_held_order.php?id=${holdId}`)
                .then(res => {
                    if (!res.ok) {
                        throw new Error(`HTTP error! status: ${res.status}`);
                    }
                    return res.json();
                })
                .then(data => {
                    
                    if (!data.success) {
                        throw new Error(data.error || 'Failed to load held order');
                    }
                    
                    if (!data.order || !data.items) {
                        throw new Error('Invalid order data received');
                    }
                    
        resetCart(false); // Don't reset customer when loading held order

                    // ✅ Restore order mode and table
                    window.selectedOrderMode = data.order.order_mode || null;
                    window.selectedTableId = data.order.table_id || null;
                    window.selectedOrderTakerId = data.order.order_taker_id || null;
                    window.unholdOrderId = holdId;
                    window.isHoldCart = true;
                    const holdReference = data.order.reference || `HOLD-${String(holdId).padStart(6, '0')}`;
                    window.activeHoldReference = holdReference;

                    // Update order mode selector if it exists
                    const orderModeSelect = document.getElementById('selected-order-mode');
                    if (orderModeSelect) {
                        orderModeSelect.value = window.selectedOrderMode || '';
                    }
                    
                    // Update table selector if it exists
                    const tableSelect = document.getElementById('selected-table-id');
                    if (tableSelect) {
                        tableSelect.value = window.selectedTableId || '';
                    }
                    
                    // Update order taker selector if it exists
                    const orderTakerSelect = document.getElementById('selected-order-taker-id');
                    if (orderTakerSelect) {
                        orderTakerSelect.value = window.selectedOrderTakerId || '';
                    }

                    const tableDisplay = document.getElementById('active-table-name');
                    if (tableDisplay && data.order.table_name) {
                        tableDisplay.textContent = 'Table: ' + data.order.table_name;
                    }

                    // ✅ Set customer
                    const customerName = data.order.customer_name || 'Walk-in';
                    const customerDropdown = document.getElementById('top-customer-select');
                    const formInput = document.getElementById('form-customer');
                    if (customerDropdown) customerDropdown.value = customerName;
                    if (formInput) formInput.value = customerName;

                    const discountInputEl = document.getElementById('discount-input');
                    const discountTypeEl = document.getElementById('discount-type');
                    const discountDisplayEl = document.getElementById('discount-display');
                    const discountNameDisplay = document.getElementById('selected-discount-name');

                    // ✅ Restore discount if exists
                    window.selectedDiscount = null;
                    if (data.discount_info) {
                        window.selectedDiscount = {
                            id: data.discount_info.id,
                            type: 'discount', // Mark as predefined discount
                            data: {
                                discount_name: data.discount_info.name,
                                discount_type: data.discount_info.type,
                                discount_rate: data.discount_info.rate,
                                discount_cap: data.discount_info.cap
                            }
                        };
                        
                        // Update discount display
                        if (discountNameDisplay) {
                            discountNameDisplay.textContent = data.discount_info.name;
                        }
                    } else if (data.manual_discount) {
                        if (discountTypeEl) {
                            discountTypeEl.value = data.manual_discount.type || 'percent';
                        }
                        if (discountInputEl) {
                            const manualValue = parseFloat(data.manual_discount.value ?? 0);
                            if (!Number.isNaN(manualValue)) {
                                discountInputEl.value = manualValue.toFixed(2);
                            } else {
                                discountInputEl.value = '0.00';
                            }
                        }
                        if (discountDisplayEl) {
                            const manualAmount = parseFloat(data.manual_discount.amount ?? 0);
                            discountDisplayEl.textContent = `Rs ${(!Number.isNaN(manualAmount) ? manualAmount : 0).toFixed(2)}`;
                        }
                        if (discountNameDisplay) {
                            discountNameDisplay.textContent = 'Manual Discount';
                        }
                    } else {
                        if (discountTypeEl) {
                            discountTypeEl.value = 'percent';
                        }
                        if (discountInputEl) {
                            discountInputEl.value = '0';
                        }
                        if (discountDisplayEl) {
                            discountDisplayEl.textContent = 'Rs 0.00';
                        }
                        if (discountNameDisplay) {
                            discountNameDisplay.textContent = '';
                        }
                    }

                    // ✅ Restore cart items (directly add to cart with stored modifiers and remarks)
                    data.items.forEach(item => {
                        const modifiers = item.modifiers || [];
                        const remarks = item.remarks || '';
                        // Use actual tax_type from backend (included, excluded, or nil) - default to excluded if not found
                        const taxType = item.tax_type || 'excluded';
                        const taxRate = parseFloat(item.tax_rate) || 0;
                        // Use item_code if available, otherwise fallback to generated code from name
                        const code = (item.item_code && item.item_code.trim() !== '') ? item.item_code : item.item_name.replace(/\s+/g, '-').toLowerCase();
                        const itemPrice = parseFloat(item.unit_price) || 0;
                        
                        // Add directly to cart bypassing modifier selection
                        addItemToCart(item.item_id, item.item_name, itemPrice, code, taxType, taxRate, modifiers);
                        
                        // Set the correct quantity and remarks
                        const uniqueCode = modifiers.length > 0 ? 
                            `${code}-mod-${modifiers.map(m => m.id).sort().join('-')}` : code;
                        const addedRow = document.querySelector(`.product-list[data-code="${uniqueCode}"]`);
                        if (addedRow) {
                            const originalUnitPrice = parseFloat(item.original_unit_price ?? item.unit_price ?? itemPrice) || 0;
                            addedRow.setAttribute('data-price', originalUnitPrice);
                            addedRow.setAttribute('data-base-price', originalUnitPrice);
                            // Ensure tax_type is set correctly from backend data
                            addedRow.setAttribute('data-tax-type', taxType);
                            addedRow.setAttribute('data-tax-rate', taxRate);
                            addedRow.setAttribute('data-item-discount-type', (item.discount_type || 'none').toLowerCase());
                            addedRow.setAttribute('data-item-discount-value', item.discount_value || 0);
                            addedRow.setAttribute('data-item-discount-per-unit', item.discount_per_unit || 0);
                            // Set quantity
                            const qtyInput = addedRow.querySelector('input[name="qty"]');
                            if (qtyInput) {
                                qtyInput.value = formatQuantity(item.quantity ?? 1);
                            }
                            
                            // Set remarks
                            if (remarks) {
                                addedRow.setAttribute('data-remarks', remarks);
                                const remarksSection = addedRow.querySelector('.remarks-section');
                                const remarksText = addedRow.querySelector('.remarks-text');
                                if (remarksSection && remarksText) {
                                    remarksSection.style.display = 'block';
                                    remarksText.textContent = `💬 ${remarks}`;
                                }
                            }
                        }
                    });

                    // ✅ Apply discount after items are loaded
                    if (window.selectedDiscount && typeof window.applySelectedDiscount === 'function') {
                        window.applySelectedDiscount();
                    } else {
                        updateTotal();
                    }

                    // ✅ Close modal
                    const ordersModal = document.getElementById('orders');
                    if (ordersModal) {
                        const modalInstance = bootstrap.Modal.getInstance(ordersModal);
                        if (modalInstance) {
                            modalInstance.hide();
                        }
                    }
                })
                .catch(error => {
                    console.error('Error loading held order:', error);
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Failed to load held order: ' + error.message,
                        confirmButtonColor: '#d33'
                    });
                })
                .finally(() => {
                    // Re-enable button
                    this.disabled = false;
                    this.innerHTML = '<i data-feather="play"></i>';
                    if (typeof feather !== 'undefined') {
                        feather.replace();
                    }
                });
        });
    });
  }

  // 🖨️ Bind print button click handler
  function bindPrintButtons() {
    document.querySelectorAll('.print-order-btn').forEach(button => {
        button.addEventListener('click', function (e) {
            e.preventDefault();
            e.stopPropagation();
            const holdId = this.dataset.id;
            
            // Use the new KOT printing function that respects print method setting
            handleKOTPrint(holdId);
        });
    });
  }

  // 🧾 Bind proforma invoice print buttons
  function bindProformaButtons() {
    document.querySelectorAll('.print-proforma-btn').forEach(button => {
        button.addEventListener('click', function (e) {
            e.preventDefault();
            e.stopPropagation();
            const holdId = this.dataset.id;
            
            // Use the new proforma printing function that respects print method setting
            handleProformaPrint(holdId);
        });
    });
  }

  // 🟢 Add to cart
document.querySelectorAll('.product-info.card').forEach(product => {
  product.addEventListener('click', function () {

    // ✅ Only run these checks if modes are enabled in settings
    if (Array.isArray(window.enabledOrderModes) && window.enabledOrderModes.length > 0) {

      // Block item selection if no order mode is selected
      if (!window.selectedOrderMode) {
        Swal.fire({
          icon: 'warning',
          title: 'Select Order Mode First',
          text: 'Please choose Dine In, Take Away, or Delivery before adding products.'
        });
        return;
      }

      // If dine-in, ensure a table is selected
      if (window.selectedOrderMode === 'dine_in' && !window.selectedTableId) {
        Swal.fire({
          icon: 'warning',
          title: 'Select a Table',
          text: 'Please select a table before adding items for Dine In orders.'
        });
        return;
      }
    }

    // ✅ If all checks pass, check for modifiers first
    const itemId = parseInt(this.getAttribute('data-id'));
    const name = this.querySelector('.product-name a').textContent.trim();
    const fallbackPrice = parseFloat(this.getAttribute('data-retail-price')) || parseFloat(this.querySelector('.price p').textContent.replace(/[^\d.]/g, ''));
    const price = fallbackPrice;
    // Use item_code from data attribute, fallback to generated code from name if not available
    const itemCode = this.getAttribute('data-item-code');
    const code = itemCode && itemCode.trim() !== '' ? itemCode : name.replace(/\s+/g, '-').toLowerCase();
    const taxType = this.getAttribute('data-tax-type');
    const taxRate = this.getAttribute('data-tax-rate');
    const isSerialized = parseInt(this.getAttribute('data-is-serialized')) === 1;
    const itemMeta = {
      itemType: this.getAttribute('data-item-type') || 'loose',
      bulkQty: parseFloat(this.getAttribute('data-bulk-qty')) || 0,
      bulkPrice: parseFloat(this.getAttribute('data-bulk-price')) || 0
    };
    
    // Check if this item has modifiers before adding to cart
    checkItemModifiers(itemId, name, price, code, taxType, taxRate, isSerialized, itemMeta);
  });
});

// Function to check if item has modifiers and show selection modal
function checkItemModifiers(itemId, name, price, code, taxType, taxRate, isSerialized = false, itemMeta = {}) {
  // ✅ First check if item is a deal
  fetch(`ajax/get_deal_info.php?item_id=${itemId}`)
    .then(response => response.json())
    .then(dealData => {
      if (dealData.success && dealData.is_deal) {
        // Item is a deal - show deal selection modal
        showDealSelectionModal(dealData.deal, itemId, name, price, code, taxType, taxRate, isSerialized, itemMeta);
        return;
      }
      
      // Not a deal - continue with normal flow
      // ✅ If item is serialized, show serial selection modal first
      if (isSerialized) {
        // Check available serials and show modal (don't limit quantity - show all available)
        fetch(`ajax/get_available_serials.php?item_id=${itemId}`)
          .then(response => response.json())
          .then(data => {
            if (!data.success) {
              Swal.fire({
                icon: 'error',
                title: 'Error',
                text: data.message || 'Failed to load available serials'
              });
              return;
            }
            
            // Check if item has modifiers too
            fetch(`ajax/get_item_modifiers.php?item_id=${itemId}`)
              .then(modResponse => modResponse.json())
              .then(modData => {
                const hasModifiers = modData.success && modData.modifier_groups && modData.modifier_groups.length > 0;
                
                // Show serial selection modal first
                // After serial selection, handle modifiers if any
                showSerialSelectionBeforeCart(itemId, name, price, code, taxType, taxRate, data.serials, data.total_available, hasModifiers ? modData.modifier_groups : null, itemMeta);
              })
              .catch(modError => {
                console.error('Error checking modifiers:', modError);
                // Show serial modal without modifiers
                showSerialSelectionBeforeCart(itemId, name, price, code, taxType, taxRate, data.serials, data.total_available, null, itemMeta);
              });
          })
          .catch(error => {
            console.error('Error fetching serials:', error);
            Swal.fire({
              icon: 'error',
              title: 'Error',
              text: 'Failed to load available serial numbers'
            });
          });
        return;
      }
      
      // Not serialized - check for modifiers as usual
      fetch(`ajax/get_item_modifiers.php?item_id=${itemId}`)
        .then(response => response.json())
        .then(data => {
          if (data.success && data.modifier_groups && data.modifier_groups.length > 0) {
            // Item has modifiers, show selection modal
            showModifierModal(itemId, name, price, code, taxType, taxRate, data.modifier_groups, isSerialized, itemMeta);
          } else {
            // No modifiers, add directly to cart
            addItemToCart(itemId, name, price, code, taxType, taxRate, [], isSerialized, [], itemMeta);
          }
        })
        .catch(error => {
          console.error('Error checking modifiers:', error);
          // If error, add item without modifiers
          addItemToCart(itemId, name, price, code, taxType, taxRate, [], isSerialized, [], itemMeta);
        });
    })
    .catch(error => {
      console.error('Error checking deal:', error);
      // If error checking deal, continue with normal flow
      if (!isSerialized) {
        checkItemModifiersNormal(itemId, name, price, code, taxType, taxRate, isSerialized, itemMeta);
      }
    });
}

// Helper function for normal modifier check (to avoid recursion)
function checkItemModifiersNormal(itemId, name, price, code, taxType, taxRate, isSerialized = false, itemMeta = {}) {
  fetch(`ajax/get_item_modifiers.php?item_id=${itemId}`)
    .then(response => response.json())
    .then(data => {
      if (data.success && data.modifier_groups && data.modifier_groups.length > 0) {
        showModifierModal(itemId, name, price, code, taxType, taxRate, data.modifier_groups, isSerialized, itemMeta);
      } else {
        addItemToCart(itemId, name, price, code, taxType, taxRate, [], isSerialized, [], itemMeta);
      }
    })
    .catch(error => {
      console.error('Error checking modifiers:', error);
      addItemToCart(itemId, name, price, code, taxType, taxRate, [], isSerialized, [], itemMeta);
    });
}

// Function to show deal selection modal
function showDealSelectionModal(deal, itemId, name, price, code, taxType, taxRate, isSerialized = false, itemMeta = {}) {
    // Store deal data globally for the modal
    window.dealModalData = {
        deal: deal,
        itemId: itemId,
        name: name,
        price: price,
        code: code,
        taxType: taxType,
        taxRate: taxRate,
        isSerialized: isSerialized,
        itemMeta: itemMeta || {}
    };
    
    // Create selections object - use arrays for components that allow multiple selections
    window.dealSelections = {};
    deal.components.forEach((comp, index) => {
        const maxSelection = parseInt(comp.max_selection || 1);
        window.dealSelections[index] = maxSelection > 1 ? [] : null; // Array for multiple, null/single object for single
    });
    
    // Escape name for safe HTML insertion
    const safeName = name.replace(/'/g, '&#39;').replace(/"/g, '&quot;');
    
    // Build component selection HTML with clickable items
    let componentsHtml = '';
    deal.components.forEach((comp, index) => {
        let selectionTypeLabel = '';
        if (comp.selection_type === 'category') {
            selectionTypeLabel = `Select from Category: ${comp.category_name || 'N/A'}`;
        } else if (comp.selection_type === 'subcategory') {
            selectionTypeLabel = `Select from Subcategory: ${comp.subcategory_name || 'N/A'}`;
        } else if (comp.selection_type === 'item') {
            selectionTypeLabel = `Select Item: ${comp.item_name || 'N/A'}`;
        }
        
        const minSelection = parseInt(comp.min_selection || 1);
        const maxSelection = parseInt(comp.max_selection || 1);
        const isMultiple = maxSelection > 1;
        const inputType = isMultiple ? 'checkbox' : 'radio';
        
        let itemsHtml = '';
        // Check if there's only one item available - auto-select it to save time
        const hasSingleItem = comp.available_items && comp.available_items.length === 1;
        const autoSelectItem = hasSingleItem; // Auto-select when there's only one option (for both single and multiple selection)
        
        if (comp.available_items && comp.available_items.length > 0) {
            comp.available_items.forEach((item, itemIndex) => {
                const safeItemName = item.name.replace(/'/g, '&#39;').replace(/"/g, '&quot;');
                const safeItemNameJs = item.name.replace(/'/g, "\\'").replace(/"/g, '\\"');
                const itemPrice = parseFloat(item.retail_price || 0).toFixed(2);
                const isAutoSelected = autoSelectItem && itemIndex === 0;
                const cardClass = isAutoSelected ? 'border-primary bg-light' : '';
                const checkedAttr = isAutoSelected ? 'checked' : '';
                
                itemsHtml += `
                    <div class="col-md-3 col-sm-4 col-6 mb-2">
                        <div class="card deal-item-card ${cardClass}" style="cursor: pointer; min-height: 100px; transition: all 0.2s;" data-component-index="${index}" data-item-id="${item.id}" data-item-name="${safeItemName}" data-item-price="${item.retail_price || 0}">
                            <div class="card-body p-2 text-center">
                                <div class="form-check d-flex align-items-center justify-content-center mb-1">
                                    <input class="form-check-input deal-item-checkbox" type="${inputType}" name="deal_component_${index}${isMultiple ? '[]' : ''}" id="deal_item_${index}_${item.id}" ${checkedAttr} data-component-index="${index}" data-item-id="${item.id}" data-item-name="${safeItemNameJs}" data-item-price="${item.retail_price || 0}">
                                    <label class="form-check-label ms-2 flex-grow-1" for="deal_item_${index}_${item.id}" style="cursor: pointer;">
                                        <strong style="font-size: 0.9rem;">${item.name}</strong>
                                    </label>
                                </div>
                                <small class="text-muted">Rs ${itemPrice}</small>
                            </div>
                        </div>
                    </div>
                `;
                
                // Auto-select the single item
                if (isAutoSelected) {
                    if (isMultiple) {
                        window.dealSelections[index] = [{
                            id: item.id,
                            name: item.name,
                            price: parseFloat(item.retail_price || 0)
                        }];
                    } else {
                        window.dealSelections[index] = {
                            id: item.id,
                            name: item.name,
                            price: parseFloat(item.retail_price || 0)
                        };
                    }
                }
            });
        } else if (comp.selection_type === 'item' && comp.item_id) {
            // Pre-select the single item
            const safeItemName = comp.item_name.replace(/'/g, '&#39;').replace(/"/g, '&quot;');
            const safeItemNameJs = comp.item_name.replace(/'/g, "\\'").replace(/"/g, '\\"');
            const itemPrice = parseFloat(comp.retail_price || 0).toFixed(2);
            itemsHtml += `
                <div class="col-md-3 col-sm-4 col-6 mb-2">
                    <div class="card deal-item-card border-primary bg-light" style="cursor: pointer; min-height: 100px; transition: all 0.2s;" data-component-index="${index}" data-item-id="${comp.item_id}" data-item-name="${safeItemName}" data-item-price="${comp.retail_price || 0}">
                        <div class="card-body p-2 text-center">
                            <div class="form-check d-flex align-items-center justify-content-center mb-1">
                                <input class="form-check-input deal-item-checkbox" type="${inputType}" name="deal_component_${index}${isMultiple ? '[]' : ''}" id="deal_item_${index}_${comp.item_id}" checked data-component-index="${index}" data-item-id="${comp.item_id}" data-item-name="${safeItemNameJs}" data-item-price="${comp.retail_price || 0}">
                                <label class="form-check-label ms-2 flex-grow-1" for="deal_item_${index}_${comp.item_id}" style="cursor: pointer;">
                                    <strong style="font-size: 0.9rem;">${comp.item_name}</strong>
                                </label>
                            </div>
                            <small class="text-muted">Rs ${itemPrice}</small>
                        </div>
                    </div>
                </div>
            `;
            if (isMultiple) {
                window.dealSelections[index] = [{
                    id: comp.item_id,
                    name: comp.item_name,
                    price: comp.retail_price || 0
                }];
            } else {
                window.dealSelections[index] = {
                    id: comp.item_id,
                    name: comp.item_name,
                    price: comp.retail_price || 0
                };
            }
        }
        
        // Show min/max selection info
        let selectionInfo = '';
        if (minSelection > 0 || maxSelection > 1) {
            if (minSelection === maxSelection) {
                selectionInfo = ` <small class="text-muted">(Select ${minSelection} ${minSelection === 1 ? 'item' : 'items'})</small>`;
            } else {
                selectionInfo = ` <small class="text-muted">(Select ${minSelection}-${maxSelection} items)</small>`;
            }
        }
        
        componentsHtml += `
            <div class="mb-4">
                <h6 class="mb-3"><strong>${selectionTypeLabel}${selectionInfo}</strong></h6>
                <div class="row g-2" id="deal-component-${index}" data-min-selection="${minSelection}" data-max-selection="${maxSelection}">
                    ${itemsHtml}
                </div>
            </div>
            <hr>
        `;
    });
    
    // Create modal HTML
    const modalHtml = `
        <div class="modal fade" id="dealSelectionModal" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header bg-primary text-white">
                        <h5 class="modal-title">
                            <i class="fas fa-gift"></i> Select Deal Items: ${safeName}
                        </h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body" style="max-height: 70vh; overflow-y: auto;">
                        <div class="alert alert-info mb-3">
                            <strong>Deal Price:</strong> Rs ${parseFloat(deal.deal_price).toFixed(2)}<br>
                            <small>Click on items below to select them for each component</small>
                        </div>
                        <div id="dealComponentsContainer">
                            ${componentsHtml}
                        </div>
                        <div class="mt-3 p-3 bg-light rounded">
                            <strong>Selected Items:</strong>
                            <div id="dealSelectedItemsPreview" class="mt-2">
                                <small class="text-muted">No items selected yet</small>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="button" class="btn btn-primary" id="confirmDealBtn" disabled>Add Deal to Cart</button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // Remove existing modal
    const existingModal = document.getElementById('dealSelectionModal');
    if (existingModal) {
        existingModal.remove();
    }
    
    // Add modal to body
    document.body.insertAdjacentHTML('beforeend', modalHtml);
    
    // Initialize Bootstrap modal
    const modal = new bootstrap.Modal(document.getElementById('dealSelectionModal'));
    modal.show();
    
    // Bind click events to cards and checkboxes after modal is shown
    setTimeout(() => {
        document.querySelectorAll('.deal-item-card').forEach(card => {
            card.addEventListener('click', function(e) {
                // Don't trigger if clicking directly on checkbox or label
                if (e.target.type === 'checkbox' || e.target.type === 'radio' || e.target.closest('label')) {
                    return;
                }
                
                const checkbox = this.querySelector('.deal-item-checkbox');
                if (checkbox) {
                    const componentIndex = parseInt(checkbox.dataset.componentIndex);
                    const itemId = parseInt(checkbox.dataset.itemId);
                    const itemName = checkbox.dataset.itemName;
                    const itemPrice = parseFloat(checkbox.dataset.itemPrice || 0);
                    const isMultiple = checkbox.type === 'checkbox';
                    
                    // Toggle checkbox state
                    checkbox.checked = !checkbox.checked;
                    
                    if (checkbox.checked) {
                        selectDealItem(componentIndex, itemId, itemName, itemPrice, isMultiple);
                    } else {
                        deselectDealItem(componentIndex, itemId);
                    }
                }
            });
        });
        
        document.querySelectorAll('.deal-item-checkbox').forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                const componentIndex = parseInt(this.dataset.componentIndex);
                const itemId = parseInt(this.dataset.itemId);
                const itemName = this.dataset.itemName;
                const itemPrice = parseFloat(this.dataset.itemPrice || 0);
                
                // Get component info to check if multiple selection is allowed
                const componentDiv = document.getElementById(`deal-component-${componentIndex}`);
                const maxSelection = parseInt(componentDiv?.dataset.maxSelection || 1);
                
                if (this.checked) {
                    selectDealItem(componentIndex, itemId, itemName, itemPrice, true);
                } else {
                    deselectDealItem(componentIndex, itemId);
                }
            });
        });
        
        // Bind confirm button click event
        const confirmBtn = document.getElementById('confirmDealBtn');
        if (confirmBtn) {
            confirmBtn.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                confirmDealSelection();
            });
        }
    }, 100);
    
    // Add hover effect styles
    const style = document.createElement('style');
    style.textContent = `
        .deal-item-card:hover {
            border-color: #0d6efd !important;
            box-shadow: 0 0 0 0.2rem rgba(13, 110, 253, 0.25);
            transform: translateY(-2px);
        }
        .deal-item-card.border-primary {
            border-width: 2px !important;
        }
    `;
    document.head.appendChild(style);
    
    // Update preview
    updateDealPreview();
    
    // Clean up on hide
    document.getElementById('dealSelectionModal').addEventListener('hidden.bs.modal', function() {
        this.remove();
        window.dealModalData = null;
        window.dealSelections = null;
        if (style && style.parentNode) {
            style.parentNode.removeChild(style);
        }
    });
}

// Function to select deal item (called when clicking on item card or checkbox)
function selectDealItem(componentIndex, itemId, itemName, itemPrice, isCheckbox = false) {
    const componentDiv = document.getElementById(`deal-component-${componentIndex}`);
    if (!componentDiv) return;
    
    const maxSelection = parseInt(componentDiv.dataset.maxSelection || 1);
    const minSelection = parseInt(componentDiv.dataset.minSelection || 1);
    const isMultiple = maxSelection > 1;
    
    if (!isMultiple && !isCheckbox) {
        // Single selection mode - uncheck all others first
        document.querySelectorAll(`input[name="deal_component_${componentIndex}"]`).forEach(cb => {
            cb.checked = false;
        });
        window.dealSelections[componentIndex] = null;
        
        // Remove selected class from all cards
        document.querySelectorAll(`#deal-component-${componentIndex} .deal-item-card`).forEach(card => {
            card.classList.remove('border-primary', 'border-success', 'bg-light');
        });
    } else if (isMultiple) {
        // Multiple selection mode - check if we've reached max
        const currentSelections = Array.isArray(window.dealSelections[componentIndex]) ? window.dealSelections[componentIndex] : [];
        if (currentSelections.length >= maxSelection) {
            Swal.fire({
                icon: 'warning',
                title: 'Maximum Selection Reached',
                text: `You can select maximum ${maxSelection} item(s) for this component.`,
                timer: 2000,
                showConfirmButton: false
            });
            return;
        }
        
        // Check if already selected
        const exists = currentSelections.some(item => item.id === parseInt(itemId));
        if (exists) return;
    }
    
    // Check the selected item checkbox
    const checkbox = document.getElementById(`deal_item_${componentIndex}_${itemId}`);
    if (checkbox) {
        checkbox.checked = true;
    }
    
    // Add selected class to the clicked card
    const selectedCard = document.querySelector(`#deal-component-${componentIndex} .deal-item-card[data-item-id="${itemId}"]`);
    if (selectedCard) {
        selectedCard.classList.add('border-primary', 'bg-light');
    }
    
    // Update selections
    const itemData = {
        id: parseInt(itemId),
        name: itemName,
        price: parseFloat(itemPrice || 0)
    };
    
    if (isMultiple) {
        if (!Array.isArray(window.dealSelections[componentIndex])) {
            window.dealSelections[componentIndex] = [];
        }
        window.dealSelections[componentIndex].push(itemData);
    } else {
        window.dealSelections[componentIndex] = itemData;
    }
    
    updateDealPreview();
}

// Function to deselect deal item
function deselectDealItem(componentIndex, itemId) {
    const componentDiv = document.getElementById(`deal-component-${componentIndex}`);
    if (!componentDiv) return;
    
    const maxSelection = parseInt(componentDiv.dataset.maxSelection || 1);
    const isMultiple = maxSelection > 1;
    
    if (isMultiple && Array.isArray(window.dealSelections[componentIndex])) {
        window.dealSelections[componentIndex] = window.dealSelections[componentIndex].filter(
            item => item.id !== parseInt(itemId)
        );
    } else {
        window.dealSelections[componentIndex] = null;
    }
    
    // Remove selected class from the card
    const selectedCard = document.querySelector(`#deal-component-${componentIndex} .deal-item-card[data-item-id="${itemId}"]`);
    if (selectedCard) {
        selectedCard.classList.remove('border-primary', 'bg-light');
    }
    
    updateDealPreview();
}

// Function to update deal preview
function updateDealPreview() {
    const previewDiv = document.getElementById('dealSelectedItemsPreview');
    const confirmBtn = document.getElementById('confirmDealBtn');
    
    const selectedItems = [];
    let allValid = true;
    const validationErrors = [];
    
    for (let i = 0; i < window.dealModalData.deal.components.length; i++) {
        const comp = window.dealModalData.deal.components[i];
        const minSelection = parseInt(comp.min_selection || 1);
        const maxSelection = parseInt(comp.max_selection || 1);
        const selection = window.dealSelections[i];
        
        if (maxSelection > 1) {
            // Multiple selection component
            const selectedCount = Array.isArray(selection) ? selection.length : 0;
            if (selectedCount < minSelection || selectedCount > maxSelection) {
                allValid = false;
                validationErrors.push(`${comp.category_name || comp.subcategory_name || comp.item_name}: Need ${minSelection}-${maxSelection} items (selected: ${selectedCount})`);
            } else if (selectedCount > 0) {
                selectedItems.push(...selection.map(item => item.name));
            }
        } else {
            // Single selection component
            if (!selection || !selection.id) {
                allValid = false;
                validationErrors.push(`${comp.category_name || comp.subcategory_name || comp.item_name}: Selection required`);
            } else {
                selectedItems.push(selection.name);
            }
        }
    }
    
    if (selectedItems.length > 0) {
        previewDiv.innerHTML = `<small>${selectedItems.join(', ')}</small>`;
        if (validationErrors.length > 0) {
            previewDiv.innerHTML += `<br><small class="text-warning">⚠ ${validationErrors.join('; ')}</small>`;
        }
    } else {
        previewDiv.innerHTML = '<small class="text-muted">No items selected yet</small>';
    }
    
    // Enable/disable confirm button
    if (confirmBtn) {
        confirmBtn.disabled = !allValid;
    }
}

// Function to confirm deal selection and add to cart
window.confirmDealSelection = function() {
    try {
        if (!window.dealModalData || !window.dealSelections) {
            console.error('Deal modal data not found');
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'Unable to process deal selection. Please try again.'
            });
            return;
        }
        
    // Verify all components are selected with min/max validation
    let allValid = true;
    const selectedItemsList = [];
    const validationErrors = [];
    
    for (let i = 0; i < window.dealModalData.deal.components.length; i++) {
        const comp = window.dealModalData.deal.components[i];
        const minSelection = parseInt(comp.min_selection || 1);
        const maxSelection = parseInt(comp.max_selection || 1);
        const selection = window.dealSelections[i];
        
        if (maxSelection > 1) {
            // Multiple selection component
            const selectedCount = Array.isArray(selection) ? selection.length : 0;
            if (selectedCount < minSelection || selectedCount > maxSelection) {
                allValid = false;
                validationErrors.push(`${comp.category_name || comp.subcategory_name || comp.item_name}: Need ${minSelection}-${maxSelection} items (selected: ${selectedCount})`);
            } else if (selectedCount > 0) {
                selectedItemsList.push(...selection);
            }
        } else {
            // Single selection component
            if (!selection || !selection.id) {
                allValid = false;
                validationErrors.push(`${comp.category_name || comp.subcategory_name || comp.item_name}: Selection required`);
            } else {
                selectedItemsList.push(selection);
            }
        }
    }
    
    if (!allValid) {
        Swal.fire({
            icon: 'warning',
            title: 'Invalid Selection',
            html: 'Please select items correctly for all components:<br><br>' + validationErrors.join('<br>')
        });
        return;
    }
        
        // Get deal data before closing modal
        const deal = window.dealModalData.deal;
        const dealPrice = parseFloat(deal.deal_price);
        const dealName = deal.deal_name;
        const itemId = window.dealModalData.itemId;
        const code = window.dealModalData.code;
        const taxType = window.dealModalData.taxType;
        const taxRate = window.dealModalData.taxRate;
        const isSerialized = window.dealModalData.isSerialized;
        const itemMeta = window.dealModalData.itemMeta;
        
    // Create display name with selected items
    // Handle both single items and arrays of items
    const selectedItemsNames = selectedItemsList.map(item => {
        if (Array.isArray(item)) {
            return item.map(i => i.name).join(', ');
        }
        return item.name;
    }).join(', ');
    const displayName = `${dealName} (${selectedItemsNames})`;
        
        // Close modal first
        const modal = bootstrap.Modal.getInstance(document.getElementById('dealSelectionModal'));
        if (modal) {
            modal.hide();
        }
        
        // Add to cart using deal price (not individual item prices)
        if (typeof addItemToCart === 'function') {
            addItemToCart(
                itemId,
                displayName,
                dealPrice,
                code,
                taxType,
                taxRate,
                [], // No modifiers
                isSerialized,
                [],
                itemMeta || {}
            );
            
            // Mark cart item as deal and store selections
            // Wait a moment for the item to be added to cart
            setTimeout(() => {
                const cartWrap = document.querySelector('.product-wrap');
                if (cartWrap) {
                    const addedRow = cartWrap.querySelector(`[data-code="${code}"]`);
                    if (addedRow) {
                        // Store the full selection structure (preserving component grouping)
                        addedRow.setAttribute('data-is-deal', '1');
                        addedRow.setAttribute('data-deal-selections', JSON.stringify(window.dealSelections));
                        addedRow.setAttribute('data-deal-id', deal.id);
                        addedRow.setAttribute('data-deal-name', dealName);
                        
                        // Update display to show deal name prominently with items small
                        const infoDiv = addedRow.querySelector('.info h6');
                        if (infoDiv) {
                            infoDiv.innerHTML = `<strong>${dealName}</strong> <small class="text-muted">(${selectedItemsNames})</small>`;
                        }
                    } else {
                        console.warn('Cart item not found after adding deal');
                    }
                } else {
                    console.warn('Cart wrap not found');
                }
            }, 200);
        } else {
            console.error('addItemToCart function not found');
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'Unable to add item to cart. Please try again.'
            });
        }
        
        // Clean up after a delay to ensure everything is processed
        setTimeout(() => {
            window.dealModalData = null;
            window.dealSelections = null;
        }, 500);
        
    } catch (error) {
        console.error('Error in confirmDealSelection:', error);
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'An error occurred while adding the deal to cart. Please try again.'
        });
    }
};

// Also create as regular function for inline onclick compatibility
function confirmDealSelection() {
    if (window.confirmDealSelection) {
        window.confirmDealSelection();
    }
}

function bindCartRowSelection(row) {
    if (!row) return;
    row.addEventListener('click', (event) => {
        if (event.target.closest('.btn-icon')) {
            return;
        }
        setActiveCartRow(row);
    });
}

function bindBulkToggle(row) {
    if (!row) return;
    const toggleBtn = row.querySelector('.bulk-toggle-btn');
    if (!toggleBtn) return;
    toggleBtn.addEventListener('click', (event) => {
        event.preventDefault();
        event.stopPropagation();
        toggleCartRowMode(row);
    });
}

function toggleCartRowMode(row) {
    if (!row) return;
    const currentMode = row.getAttribute('data-sale-mode') || 'loose';
    const targetMode = currentMode === 'bulk' ? 'loose' : 'bulk';
    setRowSaleMode(row, targetMode);
    setActiveCartRow(row);
}

function setRowSaleMode(row, targetMode) {
    if (!row) return false;
    const saleMode = targetMode === 'bulk' ? 'bulk' : 'loose';
    const hasBulkMode = row.getAttribute('data-has-bulk-mode') === '1';
    if (saleMode === 'bulk' && !hasBulkMode) {
        notifyBulkUnavailable();
        return false;
    }

    const qtyInput = row.querySelector('input[name="qty"]');
    const bulkQty = parseFloat(row.getAttribute('data-bulk-qty')) || 0;
    const retailUnitPrice = parseFloat(row.getAttribute('data-retail-unit-price')) || parseFloat(row.getAttribute('data-price')) || 0;
    const bulkPackPrice = parseFloat(row.getAttribute('data-bulk-pack-price')) || 0;
    const bulkPerUnitPrice = parseFloat(row.getAttribute('data-bulk-per-unit-price')) || (bulkQty > 0 ? bulkPackPrice / bulkQty : 0);
    const currentQty = qtyInput ? parseFloat(qtyInput.value) || 0 : 0;

    if (saleMode === 'bulk') {
        if (!(bulkQty > 0 && bulkPackPrice > 0)) {
            notifyBulkUnavailable();
            return false;
        }

        const perUnit = bulkPerUnitPrice || (bulkPackPrice / bulkQty);
        row.setAttribute('data-price', perUnit.toFixed(4));
        row.setAttribute('data-sale-mode', 'bulk');

        if (qtyInput) {
            const packs = Math.max(1, Math.round(currentQty / (bulkQty || 1)));
            qtyInput.value = formatQuantity(packs * bulkQty);
        }
    } else {
        row.setAttribute('data-price', retailUnitPrice.toFixed(4));
        row.setAttribute('data-sale-mode', 'loose');

        if (qtyInput) {
            const normalized = normalizeQuantity(qtyInput.value, POS_QTY_MIN);
            qtyInput.value = formatQuantity(normalized);
        }
    }

    refreshSaleModeUI(row);
    updateTotal();
    return true;
}

function notifyBulkUnavailable() {
    if (typeof Swal !== 'undefined') {
        Swal.fire({
            icon: 'info',
            title: 'Bulk Details Missing',
            text: 'Bulk quantity/price is not configured for this item.',
            timer: 1800,
            showConfirmButton: false
        });
    }
}

function refreshSaleModeUI(row) {
    if (!row) return;
    const saleMode = row.getAttribute('data-sale-mode') || 'loose';
    const toggleBadge = row.querySelector('.bulk-toggle-btn .sale-mode-label');
    if (toggleBadge) {
        if (saleMode === 'bulk') {
            toggleBadge.textContent = 'Bulk';
            toggleBadge.className = 'badge bg-primary sale-mode-label';
        } else {
            toggleBadge.textContent = 'Loose';
            toggleBadge.className = 'badge bg-secondary sale-mode-label';
        }
    }

    const qtyInput = row.querySelector('input[name="qty"]');
    if (qtyInput) {
        const inputStep = getRowInputStep(row); // Use input step for HTML attribute (allows decimals)
        const incrementStep = getRowQuantityStep(row); // Use increment step for +/- buttons
        qtyInput.step = inputStep;
        qtyInput.min = saleMode === 'bulk' ? incrementStep : POS_QTY_MIN;
    }
}

function updateRowPriceDisplay(row, discountInfo = null) {
    if (!row) return;
    const priceDisplay = row.querySelector('.price-display');
    if (!priceDisplay) return;

    const saleMode = row.getAttribute('data-sale-mode') || 'loose';
    const bulkQty = parseFloat(row.getAttribute('data-bulk-qty')) || 0;
    const unitPrice = parseFloat(row.getAttribute('data-price')) || 0;
    const discountPerUnit = discountInfo ? discountInfo.perUnit : 0;
    const effectiveUnitPrice = Math.max(0, unitPrice - discountPerUnit);

    if (saleMode === 'bulk' && bulkQty > 0) {
        const currentPackPrice = effectiveUnitPrice * bulkQty;
        const originalPackPrice = unitPrice * bulkQty;
        if (discountPerUnit > 0) {
            priceDisplay.innerHTML = `Rs ${currentPackPrice.toFixed(2)} (Bulk) <span class="text-muted" style="text-decoration: line-through; font-size: 0.85em;">Rs ${originalPackPrice.toFixed(2)}</span>`;
        } else {
            priceDisplay.textContent = `Rs ${currentPackPrice.toFixed(2)} (Bulk)`;
        }
    } else {
        if (discountPerUnit > 0) {
            priceDisplay.innerHTML = `Rs ${effectiveUnitPrice.toFixed(2)} (Loose) <span class="text-muted" style="text-decoration: line-through; font-size: 0.85em;">Rs ${unitPrice.toFixed(2)}</span>`;
        } else {
            priceDisplay.textContent = `Rs ${unitPrice.toFixed(2)} (Loose)`;
        }
    }
}

function getRowQuantityStep(row) {
    if (!row) return 1; // Default increment step for loose items is 1
    const saleMode = row.getAttribute('data-sale-mode') || 'loose';
    if (saleMode === 'bulk') {
        const bulkQty = parseFloat(row.getAttribute('data-bulk-qty')) || 0;
        return bulkQty > 0 ? bulkQty : 1; // For bulk, return bulk pack size, default to 1
    }
    return 1; // For loose items, increment/decrement step is 1 (not decimal)
}

function getRowInputStep(row) {
    // Returns the HTML input step attribute value (allows decimal entry)
    if (!row) return POS_QTY_STEP;
    const saleMode = row.getAttribute('data-sale-mode') || 'loose';
    if (saleMode === 'bulk') {
        const bulkQty = parseFloat(row.getAttribute('data-bulk-qty')) || 0;
        return bulkQty > 0 ? bulkQty : POS_QTY_STEP;
    }
    return POS_QTY_STEP; // For loose items, allow decimal entry (0.01 step)
}

function increaseRowQuantity(row, multiplier = 1) {
    if (!row) return;
    const qtyInput = row.querySelector('input[name="qty"]');
    if (!qtyInput) return;
    const step = getRowQuantityStep(row);
    const fallback = step || POS_QTY_MIN;
    const current = parseFloat(qtyInput.value) || fallback;
    const newValue = current + (step * multiplier);
    qtyInput.value = formatQuantity(normalizeQuantity(newValue, fallback));
    setActiveCartRow(row);
    updateTotal();
}

function decreaseRowQuantity(row, multiplier = 1) {
    if (!row) return;
    const qtyInput = row.querySelector('input[name="qty"]');
    if (!qtyInput) return;
    const step = getRowQuantityStep(row);
    const fallback = step || POS_QTY_MIN;
    const current = parseFloat(qtyInput.value) || fallback;
    let newValue = current - (step * multiplier);
    const minValue = row.getAttribute('data-sale-mode') === 'bulk' ? fallback : POS_QTY_MIN;
    if (newValue < minValue) {
        newValue = minValue;
    }
    qtyInput.value = formatQuantity(normalizeQuantity(newValue, minValue));
    setActiveCartRow(row);
    updateTotal();
}

function adjustQuantityForMode(row, value) {
    if (!row) return formatQuantity(normalizeQuantity(value, POS_QTY_MIN));
    const saleMode = row.getAttribute('data-sale-mode') || 'loose';
    if (saleMode === 'bulk') {
        const step = getRowQuantityStep(row);
        const fallback = step || POS_QTY_MIN;
        const parsed = parseFloat(value);
        if (!isFinite(parsed) || parsed <= 0) {
            return formatQuantity(fallback);
        }
        const packs = Math.max(1, Math.round(parsed / step));
        return formatQuantity(packs * step);
    }
    return formatQuantity(normalizeQuantity(value, POS_QTY_MIN));
}

function setActiveCartRow(row) {
    document.querySelectorAll('.product-list.cart-row-selected').forEach(el => el.classList.remove('cart-row-selected'));
    if (row) {
        row.classList.add('cart-row-selected');
        activeCartRow = row;
    } else {
        activeCartRow = null;
    }
}

function handleRowRemoval(row) {
    if (activeCartRow === row) {
        setActiveCartRow(null);
    }
}

window.resetCartSelection = function() {
    setActiveCartRow(null);
};

document.addEventListener('keydown', function(event) {
    if (!event || typeof event.key === 'undefined') {
        return;
    }
    const lowerKey = String(event.key || '').toLowerCase();
    const target = event.target;
    if (target) {
        const tag = target.tagName ? target.tagName.toLowerCase() : '';
        const inputType = target.type ? target.type.toLowerCase() : '';
        if ((tag === 'input' || tag === 'textarea' || target.isContentEditable) && inputType !== 'number') {
            return;
        }
    }
    if (event.ctrlKey && lowerKey === 'b' && activeCartRow) {
        event.preventDefault();
        toggleCartRowMode(activeCartRow);
        return;
    }
    if (event.altKey && lowerKey === 't') {
        event.preventDefault();
        const recentsModal = document.getElementById('recents');
        if (recentsModal) {
            const modalInstance = new bootstrap.Modal(recentsModal);
            modalInstance.show();
        }
    }
    if (!event.ctrlKey && !event.altKey && event.key === '+') {
        event.preventDefault();
        const paymentBtn = document.getElementById('payment-btn');
        if (paymentBtn && !paymentBtn.disabled) {
            paymentBtn.click();
        }
    }
    if (event.ctrlKey && lowerKey === 's') {
        event.preventDefault();
        openQuickItemSearchModal();
    }
});

function openQuickItemSearchModal() {
    const searchModalEl = document.getElementById('quickProductSearchModal');
    if (!searchModalEl) return;
    const searchModal = bootstrap.Modal.getOrCreateInstance(searchModalEl);
    searchModal.show();
    initializeQuickItemSearchEvents();
    setTimeout(() => {
        const input = document.getElementById('item-search-input');
        if (input) {
            input.focus();
            input.select();
        }
    }, 200);
    fetchQuickItemSearchResults();
}

let quickItemSearchEventsBound = false;

function initializeQuickItemSearchEvents() {
    if (quickItemSearchEventsBound) return;
    const input = document.getElementById('item-search-input');
    const priceType = document.getElementById('item-search-price-type');
    const priceFilter = document.getElementById('item-search-price-filter');
    const refreshBtn = document.getElementById('item-search-refresh-btn');
    if (!input || !priceType || !priceFilter || !refreshBtn) return;

    quickItemSearchEventsBound = true;

    let debounceTimer = null;
    function debounceFetch() {
        if (debounceTimer) clearTimeout(debounceTimer);
        debounceTimer = setTimeout(fetchQuickItemSearchResults, 300);
    }

    input.addEventListener('input', debounceFetch);
    priceType.addEventListener('change', fetchQuickItemSearchResults);
    priceFilter.addEventListener('input', debounceFetch);
    refreshBtn.addEventListener('click', fetchQuickItemSearchResults);
}

let quickItemSearchAbortController = null;

function fetchQuickItemSearchResults() {
    if (quickItemSearchAbortController) {
        quickItemSearchAbortController.abort();
    }
    quickItemSearchAbortController = new AbortController();

    const searchTerm = document.getElementById('item-search-input')?.value || '';
    const priceType = document.getElementById('item-search-price-type')?.value || 'retail';
    const priceFilter = document.getElementById('item-search-price-filter')?.value || '';

    const priceHeading = document.getElementById('item-search-price-heading');
    if (priceHeading) {
        priceHeading.textContent = priceType === 'retail' ? 'Retail' : 'Cost';
    }

    const statusEl = document.getElementById('item-search-status');
    if (statusEl) {
        statusEl.textContent = 'Searching...';
    }

    const params = new URLSearchParams({
        search_term: searchTerm,
        price_type: priceType,
        price_filter: priceFilter
    });

    fetch('ajax/item_search_modal_fetch.php?' + params.toString(), { cache: 'no-store', signal: quickItemSearchAbortController.signal })
        .then(res => res.json())
        .then(data => {
            populateQuickItemSearchResults(data);
        })
        .catch(err => {
            console.error('Item search failed:', err);
            if (statusEl) statusEl.textContent = 'Error loading records.';
        });
}

function populateQuickItemSearchResults(data) {
    const tbody = document.getElementById('item-search-results');
    if (!tbody) return;

    if (!data || !Array.isArray(data.items) || data.items.length === 0) {
        tbody.innerHTML = `<tr><td colspan="3" class="text-center text-muted py-4">No items found.</td></tr>`;
        const statusEl = document.getElementById('item-search-status');
        if (statusEl) statusEl.textContent = '0 record(s) found.';
        return;
    }

    tbody.innerHTML = '';
    data.items.forEach(item => {
        const tr = document.createElement('tr');
        tr.className = 'quick-item-row';
        tr.dataset.itemId = item.id;
        tr.dataset.itemName = item.name;
        tr.dataset.itemCode = item.item_code || '';
        tr.dataset.itemPrice = item.price;
        tr.dataset.taxType = item.tax_type || 'excluded';
        tr.dataset.taxRate = item.tax_rate_id || 0;
        tr.dataset.itemType = item.item_type || 'loose';
        tr.dataset.bulkQty = item.bulk_qty || 0;
        tr.dataset.bulkPrice = item.bulk_price || 0;
        tr.dataset.isSerialized = item.is_serialized ? '1' : '0';

        tr.innerHTML = `
            <td>
                ${item.item_code ? `<span class="text-muted small">${item.item_code}</span><br>` : ''}
                ${item.name}
                ${typeof item.current_stock !== 'undefined' ? `<div class="small text-muted">Stock: ${item.current_stock}</div>` : ''}
            </td>
            <td>${item.category || '-'}</td>
            <td class="text-end">${parseFloat(item.price).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</td>
        `;

        tr.addEventListener('click', () => {
            addQuickSearchItemToCart(tr);
        });

        tbody.appendChild(tr);
    });

    const statusEl = document.getElementById('item-search-status');
    if (statusEl) statusEl.textContent = `${data.total || data.items.length} record(s) found.`;
}

function addQuickSearchItemToCart(row) {
    const itemId = row.dataset.itemId;
    const name = row.dataset.itemName;
    const price = parseFloat(row.dataset.itemPrice) || 0;
    const code = row.dataset.itemCode || '';
    const taxType = row.dataset.taxType || 'excluded';
    const taxRate = parseFloat(row.dataset.taxRate) || 0;
    const itemMeta = {
        itemType: row.dataset.itemType || 'loose',
        bulkQty: parseFloat(row.dataset.bulkQty) || 0,
        bulkPrice: parseFloat(row.dataset.bulkPrice) || 0
    };
    const isSerialized = row.dataset.isSerialized === '1';

    addItemToCart(itemId, name, price, code, taxType, taxRate, [], isSerialized, [], itemMeta);

    const modalEl = document.getElementById('quickProductSearchModal');
    if (modalEl) {
        const modalInstance = bootstrap.Modal.getInstance(modalEl);
        if (modalInstance) {
            modalInstance.hide();
        }
    }
}

// Function to add item to cart (with or without modifiers)
function addItemToCart(itemId, name, price, code, taxType, taxRate, selectedModifiers = [], isSerialized = false, serialIds = [], itemMeta = {}) {
  
  // Ensure price is a valid number
  const basePrice = parseFloat(price) || 0;
  
  // Calculate total price with modifiers
  let totalPrice = basePrice;
  let modifierText = '';
  
  selectedModifiers.forEach(modifier => {
    totalPrice += parseFloat(modifier.price_adjustment || 0);
    if (modifierText) modifierText += ', ';
    modifierText += modifier.name;
  });
  
  // Create unique code including modifiers for cart identification
  const modifierCode = selectedModifiers.map(m => m.id).sort().join('-');
  const uniqueCode = modifierCode ? `${code}-mod-${modifierCode}` : code;
  
  const existing = cartWrap.querySelector(`[data-code="${uniqueCode}"]`);

  if (existing) {
    if (serialIds.length > 0) {
      const existingSerialIds = JSON.parse(existing.getAttribute('data-serial-ids') || '[]');
      const mergedSerialIds = [...existingSerialIds, ...serialIds];
      existing.setAttribute('data-serial-ids', JSON.stringify(mergedSerialIds));
      
      const serialBtn = existing.querySelector('.serial-btn');
      if (serialBtn) {
        const badge = serialBtn.querySelector('.serial-badge');
        const qty = parseFloat(existing.querySelector('input[name="qty"]').value) || 1;
        if (badge) {
          badge.textContent = `${mergedSerialIds.length}/${qty}`;
          badge.className = 'serial-badge ms-1 badge bg-success';
        }
      }
    }

    increaseRowQuantity(existing);
    setActiveCartRow(existing);
    return;
  }

  const normalizedMeta = {
    itemType: (itemMeta && itemMeta.itemType ? String(itemMeta.itemType).toLowerCase() : 'loose'),
    bulkQty: parseFloat(itemMeta && itemMeta.bulkQty ? itemMeta.bulkQty : 0) || 0,
    bulkPrice: parseFloat(itemMeta && itemMeta.bulkPrice ? itemMeta.bulkPrice : 0) || 0
  };
  const modifierDelta = totalPrice - basePrice;
  let computedBulkPackPrice = normalizedMeta.bulkPrice;
  if (normalizedMeta.bulkQty > 0) {
    if (!isFinite(computedBulkPackPrice) || computedBulkPackPrice <= 0) {
      computedBulkPackPrice = basePrice * normalizedMeta.bulkQty;
    }
    computedBulkPackPrice += modifierDelta;
  }
  const hasBulkMode = normalizedMeta.bulkQty > 0 && computedBulkPackPrice > 0;
  const computedBulkPerUnit = hasBulkMode && normalizedMeta.bulkQty > 0
    ? (computedBulkPackPrice / normalizedMeta.bulkQty)
    : 0;

  const row = document.createElement('div');
    row.className = 'product-list d-flex align-items-center justify-content-between';
  row.setAttribute('data-code', uniqueCode);
  row.setAttribute('data-price', totalPrice.toFixed(4));
  row.setAttribute('data-base-price', basePrice);
    row.setAttribute('data-tax-type', taxType);
    row.setAttribute('data-tax-rate', taxRate);
    row.setAttribute('data-item-id', itemId);
  row.setAttribute('data-item-name', name); // Store full item name for saving
  row.setAttribute('data-modifiers', JSON.stringify(selectedModifiers));
  row.setAttribute('data-item-discount-type', 'none');
  row.setAttribute('data-item-discount-value', '0');
  row.setAttribute('data-item-discount-per-unit', '0');
  row.setAttribute('data-is-serialized', isSerialized ? '1' : '0');
  row.setAttribute('data-serial-ids', JSON.stringify(serialIds || [])); // Store selected serial IDs
  row.setAttribute('data-retail-unit-price', totalPrice.toFixed(4));
  row.setAttribute('data-bulk-pack-price', hasBulkMode ? computedBulkPackPrice.toFixed(4) : '0');
  row.setAttribute('data-bulk-per-unit-price', hasBulkMode && computedBulkPerUnit > 0 ? computedBulkPerUnit.toFixed(4) : '0');
  row.setAttribute('data-sale-mode', 'loose');
  row.setAttribute('data-retail-price', totalPrice);
  row.setAttribute('data-bulk-qty', hasBulkMode ? normalizedMeta.bulkQty : 0);
  row.setAttribute('data-has-bulk-mode', hasBulkMode ? '1' : '0');

  // Display name with modifiers
  const displayName = name; // Keep item name clean, modifiers will show separately

  // Serial button HTML (only for serialized items)
  const serialCount = serialIds && serialIds.length > 0 ? serialIds.length : 0;
  const serialBadgeText = serialCount > 0 ? `${serialCount}/1` : '0/0';
  const serialBadgeClass = serialCount > 0 ? 'badge bg-success' : '';
  const serialButton = isSerialized ? 
    `<a class="btn-icon serial-btn" href="#" title="Select Serial Numbers" data-item-id="${itemId}" data-item-name="${name.replace(/"/g, '&quot;')}" onclick="openSaleSerialModal(this, event)">
      <i data-feather="barcode"></i>
      <span class="serial-badge ms-1 ${serialBadgeClass}" style="font-size: 0.75em;">${serialBadgeText}</span>
    </a>` : '';
  const bulkToggleButton = hasBulkMode ? `
        <a class="btn-icon bulk-toggle-btn" href="#" title="Toggle Bulk / Loose">
          <span class="badge bg-secondary sale-mode-label">Loose</span>
        </a>` : '';

    row.innerHTML = `
      <div class="d-flex align-items-center product-info" style="cursor: pointer;">
        <div class="info">
        <h6 title="${displayName}">${displayName.length > 25 ? displayName.substring(0, 25) + '...' : displayName}</h6>
        <p class="price-display">Rs ${totalPrice.toFixed(2)} (Loose)</p>
        ${modifierText ? `<small class="text-muted">${modifierText}</small>` : ''}
        <div class="item-discount-info text-success small mt-1" style="display: none;"></div>
        <div class="remarks-section mt-1" style="display: none;">
          <small class="text-warning remarks-text"></small>
        </div>
        </div>
      </div>
      <div class="qty-item text-center">
        <a href="#" class="dec"><i data-feather="minus-circle"></i></a>
        <input 
          type="number" 
          inputmode="decimal" 
          step="${POS_QTY_STEP}" 
          min="${POS_QTY_MIN}" 
          class="form-control text-center" 
          name="qty" 
          value="${formatQuantity(1)}"
          data-input-step="${POS_QTY_STEP}">
        <a href="#" class="inc"><i data-feather="plus-circle"></i></a>
      </div>
      <div class="d-flex align-items-center action">
        <a class="btn-icon price-edit-icon" href="#" title="Edit Price" style="display: none;">•••</a>
        <a class="btn-icon template-icon" href="#" title="Add Template" data-item-id="${itemId}" onclick="showTemplateSelectionModal(${itemId}, event)">
          <i data-feather="layers"></i>
        </a>
        ${bulkToggleButton}
        ${serialButton}
        <a class="btn-icon delete-icon" href="#"><i data-feather="trash-2"></i></a>
      </div>
    `;

    // Add new item at the top (descending order) instead of bottom
    cartWrap.insertBefore(row, cartWrap.firstChild);
    
    // Scroll to top to show the newly added item
    cartWrap.scrollTop = 0;
    
    bindQtyEvents(row);
    bindCartRowSelection(row);
    bindBulkToggle(row);
    refreshSaleModeUI(row);
    setActiveCartRow(row);
    
    // Replace feather icons only for the new row (safely)
    setTimeout(() => {
        if (typeof feather !== 'undefined' && feather.replace) {
            try {
                const rowIcons = row.querySelectorAll('[data-feather]');
                if (rowIcons.length > 0) {
                    feather.replace({ scope: row });
                }
            } catch (e) {
                console.warn('Feather icon replacement failed:', e);
            }
        }
    }, 50);
    
    updateTotal();
}

// Function to show modifier selection modal
function showModifierModal(itemId, name, price, code, taxType, taxRate, modifierGroups, isSerialized = false, itemMeta = {}) {
  
  // Store item data globally for the modal
  window.modifierModalData = {
    itemId: itemId,
    name: name,
    price: price,
    code: code,
    taxType: taxType,
    taxRate: taxRate,
    isSerialized: isSerialized,
    itemMeta: itemMeta || {}
  };
  
  // Escape name for safe HTML insertion
  const safeName = name.replace(/'/g, '&#39;').replace(/"/g, '&quot;');
  
  // Create modal HTML
  const modalHtml = `
    <div class="modal fade" id="modifierModal" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">Customize: ${safeName}</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body">
            <div class="text-center mb-3">
              <h6>Base Price: Rs ${price.toFixed(2)}</h6>
              <h5 id="totalPriceDisplay">Total: Rs ${price.toFixed(2)}</h5>
            </div>
            <div id="modifierGroupsContainer">
              ${modifierGroups.map(group => createModifierGroupHtml(group)).join('')}
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
            <button type="button" class="btn btn-primary" id="confirmModifierBtn">Add to Cart</button>
          </div>
        </div>
      </div>
    </div>
  `;
  
  // Remove existing modal
  const existingModal = document.getElementById('modifierModal');
  if (existingModal) {
    existingModal.remove();
  }
  
  // Add modal to body
  document.body.insertAdjacentHTML('beforeend', modalHtml);
  
  // Bind the confirm button event
  document.getElementById('confirmModifierBtn').addEventListener('click', function() {
    confirmModifierSelection();
  });
  
  // Show modal
  const modalElement = document.getElementById('modifierModal');
  const modal = new bootstrap.Modal(modalElement);
  modal.show();
  
  // Bind change events
  bindModifierEvents();
}

// Function to create HTML for modifier group
function createModifierGroupHtml(group) {
  const isRequired = group.is_required == 1;
  const isMultiple = group.is_multiple_choice == 1;
  
  return `
    <div class="card mb-3" data-group-id="${group.id}">
      <div class="card-header">
        <h6 class="mb-0">
          ${group.display_name} 
          ${isRequired ? '<span class="badge bg-danger ms-2">Required</span>' : '<span class="badge bg-secondary ms-2">Optional</span>'}
          ${isMultiple ? '<span class="badge bg-info ms-1">Multiple Choice</span>' : '<span class="badge bg-primary ms-1">Single Choice</span>'}
        </h6>
        ${group.description ? `<small class="text-muted">${group.description}</small>` : ''}
      </div>
      <div class="card-body">
        ${group.modifiers.map(modifier => createModifierOptionHtml(modifier, group)).join('')}
      </div>
    </div>
  `;
}

// Function to create HTML for individual modifier option
function createModifierOptionHtml(modifier, group) {
  const inputType = group.is_multiple_choice == 1 ? 'checkbox' : 'radio';
  const inputName = group.is_multiple_choice == 1 ? `group_${group.id}[]` : `group_${group.id}`;
  const priceText = modifier.price_adjustment > 0 ? `+Rs ${modifier.price_adjustment}` : 
                   modifier.price_adjustment < 0 ? `-Rs ${Math.abs(modifier.price_adjustment)}` : '';
  
  return `
    <div class="form-check mb-2">
      <input class="form-check-input modifier-option" type="${inputType}" 
             name="${inputName}" value="${modifier.id}" id="modifier_${modifier.id}"
             data-price="${modifier.price_adjustment}" data-group-id="${group.id}"
             ${modifier.is_default == 1 ? 'checked' : ''}>
      <label class="form-check-label d-flex justify-content-between align-items-center" for="modifier_${modifier.id}">
        <span>${modifier.name}</span>
        ${priceText ? `<span class="text-success">${priceText}</span>` : ''}
      </label>
    </div>
  `;
}

// Function to bind modifier selection events
function bindModifierEvents() {
  document.querySelectorAll('.modifier-option').forEach(input => {
    input.addEventListener('change', updateModifierTotal);
  });
  
  // Set initial total
  updateModifierTotal();
}

// Function to update total price based on selected modifiers
function updateModifierTotal() {
  const basePrice = parseFloat(document.querySelector('#modifierModal .modal-body h6').textContent.match(/Rs ([\d.]+)/)[1]);
  let totalPrice = basePrice;
  
  document.querySelectorAll('.modifier-option:checked').forEach(input => {
    totalPrice += parseFloat(input.dataset.price || 0);
  });
  
  document.getElementById('totalPriceDisplay').textContent = `Total: Rs ${totalPrice.toFixed(2)}`;
}

// Function to confirm modifier selection and add to cart
function confirmModifierSelection() {
  
  // Get item data from global storage
  const data = window.modifierModalData;
  if (!data) {
    console.error('No modifier modal data found');
    return;
  }
  
  const selectedModifiers = [];
  
  // Validate required groups
  const requiredGroups = document.querySelectorAll('[data-group-id] .card-header .badge.bg-danger');
  for (let badge of requiredGroups) {
    const groupCard = badge.closest('[data-group-id]');
    const groupId = groupCard.dataset.groupId;
    const hasSelection = groupCard.querySelector('.modifier-option:checked');
    
    if (!hasSelection) {
      const groupName = groupCard.querySelector('.card-header h6').textContent.trim();
      alert(`Please select an option for: ${groupName}`);
      return;
    }
  }
  
  // Collect selected modifiers
  document.querySelectorAll('.modifier-option:checked').forEach(input => {
    const modifier = {
      id: input.value,
      name: input.closest('.form-check').querySelector('label span').textContent,
      price_adjustment: parseFloat(input.dataset.price || 0),
      group_id: input.dataset.groupId
    };
    selectedModifiers.push(modifier);
  });
  
  // Close modal
  bootstrap.Modal.getInstance(document.getElementById('modifierModal')).hide();
  
  // Check if there are pending serial IDs (from serial selection before cart)
  const pendingSerialIds = window.pendingSerialIds || [];
  
  if (pendingSerialIds.length > 0) {
    // Add to cart with modifiers and serials
    addItemToCartWithSerials(data.itemId, data.name, data.price, data.code, data.taxType, data.taxRate, selectedModifiers, data.isSerialized || false, pendingSerialIds, data.itemMeta || {});
    delete window.pendingSerialIds;
  } else {
    // Add item to cart with modifiers (no pre-selected serials)
    addItemToCart(data.itemId, data.name, data.price, data.code, data.taxType, data.taxRate, selectedModifiers, data.isSerialized || false, [], data.itemMeta || {});
  }
}

function bindQtyEvents(row) {
    const qtyInput = row.querySelector('input[name="qty"]');
    if (!qtyInput) return;

    const incBtn = row.querySelector('.inc');
    const decBtn = row.querySelector('.dec');

    if (incBtn) {
        incBtn.addEventListener('click', () => {
            increaseRowQuantity(row, 1);
        });
    }

    if (decBtn) {
        decBtn.addEventListener('click', () => {
            decreaseRowQuantity(row, 1);
        });
    }
    
    qtyInput.addEventListener('focus', () => {
        setActiveCartRow(row);
    });
    
    // Handle manual quantity input - normalize on blur/change
    const normalizeHandler = () => {
        qtyInput.value = adjustQuantityForMode(row, qtyInput.value);
        updateTotal();
    };
    
    qtyInput.addEventListener('blur', normalizeHandler);
    qtyInput.addEventListener('change', normalizeHandler);
    
    // Allow typing decimals without interference - only update totals when value is valid
    qtyInput.addEventListener('input', () => {
        const parsed = parseFloat(qtyInput.value);
        if (isFinite(parsed) && parsed > 0) {
            updateTotal();
        }
    });

    row.querySelector('.delete-icon').addEventListener('click', async (e) => {
        e.preventDefault();
        // If working on a resumed/held order, require PIN once per session before allowing deletions
        if (window.unholdOrderId) {
            if (window.deletePinVerified === true) {
                // Ensure we have a deletion reason once per resumed session
                if (!window.deleteReasonId) {
                    try {
                        const res = await fetch('ajax/get_void_reasons.php');
                        const reasons = await res.json();
                        const options = {};
                        reasons.forEach(r => { options[r.id] = r.reason_name; });
                        const { value: reasonId } = await Swal.fire({
                            title: 'Select void reason',
                            input: 'select',
                            inputOptions: options,
                            inputPlaceholder: 'Choose a reason',
                            showCancelButton: true,
                            confirmButtonText: 'Confirm',
                            cancelButtonText: 'Skip',
                            allowOutsideClick: false
                        });
                        window.deleteReasonId = reasonId || window.deleteReasonId || null;
                        if (!window.deleteReasonId) {
                            // Try to default to seeded reason by name on server side if not set
                        }
                    } catch (_) {}
                }
                row.remove();
                updateTotal();
                handleRowRemoval(row);
            } else {
                if (typeof showPinVerification === 'function') {
                    showPinVerification('delete_item', async function() {
                        window.deletePinVerified = true;
                        // Prompt reason once per resumed session after successful PIN
                        if (!window.deleteReasonId) {
                            try {
                                const res = await fetch('ajax/get_void_reasons.php');
                                const reasons = await res.json();
                                const options = {};
                                reasons.forEach(r => { options[r.id] = r.reason_name; });
                                const { value: reasonId } = await Swal.fire({
                                    title: 'Select void reason',
                                    input: 'select',
                                    inputOptions: options,
                                    inputPlaceholder: 'Choose a reason',
                                    showCancelButton: true,
                                    confirmButtonText: 'Confirm',
                                    cancelButtonText: 'Skip',
                                    allowOutsideClick: false
                                });
                                window.deleteReasonId = reasonId || window.deleteReasonId || null;
                            } catch (_) {}
                        }
                        row.remove();
                        updateTotal();
                        handleRowRemoval(row);
                    });
                } else {
                    // Fallback: if PIN modal not available, block deletion on resumed orders
                    console.warn('PIN verification modal not found; blocking delete on resumed order');
                }
            }
        } else {
            // For new (not yet held) orders, allow deletion without PIN
                row.remove();
                updateTotal();
                handleRowRemoval(row);
        }
    });

    // Add remarks functionality - click on item itself
    row.querySelector('.product-info').addEventListener('click', (e) => {
        e.preventDefault();
        showItemOptionsModal(row);
    });
    
    // Add price editing functionality
    const priceEditIcon = row.querySelector('.price-edit-icon');
    if (priceEditIcon) {
        priceEditIcon.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
            showPriceEditModal(row);
        });
        
        // Show/hide price edit button based on user rights
        if (userCanEditPrice) {
            priceEditIcon.style.display = 'inline-block';
        } else {
            priceEditIcon.style.display = 'none';
        }
    }
}


    const discountInput = document.getElementById('discount-input');
    const discountType = document.getElementById('discount-type');
    let discountValue = 0;
    let discountMode = 'percent';

    if (discountInput && discountType) {
        discountInput.addEventListener('input', updateTotal);
        discountType.addEventListener('change', updateTotal);
    }

    // Add event listener for service charges
    const serviceChargesInput = document.getElementById('service-charges-input');
    if (serviceChargesInput) {
        serviceChargesInput.addEventListener('input', updateTotal);
    }

    // Add event listener for customer selection to apply customer discount
    const customerSelect = document.getElementById('top-customer-select');
    if (customerSelect) {
        customerSelect.addEventListener('change', function() {
            const selectedOption = this.options[this.selectedIndex];
            const discountApplied = selectedOption.getAttribute('data-discount-applied');
            const discountRate = parseFloat(selectedOption.getAttribute('data-discount-rate')) || 0;
            const withholdingRate = parseFloat(selectedOption.getAttribute('data-withholding-rate')) || 0;
            
            if (discountApplied === 'Y' && discountRate > 0) {
                // Store customer discount for later use
                window.customerDiscount = {
                    type: 'percent',
                    rate: discountRate,
                    source: 'customer'
                };
            } else {
                window.customerDiscount = null;
            }
            
            // Store customer withholding rate
            if (withholdingRate > 0) {
                window.customerWithholdingRate = withholdingRate;
            } else {
                window.customerWithholdingRate = 0;
            }
            
            // Update totals to include withholding
            if (typeof updateTotal === 'function') {
                updateTotal();
            }
        });
    }

    // Add event listener for discount selector button
    const discountSelectorBtn = document.getElementById('discount-selector-btn');
    if (discountSelectorBtn) {
        discountSelectorBtn.addEventListener('click', function() {
            openDiscountSelectionModal();
        });
    }

    // Global variables for tax calculation
    let currentPaymentMethod = 'cash';
    let taxCalculationMethod = window.taxCalculationMethod || 'item_wise'; // Use server value or default
    let discountTaxSequence = window.discountTaxSequence || 'before_tax';
    let showPaymentMethodTaxRatesSetting = false;
    let taxPreviewEnabled = true;
    
    // Initialize customer withholding rate
    if (typeof window.customerWithholdingRate === 'undefined') {
        window.customerWithholdingRate = 0;
    }

    function updateTotal() {
        let subtotal = 0, totalTax = 0, grandTotal = 0, itemDiscountTotal = 0;
        discountValue = parseFloat(discountInput?.value) || 0;
        discountMode = discountType?.value || 'percent';

        // If payment method tax is enabled, use server-side calculation
        if (taxCalculationMethod === 'payment_method') {
            updateTotalWithPaymentMethodTax();
            return;
        }

        cartWrap.querySelectorAll('.product-list').forEach(row => {
            const discountInfo = getRowDiscountInfo(row);
            updateRowDiscountAttributes(row, discountInfo);
            const price = discountInfo.price;
            const qty = normalizeQuantity(row.querySelector('input[name="qty"]').value, POS_QTY_MIN);
            const taxType = row.getAttribute('data-tax-type');
            const taxRate = parseFloat(row.getAttribute('data-tax-rate')) || 0;

            let basePrice = 0, taxAmount = 0, itemTotal = 0;
            const effectiveUnitPrice = Math.max(0, price - discountInfo.perUnit);
            const lineDiscountAmount = discountInfo.perUnit * qty;
            itemDiscountTotal += lineDiscountAmount;

            if (taxType === 'excluded') {
                basePrice = effectiveUnitPrice * qty;
                taxAmount = basePrice * (taxRate / 100);
                itemTotal = basePrice + taxAmount;
            } else if (taxType === 'included') {
                itemTotal = effectiveUnitPrice * qty;
                if (taxRate > 0) {
                    basePrice = itemTotal / (1 + taxRate / 100);
                } else {
                    basePrice = itemTotal;
                }
                taxAmount = itemTotal - basePrice;
            } else {
                basePrice = effectiveUnitPrice * qty;
                taxAmount = 0;
                itemTotal = basePrice;
            }

            subtotal += basePrice;
            totalTax += taxAmount;
            grandTotal += itemTotal;

            const discountDisplayEl = row.querySelector('.item-discount-info');
            if (discountDisplayEl) {
                if (lineDiscountAmount > 0) {
                    const perItemLabel = discountInfo.type === 'percent'
                        ? `${discountInfo.value}%`
                        : `Rs ${discountInfo.perUnit.toFixed(2)}`;
                    discountDisplayEl.style.display = 'block';
                    discountDisplayEl.textContent = `Discount: -Rs ${lineDiscountAmount.toFixed(2)} (${perItemLabel})`;
                } else {
                    discountDisplayEl.style.display = 'none';
                    discountDisplayEl.textContent = '';
                }
            }

            updateRowPriceDisplay(row, discountInfo);
        });

        const isAfterTaxDiscount = (discountTaxSequence === 'after_tax');
        const grossBeforeDiscount = subtotal + totalTax;

        // Apply discount
        let discountAmount = 0;
        const discountBase = isAfterTaxDiscount ? grossBeforeDiscount : subtotal;
        if (discountMode === 'percent') {
            discountAmount = discountBase * (discountValue / 100);
        } else if (discountMode === 'fixed') {
            discountAmount = discountValue;
        }
        const maxDiscount = isAfterTaxDiscount ? grossBeforeDiscount : subtotal;
        if (discountAmount > maxDiscount) discountAmount = maxDiscount;

        let discountedSubtotal = subtotal;
        let recalculatedTax = totalTax;
        let discountedGrandTotal = grossBeforeDiscount;

        if (isAfterTaxDiscount) {
            const subtotalDiscountPortion = Math.min(discountAmount, subtotal);
            discountedSubtotal = subtotal - subtotalDiscountPortion;
            discountedGrandTotal = grossBeforeDiscount - discountAmount;
        } else {
            discountedSubtotal = subtotal - discountAmount;
            if (discountAmount > 0 && subtotal > 0) {
                const discountRatio = discountedSubtotal / subtotal;
                recalculatedTax = totalTax * discountRatio;
            } else {
                recalculatedTax = totalTax;
            }
            discountedGrandTotal = discountedSubtotal + recalculatedTax;
        }

        // Calculate service charges (percentage after tax)
        const serviceChargesInput = document.getElementById('service-charges-input');
        const serviceChargesRate = parseFloat(serviceChargesInput?.value) || 0;
        // Service charges calculated as percentage of discounted grand total (after tax)
        const serviceCharges = serviceChargesRate > 0 ? (discountedGrandTotal * (serviceChargesRate / 100)) : 0;
        
        // Calculate withholding (on discounted subtotal + tax)
        const withholdingRate = window.customerWithholdingRate || 0;
        const withholdingBase = discountedSubtotal + recalculatedTax;
        const withholdingAmount = withholdingRate > 0 ? (withholdingBase * (withholdingRate / 100)) : 0;
        
        const finalTotal = discountedGrandTotal + serviceCharges + withholdingAmount;
        
        // Store base total (after tax, before service charges) for calculation when saving
        window.baseTotalForServiceCharges = discountedGrandTotal;

        subtotalEl.textContent = 'Rs ' + subtotal.toFixed(2);
        totalEl.textContent = 'Rs ' + finalTotal.toFixed(2);
        taxInput.value = recalculatedTax.toFixed(2) + ' Rs';
        const grandTotalLabel = (window.translations && window.translations.grand_total) ? window.translations.grand_total : 'Grand Total';
        totalDisplay.textContent = grandTotalLabel + ' : Rs ' + finalTotal.toFixed(2);
        
        // Update discount display
    const discountDisplay = document.getElementById('discount-display');
        if (discountDisplay) {
            discountDisplay.textContent = 'Rs ' + (discountAmount + itemDiscountTotal).toFixed(2);
        }

        // Update service charges display
        const serviceChargesDisplay = document.getElementById('service-charges-display');
        if (serviceChargesDisplay) {
            serviceChargesDisplay.textContent = 'Rs ' + serviceCharges.toFixed(2);
        }
        
        // Update withholding display
        const withholdingDisplay = document.getElementById('withholding-display');
        if (withholdingDisplay) {
            withholdingDisplay.textContent = 'Rs ' + withholdingAmount.toFixed(2);
        }
    }

    function updateTotalWithPaymentMethodTax() {
        const cartItems = [];
        let itemDiscountTotal = 0;
        document.querySelectorAll('.product-list').forEach(row => {
            const modifiers = row.getAttribute('data-modifiers') ? JSON.parse(row.getAttribute('data-modifiers')) : [];
            const discountInfo = getRowDiscountInfo(row);
            updateRowDiscountAttributes(row, discountInfo);
            const qty = normalizeQuantity(row.querySelector('input[name="qty"]').value, POS_QTY_MIN);
            const netUnitPrice = Math.max(0, discountInfo.price - discountInfo.perUnit);
            itemDiscountTotal += discountInfo.perUnit * qty;
            const serialIds = row.getAttribute('data-serial-ids') ? JSON.parse(row.getAttribute('data-serial-ids')) : [];
            
            // Handle deal items
            const isDeal = row.getAttribute('data-is-deal') === '1';
            let dealSelections = null;
            if (isDeal) {
                const dealSelectionsJson = row.getAttribute('data-deal-selections');
                if (dealSelectionsJson) {
                    try {
                        dealSelections = JSON.parse(dealSelectionsJson);
                    } catch (e) {
                        console.error('Error parsing deal selections:', e);
                    }
                }
            }
            
            cartItems.push({
                id: parseInt(row.getAttribute('data-item-id')) || 0,
                name: row.getAttribute('data-item-name') || row.querySelector('h6')?.textContent || '',
                price: netUnitPrice,
                original_price: discountInfo.price,
                qty: qty,
                tax_rate: parseFloat(row.getAttribute('data-tax-rate')) || 0,
                tax_type: row.getAttribute('data-tax-type') || 'excluded',
                modifiers: modifiers,
                serial_ids: serialIds,
                item_discount_type: discountInfo.type,
                item_discount_value: discountInfo.value,
                item_discount_per_unit: discountInfo.perUnit,
                item_discount_amount: discountInfo.perUnit * qty,
                is_deal: isDeal ? 1 : 0,
                deal_selections: dealSelections
            });

            updateRowPriceDisplay(row, discountInfo);
        });

        if (cartItems.length === 0) {
            subtotalEl.textContent = 'Rs 0.00';
            totalEl.textContent = 'Rs 0.00';
            taxInput.value = '0.00 Rs';
            const grandTotalLabel = (window.translations && window.translations.grand_total) ? window.translations.grand_total : 'Grand Total';
            totalDisplay.textContent = grandTotalLabel + ' : Rs 0.00';
            const discountDisplay = document.getElementById('discount-display');
            if (discountDisplay) {
                discountDisplay.textContent = 'Rs 0.00';
            }
            
            // Update service charges display
            const serviceChargesDisplay = document.getElementById('service-charges-display');
            if (serviceChargesDisplay) {
                serviceChargesDisplay.textContent = 'Rs 0.00';
            }
            
            // Update withholding display
            const withholdingDisplay = document.getElementById('withholding-display');
            if (withholdingDisplay) {
                withholdingDisplay.textContent = 'Rs 0.00';
            }
            return;
        }

        // Send AJAX request to calculate tax
        const formData = new FormData();
        formData.append('cart_json', JSON.stringify(cartItems));
        formData.append('payment_method', currentPaymentMethod);
        formData.append('discount_value', discountValue || 0);
        formData.append('discount_type', discountMode || 'percent');
        formData.append('withholding_rate', window.customerWithholdingRate || 0);

        fetch('ajax/calculate_tax.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Calculate service charges (percentage after tax)
                const serviceChargesInput = document.getElementById('service-charges-input');
                const serviceChargesRate = parseFloat(serviceChargesInput?.value) || 0;
                // Service charges calculated as percentage of total (after tax)
                // Store base total for calculation when saving
                window.baseTotalForServiceCharges = data.total;
                const serviceCharges = serviceChargesRate > 0 ? (data.total * (serviceChargesRate / 100)) : 0;
                const withholdingAmount = parseFloat(data.withholding_amount || 0);
                const finalTotal = data.total + serviceCharges;
                if (data.discount_sequence) {
                    discountTaxSequence = data.discount_sequence;
                    window.discountTaxSequence = discountTaxSequence;
                }

                subtotalEl.textContent = 'Rs ' + data.subtotal.toFixed(2);
                totalEl.textContent = 'Rs ' + finalTotal.toFixed(2);
                taxInput.value = data.tax_amount.toFixed(2) + ' Rs';
                const grandTotalLabel = (window.translations && window.translations.grand_total) ? window.translations.grand_total : 'Grand Total';
                totalDisplay.textContent = grandTotalLabel + ' : Rs ' + finalTotal.toFixed(2);
                
                // Update discount display
                const discountDisplay = document.getElementById('discount-display');
                if (discountDisplay) {
                    discountDisplay.textContent = 'Rs ' + (data.discount_amount + itemDiscountTotal).toFixed(2);
                }

                // Update service charges display
                const serviceChargesDisplay = document.getElementById('service-charges-display');
                if (serviceChargesDisplay) {
                    serviceChargesDisplay.textContent = 'Rs ' + serviceCharges.toFixed(2);
                }
                
                // Update withholding display
                const withholdingDisplay = document.getElementById('withholding-display');
                if (withholdingDisplay) {
                    withholdingDisplay.textContent = 'Rs ' + withholdingAmount.toFixed(2);
                }

                // Update payment method tax rate display
                updatePaymentMethodTaxDisplay(data.payment_tax_rate);
            }
        })
        .catch(error => {
            console.error('Error calculating tax:', error);
            // Fallback to original calculation
            updateTotal();
        });
    }

    function updatePaymentMethodTaxDisplay(taxRate) {
        const taxRateDisplay = document.getElementById('payment-tax-rate-display');
        if (!showPaymentMethodTaxRatesSetting) {
            if (taxRateDisplay) {
                taxRateDisplay.style.display = 'none';
            }
            return;
        }

        if (taxRateDisplay) {
            taxRateDisplay.textContent = `(${taxRate.toFixed(2)}%)`;
            taxRateDisplay.style.display = 'inline';
        }
    }

    function setPaymentMethod(method) {
        currentPaymentMethod = method;
        if (taxCalculationMethod === 'payment_method') {
            updateTotalWithPaymentMethodTax();
        }
    }

    // Calculate and display payment totals for all payment methods
    function calculateAndDisplayPaymentTotals(cartItems) {
        console.log('calculateAndDisplayPaymentTotals called with:', cartItems);
        
        // Get discount values
        const discountInputEl = document.getElementById('discount-input');
        const discountTypeEl = document.getElementById('discount-type');
        const discountValue = parseFloat(discountInputEl?.value) || 0;
        const discountType = discountTypeEl?.value || 'percent';
        
        console.log('Discount values:', { discountValue, discountType });
        
        if (!taxPreviewEnabled) {
            console.log('Tax preview disabled; hiding payment totals preview.');
            hidePaymentTotalsPreview();
            return;
        }
        
        // Get available payment methods and their tax rates
        fetch('ajax/get_tax_settings.php')
            .then(response => response.json())
            .then(data => {
                console.log('Tax settings response:', data);
                if (data.success) {
                    showPaymentMethodTaxRatesSetting = !!data.show_tax_rates;
                    taxPreviewEnabled = !!data.enable_preview;

                    window.showPaymentMethodTaxRatesSetting = showPaymentMethodTaxRatesSetting;
                    window.taxPreviewEnabled = taxPreviewEnabled;

                    if (!taxPreviewEnabled) {
                        console.log('Tax preview disabled via latest settings; hiding preview.');
                        hidePaymentTotalsPreview();
                        return;
                    }

                    if (data.payment_tax_rates) {
                        console.log('Calling displayPaymentTotals with rates:', data.payment_tax_rates);
                        displayPaymentTotals(cartItems, data.payment_tax_rates, discountValue, discountType);
                    } else {
                        console.log('No payment tax rates found in response');
                        hidePaymentTotalsPreview();
                    }
                } else {
                    console.log('Tax settings response unsuccessful');
                    hidePaymentTotalsPreview();
                }
            })
            .catch(error => {
                console.error('Error loading payment tax rates:', error);
                hidePaymentTotalsPreview();
            });
    }

    // Display payment totals in the modal
    function displayPaymentTotals(cartItems, paymentTaxRates, discountValue, discountType) {
        console.log('displayPaymentTotals called with:', { cartItems, paymentTaxRates, discountValue, discountType });
        
        const container = document.getElementById('payment-totals-container');
        const row = document.getElementById('payment-totals-row');
        
        console.log('Container elements:', { container, row });
        
        if (!container || !row) {
            console.log('Container or row not found!');
            return;
        }

        // Calculate subtotal first
        let subtotal = 0;
        cartItems.forEach(item => {
            subtotal += item.price * item.qty;
        });

        // Apply discount
        let discountAmount = 0;
        if (discountType === 'percent') {
            discountAmount = subtotal * (discountValue / 100);
        } else if (discountType === 'fixed') {
            discountAmount = discountValue;
        }
        if (discountAmount > subtotal) discountAmount = subtotal;
        
        const discountedSubtotal = subtotal - discountAmount;

        // Generate HTML for payment options
        let paymentTotalsHTML = '';
        
        // Show only cash and card for now (can be extended to show all methods)
        const methodsToShow = ['cash', 'card'];
        
        methodsToShow.forEach(method => {
            const rate = paymentTaxRates[method] || 0;
            const taxAmount = discountedSubtotal * (rate / 100);
            const total = discountedSubtotal + taxAmount;
            
            paymentTotalsHTML += `
                <div class="col-6 mb-2">
                    <div class="border rounded p-2 bg-light">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <span class="fw-bold text-capitalize" style="font-size: 0.8rem;">${method}</span>
                                <div class="text-muted" style="font-size: 0.7rem;">(${rate.toFixed(1)}% tax)</div>
                            </div>
                            <div class="text-end">
                                <div class="fw-bold text-primary" style="font-size: 0.8rem;">Rs ${total.toFixed(2)}</div>
                                <div class="text-muted" style="font-size: 0.7rem;">Rs ${discountedSubtotal.toFixed(2)} + Rs ${taxAmount.toFixed(2)}</div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
        });

        console.log('Generated HTML:', paymentTotalsHTML);
        row.innerHTML = paymentTotalsHTML;
        container.style.display = 'block';
        console.log('Payment totals container should now be visible');
    }

    function hidePaymentTotalsPreview() {
        const cashContainer = document.getElementById('payment-totals-container');
        const cashRow = document.getElementById('payment-totals-row');
        const cardContainer = document.getElementById('card-payment-totals-container');
        const cardRow = document.getElementById('card-payment-totals-row');
        
        if (cashRow) cashRow.innerHTML = '';
        if (cashContainer) cashContainer.style.display = 'none';
        if (cardRow) cardRow.innerHTML = '';
        if (cardContainer) cardContainer.style.display = 'none';
    }

    // 💳 PAYMENT FLOW
    const paymentBtn = document.getElementById('payment-btn');
    if (paymentBtn) {
        paymentBtn.addEventListener('click', function (e) {
            e.preventDefault();

            const cartItems = [];
            const serializedItemsMissingSerials = [];
            
            document.querySelectorAll('.product-list').forEach(row => {
            const modifiers = row.getAttribute('data-modifiers') ? JSON.parse(row.getAttribute('data-modifiers')) : [];
            const remarks = row.getAttribute('data-remarks') || '';
            const discountInfo = getRowDiscountInfo(row);
            updateRowDiscountAttributes(row, discountInfo);
            const qty = normalizeQuantity(row.querySelector('input[name="qty"]').value, POS_QTY_MIN);
            const netUnitPrice = Math.max(0, discountInfo.price - discountInfo.perUnit);
            const serialIds = row.getAttribute('data-serial-ids') ? JSON.parse(row.getAttribute('data-serial-ids')) : [];
            const isSerialized = parseInt(row.getAttribute('data-is-serialized')) === 1;
            const itemName = row.getAttribute('data-item-name') || row.querySelector('h6')?.textContent || '';
            
            // ✅ Validate serialized items have serials selected
            if (isSerialized && (serialIds.length === 0 || serialIds.length !== qty)) {
                serializedItemsMissingSerials.push({
                    name: itemName,
                    qty: qty,
                    serials_selected: serialIds.length
                });
            }
            
            cartItems.push({
                id: parseInt(row.getAttribute('data-item-id')) || 0,
                name: itemName,
                price: netUnitPrice,
                original_price: discountInfo.price,
                qty: qty,
                tax_rate: parseFloat(row.getAttribute('data-tax-rate')) || 0,
                tax_type: row.getAttribute('data-tax-type') || 'excluded',
                modifiers: modifiers,
                remarks: remarks,
                serial_ids: serialIds,
                item_discount_type: discountInfo.type,
                item_discount_value: discountInfo.value,
                item_discount_per_unit: discountInfo.perUnit,
                item_discount_amount: discountInfo.perUnit * qty
            });
            });

            if (cartItems.length === 0) {
                alert("No items in cart.");
                return;
            }
            
            // ✅ Validate serialized items before proceeding to payment
            if (serializedItemsMissingSerials.length > 0) {
                const itemList = serializedItemsMissingSerials.map(item => 
                    `• ${item.name}: Quantity ${item.qty}, Selected ${item.serials_selected}`
                ).join('\n');
                
                Swal.fire({
                    icon: 'warning',
                    title: 'Serial Numbers Required',
                    html: `Please select serial numbers for the following items:<br><pre style="text-align: left; font-size: 0.9em;">${itemList}</pre>`,
                    confirmButtonText: 'OK'
                });
                return;
            }

           window.cartItemsToSave = cartItems;

const selectedCustomer = document.getElementById('top-customer-select')?.value || 'Walk-in';
window.customerToSave = selectedCustomer;

document.getElementById('form-customer').value = selectedCustomer;


            window.taxToSave = taxInput.value.replace(' Rs', '') || '0';
            window.totalToSave = totalEl.textContent.replace('Rs ', '');

            // Display total amount in payment modal
            const paymentTotalDisplay = document.getElementById('payment-total-display');
            if (paymentTotalDisplay) {
                paymentTotalDisplay.textContent = parseFloat(window.totalToSave).toFixed(2);
            }

            // Hide payment totals by default (removed auto-display)
            hidePaymentTotalsPreview();

            const methodModal = new bootstrap.Modal(document.getElementById('select-payment-method'));
            methodModal.show();
        });
    }

    // 🟡 Handle payment method selection
function bindPaymentMethodEvents() {
  const buttons = document.querySelectorAll('.payment-option');
  
  // Remove ALL existing event listeners by cloning and replacing buttons
  buttons.forEach(button => {
    const newButton = button.cloneNode(true);
    button.parentNode.replaceChild(newButton, button);
  });
  
  // Add event listeners (removed once: true to allow multiple clicks)
  document.querySelectorAll('.payment-option').forEach(button => {
    button.addEventListener('click', handlePaymentMethodClick);
  });
  
  console.log('Payment method buttons found and bound:', buttons.length);
}

// Helper function to programmatically select a payment method
function selectPaymentMethod(methodName, buttonElement) {
  // 🛡️ Validate payment method
  if (!methodName || methodName === '') {
    console.error('Error: Invalid payment method selected.');
    return;
  }
  
  selectedPaymentMethod = methodName;
  
  // Update current payment method for tax calculation
  setPaymentMethod(methodName);
  
  // Add active class to clicked button and remove from others
  document.querySelectorAll('.payment-method-btn').forEach(btn => {
    btn.classList.remove('active');
  });
  if (buttonElement) {
    buttonElement.classList.add('active');
  }
  
  const bankWrapper = document.getElementById('bank-account-wrapper');
  const bankSelect = document.getElementById('bank-account-select');
  const cardWrapper = document.getElementById('card-details-wrapper');
  const cardTypeSelect = document.getElementById('card-type-select');
  const cardLastFour = document.getElementById('card-last-four');
  const cardTransactionRef = document.getElementById('card-transaction-ref');
  const cashWrapper = document.getElementById('cash-tender-wrapper');

  // Hide all wrappers first
  if (bankWrapper) bankWrapper.classList.add('d-none');
  if (cardWrapper) cardWrapper.classList.add('d-none');
  if (cashWrapper) cashWrapper.classList.add('d-none');

  // Check if payment method is cash
  if (selectedPaymentMethod === 'cash') {
    if (cashWrapper) cashWrapper.classList.remove('d-none');
    initializeCashTender();
    displaySelectedPaymentMethodTax('cash');
  }
  // Check if payment method requires bank account
  else if (selectedPaymentMethod === 'bank' || (buttonElement && buttonElement.hasAttribute('data-requires-bank'))) {
    if (bankWrapper) bankWrapper.classList.remove('d-none');
    initializeBankPayment();
    if (bankSelect) bankSelect.focus();
  } 
  // Check if payment method is card
  else if (selectedPaymentMethod === 'card') {
    if (cardWrapper) cardWrapper.classList.remove('d-none');
    initializeCardPayment();
    displaySelectedPaymentMethodTax('card');
    if (cardTypeSelect) cardTypeSelect.focus();

    // Handle card type selection
    if (cardTypeSelect) {
      cardTypeSelect.onchange = () => {
        if (cardTypeSelect.value && cardLastFour) {
          cardLastFour.focus();
        }
      };
    }

    // Handle card details validation (no auto-submit)
    if (cardLastFour) {
      cardLastFour.oninput = () => {
        // Only allow numbers
        cardLastFour.value = cardLastFour.value.replace(/[^0-9]/g, '');
      };
    }

    // Handle transaction reference (no auto-submit)
    if (cardTransactionRef) {
      cardTransactionRef.oninput = () => {
        // Just allow typing, no auto-submit
      };
    }

  } else {
    // Direct submission for other methods
    hidePaymentTotalsPreview();
    submitSale('');
  }
}

// Display payment method tax for the selected method only
function displaySelectedPaymentMethodTax(method) {
  // Only show if payment method tax is enabled (check window variable)
  const taxMethod = window.taxCalculationMethod || (typeof taxCalculationMethod !== 'undefined' ? taxCalculationMethod : null);
  if (!taxMethod || taxMethod !== 'payment_method') {
    // Hide both containers
    const cashContainer = document.getElementById('payment-totals-container');
    const cardContainer = document.getElementById('card-payment-totals-container');
    if (cashContainer) cashContainer.style.display = 'none';
    if (cardContainer) cardContainer.style.display = 'none';
    return;
  }
  
  if (!window.cartItemsToSave || !Array.isArray(window.cartItemsToSave) || window.cartItemsToSave.length === 0) {
    const cashContainer = document.getElementById('payment-totals-container');
    const cardContainer = document.getElementById('card-payment-totals-container');
    if (cashContainer) cashContainer.style.display = 'none';
    if (cardContainer) cardContainer.style.display = 'none';
    return;
  }
  
  // Hide the other container first
  if (method === 'cash') {
    const cardContainer = document.getElementById('card-payment-totals-container');
    if (cardContainer) cardContainer.style.display = 'none';
  } else if (method === 'card') {
    const cashContainer = document.getElementById('payment-totals-container');
    if (cashContainer) cashContainer.style.display = 'none';
  }
  
  // Get discount values
  const discountInputEl = document.getElementById('discount-input');
  const discountTypeEl = document.getElementById('discount-type');
  const discountValue = parseFloat(discountInputEl?.value) || 0;
  const discountType = discountTypeEl?.value || 'percent';
  
  // Calculate subtotal
  let subtotal = 0;
  window.cartItemsToSave.forEach(item => {
    subtotal += item.price * item.qty;
  });
  
  // Apply discount
  let discountAmount = 0;
  if (discountType === 'percent') {
    discountAmount = subtotal * (discountValue / 100);
  } else if (discountType === 'fixed') {
    discountAmount = discountValue;
  }
  if (discountAmount > subtotal) discountAmount = subtotal;
  
  const discountedSubtotal = subtotal - discountAmount;
  
  // Fetch tax settings to get payment method tax rates
  fetch('ajax/get_tax_settings.php')
    .then(response => response.json())
    .then(data => {
      if (data.success && data.payment_tax_rates) {
        const rate = data.payment_tax_rates[method] || 0;
        const taxAmount = discountedSubtotal * (rate / 100);
        const total = discountedSubtotal + taxAmount;
        
        // Use different container IDs based on method
        const containerId = method === 'cash' ? 'payment-totals-container' : 'card-payment-totals-container';
        const rowId = method === 'cash' ? 'payment-totals-row' : 'card-payment-totals-row';
        
        const container = document.getElementById(containerId);
        const row = document.getElementById(rowId);
        
        if (!container || !row) return;
        
        const methodLabel = method.charAt(0).toUpperCase() + method.slice(1);
        const paymentTotalsHTML = `
          <div class="col-12 mb-2">
            <div class="border rounded p-3 bg-light">
              <div class="d-flex justify-content-between align-items-center">
                <div>
                  <span class="fw-bold text-capitalize">${methodLabel} Payment</span>
                  <div class="text-muted small">(${rate.toFixed(1)}% tax)</div>
                </div>
                <div class="text-end">
                  <div class="fw-bold text-primary">Rs ${total.toFixed(2)}</div>
                  <div class="text-muted small">Rs ${discountedSubtotal.toFixed(2)} + Rs ${taxAmount.toFixed(2)}</div>
                </div>
              </div>
            </div>
          </div>
        `;
        
        row.innerHTML = paymentTotalsHTML;
        container.style.display = 'block';
        
        // Update the summary total due to show the total with tax
        if (method === 'cash') {
          const summaryTotalDue = document.getElementById('summary-total-due');
          if (summaryTotalDue) {
            summaryTotalDue.textContent = 'Rs ' + total.toFixed(2);
          }
        } else if (method === 'card') {
          const cardSummaryTotalDue = document.getElementById('card-summary-total-due');
          if (cardSummaryTotalDue) {
            cardSummaryTotalDue.textContent = 'Rs ' + total.toFixed(2);
          }
        }
      } else {
        const cashContainer = document.getElementById('payment-totals-container');
        const cardContainer = document.getElementById('card-payment-totals-container');
        if (cashContainer) cashContainer.style.display = 'none';
        if (cardContainer) cardContainer.style.display = 'none';
      }
    })
    .catch(error => {
      console.error('Error loading payment tax rates:', error);
      const cashContainer = document.getElementById('payment-totals-container');
      const cardContainer = document.getElementById('card-payment-totals-container');
      if (cashContainer) cashContainer.style.display = 'none';
      if (cardContainer) cardContainer.style.display = 'none';
    });
}

function handlePaymentMethodClick() {
  const methodName = this.getAttribute('data-method');
  selectPaymentMethod(methodName, this);
}

// Global function for card payment submission
window.submitCardPayment = function() {
  const cardTypeId = document.getElementById('card-type-select').value;
  const cardLastFour = document.getElementById('card-last-four').value;
  const cardTransactionRef = document.getElementById('card-transaction-ref').value;

  // Validate required fields (card type is required, last 4 digits are optional)
  if (!cardTypeId) {
    alert('Please select card type.');
    return;
  }

  // Validate last 4 digits format if provided (must be 4 digits)
  if (cardLastFour && cardLastFour.length !== 4) {
    alert('Last 4 digits must be exactly 4 digits.');
    return;
  }

  // Submit with card details
  submitSale('', cardTypeId, cardLastFour, cardTransactionRef);
}

// Global function for bank payment submission
window.submitBankPayment = function() {
  const bankAccountId = document.getElementById('bank-account-select').value;

  // Validate required fields
  if (!bankAccountId) {
    alert('Please select bank account.');
    return;
  }

  // Submit with bank account ID
  submitSale(bankAccountId);
}

// ===== CASH TENDER FUNCTIONALITY =====

// Initialize cash tender form
function initializeCashTender() {
  const billAmount = parseFloat(window.totalToSave) || 0;
  
  // Set bill amount (hidden field)
  const cashBillAmount = document.getElementById('cash-bill-amount');
  if (cashBillAmount) {
    cashBillAmount.value = billAmount.toFixed(2);
  }
  
  // Reset tendered amount and change
  const cashTenderedAmount = document.getElementById('cash-tendered-amount');
  const cashChangeAmount = document.getElementById('cash-change-amount');
  const submitBtn = document.getElementById('submit-cash-payment-btn');
  
  if (cashTenderedAmount) cashTenderedAmount.value = '';
  if (cashChangeAmount) cashChangeAmount.textContent = '0.00';
  if (submitBtn) submitBtn.disabled = true;
  
  // Hide validation message
  const validationMsg = document.getElementById('change-validation-message');
  if (validationMsg) validationMsg.style.display = 'none';
  
  // Update summary panel
  updatePaymentSummary(billAmount, 0, billAmount);
  
  // Update customer name in summary
  const customerName = window.customerToSave || 'Cash Customer';
  const summaryCustomerName = document.getElementById('summary-customer-name');
  if (summaryCustomerName) {
    summaryCustomerName.textContent = customerName;
  }
  
  // Update total due in summary - if payment method tax is enabled, it will be updated by displaySelectedPaymentMethodTax
  const summaryTotalDue = document.getElementById('summary-total-due');
  if (summaryTotalDue) {
    summaryTotalDue.textContent = 'Rs ' + billAmount.toFixed(2);
  }
  
  // Bind cash tender event listeners
  bindCashTenderEvents();
}

// Initialize card payment form
function initializeCardPayment() {
  const billAmount = parseFloat(window.totalToSave) || 0;
  
  // Update customer name in summary
  const customerName = window.customerToSave || 'Cash Customer';
  const summaryCustomerName = document.getElementById('card-summary-customer-name');
  if (summaryCustomerName) {
    summaryCustomerName.textContent = customerName;
  }
  
  // Update total due in summary - if payment method tax is enabled, calculate with tax
  const summaryTotalDue = document.getElementById('card-summary-total-due');
  if (summaryTotalDue) {
    const taxMethod = window.taxCalculationMethod || (typeof taxCalculationMethod !== 'undefined' ? taxCalculationMethod : null);
    if (taxMethod === 'payment_method' && window.cartItemsToSave && Array.isArray(window.cartItemsToSave) && window.cartItemsToSave.length > 0) {
      // Calculate with payment method tax - will be updated when displaySelectedPaymentMethodTax completes
      // For now, show the base amount, it will be updated by the tax display function
      summaryTotalDue.textContent = 'Rs ' + billAmount.toFixed(2);
    } else {
      summaryTotalDue.textContent = 'Rs ' + billAmount.toFixed(2);
    }
  }
}

// Initialize bank payment form
function initializeBankPayment() {
  const billAmount = parseFloat(window.totalToSave) || 0;
  
  // Update customer name in summary
  const customerName = window.customerToSave || 'Cash Customer';
  const summaryCustomerName = document.getElementById('bank-summary-customer-name');
  if (summaryCustomerName) {
    summaryCustomerName.textContent = customerName;
  }
  
  // Update total due in summary
  const summaryTotalDue = document.getElementById('bank-summary-total-due');
  if (summaryTotalDue) {
    summaryTotalDue.textContent = 'Rs ' + billAmount.toFixed(2);
  }
}

// Bind cash tender event listeners
function bindCashTenderEvents() {
  // Tendered amount click - open numpad
  const tenderedInput = document.getElementById('cash-tendered-amount');
  if (tenderedInput) {
    tenderedInput.onclick = () => openCashNumpad();
  }
  
  // Quick amount pills (updated selector)
  document.querySelectorAll('.quick-amount-pill[data-amount]').forEach(btn => {
    btn.onclick = () => {
      const amount = parseFloat(btn.getAttribute('data-amount'));
      setCashTenderedAmount(amount);
    };
  });
  
  // Exact amount button
  const exactBtn = document.getElementById('exact-amount-btn');
  if (exactBtn) {
    exactBtn.onclick = () => {
      const billAmount = parseFloat(window.totalToSave) || 0;
      setCashTenderedAmount(billAmount);
    };
  }
  
  // Submit cash payment button
  const submitBtn = document.getElementById('submit-cash-payment-btn');
  if (submitBtn) {
    submitBtn.onclick = () => submitCashPayment();
  }
}

// Open cash numpad modal
function openCashNumpad() {
  const numpadModal = new bootstrap.Modal(document.getElementById('cashNumpadModal'));
  const numpadInput = document.getElementById('cashNumpadInput');
  
  // Clear input
  if (numpadInput) numpadInput.value = '';
  
  // Bind numpad keys
  bindCashNumpadKeys();
  
  numpadModal.show();
}

// Bind cash numpad key events
function bindCashNumpadKeys() {
  const numpadInput = document.getElementById('cashNumpadInput');
  
  // Number keys
  document.querySelectorAll('.cash-numpad-key').forEach(key => {
    key.onclick = () => {
      const keyValue = key.getAttribute('data-key');
      let currentValue = numpadInput.value;
      
      // Handle decimal point - only allow one
      if (keyValue === '.') {
        if (!currentValue.includes('.')) {
          numpadInput.value = currentValue + keyValue;
        }
      } else {
        numpadInput.value = currentValue + keyValue;
      }
    };
  });
  
  // Clear button
  const clearBtn = document.getElementById('clearCashNumpadBtn');
  if (clearBtn) {
    clearBtn.onclick = () => {
      numpadInput.value = '';
    };
  }
  
  // Backspace button
  const backspaceBtn = document.getElementById('backspaceCashNumpadBtn');
  if (backspaceBtn) {
    backspaceBtn.onclick = () => {
      numpadInput.value = numpadInput.value.slice(0, -1);
    };
  }
  
  // Confirm button
  const confirmBtn = document.getElementById('confirmCashAmountBtn');
  if (confirmBtn) {
    confirmBtn.onclick = () => {
      const enteredAmount = parseFloat(numpadInput.value) || 0;
      setCashTenderedAmount(enteredAmount);
      
      // Close numpad modal
      const numpadModal = bootstrap.Modal.getInstance(document.getElementById('cashNumpadModal'));
      if (numpadModal) numpadModal.hide();
    };
  }
}

// Set cash tendered amount and calculate change
function setCashTenderedAmount(amount) {
  const cashTenderedAmount = document.getElementById('cash-tendered-amount');
  const cashChangeAmount = document.getElementById('cash-change-amount');
  const submitBtn = document.getElementById('submit-cash-payment-btn');
  const validationMsg = document.getElementById('change-validation-message');
  const billAmount = parseFloat(window.totalToSave) || 0;
  
  // Set tendered amount
  if (cashTenderedAmount) {
    cashTenderedAmount.value = amount.toFixed(0);
  }
  
  // Calculate change
  const change = amount - billAmount;
  
  if (cashChangeAmount) {
    if (change >= 0) {
      cashChangeAmount.textContent = change.toFixed(2);
      
      // Enable submit button
      if (submitBtn) submitBtn.disabled = false;
      
      // Hide validation message
      if (validationMsg) validationMsg.style.display = 'none';
      
      // Update summary
      updatePaymentSummary(billAmount, billAmount, 0);
    } else {
      cashChangeAmount.textContent = change.toFixed(2);
      
      // Disable submit button
      if (submitBtn) submitBtn.disabled = true;
      
      // Show validation message
      if (validationMsg) validationMsg.style.display = 'block';
      
      // Update summary
      updatePaymentSummary(billAmount, amount, billAmount - amount);
    }
  }
}

// Update payment summary panel
function updatePaymentSummary(totalDue, completed, balance) {
  const summaryTotalDue = document.getElementById('summary-total-due');
  const summaryCompleted = document.getElementById('summary-completed');
  const summaryBalance = document.getElementById('summary-balance');
  
  if (summaryTotalDue) summaryTotalDue.textContent = 'Rs ' + totalDue.toFixed(2);
  if (summaryCompleted) summaryCompleted.textContent = 'Rs ' + completed.toFixed(2);
  if (summaryBalance) summaryBalance.textContent = 'Rs ' + balance.toFixed(2);
}

// Submit cash payment
function submitCashPayment() {
  const tenderedAmount = parseFloat(document.getElementById('cash-tendered-amount').value) || 0;
  const billAmount = parseFloat(window.totalToSave) || 0;
  
  // Validate tendered amount
  if (tenderedAmount < billAmount) {
    alert('Amount tendered must be greater than or equal to bill amount.');
    return;
  }
  
  // Store cash tender details for receipt printing
  window.cashTenderedAmount = tenderedAmount;
  window.cashChangeAmount = tenderedAmount - billAmount;
  
  // Submit sale
  submitSale('');
}

// Global function to get cash tender details (for receipt)
window.getCashTenderDetails = function() {
  return {
    tendered: window.cashTenderedAmount || 0,
    change: window.cashChangeAmount || 0
  };
}

// ===== END CASH TENDER FUNCTIONALITY =====

// ===== TIP FUNCTIONALITY =====

// Global variable to store tip amount
window.tipAmount = 0;

// Open tip numpad modal
window.openTipNumpad = function() {
  const numpadModal = new bootstrap.Modal(document.getElementById('tipNumpadModal'));
  const numpadInput = document.getElementById('tipNumpadInput');
  
  // Set current tip value
  if (numpadInput) numpadInput.value = window.tipAmount > 0 ? window.tipAmount.toString() : '';
  
  // Bind numpad keys
  bindTipNumpadKeys();
  
  numpadModal.show();
}

// Bind tip numpad key events
function bindTipNumpadKeys() {
  const numpadInput = document.getElementById('tipNumpadInput');
  
  // Number keys
  document.querySelectorAll('.tip-numpad-key').forEach(key => {
    key.onclick = () => {
      const keyValue = key.getAttribute('data-key');
      let currentValue = numpadInput.value;
      
      // Handle decimal point - only allow one
      if (keyValue === '.') {
        if (!currentValue.includes('.')) {
          numpadInput.value = currentValue + keyValue;
        }
      } else {
        numpadInput.value = currentValue + keyValue;
      }
    };
  });
  
  // Clear button
  const clearBtn = document.getElementById('clearTipNumpadBtn');
  if (clearBtn) {
    clearBtn.onclick = () => {
      numpadInput.value = '';
    };
  }
  
  // Backspace button
  const backspaceBtn = document.getElementById('backspaceTipNumpadBtn');
  if (backspaceBtn) {
    backspaceBtn.onclick = () => {
      const currentValue = numpadInput.value;
      numpadInput.value = currentValue.slice(0, -1);
    };
  }
  
  // Confirm button
  const confirmBtn = document.getElementById('confirmTipAmountBtn');
  if (confirmBtn) {
    confirmBtn.onclick = () => {
      const tipValue = parseFloat(numpadInput.value) || 0;
      setTipAmount(tipValue);
      
      // Close modal
      const modalElement = document.getElementById('tipNumpadModal');
      const modalInstance = bootstrap.Modal.getInstance(modalElement);
      if (modalInstance) modalInstance.hide();
    };
  }
}

// Set tip amount and update display
function setTipAmount(amount) {
  window.tipAmount = amount;
  
  // Update tip input display
  const tipInput = document.getElementById('tip-amount-input');
  if (tipInput) {
    tipInput.value = amount > 0 ? amount.toFixed(2) : '';
  }
  
  // Update final total display
  updateFinalTotalDisplay();
}

// Update final total display (Bill + Tip)
function updateFinalTotalDisplay() {
  const billAmount = parseFloat(window.totalToSave) || 0;
  const tipAmount = window.tipAmount || 0;
  const finalTotal = billAmount + tipAmount;
  
  const finalTotalDisplay = document.getElementById('final-total-display');
  const finalTotalAmount = document.getElementById('final-total-amount');
  
  if (tipAmount > 0) {
    if (finalTotalDisplay) finalTotalDisplay.style.display = 'block';
    if (finalTotalAmount) finalTotalAmount.textContent = finalTotal.toFixed(2);
  } else {
    if (finalTotalDisplay) finalTotalDisplay.style.display = 'none';
  }
}

// Reset tip amount when payment modal is opened
function resetTipAmount() {
  window.tipAmount = 0;
  const tipInput = document.getElementById('tip-amount-input');
  if (tipInput) tipInput.value = '';
  
  const finalTotalDisplay = document.getElementById('final-total-display');
  if (finalTotalDisplay) finalTotalDisplay.style.display = 'none';
  
  // Hide tip input container by default
  const tipInputContainer = document.getElementById('tip-input-container');
  if (tipInputContainer) tipInputContainer.classList.add('d-none');
}

// ===== END TIP FUNCTIONALITY =====

// Global variables for discount management
window.customerDiscount = null;
window.selectedDiscount = null;
window.availableDiscounts = [];

// Open discount selection modal
function openDiscountSelectionModal() {
  // Fetch available discounts
  fetch('ajax/get_discounts.php')
    .then(response => response.json())
    .then(data => {
      if (data.success) {
        window.availableDiscounts = data.discounts;
        window.discountCategories = data.categories || [];
        window.discountsByCategory = data.discountsByCategory || {};
        
        // Populate category tabs
        populateDiscountCategoryTabs();
        
        // Populate discounts (show all by default)
        populateDiscountModal('all');
        
        const modal = new bootstrap.Modal(document.getElementById('discountSelectionModal'));
        modal.show();
      } else {
        alert('Error loading discounts: ' + (data.message || 'Unknown error'));
      }
    })
    .catch(error => {
      console.error('Error fetching discounts:', error);
      alert('Error loading discounts. Please try again.');
    });
}

// Populate category tabs
function populateDiscountCategoryTabs() {
  const tabsContainer = document.getElementById('discount-category-tabs');
  
  // Keep the "All" button and clear other buttons
  const allButton = tabsContainer.querySelector('[data-category="all"]');
  tabsContainer.innerHTML = '';
  if (allButton) {
    tabsContainer.appendChild(allButton);
  }
  
  // Add category buttons
  window.discountCategories.forEach(category => {
    const btn = document.createElement('button');
    btn.type = 'button';
    btn.className = 'btn btn-sm btn-outline-primary';
    btn.setAttribute('data-category', category.id);
    btn.textContent = category.category_name;
    btn.onclick = function() {
      filterDiscountsByCategory(category.id, this);
    };
    tabsContainer.appendChild(btn);
  });
  
  // Add "Uncategorized" button if there are discounts without category
  if (window.discountsByCategory['uncategorized'] && window.discountsByCategory['uncategorized'].length > 0) {
    const btn = document.createElement('button');
    btn.type = 'button';
    btn.className = 'btn btn-sm btn-outline-secondary';
    btn.setAttribute('data-category', 'uncategorized');
    btn.textContent = 'Uncategorized';
    btn.onclick = function() {
      filterDiscountsByCategory('uncategorized', this);
    };
    tabsContainer.appendChild(btn);
  }
}

// Filter discounts by category
function filterDiscountsByCategory(categoryId, buttonElement) {
  // Update active state of buttons
  const allButtons = document.querySelectorAll('#discount-category-tabs button');
  allButtons.forEach(btn => btn.classList.remove('active'));
  if (buttonElement) {
    buttonElement.classList.add('active');
  }
  
  // Populate modal with filtered discounts
  populateDiscountModal(categoryId);
}

// Populate discount modal with options
function populateDiscountModal(categoryId = 'all') {
  const container = document.getElementById('discount-options-container');
  const availableContainer = document.getElementById('available-discounts');
  
  // Clear previous content
  container.innerHTML = '';
  availableContainer.innerHTML = '';
  
  // Calculate current subtotal for discount calculations
  const subtotal = calculateCurrentSubtotal();
  
  // Show customer discount if available
  if (window.customerDiscount) {
    const customerDiscountCard = createDiscountOptionCard(
      'customer',
      'Customer Discount',
      window.customerDiscount.rate + '%',
      calculateDiscountAmount(subtotal, window.customerDiscount),
      'customer'
    );
    container.appendChild(customerDiscountCard);
  }
  
  // Filter discounts by category
  let discountsToShow = [];
  if (categoryId === 'all') {
    discountsToShow = window.availableDiscounts;
  } else if (categoryId === 'uncategorized') {
    discountsToShow = window.discountsByCategory['uncategorized'] || [];
  } else {
    discountsToShow = window.discountsByCategory[categoryId] || [];
  }
  
  // Show filtered discounts
  if (discountsToShow.length === 0) {
    availableContainer.innerHTML = '<div class="col-12 text-center text-muted py-3">No discounts available in this category</div>';
  } else {
    discountsToShow.forEach(discount => {
      const discountCard = createDiscountOptionCard(
        discount.id,
        discount.discount_name,
        discount.discount_type === 'percentage' ? discount.discount_rate + '%' : 'Rs ' + discount.discount_rate,
        calculateDiscountAmount(subtotal, discount),
        'discount',
        discount
      );
      availableContainer.appendChild(discountCard);
    });
  }
  
  // Add manual option
  const manualCard = createDiscountOptionCard(
    'manual',
    'Manual Entry',
    'Custom Amount',
    'Use current input',
    'manual'
  );
  container.appendChild(manualCard);
}

// Create discount option card
function createDiscountOptionCard(id, name, rate, amount, type, discountData = null) {
  const card = document.createElement('div');
  card.className = 'discount-option-card col-md-6';
  card.setAttribute('data-discount-id', id);
  card.setAttribute('data-discount-type', type);
  
  if (discountData) {
    card.setAttribute('data-discount-data', JSON.stringify(discountData));
  }
  
  card.innerHTML = `
    <div class="d-flex justify-content-between align-items-start">
      <div>
        <div class="fw-bold">${name}</div>
        <div class="discount-details">Rate: ${rate}</div>
        <div class="discount-amount">${amount}</div>
      </div>
      <div>
        <span class="badge discount-badge bg-${type === 'customer' ? 'success' : type === 'manual' ? 'info' : 'primary'}">
          ${type === 'customer' ? 'Customer' : type === 'manual' ? 'Manual' : 'Predefined'}
        </span>
      </div>
    </div>
  `;
  
  // Add click event
  card.addEventListener('click', function() {
    selectDiscountOption(this);
  });
  
  return card;
}

// Select discount option
function selectDiscountOption(card) {
  // Remove previous selection
  document.querySelectorAll('.discount-option-card').forEach(c => c.classList.remove('selected'));
  
  // Add selection to clicked card
  card.classList.add('selected');
  
  // Enable apply button
  const applyBtn = document.getElementById('apply-discount-btn');
  if (applyBtn) {
    applyBtn.disabled = false;
  }
  
  // Store selected discount
  const discountId = card.getAttribute('data-discount-id');
  const discountType = card.getAttribute('data-discount-type');
  const discountData = card.getAttribute('data-discount-data');
  
  window.selectedDiscount = {
    id: discountId,
    type: discountType,
    data: discountData ? JSON.parse(discountData) : null
  };
}

// Calculate current subtotal
function calculateCurrentSubtotal() {
  let subtotal = 0;
  const cartWrap = document.querySelector('.product-wrap');
  if (cartWrap) {
    cartWrap.querySelectorAll('.product-list').forEach(row => {
      const discountInfo = getRowDiscountInfo(row);
      updateRowDiscountAttributes(row, discountInfo);
      const netUnitPrice = Math.max(0, discountInfo.price - discountInfo.perUnit);
      const qty = normalizeQuantity(row.querySelector('input[name="qty"]').value, POS_QTY_MIN);
      subtotal += netUnitPrice * qty;
    });
  }
  return subtotal;
}

// Calculate discount amount with cap
function calculateDiscountAmount(subtotal, discount) {
  let amount = 0;
  
  if (discount.discount_type === 'percentage') {
    amount = subtotal * (parseFloat(discount.discount_rate) / 100);
  } else if (discount.discount_type === 'fixed') {
    amount = parseFloat(discount.discount_rate);
  } else if (discount.type === 'percent') {
    amount = subtotal * (parseFloat(discount.rate) / 100);
  }
  
  // Apply cap if exists
  if (discount.discount_cap && amount > parseFloat(discount.discount_cap)) {
    amount = parseFloat(discount.discount_cap);
  }
  
  // Don't exceed subtotal
  if (amount > subtotal) {
    amount = subtotal;
  }
  
  return 'Rs ' + amount.toFixed(2);
}

// Apply selected discount
window.applySelectedDiscount = function() {
  if (!window.selectedDiscount) {
    return;
  }
  
  const discountInput = document.getElementById('discount-input');
  const discountType = document.getElementById('discount-type');
  
  if (window.selectedDiscount.type === 'customer') {
    // Apply customer discount
    discountInput.value = window.customerDiscount.rate;
    discountType.value = 'percent';
  } else if (window.selectedDiscount.type === 'discount') {
    // Apply predefined discount with cap consideration
    const discount = window.selectedDiscount.data;
    const subtotal = calculateCurrentSubtotal();
    
    // Calculate the actual discount amount with cap
    let actualDiscountAmount = 0;
    if (discount.discount_type === 'percentage') {
      actualDiscountAmount = subtotal * (parseFloat(discount.discount_rate) / 100);
      // Apply cap if exists
      if (discount.discount_cap && actualDiscountAmount > parseFloat(discount.discount_cap)) {
        actualDiscountAmount = parseFloat(discount.discount_cap);
      }
      // Convert back to percentage for the input
      const actualPercentage = (actualDiscountAmount / subtotal) * 100;
      discountInput.value = actualPercentage.toFixed(2);
      discountType.value = 'percent';
    } else {
      // Fixed amount discount
      actualDiscountAmount = parseFloat(discount.discount_rate);
      // Apply cap if exists
      if (discount.discount_cap && actualDiscountAmount > parseFloat(discount.discount_cap)) {
        actualDiscountAmount = parseFloat(discount.discount_cap);
      }
      discountInput.value = actualDiscountAmount.toFixed(2);
      discountType.value = 'fixed';
    }
  }
  // Manual option doesn't change the input values
  
  // Update totals
  if (typeof updateTotal === 'function') {
    updateTotal();
  }
  
  // Close modal
  const modal = bootstrap.Modal.getInstance(document.getElementById('discountSelectionModal'));
  if (modal) {
    modal.hide();
  }
}

// Add event listener for apply discount button when modal is shown
document.addEventListener('DOMContentLoaded', function() {
  const discountModal = document.getElementById('discountSelectionModal');
  if (discountModal) {
    discountModal.addEventListener('shown.bs.modal', function() {
      const applyBtn = document.getElementById('apply-discount-btn');
      if (applyBtn && !applyBtn.hasAttribute('data-listener-added')) {
        applyBtn.addEventListener('click', applySelectedDiscount);
        applyBtn.setAttribute('data-listener-added', 'true');
      }
    });
  }
  
  // Also try to add the listener immediately if button exists
  const applyBtn = document.getElementById('apply-discount-btn');
  if (applyBtn && !applyBtn.hasAttribute('data-listener-added')) {
    applyBtn.addEventListener('click', applySelectedDiscount);
    applyBtn.setAttribute('data-listener-added', 'true');
  }
});

// Bind payment method events when modal is shown
const paymentModal = document.getElementById('select-payment-method');
if (paymentModal) {
  // Use 'show.bs.modal' to prepare cash before modal is displayed (prevents blank screen)
  paymentModal.addEventListener('show.bs.modal', function() {
    // Reset tip amount when modal opens
    resetTipAmount();
    
    // Bind events immediately
    bindPaymentMethodEvents();
    
    // Auto-select cash payment method by default (only if totalToSave is available)
    if (window.totalToSave !== undefined) {
      const cashButton = document.querySelector('.payment-option[data-method="cash"]');
      if (cashButton) {
        selectPaymentMethod('cash', cashButton);
      }
    }
  });
  
  paymentModal.addEventListener('shown.bs.modal', function() {
    // Bind tip input click handler
    const tipInput = document.getElementById('tip-amount-input');
    if (tipInput) {
      tipInput.onclick = () => openTipNumpad();
    }
  });
  
  // Also try to bind on modal show event as backup
  paymentModal.addEventListener('show.bs.modal', function() {
    setTimeout(() => {
      bindPaymentMethodEvents();
    }, 200);
  });
}

// Additional fallback: Try to bind payment events after a delay
setTimeout(() => {
  const paymentButtons = document.querySelectorAll('.payment-option');
  if (paymentButtons.length > 0) {
    console.log('Found payment buttons on page load, binding events...');
    bindPaymentMethodEvents();
  }
}, 1000);

// Initialize tax calculation method from server
function initializeTaxSettings() {
  console.log('initializeTaxSettings called');
  fetch('ajax/get_tax_settings.php')
    .then(response => {
      console.log('Tax settings response received:', response.status);
      return response.json();
    })
    .then(data => {
      console.log('Tax settings data:', data);
      if (data.success) {
        taxCalculationMethod = data.tax_method;
        showPaymentMethodTaxRatesSetting = !!data.show_tax_rates;
        taxPreviewEnabled = !!data.enable_preview;
        discountTaxSequence = data.discount_sequence || discountTaxSequence;

        window.taxCalculationMethod = taxCalculationMethod;
        window.showPaymentMethodTaxRatesSetting = showPaymentMethodTaxRatesSetting;
        window.taxPreviewEnabled = taxPreviewEnabled;
        window.discountTaxSequence = discountTaxSequence;

        console.log('Tax calculation method updated to:', taxCalculationMethod);
        
        // If payment method tax is enabled, show tax rate display
        if (taxCalculationMethod === 'payment_method' && showPaymentMethodTaxRatesSetting) {
          console.log('Payment method tax enabled, showing tax rates');
          showPaymentMethodTaxRates();
        } else {
          hidePaymentMethodTaxRates();
        }

        if (!taxPreviewEnabled) {
          hidePaymentTotalsPreview();
        }
      } else {
        console.log('Tax settings request failed:', data);
        hidePaymentMethodTaxRates();
      }
    })
    .catch(error => {
      console.error('Error loading tax settings:', error);
    });
}

function showPaymentMethodTaxRates() {
  if (!showPaymentMethodTaxRatesSetting) {
    hidePaymentMethodTaxRates();
    return;
  }

  // Create or update payment method tax rate display
  let taxRateDisplay = document.getElementById('payment-tax-rate-display');
  if (!taxRateDisplay) {
    taxRateDisplay = document.createElement('span');
    taxRateDisplay.id = 'payment-tax-rate-display';
    taxRateDisplay.className = 'text-muted ms-2';
    taxRateDisplay.style.fontSize = '0.9em';
    
    // Insert after tax input
    const taxInput = document.getElementById('tax-input');
    if (taxInput && taxInput.parentNode) {
      taxInput.parentNode.appendChild(taxRateDisplay);
    }
  }
  taxRateDisplay.style.display = 'inline';
}

function hidePaymentMethodTaxRates() {
  const taxRateDisplay = document.getElementById('payment-tax-rate-display');
  if (taxRateDisplay) {
    taxRateDisplay.style.display = 'none';
  }
}

// Initialize tax settings when page loads
document.addEventListener('DOMContentLoaded', function() {
  initializeTaxSettings();
});

// Event delegation approach as ultimate fallback - REMOVED to prevent double submissions
// This was causing multiple event handlers to be attached
function submitSale(bankAccountId, cardTypeId = '', cardLastFour = '', cardTransactionRef = '') {
  // Prevent multiple submissions
  if (window.isSubmitting) {
    console.log('Sale submission already in progress, ignoring duplicate click');
    return;
  }

  const holdCartActive = Boolean(window.isHoldCart || (window.activeHoldReference && window.activeHoldReference !== ''));
  if (holdCartActive && !window.unholdOrderId) {
    if (window.Swal) {
      window.Swal.fire({
        icon: 'warning',
        title: 'Hold order not linked',
        text: 'Reload the held order before completing the sale so it can be cleared from pending.',
        confirmButtonColor: '#f0ad4e'
      });
    } else {
      alert('Hold order not linked. Please reload the held order before completing the sale.');
    }
    return;
  }
  
  window.isSubmitting = true;
  
  const methodModal = bootstrap.Modal.getInstance(document.getElementById('select-payment-method'));
  methodModal.hide();

  // Prepare form data
  const formData = {
    customer_name: window.customerToSave,
    cart_json: JSON.stringify(window.cartItemsToSave),
    tax_amount: window.taxToSave,
    total_amount: window.totalToSave,
    discount_value: discountInput?.value || 0,
    discount_type: discountType?.value || 'percent',
    discount_id: window.selectedDiscount && window.selectedDiscount.type === 'discount' ? window.selectedDiscount.id : null,
    delivery_charges: (() => {
        const serviceChargesInput = document.getElementById('service-charges-input');
        const serviceChargesRate = parseFloat(serviceChargesInput?.value) || 0;
        // Calculate service charges amount from percentage
        // Service charges are calculated on total after tax (baseTotalForServiceCharges)
        const baseTotal = window.baseTotalForServiceCharges || 0;
        return serviceChargesRate > 0 && baseTotal > 0 ? (baseTotal * (serviceChargesRate / 100)) : 0;
    })(),
    tip_amount: window.tipAmount || 0,
    payment_method: selectedPaymentMethod,
    table_id: window.selectedTableId || '',
    order_mode: window.selectedOrderMode || '',
    order_taker_id: window.selectedOrderTakerId || '',
    unhold_order_id: window.unholdOrderId || '',
    bank_account_id: bankAccountId,
    card_type_id: cardTypeId,
    card_last_four: cardLastFour,
    card_transaction_ref: cardTransactionRef,
    quotation_id: window.loadedQuotationId || ''
  };



  // Add delivery data if delivery mode is active
  if (window.selectedOrderMode === 'delivery' && window.deliveryData) {
    formData.delivery_customer_id = window.deliveryData.customer_id;
    formData.delivery_customer_name = window.deliveryData.customer_name;
    formData.delivery_rider_id = window.deliveryData.rider_id;
    formData.delivery_address = window.deliveryData.delivery_address;
    formData.delivery_time = window.deliveryData.delivery_time;
    formData.delivery_instructions = window.deliveryData.delivery_instructions;
  }

  fetch('save_sale.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams(formData)
  })
  .then(res => res.text())
  .then(response => {
    if (response.includes("success")) {
      // ✅ Reload the page to trigger PHP receipt modal using session
      window.location.href = 'pos.php';
    } else {
      alert("Error saving sale: " + response);
      window.isSubmitting = false; // Reset flag on error
    }
  })
  .catch(err => {
    alert("Failed to save sale.");
    console.error(err);
    window.isSubmitting = false; // Reset flag on error
  });
}


// 💾 HOLD ORDER
const holdBtn = document.getElementById('hold-order-btn');
if (holdBtn) {
  holdBtn.addEventListener('click', function (e) {
    e.preventDefault();

    const cartItems = [];
    document.querySelectorAll('.product-list').forEach(row => {
      const modifiers = row.getAttribute('data-modifiers') ? JSON.parse(row.getAttribute('data-modifiers')) : [];
      const remarks = row.getAttribute('data-remarks') || '';
      
      // Extract template_id from modifiers if it exists
      let template_id = null;
      if (modifiers && modifiers.length > 0) {
        const templateModifier = modifiers.find(mod => mod.template_id);
        if (templateModifier) {
          template_id = templateModifier.template_id;
        }
      }

      const discountInfo = getRowDiscountInfo(row);
      updateRowDiscountAttributes(row, discountInfo);
      const qty = normalizeQuantity(row.querySelector('input[name="qty"]').value, POS_QTY_MIN);
      const netUnitPrice = Math.max(0, discountInfo.price - discountInfo.perUnit);
      
      const serialIds = row.getAttribute('data-serial-ids') ? JSON.parse(row.getAttribute('data-serial-ids')) : [];
      cartItems.push({
        id: parseInt(row.getAttribute('data-item-id')) || 0,
        name: row.getAttribute('data-item-name') || row.querySelector('h6')?.textContent || '',
        price: netUnitPrice,
        original_price: discountInfo.price,
        qty: qty,
        tax_rate: parseFloat(row.getAttribute('data-tax-rate')) || 0,
        tax_type: row.getAttribute('data-tax-type') || 'excluded',
        modifiers: modifiers,
        remarks: remarks,
        template_id: template_id,
        serial_ids: serialIds,
        item_discount_type: discountInfo.type,
        item_discount_value: discountInfo.value,
        item_discount_per_unit: discountInfo.perUnit,
        item_discount_amount: discountInfo.perUnit * qty
      });
    });

    if (cartItems.length === 0) {
      Swal.fire('No items to hold', '', 'info');
      return;
    }

    // Use delivery customer data if in delivery mode, otherwise use top customer select
    let customerName, customerId;
    if (window.selectedOrderMode === 'delivery' && window.deliveryData) {
      customerName = window.deliveryData.customer_name;
      customerId = window.deliveryData.customer_id;
    } else {
      const customerSelect = document.getElementById('top-customer-select');
      const selectedValue = customerSelect?.value || 'walk-in';
      
      if (selectedValue === 'walk-in') {
        customerName = 'Walk-in Customer';
        customerId = null;
      } else if (selectedValue === 'select') {
        customerName = 'Walk-in Customer';
        customerId = null;
      } else {
        // Customer ID is selected, get the customer name from the option text
        const selectedOption = customerSelect?.options[customerSelect.selectedIndex];
        customerName = selectedOption?.textContent || 'Walk-in Customer';
        customerId = selectedValue;
      }
    }
    
    const discountInputEl = document.getElementById('discount-input');
    const discountTypeEl = document.getElementById('discount-type');
    let holdDiscountType = discountTypeEl ? discountTypeEl.value : 'percent';
    let holdDiscountValue = discountInputEl ? parseFloat(discountInputEl.value || '0') : 0;
    if (Number.isNaN(holdDiscountValue)) {
      holdDiscountValue = 0;
    }
    if (!(window.selectedDiscount && window.selectedDiscount.type === 'discount')) {
      if (holdDiscountValue === 0) {
        holdDiscountType = 'none';
      }
    }

    const holdData = {
      customer_name: customerName,
      customer_id: customerId,
      cart_json: JSON.stringify(cartItems),
      table_id: window.selectedTableId || '',
      order_mode: window.selectedOrderMode || '',
      order_taker_id: window.selectedOrderTakerId || '',
      unhold_order_id: window.unholdOrderId || '',
      void_reason_id: window.deleteReasonId || '',
      discount_id: window.selectedDiscount && window.selectedDiscount.type === 'discount' ? window.selectedDiscount.id : '',
      discount_type: holdDiscountType,
      discount_value: holdDiscountValue
    };

    fetch('hold_order_save.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: new URLSearchParams(holdData)
    })
    .then(res => res.json())
    .then(response => {
      if (response.status === 'success') {
        Swal.fire('Order Held Successfully', '', 'success');

        // 🧹 Reset cart and order data (includes customer reset)
        resetCart();

        // 🧽 Clear selected mode & table
        window.selectedOrderMode = null;
        window.selectedTableId = null;
        document.getElementById('selected-order-mode').value = '';
        document.getElementById('selected-table-id').value = '';
        document.querySelectorAll('.order-mode-btn').forEach(btn => btn.classList.remove('active'));

        const tableDisplay = document.getElementById('active-table-name');
        if (tableDisplay) tableDisplay.textContent = '';

        // 🖨️ Trigger KOT Print if setting is enabled
        // Only print if there are actually new items to avoid reprinting existing items
        // 🔧 FIX: Prefer new_hold_item_ids for accurate filtering, fallback to new_items for backward compatibility
        if (response.print_kot && response.hold_id && ((response.new_hold_item_ids && response.new_hold_item_ids.length > 0) || (response.new_items && response.new_items.length > 0))) {
          // Use the new KOT printing function that respects print method setting
          handleKOTPrint(response.hold_id, response.new_items, response.kot_quantities || {}, response.new_hold_item_ids || []);
        }
        
        // 🗑️ Handle Void KOT printing if items were voided during hold (item-wise void)
        if (response.should_print_void_kot && response.voided_items && response.voided_items.length > 0) {
          if (typeof handleVoidKOTPrint === 'function') {
            handleVoidKOTPrint({
              hold_id: response.hold_id,
              voided_items: response.voided_items,
              void_reason: 'Item removed from order',
              void_notes: '',
              hold_order_data: response.hold_order_data || {}
            });
          }
        }

      } else {
        Swal.fire('Failed to hold order', '', 'error');
      }
    })
    .catch(err => {
      console.error('Hold error:', err);
      Swal.fire('Error', 'Could not hold order', 'error');
    });
  });
}



    // 🧾 Receipt & reset
    const printBtn = document.querySelector('#payment-completed button[data-bs-target="#print-receipt"]');
    if (printBtn) {
        printBtn.addEventListener('click', function (e) {
            e.preventDefault();
            const receiptModal = new bootstrap.Modal(document.getElementById('print-receipt'));
            receiptModal.show();
        });
    }

    const printReceiptModal = document.getElementById('print-receipt');
    if (printReceiptModal) {
        printReceiptModal.addEventListener('hidden.bs.modal', function () {
            resetCart();
        });
    }

    function resetCart(resetCustomer = true, resetQuotation = true) {
        cartWrap.innerHTML = '';
        subtotalEl.textContent = 'Rs 0.00';
        totalEl.textContent = 'Rs 0.00';
        taxInput.value = '0 Rs';
        const grandTotalLabel = (window.translations && window.translations.grand_total) ? window.translations.grand_total : 'Grand Total';
        totalDisplay.textContent = grandTotalLabel + ' : Rs 0.00';
        if (resetQuotation) {
            window.loadedQuotationId = null;
            window.loadedQuotationNumber = null;
        }

        window.unholdOrderId = null;
        window.isHoldCart = false;
        window.activeHoldReference = null;
        
        // Reset discount input and display
        if (discountInput) {
            discountInput.value = '0';
        }
        if (discountType) {
            discountType.value = 'percent';
        }
        
        const discountDisplay = document.getElementById('discount-display');
        if (discountDisplay) {
            discountDisplay.textContent = 'Rs 0.00';
        }

        // Reset service charges input and display
        const serviceChargesInput = document.getElementById('service-charges-input');
        if (serviceChargesInput) {
            serviceChargesInput.value = '0';
        }
        
        const serviceChargesDisplay = document.getElementById('service-charges-display');
        if (serviceChargesDisplay) {
            serviceChargesDisplay.textContent = 'Rs 0.00';
        }
        
        // Reset customer selection if requested (default: true)
        if (resetCustomer) {
            const customerDropdown = document.getElementById('top-customer-select');
            const formInput = document.getElementById('form-customer');
            if (customerDropdown) {
                customerDropdown.value = 'walk-in';
            }
            if (formInput) {
                formInput.value = 'Walk-in Customer';
            }
        }
    }
    
    // Make functions globally accessible
    window.resetCart = resetCart;
    window.addItemToCart = addItemToCart;
    window.updateTotal = updateTotal;

    // 🔍 Live Search with Barcode Scanner Support
    const productSearch = document.getElementById("product-search");
    const autocompleteList = document.getElementById("autocomplete-list");
    let currentFocus = -1;
    let barcodeTimeout = null;
    let isBarcodeInput = false;

    function buildSearchUrl(searchTerm) {
        let url = "search_items.php?q=" + encodeURIComponent(searchTerm);
        const customerSelect = document.getElementById("top-customer-select");
        if (customerSelect) {
            const selectedValue = (customerSelect.value || '').trim();
            const numericId = parseInt(selectedValue, 10);
            const disallowedValues = ['walk-in', 'select', 'Walk-in Customer'];
            if (!Number.isNaN(numericId) && !disallowedValues.includes(selectedValue)) {
                url += "&customer_id=" + encodeURIComponent(numericId);
            }
        }
        return url;
    }

    function appendLastPurchaseInfo(optionElement, item) {
        const metaLine = document.createElement("div");
        metaLine.className = "autocomplete-meta";

        if (!item) {
            metaLine.classList.add("autocomplete-meta--empty");
            metaLine.textContent = "No previous purchase for this customer";
            optionElement.appendChild(metaLine);
            return;
        }

        const hasPrice = item.last_purchase_price !== null && item.last_purchase_price !== undefined;
        const hasQty = item.last_purchase_qty !== null && item.last_purchase_qty !== undefined;

        if (!hasPrice || !hasQty) {
            metaLine.classList.add("autocomplete-meta--empty");
            metaLine.textContent = "No previous purchase for this customer";
            optionElement.appendChild(metaLine);
            return;
        }

        const price = parseFloat(item.last_purchase_price);
        const qty = parseFloat(item.last_purchase_qty);

        if (Number.isNaN(price) || Number.isNaN(qty)) {
            metaLine.classList.add("autocomplete-meta--empty");
            metaLine.textContent = "No previous purchase for this customer";
            optionElement.appendChild(metaLine);
            return;
        }

        const qtyDisplay = Number.isInteger(qty) ? qty.toString() : qty.toFixed(2);
        
        // Format the date if available
        let dateDisplay = '';
        if (item.last_purchase_date) {
            try {
                const purchaseDate = new Date(item.last_purchase_date);
                if (!isNaN(purchaseDate.getTime())) {
                    const day = purchaseDate.getDate().toString().padStart(2, '0');
                    const month = (purchaseDate.getMonth() + 1).toString().padStart(2, '0');
                    const year = purchaseDate.getFullYear();
                    dateDisplay = ` on ${day}/${month}/${year}`;
                }
            } catch (e) {
                // If date parsing fails, continue without date
            }
        }
        
        metaLine.innerHTML = `<span class="meta-label">Last purchase:</span> ${qtyDisplay} @ Rs ${price.toFixed(2)}${dateDisplay}`;
        optionElement.appendChild(metaLine);
    }

    if (productSearch) {
        // Detect barcode scanner input (rapid input followed by Enter)
        productSearch.addEventListener("input", function () {
            const search = this.value.trim();
            currentFocus = -1;
            
            // Clear previous timeout
            if (barcodeTimeout) {
                clearTimeout(barcodeTimeout);
            }
            
            // Set a short timeout to detect barcode input
            barcodeTimeout = setTimeout(() => {
                isBarcodeInput = false;
            }, 100); // 100ms timeout for barcode detection
            
            if (search.length < 2) {
                autocompleteList.innerHTML = "";
                return;
            }

            fetch(buildSearchUrl(search))
                .then(response => response.json())
                .then(results => {
                    const allProducts = document.querySelectorAll("#product-list .product-info");
                    allProducts.forEach(p => p.style.display = 'none');

                    results.forEach(item => {
                        const product = document.querySelector(`#product-list .product-info[data-id="${item.id}"]`);
                        if (product) product.style.display = '';
                    });

                    autocompleteList.innerHTML = "";
                    results.forEach((item, index) => {
                        const option = document.createElement("div");
                        option.className = "autocomplete-option";
                        option.dataset.id = item.id;
                        const primaryLine = document.createElement("div");
                        primaryLine.className = "autocomplete-main";
                        primaryLine.textContent = item.text;
                        option.appendChild(primaryLine);
                        appendLastPurchaseInfo(option, item);

                        option.addEventListener("click", function () {
                            productSearch.value = "";
                            autocompleteList.innerHTML = "";

                            const product = document.querySelector(`#product-list .product-info[data-id="${item.id}"]`);
                            if (product) {
                                product.click();
                                const addedItem = document.querySelector(`.product-list[data-item-id="${item.id}"]`);
                                if (addedItem) {
                                    addedItem.classList.add("highlight");
                                    setTimeout(() => addedItem.classList.remove("highlight"), 1500);
                                }
                            }
                        });

                        autocompleteList.appendChild(option);
                    });
                    
                    // Auto-select first item if it's a barcode input and we have results
                    if (isBarcodeInput && results.length > 0) {
                        setTimeout(() => {
                            const firstOption = autocompleteList.querySelector(".autocomplete-option");
                            if (firstOption) {
                                firstOption.click();
                            }
                        }, 50);
                    }
                })
                .catch(err => {
                    console.error("Search error:", err);
                    autocompleteList.innerHTML = "";
                });
        });

        productSearch.addEventListener("keydown", function (e) {
            let items = autocompleteList.querySelectorAll(".autocomplete-option");
            
            // Detect barcode scanner input (Enter key pressed)
            if (e.key === "Enter") {
                e.preventDefault();
                isBarcodeInput = true;
                
                // If we have search results, auto-select the first one
                if (items.length > 0) {
                    items[0].click();
                } else {
                    // If no results in dropdown, try to search and auto-select
                    const search = this.value.trim();
                    if (search.length >= 2) {
                        fetch(buildSearchUrl(search))
                            .then(response => response.json())
                            .then(results => {
                                if (results.length > 0) {
                                    // Find and click the matching product
                                    const product = document.querySelector(`#product-list .product-info[data-id="${results[0].id}"]`);
                                    if (product) {
                                        product.click();
                                        const addedItem = document.querySelector(`.product-list[data-item-id="${results[0].id}"]`);
                                        if (addedItem) {
                                            addedItem.classList.add("highlight");
                                            setTimeout(() => addedItem.classList.remove("highlight"), 1500);
                                        }
                                    }
                                    productSearch.value = "";
                                    autocompleteList.innerHTML = "";
                                }
                            })
                            .catch(err => {
                                console.error("Barcode search error:", err);
                            });
                    }
                }
                return;
            }
            
            if (!items.length) return;

            if (e.key === "ArrowDown") {
                currentFocus++;
                setActive(items);
            } else if (e.key === "ArrowUp") {
                currentFocus--;
                setActive(items);
            }
        });

        function setActive(items) {
            removeActive(items);
            if (currentFocus >= items.length) currentFocus = 0;
            if (currentFocus < 0) currentFocus = items.length - 1;
            items[currentFocus].classList.add("active");
        }

        function removeActive(items) {
            for (let item of items) {
                item.classList.remove("active");
            }
        }

        document.addEventListener("click", function (e) {
            if (e.target !== productSearch) {
                autocompleteList.innerHTML = "";
            }
        });
    }
    
    // Initialize feather icons for subcategory area
    if (typeof feather !== 'undefined') {
        feather.replace();
    }
    
    // Function to check if user has price editing rights
    function checkPriceEditRights() {
        fetch('ajax/check_price_edit_right.php')
            .then(response => response.json())
            .then(data => {
                userCanEditPrice = data.has_right;
                console.log('Price editing rights:', userCanEditPrice);
                // Update existing cart items to show/hide price edit buttons
                updateCartItemPriceEditButtons();
            })
            .catch(error => {
                console.error('Error checking price edit rights:', error);
                userCanEditPrice = false;
            });
    }
    
    // Function to update price edit buttons on existing cart items
    function updateCartItemPriceEditButtons() {
        const cartItems = document.querySelectorAll('.product-wrap .product-list');
        cartItems.forEach(item => {
            const priceEditIcon = item.querySelector('.price-edit-icon');
            if (priceEditIcon) {
                if (userCanEditPrice) {
                    priceEditIcon.style.display = 'inline-block';
                } else {
                    priceEditIcon.style.display = 'none';
                }
            }
        });
    }
    
    // Function to show price edit modal
    function showPriceEditModal(cartRow) {
        const itemName = cartRow.querySelector('h6').textContent;
        const currentPrice = parseFloat(cartRow.getAttribute('data-price'));
        const itemCode = cartRow.getAttribute('data-code');
        const itemId = cartRow.getAttribute('data-item-id');
        
        // Create modal HTML
        const modalHtml = `
            <div class="modal fade" id="priceEditModal" tabindex="-1" data-bs-backdrop="static">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">Edit Price: ${itemName}</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                            <div class="mb-3">
                                <label for="newPrice" class="form-label">New Price (Rs)</label>
                                <input type="number" class="form-control" id="newPrice" 
                                       value="${currentPrice.toFixed(2)}" 
                                       min="0.01" step="0.01" required>
                                <div class="form-text">Current price: Rs ${currentPrice.toFixed(2)}</div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                            <button type="button" class="btn btn-primary" id="confirmPriceEdit">Update Price</button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        // Remove existing modal
        const existingModal = document.getElementById('priceEditModal');
        if (existingModal) {
            existingModal.remove();
        }
        
        // Add modal to body
        document.body.insertAdjacentHTML('beforeend', modalHtml);
        
        // Bind events
        document.getElementById('confirmPriceEdit').addEventListener('click', function() {
            const newPrice = parseFloat(document.getElementById('newPrice').value);
            if (newPrice > 0) {
                updateCartItemPrice(cartRow, itemCode, itemId, newPrice);
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Invalid Price',
                    text: 'Price must be greater than 0',
                    confirmButtonColor: '#d33'
                });
            }
        });
        
        // Show modal
        const modalElement = document.getElementById('priceEditModal');
        const modal = new bootstrap.Modal(modalElement);
        modal.show();
        
        // Focus on input
        setTimeout(() => {
            document.getElementById('newPrice').focus();
            document.getElementById('newPrice').select();
        }, 500);
    }
    
    // Function to update cart item price
    function updateCartItemPrice(cartRow, itemCode, itemId, newPrice) {
        const formData = new FormData();
        formData.append('item_code', itemCode);
        formData.append('item_id', itemId);
        formData.append('new_price', newPrice);
        
        // Show loading
        Swal.fire({
            title: 'Updating Price...',
            text: 'Please wait',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });
        
        fetch('ajax/update_cart_item_price.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const saleMode = cartRow.getAttribute('data-sale-mode') || 'loose';
                const bulkQty = parseFloat(cartRow.getAttribute('data-bulk-qty')) || 0;
                if (saleMode === 'bulk' && bulkQty > 0) {
                    cartRow.setAttribute('data-price', newPrice.toFixed(4));
                    cartRow.setAttribute('data-bulk-per-unit-price', newPrice.toFixed(4));
                    cartRow.setAttribute('data-bulk-pack-price', (newPrice * bulkQty).toFixed(4));
                } else {
                    cartRow.setAttribute('data-price', newPrice.toFixed(4));
                    cartRow.setAttribute('data-retail-unit-price', newPrice.toFixed(4));
                }
                
                // Close modal
                const modal = bootstrap.Modal.getInstance(document.getElementById('priceEditModal'));
                modal.hide();
                
                // Update totals
                updateTotal();
                
                // Show success message
                Swal.fire({
                    icon: 'success',
                    title: 'Price Updated',
                    text: data.message,
                    confirmButtonColor: '#28a745'
                });
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: data.message,
                    confirmButtonColor: '#d33'
                });
            }
        })
        .catch(error => {
            console.error('Error updating price:', error);
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'Failed to update price. Please try again.',
                confirmButtonColor: '#d33'
            });
        });
    }
});

// Item options modal (remarks + discount)
function showItemOptionsModal(cartRow) {
    const itemName = cartRow.querySelector('h6').textContent;
    const currentRemarks = cartRow.getAttribute('data-remarks') || '';
    const discountInfo = getRowDiscountInfo(cartRow);
    const unitPrice = discountInfo.price;
    const qty = normalizeQuantity(cartRow.querySelector('input[name="qty"]').value, POS_QTY_MIN);

    const modalHtml = `
        <div class="modal fade" id="itemOptionsModal" tabindex="-1" data-bs-backdrop="static">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Item Options: ${itemName}</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="itemRemarksInput" class="form-label">Special Instructions</label>
                            <textarea class="form-control" id="itemRemarksInput" rows="3" placeholder="Enter any special instructions for this item...">${currentRemarks}</textarea>
                        </div>
                        <hr class="my-3">
                        <div class="mb-3">
                            <label for="itemDiscountType" class="form-label">Per-Item Discount</label>
                            <select class="form-select" id="itemDiscountType">
                                <option value="none">No Discount</option>
                                <option value="percent">% Percentage</option>
                                <option value="fixed">Fixed Amount</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="itemDiscountValue" class="form-label">Discount Value</label>
                            <input type="number" class="form-control" id="itemDiscountValue" min="0" step="0.01" placeholder="Enter value">
                            <div class="form-text">
                                For percentage discounts enter 0 - 100. Fixed amount applies per item.
                            </div>
                        </div>
                        <div class="alert alert-info py-2 px-3" id="itemDiscountPreview" role="alert">
                            No discount applied.
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="button" class="btn btn-primary" id="saveItemOptionsBtn">Save Changes</button>
                    </div>
                </div>
            </div>
        </div>
    `;

    const existingModal = document.getElementById('itemOptionsModal');
    if (existingModal) {
        existingModal.remove();
    }

    document.body.insertAdjacentHTML('beforeend', modalHtml);

    const typeSelect = document.getElementById('itemDiscountType');
    const valueInput = document.getElementById('itemDiscountValue');
    const previewEl = document.getElementById('itemDiscountPreview');
    const remarksInput = document.getElementById('itemRemarksInput');

    const initialType = ['percent', 'fixed'].includes(discountInfo.type) ? discountInfo.type : 'none';
    typeSelect.value = initialType;
    valueInput.value = initialType === 'none' ? '' : discountInfo.value;
    valueInput.disabled = initialType === 'none';

    function renderPreview() {
        const selectedType = typeSelect.value;
        let inputValue = parseFloat(valueInput.value) || 0;
        let perUnitDiscount = 0;

        if (selectedType === 'percent') {
            if (inputValue > 100) inputValue = 100;
            if (inputValue < 0) inputValue = 0;
            valueInput.value = inputValue;
            perUnitDiscount = unitPrice * (inputValue / 100);
        } else if (selectedType === 'fixed') {
            if (inputValue > unitPrice) inputValue = unitPrice;
            if (inputValue < 0) inputValue = 0;
            valueInput.value = inputValue;
            perUnitDiscount = inputValue;
        } else {
            perUnitDiscount = 0;
            valueInput.value = '';
        }

        if (perUnitDiscount > unitPrice) {
            perUnitDiscount = unitPrice;
        }

        if (perUnitDiscount > 0) {
            const totalLineDiscount = perUnitDiscount * qty;
            const netPerItem = unitPrice - perUnitDiscount;
            previewEl.classList.remove('alert-warning');
            previewEl.classList.add('alert-info');
            previewEl.textContent = `Per item discount: Rs ${perUnitDiscount.toFixed(2)} | Total: Rs ${totalLineDiscount.toFixed(2)} | Net per item: Rs ${netPerItem.toFixed(2)}`;
        } else {
            previewEl.classList.add('alert-info');
            previewEl.classList.remove('alert-warning');
            previewEl.textContent = 'No discount applied.';
        }
    }

    typeSelect.addEventListener('change', () => {
        valueInput.disabled = typeSelect.value === 'none';
        if (typeSelect.value === 'none') {
            valueInput.value = '';
        }
        renderPreview();
    });

    valueInput.addEventListener('input', renderPreview);
    renderPreview();

    document.getElementById('saveItemOptionsBtn').addEventListener('click', function() {
        const selectedType = typeSelect.value;
        let enteredValue = parseFloat(valueInput.value);

        if (selectedType === 'percent') {
            if (isNaN(enteredValue) || enteredValue < 0 || enteredValue > 100) {
                if (window.Swal) {
                    Swal.fire('Invalid Discount', 'Please enter a percentage between 0 and 100.', 'warning');
                } else {
                    alert('Please enter a percentage between 0 and 100.');
                }
                return;
            }
        } else if (selectedType === 'fixed') {
            if (isNaN(enteredValue) || enteredValue < 0 || enteredValue > unitPrice) {
                if (window.Swal) {
                    Swal.fire('Invalid Discount', `Enter an amount between 0 and Rs ${unitPrice.toFixed(2)}.`, 'warning');
                } else {
                    alert(`Enter an amount between 0 and Rs ${unitPrice.toFixed(2)}.`);
                }
                return;
            }
        } else {
            enteredValue = 0;
        }

        const remarks = remarksInput.value.trim();
        cartRow.setAttribute('data-remarks', remarks);

        const remarksSection = cartRow.querySelector('.remarks-section');
        const remarksText = cartRow.querySelector('.remarks-text');

        if (remarks) {
            remarksSection.style.display = 'block';
            remarksText.textContent = `💬 ${remarks}`;
        } else if (remarksSection) {
            remarksSection.style.display = 'none';
            remarksText.textContent = '';
        }

        let perUnitDiscount = 0;
        if (selectedType === 'percent') {
            perUnitDiscount = unitPrice * (enteredValue / 100);
        } else if (selectedType === 'fixed') {
            perUnitDiscount = enteredValue;
        }

        if (perUnitDiscount > unitPrice) {
            perUnitDiscount = unitPrice;
        }
        if (perUnitDiscount < 0 || !isFinite(perUnitDiscount)) {
            perUnitDiscount = 0;
        }

        const newDiscountInfo = {
            type: selectedType,
            value: selectedType === 'none' ? 0 : enteredValue,
            perUnit: perUnitDiscount,
            price: unitPrice
        };

        updateRowDiscountAttributes(cartRow, newDiscountInfo);
        updateTotal();

        const modalEl = document.getElementById('itemOptionsModal');
        const modal = bootstrap.Modal.getInstance(modalEl);
        modal.hide();
    });

    const modal = new bootstrap.Modal(document.getElementById('itemOptionsModal'));
    document.getElementById('itemOptionsModal').addEventListener('hidden.bs.modal', () => {
        const modalEl = document.getElementById('itemOptionsModal');
        if (modalEl) {
            modalEl.remove();
        }
    });
    modal.show();
}

// 🔧 Address aria-hidden warning: clear header focus before modals hide it
document.addEventListener('show.bs.modal', function () {
    const stickyHeader = document.querySelector('.sticky-top');
    if (!stickyHeader) return;

    const focusedElement = document.activeElement;
    if (focusedElement && stickyHeader.contains(focusedElement)) {
        focusedElement.blur();
    }
});

/**
 * Handle receipt printing from POS
 */
async function handleReceiptPrint() {
    try {
        // Get print settings
        const printMethod = await getPrintSetting('print_method');
        
        if (printMethod === 'direct') {
            // Use direct printing
            await executeDirectReceiptPrint();
        } else {
            // Use current popup method
            showReceiptModal();
        }
    } catch (error) {
        console.error('Receipt print error:', error);
        // Fallback to popup method
        showReceiptModal();
    }
}

/**
 * Handle KOT printing from POS
 */
async function handleKOTPrint(holdId, newItems = [], kotQuantities = {}, newHoldItemIds = []) {
    try {
        // Get print settings
        const printMethod = await getPrintSetting('print_method');
        console.log('KOT Print Method:', printMethod); // DEBUG
        
        if (printMethod === 'direct') {
            // Use direct printing via print system
            // 🔧 FIX: Pass newHoldItemIds for accurate filtering (handles items with different modifiers correctly)
            await executeDirectKOTPrint(holdId, newItems, kotQuantities, newHoldItemIds);
        } else {
            // Use popup method (current behavior)
            showKOTPopup(holdId, newItems);
        }
    } catch (error) {
        console.error('KOT print error:', error);
        // Fallback to popup method
        showKOTPopup(holdId, newItems);
    }
}

/**
 * Print receipt from recent transactions/history
 */
async function printReceiptFromHistory(saleId) {
    try {
        // Get print settings
        const printMethod = await getPrintSetting('print_method');
        console.log('Receipt Print Method (History):', printMethod, 'Sale ID:', saleId);
        
        if (printMethod === 'direct') {
            // Use direct printing
            await executeDirectReceiptPrintFromHistory(saleId);
        } else {
            // Use popup method
            const printWindow = window.open(`print_receipt.php?sale_id=${saleId}`, '_blank', 'width=400,height=600');
            if (printWindow) {
                printWindow.focus();
            } else {
                alert('Please allow popups to print receipts.');
            }
        }
    } catch (error) {
        console.error('Receipt print error (history):', error);
        // Fallback to popup method
        const printWindow = window.open(`print_receipt.php?sale_id=${saleId}`, '_blank', 'width=400,height=600');
        if (printWindow) {
            printWindow.focus();
        }
    }
}

/**
 * Execute direct receipt printing from history
 */
async function executeDirectReceiptPrintFromHistory(saleId) {
    try {
        if (!saleId) {
            throw new Error('Sale ID is required');
        }
        
        // Get receipt devices
        const receiptDevices = await getDevicesForType('receipt');
        
        if (!receiptDevices || receiptDevices.length === 0) {
            throw new Error('No receipt printers configured');
        }
        
        // Get default receipt device
        const defaultDevice = receiptDevices.find(device => device.is_default == 1) || receiptDevices[0];
        
        // Prepare sale data for printing
        const saleData = {
            sale_id: saleId,
            type: 'receipt'
        };
        
        // Execute direct print
        const result = await window.printSystem.executePrint('receipt', saleData, defaultDevice.id);
        
        if (result.success) {
            // Show success message
            Swal.fire({
                title: 'Receipt Printed!',
                text: `Receipt sent to ${defaultDevice.name}`,
                icon: 'success',
                timer: 2000,
                showConfirmButton: false
            });
        } else {
            throw new Error(result.message || 'Failed to print receipt');
        }
        
    } catch (error) {
        console.error('Direct receipt print from history failed:', error);
        
        Swal.fire({
            title: 'Print Failed',
            text: error.message || 'Could not print receipt',
            icon: 'error',
            confirmButtonText: 'OK'
        });
        
        // Fallback to popup
        const printWindow = window.open(`print_receipt.php?sale_id=${saleId}`, '_blank', 'width=400,height=600');
        if (printWindow) {
            printWindow.focus();
        }
    }
}

/**
 * Handle Proforma Invoice printing from POS
 */
async function handleProformaPrint(holdId) {
    try {
        // Show dialog to select payment method (Cash or Card)
        const { value: paymentMethod } = await Swal.fire({
            title: 'Select Payment Method',
            text: 'Choose the payment method for the proforma invoice',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Continue',
            cancelButtonText: 'Cancel',
            input: 'radio',
            inputOptions: {
                'cash': 'Cash',
                'card': 'Card'
            },
            inputValidator: (value) => {
                if (!value) {
                    return 'You need to select a payment method!';
                }
            }
        });
        
        if (!paymentMethod) {
            return; // User cancelled
        }
        
        // Get print settings
        const printMethod = await getPrintSetting('print_method');
        
        if (printMethod === 'direct') {
            // Use direct printing via print system
            await executeDirectProformaPrint(holdId, paymentMethod);
        } else {
            // Use popup method (current behavior)
            showProformaPopup(holdId, paymentMethod);
        }
    } catch (error) {
        console.error('Proforma print error:', error);
        // Fallback to popup method (without payment method selection on error)
        showProformaPopup(holdId);
    }
}

/**
 * Execute direct KOT printing using print system with station-based routing
 */
async function executeDirectKOTPrint(holdId, newItems = [], kotQuantities = {}, newHoldItemIds = []) {
    try {
        // Get station-based routing information
        // 🔧 FIX: Prefer new_hold_item_ids for accurate filtering (handles items with different modifiers correctly)
        const newHoldItemIdsParam = Array.isArray(newHoldItemIds) && newHoldItemIds.length > 0 ? newHoldItemIds.join(',') : '';
        const newItemsParam = Array.isArray(newItems) && newItems.length > 0 ? newItems.join(',') : '';
        const kotQuantitiesParam = Object.keys(kotQuantities).length > 0 ? encodeURIComponent(JSON.stringify(kotQuantities)) : '';
        const routingUrl = `ajax/get_kot_station_routing.php?hold_id=${holdId}${newHoldItemIdsParam ? '&new_hold_item_ids=' + newHoldItemIdsParam : (newItemsParam ? '&new_items=' + newItemsParam : '')}${kotQuantitiesParam ? '&kot_quantities=' + kotQuantitiesParam : ''}`;
        
        const routingResponse = await fetch(routingUrl);
        const routingData = await routingResponse.json();
        
        if (!routingData.success) {
            throw new Error(routingData.message || 'Failed to get routing information');
        }
        
        const successes = [];
        const failures = [];
        
        // Check print modes and group printers by mode
        const autoPrintGroups = [];
        const askPrintGroups = [];
        
        for (const stationGroup of routingData.station_groups) {
            const printMode = stationGroup.print_mode || 'auto';
            if (printMode === 'ask') {
                askPrintGroups.push(stationGroup);
            } else {
                autoPrintGroups.push(stationGroup);
            }
        }
        
        // Handle unassigned items print mode
        if (routingData.unassigned_items && routingData.unassigned_items.length > 0) {
            if (routingData.default_printer) {
                const defaultPrintMode = routingData.default_printer.print_mode || 'auto';
                if (defaultPrintMode === 'ask') {
                    askPrintGroups.push({
                        station_id: null,
                        station_name: 'Unassigned Items',
                        printer_name: routingData.default_printer.printer_name,
                        printer_device_id: routingData.default_printer.printer_device_id,
                        items: routingData.unassigned_items,
                        is_unassigned: true
                    });
                } else {
                    autoPrintGroups.push({
                        station_id: null,
                        station_name: 'Unassigned Items',
                        printer_name: routingData.default_printer.printer_name,
                        printer_device_id: routingData.default_printer.printer_device_id,
                        items: routingData.unassigned_items,
                        is_unassigned: true
                    });
                }
            } else {
                // No default printer configured for unassigned items
                failures.push({
                    station: 'Unassigned Items',
                    printer: 'None',
                    message: 'No default KOT printer configured'
                });
            }
        }
        
        // If there are printers with "ask" mode, show confirmation dialog
        if (askPrintGroups.length > 0) {
            const printerList = askPrintGroups.map(g => `• ${g.station_name} → ${g.printer_name}`).join('<br>');
            const confirmed = await Swal.fire({
                title: 'Print KOT?',
                html: `<div class="text-start">
                    <p>The following printers are set to "Ask User" mode:</p>
                    <div class="mb-3">${printerList}</div>
                    <p>Do you want to print the KOT?</p>
                </div>`,
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Yes, Print',
                cancelButtonText: 'Cancel',
                confirmButtonColor: '#3085d6'
            });
            
            if (!confirmed.isConfirmed) {
                // User cancelled
                return;
            }
        }
        
        // Process auto print groups first
        for (const stationGroup of autoPrintGroups) {
            try {
                // Prepare KOT data for this station
                const kotData = {
                    type: 'kot',
                    hold_id: holdId,
                    order_number: holdId,
                    station_id: stationGroup.station_id,
                    station_name: stationGroup.station_name,
                    items: stationGroup.items,
                    order: routingData.order,
                    table_name: routingData.table_name,
                    order_taker_name: routingData.order_taker_name,
                    timestamp: new Date().toISOString()
                };
                
                // Print to station's assigned printer
                const result = await window.printSystem.executePrint('kot', kotData, stationGroup.printer_device_id, false, { skipDialogFallback: true });
                
                if (result && result.success) {
                    successes.push({ 
                        station: stationGroup.station_name,
                        printer: stationGroup.printer_name, 
                        message: result.message,
                        item_count: stationGroup.items.length
                    });
                    console.log(`KOT for ${stationGroup.station_name} printed on ${stationGroup.printer_name}:`, result.message);
                } else {
                    failures.push({ 
                        station: stationGroup.station_name,
                        printer: stationGroup.printer_name, 
                        message: result ? result.message : 'Unknown error' 
                    });
                    console.error(`KOT print failed for ${stationGroup.station_name}:`, result ? result.message : 'Unknown error');
                }
            } catch (stationError) {
                failures.push({ 
                    station: stationGroup.station_name,
                    printer: stationGroup.printer_name, 
                    message: stationError.message || 'Unexpected error' 
                });
                console.error(`KOT print exception for ${stationGroup.station_name}:`, stationError);
            }
        }
        
        // Process ask print groups (user already confirmed)
        for (const stationGroup of askPrintGroups) {
            try {
                // Prepare KOT data for this station
                const kotData = {
                    type: 'kot',
                    hold_id: holdId,
                    order_number: holdId,
                    station_id: stationGroup.station_id,
                    station_name: stationGroup.station_name,
                    items: stationGroup.items,
                    order: routingData.order,
                    table_name: routingData.table_name,
                    order_taker_name: routingData.order_taker_name,
                    timestamp: new Date().toISOString()
                };
                
                // Print to station's assigned printer
                const result = await window.printSystem.executePrint('kot', kotData, stationGroup.printer_device_id, false, { skipDialogFallback: true });
                
                if (result && result.success) {
                    successes.push({ 
                        station: stationGroup.station_name,
                        printer: stationGroup.printer_name, 
                        message: result.message,
                        item_count: stationGroup.items.length
                    });
                    console.log(`KOT for ${stationGroup.station_name} printed on ${stationGroup.printer_name}:`, result.message);
                } else {
                    failures.push({ 
                        station: stationGroup.station_name,
                        printer: stationGroup.printer_name, 
                        message: result ? result.message : 'Unknown error' 
                    });
                    console.error(`KOT print failed for ${stationGroup.station_name}:`, result ? result.message : 'Unknown error');
                }
            } catch (stationError) {
                failures.push({ 
                    station: stationGroup.station_name,
                    printer: stationGroup.printer_name, 
                    message: stationError.message || 'Unexpected error' 
                });
                console.error(`KOT print exception for ${stationGroup.station_name}:`, stationError);
            }
        }
        
        // Show results to user
        if (successes.length > 0) {
            let htmlMessage = `<div class="text-start"><p><strong>KOT sent to:</strong></p><ul class="mb-0">`;
            successes.forEach(entry => {
                htmlMessage += `<li><strong>${entry.station}</strong> → ${entry.printer} (${entry.item_count} item${entry.item_count > 1 ? 's' : ''})</li>`;
            });
            htmlMessage += '</ul>';
            
            if (failures.length > 0) {
                htmlMessage += '<hr class="my-2"><p class="mb-1"><strong>Failed stations:</strong></p><ul class="mb-0 text-danger">';
                failures.forEach(entry => {
                    htmlMessage += `<li><strong>${entry.station}</strong> → ${entry.printer}: ${entry.message}</li>`;
                });
                htmlMessage += '</ul>';
            }
            htmlMessage += '</div>';

            Swal.fire({
                title: failures.length === 0 ? 'KOT Printed' : 'Partial KOT Print',
                html: htmlMessage,
                icon: failures.length === 0 ? 'success' : 'warning',
                confirmButtonText: 'OK'
            });
        }

        if (successes.length === 0) {
            console.warn('All KOT prints failed. Falling back to popup printing.');
            // Fallback to popup if direct printing fails for all devices
            showKOTPopup(holdId, newItems);
        }
    } catch (error) {
        console.error('Direct KOT print error:', error);
        // Fallback to popup method
        showKOTPopup(holdId, newItems);
    }
}

/**
 * Show KOT popup (fallback method)
 */
function showKOTPopup(holdId, newItems = []) {
    let kotUrl = `print_kot.php?id=${holdId}`;
    if (newItems && newItems.length > 0) {
        kotUrl += `&items=${newItems.join(',')}`;
    }
    const kotWindow = window.open(kotUrl, 'KOT_Print', 'width=600,height=700');
    if (kotWindow) kotWindow.focus();
}

/**
 * Handle Void KOT printing - Notify kitchen staff about cancelled/voided orders
 */
async function handleVoidKOTPrint(voidData) {
    try {
        // Check print method setting
        const printMethod = await getPrintSetting('print_method');
        console.log('Void KOT Print Method:', printMethod); // DEBUG
        
        if (printMethod !== 'direct') {
            console.log('Direct print not enabled, skipping void KOT print');
            return;
        }
        
        // Get voided items and order data
        const voidedItems = voidData.voided_items || [];
        const holdOrderData = voidData.hold_order_data || {};
        const voidReason = voidData.void_reason || 'Order cancelled';
        const voidNotes = voidData.void_notes || '';
        const orderNumber = voidData.unhold_order_id || voidData.hold_id || 'N/A';
        
        if (voidedItems.length === 0) {
            console.log('No voided items to print');
            return;
        }
        
        // Get voided by user name from session if available
        const voidedBy = window.userName || '';
        
        // Get KOT devices (use same routing as regular KOT)
        const kotDevices = await getDevicesForType('kot');
        
        if (!kotDevices || kotDevices.length === 0) {
            console.warn('No KOT printers configured for void notification');
            return;
        }
        
        // Group items by station using station info from voided items
        const stationsMap = new Map();
        const itemsWithoutStation = [];
        
        for (const item of voidedItems) {
            if (item.station_id && item.station_name) {
                if (!stationsMap.has(item.station_id)) {
                    stationsMap.set(item.station_id, {
                        station_id: item.station_id,
                        station_name: item.station_name,
                        items: []
                    });
                }
                stationsMap.get(item.station_id).items.push(item);
            } else {
                itemsWithoutStation.push(item);
            }
        }
        
        const successes = [];
        const failures = [];
        
        // If we have station-grouped items, send to each station's printer
        if (stationsMap.size > 0) {
            for (const [stationId, stationData] of stationsMap) {
                try {
                    // Get printer for this station
                    const stationPrinterResponse = await fetch(`ajax/get_station_printer.php?station_id=${stationId}`);
                    const stationPrinterData = await stationPrinterResponse.json();
                    
                    if (!stationPrinterData.success || !stationPrinterData.printer_id) {
                        console.warn(`No printer configured for station: ${stationData.station_name}`);
                        itemsWithoutStation.push(...stationData.items);
                        continue;
                    }
                    
                    const voidKotData = {
                        type: 'void_kot',
                        order_number: orderNumber,
                        voided_items: stationData.items,
                        void_reason: voidReason,
                        void_notes: voidNotes,
                        voided_by: voidedBy,
                        station_name: stationData.station_name,
                        table_name: holdOrderData.table_name || '',
                        order_mode: holdOrderData.order_mode || '',
                        order_taker_name: holdOrderData.order_taker_name || ''
                    };
                    
                    // Print to station's assigned printer
                    const result = await window.printSystem.executePrint(
                        'kot', 
                        voidKotData, 
                        stationPrinterData.printer_id, 
                        false, 
                        { skipDialogFallback: true }
                    );
                    
                    if (result && result.success) {
                        successes.push({
                            station: stationData.station_name,
                            printer: stationPrinterData.printer_name,
                            message: 'Void notification sent'
                        });
                        console.log(`Void KOT for ${stationData.station_name} printed successfully`);
                    } else {
                        failures.push({
                            station: stationData.station_name,
                            printer: stationPrinterData.printer_name,
                            message: result ? result.message : 'Unknown error'
                        });
                    }
                } catch (stationError) {
                    console.error(`Void KOT print failed for station ${stationData.station_name}:`, stationError);
                    failures.push({
                        station: stationData.station_name,
                        message: stationError.message
                    });
                }
            }
        }
        
        // Handle items without station assignment - send to default printer
        if (itemsWithoutStation.length > 0) {
            // No station routing - send to default KOT printer
            const defaultDevice = kotDevices.find(device => device.is_default == 1) || kotDevices[0];
            
            const voidKotData = {
                type: 'void_kot',
                order_number: orderNumber,
                voided_items: itemsWithoutStation,
                void_reason: voidReason,
                void_notes: voidNotes,
                voided_by: voidedBy,
                table_name: holdOrderData.table_name || '',
                order_mode: holdOrderData.order_mode || '',
                order_taker_name: holdOrderData.order_taker_name || ''
            };
            
            const result = await window.printSystem.executePrint('kot', voidKotData, defaultDevice.id);
            
            if (result && result.success) {
                successes.push({
                    printer: defaultDevice.name,
                    message: 'Void notification sent'
                });
                console.log('Void KOT printed to default kitchen printer');
            } else {
                failures.push({
                    printer: defaultDevice.name,
                    message: result ? result.message : 'Failed to print void notification'
                });
            }
        }
        
        // Show result notification (optional - can be silent)
        if (successes.length > 0) {
            console.log(`Void KOT sent to ${successes.length} printer(s)`);
            // Optionally show a small toast notification
            // Swal.fire({
            //     toast: true,
            //     position: 'top-end',
            //     icon: 'info',
            //     title: 'Kitchen notified of void',
            //     showConfirmButton: false,
            //     timer: 2000
            // });
        }
        
        if (failures.length > 0) {
            console.warn('Some void KOT prints failed:', failures);
        }
        
    } catch (error) {
        console.error('Void KOT print error:', error);
        // Fail silently - void notification is supplementary
    }
}

/**
 * Execute direct proforma invoice printing
 */
async function executeDirectProformaPrint(holdId, paymentMethod = null) {
    try {
        // Prepare proforma print data
        const proformaData = {
            type: 'receipt',
            sale_id: holdId,
            is_proforma: true,
            payment_method: paymentMethod // Pass payment method to print
        };
        
        // Get receipt devices (proforma uses receipt printer)
        const receiptDevices = await getDevicesForType('receipt');
        
        if (!receiptDevices || receiptDevices.length === 0) {
            throw new Error('No receipt printers configured');
        }
        
        // Get default receipt device
        const defaultDevice = receiptDevices.find(device => device.is_default == 1) || receiptDevices[0];
        
        // Execute direct print
        const result = await window.printSystem.executePrint('receipt', proformaData, defaultDevice.id);
        
        if (result.success) {
            // Show success message
            Swal.fire({
                title: 'Proforma Printed!',
                text: `Proforma invoice sent to ${defaultDevice.name}`,
                icon: 'success',
                timer: 2000,
                showConfirmButton: false
            });
        } else {
            throw new Error(result.message || 'Failed to print proforma invoice');
        }
        
    } catch (error) {
        console.error('Direct proforma print failed:', error);
        
        // Show error message
        Swal.fire({
            title: 'Print Failed',
            html: `
                <div class="text-start">
                    <p><strong>Direct printing failed:</strong></p>
                    <p>${error.message}</p>
                    <p class="mt-3">Would you like to try popup printing instead?</p>
                </div>
            `,
            icon: 'error',
            showCancelButton: true,
            confirmButtonText: 'Try Popup',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                showProformaPopup(holdId, paymentMethod);
            }
        });
    }
}

/**
 * Show proforma invoice in popup window
 */
function showProformaPopup(holdId, paymentMethod = null) {
    // Build URL with payment method parameter if provided
    let proformaUrl = `print_proforma_invoice.php?id=${holdId}`;
    if (paymentMethod) {
        proformaUrl += `&payment_method=${paymentMethod}`;
    }
    
    const proformaWindow = window.open(proformaUrl, 'Proforma_Print', 'width=800,height=900');
    if (proformaWindow) {
        proformaWindow.focus();
    } else {
        Swal.fire({
            icon: 'error',
            title: 'Popup Blocked',
            text: 'Please allow popups for this site to print proforma invoices',
            confirmButtonColor: '#d33'
        });
    }
}

/**
 * Execute direct receipt printing
 */
async function executeDirectReceiptPrint() {
    try {
        // Get current sale data
        const saleData = getCurrentSaleData();
        
        if (!saleData) {
            throw new Error('No sale data available for printing');
        }
        
        // Get receipt devices
        const receiptDevices = await getDevicesForType('receipt');
        
        if (!receiptDevices || receiptDevices.length === 0) {
            throw new Error('No receipt printers configured');
        }
        
        // Get default receipt device
        const defaultDevice = receiptDevices.find(device => device.is_default == 1) || receiptDevices[0];
        
        // Execute direct print
        const result = await window.printSystem.executePrint('receipt', saleData, defaultDevice.id);
        
        if (result.success) {
            // Close the payment completed modal
            const paymentModal = bootstrap.Modal.getInstance(document.getElementById('payment-completed'));
            if (paymentModal) {
                paymentModal.hide();
            }
            
            // Show success message
            Swal.fire({
                title: 'Receipt Printed!',
                text: `Receipt sent to ${defaultDevice.name}`,
                icon: 'success',
                timer: 2000,
                showConfirmButton: false
            });
        } else {
            throw new Error(result.message || 'Failed to print receipt');
        }
        
    } catch (error) {
        console.error('Direct receipt print failed:', error);
        
        // Show error message
        Swal.fire({
            title: 'Print Failed',
            html: `
                <div class="text-start">
                    <p><strong>Direct printing failed:</strong></p>
                    <p>${error.message}</p>
                    <p class="mt-3">Would you like to try popup printing instead?</p>
                </div>
            `,
            icon: 'error',
            showCancelButton: true,
            confirmButtonText: 'Try Popup',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                showReceiptModal();
            }
        });
    }
}

/**
 * Get current sale data for printing
 */
function getCurrentSaleData() {
    // Get sale data from the current sale in the modal
    const saleId = window.lastSaleId || null;
    
    if (!saleId) {
        return null;
    }
    
    // Return sale data structure for printing
    return {
        type: 'receipt',
        sale_id: saleId,
        // Additional data will be fetched by the print endpoint
    };
}

/**
 * Get print setting value
 */
async function getPrintSetting(settingCode) {
    try {
        const response = await fetch(`ajax/get_print_settings.php?code=${settingCode}`);
        const result = await response.json();
        return result.value || 'popup'; // Default to popup
    } catch (error) {
        console.error('Failed to get print setting:', error);
        return 'popup'; // Default to popup on error
    }
}

/**
 * Get devices for specific print type
 */
async function getDevicesForType(printType) {
    try {
        const response = await fetch('ajax/get_print_devices.php');
        const result = await response.json();
        
        if (result.success) {
            return result.devices.filter(device => 
                device.is_active == 1 && 
                (device.print_type === printType || device.print_type === 'all')
            );
        }
        return [];
    } catch (error) {
        console.error('Failed to get print devices:', error);
        return [];
    }
}

/**
 * Show receipt modal (current popup method)
 */
function showReceiptModal() {
    // Close the payment completed modal first
    const paymentModal = bootstrap.Modal.getInstance(document.getElementById('payment-completed'));
    if (paymentModal) {
        paymentModal.hide();
    }
    
    // Open the actual print window instead of the modal
    const saleId = window.lastSaleId;
    if (saleId) {
        const printWindow = window.open(`print_receipt.php?sale_id=${saleId}`, '_blank', 'width=400,height=600');
        if (printWindow) {
            printWindow.focus();
        } else {
            alert('Please allow popups to print receipts.');
        }
    } else {
        alert('No sale data available for printing.');
    }
}

// ===== MODIFIER TEMPLATES FUNCTIONS =====

// Show template selection modal (all templates)
function showTemplateSelectionModal(itemId, event) {
    event.stopPropagation(); // Prevent cart item click
    
    fetch('ajax/get_modifier_templates.php')
        .then(response => response.json())
        .then(data => {
            if (data.success && data.templates.length > 0) {
                // Get cart item details
                const cartItem = document.querySelector(`[data-item-id="${itemId}"]`);
                const itemName = cartItem.querySelector('h6').textContent.trim();
                const itemPrice = parseFloat(cartItem.querySelector('.price-display').textContent.replace(/[^\d.]/g, ''));
                
                // Create and show template selection modal
                createTemplateSelectionModal(itemId, itemName, itemPrice, data.templates);
            }
        });
}

// Create template selection modal (shows all templates)
function createTemplateSelectionModal(itemId, itemName, itemPrice, templates) {
    const modalHtml = `
        <div class="modal fade" id="templateSelectionModal" tabindex="-1" data-bs-backdrop="static">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Customize: ${itemName}</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="text-center mb-3">
                            <h6>Base Price: Rs ${itemPrice.toFixed(2)}</h6>
                            <h5 id="templateSelectionTotalPrice">Total: Rs ${itemPrice.toFixed(2)}</h5>
                        </div>
                        <div class="template-selection">
                            <h6 class="mb-3">Select Template:</h6>
                            <div class="row">
                                ${templates.map(template => `
                                    <div class="col-md-6 mb-3">
                                        <div class="template-card" onclick="selectTemplate(${template.id}, ${itemId}, '${itemName}', ${itemPrice})">
                                            <div class="template-icon-large">
                                                <i data-feather="${template.icon}" class="feather-24"></i>
                                            </div>
                                            <div class="template-name">${template.name}</div>
                                        </div>
                                    </div>
                                `).join('')}
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // Remove existing modal
    const existingModal = document.getElementById('templateSelectionModal');
    if (existingModal) existingModal.remove();
    
    // Add modal to body
    document.body.insertAdjacentHTML('beforeend', modalHtml);
    
    // Show modal
    const modal = new bootstrap.Modal(document.getElementById('templateSelectionModal'));
    modal.show();
    
    // Initialize feather icons
    feather.replace();
}

// Select template and show options
function selectTemplate(templateId, itemId, itemName, itemPrice) {
    // Close template selection modal
    const selectionModal = document.getElementById('templateSelectionModal');
    if (selectionModal) {
        bootstrap.Modal.getInstance(selectionModal).hide();
    }
    
    // Now show template options modal
    fetch(`ajax/get_template_options.php?template_id=${templateId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                createTemplateModal(templateId, itemId, itemName, itemPrice, data.options);
            }
        });
}

// Create template options modal
function createTemplateModal(templateId, itemId, itemName, itemPrice, options) {
    const modalHtml = `
        <div class="modal fade" id="templateModal" tabindex="-1" data-bs-backdrop="static">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Customize: ${itemName}</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="text-center mb-4">
                            <div class="alert alert-info">
                                <h6 class="mb-1">Base Price: Rs ${itemPrice.toFixed(2)}</h6>
                                <h5 class="mb-0" id="templateTotalPrice">Total: Rs ${itemPrice.toFixed(2)}</h5>
                            </div>
                        </div>
                        <div class="mb-3">
                            <h6 class="text-center">Select Option:</h6>
                        </div>
                        <div class="template-options">
                            ${options.map(option => `
                                <div class="template-option" onclick="selectTemplateOption('option_${option.id}')">
                                    <input class="form-check-input" type="radio" name="template_option" 
                                           value="${option.id}" id="option_${option.id}" 
                                           data-price="${option.price_adjustment}">
                                    <label class="form-check-label" for="option_${option.id}">
                                        <strong>${option.name}</strong>
                                        ${option.price_adjustment > 0 ? `<span class="text-success">(+Rs ${option.price_adjustment})</span>` : ''}
                                    </label>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="button" class="btn btn-primary" id="confirmTemplateBtn">Add to Cart</button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // Remove existing modal
    const existingModal = document.getElementById('templateModal');
    if (existingModal) existingModal.remove();
    
    // Add modal to body
    document.body.insertAdjacentHTML('beforeend', modalHtml);
    
    // Show modal
    const modal = new bootstrap.Modal(document.getElementById('templateModal'));
    modal.show();
    
    // Bind events
    bindTemplateModalEvents(templateId, itemId, itemName, itemPrice);
}

// Bind template modal events
function bindTemplateModalEvents(templateId, itemId, itemName, itemPrice) {
    const modal = document.getElementById('templateModal');
    const totalPriceEl = document.getElementById('templateTotalPrice');
    const confirmBtn = document.getElementById('confirmTemplateBtn');
    
    // Update total price when option changes
    modal.querySelectorAll('input[name="template_option"]').forEach(input => {
        input.addEventListener('change', function() {
            const selectedOption = modal.querySelector('input[name="template_option"]:checked');
            if (selectedOption) {
                const priceAdjustment = parseFloat(selectedOption.dataset.price);
                const newTotal = itemPrice + priceAdjustment;
                totalPriceEl.textContent = `Total: Rs ${newTotal.toFixed(2)}`;
            }
        });
    });
    
    // Confirm button
    confirmBtn.addEventListener('click', function() {
        const selectedOption = modal.querySelector('input[name="template_option"]:checked');
        if (selectedOption) {
            const priceAdjustment = parseFloat(selectedOption.dataset.price);
            const finalPrice = itemPrice + priceAdjustment;
            const optionName = selectedOption.nextElementSibling.textContent.trim();
            
            // Add to cart with template modifier
            addItemToCartWithTemplate(itemId, itemName, finalPrice, optionName, templateId, selectedOption.value);
            
            // Close modal
            bootstrap.Modal.getInstance(modal).hide();
        }
    });
}

// Add item to cart with template modifier
function addItemToCartWithTemplate(itemId, name, price, modifierText, templateId, optionId) {
    // Get cart item details
    const cartItem = document.querySelector(`[data-item-id="${itemId}"]`);
    // Use item_code from data attribute if available, otherwise fallback to generated code from name
    const itemCode = cartItem ? cartItem.getAttribute('data-item-code') : null;
    const code = (itemCode && itemCode.trim() !== '') ? itemCode : name.replace(/\s+/g, '-').toLowerCase();
    const taxType = cartItem.getAttribute('data-tax-type');
    const taxRate = cartItem.getAttribute('data-tax-rate');
    
    // Get current modifiers
    const currentModifiers = JSON.parse(cartItem.getAttribute('data-modifiers') || '[]');
    
    // Add new template modifier
    const newModifier = {
        template_id: templateId,
        option_id: optionId,
        name: modifierText,
        price_adjustment: price - parseFloat(cartItem.querySelector('.price-display').textContent.replace(/[^\d.]/g, ''))
    };
    
    // Update modifiers
    currentModifiers.push(newModifier);
    cartItem.setAttribute('data-modifiers', JSON.stringify(currentModifiers));
    
    // Update display
    const modifierTextEl = cartItem.querySelector('.text-muted');
    if (modifierTextEl) {
        const allModifiers = currentModifiers.map(mod => mod.name).join(', ');
        modifierTextEl.textContent = allModifiers;
    } else {
        // Add modifier text if it doesn't exist
        const infoDiv = cartItem.querySelector('.info');
        if (infoDiv) {
            const modifierDiv = document.createElement('small');
            modifierDiv.className = 'text-muted';
            modifierDiv.textContent = currentModifiers.map(mod => mod.name).join(', ');
            infoDiv.appendChild(modifierDiv);
        }
    }
    
    // Update price data
    const saleMode = cartItem.getAttribute('data-sale-mode') || 'loose';
    const bulkQty = parseFloat(cartItem.getAttribute('data-bulk-qty')) || 0;
    if (saleMode === 'bulk' && bulkQty > 0) {
        const perUnit = price / bulkQty;
        cartItem.setAttribute('data-bulk-pack-price', price.toFixed(4));
        cartItem.setAttribute('data-bulk-per-unit-price', perUnit.toFixed(4));
        cartItem.setAttribute('data-price', perUnit.toFixed(4));
    } else {
        cartItem.setAttribute('data-retail-unit-price', price.toFixed(4));
        cartItem.setAttribute('data-price', price.toFixed(4));
    }
    
    // Update total (also refreshes display)
    updateTotal();
}

// Select template option by clicking on the card
function selectTemplateOption(optionId) {
    const radioInput = document.getElementById(optionId);
    if (radioInput) {
        radioInput.checked = true;
        
        // Trigger change event to update price
        const changeEvent = new Event('change');
        radioInput.dispatchEvent(changeEvent);
    }
}

// Function to show serial selection modal before adding to cart (when item is first clicked)
function showSerialSelectionBeforeCart(itemId, itemName, price, code, taxType, taxRate, availableSerials, totalAvailable, modifierGroups = null, itemMeta = {}) {
    const quantity = 1; // Start with quantity 1
    const safeName = itemName.replace(/'/g, '&#39;').replace(/"/g, '&quot;');
    
    // Check if enough serials available
    if (totalAvailable < quantity) {
        Swal.fire({
            icon: 'warning',
            title: 'Insufficient Serials',
            text: `Only ${totalAvailable} serial number(s) available, but ${quantity} is required.`,
            confirmButtonText: 'OK'
        });
        return;
    }
    
    // Build serial list HTML
    let serialListHtml = '';
    if (availableSerials.length === 0) {
        serialListHtml = '<div class="alert alert-warning">No serial numbers available for this item.</div>';
    } else {
        // Show all available serials (limit to 100 for performance if too many)
        const serialsToShow = availableSerials.slice(0, 100);
        
        serialsToShow.forEach(serial => {
            const warrantyInfo = serial.warranty_expiry ? 
                `<small class="text-muted d-block">Warranty: ${serial.warranty_name || 'N/A'} (Exp: ${serial.warranty_expiry})</small>` : '';
            
            serialListHtml += `
                <div class="form-check mb-2 p-2 border rounded serial-option-row" data-serial-id="${serial.id}">
                    <input class="form-check-input serial-checkbox" type="checkbox" 
                           value="${serial.id}" id="serial_${serial.id}">
                    <label class="form-check-label w-100" for="serial_${serial.id}">
                        <strong>${serial.serial_no}</strong>
                        ${serial.details ? `<small class="text-muted d-block">${serial.details}</small>` : ''}
                        ${warrantyInfo}
                    </label>
                </div>
            `;
        });
    }
    
    const modalHtml = `
        <div class="modal fade" id="saleSerialModalBeforeCart" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Select Serial Number: ${safeName}</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="alert alert-info mb-3">
                            <i class="fas fa-info-circle"></i> Please select <strong>1</strong> serial number to add this item to cart.
                            <span id="selected-count-badge-before" class="badge bg-primary ms-2">0/1</span>
                        </div>
                        <div id="serialListContainerBefore" style="max-height: 400px; overflow-y: auto;">
                            ${serialListHtml}
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="button" class="btn btn-primary" id="confirmSerialBtnBefore" disabled>Add to Cart</button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // Remove existing modal
    const existingModal = document.getElementById('saleSerialModalBeforeCart');
    if (existingModal) {
        existingModal.remove();
    }
    
    // Add modal to body
    document.body.insertAdjacentHTML('beforeend', modalHtml);
    
    // Store item data for after serial selection
    window.serialBeforeCartData = {
        itemId: itemId,
        name: itemName,
        price: price,
        code: code,
        taxType: taxType,
        taxRate: taxRate,
        modifierGroups: modifierGroups,
        itemMeta: itemMeta || {}
    };
    
    // Bind events
    bindSerialBeforeCartEvents();
    
    // Show modal
    const modalElement = document.getElementById('saleSerialModalBeforeCart');
    const modal = new bootstrap.Modal(modalElement);
    modal.show();
}

// Function to bind serial before cart modal events
function bindSerialBeforeCartEvents() {
    const checkboxes = document.querySelectorAll('#saleSerialModalBeforeCart .serial-checkbox');
    const confirmBtn = document.getElementById('confirmSerialBtnBefore');
    const badge = document.getElementById('selected-count-badge-before');
    
    checkboxes.forEach(checkbox => {
        checkbox.addEventListener('change', () => {
            const checkedCount = document.querySelectorAll('#saleSerialModalBeforeCart .serial-checkbox:checked').length;
            if (badge) {
                badge.textContent = `${checkedCount}/1`;
                badge.className = checkedCount === 1 ? 'badge bg-success ms-2' : 'badge bg-warning ms-2';
            }
            if (confirmBtn) {
                confirmBtn.disabled = checkedCount !== 1;
            }
        });
    });
    
    confirmBtn.addEventListener('click', () => {
        const checkedBoxes = document.querySelectorAll('#saleSerialModalBeforeCart .serial-checkbox:checked');
        const selectedIds = Array.from(checkedBoxes).map(cb => parseInt(cb.value));
        
        if (selectedIds.length !== 1) {
            Swal.fire({
                icon: 'warning',
                title: 'Please Select Serial',
                text: 'Please select exactly 1 serial number.'
            });
            return;
        }
        
        const data = window.serialBeforeCartData;
        if (!data) {
            console.error('Serial before cart data not found');
            return;
        }
        
        // Close modal first (wait for it to close)
        const modal = bootstrap.Modal.getInstance(document.getElementById('saleSerialModalBeforeCart'));
        if (modal) {
            modal.hide();
        }
        
        // Clean up modal HTML after it's hidden
        setTimeout(() => {
            const modalElement = document.getElementById('saleSerialModalBeforeCart');
            if (modalElement) {
                modalElement.remove();
            }
            
            // If item has modifiers, show modifier modal first, then add to cart with serials
            if (data.modifierGroups && data.modifierGroups.length > 0) {
                // Store serial IDs for later
                window.pendingSerialIds = selectedIds;
                showModifierModal(data.itemId, data.name, data.price, data.code, data.taxType, data.taxRate, data.modifierGroups, true, data.itemMeta || {});
            } else {
                // No modifiers, add directly to cart with serials
                addItemToCartWithSerials(data.itemId, data.name, data.price, data.code, data.taxType, data.taxRate, [], true, selectedIds, data.itemMeta || {});
            }
            
            // Clean up
            delete window.serialBeforeCartData;
        }, 300);
    });
}

// Function to add item to cart with serials pre-selected
function addItemToCartWithSerials(itemId, name, price, code, taxType, taxRate, selectedModifiers = [], isSerialized = false, serialIds = [], itemMeta = {}) {
    addItemToCart(itemId, name, price, code, taxType, taxRate, selectedModifiers, isSerialized, serialIds, itemMeta);
}

// Function to open serial selection modal for sale items (when clicking serial button in cart)
function openSaleSerialModal(button, event) {
    if (event) {
        event.preventDefault();
        event.stopPropagation();
    }
    
    const cartRow = button.closest('.product-list');
    if (!cartRow) return;
    
    const itemId = parseInt(cartRow.getAttribute('data-item-id'));
    const itemName = cartRow.getAttribute('data-item-name');
    const quantity = parseFloat(cartRow.querySelector('input[name="qty"]').value) || 1;
    const currentSerialIds = JSON.parse(cartRow.getAttribute('data-serial-ids') || '[]');
    
    // Fetch available serials
    fetch(`ajax/get_available_serials.php?item_id=${itemId}&quantity=${quantity}`)
        .then(response => response.json())
        .then(data => {
            if (!data.success) {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: data.message || 'Failed to load available serials'
                });
                return;
            }
            
            // Show serial selection modal
            showSaleSerialModal(itemId, itemName, quantity, data.serials, data.total_available, cartRow, currentSerialIds);
        })
        .catch(error => {
            console.error('Error fetching serials:', error);
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'Failed to load available serial numbers'
            });
        });
}

// Function to show serial selection modal
function showSaleSerialModal(itemId, itemName, quantity, availableSerials, totalAvailable, cartRow, currentSerialIds = []) {
    const safeName = itemName.replace(/'/g, '&#39;').replace(/"/g, '&quot;');
    
    // Check if enough serials available
    if (totalAvailable < quantity) {
        Swal.fire({
            icon: 'warning',
            title: 'Insufficient Serials',
            text: `Only ${totalAvailable} serial number(s) available, but ${quantity} is required.`,
            confirmButtonText: 'OK'
        });
        return;
    }
    
    // Build serial list HTML
    let serialListHtml = '';
    if (availableSerials.length === 0) {
        serialListHtml = '<div class="alert alert-warning">No serial numbers available for this item.</div>';
    } else {
        availableSerials.forEach(serial => {
            const isSelected = currentSerialIds.includes(parseInt(serial.id));
            const warrantyInfo = serial.warranty_expiry ? 
                `<small class="text-muted d-block">Warranty: ${serial.warranty_name || 'N/A'} (Exp: ${serial.warranty_expiry})</small>` : '';
            
            serialListHtml += `
                <div class="form-check mb-2 p-2 border rounded serial-option-row" data-serial-id="${serial.id}">
                    <input class="form-check-input serial-checkbox" type="checkbox" 
                           value="${serial.id}" id="serial_${serial.id}"
                           ${isSelected ? 'checked' : ''}>
                    <label class="form-check-label w-100" for="serial_${serial.id}">
                        <strong>${serial.serial_no}</strong>
                        ${serial.details ? `<small class="text-muted d-block">${serial.details}</small>` : ''}
                        ${warrantyInfo}
                    </label>
                </div>
            `;
        });
    }
    
    const modalHtml = `
        <div class="modal fade" id="saleSerialModal" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Select Serial Numbers: ${safeName}</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="alert alert-info mb-3">
                            <i class="fas fa-info-circle"></i> Please select exactly <strong>${quantity}</strong> serial number(s).
                            <span id="selected-count-badge" class="badge bg-primary ms-2">0/${quantity}</span>
                        </div>
                        <div id="serialListContainer" style="max-height: 400px; overflow-y: auto;">
                            ${serialListHtml}
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="button" class="btn btn-primary" id="confirmSerialBtn" disabled>Confirm Selection</button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // Remove existing modal
    const existingModal = document.getElementById('saleSerialModal');
    if (existingModal) {
        existingModal.remove();
    }
    
    // Add modal to body
    document.body.insertAdjacentHTML('beforeend', modalHtml);
    
    // Store cart row reference
    window.currentSerialCartRow = cartRow;
    
    // Bind events
    bindSerialModalEvents(quantity);
    
    // Update initial count
    updateSerialSelectionCount(quantity);
    
    // Show modal
    const modalElement = document.getElementById('saleSerialModal');
    const modal = new bootstrap.Modal(modalElement);
    
    // Initialize feather icons after modal is shown
    modalElement.addEventListener('shown.bs.modal', function() {
        if (typeof feather !== 'undefined') {
            const modalIcons = modalElement.querySelectorAll('[data-feather]');
            if (modalIcons.length > 0) {
                feather.replace({ scope: modalElement });
            }
        }
    }, { once: true });
    
    modal.show();
}

// Function to bind serial modal events
function bindSerialModalEvents(requiredQuantity) {
    const checkboxes = document.querySelectorAll('#saleSerialModal .serial-checkbox');
    const confirmBtn = document.getElementById('confirmSerialBtn');
    
    checkboxes.forEach(checkbox => {
        checkbox.addEventListener('change', () => {
            updateSerialSelectionCount(requiredQuantity);
        });
    });
    
    confirmBtn.addEventListener('click', () => {
        confirmSerialSelection(requiredQuantity);
    });
}

// Function to update serial selection count
function updateSerialSelectionCount(requiredQuantity) {
    const checkedBoxes = document.querySelectorAll('#saleSerialModal .serial-checkbox:checked');
    const selectedCount = checkedBoxes.length;
    const badge = document.getElementById('selected-count-badge');
    const confirmBtn = document.getElementById('confirmSerialBtn');
    
    if (badge) {
        badge.textContent = `${selectedCount}/${requiredQuantity}`;
        badge.className = selectedCount === requiredQuantity ? 
            'badge bg-success ms-2' : 
            'badge bg-warning ms-2';
    }
    
    if (confirmBtn) {
        confirmBtn.disabled = selectedCount !== requiredQuantity;
    }
}

// Function to confirm serial selection
function confirmSerialSelection(requiredQuantity) {
    const checkedBoxes = document.querySelectorAll('#saleSerialModal .serial-checkbox:checked');
    const selectedIds = Array.from(checkedBoxes).map(cb => parseInt(cb.value));
    
    if (selectedIds.length !== requiredQuantity) {
        Swal.fire({
            icon: 'warning',
            title: 'Incorrect Selection',
            text: `Please select exactly ${requiredQuantity} serial number(s).`
        });
        return;
    }
    
    const cartRow = window.currentSerialCartRow;
    if (!cartRow) {
        console.error('Cart row not found');
        return;
    }
    
    // Update cart row with selected serial IDs
    cartRow.setAttribute('data-serial-ids', JSON.stringify(selectedIds));
    
    // Update serial badge
    const serialBtn = cartRow.querySelector('.serial-btn');
    if (serialBtn) {
        const badge = serialBtn.querySelector('.serial-badge');
        if (badge) {
            badge.textContent = `${selectedIds.length}/${requiredQuantity}`;
            badge.className = 'serial-badge ms-1 badge bg-success';
        }
    }
    
    // Close modal
    const modal = bootstrap.Modal.getInstance(document.getElementById('saleSerialModal'));
    if (modal) {
        modal.hide();
    }
    
    // Clean up
    delete window.currentSerialCartRow;
}