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

    await fetch(`http://${ip}/users/departments`, {
        method: 'GET',
        headers: {
            'x-api-key': 'uc_api'
        }
    }).then(async result => {
        const res = await result.json();
        const data = res['data'];

        const formContent = document.querySelector('.department-form-content');
        Object.entries(data).forEach(([key, department]) => {
            if(department.name !== 'CEO'){
                const label = document.createElement('label');
                label.innerHTML = `<input type="radio" name="dept" value="${department.name}">${department.name}`;
                formContent.appendChild(label);
            }
        });
    }).catch(async error => {
        await window.electronAPI.showAlert(error.message)
            .then(() => console.log('Alert window opened'))
            .catch(error => console.error('Error changing content:', error));
    });

    document.getElementById('back').addEventListener('click', async function () {
        try {
            await fadeOut('main_menu.html');
            console.log('Content changed successfully');
        } catch (error) {
            console.error('Error changing content:', error);
        }
    });

    document.getElementById('submit').addEventListener('click', async function (e) {
        e.preventDefault();

        const selectedDept = document.querySelector('input[name="dept"]:checked').value;
        if (!selectedDept) {
            throw new Error('No department had been selected!.');
        }

        let result = await window.electronAPI.readFile('loginData.json');
        if (!result.success) {
            throw new Error('Error reading the file. Please try again later.');
        }

        const data = JSON.parse(await result.content);
        const id = data.id;

        await fetch(`http://${ip}/users/change_department`, {
            method: 'PATCH',
            headers: {
                'Content-Type': 'application/json',
                'x-api-key': 'uc_api'
            },
            body: JSON.stringify({
                id: id,
                department: selectedDept,
            })
        }).then(async response => {
            if (!response.ok) {
                return;
            }

            fadeOut('main_menu.html')
        }).catch(async error => {
            console.error(error);
            await window.electronAPI.showAlert(error.message)
                .then(() => console.log('Alert window opened'))
                .catch(error => console.error('Error changing content:', error));
        });
    });
})
