//document.addEventListener('DOMContentLoaded', () => {
    const transactionForm = document.getElementById('transactionForm');
    const bankAccountSelect = document.getElementById('bankAccountSelect');
    const currentBalance = document.getElementById('currentBalance');
    const transactionType = document.getElementById('transactionType');
    const amountField = document.getElementById('amount');
    const transactionTable = document.getElementById('transactionTable').getElementsByTagName('tbody')[0];

    // Get companyId from sessionStorage
    const companyId = sessionStorage.getItem('companyId');
    const branchId = sessionStorage.getItem('branchId');

    // Load bank accounts into the dropdown based on companyId
    function loadBankAccounts() {
        if (!companyId) {
            console.error('Company ID not found in session');
            return;
        }

        fetch(`/api/bankAccounts?companyId=${companyId}`)  // Add companyId as a query parameter
            .then(response => response.json())
            .then(data => {
                data.forEach(account => {
                    const option = document.createElement('option');
                    option.value = account._id;
                    option.textContent = `${account.bankName} - ${account.accountNumber}`;
                    bankAccountSelect.appendChild(option);
                });
            })
            .catch(error => console.error('Error loading bank accounts:', error));
    }

    // Load transactions from the database based on companyId and branchId
    function loadTransactions() {
        fetch(`/api/bank-transactions?companyId=${companyId}`)
            .then(response => response.json())
            .then(transactions => {
                transactions.forEach(transaction => {
                    updateTransactionTable(transaction); // Populate table for each transaction
                });
            })
            .catch(error => console.error('Error loading transactions:', error));
    }

    // Update balance when bank account changes
    bankAccountSelect.addEventListener('change', () => {
        const accountId = bankAccountSelect.value;
        if (accountId) {
            fetch(`/api/bankAccounts/${accountId}`)
                .then(response => response.json())
                .then(account => {
                    currentBalance.value = account.balance.toFixed(2);
                })
                .catch(error => console.error('Error loading balance:', error));
        } else {
            currentBalance.value = ''; // Clear balance if no account is selected
        }
    });

    // Submit transaction form
    transactionForm.addEventListener('submit', (e) => {
        e.preventDefault();
        const accountId = bankAccountSelect.value;
        const type = transactionType.value;
        const amount = parseFloat(amountField.value);

        if (!accountId || !type || !amount) {
            alert('Please fill in all fields');
            return;
        }

        const transactionData = {
            bankAccountId: accountId,
            transactionType: type,
            amount,
            branchId,
            companyId,
        };

        fetch('/api/bank-transactions', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(transactionData)
        })
            .then(response => response.json())
            .then(responseData => {
                const { message, data: transaction } = responseData;
        
                // Display the success message or update UI as needed
                alert(message);
                updateTransactionTable(transaction);  // Add the new transaction to the table
                currentBalance.value = transaction.balance.toFixed(2);  // Update the balance
                transactionForm.reset();  // Reset the form
            })
            .catch(error => console.error('Error saving transaction:', error));
    });

    // Update the transaction table with a new transaction
    function updateTransactionTable(transaction) {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${transaction.transactionType}</td>
            <td>${transaction.amount.toFixed(2)}</td>
            <td>${transaction.balance.toFixed(2)}</td>
            <td>${new Date(transaction.createdAt).toLocaleDateString()}</td>
        `;
        transactionTable.appendChild(row);
    }







      // Function to switch between tabs
      function openTab(event, tabId) {
        // Hide all tab content
        const tabContents = document.querySelectorAll('.tab-content');
        tabContents.forEach(content => content.style.display = 'none');
  
        // Remove active class from all buttons
        const tabButtons = document.querySelectorAll('.tab-button');
        tabButtons.forEach(button => button.classList.remove('active'));
  
        // Show the selected tab and set the button as active
        document.getElementById(tabId).style.display = 'block';
        event.currentTarget.classList.add('active');
      }

    // Initialize by loading bank accounts and transactions based on companyId and branchId
    loadBankAccounts();
    loadTransactions();  // Load and display transactions when the page loads
//});
