<?php
use Leadlion\Autogedal\Helper\Config as StockHelper;
use Magento\Catalog\Helper\Image as ImageHelper;
use Magento\Catalog\Helper\Output as OutputHelper;
use Magento\Catalog\Helper\Product\Compare as CompareHelper;
use Magento\Framework\App\Action\Action;
use Magento\Wishlist\Helper\Data as WishlistHelper;
use Smartwave\Porto\Helper\Data as PortoHelper;

$productCollection = $block->getProductCollection();
$outputHelper = $this->helper(OutputHelper::class);
$imageHelper = $this->helper(ImageHelper::class);
$portoHelper = $this->helper(PortoHelper::class);
$categoryConfig = $portoHelper->getConfig('porto_settings/category');
$gridConfig = $portoHelper->getConfig('porto_settings/category_grid');
$labelConfig = $portoHelper->getConfig('porto_settings/product_label');
$isLazyLoad = $portoHelper->getConfig('porto_settings/optimization/lazyload')
    || $block->getData('enable_lazyload') === '1';
$stockHelper = $this->helper(StockHelper::class);
$hasQtyField = !empty($categoryConfig['qty_field']);
$uencParam = Action::PARAM_NAME_URL_ENCODED;
$carouselSize = 10;

$aspectRatio = $block->getData('aspect_ratio');
if ($aspectRatio == null) {
    $aspectRatio = $categoryConfig['aspect_ratio'];
}

$imageWidth = $block->getData('image_width') ?: ($categoryConfig['ratio_width'] ?: 300);
$imageHeight = $aspectRatio ? $imageWidth : $block->getData('image_height');
if (!$imageHeight) {
    $imageHeight = $categoryConfig['ratio_height'] ?: $imageWidth;
}

$moveActions = $block->getData('move_actions');
if ($moveActions == null) {
    $moveActions = $gridConfig['move_actions'];
}

$resizeImage = static fn ($product, string $imageId) => $aspectRatio
    ? $imageHelper->init($product, $imageId)->constrainOnly(false)->keepAspectRatio(true)->keepFrame(false)
        ->resize($imageWidth)
    : $imageHelper->init($product, $imageId)->resize($imageWidth, $imageHeight);
?>
<div id="top_products_widget">
    <h2><?= $escaper->escapeHtml(__('Best-selling products')) ?></h2>
    <?php if ($productCollection && $productCollection->getSize()): ?>
        <?php
        $products = array_values($productCollection->getItems());
        $items = [];
        while ($products && count($items) < $carouselSize) {
            $items[] = $products[count($items) % count($products)];
        }

        $skuAttributeSetIds = $stockHelper->getAttributesSetsIdsForShowingSku();
        $skuAttributeSetIds = $skuAttributeSetIds ? explode(',', $skuAttributeSetIds) : [];

        $showActions = $categoryConfig['actions'];
        $showWishlist = $showActions
            && $block->getMode() == 'grid'
            && $categoryConfig['addtowishlist']
            && $this->helper(WishlistHelper::class)->isAllow();
        $compareHelper = $showActions && $categoryConfig['addtocompare'] ? $this->helper(CompareHelper::class) : null;
        $defaultQty = $block->getProductDefaultQty() * 1;
        $qtyValidators = json_encode($block->getQuantityValidators());
        ?>
        <div class="products wrapper grid products-grid">
            <div class="filterproducts products list items product-items owl-carousel <?= $hasQtyField ? 'has-qty' : '' ?>">
                <?php foreach ($items as $product): ?>
                    <?php
                    $qty = $stockHelper->getStockQty($product, $product->getStore()->getWebsiteId());
                    $productUrl = $product->getProductUrl();
                    $productName = $outputHelper->productAttribute($product, $product->getName(), 'name');
                    $imageUrl = $resizeImage($product, 'category_page_grid')->getUrl();
                    $hoverImageUrl = $categoryConfig['alternative_image']
                        ? $resizeImage($product, 'category_page_grid-hover')->getUrl()
                        : null;
                    $showHoverImage = $hoverImageUrl !== null
                        && $imageUrl != str_replace('/thumbnail/', '/small_image/', $hoverImageUrl);

                    $saleLabel = null;
                    if ($labelConfig['sale_label']) {
                        if ($product->getTypeId() == 'bundle') {
                            $priceInfo = $product->getPriceInfo();
                            $regularPrice = $priceInfo->getPrice('regular_price')->getMaximalPrice()->getValue();
                            $specialPrice = $priceInfo->getPrice('final_price')->getMaximalPrice()->getValue();
                        } else {
                            $regularPrice = $product->getPrice();
                            $specialPrice = $product->getSpecialPrice();
                        }
                        $specialPrice = $specialPrice ?: $regularPrice;
                        $specialFrom = $product->getSpecialFromDate();
                        $specialTo = $product->getSpecialToDate();
                        $now = time();
                        $isOnSale = $specialPrice < $regularPrice
                            && ($specialFrom === null || $now >= strtotime($specialFrom))
                            && ($specialTo === null || $now <= strtotime($specialTo));
                        if ($isOnSale) {
                            $saleLabel = $labelConfig['sale_label_percent']
                                ? '-' . (100 - round(($specialPrice / $regularPrice) * 100)) . '%'
                                : $labelConfig['sale_label_text'];
                        }
                    }

                    $newLabel = null;
                    if ($labelConfig['new_label']) {
                        $today = date('Y-m-d');
                        $newFrom = substr((string)$product->getData('news_from_date'), 0, 10);
                        $newTo = substr((string)$product->getData('news_to_date'), 0, 10);
                        $isNew = ($newFrom !== '' || $newTo !== '')
                            && ($newFrom === '' || $today >= $newFrom)
                            && ($newTo === '' || $today <= $newTo);
                        if ($isNew) {
                            $newLabel = $labelConfig['new_label_text'];
                        }
                    }

                    $isSaleable = $product->isSaleable();
                    $isSalable = $product->getIsSalable();
                    $cartUrl = '';
                    $cartData = [];
                    $bundleInputs = [];

                    if ($showActions && $isSaleable) {
                        ['action' => $cartUrl, 'data' => $cartData] = $block->getAddToCartPostParams($product);
                        if ($product->getTypeId() == 'bundle') {
                            $bundleOptions = [];
                            $selectionCount = 0;
                            foreach (array_keys($portoHelper->getChildrenIds($product->getId())) as $optionId) {
                                $bundleOptions[$optionId][] = $optionId;
                                $selections = $product->getTypeInstance()
                                    ->getSelectionsCollection([$optionId], $product)
                                    ->exportToArray();
                                $selectionCount = count($selections);
                                if ($selectionCount > 1) {
                                    $bundleOptions = [];
                                    foreach ($selections as $selection) {
                                        $bundleOptions[$optionId][] = $selection['selection_id'];
                                    }
                                }
                            }
                            foreach ($bundleOptions as $optionId => $selectionIds) {
                                $inputName = 'bundle_option[' . $optionId . ']' . ($selectionCount > 1 ? '[]' : '');
                                foreach ($selectionIds as $selectionId) {
                                    $bundleInputs[] = ['name' => $inputName, 'value' => $selectionId];
                                }
                            }
                        }
                    }

                    $wishlistParams = $showWishlist ? $block->getAddToWishlistParams($product) : '';
                    $compareParams = $compareHelper ? $compareHelper->getPostDataParams($product) : '';
                    ?>
                    <div class="item product product-item">
                        <div class="product-item-info" data-container="product-grid">
                            <div class="product photo product-item-photo">
                                <a href="<?= $escaper->escapeUrl($productUrl) ?>" tabindex="-1">
                                    <img class="product-image-photo default_image <?= $isLazyLoad ? 'owl-lazy' : '' ?>"
                                         <?= $isLazyLoad ? 'data-src' : 'src' ?>="<?= $escaper->escapeUrl($imageUrl) ?>"
                                         width="<?= $escaper->escapeHtmlAttr($imageWidth) ?>"
                                         height="<?= $escaper->escapeHtmlAttr($imageHeight) ?>"/>
                                    <?php if ($showHoverImage): ?>
                                        <img class="product-image-photo hover_image <?= $isLazyLoad ? 'owl-lazy' : '' ?>"
                                             <?= $isLazyLoad ? 'data-src' : 'src' ?>="<?= $escaper->escapeUrl($hoverImageUrl) ?>"/>
                                    <?php endif; ?>
                                </a>
                                <?php if ($saleLabel !== null || $newLabel !== null): ?>
                                    <div class="product-labels">
                                        <?php if ($saleLabel !== null): ?>
                                            <div class="product-label sale-label"><?= /* @noEscape */ $saleLabel ?></div>
                                        <?php endif; ?>
                                        <?php if ($newLabel !== null): ?>
                                            <div class="product-label new-label"><?= /* @noEscape */ $newLabel ?></div>
                                        <?php endif; ?>
                                    </div>
                                <?php endif; ?>
                                <?php if ($showActions && $moveActions): ?>
                                    <div class="product-item-inner">
                                        <div class="product actions product-item-actions">
                                            <div class="actions-primary">
                                                <?php if ($isSaleable): ?>
                                                    <form data-role="tocart-form"
                                                          action="<?= $escaper->escapeUrl($cartUrl) ?>"
                                                          method="post">
                                                        <?php foreach ($bundleInputs as $input): ?>
                                                            <input type="hidden"
                                                                   class="bundle-option-<?= (int)$input['value'] ?> product bundle option"
                                                                   name="<?= $escaper->escapeHtml($input['name']) ?>"
                                                                   value="<?= (int)$input['value'] ?>"
                                                                   aria-required="true">
                                                        <?php endforeach; ?>
                                                        <input type="hidden" name="product" value="<?= (int)$cartData['product'] ?>">
                                                        <input type="hidden"
                                                               name="<?= /* @noEscape */ $uencParam ?>"
                                                               value="<?= /* @noEscape */ $cartData[$uencParam] ?>">
                                                        <?php if ($hasQtyField): ?>
                                                            <div class="qty-box">
                                                                <a href="javascript:void(0)" class="qtyminus"><i class="porto-icon-minus"></i></a>
                                                                <input type="text"
                                                                       name="qty"
                                                                       id="qty"
                                                                       maxlength="12"
                                                                       value="<?= /* @noEscape */ $defaultQty ?>"
                                                                       title="<?= $escaper->escapeHtmlAttr(__('Qty')) ?>"
                                                                       class="input-text qty"
                                                                       data-validate="<?= $escaper->escapeHtml($qtyValidators) ?>"/>
                                                                <a href="javascript:void(0)" class="qtyplus"><i class="porto-icon-plus"></i></a>
                                                            </div>
                                                        <?php endif; ?>
                                                        <?= $block->getBlockHtml('formkey') ?>
                                                        <button type="submit"
                                                                title="<?= $escaper->escapeHtml(__('Add to Cart')) ?>"
                                                                class="action tocart primary">
                                                            <span><?= $escaper->escapeHtml(__('Add to Cart')) ?></span>
                                                        </button>
                                                    </form>
                                                <?php elseif ($isSalable): ?>
                                                    <div class="stock available">
                                                        <span><?= $escaper->escapeHtml(__('In stock')) ?></span>
                                                    </div>
                                                <?php else: ?>
                                                    <div class="stock unavailable">
                                                        <span><?= $escaper->escapeHtml(__('Out of stock')) ?></span>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                            <?php if ($showWishlist): ?>
                                                <a href="#"
                                                   class="action towishlist actions-secondary"
                                                   title="<?= $escaper->escapeHtml(__('Add to Wish List')) ?>"
                                                   aria-label="<?= $escaper->escapeHtml(__('Add to Wish List')) ?>"
                                                   data-post='<?= /* @noEscape */ $wishlistParams ?>'
                                                   data-action="add-to-wishlist"
                                                   role="button">
                                                    <span><?= $escaper->escapeHtml(__('Add to Wish List')) ?></span>
                                                </a>
                                            <?php endif; ?>
                                            <?php if ($compareHelper): ?>
                                                <a href="#"
                                                   class="action tocompare actions-secondary"
                                                   title="<?= $escaper->escapeHtml(__('Add to Compare')) ?>"
                                                   aria-label="<?= $escaper->escapeHtml(__('Add to Compare')) ?>"
                                                   data-post='<?= /* @noEscape */ $compareParams ?>'
                                                   role="button">
                                                    <span><?= $escaper->escapeHtml(__('Add to Compare')) ?></span>
                                                </a>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <div class="product details product-item-details">
                                <strong class="product name product-item-name">
                                    <a class="product-item-link"
                                       href="<?= $escaper->escapeUrl($productUrl) ?>">
                                        <?= /* @noEscape */ $productName ?>
                                    </a>
                                </strong>
                                <div class="product-sku-container">
                                    <span class="product sku_fz" itemprop="sku">
                                        <?php if (in_array($product->getAttributeSetId(), $skuAttributeSetIds)): ?>
                                            <?= $escaper->escapeHtml($product->getSku()) ?>
                                        <?php else: ?>
                                            <?= $escaper->escapeHtml($product->getData('sku_fz')) ?>
                                        <?php endif; ?>
                                    </span>
                                </div>
                                <div class="product-stock">
                                    <?php if ($isSaleable): ?>
                                        <?php if ($isSalable && $qty > 0): ?>
                                            <div class="available">
                                                <span><?= $escaper->escapeHtml(__('In stock ')) ?></span>
                                            </div>
                                        <?php elseif ($isSalable): ?>
                                            <div class="unavailable">
                                                <span><?= $escaper->escapeHtml(__('To order')) ?></span>
                                            </div>
                                        <?php endif; ?>
                                    <?php elseif ($isSalable): ?>
                                        <div class="stock available">
                                            <span><?= $escaper->escapeHtml(__('In stock')) ?></span>
                                        </div>
                                    <?php else: ?>
                                        <div class="stock unavailable">
                                            <span><?= $escaper->escapeHtml(__('Out of stock')) ?></span>
                                        </div>
                                    <?php endif; ?>
                                </div>
                                <div class="info-block">
                                    <?php if ($isSalable && $qty > 0): ?>
                                        <?php $deliveryTerm = $product->getData('termen_livrare'); ?>
                                        <?php if ($deliveryTerm): ?>
                                            <div class="product-term">
                                                <span><?= $escaper->escapeHtml(__('Fast shipping')) ?></span>
                                                <span class="term-value"><?= $escaper->escapeHtml($deliveryTerm) ?></span>
                                            </div>
                                        <?php else: ?>
                                            <span><?= $escaper->escapeHtml(__('Fast shipping')) ?></span>
                                        <?php endif; ?>
                                    <?php else: ?>
                                        <span class="la-comanda"><?= $escaper->escapeHtml(__('Delivery in 7-30 days')) ?></span>
                                    <?php endif; ?>
                                </div>
                                <div class="action-price">
                                    <?php if ($categoryConfig['product_price']): ?>
                                        <?= /* @noEscape */ $block->getProductPrice($product) ?>
                                    <?php endif; ?>
                                    <?= $block->getProductDetailsHtml($product) ?>
                                    <?php if ($showActions && !$moveActions): ?>
                                        <div class="product-item-inner">
                                            <div class="product actions product-item-actions">
                                                <div class="actions-primary">
                                                    <?php if ($isSaleable): ?>
                                                        <form data-role="tocart-form"
                                                              action="<?= $escaper->escapeUrl($cartUrl) ?>"
                                                              method="post">
                                                            <input type="hidden" name="product" value="<?= (int)$cartData['product'] ?>">
                                                            <input type="hidden"
                                                                   name="<?= /* @noEscape */ $uencParam ?>"
                                                                   value="<?= /* @noEscape */ $cartData[$uencParam] ?>">
                                                            <?php foreach ($bundleInputs as $input): ?>
                                                                <input type="hidden"
                                                                       class="bundle-option-<?= (int)$input['value'] ?> product bundle option"
                                                                       name="<?= $escaper->escapeHtml($input['name']) ?>"
                                                                       value="<?= (int)$input['value'] ?>"
                                                                       aria-required="true">
                                                            <?php endforeach; ?>
                                                            <?php if ($hasQtyField): ?>
                                                                <div class="qty-box">
                                                                    <a href="javascript:void(0)" class="qtyminus"><i class="porto-icon-minus"></i></a>
                                                                    <input type="text"
                                                                           name="qty"
                                                                           id="qty"
                                                                           maxlength="12"
                                                                           value="<?= /* @noEscape */ $defaultQty ?>"
                                                                           title="<?= $escaper->escapeHtmlAttr(__('Qty')) ?>"
                                                                           class="input-text qty"
                                                                           data-validate="<?= $escaper->escapeHtml($qtyValidators) ?>"/>
                                                                    <a href="javascript:void(0)" class="qtyplus"><i class="porto-icon-plus"></i></a>
                                                                </div>
                                                            <?php endif; ?>
                                                            <?= $block->getBlockHtml('formkey') ?>
                                                            <button type="submit"
                                                                    title="<?= $escaper->escapeHtml(__('Add to Cart')) ?>"
                                                                    class="action tocart primary <?= $qty > 0 ? 'available' : 'unavailable' ?>">
                                                                <span><?= $escaper->escapeHtml(__('Add to Cart')) ?></span>
                                                            </button>
                                                        </form>
                                                    <?php else: ?>
                                                        <div class="not-sal-product">
                                                            <button
                                                                title="<?= $escaper->escapeHtml(__('Add to Cart')) ?>"
                                                                class="action tocart primary unavailable">
                                                                <span><?= $escaper->escapeHtml(__('Add to Cart')) ?></span>
                                                            </button>
                                                        </div>
                                                    <?php endif; ?>
                                                </div>
                                                <?php if ($showWishlist): ?>
                                                    <a href="#"
                                                       class="action towishlist actions-secondary <?= $hasQtyField ? 'has-qty' : '' ?>"
                                                       title="<?= $escaper->escapeHtml(__('Add to Wish List')) ?>"
                                                       aria-label="<?= $escaper->escapeHtml(__('Add to Wish List')) ?>"
                                                       data-post='<?= /* @noEscape */ $wishlistParams ?>'
                                                       data-action="add-to-wishlist"
                                                       role="button">
                                                        <span><?= $escaper->escapeHtml(__('Add to Wish List')) ?></span>
                                                    </a>
                                                <?php endif; ?>
                                                <?php if ($compareHelper): ?>
                                                    <a href="#"
                                                       class="action tocompare actions-secondary <?= $hasQtyField ? 'has-qty' : '' ?>"
                                                       title="<?= $escaper->escapeHtml(__('Add to Compare')) ?>"
                                                       aria-label="<?= $escaper->escapeHtml(__('Add to Compare')) ?>"
                                                       data-post='<?= /* @noEscape */ $compareParams ?>'
                                                       role="button">
                                                        <span><?= $escaper->escapeHtml(__('Add to Compare')) ?></span>
                                                    </a>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php if (!$block->isRedirectToCartEnabled()): ?>
            <script type="text/x-magento-init">
                {
                    "[data-role=tocart-form], .form.map.checkout": {
                        "catalogAddToCart": {}
                    }
                }
            </script>
        <?php endif; ?>
    <?php endif; ?>
</div>

<script>
    require([
        'jquery',
        'owl.carousel/owl.carousel.min'
    ], function ($) {
        $('#top_products_widget .owl-carousel').owlCarousel({
            autoplay: true,
            autoplayTimeout: 7000,
            autoplayHoverPause: false,
            loop: true,
            lazyLoad: true,
            navRewind: false,
            margin: 10,
            autoWidth: true,
            nav: true,
            navText: ['<em class="left-arrow-slider"></em>', '<em class="right-arrow-slider"></em>'],
            dots: false,
            center: false,
            responsive: {
                0: {
                    items: 1,
                    margin: 20,
                    autoWidth: false
                },
                768: {
                    items: 3,
                    margin: 20
                },
                1024: {
                    items: 4
                },
                1200: {
                    items: 5
                }
            }
        });
    });
</script>
