<?php
/**
 * Hyvä Themes - https://hyva.io
 * Copyright © Hyvä Themes 2020-present. All rights reserved.
 * This product is licensed per Magento install
 * See https://hyva.io/license
 */

declare(strict_types=1);

use Hyva\Theme\Model\ViewModelRegistry;
use Hyva\Theme\ViewModel\CurrentProduct;
use Hyva\Theme\ViewModel\HeroiconsSolid;
use Hyva\Theme\ViewModel\Wishlist;
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 Wishlist $wishlistViewModel */
$wishlistViewModel = $viewModels->require(Wishlist::class);

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

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

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

if (!$product->getId() || !$wishlistViewModel->isEnabled()) {
    return;
}
/**
 * When visiting wishlist/index/configure, the current class is Magento\Wishlist\Block\Item\Configure
 * In that case we take the form parameters from the existing wishlist item
 */
$updateParams = $block->getUpdateParams() ?: null;
$uniqueId = '_' . uniqid();
?>
<script>
    function initWishlist<?= /** @noEscape */ $uniqueId ?>() {
        return {
            addToWishlist(productId) {

                const postParams = <?php if ($updateParams): ?>
                    <?= /* @noEscape */ $updateParams ?>
                <?php else: ?>
                {
                    action: BASE_URL + "wishlist/index/add/",
                    data: {
                        product: productId,
                        uenc: hyva.getUenc()
                    }
                }
                <?php endif; ?>

                postParams.data['form_key'] = hyva.getFormKey();
                postParams.data['qty'] = document.getElementById(`qty[${productId}]`)
                    ? document.getElementById(`qty[${productId}]`).value || 1
                    : 1;

                let postData = Object.keys(postParams.data).map(key => {
                    return `${key}=${postParams.data[key]}`;
                }).join('&');

                // take the all the input fields that configure this product
                // includes custom, configurable, grouped and bundled options
                Array.from(document.querySelectorAll(
                    '[name^=options], [name^=super_attribute], [name^=bundle_option], [name^=super_group], [name^=links]')
                ).map(input => {
                    if (input.type === "select-multiple") {
                        Array.from(input.selectedOptions).forEach(option => {
                            postData += `&${input.name}=${option.value}`
                        })
                    } else {
                        // skip "checkable inputs" that are not checked
                        if(!(['radio', 'checkbox', 'select'].includes(input.type) && !input.checked)) {
                            postData += `&${input.name}=${input.value}`
                        }
                    }
                });
                fetch(postParams.action, {
                    "headers": {
                        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
                    },
                    "body": postData,
                    "method": "POST",
                    "mode": "cors",
                    "credentials": "include"
                }).then((response) => {
                    if (response.redirected) {
                        window.location.href = response.url;
                    } else if (response.ok) {
                        return response.json();
                    } else {
                        typeof window.dispatchMessages !== "undefined" && window.dispatchMessages(
                            [{
                                type: "warning",
                                text: "<?= $escaper->escapeHtml(__('Could not add item to wishlist.')) ?>"
                            }], 5000
                        );
                    }
                }).then((response) => {
                    if (!response) {
                        return;
                    }
                    typeof window.dispatchMessages !== "undefined" && window.dispatchMessages(
                        [{
                            type: (response.success) ? "success" : "error",
                            text: (response.success)
                                ? "<?= $escaper->escapeHtml(
                                    __("%1 has been added to your Wish List.", __("Product"))
                                ) ?>"
                                : response.error_message
                        }], 5000
                    );
                    const reloadCustomerDataEvent = new CustomEvent("reload-customer-section-data");
                    window.dispatchEvent(reloadCustomerDataEvent);
                }).catch((error) => {
                    typeof window.dispatchMessages !== "undefined" && window.dispatchMessages(
                        [{
                            type: "error",
                            text: error
                        }], 5000
                    );
                });
            }
        }
    }
</script>
<div class="relative w-[51px] h-[51px]">
<button x-data="initWishlist<?= /** @noEscape */ $uniqueId ?>()"
        x-defer="intersect"
        @click.prevent="addToWishlist(<?= (int)$product->getId() ?>)"
        title="<?= $escaper->escapeHtmlAttr(
            ($updateParams) ? __('Update Wish List') : __('Add to Wish List')
        ) ?>"
        aria-label="<?= $escaper->escapeHtmlAttr(
            ($updateParams) ? __('Update Wish List') : __('Add to Wish List')
        ) ?>"
        id="add-to-wishlist"
        class=" group relative rounded-md p-0 border-0 inline-flex items-center justify-center text-gray-500 hover:text-red-600 "
        data-addto="wishlist"
>
    <svg xmlns="http://www.w3.org/2000/svg" width="51" height="51" viewBox="0 0 52 51" fill="none">
        <rect x="0.435059" y="6.10352e-05" width="51.5525" height="51" rx="7" fill="#FCEFF1" fill-opacity="0.94"/>
        <path d="M34.2617 13.5001C38.6354 13.5003 41.9746 17.028 41.9746 21.8038C41.9745 24.359 40.9427 26.5319 39.0547 28.7833C37.154 31.0497 34.4246 33.3506 31.0791 36.168C29.9463 37.1221 28.6602 38.2049 27.3232 39.3604C27.239 39.4333 27.1297 39.4746 27.0146 39.4747C26.8995 39.4747 26.7903 39.4333 26.7061 39.3604H26.7051C25.3683 38.2052 24.0823 37.1225 22.9502 36.169C19.6043 33.3512 16.8745 31.0499 14.9736 28.7833C13.0856 26.5319 12.0548 24.3589 12.0547 21.8038C12.0547 17.0279 15.3938 13.5001 19.7676 13.5001C21.3336 13.5001 22.7658 13.9882 24.0361 14.959C25.2618 15.8958 26.0869 17.0971 26.5771 17.9825L27.0146 18.7725L27.4521 17.9825C27.9424 17.0971 28.7676 15.8957 29.9932 14.959C31.2634 13.9882 32.6957 13.5001 34.2617 13.5001Z" stroke="#C03744"/>
    </svg>


    <svg xmlns="http://www.w3.org/2000/svg"
         width="51" height="51" viewBox="0 0 51 51" fill="none"
         class="hidden group-hover:block absolute top-0 left-0">
        <rect width="50.8895" height="51" rx="7" fill="#C03744" />
        <path fill-rule="evenodd" clip-rule="evenodd"
              d="M30.5684 36.5508C36.9448 31.1109 41.2242 27.4591 41.4854 22.3066L41.498 21.8037C41.498 16.7849 38.0125 13 33.3906 13C31.7346 13.0001 30.2162 13.5254 28.8779 14.5615C27.5949 15.5549 26.7403 16.8201 26.2373 17.7402C25.7343 16.8201 24.8797 15.5549 23.5967 14.5615C22.3419 13.5901 20.929 13.0673 19.3926 13.0059L19.084 13C14.4621 13 10.9766 16.7849 10.9766 21.8037L10.9893 22.3066C11.2504 27.4584 15.5297 31.1092 21.9054 36.5484L21.9082 36.5508L23.6836 38.0703C24.3048 38.604 24.9508 39.1627 25.6094 39.7393L25.6768 39.793C25.8388 39.9109 26.035 39.9746 26.2373 39.9746C26.4396 39.9746 26.6358 39.9108 26.7979 39.793L26.8652 39.7393C27.5237 39.1627 28.1699 38.6039 28.791 38.0703L30.5684 36.5508Z"
              fill="white" />
    </svg>


</button>
</div>







