<?php $__env->startPush('css'); ?>
    <style>
        .single_value-plus, .single_value-minus{
            height: 40px;
            line-height: 24px;
            width: 40px;
            margin-right: 3px;
            display: inline-block;
            cursor: pointer;
            position: relative;
            font-size: 18px;
            color: #fff;
            text-align: center;
            -webkit-user-select: none;
            -moz-user-select: none;
            border: 1px solid #b2b2b2;
            vertical-align: bottom;
        }
        .single_value-plus:before,
        .single_value-minus:before {
            content: "";
            width: 13px;
            height: 2px;
            background: #000;
            left: 50%;
            margin-left: -7px;
            top: 50%;
            margin-top: -.5px;
            position: absolute;
        }
        .single_value-plus:after {
            content: "";
            height: 13px;
            width: 2px;
            background: #000;
            left: 50%;
            margin-left: -1.4px;
            top: 50%;
            margin-top: -6.2px;
            position: absolute;
        }
    </style>
<?php $__env->stopPush(); ?>
<?php $__env->startPush('js'); ?>
<script>
    $(document).on('click', '.single_value-plus', function(e) {
        e.preventDefault();
        var divUpd = $(this).parent().find('.value'),
        newVal = parseInt(divUpd.val(), 10) + 1;
        divUpd.val(newVal);
        $('#qty').val(newVal);
        singleUpdatePriceFromServer('/get/attr/price', $('#productSubmitForm'));
    });

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


    // Attribute | Color | Value update| Price Update
    function singleHiddenValueInputID(attribute_slug, value) {
        
        if (attribute_slug == 'single_color') {
            $('#single_color').val(value);
        } else {
            $('#single_attr_' + attribute_slug).val(value);
        }

        var form = $('#productSubmitForm');
        var allFieldsFilled = true;
        var hasColorField = $('#single_color').length > 0;
        var hasAttributes = $('[id^="single_attr_"]').length > 0;

        if (hasColorField) {
            if ($('#single_color').val() === 'blank') {
                allFieldsFilled = false;
            }
        }

        if (hasAttributes) {
            $('[id^="single_attr_"]').each(function() {
                if ($(this).val() === '' || $(this).val() === 'blank') {
                    allFieldsFilled = false;
                    return false; // Break the loop
                }
            });
        }

        if (allFieldsFilled && !window.updateInProgress) {
            window.updateInProgress = true;

            // console.log('Form data:');
            // form.find('input[type="hidden"]').each(function() {
            //     console.log($(this).attr('name') + ': ' + $(this).val());
            // });

            // Send data through singleUpdatePriceFromServer
            singleUpdatePriceFromServer('/get/attr/price', form).then(() => {
                window.updateInProgress = false;
            });
        }

        return true; // Allow further processing
    }
    // Price update from server by Attribute | Color | Value
    function singleUpdatePriceFromServer(url, form) {
        let formData = new FormData(form[0]);
        
        // Determine the current mode (cart or buy)
        let currentMode = $('#single_buy_now').length > 0 ? 'buy' : 'cart';
        formData.append('mode', currentMode);

        return $.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('singleUpdatePriceFromServer', response);
                if (response) {
                    var currentItemPrice = parseFloat($('#dynamic_price').text());
                    var responsePrice = parseFloat(response);
                    $('#dynamic_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
    $('#single_add_to_cart, #single_buy_now').on('click', function(e) {
        console.log('Add to cart or Buy Now clicked');
        let isBuyNow = $(this).attr('id') === 'single_buy_now';
        let form = $(this).closest('form');

        // Check color selection
        if ($('#single_color').val() == 'blank') {
            if (!checkColor(e)) {
                e.preventDefault(); // Prevent form submission if validation fails
                return; // Exit the function if validation fails
            }
        }

        // Check attribute selection
        let hasAttributes = $('[id^="single_attr_"]').length > 0;
        if (hasAttributes) {
            if (!checkAttributes(e)) {
                e.preventDefault(); // Prevent form submission if validation fails
                return; // Exit the function if validation fails
            }
        }

        if (isBuyNow) {
            // Redirect to buy now URL with form data
            e.preventDefault(); // Prevent default form submission
            let formData = new FormData(form[0]);
            let dynamicPrice = parseFloat($('#dynamic_price').text());
            // formData.append('dynamic_price', Math.round(dynamicPrice));
            // formData.append('just', Math.round(dynamicPrice));
            formData.append('dynamic_price', dynamicPrice.toFixed(2));
            formData.append('just', dynamicPrice.toFixed(2));
            let params = new URLSearchParams(formData).toString();
            window.location.href = '/buy/product?' + params;
        } else {
            // Proceed with AJAX for add to cart
            $.ajax({
                type: 'POST',
                url: '/add/cart',
                data: form.serialize(),
                dataType: 'JSON',
                beforeSend: function() {
                    $(e.target).attr('disabled', true);
                },
                success: function (response) {
                    handleAddToCartResponse(response);
                    // console.log('single_product_0_js.blade.php add to cart response', response);
                    $('span#total-cart-count').text(response.count);
                    $('span#mobile-total-cart-count').text(response.count);
                    $('#total-cart-amount').text(response.count);
                    $('#response-message').html(message);
                },
                complete: function() {
                    $(e.target).attr('disabled', false);
                },
                error: handleAjaxError
            });
        }
    });

    // Color check
    function checkColor(e) {
        let isValid = true; // Flag to track validation status

        if (!$('input[type="radio"][name="color"]:checked').length) {
            showAlert('Please select a color.', e, 'req_alert_color');
            isValid = false; // Set flag to false if validation fails
        }

        return isValid; // Return the validation status
    }

    // Attribute check
    function checkAttributes(e) {
        let isValid = true; // Flag to track validation status

        // Check other attributes
        $('[id^="single_attr_"]').each(function() {
            var attrName = $(this).attr('id').replace('single_attr_', '');
            if ($(this).val() === '' || $(this).val() === 'blank') {
                
                let refinedAttrName = attrName.replace(/[-\d]/g, ' ').replace(/\b\w/g, char => char.toUpperCase()).trim();
                showAlert('Please select ' + refinedAttrName + '.', e, 'req_alart_' + attrName);
                isValid = false; // Set flag to false if validation fails
            }
        });

        return isValid; // Return the validation status
    }

    // Show alert
    function showAlert(message, e, elementId) {
        var alertElement = $('#' + elementId);
        alertElement.html(message).addClass('alert alert-danger');
        e.preventDefault();
        
        setTimeout(function() {
            alertElement.removeClass('alert alert-danger').html('');
        }, 5000);
    }
</script>
<?php $__env->stopPush(); ?><?php /**PATH /home/apleusbj/public_html/resources/views/frontend/single_product_0_js.blade.php ENDPATH**/ ?>