//document.addEventListener('DOMContentLoaded', function () {
    const expenseRowsContainer = document.getElementById('expense-rows');
    const saveAllBtn = document.getElementById('save-all-btn');
    const expenseDateInput = document.getElementById('expense-date'); 
    const searchExpensesBtn = document.getElementById('search-expenses-btn');
    const startDateInput = document.getElementById('start-date');
    const endDateInput = document.getElementById('end-date');
   
    const expenseDisplayTable = document.getElementById('expenses-display-rows');
  
    // Retrieve companyId and branchId from sessionStorage
    const companyId = sessionStorage.getItem('companyId');
    const branchId = sessionStorage.getItem('branchId');
let  expenses;
    // if (!companyId || !branchId) {
    //     alert('Company ID and Branch ID are required.');
    //     return;
    // }

    // Function to add a new expense row
    function addNewExpenseRow() {
        const newRow = document.createElement('tr');
        newRow.innerHTML = `
          <td><input type="number" class="expense-amount" placeholder="Enter amount" required></td>
          
            <td><input type="text" class="expense-description" placeholder="Enter description" required></td>
           
            <td>
                <button type="button" class="add-row-btn">+</button>
                <button type="button" class="delete-row-btn">-</button>
            </td>
        `;
        expenseRowsContainer.appendChild(newRow);

        newRow.querySelector('.add-row-btn').addEventListener('click', addNewExpenseRow);
        newRow.querySelector('.delete-row-btn').addEventListener('click', function () {
            deleteExpenseRow(newRow);
        });
    }

    function deleteExpenseRow(row) {
        if (expenseRowsContainer.children.length > 1) {
            row.remove();
        } else {
            alert('At least one expense row must remain.');
        }
    }

    document.querySelector('.add-row-btn').addEventListener('click', addNewExpenseRow);
    document.querySelector('.delete-row-btn').addEventListener('click', function () {
        deleteExpenseRow(document.querySelector('tr'));
    });

    // Handle Save All Expenses button click
    saveAllBtn.addEventListener('click', function () {
        const expenses = [];
        const rows = expenseRowsContainer.querySelectorAll('tr');
        const expenseDate = expenseDateInput.value; 

        if (!expenseDate) {
            alert('Please select a date for the expenses.');
            return;
        }

        rows.forEach(row => {
            const description = row.querySelector('.expense-description').value;
        
            const amount = row.querySelector('.expense-amount').value;

            if (description && amount) {
                expenses.push({
                    date: expenseDate,
                    description,
                   
                    amount,
                    companyId,  // Add companyId and branchId to each expense
                    branchId
                });
            }
        });

        if (expenses.length === 0) {
            alert('Please fill out at least one expense.');
            return;
        }

        fetch('/api/expenses/bulk', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ expenses })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Expenses saved successfully!');
                expenseRowsContainer.innerHTML = '';
                addNewExpenseRow(); 
                expenseDateInput.value = ''; 
            } else {
                alert('Failed to save expenses.');
            }
        })
        .catch(error => {
            console.error('Error saving expenses:', error);
        });
    });

    // Search expenses by date
    searchExpensesBtn.addEventListener('click', fetchExpenses);
    startDateInput.addEventListener("change", fetchExpenses);
    endDateInput.addEventListener("change", fetchExpenses);
    
   

    function fetchExpenses() {
        const startDate = startDateInput.value;
        const endDate = endDateInput.value;
    
        if (!startDate||!endDate) {
            alert('Please select a date.');
            return;
        }
    
        fetch(`/api/expenses/?startDate=${startDate}&endDate=${endDate}&companyId=${companyId}&branchId=${branchId}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    expenses=data.data;
                    displayExpenses(expenses);
                } else {
                    expenseDisplayTable.innerHTML = ''; 
                   // alert('No expenses found for this date.');
                }
            })
            .catch(error => {
                console.error('Error fetching expenses:', error);
            });
    }
    
    function displayExpenses(expenses) {
        expenseDisplayTable.innerHTML = ''; 

        // Calculate the total sum of expenses
        const totalExpense = expenses.reduce((sum, expense) => sum + expense.amount, 0);
        

const totalAmountElement = document.getElementById('totalAmount');

if (totalAmountElement) {
    totalAmountElement.textContent = totalExpense.toLocaleString();
}



        // Add a summary row at the top of the table
        const summaryRow = document.createElement('tr');
        summaryRow.innerHTML = '';
        expenseDisplayTable.appendChild(summaryRow);
           expenses.forEach(expense => {
            const row = document.createElement('tr');
            const formattedDate = new Date(expense.date).toLocaleDateString();
            row.innerHTML = ` 
                <td>${formattedDate}</td>
                <td>${expense.amount.toFixed(2)}</td>
                <td>${expense.description}</td>
                <td><button class="delete-btn" data-expense-id="${expense._id}">Delete</button></td>
            `;
            expenseDisplayTable.appendChild(row);
        });
        
    
        // Attach event listeners for delete buttons
        document.querySelectorAll('.delete-btn').forEach(button => {
            button.addEventListener('click', deleteExpense);
        });
    }
    
    function deleteExpense(event) {
        const expenseId = event.target.getAttribute('data-expense-id');
    
        if (confirm('Are you sure you want to delete this expense?')) {
            fetch(`/api/expenses/${expenseId}`, { method: 'DELETE' })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('Expense deleted successfully');
                        fetchExpenses(); // Refresh the expenses list
                    } else {
                        alert('Failed to delete expense');
                    }
                })
                .catch(error => {
                    console.error('Error deleting expense:', error);
                });
        }
    }
    






    const tabButtons = document.querySelectorAll('.tab-btn');
    const tabContents = document.querySelectorAll('.tab-content');

    // Function to handle tab switching
    tabButtons.forEach(button => {
        button.addEventListener('click', function() {
            // Remove the active class from all buttons
            tabButtons.forEach(btn => btn.classList.remove('active'));
            // Add the active class to the clicked button
            this.classList.add('active');

            // Hide all tab content sections
            tabContents.forEach(content => content.style.display = 'none');

            // Show the selected tab content
            const tabId = this.getAttribute('data-tab');
            document.getElementById(tabId).style.display = 'block';
        });
    });

    // Initialize to show the first tab content
    document.querySelector('.tab-btn.active').click();

    // Set the sales date to today by default
    const today = new Date().toISOString().split('T')[0];
    expenseDateInput.value = today;
    startDateInput.value = today;
    endDateInput.value = today;

    async function setDefaultDates() {
        try {
          const response = await fetch(`/api/settings?companyId=${companyId}&branchId=${branchId}`);
          const data = await response.json();
     
        
       
        } catch (error) {
          console.error('Error fetching default start date:', error);
        }
      }




      const searchExpensesInput = document.getElementById('search-expenses-input');

// Attach an event listener for local search
searchExpensesInput.addEventListener('input', function () {
    const searchTerm = searchExpensesInput.value.toLowerCase();
    const filteredExpenses = expenses.filter(expense => 
        expense.description.toLowerCase().includes(searchTerm) || 
        expense.amount.toString().includes(searchTerm) || 
        new Date(expense.date).toLocaleDateString().includes(searchTerm)
    );
   
    displayExpenses(filteredExpenses);
});




    fetchExpenses();
//});
