/*

Product Name: PosPlatter
Author: KodingStudio
Website: https://posplatter.com/
Contact: contact@kodingstudio.com
File: Login Js File

*/

// variable for main endpoints

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

let inputPersonalEmail = document.getElementById('input-personal-email');
let inputPassword = document.getElementById('input-password');
let btnSubmit = document.getElementById('btn-continue');

// variable for feedback / error variables

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

// Personal Detail - End

/* verify business credentials RestApi Endpoint */
function loginUserEndpoint(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));

    });

}

// main functionality

if (!isEmpty(getCookie('securityKey'))){
    window.location.assign("business.php");
}

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

    if (!showFeedback(feedbackPersonalEmail, validateFieldValue(inputPersonalEmail))) {
        return;
    }
    if (!showFeedback(feedbackPassword, validateFieldValue(inputPassword))) {
        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/login";
    loginUserEndpoint({

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

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

            setCookies(data.data);

        })
        .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("business.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;

}

function getCookie(cname) {
    let name = cname + "=";
    let decodedCookie = decodeURIComponent(document.cookie);
    let ca = decodedCookie.split(';');
    for (let i = 0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

