
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

    // 🟢 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');
        loadSubcategories(firstCategoryId);
        showProductsByCategory(firstCategoryId);
    }
    
    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');
            
            // Load subcategories and show products for selected category
            loadSubcategories(selectedId);
            showProductsByCategory(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);
                    subcategoryHTML += `
                        <div class="subcategory-item" data-subcategory-id="${subcategory.id}">
                            <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-3, .col-xl-3');
            
            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
            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
            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 => {
        totalItems += parseInt(item.quantity);
        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: ${item.quantity}</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) * parseInt(item.quantity)).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>${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;

                    // 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;

                    // ✅ Restore cart items (directly add to cart with stored modifiers and remarks)
                    data.items.forEach(item => {
                        const modifiers = item.modifiers || [];
                        const remarks = item.remarks || '';
                        const taxType = 'percentage'; // Default tax type
                        const taxRate = parseFloat(item.tax_rate) || 0;
                        const 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) {
                            // Set quantity
                            if (item.quantity > 1) {
                                const qtyInput = addedRow.querySelector('input[name="qty"]');
                                qtyInput.value = item.quantity;
                            }
                            
                            // 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}`;
                                }
                            }
                        }
                    });

                    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;
            
            // Open proforma invoice print window
            const proformaWindow = window.open(`print_proforma_invoice.php?id=${holdId}`, 'Proforma_Print', 'width=800,height=900');
            if (proformaWindow) proformaWindow.focus();
        });
    });
  }

  // 🟢 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 price = parseFloat(this.querySelector('.price p').textContent.replace(/[^\d.]/g, ''));
    const code = name.replace(/\s+/g, '-').toLowerCase();
    const taxType = this.getAttribute('data-tax-type');
    const taxRate = this.getAttribute('data-tax-rate');
    
    // Check if this item has modifiers before adding to cart
    checkItemModifiers(itemId, name, price, code, taxType, taxRate);
  });
});

// Function to check if item has modifiers and show selection modal
function checkItemModifiers(itemId, name, price, code, taxType, taxRate) {
  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);
      } else {
        // No modifiers, add directly to cart
        addItemToCart(itemId, name, price, code, taxType, taxRate, []);
      }
    })
    .catch(error => {
      console.error('Error checking modifiers:', error);
      // If error, add item without modifiers
      addItemToCart(itemId, name, price, code, taxType, taxRate, []);
    });
}

// Function to add item to cart (with or without modifiers)
function addItemToCart(itemId, name, price, code, taxType, taxRate, selectedModifiers = []) {
  
  // 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) {
      const qtyInput = existing.querySelector('input[name="qty"]');
      qtyInput.value = parseInt(qtyInput.value) + 1;
      updateTotal();
      return;
    }

    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);
  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));

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

    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)}</p>
        ${modifierText ? `<small class="text-muted">${modifierText}</small>` : ''}
        <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="text" class="form-control text-center" name="qty" value="1">
        <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>
        <a class="btn-icon delete-icon" href="#"><i data-feather="trash-2"></i></a>
      </div>
    `;

    cartWrap.appendChild(row);
    bindQtyEvents(row);
    feather.replace();
    updateTotal();
}

// Function to show modifier selection modal
function showModifierModal(itemId, name, price, code, taxType, taxRate, modifierGroups) {
  
  // Store item data globally for the modal
  window.modifierModalData = {
    itemId: itemId,
    name: name,
    price: price,
    code: code,
    taxType: taxType,
    taxRate: taxRate
  };
  
  // 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();
  
  // Add item to cart with modifiers
  addItemToCart(data.itemId, data.name, data.price, data.code, data.taxType, data.taxRate, selectedModifiers);
}

   function bindQtyEvents(row) {
    const qtyInput = row.querySelector('input[name="qty"]');
    row.querySelector('.inc').addEventListener('click', () => {
        qtyInput.value = parseInt(qtyInput.value) + 1;
        updateTotal();
    });
    row.querySelector('.dec').addEventListener('click', () => {
        qtyInput.value = Math.max(1, parseInt(qtyInput.value) - 1);
        updateTotal();
    });
    
    // Handle manual quantity input
    qtyInput.addEventListener('change', () => {
        const newQty = parseInt(qtyInput.value);
        if (isNaN(newQty) || newQty < 1) {
            qtyInput.value = 1;
        }
        updateTotal();
    });
    
    qtyInput.addEventListener('input', () => {
        const newQty = parseInt(qtyInput.value);
        if (isNaN(newQty) || newQty < 1) {
            qtyInput.value = 1;
        }
        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();
            } 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();
                    });
                } 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();
        }
    });

    // Add remarks functionality - click on item itself
    row.querySelector('.product-info').addEventListener('click', (e) => {
        e.preventDefault();
        showRemarksModal(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 delivery charges
    const deliveryChargesInput = document.getElementById('delivery-charges-input');
    if (deliveryChargesInput) {
        deliveryChargesInput.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;
            
            if (discountApplied === 'Y' && discountRate > 0) {
                // Store customer discount for later use
                window.customerDiscount = {
                    type: 'percent',
                    rate: discountRate,
                    source: 'customer'
                };
            } else {
                window.customerDiscount = null;
            }
        });
    }

    // 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

    function updateTotal() {
        let subtotal = 0, totalTax = 0, grandTotal = 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;
        }

        // Original item-wise tax calculation
        cartWrap.querySelectorAll('.product-list').forEach(row => {
            const price = parseFloat(row.getAttribute('data-price'));
            const qty = parseInt(row.querySelector('input[name="qty"]').value);
            const taxType = row.getAttribute('data-tax-type');
            const taxRate = parseFloat(row.getAttribute('data-tax-rate')) || 0;

            let basePrice = 0, taxAmount = 0, itemTotal = 0;

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

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

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

        let discountedSubtotal = subtotal - discountAmount;
        let discountedGrandTotal = discountedSubtotal + totalTax;

        // Add delivery charges
        const deliveryChargesInput = document.getElementById('delivery-charges-input');
        const deliveryCharges = parseFloat(deliveryChargesInput?.value) || 0;
        const finalTotal = discountedGrandTotal + deliveryCharges;

        subtotalEl.textContent = 'Rs ' + subtotal.toFixed(2);
        totalEl.textContent = 'Rs ' + finalTotal.toFixed(2);
        taxInput.value = totalTax.toFixed(2) + ' Rs';
        totalDisplay.textContent = 'Grand Total : Rs ' + finalTotal.toFixed(2);
        
        // Update discount display
        const discountDisplay = document.getElementById('discount-display');
        if (discountDisplay) {
            discountDisplay.textContent = 'Rs ' + discountAmount.toFixed(2);
        }

        // Update delivery charges display
        const deliveryChargesDisplay = document.getElementById('delivery-charges-display');
        if (deliveryChargesDisplay) {
            deliveryChargesDisplay.textContent = 'Rs ' + deliveryCharges.toFixed(2);
        }
    }

    function updateTotalWithPaymentMethodTax() {
        const cartItems = [];
        document.querySelectorAll('.product-list').forEach(row => {
            const modifiers = row.getAttribute('data-modifiers') ? JSON.parse(row.getAttribute('data-modifiers')) : [];
            cartItems.push({
                id: parseInt(row.getAttribute('data-item-id')) || 0,
                name: row.getAttribute('data-item-name') || row.querySelector('h6')?.textContent || '',
                price: parseFloat(row.getAttribute('data-price')),
                qty: parseInt(row.querySelector('input[name="qty"]').value),
                tax_rate: parseFloat(row.getAttribute('data-tax-rate')) || 0,
                tax_type: row.getAttribute('data-tax-type') || 'excluded',
                modifiers: modifiers
            });
        });

        if (cartItems.length === 0) {
            subtotalEl.textContent = 'Rs 0.00';
            totalEl.textContent = 'Rs 0.00';
            taxInput.value = '0.00 Rs';
            totalDisplay.textContent = 'Grand Total : Rs 0.00';
            
            // Update delivery charges display
            const deliveryChargesDisplay = document.getElementById('delivery-charges-display');
            if (deliveryChargesDisplay) {
                deliveryChargesDisplay.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');

        fetch('ajax/calculate_tax.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Add delivery charges to the total
                const deliveryChargesInput = document.getElementById('delivery-charges-input');
                const deliveryCharges = parseFloat(deliveryChargesInput?.value) || 0;
                const finalTotal = data.total + deliveryCharges;

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

                // Update delivery charges display
                const deliveryChargesDisplay = document.getElementById('delivery-charges-display');
                if (deliveryChargesDisplay) {
                    deliveryChargesDisplay.textContent = 'Rs ' + deliveryCharges.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 (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 });
        
        // 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 && 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');
                }
            })
            .catch(error => {
                console.error('Error loading payment tax rates:', error);
                // Hide container on error
                const container = document.getElementById('payment-totals-container');
                if (container) container.style.display = 'none';
            });
    }

    // 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');
    }

    // 💳 PAYMENT FLOW
    const paymentBtn = document.getElementById('payment-btn');
    if (paymentBtn) {
        paymentBtn.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') || '';
                cartItems.push({
                    id: parseInt(row.getAttribute('data-item-id')) || 0,
                    name: row.getAttribute('data-item-name') || row.querySelector('h6')?.textContent || '',
                    price: parseFloat(row.getAttribute('data-price')),
                    qty: parseInt(row.querySelector('input[name="qty"]').value),
                    tax_rate: parseFloat(row.getAttribute('data-tax-rate')) || 0,
                    tax_type: row.getAttribute('data-tax-type') || 'excluded',
                    modifiers: modifiers,
                    remarks: remarks
                });
            });

            if (cartItems.length === 0) {
                alert("No items in cart.");
                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);
            }

            // Calculate and display payment totals if payment method tax is enabled
            console.log('Payment button clicked. Tax calculation method:', taxCalculationMethod);
            if (taxCalculationMethod === 'payment_method') {
                console.log('Calling calculateAndDisplayPaymentTotals with cart items:', cartItems);
                calculateAndDisplayPaymentTotals(cartItems);
            } else {
                console.log('Hiding payment totals container - item-wise tax mode');
                // Hide payment totals container for item-wise tax
                const container = document.getElementById('payment-totals-container');
                if (container) container.style.display = 'none';
            }

            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 only once with { once: true } to prevent multiple calls
  document.querySelectorAll('.payment-option').forEach(button => {
    button.addEventListener('click', handlePaymentMethodClick, { once: true });
  });
  
  console.log('Payment method buttons found and bound:', buttons.length);
}

function handlePaymentMethodClick() {
  const methodName = this.getAttribute('data-method');
  
  // 🛡️ Validate payment method
  if (!methodName || methodName === '') {
    alert('Error: Invalid payment method selected. Please try again.');
    return;
  }
  
  selectedPaymentMethod = methodName;
  
  // Update current payment method for tax calculation
  setPaymentMethod(methodName);
  
  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
  bankWrapper.classList.add('d-none');
  cardWrapper.classList.add('d-none');
  cashWrapper.classList.add('d-none');

  // Check if payment method is cash
  if (selectedPaymentMethod === 'cash') {
    cashWrapper.classList.remove('d-none');
    initializeCashTender();
  }
  // Check if payment method requires bank account
  else if (selectedPaymentMethod === 'bank' || this.hasAttribute('data-requires-bank')) {
    bankWrapper.classList.remove('d-none');
    bankSelect.focus();

    bankSelect.onchange = () => {
      if (bankSelect.value) submitSale(bankSelect.value);
    };
  } 
  // Check if payment method is card
  else if (selectedPaymentMethod === 'card') {
    cardWrapper.classList.remove('d-none');
    cardTypeSelect.focus();

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

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

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

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

// 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);
}

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

// Initialize cash tender form
function initializeCashTender() {
  const billAmount = parseFloat(window.totalToSave) || 0;
  
  // Set bill amount
  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.value = '0.00';
  if (submitBtn) submitBtn.disabled = true;
  
  // Hide validation message
  const validationMsg = document.getElementById('change-validation-message');
  if (validationMsg) validationMsg.style.display = 'none';
  
  // Bind cash tender event listeners
  bindCashTenderEvents();
}

// 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 buttons
  document.querySelectorAll('.quick-amount-btn').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(2);
  }
  
  // Calculate change
  const change = amount - billAmount;
  
  if (cashChangeAmount) {
    if (change >= 0) {
      cashChangeAmount.value = change.toFixed(2);
      cashChangeAmount.classList.remove('text-danger');
      cashChangeAmount.classList.add('text-success');
      
      // Enable submit button
      if (submitBtn) submitBtn.disabled = false;
      
      // Hide validation message
      if (validationMsg) validationMsg.style.display = 'none';
    } else {
      cashChangeAmount.value = change.toFixed(2);
      cashChangeAmount.classList.remove('text-success');
      cashChangeAmount.classList.add('text-danger');
      
      // Disable submit button
      if (submitBtn) submitBtn.disabled = true;
      
      // Show validation message
      if (validationMsg) validationMsg.style.display = 'block';
    }
  }
}

// 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 =====

// 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 price = parseFloat(row.getAttribute('data-price'));
      const qty = parseInt(row.querySelector('input[name="qty"]').value);
      subtotal += price * 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) {
  paymentModal.addEventListener('shown.bs.modal', function() {
    // Small delay to ensure buttons are rendered
    setTimeout(() => {
      bindPaymentMethodEvents();
    }, 100);
  });
  
  // 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;
        console.log('Tax calculation method updated to:', taxCalculationMethod);
        
        // If payment method tax is enabled, show tax rate display
        if (taxCalculationMethod === 'payment_method') {
          console.log('Payment method tax enabled, showing tax rates');
          showPaymentMethodTaxRates();
        }
      } else {
        console.log('Tax settings request failed:', data);
      }
    })
    .catch(error => {
      console.error('Error loading tax settings:', error);
    });
}

function showPaymentMethodTaxRates() {
  // 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';
}

// 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;
  }
  
  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: document.getElementById('delivery-charges-input')?.value || 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
  };



  // 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;
        }
      }
      
      cartItems.push({
        id: parseInt(row.getAttribute('data-item-id')) || 0,
        name: row.getAttribute('data-item-name') || row.querySelector('h6')?.textContent || '',
        price: parseFloat(row.getAttribute('data-price')),
        qty: parseInt(row.querySelector('input[name="qty"]').value),
        tax_rate: parseFloat(row.getAttribute('data-tax-rate')) || 0,
        modifiers: modifiers,
        remarks: remarks,
        template_id: template_id
      });
    });

    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 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 || ''
    };

    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
        if (response.print_kot && response.hold_id) {
          // Use the new KOT printing function that respects print method setting
          handleKOTPrint(response.hold_id, response.new_items || []);
        }

      } 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) {
        cartWrap.innerHTML = '';
        subtotalEl.textContent = 'Rs 0.00';
        totalEl.textContent = 'Rs 0.00';
        taxInput.value = '0 Rs';
        totalDisplay.textContent = 'Grand Total : Rs 0.00';
        
        // 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 delivery charges input and display
        const deliveryChargesInput = document.getElementById('delivery-charges-input');
        if (deliveryChargesInput) {
            deliveryChargesInput.value = '0.00';
        }
        
        const deliveryChargesDisplay = document.getElementById('delivery-charges-display');
        if (deliveryChargesDisplay) {
            deliveryChargesDisplay.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;

    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("search_items.php?q=" + encodeURIComponent(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.textContent = item.text;
                        option.dataset.id = item.id;

                        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("div");
                            if (firstOption) {
                                firstOption.click();
                            }
                        }, 50);
                    }
                })
                .catch(err => {
                    console.error("Search error:", err);
                    autocompleteList.innerHTML = "";
                });
        });

        productSearch.addEventListener("keydown", function (e) {
            let items = autocompleteList.getElementsByTagName("div");
            
            // 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("search_items.php?q=" + encodeURIComponent(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) {
                // Update the cart row
                cartRow.setAttribute('data-price', newPrice);
                cartRow.querySelector('.price-display').textContent = `Rs ${newPrice.toFixed(2)}`;
                
                // 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'
            });
        });
    }
});

// Remarks Modal Function
function showRemarksModal(cartRow) {
    const itemName = cartRow.querySelector('h6').textContent;
    const currentRemarks = cartRow.getAttribute('data-remarks') || '';
    
    // Create modal HTML
    const modalHtml = `
        <div class="modal fade" id="remarksModal" tabindex="-1" data-bs-backdrop="static">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Add Remarks: ${itemName}</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="remarksInput" class="form-label">Special Instructions:</label>
                            <textarea class="form-control" id="remarksInput" rows="3" placeholder="Enter any special instructions for this item...">${currentRemarks}</textarea>
                        </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="saveRemarksBtn">Save Remarks</button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // Remove existing modal
    const existingModal = document.getElementById('remarksModal');
    if (existingModal) {
        existingModal.remove();
    }
    
    // Add modal to body
    document.body.insertAdjacentHTML('beforeend', modalHtml);
    
    // Bind save button event
    document.getElementById('saveRemarksBtn').addEventListener('click', function() {
        const remarks = document.getElementById('remarksInput').value.trim();
        
        // Store remarks in cart row
        cartRow.setAttribute('data-remarks', remarks);
        
        // Update display
        const remarksSection = cartRow.querySelector('.remarks-section');
        const remarksText = cartRow.querySelector('.remarks-text');
        
        if (remarks) {
            remarksSection.style.display = 'block';
            remarksText.textContent = `💬 ${remarks}`;
        } else {
            remarksSection.style.display = 'none';
        }
        
        // Close modal
        const modal = bootstrap.Modal.getInstance(document.getElementById('remarksModal'));
        modal.hide();
    });
    
    // Show modal
    const modal = new bootstrap.Modal(document.getElementById('remarksModal'));
    modal.show();
}

// 🔧 Fix for aria-hidden accessibility warning
document.addEventListener('DOMContentLoaded', function() {
    // Monitor for aria-hidden changes on the sticky header
    const stickyHeader = document.querySelector('.sticky-top');
    if (stickyHeader) {
        const observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                if (mutation.type === 'attributes' && mutation.attributeName === 'aria-hidden') {
                    const focusedElement = document.activeElement;
                    if (focusedElement && stickyHeader.contains(focusedElement)) {
                        // If a focused element is inside an aria-hidden container, remove focus
                        focusedElement.blur();
                    }
                }
            });
        });
        
        observer.observe(stickyHeader, {
            attributes: true,
            attributeFilter: ['aria-hidden']
        });
    }
});

/**
 * 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 = []) {
    try {
        // Get print settings
        const printMethod = await getPrintSetting('print_method');
        
        if (printMethod === 'direct') {
            // Use direct printing via print system
            await executeDirectKOTPrint(holdId, newItems);
        } else {
            // Use popup method (current behavior)
            showKOTPopup(holdId, newItems);
        }
    } catch (error) {
        console.error('KOT print error:', error);
        // Fallback to popup method
        showKOTPopup(holdId, newItems);
    }
}

/**
 * Execute direct KOT printing using print system
 */
async function executeDirectKOTPrint(holdId, newItems = []) {
    try {
        // Prepare KOT print data
        const kotData = {
            type: 'kot',
            hold_id: holdId,
            new_items: newItems,
            order_number: holdId,
            timestamp: new Date().toISOString()
        };
        
        // Get KOT devices
        const kotDevices = await getDevicesForType('kot');
        
        if (!kotDevices || kotDevices.length === 0) {
            throw new Error('No KOT printers configured');
        }
        
        // Get default KOT device
        const defaultDevice = kotDevices.find(device => device.is_default == 1) || kotDevices[0];
        
        // Execute direct print (bypass any dialogs)
        const result = await window.printSystem.executePrint('kot', kotData, defaultDevice.id);
        
        if (result.success) {
            console.log('KOT printed successfully:', result.message);
        } else {
            console.error('KOT print failed:', result.message);
            // Fallback to popup if direct printing fails
            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();
}

/**
 * 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}"]`);
    const code = 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
    const priceEl = cartItem.querySelector('.price-display');
    priceEl.textContent = `Rs ${price.toFixed(2)}`;
    
    // Update total
    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);
    }
}