/*

Product Name: Budget4u App
Author: KodingStudio
Website: https://kodingstudio.com/
Contact: contact@kodingstudio.com
File: Register Js File

*/

// Personal Detail - Start
// variable for personal details

let inputPersonalName = document.getElementById('input-personal-name');
let inputPersonalEmail = document.getElementById('input-personal-email');
let inputPassword = document.getElementById('input-password');
let selectorCountry = document.getElementById('selector-country');
let btnSubmit = document.getElementById('btn-continue');

// variable for feedback / error variables

let feedbackPersonalName = document.getElementById('feedback-personal-name');
let feedbackPersonalEmail = document.getElementById('feedback-personal-email');
let feedbackPassword = document.getElementById('feedback-password');
let feedbackCountry = document.getElementById('feedback-country');

// Personal Detail - End

/* verify business credentials RestApi Endpoint */
function registerUserEndpoint(jsonParam, url) {

    return new Promise(function (resolve, reject) {

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

            var status = xhttp.status;
            if (status === 200 || status === 201) {
                resolve({code: status, data: 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));

    });

}

function fetchAllEndpoint(url = baseUrl + 'v1/app/country/all') {
    return new Promise(function (resolve, reject) {

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

            var status = xhttp.status;

            if (status === 200 || status === 201) {
                resolve({code: status, data: this.responseText});
            } else {
                reject({code: status, data: this.responseText});
            }

        };
        xhttp.open("GET", url, true);
        xhttp.send();

    });

}

fetchAllEndpoint()
    .then(response => JSON.parse(response.data))
    .then(data => {

        let listOfCountries = data.data;
        for(let i=0; i<listOfCountries.length; i++){

            const option = document.createElement('option');
            option.value = listOfCountries[i].id;
            option.text = listOfCountries[i].name;
            selectorCountry.appendChild(option);

        }

    })
    .catch(error => {

        let responseData = JSON.parse(error.response.data);
        console.log("Error = ",responseData);

    });

// main functionality

btnSubmit.addEventListener('click', function () {

    if (!showFeedback(feedbackPersonalName, validateFieldValue(inputPersonalName))) {
        return;
    }
    if (!showFeedback(feedbackPersonalEmail, validateFieldValue(inputPersonalEmail))) {
        return;
    }
    if (!showFeedback(feedbackPassword, validateFieldValue(inputPassword))) {
        return;
    }
    if (!showFeedback(feedbackCountry, validateFieldValue(selectorCountry))) {
        return;
    }

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

    let endpointUrl = baseUrl+"v1/web/auth/register";
    registerUserEndpoint({

            country_id : selectorCountry.value,
            name : inputPersonalName.value,
            email : inputPersonalEmail.value,
            password : window.btoa(inputPassword.value),
            os : getOs(),
            browser : getBrowser()

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

            inputPersonalName.value = null;
            inputPersonalEmail.value = null;
            inputPassword.value = null;
            selectorCountry.value = "";

            document.getElementById('myIcon').classList.remove('ri-loader-2-line');
            document.getElementById('myIcon').classList.add('ri-check-double-line');
            window.location.replace('verification.php?id='+data.data.id+"&email="+data.data.email+"&type=register");

            /**/


        })
        .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');


        });

});

// utility functions - start

/* check either value is empty or not*/
function isEmpty(value) {
    return (typeof value === "undefined" || value === null || value === "");
}

/* for validate field either empty or not */
function validateFieldValue(inputField) {

    if (isEmpty(inputField.value)) {
        return false;
    } else {
        return true;
    }

}

/* show required feedback if empty*/
function showFeedback(inputField, emptyOrNot) {

    if (!emptyOrNot) {
        inputField.style.display = 'block';
    } else {
        inputField.style.display = 'none';
    }

    return emptyOrNot;

}

function setCookies(userDataObject) {

    let userObject = userDataObject.user;
    let id = userObject.id;
    let name = userObject.name;
    let email = userObject.email;
    let securityKey = userDataObject.token;

    document.cookie = "id =" + id + ";";
    document.cookie = "name = " + name + ";";
    document.cookie = "email = " + email + ";";
    document.cookie = "login = " + true + ";";
    document.cookie = "securityKey = " + securityKey + ";";

    window.location.assign("profile.php");

}

function getOs() {
    let os = navigator.userAgent;
    let finalOs = "";
    if (os.search('Windows') !== -1) {
        finalOs = "Windows";
    } else if (os.search('Mac') !== -1) {
        finalOs = "MacOS";
    } else if (os.search('X11') !== -1 && !(os.search('Linux') !== -1)) {
        finalOs = "UNIX";
    } else if (os.search('Linux') !== -1 && os.search('X11') !== -1) {
        finalOs = "Linux"
    } else {
        finalOs = "Unknown"
    }

    return finalOs;

}

function getBrowser() {

    var browserName = "Unknown";
    var nAgt = navigator.userAgent;
    var nameOffset,verOffset,ix;

    // In Opera, the true version is after "OPR" or after "Version"
    if ((verOffset = nAgt.indexOf("OPR")) != -1) {
        browserName = "Opera";
    }
    // In MS Edge, the true version is after "Edg" in userAgent
    else if ((verOffset = nAgt.indexOf("Edg")) != -1) {
        browserName = "Microsoft Edge";
    }
    // In MSIE, the true version is after "MSIE" in userAgent
    else if ((verOffset = nAgt.indexOf("MSIE")) != -1) {
        browserName = "Microsoft Internet Explorer";
    }
    // In Chrome, the true version is after "Chrome"
    else if ((verOffset = nAgt.indexOf("Chrome")) != -1) {
        browserName = "Chrome";
    }
    // In Safari, the true version is after "Safari" or after "Version"
    else if ((verOffset = nAgt.indexOf("Safari")) != -1) {
        browserName = "Safari";
    }
    // In Firefox, the true version is after "Firefox"
    else if ((verOffset = nAgt.indexOf("Firefox")) != -1) {
        browserName = "Firefox";
    }
    // In most other browsers, "name/version" is at the end of userAgent
    else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) <
        (verOffset = nAgt.lastIndexOf('/'))) {
        browserName = nAgt.substring(nameOffset, verOffset);

        if (browserName.toLowerCase() == browserName.toUpperCase()) {
            browserName = navigator.appName;
        }
    }
    else {
        browserName = "Unknown";
    }

    return browserName;

}
