let inputPasswordNew = document.getElementById('input-password-new');
let inputPasswordConfirm = document.getElementById('input-password-confirm');

function resetPassword(jsonParam, url) {

    return new Promise(function (resolve, reject) {

        const xhttp = new XMLHttpRequest();
        xhttp.onload = function () {

            var status = xhttp.status;
            if (status === 200) {
                resolve(this.responseText);
            } else {
                reject({code: status, response: this.responseText});
            }

        };
        xhttp.open("POST", url, true);
        xhttp.setRequestHeader('Content-type', 'application/json');
        xhttp.send(JSON.stringify(jsonParam));

    });

}

const searchParams = new URLSearchParams(window.location.search);
if (searchParams.has('id')
    && searchParams.has('email')
    && searchParams.has('code')) {

    let userId = searchParams.get('id');
    let userEmail = searchParams.get('email');
    let userCode = searchParams.get('code');


    let btnContinue = document.getElementById('btn-continue');
    btnContinue.addEventListener('click', function () {


        if (inputPasswordNew.value !== inputPasswordConfirm.value){
            alert('Password Mis-match');
            return;
        }

        let endpointUrl = baseUrl + "v1/web/auth/reset/" + userId;
        resetPassword({

                email: userEmail,
                new_password: btoa(inputPasswordNew.value),
                code: userCode,

            },
            endpointUrl)
            .then(response => JSON.parse(response))
            .then(data => {

                Swal.fire({
                    position: 'center',
                    icon: 'success',
                    title : 'Success',
                    showConfirmButton: false,
                    timer: 2000,
                    showCloseButton: true
                }).then((result) => {

                    window.location.replace('login.php');

                });


            })
            .catch(error => {

                let responseData = JSON.parse(error.response);

                document.getElementById('div-message').innerText = responseData.message;
                document.getElementById('div-message').style.display = 'block';
                document.getElementById('myIcon').classList.remove('ri-loader-2-line');
                document.getElementById('myIcon').classList.add('ri-arrow-right-line');

            });

    });


}