<?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\Cart\Items as CartItems;
use Hyva\Theme\ViewModel\ProductCompare;
use Hyva\Theme\ViewModel\ProductList;
use Hyva\Theme\ViewModel\Slider;
use Hyva\Theme\ViewModel\Store;
use Hyva\Theme\ViewModel\Wishlist;
use Magento\Catalog\Model\Product\Visibility as ProductVisibility;
use Magento\Framework\Escaper;
use Magento\Framework\View\Element\Template;

/** @var Template $block */
/** @var Escaper $escaper */
/** @var ViewModelRegistry $viewModels */
/** @var Slider $sliderViewModel */
/** @var ProductList $productListViewModel */
/** @var Wishlist $wishlistViewModel */
/** @var ProductCompare $compareViewModel */
/** @var Store $storeViewModel */

$sliderViewModel      = $viewModels->require(Slider::class);
$productListViewModel = $viewModels->require(ProductList::class);
$wishlistViewModel    = $viewModels->require(Wishlist::class);
$compareViewModel     = $viewModels->require(ProductCompare::class);
$storeViewModel       = $viewModels->require(Store::class);

$categoryIds       = array_filter(explode(',', $block->getData('category_ids') ?: ''));
$pageSize          = $block->getData('page_size') ?: 8;
$priceFrom         = $block->getData('price_from');
$priceTo           = $block->getData('price_to');
$sortAttribute     = $block->getData('sort_attribute') ?: 'position';
$sortDirection     = $block->getData('sort_direction') ?: 'ASC';
$title             = $block->getData('title') ?: '';
$hideDetails       = $block->getData('hide_details') ?? false;
$hideRatingSummary = $block->getData('hide_rating_summary') ?? false;
$type              = $block->getData('type');
$additionalFilters = (array) $block->getData('additional_filters');
$itemTemplate      = $block->getData('item_template') ?? 'Magento_Catalog::product/list/item.phtml';
$containerTemplate = $block->getData('container_template')
    ?? 'Magento_Catalog::product/slider/product-slider-container.phtml';


if ($categoryIds) {
    $productListViewModel->addFilter('category_id', $categoryIds, 'in');
}
if ($priceFrom) {
    $productListViewModel->addFilter('price', $priceFrom, 'gteq');
}
if ($priceTo) {
    $productListViewModel->addFilter('price', $priceTo, 'lteq');
}

if ($hideRatingSummary) {
    $productListViewModel->excludeReviewSummary();
}

foreach ($additionalFilters as $filter) {
    $productListViewModel->addFilter($filter['field'], $filter['value'], $filter['conditionType'] ?? 'eq');
}

$productListViewModel->setPageSize($pageSize);
$productListViewModel->addFilter('website_id', $storeViewModel->getWebsiteId());
$productListViewModel->addFilter('visibility', [
    ProductVisibility::VISIBILITY_IN_CATALOG,
    ProductVisibility::VISIBILITY_IN_SEARCH,
    ProductVisibility::VISIBILITY_BOTH,
], 'in');
$sortDirection === 'ASC'
    ? $productListViewModel->addAscendingSortOrder($sortAttribute)
    : $productListViewModel->addDescendingSortOrder($sortAttribute);

if (in_array($type, ['related', 'upsell', 'crosssell'], true)) {

    $items = $type === 'crosssell'
        ? $productListViewModel->getCrosssellItems(...$viewModels->require(CartItems::class)->getCartItems())
        : $productListViewModel->getLinkedItems($type, $block->getProduct());

} else {
    $items = $productListViewModel->getItems();
}

?>
<div class="product-slider">
    <div>
        <?=
        $sliderViewModel->getSliderForItems($itemTemplate, $items, $containerTemplate)
                        ->setData('hide_details', $hideDetails)
                        ->setData('hide_rating_summary', $hideRatingSummary)
                        ->setData('title', $title)
                        ->setData('slider_type', $type)
                        ->toHtml();
        ?>
    </div>
    <script>
        'use strict';
        window.addEventListener('DOMContentLoaded', function() {
            if (! window.productSliderEventHandlerInitialized) {
                window.productSliderEventHandlerInitialized = true;

                <?php if ($wishlistViewModel->isEnabled()): ?>
                window.addEventListener('product-add-to-wishlist', (event) => {
                    const productId = event.detail.productId;
                    fetch(BASE_URL + "wishlist/index/add/", {
                        headers: {
                            "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
                        },
                        body: new URLSearchParams({
                                form_key: hyva.getFormKey(),
                                product: productId,
                                uenc: btoa(window.location.href)
                            }
                        ),
                        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 (result) {
                        if (!result) {
                            return
                        }
                        typeof window.dispatchMessages !== "undefined" && window.dispatchMessages(
                            [{
                                type: (result.success) ? "success" : "error",
                                text: (result.success)
                                    ? "<?=
                                        $escaper->escapeHtml(
                                            __("%1 has been added to your Wish List.", __("Product"))
                                        )
                                        ?>" : result.error_message
                            }], 5000
                        );
                        window.dispatchEvent(new CustomEvent("reload-customer-section-data"));
                    }).catch(function (error) {
                        typeof window.dispatchMessages !== "undefined" && window.dispatchMessages(
                            [{
                                type: "error",
                                text: error
                            }], 5000
                        );
                    });
                })
                <?php endif; ?>

                <?php if ($compareViewModel->showInProductList()): ?>
                window.addEventListener('product-add-to-compare', (event) => {
                    const productId = event.detail.productId;
                    hyva.postForm({
                        action: BASE_URL + 'catalog/product_compare/add/',
                        data: {product: productId}
                    })
                })
                <?php endif; ?>
            }
        });
    </script>
</div>
