//document.addEventListener('DOMContentLoaded', () => {
  const totalSalesElem = document.getElementById('total-sales');
  const totalPurchasesElem = document.getElementById('total-purchases');
  const totalProfitElem = document.getElementById('total-profit');
  const transactionTableBody = document.getElementById('transaction-table').querySelector('tbody');
  const companySelect = document.getElementById('company-select');
  const branchSelect = document.getElementById('branch-select');
  const transactionTypeSelect = document.getElementById('transaction-type');
  const startDateInput = document.getElementById('date-range-start');
  const endDateInput = document.getElementById('date-range-end');
  const companyName=sessionStorage.getItem('companyName');
const branchName=sessionStorage.getItem('branchName');
const companyId=sessionStorage.getItem('companyId');
const branchId=sessionStorage.getItem('branchId');

  // Load companies when the page loads
  function loadCompanies() {
    fetch('/api/companies')
      .then(response => response.json())
      .then(data => {
        companySelect.innerHTML = '<option value="">All Companies</option>';
        data.forEach(company => {
          const option = document.createElement('option');
          option.value = company._id;
          option.textContent = company.name;
          companySelect.appendChild(option);
        });
      })
      .catch(error => console.error('Error loading companies:', error));
  }

  // Load branches when a company is selected
  companySelect.addEventListener('change', function () {
    const companyId = this.value;
    if (companyId) {
      fetch(`/api/branches?companyId=${companyId}`)
        .then(response => response.json())
        .then(data => {
          branchSelect.innerHTML = '<option value="">All Branches</option>';
          data.forEach(branch => {
            const option = document.createElement('option');
            option.value = branch._id;
            option.textContent = branch.name;
            branchSelect.appendChild(option);
          });
        })
        .catch(error => console.error('Error loading branches:', error));
    } else {
      branchSelect.innerHTML = '<option value="">All Branches</option>';
    }
  });

  // Fetch the report data based on filters
  function fetchReportData() {
    const companyId = companySelect.value;
    const branchId = branchSelect.value;
    const transactionType = transactionTypeSelect.value;
    const startDate = startDateInput.value;
    const endDate = endDateInput.value;

    const query = new URLSearchParams({ companyId, branchId, transactionType, startDate, endDate }).toString();
    
    fetch(`/api/report?${query}`)
      .then(response => response.json())
      .then(data => {
        // Update the summary section
        totalSalesElem.textContent = data.totalSales.toFixed(2);
        totalPurchasesElem.textContent = data.totalPurchases.toFixed(2);
        totalProfitElem.textContent = data.totalProfit.toFixed(2);

        // Render transactions in the table
        transactionTableBody.innerHTML = ''; // Clear previous entries
        data.transactions.forEach(txn => {
          txn.items.forEach(item => {
            const row = document.createElement('tr');
            row.innerHTML = `
              <td>${txn._id}</td>
              <td>${new Date(txn.date).toLocaleDateString()}</td>
              <td>${txn.company.name}/${txn.branch.name}</td>
              <td>${txn.transactionType}</td>
              <td>$${txn.total.toFixed(2)}</td>
              <td>${txn.transactionType === 'selling' ? '$' + item.profit.toFixed(2) : 'N/A'}</td>
            `;
            transactionTableBody.appendChild(row);
          });
        });

        // Update charts
        updateCharts(data);
      })
      .catch(error => console.error('Error fetching report:', error));
  }

  // Update charts with Chart.js
  function updateCharts(data) {
    const ctx1 = document.getElementById('sales-vs-purchases-chart').getContext('2d');
    const ctx2 = document.getElementById('profit-margins-chart').getContext('2d');
    
    new Chart(ctx1, {
      type: 'bar',
      data: {
        labels: ['Total Sales', 'Total Purchases'],
        datasets: [{
          label: 'Transaction Values',
          data: [data.totalSales, data.totalPurchases],
          backgroundColor: ['#4caf50', '#f44336']
        }]
      }
    });

    new Chart(ctx2, {
      type: 'pie',
      data: {
        labels: data.transactions
          .filter(txn => txn.transactionType === 'selling')
          .map(txn => txn.items[0].name),
        datasets: [{
          label: 'Profit Margins',
          data: data.transactions
            .filter(txn => txn.transactionType === 'selling')
            .map(txn => txn.items.reduce((acc, item) => acc + item.profit, 0)),
          backgroundColor: ['#4caf50', '#f44336', '#2196f3', '#ff9800', '#9c27b0']
        }]
      }
    });
  }

  // Export to PDF using jsPDF
  document.getElementById('download-pdf-btn').addEventListener('click', function () {
    const { jsPDF } = window.jspdf;
    const doc = new jsPDF();
    doc.text('Transaction Report', 10, 10);

    // Add summary section
    doc.text(`Total Sales: $${totalSalesElem.textContent}`, 10, 20);
    doc.text(`Total Purchases: $${totalPurchasesElem.textContent}`, 10, 30);
    doc.text(`Total Profit: $${totalProfitElem.textContent}`, 10, 40);

    // Add transaction table data
    doc.autoTable({
      html: '#transaction-table',
      startY: 50
    });

    doc.save('transaction_report.pdf');
  });

  // Export to CSV using PapaParse
  document.getElementById('download-csv-btn').addEventListener('click', function () {
    const rows = Array.from(transactionTableBody.querySelectorAll('tr')).map(row => {
      const cells = row.querySelectorAll('td');
      return Array.from(cells).map(cell => cell.textContent);
    });

    const csv = Papa.unparse({
      fields: ['Transaction ID', 'Date', 'Company/Branch', 'Transaction Type', 'Total Value', 'Profit'],
      data: rows
    });

    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', 'transaction_report.csv');
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  });

  // Event listener for filter button
  document.getElementById('filter-btn').addEventListener('click', fetchReportData);

  // Initial fetch of report data on page load
  loadCompanies();
  fetchReportData();
// });
