//document.addEventListener('DOMContentLoaded', () => {
    const branchGroupForm = document.getElementById('branchGroupForm');
    const branchGroupIdField = document.getElementById('branchGroupId');
    const groupNameField = document.getElementById('groupName');
    const branchGroupsTableBody = document.querySelector('#branchGroupsTable 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 branch groups
    async function fetchBranchGroups() {
        try {
            const response = await fetch(`/api/branch-groups/company/${companyId}`);
            const branchGroups = await response.json();
            
            branchGroupsTableBody.innerHTML = ''; // Clear the table

            branchGroups.forEach(branchGroup => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${branchGroup.groupName}</td>
                    <td>
                        <button class="edit" onclick="editBranchGroup('${branchGroup._id}')">Edit</button>
                        <button class="delete" onclick="deleteBranchGroup('${branchGroup._id}')">Delete</button>
                    </td>
                `;
                branchGroupsTableBody.appendChild(row);
            });
        } catch (error) {
            console.error('Error fetching branch groups:', error);
        }
    }

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

        const branchGroupId = branchGroupIdField.value;
        const groupName = groupNameField.value;

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

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

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

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

            groupNameField.value = branchGroup.groupName;
            branchGroupIdField.value = branchGroup._id;
        } catch (error) {
            console.error('Error fetching branch group:', error);
        }
    };

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

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