//document.addEventListener('DOMContentLoaded', () => {
    const expenseGroupForm = document.getElementById('expenseGroupForm');
    const expenseGroupIdField = document.getElementById('expenseGroupId');
    const groupNameField = document.getElementById('groupName');
    const expenseGroupsTableBody = document.querySelector('#expenseGroupsTable tbody');

    // Get companyId from sessionStorage
    const companyId = sessionStorage.getItem('companyId');
    // if (!companyId) {
    //     alert('No companyId found in session. Please log in or set the companyId.');
    //     return;
    // }

    // Function to fetch and display expense groups
    async function fetchExpenseGroups() {
        try {
            const response = await fetch(`/api/expense-groups/company/${companyId}`);
            const expenseGroups = await response.json();
            
            expenseGroupsTableBody.innerHTML = ''; // Clear the table

            expenseGroups.forEach(expenseGroup => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${expenseGroup.groupName}</td>
                    <td>
                        <button class="edit" onclick="editExpenseGroup('${expenseGroup._id}')">Edit</button>
                        <button class="delete" onclick="deleteExpenseGroup('${expenseGroup._id}')">Delete</button>
                    </td>
                `;
                expenseGroupsTableBody.appendChild(row);
            });
        } catch (error) {
            console.error('Error fetching expense groups:', error);
        }
    }

    // Function to handle form submission
    expenseGroupForm.addEventListener('submit', async (e) => {
        e.preventDefault();

        const expenseGroupId = expenseGroupIdField.value;
        const groupName = groupNameField.value;

        const payload = { groupName, companyId }; // companyId is fetched from sessionStorage

        try {
            let response;
            if (expenseGroupId) {
                // Update expense group
                response = await fetch(`/api/expense-groups/${expenseGroupId}`, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(payload)
                });
            } else {
                // Create new expense group
                response = await fetch('/api/expense-groups', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(payload)
                });
            }

            const result = await response.json();
            alert(result.message);
            expenseGroupForm.reset(); // Clear the form
            fetchExpenseGroups(); // Refresh the table
        } catch (error) {
            console.error('Error submitting expense group:', error);
        }
    });

    // Function to populate the form for editing
    window.editExpenseGroup = async function (id) {
        try {
            const response = await fetch(`/api/expense-groups/${id}`);
            const expenseGroup = await response.json();

            groupNameField.value = expenseGroup.groupName;
            expenseGroupIdField.value = expenseGroup._id;
        } catch (error) {
            console.error('Error fetching expense group:', error);
        }
    };

    // Function to delete an expense group
    window.deleteExpenseGroup = async function (id) {
        if (confirm('Are you sure you want to delete this expense group?')) {
            try {
                const response = await fetch(`/api/expense-groups/${id}`, {
                    method: 'DELETE'
                });
                const result = await response.json();
                alert(result.message);
                fetchExpenseGroups(); // Refresh the table
            } catch (error) {
                console.error('Error deleting expense group:', error);
            }
        }
    };

    // Initial fetch to populate the table
    fetchExpenseGroups();
//});
