// document.addEventListener('DOMContentLoaded', () => {
   
    const itemDetailsModal = document.getElementById('stock-details-modal');
   
    const itemDetailsTable = document.getElementById('item-table-container').querySelector('tbody');
  
    let allItems = []; // Store all items for local search
    let branchItems=[]
    let branchInventory = {}; // Store branch-specific inventory
  
var activeItemId=''; // ite will hold item id for active item for detail lists.
var activeItem='';
  // Filter elements
  const transactionTypeFilter = document.getElementById('transaction-type-filter');
  const startDateFilter = document.getElementById('start-date-filter');
  const endDateFilter = document.getElementById('end-date-filter');

  const itemNameLabel = document.getElementById('item-name-label');
  const availableQtyLabel = document.getElementById('available-qty-label');
  const typeLabel = document.getElementById('type-label');

 
    const companyId=sessionStorage.getItem('companyId');
    const branchId=sessionStorage.getItem('branchId');


    // Load all items
    function loadItems() {
        fetch(`/api/items?companyId=${companyId}`)
            .then(response => response.json())
            .then(data => {
                itemsTable.innerHTML = ''; // Clear current rows

                data.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>
                            <button onclick="viewItemDetails('${item._id}','${item.name}')">View Details</button>
                        </td>
                    `;
                    itemsTable.appendChild(row);
                });
            })
            .catch(error => console.error('Error loading items:', error));
    }
    


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

 

function displayBranchItems(branchItems) {


  const itemListTable = document.getElementById('item-list');
  itemListTable.innerHTML = ''; // Clear the current list
  let stockValue=0
  branchItems.forEach(branchItem => {
    const row = document.createElement('tr');

    if (!branchItem.itemId) {
      return; // Skip to the next iteration if itemId is missing
    }
   const stockValue1 = branchItem.quantity * (branchItem.itemId && typeof branchItem.itemId.avg_price === 'number' ? branchItem.itemId.selling_price : 0);
   console.log(branchItem.itemId.name,stockValue1);
   console.log(branchItem.quantity,)
    stockValue += branchItem.quantity * (branchItem.itemId && typeof branchItem.itemId.avg_price === 'number' ? branchItem.itemId.selling_price : 0);

    

    // Ensure branchItem.itemId references the Item model and its fields like name, code, and image_url
    row.innerHTML = `
      <td>
        <img src="${branchItem.itemId.image_url}" alt="${branchItem.itemId.name}" style="width:50px; height:50px;"> <!-- Display item image -->
      </td>
      <td>${branchItem.itemId.name}</td> <!-- Display item name -->
      <td>${branchItem.itemId.code}</td> <!-- Display item code -->
      <td>$${branchItem.itemId.selling_price.toFixed(2)}</td> <!-- Display selling price -->
      <td>${branchItem.quantity.toFixed(2)}</td> <!-- Display available quantity in this branch -->
     <td> <button onclick="viewItemDetails('${branchItem.itemId._id}','${branchItem.itemId.name}')">View Details</button>
                        </td>
    `;
  
    itemListTable.appendChild(row);


  });//

  stockValue=stockValue.toFixed(2);
  updateStockValue(stockValue);
}





function updateStockValue(stockValue) {
  const stockLabel = document.getElementById('stock-value-label');
  stockLabel.textContent = `Stock value for current Branch is: ${stockValue}`;
}








    // View item details in a modal
    window.viewItemDetails = function (itemId,itemName) {
     
       
        const transactionType = transactionTypeFilter.value?transactionTypeFilter.value:"purchasing"// default is purchasing
      
        const dateFrom = startDateFilter.value?new Date(startDateFilter.value):new Date();
        
        const dateTo =endDateFilter.value? new Date(endDateFilter.value):new Date();
      
        activeItemId=itemId;// for later use during filtering
       
       
        activeItem=itemName?itemName:activeItem;// if request is sent with item name hold the new request else hold the previous
        
      
        fetch(`/api/items/${itemId}/detailsAndTransfer?startDate=${dateFrom}&endDate=${dateTo}&transactionType=${transactionType}&companyId=${companyId}&branchId=${branchId}`)
            .then(response => response.json())
            .then(data => { 
                const { details, inventory } = data;

              


              //  Find the modal elements
                // const itemDetailsModal = document.getElementById('item-details-modal');
                // const itemDetailsTable = document.getElementById('item-details-table');
               
          
                // Set item name and available quantity labels
                itemNameLabel.textContent =`Item Name: ${activeItem}`;
               availableQtyLabel.textContent =` Available Quantity: ${inventory.quantity}`;
                typeLabel.textContent =`Transaction Type: ${transactionType}`;

                itemDetailsTable.innerHTML = ''; // Clear current details

                details.forEach(detail => { 
                    const row = document.createElement('tr');
                
                
                 if(detail.type=="transaction")
                 {
                    row.innerHTML = `
                        <td>${new Date(detail.createdAt).toLocaleDateString()}</td>
                       
                         <td>${detail.quantity.toFixed(2)}</td>
                        <td>$${detail.total.toFixed(2)}</td>
                         <td>${detail.transactionType}</td>
                          <td>${detail.balance}</td>
                           <td></td>
                        
                    `;
                 }

            if(detail.type=="transfer")
                 {

                  const otherBranch = detail.transferType === 'Out' ? detail.toBranch.name : detail.fromBranch.name;

                  // Determine the correct balance based on current branch (fromBranchBalance or toBranchBalance)
                  const balance = detail.transferType === 'Out' 
                    ? detail.FromBranchBalance 
                    : detail.toBranchBalance;

                   row.innerHTML = `
                   <td>${new Date(detail.createdAt).toLocaleDateString()}</td>
                    
                    <td>${detail.quantity.toFixed(2)}</td>
                    <td></td>
                    <td>${detail.transferType}</td>
                   
                    <td>${balance}</td> <!-- Display balance -->
                    <td>${otherBranch}</td>

                                `;
                 }

                    itemDetailsTable.appendChild(row);
                });

                // Show the modal
              
                itemDetailsModal.style.display = 'block';
              
                
            })
            .catch(error => console.error('Error loading item details:', error));




    };




  // Filter details based on transaction type and date
  function applyFilters() {
    const typeFilter = transactionTypeFilter.value.toLowerCase();
    const startDate = new Date(startDateFilter.value);
    const endDate = new Date(endDateFilter.value);

    const tableRows = detailList.getElementsByTagName('tr');

    Array.from(tableRows).forEach(row => {
      const date = new Date(row.getElementsByTagName('td')[0].textContent);
      const transactionType = row.getElementsByTagName('td')[4].textContent.toLowerCase();

      let matchesType = typeFilter === '' || transactionType === typeFilter;
      let matchesDate = (!startDateFilter.value || date >= startDate) &&
                        (!endDateFilter.value || date <= endDate);

      if (matchesType && matchesDate) {
        row.style.display = '';
      } else {
        row.style.display = 'none';
      }
    });
  }


      

  // Add event listeners for filters
  transactionTypeFilter.addEventListener('change', () =>  viewItemDetails(activeItemId));
  startDateFilter.addEventListener('change', () =>  viewItemDetails(activeItemId));
  endDateFilter.addEventListener('change', () =>  viewItemDetails(activeItemId));



    // Close the item details modal
    window.closeItemDetailsModal = function () {
        itemDetailsModal.style.display = 'none';
    };

    // Close the modal when clicking outside of it
    window.onclick = function(event) {
        if (event.target == itemDetailsModal) {
            itemDetailsModal.style.display = 'none';
        }
    };

  // Initial load
const currentDate = new Date();
const oneMonthAgo = new Date();
oneMonthAgo.setMonth(currentDate.getMonth() - 1);

// Format dates as YYYY-MM-DD
const formatDate = (date) => {
  return date.toISOString().split('T')[0];
};

// Assuming transactionTypeFilter, startDateFilter, and endDateFilter are input elements
transactionTypeFilter.value = 'All';
startDateFilter.value = formatDate(oneMonthAgo); // Set start date in proper format
endDateFilter.value = formatDate(currentDate);   // Set end date in proper format


    branchData();
// });
