document.addEventListener('DOMContentLoaded', function () {
    const cashOutRowsContainer = document.getElementById('cash-out-rows');
    const saveAllBtn = document.getElementById('save-all-btn');
    const cashOutDateInput = document.getElementById('cash-out-date');
  
    const searchDateInput = document.getElementById('search-date');
    const cashOutDisplayTable = document.getElementById('cash-outs-display-rows');
    

    const companyId = sessionStorage.getItem('companyId');
    const branchId = sessionStorage.getItem('branchId');

    function addNewCashOutRow() {
        const newRow = document.createElement('tr');
        newRow.innerHTML = `
          <td><input type="number" class="cash-out-amount" placeholder="Enter amount" required></td>
          
            <td><input type="text" class="cash-out-description" placeholder="Enter description" required></td>
             <td>
                <button type="button" class="add-row-btn">+</button>
                <button type="button" class="delete-row-btn">-</button>
            </td>
        `;
        cashOutRowsContainer.appendChild(newRow);

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

    function deleteCashOutRow(row) {
        if (cashOutRowsContainer.children.length > 1) {
            row.remove();
        } else {
            alert('At least one cash out row must remain.');
        }
    }

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

    saveAllBtn.addEventListener('click', function () {
        const cashOuts = [];
        const rows = cashOutRowsContainer.querySelectorAll('tr');
        const cashOutDate = cashOutDateInput.value;

        if (!cashOutDate) {
            alert('Please select a date for the cash outs.');
            return;
        }

        rows.forEach(row => {
            const description = row.querySelector('.cash-out-description').value;
            const amount = row.querySelector('.cash-out-amount').value;
           
            if (description && amount) {
                cashOuts.push({
                    date: cashOutDate,
                    description,
                    amount: parseFloat(amount), // Parse amount as a number
                 
                    companyId,
                    branchId
                });
            }
        });

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

        fetch('/api/cashouts/bulk', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ cashOuts })
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Cash Outs saved successfully!');
                    cashOutRowsContainer.innerHTML = '';
                    addNewCashOutRow();
                    fetchCashOuts();//refresh table after save
                } else {
                    alert(data.message || 'Failed to save cash outs.'); // Display server error message
                }
            })
            .catch(error => {
                console.error('Error saving cash outs:', error);
                alert('An error occurred while saving cash outs.'); // General error message for the user
            });
    });

    searchDateInput.addEventListener("change", fetchCashOuts);

    function fetchCashOuts() {
        const searchDate = searchDateInput.value;

        if (!searchDate) {
            alert('Please select a date.');
            return;
        }

        fetch(`/api/cashouts/${searchDate}?companyId=${companyId}&branchId=${branchId}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    displayCashOuts(data.data, searchDate);
                } else {
                    cashOutDisplayTable.innerHTML = '';
                  
                    //alert(data.message || 'No cash outs found for this date.'); //optional message
                }
            })
            .catch(error => {
                console.error('Error fetching cash outs:', error);
                alert('An error occurred while fetching cash outs.');
            });
    }

    function displayCashOuts(cashOuts, date) {
        cashOutDisplayTable.innerHTML = '';
      

        cashOuts.forEach(cashOut => {
            const row = document.createElement('tr');
            row.innerHTML = `
               <td>${cashOut.amount}</td>
                <td>${cashOut.description}</td>
             
              
                <td><button class="delete-btn" data-cash-out-id="${cashOut._id}">Delete</button></td>
            `;
            cashOutDisplayTable.appendChild(row);
        });

        document.querySelectorAll('.delete-btn').forEach(button => {
            button.addEventListener('click', deleteCashOut);
        });
    }

    function deleteCashOut(event) {
        const cashOutId = event.target.getAttribute('data-cash-out-id');

        if (confirm('Are you sure you want to delete this cash out?')) {
            fetch(`/api/cashouts/${cashOutId}`, { method: 'DELETE' })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('Cash out deleted successfully');
                        fetchCashOuts(); // Refresh the cash outs list
                    } else {
                        alert(data.message || 'Failed to delete cash out'); // Display server error message
                    }
                })
                .catch(error => {
                    console.error('Error deleting cash out:', error);
                    alert('An error occurred while deleting the cash out.');
                });
        }
    }

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

    tabButtons.forEach(button => {
        button.addEventListener('click', function () {
            tabButtons.forEach(btn => btn.classList.remove('active'));
            this.classList.add('active');

            tabContents.forEach(content => content.style.display = 'none');

            const tabId = this.getAttribute('data-tab');
            document.getElementById(tabId).style.display = 'block';
        });
    });

    document.querySelector('.tab-btn.active').click();

    const today = new Date().toISOString().split('T')[0];
    cashOutDateInput.value = today;
    searchDateInput.value = today;
    fetchCashOuts();
  
});