const emailLogin = document.getElementById('emailLogin');
const passwordLogin = document.getElementById('passwordLogin');
const rememberme = document.getElementById('rememberMe');

const formLogin = document.getElementById('loginForm');
formLogin.addEventListener('submit', login);

async function login(event) {
    event.preventDefault();
    if (checkLogin()) {
        //get form data
        const formData = new FormData(formLogin);
        //create object with form data
        const data = {};
        formData.forEach((value, key) => data[key] = value);
        //log data on console
        datastring = JSON.stringify(data);
        //send data to php with Ajax
        $.ajax({
            url: '../logic/loginLogic.php',
            type: 'POST',
            data: datastring,
            cache: false,
            datatype: 'text',
            success: function (response) {
                if (response == 'success') {
                    if (rememberme.checked) {
                        document.cookie = "rememberme=true; expires=Fri, 31 Dec 9999 23:59:59 GMT";
                        document.cookie = "email=" + emailLogin.value + "; expires=Fri, 31 Dec 9999 23:59:59 GMT";
                        document.cookie = "loggedIn=true; expires=Fri, 31 Dec 9999 23:59:59 GMT";
                    } else {
                        document.cookie = "rememberme=false";
                        document.cookie = "email=" + emailLogin.value;
                        document.cookie = "loggedIn=true";
                    }
                    window.location.href = '../index.html';
                    alert(response);
                } else {
                    alert(response);
                }
            }
        });
    }
} 

function checkLogin() {
    if (emailLogin.value == '' || passwordLogin.value == '') {
        alert('Please fill in all fields');
        return false;
    } else {
        return true;
    }
}