//document.addEventListener('DOMContentLoaded', () => {
    const bankAccountForm = document.getElementById('bankAccountForm');
 
    const accountIdField = document.getElementById('accountId');
    const accountNumberField = document.getElementById('accountNumber');
    const bankNameField = document.getElementById('bankName');
    const accountHolderField = document.getElementById('accountHolderName');
    const balanceField = document.getElementById('balance');
    const bankAccountTable = document.getElementById('bankAccountTable').getElementsByTagName('tbody')[0];

    let bankAccounts = [];
    let companies = [];
    let branches = [];

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


    // Load bank accounts and display them in the list
    function loadBankAccounts() {
        fetch(`/api/bankAccounts?companyId=${companyId}`)
            .then(response => response.json())
            .then(data => {
                bankAccounts = data;
                console.log("data is",data);
                bankAccountTable.innerHTML = ''; // Clear existing list
              
                if(data.length<=0){

                    alert("No data Found",data.length);
                    return 0;
                }
                bankAccounts.forEach(account => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${account.accountNumber}</td>
                        <td>${account.bankName}</td>
                        <td>${account.accountHolderName}</td>
                          <td>${account.balance}</td>
                        <td>
                            <button class="edit-btn" data-id="${account._id}">Edit</button>
                            <button class="delete-btn" data-id="${account._id}">Delete</button>
                        </td>
                    `;
                    bankAccountTable.appendChild(row);
                });

                // Add event listeners to edit and delete buttons
                
                document.querySelectorAll('.edit-btn').forEach(button => {
                    button.addEventListener('click', editBankAccount);
                });
                document.querySelectorAll('.delete-btn').forEach(button => {
                    button.addEventListener('click', deleteBankAccount);
                });
            })
            .catch(error => console.error('Error loading bank accounts:', error));
    }

    // Submit the form to create or update a bank account
    bankAccountForm.addEventListener('submit', (e) => {
        e.preventDefault();

        const bankAccountData = {
            accountNumber: accountNumberField.value,
            bankName: bankNameField.value,
            accountHolderName: accountHolderField.value,
            branchId,
            companyId,
            balance: balanceField.value
        };

        const accountId = accountIdField.value;
        const method = accountId ? 'PUT' : 'POST';
        const url = accountId ? `/api/bankAccounts/${accountId}` : '/api/bankAccounts';

        fetch(url, {
            method: method,
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(bankAccountData)
        })
            .then(response => response.json())
            .then(() => {
                bankAccountForm.reset();
                alert("successfully saved");
                accountIdField.value = '';  // Clear hidden field after submission
                loadBankAccounts();  // Reload bank accounts after saving
            })
            .catch(error => console.error('Error saving bank account:', error));
    });

    // Edit bank account (load data into form)
    function editBankAccount(event) {
        const accountId = event.target.getAttribute('data-id');
        const account = bankAccounts.find(account => account._id === accountId);

        accountIdField.value = account._id;
        accountNumberField.value = account.accountNumber;
        bankNameField.value = account.bankName;
        accountHolderField.value = account.accountHolderName;
      
        balanceField.value = account.balance;

     
    }

    // Delete bank account
    function deleteBankAccount(event) {
        const accountId = event.target.getAttribute('data-id');
        if (confirm('Are you sure you want to delete this bank account?')) {
            fetch(`/api/bankAccounts/${accountId}`, {
                method: 'DELETE'
            })
                .then(() => loadBankAccounts())  // Reload bank accounts after deletion
                .catch(error => console.error('Error deleting bank account:', error));
        }
    }

  
    loadBankAccounts();
//});
