$(document).ready(function () {
    updateCartTotal();
    document.getElementById("emptycart").addEventListener("click", emptyCart);
    document.getElementById("checkout").addEventListener("click", function () {
        if (sessionStorage.getItem('cart') && document.cookie.indexOf("loggedIn=true") != -1) {
            $('#mmlMainContent').load('../components/checkout.html');
        } else {
            $('#mmlMainContent').load('../components/login.html');
        }
    });
});


/* User Manually empty cart */
function emptyCart() {
    //remove cart session storage object & refresh cart totals
    if (sessionStorage.getItem('cart')) {
        sessionStorage.removeItem('cart');
        updateCartTotal();
        updateCartCount();
        //clear message and remove class style
    }
}

function updateCartTotal() {
    //init
    var total = 0;
    var price = 0;
    var items = 0;
    var prodCount = 0;
    var productname = "";
    var carttable = "";
    if (sessionStorage.getItem('cart')) {
        //get cart data & parse to array
        var cart = JSON.parse(sessionStorage.getItem('cart'));
        //get no of items in cart 
        items = cart.length;
        //loop over cart array
        for (var i = 0; i < items; i++) {
            //convert each JSON product in array back into object
            var x = JSON.parse(cart[i]);
            //get property value of price;
            productid = x.productid;
            price = parseFloat(x.price);
            productname = x.productname;
            count = x.count;
            totalperproduct = price * count;
            totalperproduct = parseFloat(totalperproduct.toFixed(2));
            //add price to total
            carttable += "<tr><td>" + productid + "</td><td class='text-center'><button type='button' class='btn btn-danger removeproduct'>X</button></td><td>" + productname + "</td><td class='text-end'>" + price + "€</td><td class='text-center'><button type='button' class='btn btn-danger decreasecount float-start'>-</button>" + count + "<button type='button' class='btn btn-success increasecount float-end'>+</button></td><td class='text-end'>" + totalperproduct + "€</td></tr>";
            total += totalperproduct;
            total = parseFloat(total.toFixed(2));
            prodCount += count;
        }

    }
    //update total on website HTML
    document.getElementById("total").innerHTML = total;
    //insert saved products to cart table
    document.getElementById("carttable").innerHTML = carttable;
    //update items in cart on website HTML
    document.getElementById("itemsquantity").innerHTML = prodCount;

    var delbtns = document.getElementsByClassName("btn btn-danger removeproduct");
    for (var i = 0; i < delbtns.length; i++) {
        delbtns[i].addEventListener("click", function() { removeProductFromCart(this); });
    }

    var incbtns = document.getElementsByClassName("btn btn-success increasecount");
    for (var i = 0; i < incbtns.length; i++) {
        incbtns[i].addEventListener("click", function() { increaseCount(this); });
    }

    var decbtns = document.getElementsByClassName("btn btn-danger decreasecount");
    for (var i = 0; i < decbtns.length; i++) {
        decbtns[i].addEventListener("click", function() { decreaseCount(this); });
    }

}

function removeProductFromCart(elem) {
    
    var productid = elem.parentNode.parentNode.children[0].innerText;
    var cart = JSON.parse(sessionStorage.getItem('cart'));
    var items = cart.length;
    for (var i = 0; i < items; i++) {
        var x = JSON.parse(cart[i]);
        if (x.productid == productid) {
            cart.splice(i, 1);
            break;
        }
    }
    var stringCart = JSON.stringify(cart);
    sessionStorage.setItem('cart', stringCart);
    updateCartTotal();
    updateCartCount();
}

//function to increase product count in cart
function increaseCount(elem) {
    console.log("triggered");
    var productid = elem.parentNode.parentNode.children[0].innerText;
    var cart = JSON.parse(sessionStorage.getItem('cart'));
    var items = cart.length;
    for (var i = 0; i < items; i++) {
        var x = JSON.parse(cart[i]);
        if (x.productid == productid) {
            x.count++;
            cart[i] = JSON.stringify(x);
            console.log(x.count);
            break;
        }
    }
    var stringCart = JSON.stringify(cart);
    sessionStorage.setItem('cart', stringCart);
    updateCartTotal();
    updateCartCount();
}

//function to decrease product count in cart
function decreaseCount(elem) {
    var productid = elem.parentNode.parentNode.children[0].innerText;
    var cart = JSON.parse(sessionStorage.getItem('cart'));
    var items = cart.length;
    for (var i = 0; i < items; i++) {
        var x = JSON.parse(cart[i]);
        if (x.productid == productid) {
            x.count--;
            if (x.count < 1) {
                cart.splice(i, 1);
                break;
            } else {
                cart[i] = JSON.stringify(x);
                break;
            }
        }
    }
    var stringCart = JSON.stringify(cart);
    sessionStorage.setItem('cart', stringCart);
    updateCartTotal();
    updateCartCount();
}
