const companyId = sessionStorage.getItem('companyId');  // Assuming you are using sessionStorage for companyId
const branchId = sessionStorage.getItem('branchId');    // Assuming you are using sessionStorage for branchId
const form = document.getElementById('expenseForm');
const messageDiv = document.getElementById('message');
const expenseTableBody = document.getElementById('expenseTableBody');

// Function to load existing monthly expense for editing
function loadMonthlyExpense() {
  fetch(`/api/monthly-expenses?companyId=${companyId}&branchId=${branchId}`)
    .then(response => response.json())
    .then(data => {
      if (data) {
        document.getElementById('rent').value = data.rent || 0;
        document.getElementById('salaries').value = data.salaries || 0;
        document.getElementById('utilities').value = data.utilities || 0;
        document.getElementById('tax').value = data.tax || 0;
        document.getElementById('otherExpenses').value = data.otherExpenses || 0;
      } else {
        alert('No data found.');
      }
    })
    .catch(error => {
      console.error('Error loading monthly expense:', error);
      messageDiv.textContent = 'Error loading monthly expense.';
    });
}

// Function to load and display all expenses for the company
function loadAllExpenses() {
  fetch(`/api/monthly-expenses/all?companyId=${companyId}`)
    .then(response => response.json())
    .then(expenses => {
      expenseTableBody.innerHTML = ''; // Clear previous rows
      expenses.forEach(expense => {
        const row = document.createElement('tr');
        const total = expense.rent + expense.salaries + expense.utilities + expense.tax + expense.otherExpenses;
        row.innerHTML = `
          <td>${expense.rent}</td>
          <td>${expense.salaries}</td>
          <td>${expense.utilities}</td>
          <td>${expense.tax}</td>
          <td>${expense.otherExpenses}</td>
          <td>${total.toFixed(2)}</td>
        
        `;
        expenseTableBody.appendChild(row);
      });
    })
    .catch(error => console.error('Error loading all expenses:', error));
}

// Event listener for form submission
form.addEventListener('submit', function(e) {
  e.preventDefault();

  const rent = parseFloat(document.getElementById('rent').value);
  const salaries = parseFloat(document.getElementById('salaries').value);
  const utilities = parseFloat(document.getElementById('utilities').value);
  const tax = parseFloat(document.getElementById('tax').value);
  const otherExpenses = parseFloat(document.getElementById('otherExpenses').value);

  const expenseData = {
    companyId,
    branchId,
    rent,
    salaries,
    utilities,
    tax,
    otherExpenses
  };

  // Save or update the expense
  fetch('/api/monthly-expenses', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(expenseData)
  })
  .then(response => response.json())
  .then(data => {
    messageDiv.textContent = 'Monthly expense saved successfully!';
    loadAllExpenses();  // Reload all expenses after saving
  })
  .catch(error => {
    console.error('Error saving monthly expense:', error);
    messageDiv.textContent = 'Error saving monthly expense.';
  });
});

// Load existing monthly expense on page load
loadMonthlyExpense();
loadAllExpenses(); // Load all expenses initially
