//document.addEventListener('DOMContentLoaded', function() {
    // Fetch companyId and branchId from sessionStorage
    const companyId = sessionStorage.getItem('companyId');
    const branchId = sessionStorage.getItem('branchId');

    // if (!companyId || !branchId) {
    //   alert('Company or Branch not set in session.');
    //   return;
    // }

    // Fetch financial summary based on companyId, branchId, and date range
    function loadFinancialSummary(startDate, endDate) {
      const tableWrapper = document.getElementById('table-wrapper');
      const loadingDiv = document.getElementById('loadingDiv');
      tableWrapper.style.display='none';
      loadingDiv.style.display='block';
     
      const url = `/api/all-total-summary/fSummary?companyId=${companyId}&branchId=${branchId}&startDate=${startDate}&endDate=${endDate}`;
      fetch(url)
        .then(response => response.json())
        .then(data => {
          const tableBody = document.getElementById('financialSummaryTable').getElementsByTagName('tbody')[0];
          tableBody.innerHTML = ''; // Clear previous rows
              if (data.length) {
            data.forEach(summary => {
              const row = document.createElement('tr');
              row.innerHTML = `

                <td >${new Date(summary.createdAt).toISOString().split('T')[0]}</td>
  
              <td>${Number((Number(summary.totalSales) || 0).toFixed(0)).toLocaleString('en-US')}</td>
              <td>${Number((Number(summary.toDaySale) || 0).toFixed(0)).toLocaleString('en-US')}</td>
              <td>${Number((Number(summary.totalPurchases) || 0).toFixed(0)).toLocaleString('en-US')}</td>
              <td>${Number((Number(summary.totalExpense) || 0).toFixed(0)).toLocaleString('en-US')}</td>
              <td>${Number((Number(summary.storeWithdrawal) || 0).toFixed(0)).toLocaleString('en-US')}</td>
              <td>${Number((Number(summary.storeWithdrawalForSelling) || 0).toFixed(0)).toLocaleString('en-US')}</td>
              <td>${Number((Number(summary.dailyNetProfitUsingSystem) || 0).toFixed(0)).toLocaleString('en-US')}</td>
              <td>${Number((Number(summary.dailyNetProfitUsingCashier) || 0).toFixed(0)).toLocaleString('en-US')}</td>
              <td>${Number((Number(summary.orderAdvance) || 0).toFixed(0)).toLocaleString('en-US')}</td>
              <td>${Number((Number(summary.orderRemaining) || 0).toFixed(0)).toLocaleString('en-US')}</td>
              <td>${Number((Number(summary.stockValue) || 0).toFixed(0)).toLocaleString('en-US')}</td>
              <td>${Number((Number(summary.bankDeposit) || 0).toFixed(0)).toLocaleString('en-US')}</td>
              <td>${Number((Number(summary.bankWithdraw) || 0).toFixed(0)).toLocaleString('en-US')}</td>
            `;
            
            
            
            
              tableBody.appendChild(row);
            });

//after fetching hide some columns
            toggleColumns() ;


         tableWrapper.style.display='block';
            loadingDiv.style.display='none';
          } else {
           
            
            const row = document.createElement('tr');
            row.innerHTML = '<td colspan="7">No financial summary data found.</td>';
            tableBody.appendChild(row);
            tableWrapper.style.display='block';
            loadingDiv.style.display='none';
          }
        })
        .catch(error => console.error('Error fetching financial summary:', error));
    }

    // Automatically load the financial summary when date fields are changed
    document.getElementById('startDate').addEventListener('change', () => {
      const startDate = document.getElementById('startDate').value;
      const endDate = document.getElementById('endDate').value;
      if (startDate && endDate) {
        loadFinancialSummary(startDate, endDate);
      }
    });

    document.getElementById('endDate').addEventListener('change', () => {
      const startDate = document.getElementById('startDate').value;
      const endDate = document.getElementById('endDate').value;
      if (startDate && endDate) {
        loadFinancialSummary(startDate, endDate);
      }
    });

    // Get today's date
    function getToday() {
      const today = new Date();
      return today.toISOString().split('T')[0];  // Return date in YYYY-MM-DD format
    }

    // Get date for last N days
    function getLastNDays(n) {
      const date = new Date();
      date.setDate(date.getDate() - n);
      return date.toISOString().split('T')[0];  // Return date in YYYY-MM-DD format
    }

    // Event listener for 'Today' button
    document.getElementById('todayButton').addEventListener('click', () => {
      const today = getToday();
      loadFinancialSummary(today, today);
    });

    // Event listener for 'Last 7 Days' button
    document.getElementById('last7DaysButton').addEventListener('click', () => {
      const today = getToday();
      const last7Days = getLastNDays(7);
      loadFinancialSummary(last7Days, today);
    });

    // Event listener for 'Last 30 Days' button
    document.getElementById('last30DaysButton').addEventListener('click', () => {
      const today = getToday();
      const last30Days = getLastNDays(30);
      loadFinancialSummary(last30Days, today);
    });

    // Call the function to load the summary initially with default 7 day
    const today = getToday();
    const last7Days = getLastNDays(7);
    document.getElementById('startDate').value=last7Days;
    document.getElementById('endDate').value=today;
    loadFinancialSummary( last7Days,today); // Default to empty dates (optional)
 // });
// toggleColumns();

 function toggleColumns() {

  const rows = document.querySelectorAll('#financialSummaryTable tr');
      
      rows.forEach(row => {
       // const c1 = row.children[1]; // Profit-S
       // const c6 = row.children[6]; //
       
         const c3 = row.children[3]; //purchase
        const c7 = row.children[7];  
        const c8 = row.children[8]; // Advance
        const c9 = row.children[9]; // Order
        const c10 = row.children[10]; // Stock Value
        const c11 = row.children[11]; // 
        const c12 = row.children[12]; // Expense
        const c13 = row.children[13]; // Expense
          // Toggle the hidden class
       //   c1.classList.toggle('hidden');
       //   c6.classList.toggle('hidden');
       c3.classList.toggle('hidden');
          c7.classList.toggle('hidden');
          c8.classList.toggle('hidden');
          c9.classList.toggle('hidden');
          c10.classList.toggle('hidden');
          c11.classList.toggle('hidden');
          c12.classList.toggle('hidden');
          c13.classList.toggle('hidden');

      });


  }

  const showModalBtn = document.getElementById('show-modal');
const modal = document.getElementById('common-modal');
 const closeBtn = document.getElementById('close-btn');

// Show the modal when the button is clicked
showModalBtn.addEventListener('click', function () {
 
  modal.style.display = 'flex'; // Change display from none to flex to show modal
});


closeBtn.addEventListener('click', function () {
 
  modal.style.display = 'none'; // Change display from none to flex to show modal
});
//
// 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
  }
});