

import permissionUtils from "./common.js";
import { NEW_TRANSACTIONS_PERMISSIONS } from "./frontEndPermission.js";



// document.addEventListener('DOMContentLoaded', () => {
  //const companySelect = document.getElementById('company-select');
  //const branchSelect = document.getElementById('branch-select');
  const customerSelect = document.getElementById('customerList');
  const transactionTypeSelect = document.getElementById('transaction-type');
  const cartItemsTable = document.getElementById('cart-items'); // Table body for cart items
  const submitTransactionButton = document.getElementById('submit-transaction');
  const searchInput = document.getElementById('search-input');
  const cartCountElement = document.getElementById('cart-count');
  const toBranchSelect = document.getElementById('to-branch-select');
  const toBranchField = document.getElementById('to-branch-select-field');
 let itemType='shop';//default
const searchBox = document.getElementById('searchBox');// ordering
const searchBox2 = document.getElementById('searchBox2');// selecting customer
const dropdown = document.getElementById('dropdownList');// for ordering
let currentitemId = null;//current
const selectedSpecialNeeds = [];
const SelectedSpecialNeedsForItem = [];
const dropdown2 = document.getElementById('dropdownList2');// for customer
let paymentDetailTotal=0;
 
  let selectedOrderId='';
  let selectedCustomerId='';
  let currentWaiterId=null;
  let currentWaiterName=null;
  // Capture the transaction date
const transactionDateInput = document.getElementById('transaction-date');
// const companyName=sessionStorage.getItem('companyName');
// const branchName=sessionStorage.getItem('branchName');
const companyId=sessionStorage.getItem('companyId');
const branchId=sessionStorage.getItem('branchId');
const userId=sessionStorage.getItem('userId');
const defaultAction= "cafe" //sessionStorage.getItem('defaultAction');
let tableNo=null;





if (!companyId || !branchId) {
  console.log('Company ID and Branch ID are required.');
  window.location.href = "/"; // Redirect to the login page
}

  let selectedItems = []; // Stores items added to the cart for the transaction
  let allItems = []; // Store all items for local search
  let branchItems=[]
  let branchInventory = {}; // Store branch-specific inventory

  let   extractedData = [];

 
  const typeStore = document.getElementById('store-btn');
  const typeShop = document.getElementById('shop-btn')


  const branchType =sessionStorage.getItem('branchType');
  // Set the default radio button based on the condition
  if (branchType === "store") {
  
    itemType='store';

    handleItemTypeChange(itemType) 
    
  } else if (branchType === "shop") {
   
    itemType='shop';
    handleItemTypeChange(itemType) 
  }




  typeStore.addEventListener('click', () => handleItemTypeChange('store'));
   typeShop.addEventListener('click', () => handleItemTypeChange('shop'));




// Global variable to store items after fetching
let allOrders = [];

let allCustomers=[];
// Initial Fetch of All Items

async function fetchAllOrders() {
  try {
    const response = await fetch(`/api/order?companyId=${companyId}&branchId=${branchId}`);
    allOrders = await response.json();




    console.log("orders", allOrders);
  } catch (error) {
    console.error('Error fetching items:', error);
  }
}

// Event Listener for Search

searchBox.addEventListener('input', handleSearchBoxEvent);
searchBox.addEventListener('click', handleSearchBoxEvent);


function handleSearchBoxEvent() {
  const query = searchBox.value.trim().toLowerCase();

  // if (query) {
    // Filter items locally based on the search query
    
    let filteredItems = allOrders.filter((item) =>
      item.customerName.toLowerCase().includes(query)
    );

  
if(query.length==0){
  
  filteredItems=allOrders}

    // Clear previous dropdown options
    dropdown.innerHTML = '';

    // Populate dropdown with filtered results
    filteredItems.forEach((item) => {
      const option = document.createElement('div'); // Using div for custom styling
      option.className = 'dropdown-option'; // Add class for styling
      option.dataset.id = item._id; // Store the item's unique ID
   
      option.textContent = `${item.customerName} - ${item.itemName} - Advance: $${item.advancePayment}`;
      // Display name in the dropdown

      // Add click event to select the item
      option.addEventListener('click', () => {

         selectedOrderId = item._id; // Access the stored data-id
   
      searchBox.value = item.customerName; // Update the search box with the selected item's name
        dropdown.style.display = 'none'; // Hide the dropdown
      });

      dropdown.appendChild(option);
    });

    // Show the dropdown
    dropdown.style.display = 'block';
  // } else {
  //   // Hide the dropdown if search box is empty
  //   dropdown.style.display = 'none';
  // }
}

// Hide the dropdown when clicking outside
document.addEventListener('click', (event) => {
  if (!dropdown.contains(event.target) && event.target !== searchBox) {
    dropdown.style.display = 'none';
  }
});



// Initialize by fetching all items
fetchAllOrders();



async function fetchAllCustomers() {


  try {
  
    const response = await fetch(`/api/customers?companyId=${companyId}`);
    allCustomers = await response.json();


   console.log("customers", allCustomers);
  } catch (error) {
    console.error('Error fetching items:', error);
  }
}

// Event Listener for Search

searchBox2.addEventListener('input', handleSearchBoxEvent2);
searchBox2.addEventListener('click', handleSearchBoxEvent2);


function handleSearchBoxEvent2() {
  const query = searchBox2.value.trim().toLowerCase();

  // if (query) {
    // Filter items locally based on the search query
    
    let filteredItems = allCustomers.filter((item) =>
      item.name.toLowerCase().includes(query)
    );

  
if(query.length==0){
  
  filteredItems=allCustomers}

    // Clear previous dropdown options
    dropdown2.innerHTML = '';

    // Populate dropdown with filtered results
    filteredItems.forEach((item) => {
      const option = document.createElement('div'); // Using div for custom styling
      option.className = 'dropdown-option'; // Add class for styling
      option.dataset.id = item.customerId; // Store the item's unique ID
   
      option.textContent = `${item.name}`;
      // Display name in the dropdown

      // Add click event to select the item
      option.addEventListener('click', () => {

         selectedCustomerId = item.customerId; 
   
      searchBox2.value = item.name; // Update the search box with the selected item's name
        dropdown2.style.display = 'none'; // Hide the dropdown
      });

      dropdown2.appendChild(option);
    });

    // Show the dropdown
    dropdown2.style.display = 'block';
  // } else {
  //   // Hide the dropdown if search box is empty
  //   dropdown.style.display = 'none';
  // }
}

// Hide the dropdown when clicking outside
document.addEventListener('click', (event) => {
  if (!dropdown2.contains(event.target) && event.target !== searchBox) {
    dropdown2.style.display = 'none';
  }
});



// Initialize by fetching all items
fetchAllCustomers();




// Get references to the checkbox and search container
const addOrderCheckbox = document.getElementById('addOrder');
const searchContainer = document.getElementById('searchContainer');


// Add event listener to toggle visibility
addOrderCheckbox.addEventListener('change', () => {
  if (addOrderCheckbox.checked) {
    searchContainer.style.display = 'block'; // Show the search container
  } else {
    searchContainer.style.display = 'none'; // Hide the search container
  }
});



const showCustomer = document.getElementById('showCustomer');
const searchContainer2 = document.getElementById('searchContainer2');

showCustomer.addEventListener('click', () => {
  
  if ( searchContainer2.style.display === 'none') {
    searchContainer2.style.display = 'block'; // Show the search container
  } else {
    searchContainer2.style.display = 'none'; // Hide the search container
  }
});













  
 
  // itemTypeRadios.forEach(radio => {
  //   radio.addEventListener('change', handleItemTypeChange);

  // });






// Function to handle itemType change
function handleItemTypeChange(type) {

  itemType=type;
  // first show all
typeStore.style.display='block'
typeShop.style.display='block'

// then hide current active type

if(type==='store')
{
typeStore.style.display='none'
}
else{
  typeShop.style.display='none'
}
  displayBranchItems(branchItems);
}





  


      // Load branches for both "From" and "To" selections
      function loadBranches() {
        fetch(`/api/branches?companyId=${companyId}`)
          .then(response => response.json())
          .then(branches => {
            branches.forEach(branch => {
             const optionTo = document.createElement('option');
              optionTo.value = branch._id;
              optionTo.textContent = branch.name;
  
           
              toBranchSelect.appendChild(optionTo);
            });
          })
          .catch(error => console.error('Error loading branches:', error));
      }



      // const cameraBtn = document.getElementById('camera-btn');

      // cameraBtn.addEventListener('click', handleCameraData); 


      function handleCameraData() {


        // Simulate getting data from the camera (replace with your actual OCR logic)
     
    
       // console.log("branch data is",branchItems);
        extractedData.forEach(item => {
            const branchItem = branchItems.find(branchItem => branchItem.itemId.code === item.code);
    
            if (branchItem) {
                // Create a new cart item with quantity from OCR and details from branchItems

             
                let price = item.price === 0 ? branchItem.itemId.selling_price : item.price;
                let qty = item.quantity === 0 ? 1 : item.quantity;

                const cartItem = {
                  _id: branchItem.itemId._id,  // Extract the item ID from branchItem's itemId reference
                  name: branchItem.itemId.name,
                    code: item.code,
                     selling_price:price,
                    selling_quantity: qty, // Quantity from the OCR data
                    total:0// just only for formality
                };
console.log("cart item is",cartItem)

                addItemToCart(cartItem);
            } else {
                console.log(`Code ${item.code} not found in branch items.`);
            }
        });
    }



function branchData()
{
  {
    //const branchId = this.value; essss
  
    if (branchId) {  
      // Fetch branch-specific inventory from the backend
      fetch(`/api/branchInventory/all?branchId=${branchId}&companyId=${companyId}`)
        .then(response => response.json())
        .then(data => {
          branchItems = data;
          branchInventory = {}; // Clear previous inventory
          console.log("data is",data);
          data.forEach(item => {
            
            const itemId = item && item.itemId && item.itemId._id ? item.itemId._id : null;

          
           if(itemId){ // may tehre is item loaded for tsis branch inventory. may be it is deleted
            branchInventory[itemId] = item.quantity; // Store quantity for each item
           }
          });
      
          displayBranchItems(branchItems)
         // Display branch-specific item quantities
       
        })
        .catch(error => console.error('Error loading branch inventory:', error));
    } else {
    
      displayBranchItems([]); // Clear item list if no branch is selected
    }
  }

}



  // Display items in the item list table with branch-specific quantity
function displayItems(items) {
  const itemListTable = document.getElementById('item-list');
 
  itemListTable.innerHTML = ''; // Clear the current list

  items.forEach(item => { 
    const row = document.createElement('tr');
    row.innerHTML = `
      <td>${item.name}</td>
      <td>${item.code}</td>
      <td>$${item.selling_price.toFixed(2)}</td>
      <td>${item.quantity.toFixed(2)}</td> <!-- Show available quantity from the branch -->
      <td><button class="add-item-btn">Add to Cart</button></td>
    `;
    itemListTable.appendChild(row);

    // Add functionality for each 'Add to Cart' button
    row.querySelector('.add-item-btn').addEventListener('click', () => {
      addItemToCart(item);
    });
  });
}


function exportToExcel(items) {
  const worksheetData = [
    ['Name', 'Code','Average Price' ,'Selling Price', 'Quantity','type'], // Header row
    ...items.map(item => {
      // Check for null or undefined values in each property
      const name = item.itemId ? item.itemId.name : '';
      const code = item.itemId ? item.itemId.code : '';
      const avgPrice = item.itemId ? item.itemId.avg_price : 0; // Use 0 for numeric values or an empty string for text
     
      const sellingPrice = item.itemId ? item.itemId.selling_price : 0; // Use 0 for numeric values or an empty string for text
      const quantity = item.quantity || 0; // Use 0 for numeric values or an empty string for text
  const type=item.type||'';
      // Return an array with potentially adjusted values
      return [name, code, avgPrice,sellingPrice, quantity,type];
    }),
  ];

  // Create a worksheet
  const worksheet = XLSX.utils.aoa_to_sheet(worksheetData);

  // Create a workbook and append the worksheet
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Items');

  // Generate and download the Excel file
  XLSX.writeFile(workbook, 'Items.xlsx');
}

document.getElementById('export-btn').addEventListener('click', () => {
 
 //console.log("items are",branchItems);
 
  exportToExcel(branchItems); // Pass the items array to the function
});

function displayBranchItems(branchItems) {
  const itemListContainer = document.getElementById('item-list'); // Get the container element
  itemListContainer.innerHTML = ''; // Clear the current list

  branchItems.forEach(branchItem => {
    const image_url = branchItem.itemId.image_url2 || localStorage.getItem('companyLogo') || "/uploads/cyber.jpeg";

    // Ensure branchItem.itemId references the Item model and its fields like name, code, and image_url
    if (branchItem.itemId.type === itemType||branchItem.itemId.type === 'attachment') {
      // Create the card element
      const card = document.createElement('div');
      card.classList.add('item-card'); // Add a class for styling purposes

      card.innerHTML = `
        <div class="card-image">
          <img src="${image_url}" alt="${branchItem.itemId.name}">
        </div>
        <div class="card-content">
          <h4 class="item-name" style="color: ${branchItem.quantity <= branchItem.itemId.lowStock ? 'red' : 'green'}">
            ${branchItem.itemId.name}
          </h4>
           <p class="item-price">Price: $${branchItem.itemId.selling_price.toFixed(2)}</p>
           <button class="add-item-btn">Add</button>
        </div>
      `;

      itemListContainer.appendChild(card);

      // Add event listener for the "Add" button
      card.querySelector('.add-item-btn').addEventListener('click', () => {
        const item = {
          _id: branchItem.itemId._id, // Extract the item ID from branchItem's itemId reference
          name: branchItem.itemId.name,
          code: branchItem.itemId.code,
          selling_price: branchItem.itemId.selling_price,
          quantity: branchItem.quantity, // Include available quantity from branch inventory
        };

        addItemToCart(item); // Pass the constructed item object to addItemToCart
      });
    }
  });
}














function handleQuantityEdit(element) {

if (!permissionUtils.hasPermission(userPermissions, NEW_TRANSACTIONS_PERMISSIONS .FREE_EDIT)) {
 alert("you do not have permission to update branch quantity ");
 element.textContent = element.getAttribute('data-original');
  return 0;
}
 const ItemId = element.dataset.itemId; // Get branch item ID
  

  const newQuantity = parseFloat(element.textContent.trim());
  // Validate the input: ensure it is a valid positive number
  if (isNaN(newQuantity) || newQuantity < 0) {
    alert("Invalid quantity. Please enter a valid positive number.");
    // Revert to the original value
    element.textContent = element.getAttribute('data-original');
    return;
  }

  // Send the updated quantity to the server
  fetch(`/api/branch-inventory`, {
    method: "PUT",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      quantity: newQuantity,  // Updated quantity
      itemId: ItemId,   // Item ID
      branchId: branchId,     // Branch ID
    }),
  })
    .then(response => {
      if (!response.ok) {
        throw new Error(`Server Error: ${response.statusText}`);
      }
      return response.json();
    })
    .then(data => {
      console.log("Update successful:", data);
        // Change the text color to red
        element.style.color = "red";
      // Update the original value attribute to the new quantity
      element.setAttribute('data-original', newQuantity.toFixed(2));
    })
    .catch(error => {
      console.error("Error updating quantity:", error.message);
      alert("Error updating quantity. Please try again later.");
      // Revert to the original value if update fails
      element.textContent = element.getAttribute('data-original');
    });
}




  // Function to add the selected item to the cart
  function addItemToCart(item) {
    const existingRow = Array.from(cartItemsTable.children).find(row => row.querySelector('td').textContent === item.name);
   
    const transactionType = transactionTypeSelect.value;

   
    if (existingRow) {
      // If the item is already in the cart, just increase the quantity
      const quantityInput = existingRow.querySelector('.quantity-input');
      const newQuantity = parseInt(quantityInput.value) + 1;


// only for purchasing






// only for selling
      if (newQuantity <= branchInventory[item._id]) {
        quantityInput.value = newQuantity;
        const totalCell = existingRow.querySelector('td:nth-child(4)');
        const newPrice = cartRow.querySelector('.editable-price');;
       totalCell.value =  (newPrice.value * quantityInput.value).toFixed(2);

        // Update the total in selectedItems array
        const selectedItem = selectedItems.find(selectedItem => selectedItem._id === item._id);
        selectedItem.quantity = quantityInput.value;
        selectedItem.total = newPrice.value * quantityInput.value;

   // update sub total

   const subtotal = calculateSubtotal(selectedItems);
   const totalItems = calculateTotalItems(selectedItems);
   cartCountElement.innerText =  totalItems;
   // Update the UI to display the subtotal and number of items
   updateCartSummary(subtotal, totalItems);

      }
      
      
      else {
       // Check stock availability only if transaction type is 'selling'
     
    if (transactionType === 'selling' && item.quantity === 0) {
      alert('Item is out of stock!');
  return;
} 






      }
    }
    
    else {







      // Add new row for the item in the cart
      const cartRow = document.createElement('tr');
      let quantity = 1; // Default quantity when added to cart

if(item.selling_quantity)
{

  quantity=item.selling_quantity// if provided means if it is from camera update quantity
}
    
cartRow.innerHTML = `
        <td>${item.name}</td>
        <td><input type="number" value="${quantity}" min="1" class="quantity-input"></td>
       <td><input type="number" value="${item.selling_price}" class="editable-price"></td>
        <td style="display:none"><input type="number" value="${(item.selling_price * quantity).toFixed(2)}" class="editable-total-price"</td>
     <td style="display:none" ><input type="date" class="expDate" ></td>
        <td><button class="specialNeed">Special Need</button></td>

        <td><button class="remove-item-btn">Remove</button></td>
      `;

      cartItemsTable.appendChild(cartRow);

      // Add event listener to update total when quantity changes
       cartRow.querySelector('.quantity-input').addEventListener('input', function () {
       
        const newQuantity = this.value;

// only for purchasing , no need to check stock quantity
        if (transactionTypeSelect.value === 'purchasing'||transactionTypeSelect.value === 'producing')
{


   const totalCell = cartRow.querySelector('.editable-total-price');;
   const newPrice = cartRow.querySelector('.editable-price');;
         totalCell.value =  (newPrice.value * newQuantity).toFixed(2);

          // Update the total in the selectedItems array
          const selectedItem = selectedItems.find(selectedItem => selectedItem._id === item._id);
          selectedItem.quantity = newQuantity;
          selectedItem.total = newPrice.value * newQuantity; // Update total

             // update sub total

      const subtotal = calculateSubtotal(selectedItems);
      const totalItems = calculateTotalItems(selectedItems);
        // Update the content of the span
  cartCountElement.innerText =  totalItems;
      // Update the UI to display the subtotal and number of items
      updateCartSummary(subtotal, totalItems);

}

        // only for selling by default

        if (newQuantity <= branchInventory[item._id]) {

           const totalCell = cartRow.querySelector('.editable-total-price');;
           const newPrice = cartRow.querySelector('.editable-price');;
         totalCell.value =  (newPrice.value * newQuantity).toFixed(2);

          // Update the total in the selectedItems array
          const selectedItem = selectedItems.find(selectedItem => selectedItem._id === item._id);
          selectedItem.quantity = newQuantity;
          selectedItem.total = newPrice.value* newQuantity; // Update total


             // update sub total

      const subtotal = calculateSubtotal(selectedItems);
      const totalItems = calculateTotalItems(selectedItems);
      cartCountElement.innerText =  totalItems;
      // Update the UI to display the subtotal and number of items
       updateCartSummary(subtotal, totalItems);
        
      } 
        
        else {

            if (transactionTypeSelect.value === 'cafe'||transactionTypeSelect.value === 'selling'||transactionTypeSelect.value === 'transfering'||transactionTypeSelect.value === 'using') {
          
         if(transactionTypeSelect.value != 'cafe')
         {
              alert('Not enough stock available. ' +branchInventory[item._id]);
        
          this.value = branchInventory[item._id]; // Revert to maximum available stock
           
          const newQuantity=this.value;
         }

          const totalCell = cartRow.querySelector('.editable-total-price');;
          const newPrice = cartRow.querySelector('.editable-price');;
         totalCell.value =  (newPrice.value * newQuantity).toFixed(2);

          // Update the total in the selectedItems array
          const selectedItem = selectedItems.find(selectedItem => selectedItem._id === item._id);
          selectedItem.quantity = newQuantity;
          selectedItem.total = newPrice.value* newQuantity; // Update total


             // update sub total

      const subtotal = calculateSubtotal(selectedItems);
      const totalItems = calculateTotalItems(selectedItems);
      cartCountElement.innerText =  totalItems;
      // Update the UI to display the subtotal and number of items
       updateCartSummary(subtotal, totalItems);


        
        }

        }
      });



    // Add event listener to update total when price changes
    cartRow.querySelector('.editable-price').addEventListener('input', function () {
      const newPrice = this.value;
       const totalCell = cartRow.querySelector('.editable-total-price');;
      const quantityInput = cartRow.querySelector('.quantity-input');
     totalCell.value =  (newPrice * quantityInput.value).toFixed(2);

      // Update the total in the selectedItems array
      const selectedItem = selectedItems.find(selectedItem => selectedItem._id === item._id);
      selectedItem.price = newPrice;
      selectedItem.total = newPrice * quantityInput.value;

      // update sub total

      const subtotal = calculateSubtotal(selectedItems);
      const totalItems = calculateTotalItems(selectedItems);
      cartCountElement.innerText =  totalItems;
      // Update the UI to display the subtotal and number of items
      updateCartSummary(subtotal, totalItems);

    });




  // Add event listener to update total when price changes
  cartRow.querySelector('.editable-total-price').addEventListener('input', function () {
    
     const totalCell = cartRow.querySelector('.editable-total-price');
    const quantityInput = cartRow.querySelector('.quantity-input');
    const estimatedPrice=cartRow.querySelector('.editable-price');

   estimatedPrice.value =  (totalCell.value/quantityInput.value).toFixed(2);

    // Update the total in the selectedItems array
    const selectedItem = selectedItems.find(selectedItem => selectedItem._id === item._id);
   
    selectedItem.price = estimatedPrice.value;
    selectedItem.total = totalCell; 
    
   

    // update sub total

    const subtotal = calculateSubtotal(selectedItems);
    const totalItems = calculateTotalItems(selectedItems);
    cartCountElement.innerText =  totalItems;
    // Update the UI to display the subtotal and number of items
    updateCartSummary(subtotal, totalItems);

  });






      // Add event listener to remove item from cart
      cartRow.querySelector('.remove-item-btn').addEventListener('click', () => {
        cartItemsTable.removeChild(cartRow);
        selectedItems = selectedItems.filter(selectedItem => selectedItem._id !== item._id);
          // update sub total

   const subtotal = calculateSubtotal(selectedItems);
   const totalItems = calculateTotalItems(selectedItems);
   cartCountElement.innerText =  totalItems;
   // Update the UI to display the subtotal and number of items
   updateCartSummary(subtotal, totalItems);

      });



  cartRow.querySelector('.specialNeed').addEventListener('click', function () {
       
      
  currentitemId = item._id;
  selectedSpecialNeeds.length=0; // remove items
  updateSelectedSpecialNeeds();
  document.getElementById("special-specialNeedsModal").style.display = 'block';
  

      });





      // Add item to the selectedItems array
      selectedItems.push({
        _id: item._id,
        name: item.name,
        code: item.code,
        price: item.selling_price,
        total: item.selling_price * quantity,
        quantity: item. selling_quantity||1,
        specialNeeds:[],
       expDate:null,// make null until update
      });
    }





     // update sub total

     const subtotal = calculateSubtotal(selectedItems);
     const totalItems = calculateTotalItems(selectedItems);
     cartCountElement.innerText =  totalItems;
     // Update the UI to display the subtotal and number of items
     updateCartSummary(subtotal, totalItems); 


  }// end of cart function





// Function to calculate subtotal
function calculateSubtotal(items) {
 return items.reduce((acc, item) => acc + Number( item.total), 0);
}

// Function to calculate the number of items in the cart
function calculateTotalItems(items) {
 return items.reduce((acc, item) => acc + Number(item.quantity), 0);
}

// Function to update the subtotal and number of items in the UI
function updateCartSummary(subtotal, totalItems) {
 // Assuming you have elements with ids `cart-subtotal` and `cart-total-items` to display the subtotal and total items
 document.getElementById('cart-subtotal').textContent = `Subtotal: $${subtotal.toFixed(2)}`;
 document.getElementById('cart-total-items').textContent = `Total Items: ${totalItems}`;

 paymentDetailTotal=subtotal;
 document.getElementById("editCash").value=subtotal;
}


  transactionTypeSelect.addEventListener('change', function () {
    if (transactionTypeSelect.value === 'selling') {
      // Clear the cart when switching to selling
      cartItemsTable.innerHTML = '';
      selectedItems = [];
      alert('Cart cleared as you switched to selling.');
      toBranchField .style.display = 'none';
    }

    else if(transactionTypeSelect.value === 'transfering'){

      loadBranches();
      toBranchField .style.display = 'block';
    }
    else{
       toBranchField .style.display = 'none';

    }
  });
  





  function cafeOrders(orders)
  {
    if (!orders.items || orders.items.length === 0) {
      alert('No items in cart to order.');
      return;
    }

    // Capture waiter name BEFORE async operation to ensure it's available
    const waiterNameForPrint = currentWaiterName || 'N/A';

    fetch('/api/cafeorder', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ orders })
    })
      .then(response => response.json())
      .then(data => {
        if (data.success) {
          // Show toast notification instead of alert
      

          // Automatic printing after successful order
          if (window.kitchenPrinter) {
            const printData = {
              id: data.orderNo || 'N/A',
              orderId: data.orderId || data._id || null,
              table: orders.tableNo || null,
              waiter: waiterNameForPrint, // Use captured waiter name
              items: orders.items.map(item => ({
                itemId: item.itemId || null,
                quantity: item.quantity,
                name: item.name,
                specialNeeds: item.specialNeeds || []
              })),
              notes: ''
            };
            
            // Save print data immediately after successful order (don't wait for print)
            window.kitchenPrinter.savePrintDataToDatabase(printData);
            
            // Print order (async, don't wait)
         //   window.kitchenPrinter.printOrder(printData);

            if (window.showToast) {
              window.showToast('Ordered successfully!', 'success', 3000);
            } else {
              alert('ordered successfuly!');
            }
          }

          branchData();

          cartItemsTable.innerHTML = '';
          selectedItems = [];
          
          // Reset waiter info AFTER print data is captured and saved
          currentWaiterId = null;
          currentWaiterName = null;

          submitTransactionButton.disabled = false; 
          submitTransactionButton.style.backgroundColor = '';  
         
        //  renderCart();



        } else {
          alert('Order failed.');
        }
      })
      .catch(error => console.error('Error during transfer:', error));

  }


  function transferItems(transferCart)
  {
    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({ transferCart })
    })
      .then(response => response.json())
      .then(data => {
        if (data.success) {
          alert('Transfer successful!');

          branchData();

          cartItemsTable.innerHTML = '';
          selectedItems = [];
       
          transferCart = [];
          renderCart();



        } else {
          alert('Transfer failed.');
        }
      })
      .catch(error => console.error('Error during transfer:', error));

  }




// payment detail


//const total = 100; // Fixed total amount

// Elements
const cashField = document.getElementById("editCash");
const bankField = document.getElementById("editBank");
const creditField = document.getElementById("editCredit");
const otherField = document.getElementById("editOther");

// To store previous valid values
const previousValues = {
  bank: parseFloat(bankField.value) || 0,
  credit: parseFloat(creditField.value) || 0,
  other: parseFloat(otherField.value) || 0,
};

// Function to recalculate the cash field dynamically
function recalculateCash() {
  const bank = parseFloat(bankField.value) || 0;
  const credit = parseFloat(creditField.value) || 0;
  const other = parseFloat(otherField.value) || 0;

  // Calculate the current total
  const currentTotal = bank + credit + other;

  if (currentTotal > paymentDetailTotal) {
    // If total exceeds 100, reject the change and revert to previous value
    alert(`Total cannot exceed ${paymentDetailTotal}. Reverting to previous value.`);
    bankField.value = previousValues.bank;
    creditField.value = previousValues.credit;
    otherField.value = previousValues.other;
  } else {
    // Update the previous values
    previousValues.bank = bank;
    previousValues.credit = credit;
    previousValues.other = other;

    // Calculate remaining cash
    const cash = paymentDetailTotal - currentTotal;
    cashField.value = cash;
  }
}

// Attach event listeners to all fields except cash
[bankField, creditField, otherField].forEach((field) => {
  field.addEventListener("input", recalculateCash);
});

function submitTransaction() {
if(tableNo==null)
{
  alert('Please select a table number.');
  return;
}

document.getElementById('passcodeModal').style.display = 'block';

}
  // Function to gather the form and cart data and submit the transaction
  function submitTransactionAfterVerification() {
    submitTransactionButton.disabled = true; 
    submitTransactionButton.style.backgroundColor = 'gray';  
  
   // const companyId = companySelect.value; esss
     const customerId = selectedCustomerId;
   // console.log("cid is",customerId);
    let transactionType = transactionTypeSelect.value;
    const transactionDate =  new Date(transactionDateInput.value); // Get the selected date


// Get the current time
 const currentTime = new Date();

// Append the current time to the selected date
transactionDate .setUTCHours(currentTime.getHours());
transactionDate .setMinutes(currentTime.getMinutes());
transactionDate .setSeconds(currentTime.getSeconds());
transactionDate .setMilliseconds(currentTime.getMilliseconds());



const addOrderCheckbox = document.getElementById('addOrder');
if (addOrderCheckbox.checked&&selectedOrderId!='') {
transactionType='ordering';
searchBox.value = ''; // Update the search box to empty

   
}



//  Update  customer search box to empty
searchBox2.value = '';




if( selectedItems.length < 1) {
  alert('No items in cart to submit.');
  submitTransactionButton.disabled = false; 
  submitTransactionButton.style.backgroundColor = '#4CAF50';  
  submitTransactionButton.style.cursor = 'pointer';
  return;
}




if (transactionType=='cafe'){


if (tableNo==null)
{
  alert('Please select a table.');
  submitTransactionButton.disabled = false; 
  submitTransactionButton.style.backgroundColor = '#4CAF50';  
  submitTransactionButton.style.cursor = 'pointer';
  return;
}

  const ordersData = {
    companyId,
    branchId,
    userId:currentWaiterId,
    tableNo,
           items: selectedItems.map(item => ({
      itemId: item._id,
      name: item.name,
      code: item.code,
      quantity: item.quantity,
      specialNeeds: item.specialNeeds,
     
      
    }))
  };

  cafeOrders(ordersData);
  // Don't reset waiter info here - it's reset inside cafeOrders() after successful order
  return;
}




    if (transactionType=='transfering'){


      const transferData = {
        companyId,
            fromBranchId: branchId,
             toBranchId:toBranchSelect.value,
        transactionType,       
        items: selectedItems.map(item => ({
          itemId: item._id,
          name: item.name,
          code: item.code,
          quantity: item.quantity,
          balance: calculateBalance( transactionType,branchInventory[item._id],item.quantity),
        
        }))
      };

if(transferData.fromBranchId==transferData.toBranchId)
{
alert("please select different Branch!")
return;
}



      transferItems(transferData);
      return;
    }



    const { totalItems, subtotal } = getCartSummaryValues();

    if (!companyId || !branchId || !transactionType || selectedItems.length === 0) {
   
   
   
      console.log("Validation failed:");
      console.log("companyId is missing:", !companyId, "Value:", companyId);
      console.log("branchId is missing:", !branchId, "Value:", branchId);
      console.log("transactionType is missing:", !transactionType, "Value:", transactionType);
      console.log("No selected items:", selectedItems.length === 0, "Length:", selectedItems.length);
    

      alert('Please fill all fields and add items to the cart.');
      return;
    }




  const paymentDetail = {
      cash: parseFloat(document.getElementById("editCash").value) || 0,
      bank: parseFloat(document.getElementById("editBank").value) || 0,
      credit: parseFloat(document.getElementById("editCredit").value) || 0,
      other: parseFloat(document.getElementById("editOther").value) || 0,
      description: document.getElementById("editDescription").value.trim() || "",
    };
  
    const transactionData = {
      companyId,
      branchId,customerId,
      transactionType,
      totalItems,
      subtotal,
      transactionDate, // Include the selected date
      orderId:selectedOrderId,// include order Id
      paymentDetail,
      items: selectedItems.map(item => ({
        itemId: item._id,
        name: item.name,
        code: item.code,
        quantity: item.quantity,
        balance: calculateBalance( transactionType,branchInventory[item._id],item.quantity),
        price: item.price,
        total: item.total
      }))
    };

    console.log("data is",transactionData);
function calculateBalance(type,previousQuantity,quantity)
{ 
if(type=="selling"||type=="transfering"||type=="using"||type=='ordering')
{
return (Number(previousQuantity)-Number(quantity));

}
else return(Number(previousQuantity)+Number(quantity));// purchasing, producing

}
// Send the transaction data to the backend
fetch('/api/transaction', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(transactionData)
})
.then(response => response.json())
.then(data => {
  if (data.success) {
    // Reset the inner text of the cart summary elements
    document.getElementById('cart-total-items').innerText = 'Total Items: 0';
    document.getElementById('cart-subtotal').innerText = 'Subtotal: $0.00';
    
    alert('Transaction submitted successfully!');
    submitTransactionButton.disabled = false; 
    submitTransactionButton.style.backgroundColor = '';  // Reset to default
    submitTransactionButton.style.cursor = 'pointer';  // Set cursor back to pointer
    // Update branch data and clear cart and form
    fetchAllOrders();
    branchData();
    cartItemsTable.innerHTML = '';
       selectedItems = [];
       
  
  } else {
    // Display specific error message returned from the backend
    alert(`Failed to submit transaction: ${data.message || 'Unknown error'}`);
  }
})
.catch(error => {
  console.error('Error submitting transaction:', error);
  alert('An error occurred while submitting the transaction.');
});



  }

// Function to extract values from #cart-summary
function getCartSummaryValues() {
  // Get the number of total items
  const totalItemsText = document.getElementById('cart-total-items').innerText; // e.g., "Total Items: 3"
  const subtotalText = document.getElementById('cart-subtotal').innerText; // e.g., "Subtotal: $123.45"

  // Extract the numerical values from the text
  const totalItems = parseInt(totalItemsText.replace('Total Items:', '').trim(), 10);
  const subtotal = parseFloat(subtotalText.replace('Subtotal: $', '').trim());


  return { totalItems, subtotal };
}



const lowstockBtn=document.getElementById("lowStock-btn");
lowstockBtn.addEventListener('click',onlyRed);

function onlyRed()
{


const redBranchItems = branchItems.filter(
  (branchItem) => branchItem.quantity <= branchItem.itemId.lowStock
);

displayBranchItems(redBranchItems);
}




// Search input event listener for real-time search and auto-add to cart
searchInput.addEventListener('input', function () {
  const searchText = searchInput.value.toLowerCase();
  // Add a console log to check structure of branchItems


  // Filter branchItems based on name or code matching the search text
  const filteredItems = branchItems.filter(item =>
    
    item.itemId? item.itemId.name.toLowerCase().includes(searchText):false ||
    item.itemId?item.itemId.code.toLowerCase().includes(searchText):false
  );


  // Update displayed items based on search results
  displayBranchItems(filteredItems);

  // Automatically add to cart if only one item matches
  if (searchText.length > 3 && filteredItems.length === 1) {
    addItemToCart(filteredItems[0].itemId);
    searchInput.value = ''; // Clear the search input after adding to cart
  }
});






  // Add event listener to the submit button
  submitTransactionButton.addEventListener('click', submitTransaction);

  // Functionality for toggling fields
  //const companyTypeField = document.getElementById('company-type-field');
  //const branchField = document.getElementById('branch-field');
  const transactionTypeField = document.getElementById('transaction-type-field');
  const toggleBtn = document.getElementById('toggle-fields-btn1');

  const customerField = document.getElementById('customer-field');
  const dateField = document.getElementById('date-field');

  // Initially hide the fields
  //companyTypeField.style.display = 'none';
  //branchField.style.display = 'none';
  transactionTypeField.style.display = 'none';
  customerField.style.display = 'none';
      dateField.style.display = 'none';
     toBranchField.style.display = 'none';

  // Function to show or hide fields
  function toggleFields() {
  
    if ( dateField.style.display == 'none') {
    
      // companyTypeField.style.display = 'block';
      // branchField.style.display = 'block';
      transactionTypeField.style.display = 'block';
      customerField.style.display = 'block';
      dateField.style.display = 'block';
    } else {
    
     // companyTypeField.style.display = 'none';
    //  branchField.style.display = 'none';
      transactionTypeField.style.display = 'none';
      customerField.style.display = 'none';
      dateField.style.display = 'none';
    }
  }

  // Add event listener to the button to toggle fields visibility
  toggleBtn.addEventListener('click', toggleFields);
 
  // Load companies, branches, and items when the page loads


 //loadCompanies();    esss

  
// loadAllItems(); essss

 
const fetchCustomers = async () => {
  try {
    const response = await fetch(`/api/customers?companyId=${companyId}`);
    const customers = await response.json();

console.log("customers",customers)

 customerSelect.innerHTML = `<option value=''>select customer</option>`;


    customers.forEach(customer => {
      const option = document.createElement('option');
      option.value =customer.customerId;
      option.textContent = customer.name;

   //  if(customer.customerType=='customer'||customer.customerType=='Customer')
      if (customer.name=="walking" ||customer.name=="Walking") {
        option.selected = true; // Set this option as selected

        selectedCustomerId=customer.customerId;// it takes walking customer id as default customerId
      
        
      }

      customerSelect.appendChild(option);
    });
    
  } catch (err) {
    console.error('Error fetching customers:', err);
  }
};

//window.openTab = function(evt, tabName) {

// Function to handle tab switching
window.openTab = function(evt, tabName,btnName) {
  // 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('.tab-btn');
  tabButtons.forEach(btn => btn.classList.remove('active'));

  document.getElementById(tabName).style.display = 'block';
// first show all buttons
  document.getElementById("list-btn").style.display = 'block';
  document.getElementById("cart-btn").style.display = 'block';
// hide only current clicked button
  document.getElementById(btnName).style.display = 'none';

 // evt.currentTarget.classList.add('active');


      const trTabs = document.querySelector('.tr-tabs'); // Get the element to hide
       trTabs.style.display = (trTabs.style.display === 'none') ? 'flex' : 'none';
           
       const topAccess = document.querySelector('.top-access'); // Get the element to hide
       topAccess.style.display = (trTabs.style.display === 'none') ? 'flex' : 'none';
        

}







function populateTransactionOptions() {
  const transactionTypeSelect = document.getElementById('transaction-type');

  const branchType=sessionStorage.getItem('branchType');

  const typeOptions = ["C","P","PR","S", "T","U"];

    transactionTypeSelect.innerHTML = `
    <option value="cafe" ${defaultAction  == 'cafe' ? 'selected' : ''}>Cafe</option>

    <option value="purchasing" ${defaultAction  == 'purchasing' ? 'selected' : ''}>Purchasing</option>
<option value="producing" ${defaultAction == 'producing' ? 'selected' : ''}>Producing</option>
      <option value="selling" ${defaultAction == 'selling' ? 'selected' : ''}>Selling</option>
      <option value="transfering" ${defaultAction  == 'transfering' ? 'selected' : ''}>Transfer</option>
 
      <option value="using" ${defaultAction == 'using' ? 'selected' : ''}>Using</option>
   
 
        `;
  
}

// Call the function with the current condition
populateTransactionOptions();





function initializeNewTransaction()
{
  fetchCustomers();

  branchData();
  populateTransactionOptions();
 
}
initializeNewTransaction();


// Get today's date in the format yyyy-mm-dd
// const today = new Date();
// const year = today.getFullYear();
// const month = String(today.getMonth() + 1).padStart(2, '0'); // Month is zero-based
// const day = String(today.getDate()).padStart(2, '0');

const today = new Date();
console.log('Today\'s date:', today);

const year = today.getFullYear();
console.log('Year:', year);

const month = String(today.getMonth() + 1).padStart(2, '0'); // Month is zero-based
console.log('Month:', month);

const day = String(today.getDate()).padStart(2, '0');
console.log('Day:', day);

// Set the value of the date input
transactionDateInput.value = `${year}-${month}-${day}`;

//});

// Get elements
const showPaymentBtn = document.getElementById("showPaymentBtn");
const paymentFields = document.getElementById("editPaymentModal");

// Toggle visibility of payment fields
showPaymentBtn.addEventListener("click", function () {
  
    paymentFields.style.display = "block"; // Show payment fields
 
   
});








// Get the close button element
const closeEditModal = document.getElementById("closeEditModal");
closeEditModal.addEventListener("click", closeEditPaymentModal);


// Function to close the modal
function closeEditPaymentModal() {
  const modal = document.getElementById("editPaymentModal");
  modal.style.display = "none";
}


  const video = document.createElement('video');
  const canvas = document.getElementById('canvas');
  const startCameraButton = document.getElementById('start-camera-btn');// 
  const startCameraButton2 = document.getElementById('start-camera-btn2');// 
const chooseImageLabel=document.getElementById('chooseImageLabel');
  const captureButton = document.getElementById('capture-btn');
  const extractedTextDiv = document.getElementById('extracted-text'); // Make sure you have this div in your HTML
  let cameraStarted = false;

  const reshootButton = document.getElementById("reshoot-btn");
  const confirmButton = document.getElementById("confirm-btn");
  let currentStream;
  async function startCamera() {
      try {
          const constraints = { video: { facingMode: "environment" } };

        //   const stream = await navigator.mediaDevices.getUserMedia({
        //     video: {
        //         facingMode: "environment", // Or "user" for front camera
        //         zoom: true // Indicate that we want to use zoom
        //     },
        //     audio: false
        // });
        // currentStream = stream;
        // video.srcObject = stream;
        // video.style.display = 'block';
        // cameraStarted = true;
        // const track = stream.getVideoTracks()[0];
        // const capabilities = track.getCapabilities();
        // if(!capabilities.zoom){
        //     alert("Your device doesn't support zoom")
        //     return
        // }


         const stream = await navigator.mediaDevices.getUserMedia(constraints);
         video.srcObject = stream;
         video.setAttribute('playsinline', '');
         video.autoplay = true;

          video.style.cssText = `
              width: 100%;
              max-height: 50vh;
              display: block;
              margin-bottom: 10px;
          `;


     



          async function setZoom(value) {
            if (!currentStream) return;
            const track = currentStream.getVideoTracks()[0];
            try {
                await track.applyConstraints({ advanced: [{ zoom: value }] });
            } catch (err) {
                console.error("Could not apply zoom:", err);
            }
        }
        const zoomInButton = document.getElementById('zoomIn');
        const zoomOutButton = document.getElementById('zoomOut');
        startCameraButton.addEventListener('click',startCamera)
        zoomInButton.addEventListener('click', async () => {
            if (!currentStream) return;
            const track = currentStream.getVideoTracks()[0];
            const capabilities = track.getCapabilities();
            let currentZoom = track.getSettings().zoom || capabilities.zoom.min;
            let newZoom = Math.min(capabilities.zoom.max, currentZoom + 0.1);
            await setZoom(newZoom);
        });
        zoomOutButton.addEventListener('click', async () => {
            if (!currentStream) return;
            const track = currentStream.getVideoTracks()[0];
            const capabilities = track.getCapabilities();
            let currentZoom = track.getSettings().zoom || capabilities.zoom.min;
            let newZoom = Math.max(capabilities.zoom.min, currentZoom - 0.1);
            await setZoom(newZoom);
        });
        










          const mainContent = canvas.closest('.main-content');
          if (mainContent) {
              mainContent.insertBefore(video, canvas);
          } else {
              document.body.appendChild(video);
          }

          startCameraButton.style.display = 'none';
          chooseImageLabel.style.display='block';
          captureButton.style.display = 'block';
          captureButton.disabled = false;
          cameraStarted = true;
      } catch (error) {
          console.error("Error accessing camera:", error);
          alert("Camera access denied or not available.");
      }
  }

  async function takePhoto() {
      if (!cameraStarted) {
          alert("Please start the camera first.");
          return;
      }

      try {
          canvas.width = video.videoWidth;
          canvas.height = video.videoHeight;
          const context = canvas.getContext('2d');
          context.drawImage(video, 0, 0, canvas.width, canvas.height);

          video.srcObject?.getTracks().forEach(track => track.stop());
          video.srcObject = null;
          video.remove();

          canvas.style.display = 'block';
          video.style.display = 'none';

          captureButton.style.display = 'none';
          startCameraButton.style.display = 'none';

          reshootButton.style.display = 'block';
          confirmButton.style.display = 'block';

          reshootButton.addEventListener('click', () => {
              reshootButton.style.display = 'none';
              confirmButton.style.display = 'none';
              context.clearRect(0, 0, canvas.width, canvas.height);
              video.style.display = 'block';
              canvas.style.display = 'none'; // Hide the canvas again when reshooting
              startCamera();
          }, { once: true });

          confirmButton.addEventListener('click', async () => {
              reshootButton.style.display = 'none';
              confirmButton.style.display = 'none';
              startCameraButton.style.display = 'block';

              const imageData = canvas.toDataURL('image/jpeg', 0.8);

              try {
                  const response = await sendImageToBackend(imageData); // Call the backend function

                  if (response.ok) {
                     
                

                    const data = await response.json(); // Parse the JSON response
                     extractedData = data.data; // Access the 'data' property of the JSON
                    const message = data.message //access the message property
                    console.log("Extracted data:", extractedData);
                    console.log("Message from backend:", message);

                    handleCameraData()
                   
                     canvas.style.display = 'none'; // Hide the canvas again when reshooting
                    startCameraButton.style.display = 'none';
                    processButton.style.display = 'none';
                    chooseImageLabel.style.display='none';
                    captureButton.style.display = 'none';
                    openTab(null, 'right-column','cart-btn');



                    //  extractedTextDiv.textContent = extractedText; // Display in the designated div
                  } else {
                      console.error("Error sending image to backend:", response.status);
                     alert("Error processing the image. Please try again later.");
                    canvas.style.display = 'none'; // Hide the canvas again when reshooting
                    startCameraButton.style.display = 'block';
                    chooseImageLabel.style.display='none';
                    captureButton.style.display = 'none';
                  }
              } catch (error) {
                  console.error("Error sending image to backend:", error);

                  canvas.style.display = 'none'; // Hide the canvas again when reshooting
                  startCameraButton.style.display = 'block';
                  chooseImageLabel.style.display='none';
                  captureButton.style.display = 'none';
                  alert("A network error occurred. Please check your connection.");
              }
          }, { once: true });
      } catch (error) {
          console.error("Error taking photo:", error);
      }
  }

  startCameraButton.addEventListener('click', startCamera);

  startCameraButton2.addEventListener('click', startCamera);

  captureButton.addEventListener('click', takePhoto);
  captureButton.style.display = 'none';
  captureButton.disabled = true;


// **Backend Function (REPLACE THIS WITH YOUR ACTUAL BACKEND LOGIC)**
async function sendImageToBackend(imageData) {
  const backendUrl = '/upload'; // Replace with your backend URL

  try {
      const response = await fetch(backendUrl, {
          method: 'POST',
          headers: {
              'Content-Type': 'application/json', // Important for sending base64 data
          },
          body: JSON.stringify({ image: imageData }),
      });
      return response; // Return the full response object for better error handling
  } catch (error) {
      console.error("Error sending image:", error);
      throw error; // Re-throw to be caught by the caller
  }
}



document.addEventListener('DOMContentLoaded', () => {
  const typeButton = document.getElementById('type-btn');
   let typeIndex = 0;
  const typeOptions = ["C","P", "PR","S", "T","U"  ];
  const transactionValues = ["cafe","purchasing","producing","selling", "transfering", "using"];

 
   if (defaultAction) {// selling or purchasing
      let defaultIndex = transactionValues.indexOf(defaultAction);
      if (defaultIndex !== -1) {
          typeIndex = defaultIndex;
      }
  }

  typeButton.textContent = typeOptions[typeIndex];

  typeButton.addEventListener('click', () => {
      typeIndex = (typeIndex + 1) % typeOptions.length;
      typeButton.textContent = typeOptions[typeIndex];
      console.log("value is ", transactionTypeSelect.value);
      transactionTypeSelect.value = transactionValues[typeIndex];

      // No need to rebuild innerHTML, just update the selected option
      for (let i = 0; i < transactionTypeSelect.options.length; i++) {
          transactionTypeSelect.options[i].selected = (i === typeIndex);
      }
  });
});
  



const imageInput = document.getElementById('imageInput');
   
    const processButton = document.getElementById('processImage');
    let imageData2;

let file;
    imageInput.addEventListener('change', (event) => {
      const canvas = document.getElementById('canvas');
      const canvasHidden = document.getElementById('canvasHidden');
       file = event.target.files[0];

    


      if (file) {

        processButton.style.display="block";

        video.srcObject?.getTracks().forEach(track => track.stop());
        video.srcObject = null;
        video.remove();
        canvas.style.display = 'block';
        video.style.display = 'none';

          const reader = new FileReader();

          reader.onload = (e) => {
              const img = new Image();
              img.onload = () => {
                  canvas.width =400;
                  canvas.height =400;
                  canvasHidden.width =img.width;
                  canvasHidden.height =img.height;
                  const context = canvas.getContext('2d');
                  const contextHidden = canvasHidden.getContext('2d');
                  context.drawImage(img, 0, 0, canvas.width, canvas.height); // 
                  contextHidden.drawImage(img, 0, 0,img.width,img.height); // orginal size
               
                  imageData2 = canvasHidden.toDataURL('image/jpeg', 0.8);
            
                  canvas.style.display = 'block';
                 // video.style.display = 'none';
              };
              img.src = e.target.result;
          };

          reader.readAsDataURL(file);
      }
  });


  processButton.addEventListener('click', async () => {
    if (!imageData2) {
        alert("Please select an image first.");
        return;
    }

   



    try {
     
        const response = await sendImageToBackend(imageData2); 
      
         if (response.ok) {
               

          const data = await response.json(); // Parse the JSON response
           extractedData = data.data; // Access the 'data' property of the JSON
          const message = data.message //access the message property
          console.log("Extracted data:", extractedData);
          console.log("Message from backend:", message);

          handleCameraData()
         
          canvas.style.display = 'none'; // Hide the canvas again when reshooting
          startCameraButton.style.display = 'none';
          processButton.style.display = 'none';
          chooseImageLabel.style.display='none';
          captureButton.style.display = 'none';
          openTab(null, 'right-column','cart-btn');



        }







    } catch (error) {
        // ... (error handling)
    }
});


async function sendImageToBackend2(formData) {
  const backendUrl = '/upload'; // Replace with your backend URL

  try {
  
    const response = await fetch(backendUrl, {
      method: 'POST',
      body: formData, 
  });
      return response; // Return the full response object for better error handling
  } catch (error) {
      console.error("Error sending image:", error);
      throw error; // Re-throw to be caught by the caller
  }
}



if (permissionUtils.hasPermission(userPermissions, NEW_TRANSACTIONS_PERMISSIONS .VIEW_CART_SUBTOTAL)) {
const cartSubtotal=document.getElementById('cart-summary');
 cartSubtotal.style.display = 'block';
 }



// JavaScript to fetch category data and add click functionality
const renderCategories = async () => {
  try {
    const res = await fetch('/api/category');
    const categories = await res.json(); // Assuming the API returns an array of category objects

    const container = document.getElementById('categoryContainer');
    container.innerHTML = ''; // Clear any existing content

    categories.forEach(category => {
      const item = document.createElement('div');
      item.classList.add('category-item');
      item.textContent = category.name; // Customize to match your API response structure

      // Add click event listener to alert the category ID
      item.addEventListener('click', () => {
        onlySomeCategory(category._id)   
         });

      container.appendChild(item);
    });
  } catch (error) {
    console.error('Error fetching categories:', error);
  }
};

renderCategories();


function onlySomeCategory(categoryId) {



  const someItems = branchItems.filter((branchItem) => {
    // Check if branchItem and its catagoryId are defined
    if (!branchItem || branchItem.itemId.categoryId === undefined || branchItem.itemId.categoryId === null) {
   //   console.warn('Encountered a branchItem with undefined or null catagoryId:', branchItem);
      return false; // Skip this item
    }
  //  alert('found a branchItem with',branchItem.itemId.categoryId.toString());
    return branchItem.itemId.categoryId.toString() === categoryId.toString();
  });

  if (someItems.length === 0) {
    console.warn(`No items found for category ID: ${categoryId}`);
  }

  displayBranchItems(someItems);
}


async function fetchTables() {
  try {
    const res = await fetch('/api/table');
    const tables = await res.json();
    const calendar = document.getElementById('calendar');

    tables.forEach(table => {
      const tableDiv = document.createElement('div');
      tableDiv.className = 'table-item';
      tableDiv.innerHTML = `
        <div> No: ${table.No}</div>
        <button onclick="updateSelectedTable(${table.No})">Select</button>
      `;
      calendar.appendChild(tableDiv);
    });
  } catch (error) {
    console.error('Error fetching tables:', error);
  }
}

// Function to update the selected table
window.updateSelectedTable = function(tableNumber) {
  tableNo = tableNumber;
  
  document.getElementById('selectedTable').textContent = `No: ${tableNumber}`;
 document.getElementById('tableModal').style.display = 'none';
 };

// Open Modal
document.getElementById('openTableModal').addEventListener('click', () => {
  document.getElementById('tableModal').style.display = 'flex';
});

// Close Modal
document.getElementById('closeTableModal').addEventListener('click', () => {
  document.getElementById('tableModal').style.display = 'none'
  
  
  ;
});

// Close modal by clicking outside the content
window.addEventListener('click', (event) => {
  const modal = document.getElementById('tableModal');
  if (event.target === modal) {
    modal.style.display = 'none';
  }
});

// Fetch tables when the page loads
fetchTables();

const passcode = document.getElementById('passcodeInputModal');
  

passcode.addEventListener("input", function () {
  if (this.value.length === 4) {

   

    verifyPassCode(this.value);
  }
});

async function verifyPassCode(passcode) {
  try {
    const response = await fetch(`api/users/getByPasscode?passcode=${passcode}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    });

    if (response.ok) {
      const data = await response.json();
      currentWaiterId = data.userId;
      currentWaiterName = data.waiterName;
      console.log("waiter name is",currentWaiterName);
      submitTransactionAfterVerification();
      closePasscodeModal ();
   document.getElementById('passcodeInputModal').value = '';
    } else {
      alert('Invalid passcode. Please try again.');
    }
  } catch (error) {
    console.error('Error verifying passcode:', error);
    alert('An error occurred while verifying the passcode.');
  }
}

window.closePasscodeModal = function () {
  document.getElementById('passcodeModal').style.display = 'none';
  document.getElementById('passcodeError').style.display = 'none';
  document.getElementById('passcodeInputModal').value = '';
};



    // Function to fetch data from API
    async function fetchData(url) {
      try {
          const response = await fetch(url);
          return await response.json();
      } catch (error) {
          console.error('Error fetching data:', error);
          return [];
      }
  }


 

  function updateSelectedSpecialNeeds() {
      const selectedDiv = document.getElementById('selected-specialNeeds');
      if (selectedSpecialNeeds.length > 0) {
          selectedDiv.innerText = `Selected Special Needs: ${selectedSpecialNeeds.join(', ')}`;
      } else {
          selectedDiv.innerText = 'Selected Special Needs: None';
      }
  }

  function handleAddButtonClick(specialNeedName) {
      if (!selectedSpecialNeeds.includes(specialNeedName)) {
          selectedSpecialNeeds.push(specialNeedName);

          console.log(`Added: ${specialNeedName}`);
          console.log('Current list:', selectedSpecialNeeds);
      } else {
          console.log(`${specialNeedName} is already in the list.`);
      }
      updateSelectedSpecialNeeds();
      
    
  
  }

  document.getElementById('remove-all-btn').onclick = () => {
      selectedSpecialNeeds.length = 0; // Clear the array
      updateSelectedSpecialNeeds(); // Update the UI
      console.log('All selected special needs have been removed.');
  };

  document.getElementById('save-btn').onclick = () => {
      if (selectedSpecialNeeds.length > 0) {

      const selectedItem = selectedItems.find(selectedItem => selectedItem._id === currentitemId);
      selectedItem.specialNeeds = [...selectedSpecialNeeds]; // Using spread operator
     selectedSpecialNeeds.length=0; // remove items
     document.getElementById("special-specialNeedsModal").style.display = 'none';
     console.log(selectedItems); //
     console.log('special needs:', selectedItem.specialNeeds)
         } else {
          console.log('No special needs to save.');
      }
  };

  const modal = document.getElementById("special-specialNeedsModal");

  const closeModalBtn = document.getElementsByClassName("special-close")[0];


  closeModalBtn.onclick = () => modal.style.display = "none";
  window.onclick = (event) => {
      if (event.target === modal) modal.style.display = "none";
  };

  // Load categories and special needs
  async function loadModalData() {
      const categories = await fetchData('api/category');
      const specialNeeds = await fetchData('api/special-need');

      const categoriesDiv = document.getElementById('special-categories');
      const specialNeedsDiv = document.getElementById('special-specialNeeds');

      categoriesDiv.innerHTML = ''; // Clear previous categories
      specialNeedsDiv.innerHTML = ''; // Clear previous special needs

      // Display all special needs in card view by default
      specialNeeds.forEach(item => {
          const card = document.createElement('div');
          card.className = 'special-card';
          card.innerHTML = `
              <div>${item.name}</div>
              <button>Add</button>
          `;
          const addButton = card.querySelector('button');
          addButton.onclick = () => handleAddButtonClick(item.name);

          specialNeedsDiv.appendChild(card);
      });

      // Add category buttons in a row
      categories.forEach(category => {
          const button = document.createElement('button');
          button.className = 'special-category-button';
          button.innerText = category.name;
          button.onclick = () => {
              // Filter and display special needs for the selected category
              const filteredSpecialNeeds = specialNeeds.filter(item => item.categoryId._id === category._id);
              specialNeedsDiv.innerHTML = ''; // Clear previous special needs

              if (filteredSpecialNeeds.length > 0) {
                  filteredSpecialNeeds.forEach(item => {
                      const card = document.createElement('div');
                      card.className = 'special-card';
                      card.innerHTML = `
                          <div>${item.name}</div>
                          <button>Add</button>
                      `;
                      specialNeedsDiv.appendChild(card);
                  });
              } else {
                  const noResults = document.createElement('div');
                  noResults.innerText = 'No special needs found for this category.';
                  specialNeedsDiv.appendChild(noResults);
              }
          };
          categoriesDiv.appendChild(button);
      });
  }

  loadModalData();