<?php $__env->startPush('js'); ?>
<style>
    label.color {
        min-width: 1.8rem;
        min-height: 1.8rem;
    }
</style>
<script>
    // Qty Plus
    $(document).on('click', '.value-plus', function(e) {
        e.preventDefault();
        var divUpd = $(this).parent().find('.value'),
        newVal = parseInt(divUpd.val(), 10) + 1;
        divUpd.val(newVal);
        $('#product_model_pop_up_qty_hidden').val(newVal);
        updatePriceFromServer('/get/attr/price', $('#product_model_pop_up_addToCart, #product_model_pop_up_buyNowDirect'));
    });

    // Qty Minus
    $(document).on('click', '.value-minus', function(e) {
        e.preventDefault();
        var divDown = $(this).parent().find('.value'),
            newDownVal = parseInt(divDown.val(), 10) - 1;
        if (newDownVal >= 1) {
            divDown.val(newDownVal);
            $('#product_model_pop_up_qty_hidden').val(newDownVal);
            updatePriceFromServer('/get/attr/price', $('#product_model_pop_up_addToCart, #product_model_pop_up_buyNowDirect'));
        }
    });

    // Product info popup
    function productInfoPopUp(url, mode) {
        $.ajax({
            type: 'GET',
            url: url,
            dataType: 'JSON',
            success: function (response) {
                renderProductInfo(response, mode);
            },
            complete: function() {
                $('#cart-modal').modal('show');
            },
            error: handleAjaxError
        });
    }

    function renderProductInfo(result, mode) {
        const product = result[0];
        const price = product.discount_price > 0 ? product.discount_price : product.regular_price;

        renderProductImg(product);
        updatePriceDisplay(product);
        renderColors(product.colors);
        renderAttributes(result[1], result[2]);
        updateFormInputs(product.id, price);

        // Change form ID and action based on mode
        updateFormMode(mode);
    }

    function updateFormMode(mode) {
        if (mode === 'buy') {
            if ($('#product_model_pop_up_addToCart').length) {
                $('#product_model_pop_up_addToCart').attr('id', 'product_model_pop_up_buyNowDirect')
                                .attr('action', '/buy/product')
                                .attr('method', 'get');
                                $('.product_model_pop_up_addToCart').text('Buy Now');
                            }
                $('.product_model_pop_up_addToCart').text('Buy Now');
        } else {
            if ($('#product_model_pop_up_buyNowDirect').length) {
                $('#product_model_pop_up_buyNowDirect').attr('id', 'product_model_pop_up_addToCart')
                                    .attr('action', '<?php echo e(route('add.cart')); ?>')
                                    .attr('method', 'post');
                $('.product_model_pop_up_addToCart').text('Add Cart');
            }
        }
    }

    function renderProductImg(product){
        $('#cart-img').html(`<img src="/uploads/product/${product.image}" class="img-responsive img-fluid"/>`);
    }

    function updatePriceDisplay(product) {
        if(product.discount_price > 0) {
            $('#product_model_pop_up_item_price').html("<del class='text-danger'>" + product.regular_price + "</del>");
            $('#product_model_pop_up_discount_price').text(product.discount_price);
        } else {
            $('#product_model_pop_up_item_price').html(product.regular_price);
            $('#product_model_pop_up_discount_price').text('');
        }
        $('#product_model_pop_up_qty').val(1);
        $('#product_model_pop_up_qty_hidden').val(1);
    }

    function renderColors(colors) {
        let colorsHtml = colors.map(color => 
            `<label class="btn rounded-circle p-3 m-1 color" style="background: ${color.code}">
                <input type="radio" name="color" autocomplete="off" value="${color.slug}">
            </label>`
        ).join('');
        
        $('#product_model_pop_up_colors').html(colorsHtml);
        $('#colors_label').toggleClass('d-none', colors.length === 0);
    }

    function renderAttributes(attributes, attrValues) {
        $('#product_model_pop_up_attributes_all').html(attributes);
        $('#product_model_pop_up_attr_values_hidden').html(attrValues);
    }

    function updateFormInputs(productId, price) {
        $('#product_model_pop_up_id_hidden').val(productId);
        $('#product_model_pop_up_qty_hidden').val(1);
        $('#product_model_pop_up_color_hidden').val('blank');
    }

    // Event listeners
    $(document).on('click', '.productInfoAddToCart', function (e) {
        e.preventDefault();
        updateFormMode('cart');
        productInfoPopUp($(this).data('url'), 'cart');
    });

    $(document).on('click', '.productInfoBuyNow', function (e) {
        e.preventDefault();
        updateFormMode('buy');
        productInfoPopUp($(this).data('url'), 'buy');
    });

    // Color selection
    $(document).on('click', '.color', function(e) {
        e.preventDefault();
        $('.color').removeClass('active');
        $(this).addClass('active');
        
        var selectedColor = $(this).children('input[name="color"]').val();
        $('#product_model_pop_up_color_hidden').val(selectedColor);
        
        updatePriceFromServer('/get/color/price', $('#product_model_pop_up_addToCart, #product_model_pop_up_buyNowDirect'));
    });

    // Attribute selection
    $(document).on('click', '.product_model_pop_up_get_attri_price', function(e) {
        updatePriceFromServer('/get/attr/price', $('#product_model_pop_up_addToCart, #product_model_pop_up_buyNowDirect'));
    });

    function updatePriceFromServer(url, form) {
        let formData = new FormData();
        let allFieldsFilled = true;

        // Check if color is selected
        let selectedColor = $('#product_model_pop_up_color_hidden').val();
        if (selectedColor === 'blank' && $('#colors_label').is(':visible')) {
            allFieldsFilled = false;
        }

        // Check if all visible attributes are selected
        $('.product_model_pop_up_get_attri_price:visible').each(function() {
            let attrName = $(this).attr('name');
            if ($(`input[name="${attrName}"]:checked`).length === 0) {
                allFieldsFilled = false;
            }
        });

        if (allFieldsFilled) {
            formData.append('id', $('#product_model_pop_up_id_hidden').val());
            formData.append('qty', $('#product_model_pop_up_qty_hidden').val());
            formData.append('color', selectedColor);
            
            // Add all attribute inputs
            $('input[name^="attribute_"]').each(function() {
                if (this.value !== '') {
                    formData.append(this.name, this.value);
                }
            });

            // Add all attribute data from hidden div
            $('#product_model_pop_up_attr_values_hidden input[type="hidden"]').each(function() {
                if ($(this).val() !== '') {
                    formData.append($(this).attr('name'), $(this).val());
                }
            });

            // Determine the current mode (cart or buy)
            let currentMode = $('#product_model_pop_up_buyNowDirect').length > 0 ? 'buy' : 'cart';
            formData.append('mode', currentMode);

            // Proceed with AJAX call
            $.ajax({
                type: 'POST',
                url: url,
                data: formData,
                processData: false,
                contentType: false,
                dataType: "JSON",
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                },
                success: function (response) {
                    console.log('updatePriceFromServer', response);
                    if (response) {
                        var currentItemPrice = parseFloat($('#product_model_pop_up_item_price').text());
                        var currentDiscountPrice = parseFloat($('#product_model_pop_up_discount_price').text());
                        var responsePrice = parseFloat(response);
    
                        if (currentDiscountPrice > 0) {
                            // If there's a discount price greater than 0, update only that
                            $('#product_model_pop_up_discount_price').html(responsePrice.toFixed(2));
                        } else {
                            // If no discount price or it's 0, update the item price
                            $('#product_model_pop_up_item_price').html(responsePrice.toFixed(2));
                        }
                    } else {
                        console.error('Invalid response:', response);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('AJAX error:', status, error);
                }
            });
        }
    }

    // Add to cart or Buy Now submission
    $(document).on('submit', '#product_model_pop_up_addToCart, #product_model_pop_up_buyNowDirect', function(e) {
        e.preventDefault();
        console.log('submit', $(this));
        let btn = $(this).find('button[type="submit"]');
        let formData = new FormData(this);
        let isBuyNow = $(this).attr('id') === 'product_model_pop_up_buyNowDirect';
        
        // Remove pre and post text from form data
        let payload = {};
        for (let [key, value] of formData.entries()) {
            let newKey = key.replace('product_model_pop_up_', '').replace('_hidden', '');
            payload[newKey] = value;
        }

        // Add dynamic_price and just value
        let itemPrice = parseFloat($('#product_model_pop_up_item_price').text());
        let discountPrice = parseFloat($('#product_model_pop_up_discount_price').text());
        payload.dynamic_price = discountPrice > 0 ? Math.round(discountPrice) : Math.round(itemPrice);
        payload.just = Math.round(itemPrice);
        
        if (isBuyNow) {
            // Redirect to buy now URL with parameters
            let params = new URLSearchParams(payload).toString();
            window.location.href = '/buy/product?' + params;
        } else {
            // Proceed with AJAX for add to cart
            $.ajax({
                type: 'POST',
                url: $(this).attr('action'),
                data: payload,
                dataType: 'JSON',
                beforeSend: function() {
                    btn.attr('disabled', true);
                },
                success: function (response) {
                    handleAddToCartResponse(response);
                },
                complete: function() {
                    btn.attr('disabled', false);
                },
                error: handleAjaxError
            });
        }
    });

    function handleAddToCartResponse(response) {
        if(response.alert !== 'Congratulations') {
            showToast('Warning', response.message, 'warning');
        } else {
            updateCartCount(response.count);
            <?php if(setting('GTM_DATA_LAYER_STATUS') == 1 || setting('GTM_DATA_LAYER_STATUS') == null): ?>
                gtm_add_to_cart_event_data_layer(response.count, response.subtotal, response.title);
            <?php endif; ?>
            showToast('Congratulations', response.message, 'success');
            $('#cart-modal').modal('hide');
        }
    }

    function updateCartCount(count) {
        $('span#total-cart-count, span#mobile-total-cart-count').text(count);
    }

    function showToast(heading, text, icon) {
        $.toast({
            heading: heading,
            text: text,
            icon: icon,
            position: 'top-right',
            stack: false
        });
    }

    function handleAjaxError(xhr) {
        console.error('AJAX Error:', xhr);
        let errorMessage = 'An error occurred. Please try again.';
        if (xhr.responseJSON && xhr.responseJSON.message) {
            errorMessage = xhr.responseJSON.message;
        }
        showToast('Error', errorMessage, 'error');
    }

    
    // Whishlist
    function submit_payment_form(typeId) {
        event.preventDefault(); // Use 'event' instead of 'e'
        let action = "<?php echo e(route('wishlist.add')); ?>"; // Changed to use Blade syntax for string
        let formElement = document.getElementById('submit_payment_form' + typeId); // Get the form element by ID
        let formData = new FormData(formElement); // Use the form element to create FormData

        $.ajax({
            type: 'POST',
            url: action,
            data: formData,
            processData: false, // Added to prevent jQuery from processing the data
            contentType: false, // Added to prevent jQuery from overriding the content type
            dataType: "JSON",
            beforeSend: function() {
                loader(true);
            },
            success: function(response) {
                responseMessage(response.alert, response.message, response.alert.toLowerCase());
                
                if(response.alert === 'Success' && !response.alreadyAdded){
                    let cartCount = parseInt($('#total-cart-').text());
                    $('#total-cart-').text(cartCount + 1);

                    // btn color
                    $('#wish_' + typeId).css('background', '#1abf92');
                }
                
            },
            complete: function() {
                loader(false);
            },
            error: function(xhr) {
                if (xhr.status === 422) {
                    if (xhr.responseJSON && typeof(xhr.responseJSON.errors) !== 'undefined') {
                        $.each(xhr.responseJSON.errors, function(key, error) {
                            $('small.' + key).text(error);
                            $('#' + key).addClass('is-invalid');
                        });
                        responseMessage('Error', xhr.responseJSON.message, 'error');
                    }
                } else if (xhr.status === 401) {
                    alert('Please login');
                    window.location = '/login';
                } else {
                    responseMessage(xhr.status, xhr.statusText, 'error');
                }
            }
        });
    }


    // response message hande
    function responseMessage(heading, message, icon) {
        $.toast({
            heading: heading,
            text: message,
            icon: icon,
            position: 'top-right',
            stack: false
        });
    }

    // loader handle this function
    function loader(status) {
        if (status == true) {
            $('#loading-image').removeClass('d-none').addClass('d-block');

        } else {
            $('#loading-image').addClass('d-none').removeClass('d-block');
        }
    }

    
    // GTM Data Layer
    <?php if(setting('GTM_DATA_LAYER_STATUS') == 1 || setting('GTM_DATA_LAYER_STATUS') == null): ?>
        function gtm_add_to_cart_event_data_layer(count, subtotal, title){
            console.log('GTM Data Layer: POP up add to cart event');

            var gtm_product_id = $('#product_model_pop_up_id_hidden').val();
            var gtm_product_qty = $('#product_model_pop_up_qty_hidden').val();
            var gtm_product_price = $('#product_model_pop_up_discount_price').text();

            window.dataLayer = window.dataLayer || [];
            window.dataLayer.push({
                event: "add_to_cart",
                ecommerce: {
                    currency: "<?php echo setting('CURRENCY_CODE'); ?>",
                    value: Math.floor(parseFloat(subtotal.replace(/,/g, ''))),
                    items: [
                        {
                            item_id: gtm_product_id,
                            item_name: title,
                            affiliation: "",
                            coupon: "",
                            discount: "",
                            index: "",
                            item_brand: "",
                            item_category: "",
                            item_category2: "",
                            item_category3: "",
                            item_category4: "",
                            item_list_id: "",
                            item_list_name: "",
                            item_variant: "",
                            location_id: "",
                            price: Math.floor(parseFloat(gtm_product_price.replace(/,/g, ''))),
                            quantity: count
                        }
                    ]
                }
            });
        }
    <?php endif; ?>
</script>
<?php $__env->stopPush(); ?><?php /**PATH /home/apleusbj/shopping.apleefix.com/resources/views/components/cart-modal-attri.blade.php ENDPATH**/ ?>