<?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\QuickView\Popup;

/** @var Modal $modalViewModel */
/** @var HeroiconsOutline $heroicons */
/** @var Popup $block */

$modalViewModel = $viewModels->require(Modal::class);
$heroicons      = $viewModels->require(HeroiconsOutline::class);
$helperData     = $block->getHelperData();
$iconLabel      = $block->getDisplayLabel();
$popupEffect    = $block->getEffectPopup();
?>

<?php
if ($block->isEnableQuickView() && $block->checkApply() && $helperData->isEnabled()) {
    $infoConfig             = explode(',', $helperData->getQuickViewConfig('popup_info'));
    $infoEditCart           = explode(',', $helperData->getQuickViewConfig('edit_cart_info'));
    $listInfoRemove         = $helperData->listInfoRemove($infoConfig);
    $listInfoEditCartRemove = $helperData->listInfoRemove($infoEditCart); ?>
    <script>
        function configureDataQuickPopup() {
            return {
                isLoading: false,
                initDataQuickPopup() {
                    let self = this;
                    let popupData = <?=  /* @noEscape */ $block->getPopupData() ?>;
                    function initButton (selector) {
                        let listProducts = document.querySelectorAll(selector);
                        listProducts.forEach(product => {
                            product.insertAdjacentHTML('beforeend', popupData.buttonHtml);
                            let productId = product.querySelector('input[name="product"]').value;
                            product.querySelector('.mpquickview-button').addEventListener('click', () => {
                                processQuickView(productId, false, false);
                            })
                        })
                    }

                    function editCart() {
                        var listCart = document.getElementById('shopping-cart-table');
                        if(listCart) {
                            let editCartEls = listCart.querySelectorAll('.action.action-edit');
                            editCartEls.forEach(function (el) {
                                el.addEventListener('click', function (e) {
                                    e.preventDefault();
                                    var href = el.getAttribute('href');
                                    self.isLoading = true;
                                    fetch(href + '?mpquickview=1', {
                                        method: 'GET',
                                        headers: {
                                            'Content-Type': 'application/json',
                                            'X-Requested-With': 'XMLHttpRequest'
                                        }
                                    })
                                    .then(response => {
                                        if (!response.ok) {
                                            throw new Error('Network response was not ok');
                                        }
                                        return response.json();
                                    })
                                    .then(data => {
                                        if(data.html_content) {
                                            window.dispatchEvent(
                                                new CustomEvent('hyva-modal-show', {detail: {dialog: 'mp-quickview-dialog'}})
                                            );
                                            let popUp       = document.querySelector('#popup-quickview');
                                            popUp.classList.add('mpquickview-popup-editcart');
                                            popUp.classList.remove('mpquickview-popup');

                                            popUp.innerHTML = data.html_content;
                                            hyva.activateScripts(popUp);
                                        }
                                    })
                                    .catch(error => {
                                        console.error(error);
                                    }).finally(()=>{
                                        self.isLoading = false;
                                        window.dispatchEvent(new Event('clear-messages'));

                                    });
                                })
                            })
                        }
                    }

                    function processQuickView (productId, listCart, itemId) {
                        var urlOrigin = popupData.url,
                            type      = 'POST',
                            url;
                        if (listCart && itemId) {
                            type = 'GET';
                            url  = popupData.urlCart + 'id/' + itemId + '/product_id/' + productId + '?mpquickview=1';
                        } else {
                            url = urlOrigin + 'id/' + productId + '?mpquickview=1';
                        }

                        let formData = new FormData();
                        formData.append('productId', productId);
                        self.isLoading = true;
                        fetch(url, {
                            method: type,
                            headers: {
                                "X-Requested-With": "XMLHttpRequest"
                            },
                            body: formData,
                            mode: "cors",
                            credentials: "include"
                        })
                        .then(response => {
                            if (!response.ok) {
                                throw new Error('Network response was not ok');
                            }
                            return response.text();
                        })
                        .then(data => {
                            window.dispatchEvent(
                                new CustomEvent('hyva-modal-show', {detail: {dialog: 'mp-quickview-dialog'}})
                            );

                            let popUp    = document.querySelector('#popup-quickview');
                            const parser = new DOMParser();
                            const doc    = parser.parseFromString(data, 'text/html');

                            const mainContent = doc.querySelector('#maincontent');
                            if (mainContent) {
                                ['social-login-popup', 'my-dialog-social-login', 'test'].forEach(id => {
                                    const el = mainContent.querySelector(`#${id}`);
                                    if (el) el.remove();
                                });
                            }
                            const cleanedHtml = mainContent ? mainContent.outerHTML : data;
                            popUp.innerHTML   = cleanedHtml;

                            hyva.activateScripts(popUp);
                            if (!popupData.isApplyQV || document.querySelector('.checkout-cart-index')) {
                                addToCartInPopup();
                            }

                        })
                        .catch(error => {
                            console.error('There was a problem with the fetch operation:', error);
                        }).finally(() => {
                            self.isLoading = false;
                            window.dispatchEvent(new Event('clear-messages'));

                        });
                    }

                    function addToCartInPopup () {
                        var form = document.querySelector('.mpquickview-popup #product_addtocart_form');
                        if (form) {
                            var action = form.getAttribute('action');
                            form.setAttribute('action', action + '?mpquickview=1');
                            form.addEventListener('submit', function (e) {
                                    e.preventDefault();
                                self.isLoading = true;
                                    fetch(form.getAttribute('action'), {
                                        method: 'POST',
                                        headers: {
                                            "X-Requested-With": "XMLHttpRequest"
                                        },
                                        body: new FormData(form),
                                        mode: "cors",
                                        credentials: "include"
                                    })
                                    .then(response => {

                                        return response.json()
                                    }).then((res)=>{
                                        if(res?.backUrl) {
                                            window.dispatchEvent(new Event('clear-messages'));
                                            return;
                                        }
                                        window.dispatchEvent(new CustomEvent('reload-customer-section-data'));

                                        if(Array.isArray(res) && res.length === 0) {
                                            if(document.querySelector('.checkout-cart-index')) {
                                                window.dispatchEvent(new Event('clear-messages'));
                                                window.location.reload();
                                            }
                                        }
                                    })
                                    .catch(error => {
                                        console.error('Error:', error);
                                    }).finally(()=>{
                                        self.isLoading = false;
                                        setTimeout(()=>{
                                            window.dispatchEvent(new Event('clear-messages'));
                                        }, 3000)
                                    });
                                }
                            );
                        }

                    }

                    editCart();
                    initButton('.products > ul > li > form');
                    initButton('.product-slider form');
                },
                closeQuickViewModal() {
                    const modal = document.querySelector('.wrap-quickview-popup');
                    modal.classList.remove('<?=  /* @noEscape */ $popupEffect ?>-appear');
                    modal.classList.add('<?=  /* @noEscape */ $popupEffect ?>-disappear');
                    window.hyva.modal.pop();
                    setTimeout(() => {
                        modal.classList.remove('<?=  /* @noEscape */ $popupEffect ?>-disappear');
                        modal.classList.add('<?=  /* @noEscape */ $popupEffect ?>-appear');
                    }, 200);
                }
            }
        }
    </script>
    <div x-data="Object.assign({}, hyva.modal(), configureDataQuickPopup())" x-init="initDataQuickPopup()" >
        <?= $block->getChildHtml('loading_quickview') ?>
        <?= /** @noEscape */
        $modalViewModel->createModal()->withDialogRefName('mp-quickview-dialog')
            ->addDialogClass('pb-10 relative wrap-quickview-popup' . ' ' . $popupEffect . '-appear')
            ->removeDialogClass('p-10')->withContent(<<<END_OF_CONTENT
            <div id="popup-quickview" class="mpquickview-popup"></div>
           <button @click="closeQuickViewModal()" title="Close (Esc)" type="button" class="mfp-close quick-view-modal" style="color: black">{$heroicons->xHtml('w-8 h-8')}</button>

END_OF_CONTENT
            ) ?>
    </div>
    <style>
        .mpquickview-button {
            display: none;
            position: absolute;
            z-index: 49;
            width: 100%;
            height: 100%;
            top: 30%;
            left: 50%;
            transform: translateX(-50%) translateY(-50%) rotate(0deg);
            cursor: pointer;
        }

        .mpquickview-button img {
            width: 40px !important;
            height: 40px !important;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translateX(-50%) translateY(-50%) rotate(0deg);
            z-index: 10;
        }


        .products > ul > li > form {
            position: relative;
        }

        .products > ul > li > form:hover .mpquickview-button {
            display: block;
        }

        .products > ul > li > form:hover .product-item-photo img {
            opacity: 0.5;
        }

        .product-slider form {
            position: relative;
        }

        .product-slider form:hover .mpquickview-button {
            display: block;
        }

        .product-slider form:hover .product-item-photo img {
            opacity: 0.5;
        }

        #popup-quickview {
            min-height: 400px;
            max-width: 950px;
            max-height: 750px;
        }

        #mpajaxcart-popup {
            min-height: 400px;
            max-width: 950px;
            max-height: 750px;
        }

        @media (min-width: 768px) {
            #popup-quickview .columns .column.main {
                grid-column-start: 1 !important;
                grid-column: span 4/span 4;
            }
            .products.mode-list > ul > li > form .mpquickview-button {
                width: 30%;
                top: 50%;
                left: 18%;
            }
        }


    </style>
    <style>
        <?php if ($iconLabel): ?>
        .mpquickview-button {
            margin-top: 85%;
            top: 0 !important;
        }

        @media (min-width: 768px) {
            .products.mode-list > ul > li > form .mpquickview-button {
                width: 30%;
                bottom: 10% !important;
                margin-top: 0 !important;
                top: unset !important;
                left: 18%;
            }
        }

        .mpquickview-label {
            opacity: 0.7;
            border-radius: 4px;
            width: 91% !important;
        }
        .mpquickview-label {
            color: <?= /** @noEscape */ $block->getLabelColor() ? : '#ffffff' ?>;
            background: <?= /** @noEscape */ $block->getBackgroundColor() ? : '#0099e5' ?>
        }
        .mpquickview-label img {
            margin-left: -28%;
            width: 8% !important;
        }
        .mpquickview-label {
            text-align: center;
            padding: 10px;
            width: 40%;
            font-weight: 600;
            position: absolute;
            left: 50%;
            transform: translateX(-50%) translateY(15%) rotate(0deg);
            z-index: 10;
        }
        <?php endif ?>
        /** QUICK VIEW POPUP */

        <?php if (in_array('product_description', $listInfoRemove, false)): ?>
        .mpquickview-popup .product-description {
            display: none !important;
        }

        <?php endif ?>
        <?php if (in_array('upsales_product', $listInfoRemove, false)): ?>
        .mpquickview-popup .upsell-product-slider {
            display: none !important;
        }

        <?php endif ?>
        <?php if (in_array('related_product', $listInfoRemove, false)): ?>
        .mpquickview-popup .related-product-slider {
            display: none !important;
        }

        .mpquickview-popup #related\.post\.tab {
            display: none !important;
        }

        <?php endif ?>


        <?php if (in_array('product_img_thumbnail', $listInfoRemove, false)): ?>
        .mpquickview-popup #thumbs {
            display: none !important;
        }

        <?php endif ?>

        <?php if (in_array('product_img', $listInfoRemove, false)
         && in_array('product_img_thumbnail', $listInfoRemove, false)): ?>
        .mpquickview-popup #gallery {
            display: none !important;
        }

        .mpquickview-popup #gallery {
            display: none !important;
        }

        <?php endif; ?>

        <?php if (in_array('stock_status', $listInfoRemove, false)): ?>
        .mpquickview-popup .stock.available, .mpquickview-popup .stock.unavailable {
            display: none !important;
        }

        <?php endif ?>

        <?php if (in_array('add_new_review', $listInfoRemove, false)): ?>
        .mpquickview-popup #review-form {
            display: none !important;
        }

        <?php endif ?>

        <?php if (in_array('review', $listInfoRemove, false)): ?>
        .mpquickview-popup #customer-review-list {
            display: none !important;
        }

        <?php endif ?>


        /** Edit cart popup */

        <?php if (in_array('product_description', $listInfoEditCartRemove, false)): ?>
        .mpquickview-popup-editcart .product-description {
            display: none !important;
        }

        <?php endif ?>
        <?php if (in_array('upsales_product', $listInfoEditCartRemove, false)): ?>
        .mpquickview-popup-editcart .upsell-product-slider {
            display: none !important;
        }

        <?php endif ?>
        <?php if (in_array('related_product', $listInfoEditCartRemove, false)): ?>
        .mpquickview-popup-editcart .related-product-slider {
            display: none !important;
        }

        .mpquickview-popup-editcart #related\.post\.tab {
            display: none !important;
        }

        <?php endif ?>


        <?php if (in_array('product_img_thumbnail', $listInfoEditCartRemove, false)): ?>
        .mpquickview-popup-editcart #thumbs {
            display: none !important;
        }

        <?php endif ?>

        <?php if (in_array('product_img', $listInfoEditCartRemove, false)
         && in_array('product_img_thumbnail', $listInfoEditCartRemove, false)): ?>
        .mpquickview-popup-editcart #gallery {
            display: none !important;
        }

        .mpquickview-popup-editcart #gallery {
            display: none !important;
        }

        <?php endif; ?>

        <?php if (in_array('stock_status', $listInfoEditCartRemove, false)): ?>
        .mpquickview-popup-editcart .stock.available, .mpquickview-popup-editcart .stock.unavailable {
            display: none !important;
        }

        <?php endif ?>

        <?php if (in_array('add_new_review', $listInfoEditCartRemove, false)): ?>
        .mpquickview-popup-editcart #review-form {
            display: none !important;
        }

        <?php endif ?>

        <?php if (in_array('review', $listInfoEditCartRemove, false)): ?>
        .mpquickview-popup-editcart #customer-review-list {
            display: none !important;
        }

        <?php endif ?>
    </style>
    <style>
        @keyframes newspaperAnimation {
            0% {
                opacity: 0;
                transform: scale(0) rotate(360deg);
            }
            100% {
                opacity: 1;
                transform: scale(1) rotate(0deg);
            }
        }

        .mfp-newspaper-appear {
            animation: newspaperAnimation 0.5s ease-out forwards;
        }

        @keyframes newspaperAnimationOut {
            0% {
                opacity: 1;
                transform: scale(1) rotate(0deg);


            }
            100% {
                opacity: 0;
                transform: scale(0) rotate(360deg);
            }
        }

        .mfp-newspaper-disappear {
            animation: newspaperAnimationOut 0.5s ease-out forwards;
        }


        @keyframes zoomInAnimation {
            0% {
                opacity: 0;
                transform: scale(0);
            }
            100% {
                opacity: 1;
                transform: scale(1);
            }
        }

        .mfp-zoom-in-appear {
            animation: zoomInAnimation 0.5s ease-out forwards;
        }


        @keyframes zoomInAnimationOut {
            0% {
                opacity: 1;
                transform: scale(1);

            }
            100% {

                opacity: 0;
                transform: scale(0);
            }
        }

        .mfp-zoom-in-disappear {
            animation: zoomInAnimationOut 0.5s ease-out forwards;
        }

        @keyframes slideInLeftAnimation {
            0% {
                opacity: 0;
                transform: translateX(-10%);
            }
            100% {
                opacity: 1;
                transform: translateX(0);
            }
        }

        .mfp-move-horizontal-appear {
            animation: slideInLeftAnimation 0.5s ease-out forwards;
        }

        @keyframes slideInLeftAnimationOut {
            0% {
                opacity: 1;
                transform: translateX(0);

            }
            100% {
                opacity: 0;
                transform: translateX(20%);
            }
        }

        .mfp-move-horizontal-disappear {
            animation: slideInLeftAnimationOut 0.5s ease-out forwards;
        }


        @keyframes fadeInDownAnimation {
            0% {
                opacity: 0;
                transform: translateY(-20%);
            }
            100% {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .mfp-move-from-top-appear {
            animation: fadeInDownAnimation 0.5s ease-out forwards;
        }


        @keyframes fadeInDownAnimationOut {
            0% {
                opacity: 1;
                transform: translateY(0);

            }
            100% {

                opacity: 0;
                transform: translateY(20%);
            }
        }

        .mfp-move-from-top-disappear {
            animation: fadeInDownAnimationOut 0.5s ease-out forwards;
        }


        @keyframes flipInYAnimation {
            0% {
                opacity: 0;
                transform: perspective(400px) rotateY(-90deg);
            }
            100% {
                opacity: 1;
                transform: perspective(400px) rotateY(0);
            }
        }

        .mfp-3d-unfold-appear {
            animation: flipInYAnimation 0.5s ease-out forwards;
        }

        @keyframes flipInYAnimationOut {
            0% {
                opacity: 1;
                transform: perspective(400px) rotateY(0);

            }
            100% {

                opacity: 0;
                transform: perspective(400px) rotateY(90deg);
            }
        }

        .mfp-3d-unfold-disappear {
            animation: flipInYAnimationOut 0.5s ease-out forwards;
        }

        @keyframes zoomOutAnimation {
            0% {
                opacity: 0;
                transform: scale(2);
            }
            100% {
                opacity: 1;
                transform: scale(1);
            }
        }

        .mfp-zoom-out-appear {
            animation: zoomOutAnimation 0.5s ease-out forwards;
        }

        @keyframes zoomOutAnimationOut {
            0% {
                opacity: 1;
                transform: scale(1);

            }
            100% {

                opacity: 0;
                transform: scale(2);
            }
        }

        .mfp-zoom-out-disappear {
            animation: zoomOutAnimationOut 0.5s ease-out forwards;
        }
    </style>
<?php } ?>
<style type="text/css">
    button.action.primary.btn-view-cart, button.action.primary.btn-proceed-checkout, button.action.primary.continue-shopping {
        font-size: 1rem;
        padding: 10px;
        border: none;
        width: 40%;
        height: 100%;
        margin-left: 5%;
    }

    button.action.primary.continue-shopping {
        background: <?=  /* @noEscape  */ $helperData->getContinueButtonColor() ?> !important;
    }

    button.action.primary.btn-view-cart {
        background: <?=  /* @noEscape  */ $helperData->getViewCartButtonColor() ?> !important;
    }

    button.action.primary.btn-proceed-checkout {
        background: <?= /* @noEscape  */ $helperData->getCheckoutButtonColor() ?> !important;
    }

    .mpajaxcart-success-action button {
        color: <?= /* @noEscape  */ $helperData->getButtonTextColor() ?>
    }

    <?= /* @noEscape  */ $helperData->getCustomCSS() ?>
</style>

