// document.addEventListener('DOMContentLoaded', () => {
  const transactionTypeFilter = document.getElementById('transaction-type-filter');
  const dateFromFilter = document.getElementById('date-from-filter');
  const dateToFilter = document.getElementById('date-to-filter');
  const itemNameFilter = document.getElementById('item-name-filter');
  const summaryTableBody = document.getElementById('summary-table').querySelector('tbody');
  const transactionDetailsTable = document.getElementById('transaction-details-table').querySelector('tbody');

  const detailsModal = document.getElementById('details-modal');
  const transactionType=transactionTypeFilter.value

    
//   const companyName=sessionStorage.getItem('companyName');
// const branchName=sessionStorage.getItem('branchName');
const companyId=sessionStorage.getItem('companyId');
const branchId=sessionStorage.getItem('branchId');

  let transactionData = []; // Store all fetched data to filter locally
  let branchesData = [];

  // Set default dates to today
  dateFromFilter.value = new Date().toISOString().split('T')[0];
  dateToFilter.value = new Date().toISOString().split('T')[0];

  const dateFrom = dateFromFilter.value;
  const dateTo = dateToFilter.value;

  transactionTypeFilter.value="selling";// intial make selling
  // Fetch all transaction summaries initially
  async function fetchTransactionSummaries() {
    const dateFrom = dateFromFilter.value;
    const dateTo = dateToFilter.value;
    const transactionType=transactionTypeFilter.value

    const url = `/api/transaction/summary?branchId=${branchId}&companyId=${companyId}&startDate=${dateFrom}&endDate=${dateTo}&transactionType=${transactionType}`;
  const response = await fetch(url);
    
       
    const { summaries, branches } = await response.json();
    
    transactionData = summaries;
   
    branchesData = branches;
    
    populateTable();
  }





  function    filterbyDate() {
    
      const dateFrom = dateFromFilter.value;
      const dateTo = dateToFilter.value;
     


// If date filters are provided, fetch data from the backend
if (dateFrom && dateTo) {
  fetchFilteredDataByDate(dateFrom, dateTo);

 }

else{alert("please select date correctly");}


  }


  // Populate the summary table based on transactionData
  function populateTable() {
   


    renderTable(transactionData );
  }

  // Render the summary table based on filtered data
  function renderTable(data) {

     
      const dateFrom = dateFromFilter.value;
      const dateTo = dateToFilter.value;
      const transactionType=transactionTypeFilter.value


    summaryTableBody.innerHTML = ''; // Clear current table rows
    
  //   // Create a header row for branch names
  //   const headerRow = summaryTableBody.insertRow(0);
  //   headerRow.insertCell(0).textContent = 'Item Name';
  //   branchesData.forEach(branch => {
  //     // const cell = headerRow.insertCell();
  //     // cell.textContent = branch.name;

  //     const headerCell = document.createElement('th');
  //     headerCell.setAttribute('colspan', '2'); // Set colspan to 2
  //     headerCell.textContent = branch.name; // Name of the branch
  //     headerRow.appendChild(headerCell);
  //  }
  
  // );
// Create main header row for the item name and branches
const headerRow = document.createElement('tr');
headerRow.innerHTML = `<th>Item Name</th>`; // Add initial column for item name

// For each branch, create a nested header
branchesData.forEach(branch => {
  const branchHeaderCell = document.createElement('th');
  branchHeaderCell.setAttribute('colspan', '2'); // Colspan for quantity and price
  branchHeaderCell.textContent = branch.name;
  headerRow.appendChild(branchHeaderCell);
});

headerRow.innerHTML = headerRow.innerHTML + `<th rowspan="2" style="text-align:center;">Action</th>`;

summaryTableBody.appendChild(headerRow);

// Create a second row for the sub-headers (Quantity and Price)
const subHeaderRow = document.createElement('tr');
subHeaderRow.innerHTML = `<th></th>`; // Empty cell under "Item Name"

branchesData.forEach(() => {
  const quantityHeader = document.createElement('th');
  quantityHeader.textContent = 'Quantity';

  const priceHeader = document.createElement('th');
  priceHeader.textContent = 'Price';

  subHeaderRow.appendChild(quantityHeader);
  subHeaderRow.appendChild(priceHeader);
});

summaryTableBody.appendChild(subHeaderRow);





    // Render rows for each item and branch-specific transactions
    data.forEach(item => {
      const row = summaryTableBody.insertRow();
      row.insertCell(0).textContent = item.name;

      // Render cell for each branch
      branchesData.forEach(branch => {
        const branchSummary = item.branches.find(b => b.branchId === branch._id);
       // const cell = row.insertCell();
        if (branchSummary) {
        //  cell.textContent = `Q: ${branchSummary.totalQuantity} (Price: ${branchSummary.totalPrice})`;
        const quantityCell = document.createElement('td');
        quantityCell.textContent = branchSummary.totalQuantity.toFixed(2); // Set quantity with 2 decimal places
        
        const priceCell = document.createElement('td');
        priceCell.textContent = branchSummary.totalPrice.toFixed(2); // Set price with 2 decimal places
        
        row.appendChild(quantityCell);
        row.appendChild(priceCell);
       
      
      } else {
         // cell.textContent = 'N/A';
     
         const quantityCell = document.createElement('td');
         quantityCell.textContent = "N/A" // Set quantity
     
         const priceCell = document.createElement('td');
         priceCell.textContent = "N/A"; // Set price
         row.appendChild(quantityCell);
         row.appendChild(priceCell);
       

        }

    
      });

  
      const itemId= item._id.itemId;
    
      const detailButton = document.createElement('td');
    detailButton.innerHTML = `<button class="details-btn" onclick="openDetailsModal('${itemId}', '${dateFrom}', '${dateTo}', '${transactionType}')">Details</button>`;
    // detailButton.innerHTML = `<button> edit</button>`;   
   row.appendChild(detailButton);
      

           
      
    });
  }


  function fetchFilteredDataByDate(dateFrom, dateTo) {  

   
    const transactionType=transactionTypeFilter.value
    // Make sure dateFrom and dateTo are not empty before making the request
    if (dateFrom && dateTo) {
      // Construct the API URL with query parameters for start and end dates
      const url = `/api/transaction/summary?branchId=${branchId}&startDate=${dateFrom}&endDate=${dateTo}&transactionType=${transactionType}`;
     
        // Fetch the data from the backend with the provided date range
        fetch(url)
          .then(response => response.json())
          .then(data => {
            transactionData = data.summaries; // Update the transactionData with the new data
         
            renderTable( transactionData ); // Repopulate the table with the new data
          })
          .catch(error => console.error('Error fetching filtered data:', error));
      }
    }
    


    function filterbyType() {  
     
      const dateFrom = dateFromFilter.value;
      const dateTo = dateToFilter.value;
      const transactionType=transactionTypeFilter.value
      // Make sure dateFrom and dateTo are not empty before making the request
      if (dateFrom && dateTo) {
        // Construct the API URL with query parameters for start and end dates
        const url = `/api/transaction/summary?branchId=${branchId}&startDate=${dateFrom}&endDate=${dateTo}&transactionType=${transactionType}`;
       

        // Fetch the data from the backend with the provided date range
        fetch(url)
          .then(response => response.json())
          .then(data => {
            transactionData = data.summaries; // Update the transactionData with the new data
         
            renderTable( transactionData ); // Repopulate the table with the new data
          })
          .catch(error => console.error('Error fetching filtered data:', error));
      }
    }



// Function to filter the items based on the search input
function filterItems() {
  const searchTerm =  itemNameFilter.value.toLowerCase();
  
  // Filter the `transactionData` based on item name
  const filteredData = transactionData.filter(item =>
    item.name.toLowerCase().includes(searchTerm)
  );
  
  renderTable(filteredData); // Render the filtered results
}





window.openDetailsModal = function(itemId, dateFrom, dateTo, transactionType) {
  
  fetchTransactionDetails(itemId, dateFrom, dateTo, transactionType);
}


// shall veiw esss brnachId
// Function to fetch transaction details
function fetchTransactionDetails(itemId, dateFrom, dateTo, transactionType) {  
 
fetch(`/api/items/${itemId}/details?startDate=${dateFrom}&endDate=${dateTo}&transactionType=${transactionType}`)
  .then(response => { 
    // Check for a successful response
   
    if (!response.ok) {
    
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => {  const { details, inventory } = data;
    // Clear previous content
    transactionDetailsTable.innerHTML = '';

    // If there are no details, display a message
    if (details.length === 0) {
      const noDataRow = document.createElement('tr');
      noDataRow.innerHTML = `<td colspan="4">No transaction details found for the specified filters.</td>`;
      transactionDetailsTable.appendChild(noDataRow);
      return; // Return early if no details
    }

    // Loop through and append each detail to the table
    details.forEach(detail => {   
      const row = document.createElement('tr');
    
      // Ensure detail properties exist and are numbers before formatting
      row.innerHTML = `
     <td>${new Date(detail.createdAt).toISOString().split('T')[0] || 'N/A'}</td>


        <td>${detail.name || 'N/A'}</td>
        <td>${detail.quantity || 0}</td>
        <td>$${(detail.price || 0).toFixed(2)}</td>
        <td>$${(detail.total || 0).toFixed(2)}</td>
         <td>${detail.transactionId.customerId.name || 'N/A'}</td>
      `;

      transactionDetailsTable.appendChild(row);
    });
  
    // Open the modal
    detailsModal.style.display = 'block';
  })
  .catch(error => console.error('Error fetching transaction details:', error));
}




// Close the modal
window.closeDetailsModal = function() {
  detailsModal.style.display = 'none';
}






  // Add event listeners to filters for real-time filtering
  transactionTypeFilter.addEventListener('change', filterbyType);
  dateFromFilter.addEventListener('change', filterbyDate);
  dateToFilter.addEventListener('change', filterbyDate);
  itemNameFilter.addEventListener('input',filterItems);

  // Initial fetch of data
  fetchTransactionSummaries();
// });
