// document.addEventListener('DOMContentLoaded', () => {
    const fromBranchSelect = document.getElementById('from-branch-select');
    const toBranchSelect = document.getElementById('to-branch-select');
    const searchInput = document.getElementById('search-input');
    const itemsTbody = document.getElementById('items-tbody');
    const cartTbody = document.getElementById('cart-tbody');
    const performTransferBtn = document.getElementById('perform-transfer-btn');
  
    let transferCart = [];
    let allItems = [];
   
    // Function to handle tab switching
    window.openTab = function(evt, tabName) {
      // Hide all tab contents
      const tabContent = document.querySelectorAll('.tab-content');
      tabContent.forEach(content => content.style.display = 'none');
  
      // Remove 'active' class from all buttons
      const tabButtons = document.querySelectorAll('.tr-tab-button');
      tabButtons.forEach(btn => btn.classList.remove('active'));
  
      // Show the current tab and add 'active' class to clicked button
      document.getElementById(tabName).style.display = 'block';
      evt.currentTarget.classList.add('active');
    }
  
    // Load items when the page loads
    function loadItems() {
      fetch('/api/items')
        .then(response => response.json())
        .then(items => {
          allItems = items;
          displayItems(items);
        })
        .catch(error => console.error('Error loading items:', error));
    }
  
    // Display items in the table with an "Add to Cart" button
    function displayItems(items) {
      itemsTbody.innerHTML = ''; // Clear current items
      items.forEach(item => {
        const row = document.createElement('tr');
        row.innerHTML = `
          <td>${item.name}</td>
          <td>${item.code}</td>
          <td>${item.quantity}</td>
          <td><button class="add-to-cart-btn" data-id="${item._id}">Add to Cart</button></td>
        `;
        itemsTbody.appendChild(row);
  
        // Add functionality for "Add to Cart" button
        row.querySelector('.add-to-cart-btn').addEventListener('click', () => {
          addToCart(item);
        });
      });
    }
  
    // Search and filter items based on input
    searchInput.addEventListener('input', () => {
      const query = searchInput.value.toLowerCase();
      const filteredItems = allItems.filter(item => 
        item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query)
      );
      displayItems(filteredItems);
    });
  
    // Add item to cart
    function addToCart(item) {
      // Check if the item is already in the cart
      const existingCartItem = transferCart.find(cartItem => cartItem.itemId === item._id);
  
      if (existingCartItem) {
        existingCartItem.quantity += 1;
      } else {
        transferCart.push({ itemId: item._id, name: item.name, quantity: 1 });
      }
  
      renderCart();
    }
  
    // Render cart items
    function renderCart() {
      cartTbody.innerHTML = ''; // Clear current cart items
      transferCart.forEach((item, index) => {
        const row = document.createElement('tr');
        row.innerHTML = `
          <td>${item.name}</td>
          <td>${item.quantity}</td>
          <td><button onclick="removeFromCart(${index})">Remove</button></td>
        `;
        cartTbody.appendChild(row);
      });
    }
  
    // Remove item from cart
    window.removeFromCart = (index) => {
      transferCart.splice(index, 1);
      renderCart();
    };
  
    // Perform transfer
    performTransferBtn.addEventListener('click', () => {
      if (transferCart.length === 0) {
        alert('No items in cart to transfer.');
        return;
      }
  
      fetch('/api/transfers/transfer', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ items: transferCart })
      })
        .then(response => response.json())
        .then(data => {
          if (data.success) {
            alert('Transfer successful!');
            transferCart = [];
            renderCart();
          } else {
            alert('Transfer failed.');
          }
        })
        .catch(error => console.error('Error during transfer:', error));
    });
  
    loadItems();





    
  // });
  