const startDateInput = document.getElementById('startDate');
const endDateInput = document.getElementById('endDate');
const startDateInput2 = document.getElementById('startDate2');
const endDateInput2 = document.getElementById('endDate2');
const branchGroupSelect = document.getElementById('branchGroup');
const companyId = sessionStorage.getItem('companyId');
const branchId = sessionStorage.getItem('branchId');

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

// Function to fetch and set the default start date


const tableWrapper = document.getElementById('table-wrapper');
const loadingDiv = document.getElementById('loadingDiv');
tableWrapper.style.display='none';
loadingDiv.style.display='none';



async function setDefaultDates() {
  try {
    const response = await fetch(`/api/settings?companyId=${companyId}&branchId=${branchId}`);
    const data = await response.json();

    // Set default start date or fallback to today
    startDateInput.value = data.defaultStartDate ? data.defaultStartDate.split('T')[0] : getToday();
    endDateInput.value = getToday(); // Set end date to today's date
    const startDate = startDateInput.value; // Capture start date if already set
    const endDate = endDateInput.value;
   // loadingDiv.style.display='none';
     // fetchFinancialSummary(startDate, endDate);
  
 
  } catch (error) {
    console.error('Error fetching default start date:', error);
  }
}

// Utility functions for setting date ranges
function getToday() {
  return new Date().toISOString().split('T')[0];
}
function getLastWeek() {
  const date = new Date();
  date.setDate(date.getDate() - 7);
  return date.toISOString().split('T')[0];
}
function getLastMonth() {
  const date = new Date();
  date.setMonth(date.getMonth() - 1);
  return date.toISOString().split('T')[0];
}

// Load branch groups for the selected company
function loadBranchGroups() {
    
  fetch(`/api/branch-groups/company/${companyId}`)
    .then(response => response.json())
    .then(groups => {
      
     
      groups.forEach(group => {
        const option = document.createElement('option');
        option.value = group._id;
        option.textContent = group.groupName;
        branchGroupSelect.appendChild(option);
      });

    
      const lastWeek = getLastWeek();
      const today = getToday();
      startDateInput.value = lastWeek;
      endDateInput.value = today;
      setDefaultDates();



    })
    .catch(error => console.error('Error loading branch groups:', error));
}





function runSummary(startDate, endDate) {

  if ((new Date(endDate) - new Date(startDate)) / (1000 * 60 * 60 * 24) > 3) {
    alert("The date interval shall not be greater than 3 days");
    return 0;
  }
  

  const url = `/api/financial-summary/interval?companyId=${companyId}&startDate=${startDate}&endDate=${endDate}`;
  

  tableWrapper.style.display='none';
  loadingDiv.style.display='block';
 

  fetch(url)
    .then(response => response.json())
    .then(data => {
    
   

     // alert(data.message);


  tableWrapper.style.display='block';
  loadingDiv.style.display='none';

  fetchFinancialSummary(startDate, endDate);


    }

    )    };


// Fetch and render financial summary based on filters
async function fetchFinancialSummary(startDate, endDate) {
  const branchGroup =  await branchGroupSelect.value;
  const url = `/api/financial-summary/merged?companyId=${companyId}&startDate=${startDate}&endDate=${endDate}&groupId=${branchGroup}`;
  

  tableWrapper.style.display='none';
  loadingDiv.style.display='block';
 

  fetch(url)
    .then(response => response.json())
    .then(data => {
      const tableBody = document.getElementById('financialSummaryTable').querySelector('tbody');
      tableBody.innerHTML = '';
      
      if (data.length > 0) {

console.log(data);

// Initialize sums
let totalSaleS = 0;
let totalSaleC = 0;
let totalDeductedStock = 0;
let totalExpenses = 0;
let totalProfitS = 0;
let totalProfitC = 0;
let totalPurchases = 0;

// Loop through data and append rows
data.forEach(item => {
  totalSaleS += item.totalSales;
  totalSaleC += item.toDaySale;
  totalDeductedStock += item.totalStoreWithdrawal;
  totalExpenses += item.totalExpense;
  totalProfitS += item.dailyNetProfitUsingSystem;
  totalProfitC += item.dailyNetProfitUsingCashier;
  totalPurchases += item.totalPurchases;

  const row = document.createElement('tr');
  row.innerHTML = `
    <td class="column-date">${new Date(item.createdAt).toISOString().split('T')[0]}</td>
     
    <td class="column-sale-s">${Math.round(item.totalSales).toLocaleString()}</td>
    <td class="column-sale-c">${Math.round(item.toDaySale).toLocaleString()}</td>
    <td class="column-deducted-stock">${Math.round(item.totalStoreWithdrawal).toLocaleString()}</td>
    <td class="column-total-expenses">${Math.round(item.totalExpense).toLocaleString()}</td>
    <td class="column-profit-s">${Math.round(item.dailyNetProfitUsingSystem).toLocaleString()}</td>
    <td class="column-profit-c">${Math.round(item.dailyNetProfitUsingCashier).toLocaleString()}</td>
    <td class="column-purchases">${Math.round(item.totalPurchases).toLocaleString()}</td>
    <td class="column-bank-deposit">${Math.round(item.bankDeposit).toLocaleString()}</td>
    <td class="column-bank-withdraw">${Math.round(item.bankWithdraw).toLocaleString()}</td>
    <td class="column-stock-value">${Math.round(item.stockValue).toLocaleString()}</td>
  `;
  tableBody.appendChild(row);
});

// Append a summary row at the end
const summaryRow = document.createElement('tr');
 
summaryRow.classList.add('summary-row'); // Add the CSS class

summaryRow.innerHTML = `
  <td class="column-date"><strong>Total</strong></td>
  <td class="column-sale-s">${formatNumber(totalSaleS)}</td>
  <td class="column-sale-c">${formatNumber(totalSaleC)}</td>
  <td class="column-deducted-stock">${formatNumber(totalDeductedStock)}</td>
  <td class="column-total-expenses">${formatNumber(totalExpenses)}</td>
  <td class="column-profit-s">${formatNumber(totalProfitS)}</td>
  <td class="column-profit-c">${formatNumber(totalProfitC)}</td>
  <td class="column-purchases">${formatNumber(totalPurchases)}</td>
  <td class="column-bank-deposit">${formatNumber(0)}</td> 
  <td class="column-bank-withdraw">${formatNumber(0)}</td> 
  <td class="column-stock-value">-</td> 
`;

// Helper function for robust number formatting
function formatNumber(value) {
  if (isNaN(value) || value === null || value === undefined) {
    return '-'; // Handle NaN, null, and undefined values
  }
  return Math.round(value).toLocaleString(); 
}

// Append the summary row to the table
tableBody.appendChild(summaryRow);




      } else {
        
        const noDataRow = document.createElement('tr');
        noDataRow.innerHTML = '<td colspan="9">No financial summary data available for the selected period.</td>';
        tableBody.appendChild(noDataRow);
      }
     
      setColumnVisibility('basic');
      tableWrapper.style.display='block';
      loadingDiv.style.display='none';
    })
    .catch(error => {
      
      console.error('Error fetching financial summary:', error);
      
      // Create an error row
      const errorRow = document.createElement('tr');
      errorRow.innerHTML = '<td colspan="9" style="color: red; text-align: center;">Error fetching financial summary</td>';
      
      // Append the error row to the table body
      tableBody.appendChild(errorRow);
    });
  }    


// Event Listeners for Filter Buttons
document.getElementById('dailyButton').addEventListener('click', () => {
  const today = getToday();
  startDateInput.value = today;
  endDateInput.value = today;
  fetchFinancialSummary(today, today);
  
});

document.getElementById('weeklyButton').addEventListener('click', () => {
  const lastWeek = getLastWeek();
  const today = getToday();
  startDateInput.value = lastWeek;
  endDateInput.value = today;
  fetchFinancialSummary(lastWeek, today);
 
});

document.getElementById('monthlyButton').addEventListener('click', () => {
  const lastMonth = getLastMonth();
  const today = getToday();
  startDateInput.value = lastMonth;
  endDateInput.value = today;
   fetchFinancialSummary(lastMonth, today);
  
});



document.getElementById('summaryButton').addEventListener('click', () => {
  
  // const startDate2 = startDateInput2.value;
  //   const endDate2 = endDateInput2.value; // Capture end date if already set
  
    const modal = document.getElementById("runSummaryModal");
    modal.style.display = "block";


 
 
});


// const closeRunSummaryModalBtn = document.getElementById("closeRunSummaryModal");
// closeRunSummaryModalBtn.addEventListener("click", closeRunSummaryModal);

// function closeRunSummaryModal() {
//   const modal = document.getElementById("runSummaryModal");
//   modal.style.display = "none";
// }


  
// startDateInput2.addEventListener('change', () => {
//   const startDate2 = startDateInput2.value;
//   const endDate2 = endDateInput2.value; // Capture end date if already set
//   if (startDate2) {
//     runSummary(startDate2, endDate2);
//   }
// });

// endDateInput2.addEventListener('change', () => {
//   const startDate2 = startDateInput2.value; // Capture start date if already set
//   const endDate2 = endDateInput2.value;
//   if (endDate2) {
//     runSummary(startDate2, endDate2);
//   }
// });

processSummary.addEventListener('click', () => {
  const startDate2 = startDateInput2.value; // Capture start date if already set
  const endDate2 = endDateInput2.value;
 // if (endDate2) {
    runSummary(startDate2, endDate2);
    const modal = document.getElementById("runSummaryModal");
    modal.style.display = "none";
 // }
});





  // Event listeners for date changes
  startDateInput.addEventListener('change', () => {
    const startDate = startDateInput.value;
    const endDate = endDateInput.value; // Capture end date if already set
    if (startDate) {
      fetchFinancialSummary(startDate, endDate);
    }
  });

  endDateInput.addEventListener('change', () => {
    const startDate = startDateInput.value; // Capture start date if already set
    const endDate = endDateInput.value;
    if (endDate) {
      fetchFinancialSummary(startDate, endDate);
    }
  });


// Fetch data whenever branchGroup selection changes
branchGroupSelect.addEventListener('change', () => {
  const startDate = startDateInput.value || getToday();
  const endDate = endDateInput.value || getToday();
  fetchFinancialSummary(startDate, endDate);
});








document.querySelectorAll('.dropdown-content input[type="checkbox"]').forEach(checkbox => {
    checkbox.addEventListener('change', (event) => {
      const columnClass = `column-${event.target.getAttribute('data-column')}`;
      const isChecked = event.target.checked;
      
      document.querySelectorAll(`.${columnClass}`).forEach(cell => {
        cell.classList.toggle('hidden-column', !isChecked);
      });
    });
  });
  


  const columnsConfig = {
    basic: ['column-date',
     
      'column-sale-c',
      'column-deducted-stock',
      'column-total-expenses',
      'column-profit-c',
    ],
    medium: [
        'column-date',
        'column-sale-s',
        'column-sale-c',
        'column-deducted-stock',
        'column-total-expenses',
        'column-profit-s',
         'column-profit-c'
    ],
    all: [
        'column-date',
      'column-stock-value',
      'column-sale-s',
      'column-sale-c',
      'column-purchases',
      'column-deducted-stock',
      'column-total-expenses',
      'column-bank-deposit',
      'column-bank-withdraw',
      'column-profit-s',
      'column-profit-c'
    ]
  };
  
  // Function to set the visibility of columns
  function setColumnVisibility(mode) {
    // Hide all columns initially
    document.querySelectorAll('th, td').forEach(cell => {
      cell.classList.add('hidden-column');
    });
    
    // Show columns for the selected mode
    columnsConfig[mode].forEach(columnClass => {
      document.querySelectorAll(`.${columnClass}`).forEach(cell => {
        cell.classList.remove('hidden-column');
      });
    });
  }
  
  // Event listener for mode selection
  document.querySelectorAll('input[name="viewMode"]').forEach(radio => {
  
    radio.addEventListener('change', (event) => {
      setColumnVisibility(event.target.value);
    });
  });
  
  // Initialize with the "basic" view
  setColumnVisibility('basic');
  


// Initial Load: Set default dates and load branch groups
loadBranchGroups();

// set default day for today for run summary modal
startDateInput2.value =getToday();
endDateInput2.value=getToday();

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
  }
});