$(document).ready(function () {
    getProductsOnSide();
    getUserData();
    //add click listener to submit order button
    $('#submitOrder').click(function () {
        //supress default
        event.preventDefault();
        submitOrder();
    });
});

function getTotalAmount() {
    var cart = JSON.parse(sessionStorage.getItem('cart'));
    var items = cart.length;
    var total = 0;
    for (var i = 0; i < items; i++) {
        var x = JSON.parse(cart[i]);
        total += x.price * x.count;
    }
    return total.toFixed(2);
}


function getProductsOnSide() {
    var cart = JSON.parse(sessionStorage.getItem('cart'));
    var items = cart.length;
    for (var i = 0; i < items; i++) {
        var x = JSON.parse(cart[i]);
        /*console.log(x);
        console.log(x.count);
        console.log(x.productid)
        console.log(x.price);
        console.log(x.productname);*/
        var total = x.count * x.price;
        const productListSideways = document.getElementById('productListSideways');
        const product = document.createElement('li');

        product.className = "list-group-item d-flex justify-content-between lh-sm";
        product.id = productid;
        product.innerHTML = `<div>
                                <h6 class="my-0">${x.productname}</h6>
                                <small class="text-muted">${x.count} Stück x ${x.price} €</small>
                            </div>
                            <span class="text-muted">${total} €</span>`;
        productListSideways.appendChild(product);
    }
    var gesamtMengeCart = getCartCount();
    var totalMoneyAmount = getTotalAmount();
    $('#gesamtMengeCart').text(gesamtMengeCart);
    const totalAmount = document.createElement('li');
    totalAmount.className = "list-group-item d-flex justify-content-between";
    totalAmount.innerHTML = `<span>Gesamtpreis (EUR)</span>
                            <strong>${totalMoneyAmount} €</strong>`;
    productListSideways.appendChild(totalAmount);
}

function getUserData() {
    const firstname = document.getElementById('firstName');
    const lastname = document.getElementById('lastName');
    const address = document.getElementById('address');
    const plz = document.getElementById('zip');
    const city = document.getElementById('city');
    var username = getCookie('email');
    var loggedIn = getCookie('loggedIn');
    var sendData = {
        "username": username,
    };
    stringData = JSON.stringify(sendData);
    if (loggedIn == 'true') {
        $.ajax({
            url: '../logic/getUserData.php',
            type: 'POST',
            cache: false,
            datatype: 'json',
            data: stringData,
            success: function (response) {
                const data = JSON.parse(response);
                //set data to fields
                firstname.value = data.firstname;
                lastname.value = data.lastname;
                address.value = data.address;
                plz.value = data.plz;
                city.value = data.city;
            }
        });
    } else {
        window.location.href = '../index.html';
    }
}

function getCookie(cname) {
    let name = cname + "=";
    let decodeCookie = decodeURIComponent(document.cookie);
    let ca = decodeCookie.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 "";
}

function paymentTypeClicked() {
    if (document.getElementById('credit').checked) {
        document.getElementById('creditCardData').style.display = 'block';
    } else {
        document.getElementById('creditCardData').style.display = 'none';
    }
}

        
function submitOrder() {
    var cart = JSON.parse(sessionStorage.getItem('cart'));
    var items = cart.length;
    var total = getTotalAmount();
    var firstname = document.getElementById('firstName').value;
    var lastname = document.getElementById('lastName').value;
    var address = document.getElementById('address').value;
    var plz = document.getElementById('zip').value;
    var city = document.getElementById('city').value;
    if (document.getElementById('credit').checked) {
        var paymentId = 2;
        var creditCardNumber = document.getElementById('creditCardNumber').value;
        var creditCardExpiration = document.getElementById('creditCardExpiration').value;
        var creditCardCvv = document.getElementById('creditCardCvv').value;
    } else {
        var paymentId = 1;
    }
    var username = getCookie('email');
    var loggedIn = getCookie('loggedIn');
    var sendData = {
        "username": username,
        "firstname": firstname,
        "lastname": lastname,
        "address": address,
        "plz": plz,
        "city": city,
        "total": total,
        "cart": cart,
        "paymentId": paymentId,
    };
    stringData = JSON.stringify(sendData);
    if (loggedIn == 'true') {
        $.ajax({
            url: '../logic/submitOrder.php',
            type: 'POST',
            cache: false,
            datatype: 'json',
            data: stringData,
            success: function (response) {
                console.log(response);
                if (response == 'success') {
                    sessionStorage.removeItem('cart');
                    updateCartCount();
                    alert('Bestellung erfolgreich abgeschlossen');
                    $('#mmlMainContent').load('../components/homepage.html');
                } else {
                    alert('Fehler beim Abschicken der Bestellung');
                }
            }
        });
    } else {
        alert('Bitte einloggen');
    }
}
