
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;

    // 🟢 Category filter
    document.querySelectorAll('ul.tabs.pos-category li').forEach(category => {
        category.addEventListener('click', function (e) {
            e.preventDefault();
            const selectedId = this.getAttribute('data-category');
            document.querySelectorAll('ul.tabs.pos-category li').forEach(tab => tab.classList.remove('active'));
            this.classList.add('active');
            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 = selectedId === 'all' || selectedId == cardCategory;
                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;

        // Set global and form values
        window.selectedOrderMode = mode;
        document.getElementById('selected-order-mode').value = mode;

        // If mode is NOT dine_in, clear table info
        if (mode !== 'dine_in') {
            window.selectedTableId = null;
            document.getElementById('selected-table-id').value = '';
            const tableNameDisplay = document.getElementById('active-table-name');
            if (tableNameDisplay) tableNameDisplay.textContent = '';
        }

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

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




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

                    data.forEach(order => {
                        const tr = document.createElement('tr');
                        tr.innerHTML = `
    <td>${order.reference}</td>
    <td>${order.customer_name}</td>
    <td>${order.order_mode ? order.order_mode.replace(/_/g, ' ').toUpperCase() : '-'}</td>
    <td>${order.table_id || '-'}</td>
    <td>Rs ${parseFloat(order.total_amount).toFixed(2)}</td>
    <td>${order.created_at}</td>
    <td>
        <button class="btn btn-sm btn-success resume-order-btn" data-id="${order.id}">
            Resume
        </button>
    </td>
`;

                        tbody.appendChild(tr);
                    });

                    bindResumeButtons();
                });
        });
    }

    // 🔄 Bind resume button click handler
  function bindResumeButtons() {
    document.querySelectorAll('.resume-order-btn').forEach(button => {
        button.addEventListener('click', function () {
            const holdId = this.dataset.id;

            fetch(`load_held_order.php?id=${holdId}`)
                .then(res => res.json())
                .then(data => {
                    resetCart();

                    // ✅ Restore order mode and table
                    window.selectedOrderMode = data.order.order_mode || null;
                    window.selectedTableId = data.order.table_id || null;
                    window.unholdOrderId = holdId;

                    document.getElementById('selected-order-mode').value = window.selectedOrderMode || '';
                    document.getElementById('selected-table-id').value = window.selectedTableId || '';

                    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
                    data.items.forEach(item => {
                        const product = document.querySelector(`.product-info[data-id="${item.item_id}"]`);
                        if (product) {
                            product.click();
                            const addedRow = document.querySelector(`.product-list[data-item-id="${item.item_id}"]`);
                            if (addedRow) {
                                const qtyInput = addedRow.querySelector('input[name="qty"]');
                                qtyInput.value = item.quantity;
                            }
                        }
                    });

                    updateTotal();

                    // ✅ Close modal
                    const modalInstance = bootstrap.Modal.getInstance(document.getElementById('orders'));
                    modalInstance.hide();
                });
        });
    });
}



  // 🟢 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, proceed with adding to cart
    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');
    const existing = cartWrap.querySelector(`[data-code="${code}"]`);

    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', code);
    row.setAttribute('data-price', price);
    row.setAttribute('data-tax-type', taxType);
    row.setAttribute('data-tax-rate', taxRate);
    row.setAttribute('data-item-id', itemId);

    row.innerHTML = `
      <div class="d-flex align-items-center product-info">
        <div class="info">
          <span>${code}</span>
          <h6>${name}</h6>
          <p>Rs ${price}</p>
        </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 delete-icon" href="#"><i data-feather="trash-2"></i></a>
      </div>
    `;

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


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

    row.querySelector('.delete-icon').addEventListener('click', () => {
        row.remove();
        updateTotal();
    });
}


    function updateTotal() {
        let subtotal = 0, totalTax = 0, grandTotal = 0;

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

        subtotalEl.textContent = 'Rs ' + subtotal.toFixed(2);
        totalEl.textContent = 'Rs ' + grandTotal.toFixed(2);
        taxInput.value = totalTax.toFixed(2) + ' Rs';
        totalDisplay.textContent = 'Grand Total : Rs ' + grandTotal.toFixed(2);
    }

    // 💳 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 => {
                cartItems.push({
                    id: parseInt(row.getAttribute('data-item-id')) || 0,
                    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
                });
            });

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

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

    // 🟡 Handle payment method selection
document.querySelectorAll('.payment-option').forEach(button => {
  button.addEventListener('click', function () {
    selectedPaymentMethod = this.getAttribute('data-method');
    const bankWrapper = document.getElementById('bank-account-wrapper');
    const bankSelect = document.getElementById('bank-account-select');

    // If bank method, show dropdown and wait for selection
    if (selectedPaymentMethod === 'bank') {
      bankWrapper.classList.remove('d-none');
      bankSelect.focus();

      bankSelect.onchange = () => {
        if (bankSelect.value) submitSale(bankSelect.value);
      };
    } else {
      bankWrapper.classList.add('d-none');
      submitSale('');
    }
  });
});
function submitSale(bankAccountId) {
  const methodModal = bootstrap.Modal.getInstance(document.getElementById('select-payment-method'));
  methodModal.hide();

  fetch('save_sale.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
      customer_name: window.customerToSave,
      cart_json: JSON.stringify(window.cartItemsToSave),
      tax_amount: window.taxToSave,
      total_amount: window.totalToSave,
      payment_method: selectedPaymentMethod,
      table_id: window.selectedTableId || '',
      order_mode: window.selectedOrderMode || '',
      unhold_order_id: window.unholdOrderId || '',
      bank_account_id: bankAccountId
    })
  })
  .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);
    }
  })
  .catch(err => {
    alert("Failed to save sale.");
    console.error(err);
  });
}


// 💾 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 => {
      cartItems.push({
        id: parseInt(row.getAttribute('data-item-id')) || 0,
        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
      });
    });

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

    const holdData = {
      customer_name: document.getElementById('top-customer-select')?.value || 'Walk-in',

      cart_json: JSON.stringify(cartItems),
      table_id: window.selectedTableId || '',
      order_mode: window.selectedOrderMode || ''
    };

    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
        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) {
          const kotWindow = window.open(`print_kot.php?id=${response.hold_id}`, 'KOT_Print', 'width=600,height=700');
          if (kotWindow) kotWindow.focus();
        }

      } 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() {
        cartWrap.innerHTML = '';
        subtotalEl.textContent = 'Rs 0.00';
        totalEl.textContent = 'Rs 0.00';
        taxInput.value = '0 Rs';
        totalDisplay.textContent = 'Grand Total : Rs 0.00';
    }

    // 🔍 Live Search
    const productSearch = document.getElementById("product-search");
    const autocompleteList = document.getElementById("autocomplete-list");
    let currentFocus = -1;

    if (productSearch) {
        productSearch.addEventListener("input", function () {
            const search = this.value.trim();
            currentFocus = -1;
            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);
                    });
                })
                .catch(err => {
                    console.error("Search error:", err);
                    autocompleteList.innerHTML = "";
                });
        });

        productSearch.addEventListener("keydown", function (e) {
            let items = autocompleteList.getElementsByTagName("div");
            if (!items.length) return;

            if (e.key === "ArrowDown") {
                currentFocus++;
                setActive(items);
            } else if (e.key === "ArrowUp") {
                currentFocus--;
                setActive(items);
            } else if (e.key === "Enter") {
                e.preventDefault();
                if (currentFocus > -1 && items[currentFocus]) {
                    items[currentFocus].click();
                }
            }
        });

        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 = "";
            }
        });
    }
});
