<?php
/**
 * Mageplaza
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Mageplaza.com license that is
 * available through the world-wide-web at this URL:
 * https://www.mageplaza.com/LICENSE.txt
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade this extension to newer
 * version in the future.
 *
 * @category    Mageplaza
 * @package     Mageplaza_QuickCart
 * @copyright   Copyright (c) Mageplaza (https://www.mageplaza.com/)
 * @license     https://www.mageplaza.com/LICENSE.txt
 */
use Hyva\Theme\ViewModel\HeroiconsOutline;
use Hyva\Theme\ViewModel\Modal;
use Mageplaza\QuickCart\Block\AjaxCart\Popup;
use Mageplaza\QuickCart\Helper\QuickViewData;

/** @var Popup $block */
/** @var Modal $modalViewModel */
/** @var QuickViewData $helperData */
$helperData     = $block->getHelperData();
$modalViewModel = $viewModels->require(Modal::class);
$heroicons      = $viewModels->require(HeroiconsOutline::class);
if ($helperData->isAddToCart()): ?>
    <script>
        function configureAjaxCart() {
            return {
                isLoading: false,
                initAjaxCart() {
                    let self = this;
                    let ajaxCartData =  <?=  /* @noEscape */ $block->getAjaxCartData() ?>;
                    document.body.addEventListener('submit', function (e) {
                        if (e.target.matches('form.product_addtocart_form') ||
                            e.target.matches('form#product_addtocart_form')) {

                            if (document.querySelector('.checkout-cart-index')) {
                                return;
                            }

                            if (e.target.closest('.mpquickview-popup #maincontent') && !ajaxCartData.isApplyQV) {
                                return;
                            }

                            if (!e.target.closest('.mpquickview-popup #maincontent') && !ajaxCartData.isApplyPage) {
                                return;
                            }

                            e.preventDefault();
                            let form = e.target;
                            var action = form.getAttribute('action');
                            form.setAttribute('action', action + '?mpajaxcart=1');
                            self.isLoading = true;
                            let formData = new FormData(form);
                            formData.append('form_key', hyva.getFormKey());

                            fetch(form.getAttribute('action'), {
                                method: 'POST',
                                headers: {
                                    "X-Requested-With": "XMLHttpRequest"
                                },
                                body: new FormData(form),
                                mode: "cors",
                                credentials: "include"
                            })
                            .then(response => response.json())
                            .then(res => {
                                if(res.error) {
                                    typeof window.dispatchMessages !== "undefined" && window.dispatchMessages(
                                        [{
                                            type: "error",
                                            text: res?.message[0]
                                        }], 2000
                                    );
                                    return;
                                }
                                if(res.success) {
                                    let closeQuickView = document.querySelector('.wrap-quickview-popup .mfp-close.quick-view-modal');
                                    if(closeQuickView) {
                                        closeQuickView.click()
                                    }
                                    if (res?.html_popup && !res?.show_mini_cart) {
                                        window.dispatchEvent(
                                            new CustomEvent('hyva-modal-show', {detail: {dialog: 'mp-ajaxcart-dialog'}})
                                        );
                                        let popUpAjaxcart       = document.querySelector('#mpajaxcart-popup');
                                        popUpAjaxcart.innerHTML = res.html_popup;
                                        hyva.activateScripts(popUpAjaxcart);
                                        if(ajaxCartData.isAnimate === '1') {
                                            setTimeout(()=>{
                                                flyToCart(popUpAjaxcart);
                                            }, 300);
                                        }
                                    }
                                    if(res?.show_mini_cart) {
                                        window.dispatchEvent(new Event('toggle-cart'));
                                    }
                                    window.dispatchEvent(new CustomEvent('reload-customer-section-data'));
                                }

                            })
                            .catch(error => {
                                console.error('Error:', error);
                            }).finally(()=>{
                                self.isLoading = false;
                            });

                        }
                    });


                    function flyToCart () {
                        let wrapEl = document.querySelector('.wrap-mp-ajaxcart');
                        let imageEl = wrapEl.querySelector('.mp-product-item-photo img');

                        let miniCart = document.querySelector('#menu-cart-icon');


                        const clone = imageEl.cloneNode();
                        clone.classList.add('mp-fly-tocart');
                        document.body.appendChild(clone);
                        // Get the position of the source and destination boxes
                        const imageRect       = wrapEl.getBoundingClientRect();
                        const destinationRect = miniCart.getBoundingClientRect();
                        // Calculate the center positions
                        const startX = imageRect.left;
                        const startY = imageRect.top;
                        const endX   = destinationRect.left;
                        const endY   = destinationRect.top;


                        // Set the initial position of the clone
                        clone.style.left      = `${startX}px`;
                        clone.style.top       = `${startY}px`;
                        clone.style.opacity   = '1';
                        clone.style.transform = 'scale(1)';


                        // Move the clone to the new position, zoom out, and decrease opacity
                        setTimeout(() => {
                            clone.style.opacity   = '0';
                            clone.style.transform = 'scale(0.2)';
                            clone.style.top   = `${endY - clone.offsetHeight * 0.5}px`;
                            clone.style.left   = `${endX - clone.offsetWidth * 0.5 }px`;
                        }, 0); // Start immediately

                        // Remove the clone after the animation ends
                        setTimeout(() => {
                            document.body.removeChild(clone);
                        }, 2000); // Match this duration with the CSS transition duration
                    }
                },
                closeAjaxCartModal() {
                    window.hyva.modal.pop();
                }
            }
        }
    </script>
    <div x-data="Object.assign({}, hyva.modal(), configureAjaxCart())" x-init="initAjaxCart()">
        <?= $block->getChildHtml('loading') ?>
        <?= /** @noEscape */ $modalViewModel->createModal()->withDialogRefName('mp-ajaxcart-dialog')
            ->addDialogClass('pb-10', 'relative', 'wrap-mp-ajaxcart')
            ->removeDialogClass('p-10')->withContent(<<<END_OF_CONTENT
            <div id="mpajaxcart-popup" class="mpajaxcart-popup"></div>
           <button @click="closeAjaxCartModal()" title="Close (Esc)" type="button" class="mfp-close" style="color: black">
{$heroicons->xHtml('w-8 h-8')}
</button>
END_OF_CONTENT
            ) ?>
    </div>

<style>
    .mp-fly-tocart {
        position: fixed;
        z-index: 10000000000000000000000000000000000000000;
        transition: left 2s ease, opacity 2s ease,top 2s ease, transform 2s ease, scale 2s ease ;
    }
</style>
<?php endif; ?>



