//document.addEventListener('DOMContentLoaded', () => {
    // Variables and DOM Elements
    const transactionsTable = document.getElementById('transactions-table').querySelector('tbody');
    const searchInput = document.getElementById('item-name-filter'); // For real-time search by item name
    const transactionTypeFilter = document.getElementById('transaction-type-filter');
    const startDateSelect= document.getElementById('start-date');
    const endDateSelect = document.getElementById('end-date');
   
  
   const updateDetailBtn = document.getElementById('update-detail-btn');
  
   // Add click event listener
   updateDetailBtn.addEventListener('click', updateDetail);
  
    const companyName=sessionStorage.getItem('companyName');
  const branchName=sessionStorage.getItem('branchName');
  const companyId=sessionStorage.getItem('companyId');
  const branchId=sessionStorage.getItem('branchId');
  
  transactionTypeFilter.value="selling"; // intially set to selling by default
  
    let allTransactionDetails = []; // Store all transaction details locally
  
  
  
    // Add event listeners to handle changes
  startDateSelect.addEventListener('change', loadTransactionDetails);
  endDateSelect.addEventListener('change', loadTransactionDetails);
  transactionTypeFilter.addEventListener('change', loadTransactionDetails);
    // Load all transaction details once
         
          function loadTransactionDetails() {  
            const dateFrom=startDateSelect.value;
            const dateTo= endDateSelect.value;
       const transactionType=transactionTypeFilter.value;
  
            const url = `api/transactions/tr_details?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 => {
          allTransactionDetails = data; // Store all details locally
          displayTransactionDetails(allTransactionDetails); // Display all initially
        })
        .catch(error => console.error('Error loading transaction details:', error));
    }
  
   
  
  
    // Display transactions based on provided data
    function displayTransactionDetails(details) {
      let totalProfit = 0;
      let totalItems = 0;
      let totalSales=0;
      document.getElementById('total-sales').textContent ="0.00";
      document.getElementById('total-quantity').textContent = 0;
      document.getElementById('total-profit').textContent = "0.00";
  
  
  
      transactionsTable.innerHTML = ''; // Clear table before populating
      details.forEach(detail => {
     
        totalProfit += (detail.profit * detail.quantity);
        totalItems += detail.quantity;
        totalSales += (detail.price * detail.quantity); //
    
        const row = document.createElement('tr');
        row.innerHTML = `
          <td>${new Date(detail.createdAt).toLocaleDateString()}</td>
          <td>${detail.name}</td>
          <td>${detail.quantity}</td>
          <td>$${detail.price.toFixed(2)}</td>
          
          <td>$${detail.total.toFixed(2)}</td>
            <td class="profit-column">$${(detail.profit)*(detail.quantity).toFixed(2)}</td>
          <td>
          <button class="edit-btn hidden" onclick="openEditModal('${detail._id}', '${detail.quantity}', '${detail.price}')">Edit</button>
  
            <button onclick="deleteDetail('${detail._id}','${detail.transactionType}')">Delete</button>
          </td>
        `;
        // esssss   shall be view  <button class="edit-btn hidden"
        transactionsTable.appendChild(row);
  
        row.querySelector('.edit-btn').addEventListener('click', () => {
             
              openEditModal(detail._id, detail.quantity, detail.price,detail.name);
            });
        
  
  
      }     );
  
      totalProfit = totalProfit.toFixed(2); 
      totalSales = totalSales.toFixed(2); 
  
  // Display in HTML
  document.getElementById('total-sales').textContent = `$${totalSales}`;
  document.getElementById('total-quantity').textContent = totalItems
  document.getElementById('total-profit').textContent = `$${totalProfit}`;
  
    }
  
  
  
    // Real-time search by item name
    searchInput.addEventListener('input', () => {
      const searchValue = searchInput.value.toLowerCase();
     
      // Filter locally based on item name
      const filteredDetails = allTransactionDetails.filter(detail =>
        detail.name.toLowerCase().includes(searchValue)
      );
     
      displayTransactionDetails(filteredDetails); // Display filtered results
    });
  
   
  
      // Filter transactions locally
      const filteredDetails = allTransactionDetails.filter(detail => {
        let isMatch = true;
        if (filters.dateFrom && new Date(detail.date) < new Date(filters.dateFrom)) {
          isMatch = false;
        }
        if (filters.dateTo && new Date(detail.date) > new Date(filters.dateTo)) {
          isMatch = false;
        }
        if (filters.branch && detail.branch !== filters.branch) {
          isMatch = false;
        }
        return isMatch;
      });
  
    //   displayTransactionDetails(filteredDetails);
    // });
  
  
  
  
  
  // Function to view details
  function viewDetail(detailId) {
    fetch(`/api/transactionDetails/${detailId}`)
      .then(response => response.json())
      .then(detail => {
        // Populate modal or display area with the detail data
        // Example:
        alert(`Item: ${detail.itemName}, Quantity: ${detail.quantity}, Price: $${detail.price}`);
        
        // Here you can open a modal or update a specific HTML element to show details
      })
      .catch(error => console.error('Error fetching transaction detail:', error));
  }
  
  
  
  
  // Function to open the edit modal with pre-filled data
  function editDetail(detailId) {
  
    fetch(`/api/transactionDetails/${detailId}`)
      .then(response => response.json())
      .then(detail => {
        // Open the modal and pre-fill data fields
        const editModal = document.getElementById('edit-modal');
        document.getElementById('edit-item-name').value = detail.name;
        document.getElementById('edit-quantity').value = detail.quantity;
        document.getElementById('edit-price').value = detail.price;
        document.getElementById('edit-total').value = detail.total;
        document.getElementById('edit-detail-id').value = detail._id; // Store the detailId for updating
  
        // Show the modal
        editModal.style.display = 'block';
      })
      .catch(error => console.error('Error fetching transaction detail for editing:', error));
  }
  
  // Function to update detail
  function updateDetail() {
    const detailId = document.getElementById('edit-detail-id').value; // Get the stored detailId
    const updatedDetail = {
      itemName: document.getElementById('edit-item-name').value,
      quantity: parseInt(document.getElementById('edit-quantity').value),
      price: parseFloat(document.getElementById('edit-price').value),
      total: parseFloat(document.getElementById('edit-total').value)
    };
  
    fetch(`/api/transactionDetails/${detailId}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(updatedDetail)
    })
      .then(response => response.json())
      .then(data => {
        if (data.success) {
          alert('Transaction detail updated successfully');
          document.getElementById('edit-modal').style.display = 'none'; // Close the modal
          loadTransactionDetails(); // Reload transaction details
        } else {
          alert('Failed to update transaction detail');
        }
      })
      .catch(error => console.error('Error updating transaction detail:', error));
  }
  
  
  //document.querySelector('.close').addEventListener('click', closeEditModal);
  // Select all elements with the 'close' class and add click listener
  document.querySelectorAll('.close').forEach(button => {
    button.addEventListener('click', closeEditModal);
  });
  
  // Function to close the edit modal
  function closeEditModal() {
   
    document.getElementById('edit-modal').style.display = 'none';
  }
  // Assign the function to the window object to make it global
  window.deleteDetail = function(detailId,transactionType) {
  
  
    if (confirm('Are you sure you want to delete this transaction?')) {
      fetch(`/api/transactions/one/${detailId}?transactionType=${transactionType}`, { method: 'DELETE' })
          .then(response => response.json())
          .then(data => {
              if (data.success) {
                  alert('Transaction deleted successfully');
                  loadTransactionDetails() ;// Reload transactions
              } else {
                  alert('Failed to delete transaction');
              }
          })
          .catch(error => console.error('Error deleting transaction:', error));
  }
  
  
  }
  
  
  
  
  
  
  
  
  
  // Calculate total automatically when quantity or price changes
  
  document.getElementById('edit-quantity').addEventListener('input', calculateTotal);
  
  document.getElementById('edit-price').addEventListener('input', calculateTotal);
  
  
  
  function calculateTotal() {
  const quantity = parseInt(document.getElementById('edit-quantity').value) || 0;
  const price = parseFloat(document.getElementById('edit-price').value) || 0;
  document.getElementById('edit-total').value = (quantity * price).toFixed(2);
  }
  
  
  
  function openEditModal(detailId, quantity, price,name) {
  
  
    // Populate the modal fields with the transaction detail data
    document.getElementById('edit-item-name').value =name;
    document.getElementById('edit-detail-id').value = detailId;
    document.getElementById('edit-quantity').value = quantity;
    document.getElementById('edit-price').value = price;
  
    // Calculate total and display
    document.getElementById('edit-total').value = (quantity * price).toFixed(2);
  
    // Display the modal
    const modal = document.getElementById('edit-modal');
    modal.style.display = 'block';
  }
  
  // Close the modal function
  function closeEditModal() {
    document.getElementById('edit-modal').style.display = 'none';
  }
  
  // Optionally, close the modal when clicking outside of it
  window.onclick = function(event) {
    const modal = document.getElementById('edit-modal');
    if (event.target == modal) {
      modal.style.display = 'none';
    }
  };
  
  transactionTypeFilter.addEventListener('change', () => {
    loadTransactionDetails();
  
    // Hide profit section and total profit if transaction type is 'purchasing'
    const profitColumns = document.querySelectorAll('.profit-column'); // Select profit columns
    const totalProfitSection = document.getElementById('total-profit'); // Total profit element
  
    if (transactionTypeFilter.value === 'purchasing') {
      profitColumns.forEach(column => column.style.display = 'none'); // Hide profit columns
      totalProfitSection.parentElement.style.display = 'none'; // Hide total profit section
    } else {
      profitColumns.forEach(column => column.style.display = 'table-cell'); // Show profit columns
      totalProfitSection.parentElement.style.display = 'block'; // Show total profit section
    }
  });
  
  
  
  
  //
  
  const showModalBtn = document.getElementById('show-modal');
  const modal = document.getElementById('stock-details-modal');
  //  const closeBtn = modal.querySelector('.close-btn');
  
  // Show the modal when the button is clicked
  showModalBtn.addEventListener('click', function () {
    alert()
    modal.style.display = 'flex'; // Change display from none to flex to show modal
  });
  //
  // Hide the modal when the close button is clicked
  // closeBtn.addEventListener('click', function () {
  //   modal.style.display = 'none'; // Hide modal by setting display to none
  // });
  
  // Hide modal when clicking outside the modal content
  window.addEventListener('click', function (e) {
    if (e.target === modal) {
      modal.style.display = 'none'; // Hide modal by setting display to none
    }
  });
  
  
  
  
    loadTransactionDetails();
  //});
  