document.addEventListener('DOMContentLoaded', () => {
    const addItemsBtn = document.getElementById('add-items-btn');
    const cartModal = document.getElementById('cart-modal');
    const closeModal = document.querySelector('.close');
    const finalizeItemsBtn = document.getElementById('finalize-items-btn');
    const searchButton = document.getElementById('search-item-btn');
    const cartTableBody = document.getElementById('cart-table-body');
    const totalPriceElement = document.getElementById('total-price');
    const companyName=sessionStorage.getItem('companyName');
const branchName=sessionStorage.getItem('branchName');
const companyId=sessionStorage.getItem('companyId');
const branchId=sessionStorage.getItem('branchId');
  
    let cartItems = []; // Store items in the cart
    let totalPrice = 0;
  
    // Open Modal
    addItemsBtn.addEventListener('click', () => {
      cartModal.style.display = 'block';
    });
  
    // Close Modal
    closeModal.addEventListener('click', () => {
      cartModal.style.display = 'none';
    });
  
    // Close Modal if clicked outside the modal content
    window.addEventListener('click', (event) => {
      if (event.target === cartModal) {
        cartModal.style.display = 'none';
      }
    });
  
    // Search item by code and add to cart
    searchButton.addEventListener('click', () => {
      const itemCode = document.getElementById('search-item-code').value.trim();
      if (itemCode) {
        // Assuming you already have items loaded in `allItems` array (from backend)
        const foundItem = allItems.find(item => item.code === itemCode);
        if (foundItem) {
          addItemToCart(foundItem);
        } else {
          alert('Item not found');
        }
      }
    });
  
    // Add item to cart
    function addItemToCart(item) {
      const existingItem = cartItems.find(cartItem => cartItem.code === item.code);
      const price = item.price ? item.price : 0;  // Handle undefined price
  
      if (existingItem) {
        // If item already exists in the cart, increase its quantity
        existingItem.quantity += 1;
        updateCartItem(existingItem);
      } else {
        // Add new item to cart
        cartItems.push({ ...item, quantity: 1 });
        const row = document.createElement('tr');
        row.innerHTML = `
          <td>${item.name}</td>
          <td>${item.code}</td>
          <td class="item-quantity">1</td>
          <td>$${price.toFixed(2)}</td>
          <td class="item-total">$${price.toFixed(2)}</td>
          <td><button class="remove-item-btn">Remove</button></td>
        `;
        cartTableBody.appendChild(row);
  
        // Add event listener for removing items from the cart
        row.querySelector('.remove-item-btn').addEventListener('click', () => {
          removeItemFromCart(item.code);
        });
      }
      updateTotalPrice();  // Recalculate the total price
    }
  
    // Update total price of the cart
    function updateTotalPrice() {
      totalPrice = cartItems.reduce((sum, item) => sum + item.price * item.quantity, 0);
      totalPriceElement.textContent = `$${totalPrice.toFixed(2)}`;
    }
  
    // Update an existing cart item
    function updateCartItem(item) {
      const existingRow = document.querySelector(`tr[data-item-code="${item.code}"]`);
      existingRow.querySelector('.item-quantity').textContent = item.quantity;
      existingRow.querySelector('.item-total').textContent = `$${(item.price * item.quantity).toFixed(2)}`;
    }
  
    // Remove item from cart
    function removeItemFromCart(itemCode) {
      cartItems = cartItems.filter(item => item.code !== itemCode);
      const row = document.querySelector(`tr[data-item-code="${itemCode}"]`);
      row.remove();
      updateTotalPrice();
    }
  
    // Finalize items and close the modal
    finalizeItemsBtn.addEventListener('click', () => {
      cartModal.style.display = 'none';
      console.log('Items finalized:', cartItems);
      // These finalized items will be used when submitting the transaction
    });
  });
  