<?php

/** @var \Wyomind\ElasticsearchCore\Helper\Data $dataHelper */
$dataHelper = $this->helper('Wyomind\ElasticsearchCore\Helper\Data');
/** @var \Wyomind\ElasticsearchCore\Helper\Currency $currencyHelper */
$currencyHelper = $this->helper('Wyomind\ElasticsearchCore\Helper\Currency');
/** @var \Wyomind\ElasticsearchLayeredNavigation\Helper\Category $categoryHelper */
$categoryHelper = $this->helper('Wyomind\ElasticsearchLayeredNavigation\Helper\Category');
/** @var \Wyomind\ElasticsearchLayeredNavigation\Helper\Config $configHelper */
$configHelper = $this->helper('Wyomind\ElasticsearchLayeredNavigation\Helper\Config');
/** @var \Wyomind\ElasticsearchLayeredNavigation\Helper\Toolbar $toolbarHelper */
$toolbarHelper = $this->helper('Wyomind\ElasticsearchLayeredNavigation\Helper\Toolbar');
/** @var \Wyomind\ElasticsearchLayeredNavigation\Helper\Frontend $frontendHelper */
$frontendHelper = $this->helper('Wyomind\ElasticsearchLayeredNavigation\Helper\Frontend');
/** @var \Wyomind\ElasticsearchCore\Helper\Tax $taxHelper */
$taxHelper = $this->helper('Wyomind\ElasticsearchCore\Helper\Tax');
/** @var \Wyomind\ElasticsearchCore\Helper\Theme $themeHelper */
$themeHelper = $this->helper('Wyomind\ElasticsearchCore\Helper\Theme');
/** @var \Wyomind\Core\Helper\Data $coreHelper */
$coreHelper = $this->helper('Wyomind\Core\Helper\Data');

$themeModel = $themeHelper->getThemeModel();
$elasticsearchUrl = $dataHelper->getElasticsearchUrl();
$storeId = $dataHelper->getCurrentStoreId();

$searchTerm = "";

$params = $frontendHelper->getParams();
if (isset($params['q']) && $params['q'] !== null) {
    $searchTerm = $params['q'];
}

$currentCategory = $categoryHelper->getCurrentCategoryId();
$displayMode = "LIST";
if ($currentCategory != -1) {
    $displayMode = $categoryHelper->getCurrentCategoryDisplayMode();

}

/* @noEscape */ echo $block->getChildBlock('wyo.eln.mage_version')->toHtml();

if ($displayMode !== "PAGE") :


    $swatchMediaUrl = $block->getUrl(\Magento\Swatches\Block\Product\Renderer\Configurable::MEDIA_CALLBACK_ACTION, ['_secure' => $block->getRequest()->isSecure()]);

    $storeCode = $dataHelper->getCurrentStoreCode();


    $switcherBlock = $block->getChildBlock("wyo.eln.listing.products.mode.switcher");
    $sorterBlock = $block->getChildBlock("wyo.eln.listing.products.sorter");
    $sorterBlock->setData('type', $block->getType());
    $limiterBlock = $block->getChildBlock("wyo.eln.listing.products.limiter");
    $amountBlock = $block->getChildBlock("wyo.eln.listing.products.amount");
    if (stripos($themeModel, "Infortis") !== false) {
        $gridBlock = $block->getChildBlock("wyo.eln.listing.products.grid.ultimo");
    } else {
        $gridBlock = $block->getChildBlock("wyo.eln.listing.products.grid.default");
    }
    $pagingBlock = $block->getChildBlock("wyo.eln.listing.products.paging");


    $currentMode = $toolbarHelper->getCurrentMode();


    $currentOrder = $toolbarHelper->getCurrentOrder($block->getType());
    $currentDirection = $toolbarHelper->getCurrentDirection($block->getType());


    $perPageDefaultValue = $toolbarHelper->getPerPageDefaultValue();
    $currentPerPage = $toolbarHelper->getCurrentPerPage();

    $filterableAttributes = $configHelper->getFilterableAttributesJson($block->getType(), $storeId);
    $isInfiniteScrollEnabled = $configHelper->isInfiniteScrollEnabled($block->getType(), $storeId);
    $infiniteScrollStep = $configHelper->getInfiniteScrollStep($block->getType(), $storeId);
    $isInfiniteScrollAutomatic = $configHelper->isInfiniteScrollAutomatic($block->getType(), $storeId);
    $infiniteScrollOffset = $configHelper->getInfiniteScrollOffset($block->getType(), $storeId);
    $isAutoRefreshEnabled = $configHelper->isAutoRefreshEnabled($storeId);
    $isAjaxCartEnabled = $configHelper->isAjaxCartEnabled($block->getType(), $storeId);
    $isAddToCompareEnabled = $configHelper->isAddToCompareEnabled($block->getType(), $storeId);
    $isHighlightEnabled = $configHelper->isHighlightEnabled($storeId);
    $isLayerHideOneValue = $configHelper->isLayerHideOneValue($block->getType(), $storeId);
    $isLayerUpdateEnabled = $configHelper->isLayerUpdateEnabled($block->getType(), $storeId);
    if ($isLayerUpdateEnabled) {
        $layerUpdateMethod = $configHelper->getLayerUpdateMethod($block->getType(), $storeId);
    } else {
        $layerUpdateMethod = -1;
    }
    $updateSearchTerm = $configHelper->getUpdateSearchTerm($storeId);
    $layerUpdateSorting = $configHelper->getLayerUpdateSorting($block->getType(), $storeId);
    $isStickyLayerEnabled = $configHelper->isStickyLayerEnabled($block->getType(), $storeId);

    $labels = $configHelper->getLabels($storeId);

    $displayInputBoxesForPriceFilter = $configHelper->displayInputBoxesForPriceFilter($block->getType(), $storeId);

    // CUSTOM THEME
    $themeHelper = $this->helper('Wyomind\ElasticsearchCore\Helper\Theme');
    $themeClass = "";
    $theme = ['model' => $themeHelper->getThemeModel()];
    if ($theme['model'] == "Infortis/ultimo") {
        $themeClass = "ultimo";
        $ultimo = $this->helper('Infortis\Base\Helper\Data');
        $theme['config'] = $ultimo->getCfgGroup('category_grid');
    }

    /** @var boolean $edd */
    $edd = $coreHelper->moduleIsEnabled("Wyomind_EstimatedDeliveryDate") && $coreHelper->getStoreConfig("estimateddeliverydate/common/enabled", $storeId);


    $eaConfig = json_encode($configHelper->getEaConfig($storeId));

    $size = $isInfiniteScrollEnabled ? $infiniteScrollStep : $currentPerPage;

    $result = $frontendHelper->getResult($block->getType());


    if (!isset($customerGroupId) && isset($result['customerGroupId'])) {
        $customerGroupId = $result['customerGroupId'];
    }

    ?>

    <div class="eln-main-content <?= $block->escapeHtml($themeClass); ?>">

        <div class="eln-main-loader" style="display:none"></div>

        <div class="eln-toolbar toolbar toolbar-products">
            <!-- PRODUCTS MODE SWITCHER -->
            <?= /* @noEscape */ $switcherBlock->toHtml() ?>
            <!-- PRODUCT AMOUNT -->
            <?php
            $amountBlock->setData("count", $result['amount']['total']);
            $amountBlock->setData("labels", $labels);
            $amountBlock->setData("from", 1);
            $amountBlock->setData("to", $size);
            $amountBlock->setData("infiniteScroll", $isInfiniteScrollEnabled);
            echo /* @noEscape */ $amountBlock->toHtml();
            ?>
            <!-- SORTER -->
            <?= /* @noEscape */ $sorterBlock->toHtml() ?>
        </div>

        <!-- PRODUCT GRID -->
        <?php
        $gridBlock->setData('noMoreProduct', !$result['amount']['next'] && $isInfiniteScrollEnabled);
        $gridBlock->setData('count', $result['amount']['total']);
        $gridBlock->setData('products', $result['products']);
        $gridBlock->setData('customerGroupId', $customerGroupId);
        $gridBlock->setData('ajaxCartEnabled', $isAjaxCartEnabled);
        $gridBlock->setData('addToCompareEnabled', $isAddToCompareEnabled);

        $configurableIndex = [];
        $configurableImages = [];

        foreach ($result['products'] as $product) :
            if (isset($product['configurable_index'])):
                $configurableIndex[$product['id']] = json_decode($product['configurable_index']);
                $configurableImages[$product['id']] = json_decode($product['configurable_images']);
            endif;
        endforeach;

        ?>
        <?= /* @noEscape */ $gridBlock->toHtml() ?>


        <!-- BOTTOM PAGING -->
        <?php if (!$isInfiniteScrollEnabled) : ?>
            <?php
            $pagingBlock->setData('previous', $result['amount']['previous']);
            $pagingBlock->setData('next', $result['amount']['next']);
            $pagingBlock->setData('current', $result['amount']['current']);
            $pagingBlock->setData('size', $result['amount']['size']);
            $pagingBlock->setData('pages', $result['amount']['pages']);
            ?>
            <?= /* @noEscape */ $pagingBlock->toHtml() ?>
        <?php endif; ?>

        <!-- LIMITER -->
        <?php if (!$isInfiniteScrollEnabled) : ?>
            <?= /* @noEscape */ $limiterBlock->toHtml() ?>
        <?php endif; ?>

        <!-- MANUAL INFINITE SCROOL -->
        <?php if ($isInfiniteScrollEnabled && !$isInfiniteScrollAutomatic): ?>
            <div style="text-align: center;">
                <button id='eln-manual-infinite-scroll'
                        class="action primary <?= (!$result['amount']['next']) ? 'hidden' : '' ?>">
                    <span><?= /* @noEscape */  __('Load more products') ?></span>
                </button>
            </div>
        <?php endif; ?>

    </div>
    <!-- INITIALIZER -->
    <script>
        require(['jquery', 'underscore', 'Magento_Catalog/js/price-utils', 'mage/cookies', 'wyoeln', 'truncate'], function ($, _, utils, cookie, wyoeln, truncate) {
            'use strict';

            $(".inner-description").each(function(i,elt) {
                if (typeof $.truncate === "function") {
                    $(elt).html($.truncate($(elt).html(), {length: 150, words: true}))
                }
            });

            _.mixin({
                getFormattedPrice: function (price, productTaxClassId) {
                    return _.formatPrice(_.calculateTax(_.convertPrice(price), productTaxClassId));
                },
                formatPrice: function (price) {
                    var priceFormat = <?= /* @noEscape */ $this->helper('Magento\Tax\Helper\Data')->getPriceFormat($block->getStore()); ?>;

                    return utils.formatPrice(price, priceFormat);
                },
                calculateTax: function (price, productTaxClassId) {
                    return price;
                    var needPriceConversion = <?= $block->escapeHtml($taxHelper->needPriceConversion() ? 'true' : 'false') ?>;
                    var taxRates = <?= /* @noEscape */ json_encode($taxHelper->getRates()) ?>;

                    if (!needPriceConversion || !taxRates[productTaxClassId]) {
                        return price;
                    }

                    var rate = taxRates[productTaxClassId] / 100;
                    var priceIncludesTax = <?= $block->escapeHtml($taxHelper->priceIncludesTax() ? 'true' : 'false') ?>;

                    if (priceIncludesTax) {
                        return price / (1 + rate);
                    }

                    return price + price * rate;
                },
                convertPrice: function (price) {
                    var rate = <?= /* @noEscape */ $currencyHelper->getCurrentCurrencyRate()?>;

                    return price * rate;
                },
                getCookie: function (cname) {
                    var name = cname + "=";
                    var decodedCookie = decodeURIComponent(document.cookie);
                    var ca = decodedCookie.split(';');
                    for (var i = 0; i < ca.length; i++) {
                        var c = ca[i];
                        while (c.charAt(0) == ' ') {
                            c = c.substring(1);
                        }
                        if (c.indexOf(name) == 0) {
                            return c.substring(name.length, c.length);
                        }
                    }
                    return "";
                },
                createFilterUrl: function (attributeCode, optionLabel) {
                    var url = "";
                    if (wyoeln.search.term != "") {
                        url = "/catalogsearch/result/" + wyoeln.search.term + "/" + wyoeln.encodeFilters(wyoeln.filtersLabels, {
                            "attributeCode": attributeCode,
                            "optionLabel": optionLabel
                        });
                    } else {
                        url = wyoeln.search.categoryUrl.replace('<?= $block->escapeUrl($configHelper->getSEOCategoryUrlSuffix($storeId)) ?>', '') + "/" + wyoeln.encodeFilters(wyoeln.filtersLabels, {
                            "attributeCode": attributeCode,
                            "optionLabel": optionLabel
                        }) + '<?= $block->escapeUrl($configHelper->getSEOCategoryUrlSuffix($storeId)) ?>';
                    }

                    return url;
                },
                createFilterUrlMinus: function (attributeCode, optionLabel) {
                    var url = "";
                    if (wyoeln.search.term != "") {
                        url = "/catalogsearch/result/" + wyoeln.search.term + "/" + wyoeln.encodeFiltersMinus(wyoeln.filtersLabels, {
                            "attributeCode": attributeCode,
                            "optionLabel": optionLabel
                        });
                    } else {
                        // @todo
                        url = wyoeln.search.categoryUrl.replace('<?= $block->escapeUrl($configHelper->getSEOCategoryUrlSuffix($storeId)) ?>', '') + "/" + wyoeln.encodeFiltersMinus(wyoeln.filtersLabels, {
                            "attributeCode": attributeCode,
                            "optionLabel": optionLabel
                        }) + '<?= $block->escapeUrl($configHelper->getSEOCategoryUrlSuffix($storeId)) ?>';
                    }
                    return url;
                }
            });


            wyoeln.config = {
                elasticsearchUrl: "<?= $block->escapeUrl($elasticsearchUrl) ?>",
                storeCode: "<?= $block->escapeHtml($storeCode) ?>",
                filterableAttributes: <?= /* @noEscape */ $filterableAttributes ?>,
                infiniteScroll: {
                    enabled: <?= $isInfiniteScrollEnabled ? 'true' : 'false' ?>,
                    automatic: <?= $isInfiniteScrollAutomatic ? 'true' : 'false' ?>,
                    offset: '<?= $block->escapeHtml($infiniteScrollOffset) ?>'
                },
                displayInputBoxesForPriceFilter: <?= $displayInputBoxesForPriceFilter ? 'true' : 'false'; ?>,
                ajaxCart: {
                    enabled: <?= $isAjaxCartEnabled ? 'true' : 'false' ?>
                },
                addToCompare: {
                    enabled: <?= $isAddToCompareEnabled ? 'true' : 'false' ?>
                },
                theme: <?= json_encode($theme) ?>,
                highlightEnabled: <?= $isHighlightEnabled ? 'true' : 'false' ?>,
                layerHideOneValue: <?= $isLayerHideOneValue ? 'true' : 'false' ?>,
                layerUpdateMethod: '<?= $block->escapeHtml($layerUpdateMethod) ?>',
                layerUpdateSorting: '<?= $block->escapeHtml($layerUpdateSorting) ?>',
                labels: <?= /* @noEscape */ json_encode($labels) ?>,
                customerGroupId: <?= /* @noEscape */ $customerGroupId ?>,
                pageTitle: "<?= $block->escapeHtml(\Wyomind\ElasticsearchLayeredNavigation\Block\Search\Header::TITLE); ?>",
                autoRefresh: <?= $isAutoRefreshEnabled ? 'true' : 'false'; ?>,
                updateSearchTerm: <?= $updateSearchTerm ? 'true' : 'false'; ?>,
                updateSearchTermUrl: "<?= $block->getUrl('elasticsearchcore/searchTerm/add'); ?>",
                eaConfig: <?= /* @noEscape */$eaConfig ?>,
                stickyLayer: <?= $isStickyLayerEnabled ? 'true' : 'false' ?>,
                seoCategoryUrlSuffix: '<?= $block->escapeUrl($configHelper->getSEOCategoryUrlSuffix($storeId)) ?>',
                edd: <?= $edd ? 'true' : 'false'; ?>
            }
            wyoeln.search = {
                categoryId: <?= $block->escapeHtml($currentCategory) ?>,
                categoryUrl: "<?= $block->escapeUrl($categoryHelper->getCurrentCategoryUrl()); ?>",
                term: "<?= $block->escapeHtml($searchTerm) ?>"
            };
            wyoeln.paging = {
                from: "0",
                size: '<?= $isInfiniteScrollEnabled ? (int)$infiniteScrollStep : (int)$currentPerPage ?>'
            };
            wyoeln.sorter = {
                order: "<?= $block->escapeHtml($currentOrder) ?>",
                direction: "<?= $block->escapeHtml($currentDirection) ?>"
            };

            wyoeln.filtersLabels = wyoeln.decodeFilters(<?= /* @noEscape */ json_encode($params['filters'] ?? []) ?>);

            <?php
            $allowUrls = [];
            $attributes = json_decode($filterableAttributes, true);
            foreach ($attributes as $uid => $atts) {
                foreach ($atts as $att) {
                    if ($att[6]) {
                        $allowUrls[] = $att[0];
                    }
                }
            }
            ?>

            wyoeln.allowUrls = <?= /* @noEscape */ json_encode($allowUrls); ?>;

            wyoeln.configurableIndex = <?= /* @noEscape */ json_encode($configurableIndex); ?>;
            wyoeln.configurableImages = <?= /* @noEscape */ json_encode($configurableImages); ?>;

            wyoeln.initObservers();
            wyoeln.initPriceSliders();

            <?php
            $allProductIds = [];
            foreach ($result['products'] as $product) :
                $allProductIds[] = $product['id'];
            endforeach;
            ?>
            wyoeln.updateEstimatedDeliveryDate(<?= /* @noEscape */ json_encode($allProductIds) ?>);

            $(document).ready(function () {

                // if search page && if auto refresh enabled
                <?php if ($isAutoRefreshEnabled) : ?>
                if ($('body').hasClass('catalogsearch-result-index')) {
                    $('body').addClass('eln-auto-refresh');
                    $('#search').attr('data-mage-init', '{}');
                }
                <?php endif; ?>

            });


        });
    </script>
<?php else: ?>
    <style>
        .eln-main-loader {
            display: none !important;
        }
    </style>

<?php endif; ?>