 
 
 
 const startDateInput = document.getElementById('startDate');
 const endDateInput = document.getElementById('endDate');
 // Get today's date in YYYY-MM-DD format
 const today = new Date().toISOString().split('T')[0];

 // Set start and end date to today by default
 startDateInput.value = today;
 endDateInput.value = today;





 document.getElementById('filterButton').addEventListener('click', () => {

  fetchTransferReport();


 });


function fetchTransferReport() {
  const branchId = sessionStorage.getItem('branchId'); // Retrieve branchId from sessionStorage
  const companyId = localStorage.getItem('companyId'); // Retrieve companyId from localStorage


 // Get the start and end date values
 const startDate = document.getElementById('startDate').value;
 const endDate = document.getElementById('endDate').value;

 
  // Fetch transfer report for the branch and company
  fetch(`/api/transfers/report?branchId=${branchId}&companyId=${companyId}&start=${startDate}&end=${endDate}`)
  
    .then(response => response.json())
    .then(data => {
      const transfersTableBody = document.getElementById('transfers-table').querySelector('tbody');

      // Clear previous data
      transfersTableBody.innerHTML = '';

      // Populate the table with transfers
      data.forEach(transfer => {
        const otherBranch = transfer.transferType === 'Out' ? transfer.toBranchId.name : transfer.fromBranchId.name;
        const balance = transfer.transferType === 'Out' 
          ? transfer.fromBranchBalance 
          : transfer.toBranchBalance;

        const isActionDisabled =transfer.status === 'Returned'|| transfer.status === 'Accepted' || transfer.status === 'Rejected';
        const disabledClass = isActionDisabled ? 'disabled-button' : '';

        const actionButtons = transfer.transferType === 'Out'
          ? `<button class="return-transfer ${disabledClass}" ${isActionDisabled ? 'disabled' : ''}>Return</button>`
          : `
            <button class="accept-transfer ${disabledClass}" ${isActionDisabled ? 'disabled' : ''}>Accept</button>
            <button class="reject-transfer ${disabledClass}" ${isActionDisabled ? 'disabled' : ''}>Reject</button>
          `;

        const row = `
          <tr data-transfer-id="${transfer._id}">
            <td>${transfer.itemId.name}</td>
            <td>${transfer.quantity}</td>
            <td>${transfer.transferType}</td>
            <td>${otherBranch}</td>
            <td>${transfer.status}</td>
            <td>${new Date(transfer.createdAt).toLocaleDateString()}</td>
            <td>${actionButtons}</td>
          </tr>
        `;
        
        transfersTableBody.innerHTML += row;
      });

      // Attach event listeners to active buttons
      document.querySelectorAll('.accept-transfer:not([disabled])').forEach(button => {
        button.addEventListener('click', handleAcceptTransfer);
      });

      document.querySelectorAll('.reject-transfer:not([disabled])').forEach(button => {
        button.addEventListener('click', handleRejectTransfer);
      });

      document.querySelectorAll('.return-transfer:not([disabled])').forEach(button => {
        button.addEventListener('click', handleReturnTransfer);
      });
    })
    .catch(error => console.error('Error loading transfer report:', error));
}

// Function to handle accepting a transfer
function handleAcceptTransfer(event) {
  const transferId = event.target.closest('tr').dataset.transferId;
  const companyId = localStorage.getItem('companyId');

  showConfirmationModal("Are you sure you want to accept this transfer?", () => {
    fetch(`/api/transfers/process/${transferId}?status=Accepted&companyId=${companyId}`, { method: 'POST' })
      .then(response => response.json())
      .then(data => {
        alert('Transfer accepted');
        fetchTransferReport(); // Refresh the report
      })
      .catch(error => console.error('Error accepting transfer:', error));
  });
}

// Function to handle returning a transfer
function handleReturnTransfer(event) {
  const transferId = event.target.closest('tr').dataset.transferId;
  const companyId = localStorage.getItem('companyId');

  showConfirmationModal("Are you sure you want to return this transfer?", () => {
    fetch(`/api/transfers/process/${transferId}?status=Returned&companyId=${companyId}`, { method: 'POST' })
      .then(response => response.json())
      .then(data => {
        alert('Transfer returned');
        fetchTransferReport(); // Refresh the report
      })
      .catch(error => console.error('Error returning transfer:', error));
  });
}

// Function to handle rejecting a transfer
function handleRejectTransfer(event) {
  const transferId = event.target.closest('tr').dataset.transferId;
  const companyId = localStorage.getItem('companyId');

  showConfirmationModal("Are you sure you want to reject this transfer?", () => {
    const reason = prompt("Enter reason for rejection:");
    if (reason) {
      fetch(`/api/transfers/process/${transferId}?status=Rejected&reason=${encodeURIComponent(reason)}&companyId=${companyId}`, { method: 'POST' })
        .then(response => response.json())
        .then(data => {
          alert('Transfer rejected');
          fetchTransferReport(); // Refresh the report
        })
        .catch(error => console.error('Error rejecting transfer:', error));
    }
  });
}

// Confirmation modal functionality
function showConfirmationModal(actionMessage, onConfirm) {
  const modal = document.getElementById('confirmation-modal');
  const message = document.getElementById('confirmation-message');
  const confirmButton = document.getElementById('confirm-action');

  modal.style.display = 'flex';
  message.textContent = actionMessage;

  confirmButton.onclick = () => {
    onConfirm(); // Execute the confirmation action
    closeModal();
  };
}

function closeModal() {
  document.getElementById('confirmation-modal').style.display = 'none';
}

document.getElementById('cancel-action').onclick = closeModal;

fetchTransferReport();
function initializeTransfer() {

}
