//document.addEventListener('DOMContentLoaded', () => {
    const itemForm = document.getElementById('item-form');
    const itemList = document.getElementById('items-list');
  //  const companySelect = document.getElementById('company-select');
    const itemIdField = document.getElementById('item-id');
    const itemNameField = document.getElementById('item-name');
    const kitchen = document.getElementById('kitchen');
    const category = document.getElementById('category');
const attachmentRequired = document.getElementById('attachmentRequired');
const stockRequired = document.getElementById('stockRequired');
    const itemCodeField = document.getElementById('item-code');
    const itemAvgPriceField = document.getElementById('item-avg-price');
    const itemSellingPriceField = document.getElementById('item-selling-price');
    const itemExpDate = document.getElementById('item-exp-date');
    const itemImageUrlField = document.getElementById('item-image-url');
    const itemType=document.getElementById('item-type');
    // const companyName=sessionStorage.getItem('companyName');
    // const branchName=sessionStorage.getItem('branchName');
     const companyId=sessionStorage.getItem('companyId');
    const branchId=sessionStorage.getItem('branchId');
   
 
    let items = [];
  
    // Load companies into dropdown
 
    function exportAsCSV() {
      // Get the table body data
      const tableBody = document.getElementById('items-tbody');
      const rows = tableBody.querySelectorAll('tr');
    
      // Prepare CSV data
      let csvData = 'Item Name,Item Code,Avg. Price,Selling Price\n'; // CSV header
    
      rows.forEach(row => {
        const cells = row.querySelectorAll('td');
        const rowData = Array.from(cells)
          .slice(0, 4) // Exclude the Actions column
          .map(cell => cell.textContent.trim()) // Get cell text
          .join(','); // Join cells with commas
        csvData += rowData + '\n'; // Add row to CSV data
      });
    
      // Create a Blob object with CSV data
      const blob = new Blob([csvData], { type: 'text/csv' });
    
      // Create a link to download the CSV
      const a = document.createElement('a');
      a.href = URL.createObjectURL(blob);
      a.download = 'items.csv'; // Filename
      a.style.display = 'none';
      document.body.appendChild(a);
    
      // Trigger the download
      a.click();
    
      // Clean up
      document.body.removeChild(a);
    }
    


// Populate the table with items
function renderItems(items) {
  
  const tbody = document.getElementById('items-tbody');
  tbody.innerHTML = ''; // Clear previous rows

  items.forEach(item => {
    const row = document.createElement('tr');
    row.innerHTML = `
      <td>${item.name}</td>
      <td>${item.code}</td>
      <td>${item.avg_price}</td>
      <td>${item.selling_price}</td>
      <td>
        <button class="edit-btn" data-id="${item._id}">Edit</button>
        <button class="delete-btn" data-id="${item._id}">Delete</button>
      </td>
    `;
    tbody.appendChild(row);
  });

  
          // Add event listeners for edit and delete buttons
          document.querySelectorAll('.edit-btn').forEach(button => {
            button.addEventListener('click', editItem);
          });
          document.querySelectorAll('.delete-btn').forEach(button => {
            button.addEventListener('click', deleteItem);
          });  
        

}


// Filter items by name
function filterItems() {

  const searchValue = document.getElementById('search-item').value.toLowerCase();
  const filteredItems = items.filter(item =>
    item.name.toLowerCase().includes(searchValue)
  );

  renderItems(filteredItems);
}




    // Load items and display them in the table
    function loadItems() {
      fetch(`/api/items?companyId=${companyId}`)
        .then(response => response.json())
        .then(data => {

       


          items = data;
     
   
        const tbody = itemList.querySelector('#items-tbody');
        tbody.innerHTML='';
          items.forEach(item => {  
            const row = document.createElement('tr');
            row.innerHTML = `
             

<td contenteditable="true" 
    class="editable-item-name" 
    data-original="${item.name}"
    data-item-id="${item._id}">
  ${item.name}
</td>

<td contenteditable="true" 
    class="editable-item-code" 
    data-original="${item.code}"
    data-item-id="${item._id}">
  ${item.code}
</td>

            

<td contenteditable="true" 
    class="editable-avg_price" 
    data-original="${item.avg_price.toFixed(2)}"
    data-item-id="${item._id}">
  ${item.avg_price.toFixed(2)}
</td>

<!-- Selling Price Cell -->
<td contenteditable="true" 
    class="editable-selling_price" 
    data-original="${item.selling_price.toFixed(2)}"
    data-item-id="${item._id}">
  ${item.selling_price.toFixed(2)}
</td>

<td contenteditable="true" 
    class="editable-low-stock" 
    data-original="${item.lowStock ? item.lowStock.toFixed(0) : '0'}"
    data-item-id="${item._id}">
  ${item.lowStock ? item.lowStock.toFixed(2) : '0.00'}
</td>



              <td>
                <button class="edit-btn" data-id="${item._id}">Edit</button>
                <button class="delete-btn" data-id="${item._id}">Delete</button>
              </td>
            `;



            row.querySelector('.editable-item-name').addEventListener('keydown', (e) => {
            const itemName = row.querySelector('.editable-item-name').textContent.trim();
            const itemCode = row.querySelector('.editable-item-code').textContent.trim();
            
              if (e.key === 'Enter') {
                e.preventDefault(); // Prevent new line in the contenteditable cell
            
                // Pass the updated values to the handler function
                handleItemEdit(e.target,itemName,itemCode)
                e.target.blur(); // Remove focus after processing the input
              }
            });




            row.querySelector('.editable-item-code').addEventListener('keydown', (e) => {
              const itemName = row.querySelector('.editable-item-name').textContent.trim();
              const itemCode = row.querySelector('.editable-item-code').textContent.trim();
              
                if (e.key === 'Enter') {
                  e.preventDefault(); // Prevent new line in the contenteditable cell
              
                  // Pass the updated values to the handler function
                  handleItemEdit(e.target,itemName,itemCode)
                  e.target.blur(); // Remove focus after processing the input
                }
              });

            row.querySelector('.editable-avg_price').addEventListener('keydown', (e) => {
              const selling_price = row.querySelector('.editable-selling_price').textContent.trim();
              const avg_price = row.querySelector('.editable-avg_price').textContent.trim();
            
              if (e.key === 'Enter') {
                e.preventDefault(); // Prevent new line in the contenteditable cell
            
                // Pass the updated values to the handler function
                handlePriceEdit(e.target, avg_price, selling_price);
            
                e.target.blur(); // Remove focus after processing the input
              }
            });
            


            row.querySelector('.editable-selling_price').addEventListener('keydown', (e) => {
              const selling_price = row.querySelector('.editable-selling_price').textContent.trim();
              const avg_price = row.querySelector('.editable-avg_price').textContent.trim();
            
              if (e.key === 'Enter') {
                e.preventDefault(); // Prevent new line in the contenteditable cell
            
                // Pass the updated values to the handler function
                handlePriceEdit(e.target, avg_price, selling_price);
            
                e.target.blur(); // Remove focus after processing the input
              }
            });




            row.querySelector('.editable-low-stock').addEventListener('keydown', (e) => {
              const lowStock = row.querySelector('.editable-low-stock').textContent.trim();
            
              if (e.key === 'Enter') {
                e.preventDefault(); // Prevent new line in the contenteditable cell
            
                // Pass the updated values to the handler function
                handleLowStockEdit(e.target,lowStock);
            
                e.target.blur(); // Remove focus after processing the input
              }
            });


                    tbody.appendChild(row);
          });
  
         
          // Add event listeners for edit and delete buttons
          document.querySelectorAll('.edit-btn').forEach(button => {
            button.addEventListener('click', editItem);
          });
          document.querySelectorAll('.delete-btn').forEach(button => {
            button.addEventListener('click', deleteItem);
          });  
       
      
          // document.querySelectorAll('.editable-avg_price').forEach(cell => {
          //   cell.addEventListener('keydown', (e) => {
          //     if (e.key === 'Enter') {
          //       e.preventDefault(); // Prevent new line in the contenteditable cell
          //       handlePriceEdit(e.target);
          //       e.target.blur(); // Remove focus after processing the input
          //     }
          //   });
          // });

          // document.querySelectorAll('.editable-selling_price').forEach(cell => {
          //   cell.addEventListener('keydown', (e) => {
          //     if (e.key === 'Enter') {
          //       e.preventDefault(); // Prevent new line in the contenteditable cell
          //       handlePriceEdit(e.target);
          //       e.target.blur(); // Remove focus after processing the input
          //     }
          //   });
          // });


        })
        .catch(error => console.error('Error loading items:', error));
    }
  





    function handleLowStockEdit(element,lowStock) {

      // 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
        
      
       
      
        if (lowStock< 0) {
          alert("Invalid quantity. Please enter a valid positive number.");
           element.textContent = element.getAttribute('data-original');
          return;
        }
      
        // Send the updated quantity to the server
        fetch(`/api/items/bulkEdit`, {
          method: "PUT",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
          lowStock:lowStock,
            itemId: ItemId,   // Item ID
            companyId: companyId,     // Branch ID
          }),
        })
          .then(response => {
            if (!response.ok) {
              throw new Error(`Server Error: ${response.statusText}`);
            }
            return response.json();
          })
          .then(data => {
            console.log("successfully updated:", data);
              // Change the text color to red
              element.style.color = "green";
            // Update the original value attribute to the new quantity
         
          })
          .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 handleItemEdit(element,name,code) {

      // 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
        
      
      
      
        if (name==='' || code==='') {
          alert("Invalid Name or Code. Please enter a valid Name or code.");
         
          element.textContent = element.getAttribute('data-original');
          return;
        }
      
        // Send the updated quantity to the server
        fetch(`/api/items/bulkEdit`, {
          method: "PUT",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            name:name,  
           code:code,
            itemId: ItemId,   // Item ID
            companyId: companyId,     // Branch ID
          }),
        })
          .then(response => {
            if (!response.ok) {
              throw new Error(`Server Error: ${response.statusText}`);
            }
            return response.json();
          })
          .then(data => {
            console.log("successfully updated:", data);
              // Change the text color to red
              element.style.color = "green";
            // Update the original value attribute to the new quantity
         
          })
          .catch(error => {
            console.error("Error updating code :", error.message);
            alert("Error updating  code. Please try again later.");
            // Revert to the original value if update fails
            element.textContent = element.getAttribute('data-original');
          });
      }
      


      function handlePriceEdit(element,avg_price,selling_price) {

        // 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 newAvg_price =avg_price;
          const newSelling_price=selling_price;
        
          if (newAvg_price<0 || newSelling_price< 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/items/bulkEdit`, {
            method: "PUT",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              avg_price: newAvg_price,  // Updated quantity
            selling_price:newSelling_price,
              itemId: ItemId,   // Item ID
              companyId: companyId,     // Branch ID
            }),
          })
            .then(response => {
              if (!response.ok) {
                throw new Error(`Server Error: ${response.statusText}`);
              }
              return response.json();
            })
            .then(data => {
              console.log("successfully updated:", data);
                // Change the text color to red
                element.style.color = "green";
              // Update the original value attribute to the new quantity
           
            })
            .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');
            });
        }



    // Submit the item form (Create or Update item)
    itemForm.addEventListener('submit', (e) => {
      e.preventDefault();
      var type='shop';
      const typeElement = document.querySelector('input[name="item-type"]:checked');
     
      if (typeElement) {
         type =typeElement.value;
        // Continue with the logic for saving or updating the item using the status value
      } else {
        // Handle the case where no status is selected
      //  console.error('No status selected.');
        // You can also show an alert or set a default status value
      }

     
      const imageFile = document.getElementById('item-image-url').files[0];
      

      // Create a FormData object
      const formData = new FormData();
      
      // Append text fields to FormData
      formData.append('companyId', companyId);
     // formData.append('status', status);
      formData.append('type', type);
      formData.append('name', itemNameField.value);
      formData.append('code', itemCodeField.value);
      formData.append('avg_price', itemAvgPriceField.value);
      formData.append('selling_price', itemSellingPriceField.value);
     // formData.append('expDate', itemExpDate.value);
      formData.append('kitchen',  kitchen.value); //
      formData.append('category', category.value);
      formData.append('attachmentRequired', attachmentRequired.value);
      formData.append('stockRequired', stockRequired.value);


      // Console check FormData
for (const [key, value] of formData.entries()) {
  
}

      // Append the image file to FormData
      if (imageFile) {
        formData.append('image', imageFile); // 'image' is the field name that the backend expects
      }
      
      // Define the item ID if updating an existing item
      const itemId = itemIdField.value;
      const method = itemId ? 'PUT' : 'POST';
      const url = itemId ? `/api/items/${itemId}` : '/api/items';
      
      // Send the request using fetch
      fetch(url, {
        method: method,
        body: formData, // Send FormData as the request body
      })
        .then(response => response.json())
        .then(data => {
          if (data) {
            alert('Item uploaded successfully!');
            itemForm.reset();
        
            itemIdField.value = '';  // Clear hidden field after submission
           
            loadItems();  // Reload items after saving
          } else {
            alert('Error uploading item.');
          }
        })
        .catch(error => console.error('Error:', error));
      

  
    
    });
  

   
  

    // Edit item (load data into form)
    function editItem(event) {
    
      const itemId = event.target.getAttribute('data-id');
      const item = items.find(item => item._id === itemId);
    
      itemIdField.value = item._id;
      itemNameField.value = item.name;
      itemCodeField.value = item.code;
   
      itemAvgPriceField.value = item.avg_price;
      itemSellingPriceField.value = item.selling_price;
      kitchen.value = item.kitchenId
      category.value = item.categoryId
      attachmentRequired.value = item.attachmentReq==true?'yes':'no';
      stockRequired.value = item.needStock==true?'yes':'no';
      
    

           // Show the "Register Item" tab
           document.getElementById('register-item').style.display = 'block';
           document.getElementById('items-list').style.display = 'none';
          
           setTypeValue(item.type);  // Call this function when the item is being edited to set the status radio button
   

    }
  
    // Delete item
    function deleteItem(event) {
      const itemId = event.target.getAttribute('data-id');
      if (confirm('Are you sure you want to delete this item?')) {
        fetch(`/api/items/${itemId}`, {
          method: 'DELETE'
        })
          .then(() => loadItems())  // Reload items after deletion
          .catch(error => console.error('Error deleting item:', error));
      }
    }
  


// Assuming you have the item object with a status field
function setTypeValue(type) {
  // Find the radio input that matches the item's current status
  const typeInput = document.querySelector(`input[name="item-type"][value="${type}"]`);
  
  // Check the radio input if it exists
  if (typeInput) {
    typeInput.checked = true;
  }
}


// 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('.tab-btn');
  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');
}


document.getElementById('register-item').style.display = 'block';
    // Initialize: load companies and items
  


   window.importCSV= function() {

      const csvFileInput = document.getElementById('csv-file');
      const file = csvFileInput.files[0];
    
      if (!file) {
        alert('Please select a CSV file to import.');
        return;
      }
    
      const updateQuantity = document.getElementById('update-quantity').checked;

      // Parse the CSV file
      Papa.parse(file, {
        header: true,
        skipEmptyLines: true,
        complete: function(results) {
          const items = results.data;
    
          // Assuming you want to send the items to the backend for saving
          fetch('/api/items/import', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({companyId, items,branchId ,updateQuantity})
          })
          .then(response => response.json())
          .then(data => {
           
              alert(data.message);
          
          })
          .catch(error => console.error('Error importing items:', error));
        }
      });
    }
    



   loadItems();
  //});
  