document.addEventListener('DOMContentLoaded', async function() {
    let ip = '';
    await window.electronAPI.readFile('ipConfig.json')
        .then(result => {
            const jsonData = JSON.parse(result.content);
            ip = jsonData.ip;
        })

    const result = await window.electronAPI.readFile('loginData.json');
    const loginData = JSON.parse(result.content);
    const password = loginData.password;
    const ceoId = loginData.id;

    const loadUsers = (async () => {
        const url = `http://${ip}/users`;

        try {
            const response = await fetch(url, {
                method: 'GET',
                headers: {
                    'x-api-key': 'uc_api'
                }
            });
            if (response.ok) {
                let users = await response.json();
                users = users.data;
                const formContent = document.querySelector('.signup-form-content');
                formContent.innerHTML = '';

                users.forEach(user => {
                    if(user.id !== ceoId) {
                        const label = document.createElement('label');
                        const radioInput = document.createElement('input');
                        radioInput.type = 'radio';
                        radioInput.name = 'dept';
                        radioInput.value = user.id; // Set user ID as value
                        label.appendChild(radioInput);
                        label.appendChild(document.createTextNode(user.name)); // User's name for display
                        formContent.appendChild(label);
                    }
                });
            } else {
                console.error('Failed to fetch users:', response.status);
            }
        } catch (error) {
            console.error('Error making the request:', error);
        }
    });

    await loadUsers();

    const deleteButton = document.querySelector('button[name="delete"]');
    deleteButton.addEventListener('click', async function(event) {
        event.preventDefault(); // Prevent the default form submission
        const selectedUser = document.querySelector('input[type="radio"][name="dept"]:checked');

        if (!selectedUser) {
            await window.electronAPI.showAlert('Please select a user to delete.')
                .then(() => console.log('Alert window opened'))
                .catch(error => console.error('Error showing alert:', error));
            return;
        }

        const userId = selectedUser.value;
        const deleteUrl = `http://${ip}/ceo/users/${userId}`;

        try {
            const response = await fetch(deleteUrl, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                    'x-api-key': 'uc_api',
                    'ceo_password': password
                }
            });
            const data = await response.json();

            await window.electronAPI.showAlert(data.message)
                .then(() => console.log('Alert window opened'))
                .catch(error => console.error('Error showing alert:', error));
            fadeOut('manage_users.html');
        } catch (error) {
            await window.electronAPI.showAlert(error.message)
                .then(() => console.log('Alert window opened'))
                .catch(error => console.error('Error showing alert:', error));
        }
    });

    const backButton = document.querySelector('button[name="back"]');
    backButton.addEventListener('click', function() {
        fadeOut('main_menu.html');
        console.log('Back button clicked');
    });
});
