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('.signup-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 () {
        fadeOut('sign_up_profile.html');
    });

    // Handler for the continue button
    document.getElementById('submit').addEventListener('click', async function (e) {
        e.preventDefault();

        await window.electronAPI.readFile('signupData.json')
            .then(async result => {
                const selectedDept = document.querySelector('input[name="dept"]:checked').value;
                if (!selectedDept) {
                    throw new Error('No department had been selected!.');
                }

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

                const email = data.email;
                const name = data.name;
                const password = data.password;

                const userData = {
                    name: name,
                    email: email,
                    password: password,
                    department: selectedDept,
                }

                await fetch(`http://${ip}/users/register`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'x-api-key': 'uc_api'
                    },
                    body: JSON.stringify(userData)
                })
                    .then(async response => {
                        let data = await response.json();

                        if (!response.ok) {
                            console.log(data);
                            throw new Error(data.message);
                        }

                        data = data.data;
                        userData['id'] = data.id;

                        await window.electronAPI.writeFile('loginData.json', JSON.stringify(userData));
                        fadeOut('sign_up_confirmation.html');
                    })
            })
            .catch(async error => {
                await window.electronAPI.showAlert(error.message)
                    .then(() => console.log('Alert window opened'))
                    .catch(error => console.error('Error changing content:', error));
            })
    });
})

