/**
 * Class to display product labeling and pacing options
 */
class PandaCalculator {

    positions = {}; 
    productInfo;
    productPrice;

    constructor(productInfo) {
        this.productInfo = productInfo;
        this.productPrice = calculatorScriptVariables.productInfo.productBaseInfo.price;
        this.#decodeLabeling();
        
    }
    
    init(optionDiv, technologyDiv, imageDiv, totalPrice) {

        document.querySelector("#attributes").innerHTML = this.#drawAttributes();
        document.querySelector(optionDiv).innerHTML = this.#drawPositionSelect();

        this.#updatePrice(totalPrice);

        document.querySelector("#select_options").addEventListener("change", () => {
            document.querySelector(technologyDiv).innerHTML = this.#drawTechnologySelect();
            
            // this.#updatePrice(totalPrice);

            document.querySelector("#select_technology").addEventListener("change", () => {
                if (document.querySelector("#select_technology").value != "brak") {
                    document.querySelector(imageDiv).innerHTML = this.#getImage();
                    let value = this.#getSelectedOptions();
                    if (value) {
                        
                        let maxColors = value.max_colors;
                        let dimensions = { "width": value.max_width, "height": value.max_height, "radius": value.max_radius } ;
                        this.#getColorNumber(maxColors);
                        this.#showDemission(dimensions);
        
                        this.#updatePrice(totalPrice);

                        const colorInput = document.querySelector("#color_number_input");
                        if (colorInput) {
                            colorInput.addEventListener("change", () => {
                                this.#updatePrice(totalPrice);
                            });
                        }


                    }
                }
            })

        })


        document.querySelector("#quantity").addEventListener("change", (event) => {
            this.#updatePrice(totalPrice);
        })

        //this.#updatePriceDefaultBDI();
    }

    #updatePrice(totalPrice) {
        let sumPrice = this.#getPricingTable();
        document.querySelector(totalPrice).innerHTML = sumPrice;
        document.getElementsByName("total_price")[0].value = sumPrice;
        // document.getElementsByName("product_price")[0].value = this.productPrice;
    }


    #decodeLabeling() {
        this.productInfo.labeling.forEach(element => {
            this.positions[element.name] = this.positions[element.name] ? this.positions[element.name].concat(element) : [element]
        });
    }

    #drawPositionSelect() {
        var html = "<select id='select_options' name='option'>";
        html += "<option value='brak'>Bez znakowania</option>";
        Object.keys(this.positions).forEach(key => {
            html += "<option value='" + key + "'>" + key +"</option>";
        })
        html += "</select>";

        return html;
    }

    #drawTechnologySelect() {
        var html = "";
        
        var positionKey = document.querySelector("#select_options").value;

        if (positionKey != "brak") {
            html += "<p>Technologia znakowania</p>";
            html += "<select id='select_technology' name='technology'>";
            html += "<option value='brak'>Wybierz technikę znakowania</option>";
            Object.keys(this.positions[positionKey]).forEach(key => {
                let value = this.positions[positionKey][key];
                let size = value.max_radius != "0" ? "(" + value.max_radius + "mm)" : "(" + value.max_height + "mm x " + value.max_height + "mm)";
                html += "<option value='" + value.technology + "'>" + value.technology + " " + size + "</option>";
            })
            html += "</select>";
        }

        return html;
    }

    #drawAttributes() {
        let html = "";

        const attributes = this.productInfo.productBaseInfo.attributes || {};

        if (Object.keys(attributes).length === 0) {
            return html;
        }

        Object.keys(attributes).forEach(key => {
            html += `<label>`;
            html += `<p>${key}</p>`;
            html += `<select id='select_attributes_${key}' name='${key}'>`;
            attributes[key].forEach(value => {
                html += `<option value='${value.attributes}'>${value.attributes}</option>`;
            });
            html += `</select>`;
            html += `</label>`;
        });

        return html;
    }


    #getImage() {

        var value = this.#getSelectedOptions();

        if (value.image) {
            var html = "<img src='" + value.image +"' />";
            return html;
        }

        return "";
    }


    #getPricingTable() {

        let quantity = document.querySelector("#quantity").value ? document.querySelector("#quantity").value : 1;
        let productPrice = this.#getBulkPrice(parseFloat(this.productPrice), quantity);

        document.getElementsByName("product_price")[0].value = productPrice;
        document.querySelector("#product_price").innerHTML = productPrice;

        var unitPrice = 0;
        var setupCost = 0;

        if (document.querySelector("#select_options") && document.querySelector("#select_technology")) {

            let value = this.#getSelectedOptions();

            // console.log(value);

            var colorNumber = document.querySelector("#color_number_input") ? document.querySelector("#color_number_input").value : 1;
            // console.log(colorNumber);
            // console.log(value);
            if (value.max_colors == 0 && Object.keys(value.pricing)[0] == "fullcolour") {
                colorNumber = "fullcolour";
            }

            if (value.pricing && value.pricing[colorNumber]) {

                var unitPrice = value.pricing[colorNumber].unit_price
                var setupCost = value.pricing[colorNumber].setup_cost
                value.pricing[colorNumber].forEach((element) => {
                    if (
                        parseInt(element.quantity_from) <= parseInt(quantity)
                        && parseInt(element.quantity_to) >= parseInt(quantity)
                    ) {
                        unitPrice = element.unit_price
                        setupCost = element.setup_cost
                    }
                })

            }

        }


        document.querySelector("#price").innerHTML = unitPrice;
        document.querySelector("#setup_price").innerHTML = setupCost;
        document.getElementsByName("labeling_price")[0].value = unitPrice;
        document.getElementsByName("setup_price")[0].value = setupCost;
        let sum = (parseFloat(productPrice) * quantity) + (parseFloat(unitPrice) * quantity) + parseFloat(setupCost);

        return Math.round(sum * 100) / 100;
    }


    #getSelectedOptions() {
        var positionKey = document.querySelector("#select_options").value;
        var technologyKey = document.querySelector("#select_technology").value;

        // console.log(technologyKey);
        // console.log(positionKey);

        if (technologyKey != "brak") {

            var position = this.positions[positionKey];
    
            for (let index = 0; index < position.length; index++) {
                if (position[index].technology == technologyKey) {
                    var value = position[index]
                }
            }

            return value;
        }

        return null;


    }

    #getColorNumber(maxColor) {


        if (maxColor != 0)  {
            var html = `<label>`;
            html += `<p>Ilość kolorów</p>`;
            html += `<input type='number' max='${maxColor}' min='1' value='1' name='colors' id='color_number_input'/>`;
            html += "</label>";
        } else {
            var html = `<label>`;
            html += `<p>Ilość kolorów</p>`;
            html += `<input type='number' max='1' min='1' value='1' name='colors' id='color_number_input'/>`;
            html += "</label>";
        }

        document.querySelector("#color_number").innerHTML = html;
    }

    #showDemission(dimensions) {
        let demission = "";
        if (dimensions.radius == "0") {
            demission += dimensions.width + "mm x " + dimensions.height + "mm";
        } else {
            demission += dimensions.radius + "mm";
        }

        document.querySelector("#dimensions_name").innerHTML = "Wymiary nadruku:";
        document.querySelector("#dimensions").innerHTML = demission;
    }

    #updatePriceDefaultBDI() {
        let currencySymbol = document.querySelector('.woocommerce-Price-currencySymbol').innerHTML;
        let priceBox = document.querySelector('.woocommerce-Price-amount');
        priceBox.innerHTML = " 0.00";
        
    }

    #getBulkPrice(price, quantity) {
        var newPrice = price;
        if (price < 5) {
            if (quantity >= 1 && quantity <= 9) {
                newPrice = price + price * 0.36;
            } else if (quantity >= 10 && quantity <= 249) {
                newPrice = price - price * 0.31;
            } else if (quantity >= 250 && quantity <= 999) {
                newPrice = price - price * 0.37;
            } else if (quantity >= 1000 && quantity <= 4999) {
                newPrice = price - price * 0.42;
            } else if (quantity >= 5000) {
                newPrice = price - price * 0.47;
            }
        } else {
            if (quantity >= 1 && quantity <= 9) {
                newPrice = price;
            } else if (quantity >= 10 && quantity <= 99) {
                newPrice = price - price * 0.31;
            } else if (quantity >= 100 && quantity <= 249) {
                newPrice = price - price * 0.37;
            } else if (quantity >= 250 && quantity <= 999) {
                newPrice = price - price * 0.42;
            } else if (quantity >= 1000) {
                newPrice = price - price * 0.47;
            }
        }


        newPrice = Math.round(newPrice * 100) / 100;
        return newPrice;
    }
    
}


class ShowInformation {
    constructor() {
        let base = calculatorScriptVariables.productInfo.productBaseInfo

        let price = base.price;
        //let currencySymbol = document.querySelector(".woocommerce-Price-currencySymbol").innerHTML;
        //document.querySelector("bdi").innerHTML = price + currencySymbol;

        console.log(calculatorScriptVariables.productInfo)
        
        const invent = calculatorScriptVariables.productInfo.inventory
        const attributes = document.getElementById("select_attributes_color")
        if(!attributes) {    
            if(invent.length == 0) {
                document.getElementById("stock").innerHTML = "Ilość w magazynie " + 0 + " szt."
                document.getElementById("add_to_cart_button").disabled = true;
                document.getElementById("add_to_cart_button").value = "Niedostępne";
                document.getElementById("add_to_cart_button").classList.add("unavailable");
            }

            invent.forEach(inv => {
                if(inv.type === "central_stock") {
                    document.getElementById("stock").innerHTML = "Ilość w magazynie " + inv.amount + " szt."
               if (inv.amount < 50) {
                        document.getElementById("add_to_cart_button").disabled = true;
                        document.getElementById("add_to_cart_button").value = "Niedostępne";
                        document.getElementById("add_to_cart_button").classList.add("unavailable");
                    } else {
                        document.getElementById("add_to_cart_button").disabled = false;
                        document.getElementById("add_to_cart_button").value = "Dodaj do koszyka";
                        document.getElementById("add_to_cart_button").classList.remove("unavailable");
                    }

                }
            })
        } else {
            const color = attributes.value;
            const selectedColor = calculatorScriptVariables.productInfo.productBaseInfo.attributes.color.find(c => {
                return c.attributes === color;
            });

            const sku = selectedColor.image.split('/').at(-1).split('.')[0]
            const invent = calculatorScriptVariables.productInfo.inventory
            
            invent.forEach(inv => {
                if(inv.type === "central_stock" && inv.sku == sku) {
                    document.getElementById("stock").innerHTML = "Ilość w magazynie " + inv.amount + " szt."
                    if (inv.amount < 50) {
                        document.getElementById("add_to_cart_button").disabled = true;
                        document.getElementById("add_to_cart_button").value = "Niedostępne";
                        document.getElementById("add_to_cart_button").classList.add("unavailable");
                    } else {
                        document.getElementById("add_to_cart_button").disabled = false;
                        document.getElementById("add_to_cart_button").value = "Dodaj do koszyka";
                        document.getElementById("add_to_cart_button").classList.remove("unavailable");
                    }

                }
            })
        }

        const gallery = document.querySelector(".single-product__images");
        const images = calculatorScriptVariables.productInfo.productBaseInfo.images

        if(images) {
            
            images.forEach(img => {
                const url = img.url;

                const imageElement = document.createElement("img");
                imageElement.src = url;
                imageElement.alt = "Obraz produktu"; 
                imageElement.classList.add("product-image");

                imageElement.addEventListener("click", () => {
                    const thumbnail = document.querySelector(".single-product__thumbnails img");
                    thumbnail.src = url;
                })

                gallery.appendChild(imageElement);
            });

            
            jQuery(function($) {
                $('.single-product__images').slick({
                    slidesToShow: images.length,
                    slidesToScroll: 1,
                    arrows: true,
                    infinite: true,
                    adaptiveHeight: false,
                    draggable: false,
                    swipe: false,    
                    prevArrow: '<button type="button" class="slick-prev slider-arrow"><span class="screen-reader-text">Poprzedni</span></button>',
                    nextArrow: '<button type="button" class="slick-next slider-arrow"><span class="screen-reader-text">Następny</span></button>',

                });
            });

        }

        const photo = base.primary_img;
        if (photo) {
            const thumbnailContainer = document.querySelector(".single-product__thumbnails");

            const img = document.createElement("img");
            img.src = photo;
            img.alt = "Podgląd produktu";
            img.style.borderRadius = "8px";

            thumbnailContainer.appendChild(img);
        }

        const nameDiv = document.getElementById("product-name")
        const infoCard = document.querySelector(".product-info-card__header h2")
        nameDiv.innerHTML = infoCard.innerHTML

        const selectColor = document.getElementById("select_attributes_color")

        if(selectColor) {
            selectColor.addEventListener("change", this.colorChanged)
        }
        
    }


    colorChanged(e) {
        const color = e.target.value;

        const selectedColor = calculatorScriptVariables.productInfo.productBaseInfo.attributes.color.find(c => {
            return c.attributes === color;
        });

        if (!selectedColor) {
            console.warn("Nie znaleziono koloru:", color);
            return;
        }

        const img = document.createElement("img");
        img.src = selectedColor.image;
        img.alt = "Podgląd produktu";
        img.style.borderRadius = "8px";

        const photoContainer = document.getElementById("attributes-photo");
        photoContainer.innerHTML = "";
        photoContainer.appendChild(img);

        const sku = selectedColor.image.split('/').at(-1).split('.')[0]

        const invent = calculatorScriptVariables.productInfo.inventory
        
        invent.forEach(inv => {
            if(inv.type === "central_stock" && inv.sku == sku) {
                document.getElementById("stock").innerHTML = "Ilość w magazynie " + inv.amount + " szt."
               if (inv.amount < 50) {
                        document.getElementById("add_to_cart_button").disabled = true;
                        document.getElementById("add_to_cart_button").value = "Niedostępne";
                        document.getElementById("add_to_cart_button").classList.add("unavailable");
                    } else {
                        document.getElementById("add_to_cart_button").disabled = false;
                        document.getElementById("add_to_cart_button").value = "Dodaj do koszyka";
                        document.getElementById("add_to_cart_button").classList.remove("unavailable");
                    }
            }
        })
    }

}

document.addEventListener("DOMContentLoaded", function () {
    var productCalculator = new PandaCalculator(calculatorScriptVariables.productInfo);
    productCalculator.init("#options", "#technology", "#select_image", '#total_price');

    var information = new ShowInformation();
});