const href = window.location.href;
const url = href.substring(0, href.lastIndexOf('/')) + "/api/api.php/user";
const form = document.forms[0];
let body = { 'role': 0 };

form.addEventListener('submit', function(e) {
    e.preventDefault();

    Object.entries(form.elements).forEach((key) => {
        if (key[1].id != "repeatPassword")
            body[key[1].id] = key[1].value;
    })
    
    fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body)
    })
        .then(response => {
            if (response.status === 200) {
                window.location.href = href.substring(0, href.lastIndexOf('/')) + "/login.php";
            } else {
                throw new Error('Something went wrong on api server!');
            }
        }).catch(error => {
            console.error(error);
        });
});
