// source --> https://vrecka-do-vysavaca.sk/wp-content/plugins/wx-eshop/jsm/pre-cart.js?ver=3.85 
jQuery(document).ready(function($) {
    console.log('v3 loaded');

    $('.coupon-col-end').on('click', function(e) {
        e.preventDefault();
        window.location.href = '/kosik/';
    });
    $('#wx_coupon_code_submit').on('click', function(e) {
        e.preventDefault();
        var coupon_code = $('#wx_coupon_code_input').val();
        window.location.href = '/kosik/?wt_coupon='+coupon_code;
    });

    var couponHtml = `
        <form id="wx_coupon_wrapper" action="/kosik/" method="get">
            <input name="wt_coupon" type="text" id="wx_coupon_code_input" placeholder="Kód pro stálé zákazníky">
            <button id="wx_coupon_code_submit">Odeslat kód</button>
        </form>
    `;

    // Add the HTML before the element with the class .wt_coupon_wrapper
    $('.wt_coupon_wrapper').before(couponHtml);

    $('.pridat_do_kosiku').on('click', function(e) {
        e.preventDefault();

        $(this).addClass('loading');

        var product_id = $(this).attr('data-product_id');
        var thisbutton = $(this);
        console.log("adding product to cart: "+product_id); // Print or echo the product ID

        // WooCommerce AJAX Add to Cart Request
        $.ajax({
            type: 'POST',
            url: wc_add_to_cart_params.ajax_url, // WooCommerce provides this global variable
            data: {
                action: 'woocommerce_add_to_cart',
                product_id: product_id,
                quantity: 1 // Add 1 item by default, you can modify this as per your requirement
            },
            beforeSend: function(response) {
                // Disable the button and add a loading class during the request
                thisbutton.prop('disabled', true).addClass('loading');
            },
            success: function(response) {

                if (response.error && response.product_url) {
                    // Redirect to the product URL if there's an error
                    window.location.href = response.product_url;
                    return;
                }
                nonce = $(this).attr("data-nonce");
                $.ajax({
                    type : "post",
                    url : myAjax.ajaxurl,
                    data : {action: "wx_pre_cart_ajax", product_id : product_id, nonce: nonce},
                    success: function(response) {
                        if (!$('body').hasClass('elementor-popup-modal-opened')) {
                            elementorProFrontend.modules.popup.showPopup({id: 4299});

                            $.ajax({
                                url: wc_add_to_cart_params.ajax_url, // WooCommerce provides this global object
                                type: 'POST',
                                data: {
                                    action: 'get_cart_contents'
                                },
                                success: function(response2) {
                                    console.log("Cart contents refreshed");
                                    $('.wx_cart_popup').html(response2);
                                    console.log("cross all:"+response);
                                    $.each(response, function(key, value) {
                                        console.log("cross id:"+key); // Print or echo the value
                                        if ($('#cross_prod_'+key).length === 0) {
                                            $(".pre_cart_cross_sell_ajax").append(value);
                                            console.log("cross added: #cross_prod_"+key);
                                            console.log(value);
                                        }else{
                                            console.log("cross already there: #cross_prod_"+key);
                                        }
                                    });
                                    toggleCouponCodeForm();
                                },
                                error: function(error) {
                                    console.log('Error fetching cart contents:', error);
                                }
                            });


                            console.log("popup opened");
                        }else{
                            console.log("popup already opened / no need to open it again");
                        }
                        console.log("refreshing cart fragment");
                        // Trigger the WooCommerce event 'added_to_cart' (important for cart updates)
                        // $(document.body).trigger('added_to_cart', [response.fragments, response.cart_hash, thisbutton]);

                        console.log("refreshing done");

                    },
                    error: function(xhr, status, error) {
                        // Handle AJAX error
                        console.log('An error occurred: ' + error);
                    }
                });

            },
            complete: function() {
                // Re-enable the button and remove the loading class after the request completes
                setTimeout(function() {
                    $(this).removeClass('loading');
                    thisbutton.prop('disabled', false).removeClass('loading');
                }, 4000);
            },
            error: function(error) {
                console.log('AJAX Error: ', error);
            }
        });

        $('body').on('change', '.quantity .qty', function() {
                var newQuantity = $(this).val();
                console.log("changing quantity to: "+newQuantity);
                var $this = $(this);
                var quantity = $this.val();
                var nameAttr = $(this).attr('name'); // Get the 'name' attribute
                var item_hash = nameAttr.match(/\[([a-zA-Z0-9]+)\]/)[1];

                // Trigger update cart event
                var data = {
                    action: 'woocommerce_update_cart',
                    item_key: item_hash,
                    quantity: quantity
                };

                $.ajax({
                    url: wc_add_to_cart_params.ajax_url,
                    type: 'POST',
                    data: data,
                    success: function(response4) {
                        // Trigger WooCommerce cart update
                        $(document.body).trigger('updated_wc_div');
                        console.log('recalculating: '+response4);
                        $.ajax({
                            url: wc_add_to_cart_params.ajax_url, // WooCommerce provides this global object
                            type: 'POST',
                            data: {
                                action: 'get_cart_contents'
                            },
                            success: function(response5) {
                                console.log("Cart contents refreshed");
                                $('.wx_cart_popup').html(response5);

                                toggleCouponCodeForm();
                            },
                            error: function(error) {
                                console.log('Error fetching cart contents:', error);
                            }
                        });
                    }
                });


        });
    });



    function toggleCouponCodeForm(){
        $('input#coupon_code').attr('placeholder', 'Kód pro stálé zákazníky');
        $('.coupon-col').after('<div class="show-coupon" style="text-decoration: underline; cursor: pointer;"><img src="/wp-content/uploads/2024/10/coupon-gift.png" style="width: 40px; float: left; margin-right:10px; color:black;" alt="Coupon Gift"><span style=" color:black;">Kód pro stálé zákazníky</span></div>');
        $('.coupon-col').hide();

        $('.show-coupon').on('click', function() {
            $('.coupon-col').slideDown();  // Show the coupon column with a slide down effect
            $(this).hide(); // Hide the clickable text after the coupon-col is shown
        });
    }
    if ($('.coupon-col').length > 0) {
        toggleCouponCodeForm();
    }


    if ($('#company_details').length > 0) {

        toggleCompanyField();

        // Toggle visibility when #company_details is clicked
        $('#company_details').on('click', function () {
            toggleCompanyField();
        });

        // Function to toggle the company field visibility
        function toggleCompanyField() {
            if ($('#company_details').is(':checked')) {
                $('.wpify-woo-ic-dic__company_field').slideDown();
            } else {
                $('.wpify-woo-ic-dic__company_field').slideUp();
            }
        }
    }


    var linkCount = $('.hepa-compatible-list a').length;
    // Check if there are more than 50 <a> elements
    if (linkCount > 50) {
        // Move .detdesc after .elementor-widget-woocommerce-product-image
        $('.elementor-widget-woocommerce-product-images').parent().append("<h2>Popis produktu</h2>").append($('elementor-element-e58fc52')).append($('.detdesc')).append($('.tabulka-vlastnosti'));
        $('.detdesc').css('padding-right', '5%');
        $('.tabulka-vlastnosti').css('width', '95%');
        $('#vice-o-produktu').hide();
    }

    if ($('.e-woocommerce-login-nudge').length) {
        $('.e-woocommerce-login-nudge').html('Pokud jste u nás již nakupovali, prosím zadejte své údaje níže. Pokud jste nový zákazník, přejděte prosím do sekce Fakturační údaje.');
        $('.elementor-woocomemrce-login-rememberme').html('Trvalé přihlášení');
        $('label[for="password"]').contents().filter(function() {
            return this.nodeType === 3; // Only target text nodes
        }).first().replaceWith('Heslo ');
    }
    //Administrace
    // WP 7.1+ renderuje primární buňku (číslo objednávky) jako <th scope="row">, ne <td>,
    // takže selektor musí být bez tagu, jinak celý admin blok (odkazy Reklamace, formátování
    // čísel, zobrazení lišty subsubsub) na novějším WP nikdy neproběhne.
    if ($('.column-order_number').length) {
        console.log("column-order_number found");
        // WP 7.1 přesunul checkbox řádku z <th> do <td class="check-column">. WooCommerce
        // řádkový klik (wc-orders.min.js, delegace na document se selektorem "tbody td")
        // tím nově chytá i klik na zaškrtávátko a naviguje do detailu objednávky.
        // Zastavením propagace z check-column se checkbox dá zase normálně zaškrtnout
        // (výběr pro hromadné akce); WP shift-výběr rozsahu je vázán níž, ten běží dál.
        $('#the-list').on('click', 'td.check-column, th.check-column', function (e) {
            e.stopPropagation();
        });
       $('ul.subsubsub li:nth-last-child(-n+2)').remove();
        $('ul.subsubsub').append('<li><a href="/wp-admin/admin.php?page=wc-orders&_k2note=1" ><strong>Reklamace</strong> | </a></li>');
        $('ul.subsubsub').append('<li><a href="/wp-admin/admin.php?page=wc-orders&_k2note=1&refund_status=finished" >Reklamace uzavřené | </a></li>');
        $('ul.subsubsub').append('<li><a href="#" id="show-actions-2">Další filtry</a></li>');
        $('#show-actions-2').on('click', function(e) {
            e.preventDefault();
            $('.tablenav .actions:nth-of-type(2)').fadeToggle();
        });
        $('ul.subsubsub').fadeIn();
        $('.column-order_number strong').each(function () {
            var text = $(this).text();
            var updatedText = text.replace(/^#/, '');
            //var updatedText = updatedText.replace(/ /g, ' <br>');
            var updatedText = updatedText.replace(/^(\d+)/, '<span class="order_number">$1</span>')
            $(this).html(updatedText);
            $(this).fadeIn();
        });
    }else{
        console.log("column-order_number not found");
    }

 /*   document.querySelectorAll('.disable-right-click').forEach((element) => {
        element.addEventListener('contextmenu', function (event) {
            event.preventDefault(); // Disable right-click
        });
    });*/
/*
    $(document).on('click', function (event) {
        // Check if the clicked element or any of its parents has the class 'no-select'
        if ($(event.target).closest('.no-select').length) {
            event.preventDefault(); // Prevent default action
            console.log('Clicked inside no-select element');
        }
    });*/


    // Hide trailing ".00" in prices inside .shop_table and .xoo-wsc-markup
    function hideTrailingZeros() {
        $('.shop_table, .xoo-wsc-markup').find('td, span, div').each(function() {
            var text = $(this).text();
            if (text.match(/\d+\.00(\s*[^0-9]|$)/)) {
                $(this).text(text.replace(/(\d+)\.00(\s*[^0-9]|$)/g, '$1$2'));
            }
        });
        $('.xoo-wsc-markup .xoo-wsc-align-right').each(function(){
            var txt = $(this).text().trim();
            $(this).text(txt.replace(/(\d+)\.00(\s*Kč)?$/, '$1$2'));
        });
    }
    // Run on page load
    hideTrailingZeros();
    // Also run after any ajax complete (to catch cart updates etc.)
    $(document).ajaxComplete(function() {
        hideTrailingZeros();
    });

    function hideTrailingZeros(){

    }


});