// change password form elements
const userName = document.getElementById('userName');
const userPass = document.getElementById('userPass');
const newUserPass = document.getElementById('newUserPass');
const renewUserPass = document.getElementById('renewUserPass');
const chPassBtn = document.getElementById('chPassBtn');
const connInfo = document.getElementById('connInfo');
const chPhURL = "changePass.php";
const formLog = document.getElementById('formLog');

async function chPass(chForm) {
    const response = await fetch(chPhURL, {
        method: 'POST',
        body: chForm
    });
    
    const phResp = await response.text();
    if(phResp == "UserPassNOTOK") {
      connInfo.textContent = "User name or Password incorrect!";
    } else if (phResp == "changeNOTOK") {
      connInfo.textContent = "We encountered a problem! Please try again!";
    } else if (phResp == "changeOK") {
        connInfo.textContent = "Password changed! Wait 3 seconds to redirect to \"Login\" form.";
        function toLogin() {
            setTimeout(function(){window.location.href = "login.html";}, 3000);
        }
        toLogin();
    }
}

formLog.addEventListener('submit', function(event) {
    event.preventDefault();
    
    let chForm = new FormData();
    chForm.append('userName', userName.value);
    chForm.append('userPass', userPass.value);
    chForm.append('newUserPass', newUserPass.value);
    
    if(newUserPass.value != renewUserPass.value) {
        connInfo.textContent = "New password doesn't match with retyped password!";
    } else {
       chPass(chForm);
    }
});

