<?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\Model\ViewModelRegistry;
use Hyva\Theme\ViewModel\CurrentProduct;
use Hyva\Theme\ViewModel\HeroiconsOutline;
use Hyva\Theme\ViewModel\ProductCompare;
use Magento\Catalog\Model\Product;
use Magento\Framework\Escaper;
use Magento\Framework\View\Element\Template;

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

/** @var ProductCompare $compareViewModel */
$compareViewModel = $viewModels->require(ProductCompare::class);

/** @var HeroiconsOutline $heroicons */
$heroicons = $viewModels->require(HeroiconsOutline::class);

/** @var CurrentProduct $currentProduct */
$currentProduct = $viewModels->require(CurrentProduct::class);

/** @var Product $product */
$product = $currentProduct->get();

if (!$product->getId() || !$compareViewModel->showOnProductPage()) {
    return;
}

$ajaxCart= $block->getLayout()->createBlock('Mageplaza\QuickCart\Block\AjaxCart\Popup');
$isAjaxCompare =$this->helper('Mageplaza\QuickCart\Helper\QuickViewData')->isAjaxCompare();
?>
<script>
    function initCompareOnProductView() {
        return {
            addToCompare: function (productId) {
                let optionsData = <?= /** @noEscape */ $ajaxCart->wishListAndCompareData() ?>;
                let isAjaxCompare = <?=  /** @noEscape */  json_encode($isAjaxCompare) ?>;

                const formKey = hyva.getFormKey();
                const postUrl = BASE_URL + 'catalog/product_compare/add/';

                fetch(postUrl + "?" + "form_key=" + formKey + "&product=" + productId + "&uenc=" + hyva.getUenc(), {
                    "headers": {
                        "content-type": "application/json",
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    "method": "POST",
                    "mode": "cors",
                    "credentials": "include"
                }).then(function (response) {
                    if (response.redirected) {
                        window.location.href = response.url;
                    } else if(response.ok) {
                        if (isAjaxCompare) {
                            const isQuickView = document.querySelector('.mpquickview-popup #maincontent');
                            if ((isQuickView && !optionsData.isApplyQV) ||
                                (!isQuickView && !optionsData.isApplyPage)) {
                                window.location.reload();
                                return;
                            }
                            return response.json();
                        }
                        window.location.reload();
                    } else {
                        typeof window.dispatchMessages !== "undefined" && window.dispatchMessages(
                            [{
                                type: "warning",
                                text: "<?= $escaper->escapeHtml(__('Could not add item to compare.')) ?>"
                            }], 5000
                        );
                    }
                }).then(response => {
                    if (!response) {
                        return;
                    }
                    const reloadCustomerDataEvent = new CustomEvent("reload-customer-section-data");
                    window.dispatchEvent(reloadCustomerDataEvent);
                }).catch(function (error) {
                    typeof window.dispatchMessages !== "undefined" && window.dispatchMessages(
                        [{
                            type: "error",
                            text: error
                        }], 5000
                    );
                });
            }
        };
    }
</script>

<button x-data="initCompareOnProductView()"
        @click.prevent="addToCompare(<?= (int)$product->getId() ?>)"
        title="<?= $escaper->escapeHtmlAttr(__('Add to Compare')) ?>"
        aria-label="<?= $escaper->escapeHtmlAttr(__('Add to Compare')) ?>"
        id="add-to-compare"
        class="rounded-full w-10 h-10 bg-gray-200 p-0 border-0 inline-flex items-center
            justify-center text-gray-500 hover:text-yellow-500 ml-2"
        data-addto="compare"
>
    <?= $heroicons->scaleHtml("w-5 h-5", 25, 25) ?>
</button>
