<?php
/**
 * BSS Commerce Co.
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the EULA
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://bsscommerce.com/Bss-Commerce-License.txt
 *
 * @category  BSS
 * @package   Bss_AjaxCart
 * @author    Extension Team
 * @copyright Copyright (c) 2022 BSS Commerce Co. ( http://bsscommerce.com )
 * @license   http://bsscommerce.com/Bss-Commerce-License.txt
 */

declare(strict_types=1);

use Bss\AjaxCart\Block\Ajax\Template;
use Magento\Framework\Escaper;

/** @var Template $block */
/** @var Escaper $escaper */

?>
<script>
    function initAjaxSuggest() {
        return {
            action: "<?= $escaper->escapeJs($block->getUrl('ajaxcart')) ?>",
            init() {
                const splideOptions = {
                    type: 'loop',
                    perPage: 3,
                    pagination: false,
                    breakpoints: {
                        1024: {
                            perPage: 3
                        },
                        768: {
                            perPage: 2
                        },
                        480: {
                            perPage: 1
                        },
                    },
                    flickMaxPages: 1,
                    updateOnMove: true,
                    autoplay: true,
                    perMove: 1,
                    focus: 'center'
                };
                this.splide = new Splide('.splide', splideOptions);
                this.splide.mount();
            },
            addToCart(postData) {
                let formData = postData.data;

                if (!formData?.form_key) {
                    formData.form_key = hyva.getFormKey();
                }
                formData.id = formData.product;

                var requestConfigs = {
                    method: "POST",
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    mode: 'cors',
                    credentials: 'include',
                    dataType: 'json',
                    body: new URLSearchParams(formData)
                };
                const addToCartRequesting = fetch(this.action, requestConfigs);
                addToCartRequesting
                    .then(response => responseSerialize(response))
                    .then(response => {
                        if (response.backUrl) {
                            window.location.href = response.backUrl;
                        } else if (response?.messages && !response.view) {
                            response.messages.map((msg) => {
                                if (msg.type !== 'error') {
                                    return null;
                                }
                                window.dispatchMessages([
                                    {
                                        type: msg.type,
                                        text: msg.text
                                    }
                                ], 3000);
                            });
                        } else if (response.error && response.view) {
                            window.parent.postMessage('ajax-cart-popup-close','*');
                            window.dispatchEvent(
                                new CustomEvent(
                                    "ajax-cart-popup-iframe",
                                    {
                                        detail: {
                                            open: true,
                                            url: response.url,
                                        }
                                    }
                                )
                            );
                        } else if (response.popup) {
                            const popupContent = document.getElementById("popup-content");
                            popupContent.textContent ="";
                            popupContent.insertAdjacentHTML("beforeend", response.popup);
                            let scripts = popupContent.getElementsByTagName("script");
                            while (scripts.length) {
                                const script = scripts[0];
                                script.parentNode.removeChild(script);
                                const newScript = document.createElement("script");
                                newScript.setAttribute('type', 'text/javascript');

                                const scriptId = script.getAttribute('id');
                                if (scriptId) {
                                    const existedSript = document.getElementById(scriptId);
                                    if (existedSript) {
                                        continue;
                                    }
                                    newScript.setAttribute('id', scriptId);
                                }
                                if (script.src) {
                                    newScript.src = script.src;
                                } else if (script.textContent) {
                                    newScript.textContent = script.textContent;
                                } else if (script.innerText) {
                                    newScript.innerText = script.innerText;
                                }
                                document.body.appendChild(newScript);
                            }
                            window.parent.postMessage('ajax-cart-message','*');
                            window.dispatchEvent(new CustomEvent("ajax-cart-popup"));
                        }
                        window.dispatchEvent(new CustomEvent("reload-customer-section-data"));
                    }).catch(err => {
                    window.dispatchMessages([
                        {
                            type: 'error',
                            text: err
                        }
                    ], 3000);
                });
                return false;
            }
        }
    }
</script>
