$(document).ready(function () {
    getProducts();
    document.getElementById("productAddedAlert").hidden = true;
});

function getProducts() {
    //ajax call to php 
    $.ajax({
        url: '../logic/getProductData.php',
        type: 'GET',
        cache: false,
        datatype: 'json',
        data: {},
        success: function (response) {
            const data = JSON.parse(response);
            //set data to fields
            const productOverview = document.getElementById("productOverviewDiv");
            for (let i = 0; i < data.length; i++) {
                const product = document.createElement("div");
                product.className = "product col-md-3";
                product.id = data[i].id;
                product.innerHTML = `<div class="card p-3">
                                        <div class="text-center">
                                            <img src="../res/img/${data[i].image}" class="card-img-top" alt="${data[i].name}" width=200>
                                        </div>
                                        <div class="product-details">
                                            <span class="fw-bold d-block productname">${data[i].name}</span>
                                            <span class="fw-bold d-block price">${data[i].price} €</span>
                                            <span>${data[i].description}</span>
                                            <div class="buttons d-flex flex-row shopbutton">
                                                <div class="cart"><i class="fa fa-shopping-cart"></i></div> <button class="btn btn-success cart-button btn-block addtocart">Add to cart</button>
                                            </div>
                                            <div class="weight">
                                                <small class="productweight">1 Stück | ${data[i].weight} g</small>
                                            </div>
                                            <div class="id">
                                                <small class="productid">ID: ${data[i].product_id}</small>
                                            </div>
                                        </div>`;
                productOverview.appendChild(product);
            }

            var btns = document.getElementsByClassName('btn btn-success cart-button btn-block addtocart');
            for (var i = 0; i < btns.length; i++) {
                btns[i].addEventListener('click', function () { addToCart(this); });
            }
        }
    });
}

function addToCart(elem) {
    //init
    var productDetails = elem.parentNode.parentNode;
    var productDetailsKids = productDetails.children;
    var getprice;
    var getproductName;
    var getproductId;
    var productCount;
    var cart = [];
    var stringCart;

    for (let i = 0; i < productDetailsKids.length; i++) {
        if (productDetailsKids[i].className == "fw-bold d-block price") {
            getprice = productDetailsKids[i].innerText.replace(" €", "");
        }
        if (productDetailsKids[i].className == "fw-bold d-block productname") {
            getproductName = productDetailsKids[i].innerText;
        }
        if (productDetailsKids[i].className == "id") {
            getproductId = productDetailsKids[i].innerText.replace("ID: ", "");
        }
    }

    //create product object
    var product = {
        productid: getproductId,
        productname: getproductName,
        price: getprice,
        count: 1
    };
    //convert product data to JSON for storage
    var stringProduct = JSON.stringify(product);
    /*send product data to session storage */

    if (!sessionStorage.getItem('cart')) {
        //append product JSON object to cart array
        cart.push(stringProduct);
        //cart to JSON
        stringCart = JSON.stringify(cart);
        //create session storage cart item
        sessionStorage.setItem('cart', stringCart);
        addedToCart(getproductName);
        updateCartCount();
    }
    else {
        //get existing cart data from storage and convert back into array
        cart = JSON.parse(sessionStorage.getItem('cart'));
        var productExists = false;

        for (let i = 0; i < cart.length; i++) {
            var object = JSON.parse(cart[i]);
            if (object.productid == getproductId) {
                productExists = true;
            }
        }
        if (!productExists) {
            cart.push(stringProduct);
            stringCart = JSON.stringify(cart);
            sessionStorage.setItem('cart', stringCart);
            addedToCart(getproductName);
            updateCartCount();
        }
        else {
            for (let i = 0; i < cart.length; i++) {
                var object = JSON.parse(cart[i]);
                if (object.productid == getproductId) {
                    object.count++;
                    cart[i] = JSON.stringify(object);
                    stringCart = JSON.stringify(cart);
                    sessionStorage.setItem('cart', stringCart);
                    addedToCart(getproductName);
                    updateCartCount();
                }
            }
        }
    }
}

    function addedToCart(pname) {
        var message = pname + " was added to the cart";
        var alerts = document.getElementById("productAddedAlert");
        alerts.innerHTML = message;
        if (!alerts.classList.contains("message")) {
            alerts.classList.add("message");
        }
        alerts.hidden = false;
        setTimeout(function () {
            alerts.hidden = true;
        }
            , 3000);
    }


    function updateCartCount() {
        var items = getCartCount();
        $('#cartCount').text(items);
    }

    function getCartCount() {
        var items;
        if (sessionStorage.getItem('cart')) {
            var cart = JSON.parse(sessionStorage.getItem('cart')) ?? [];
            items = 0;
            for (let i = 0; i < cart.length; i++) {
                var object = JSON.parse(cart[i]);
                items += object.count;
            }
        } else {
            items = 0;
        }
        return items;
    }