<?php
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();

/** @var \FoundationCommerce\ThemeViewModels\ViewModels\ThemeIcons $icons */
$icons = $viewModels->require(\FoundationCommerce\ThemeViewModels\ViewModels\ThemeIcons::class);

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: function addToWishlist(productId) {

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

                postParams.data['form_key'] = document.querySelector('input[name=form_key]').value;
                postParams.data['qty'] = document.getElementById(`qty[${productId}]`).value || 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(function (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(function (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(function (error) {
                    typeof window.dispatchMessages !== "undefined" && window.dispatchMessages(
                        [{
                            type: "error",
                            text: error
                        }], 5000
                    );
                });
            }
        }
    }
</script>


<div class="flex items-center justify-center w-full px-5 py-3 mt-6 shadow-custom1 lg:w-auto lg:mt-0">
    <button x-data="initWishlist<?= /** @noEscape */ $uniqueId ?>()"
            @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')
            ) ?>"
            class="inline-flex items-center justify-center mr-3 border-0 rounded-full">
            <?= $icons->heartRegularHtml(
                    "hover:text-red-600 text-primary hover:text-main",
                    20,
                    18
                ) ?>
        <span class="font-semibold leading-4 uppercase text-primary ml-4"><?= $escaper->escapeHtml(__('Add to wishlist')) ?></span>
    </button>
</div>
