// Assume this is inside your "path/to/your/javascript/file.js"
document.getElementById('fetchSummaryBtn').addEventListener('click', fetchFinancialSummary);

async function fetchFinancialSummary() {
  const companyId = document.getElementById('companySelect').value;
  const branchId = document.getElementById('branchSelect').value;

  try {
    const response = await fetch(`/api/financial-summary?companyId=${companyId}&branchId=${branchId}`);
    const financialSummary = await response.json();

    populateFinancialSummaryTable(financialSummary);
  } catch (error) {
    console.error('Error fetching financial summary:', error);
  }
}

// Function to populate the table with financial summary data
function populateFinancialSummaryTable(data) {
  const tableBody = document.querySelector('#financialSummaryTable tbody');
  tableBody.innerHTML = ''; // Clear previous data

  data.forEach(item => {
    const row = document.createElement('tr');

    row.innerHTML = `
      <td>${item.branchName}</td>
      <td>${item.stockValue}</td>
      <td>${item.totalSales}</td>
      <td>${item.totalPurchases}</td>
      <td>${item.totalExpense}</td>
      <td>${item.bankDeposit}</td>
      <td>${item.bankWithdraw}</td>
    `;

    tableBody.appendChild(row);
  });
}

// Sample function to populate the company and branch select dropdowns
async function populateDropdowns() {
  try {
    const companyResponse = await fetch('/api/companies');
    const companies = await companyResponse.json();

    const companySelect = document.getElementById('companySelect');
    companies.forEach(company => {
      const option = document.createElement('option');
      option.value = company._id;
      option.textContent = company.name;
      companySelect.appendChild(option);
    });

    // Populate branches based on selected company
    companySelect.addEventListener('change', async () => {
      const companyId = companySelect.value;
      const branchResponse = await fetch(`/api/branches?companyId=${companyId}`);
      const branches = await branchResponse.json();

      const branchSelect = document.getElementById('branchSelect');
      branchSelect.innerHTML = ''; // Clear previous options

      branches.forEach(branch => {
        const option = document.createElement('option');
        option.value = branch._id;
        option.textContent = branch.name;
        branchSelect.appendChild(option);
      });
    });
  } catch (error) {
    console.error('Error populating dropdowns:', error);
  }
}

// Call the populateDropdowns function when the page loads
populateDropdowns();
