<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

use Magento\Catalog\Block\Product\ReviewRendererInterface;
use Magento\Catalog\Helper\Product\Compare;
use Magento\CatalogWidget\Block\Product\ProductsList;
use Magento\Framework\App\Action\Action;
use Magento\Framework\Escaper;
use Magento\Wishlist\Helper\Data;

/** @var Escaper $escaper */
/** @var ProductsList $block */
?>
<?php if ($exist = ($block->getProductCollection() && $block->getProductCollection()->count())): ?>
<?php
    $classes = [];
    $_helper = $this->helper(\Magento\Catalog\Helper\Output::class);
    $theme_helper = $this->helper(\Olegnax\Athlete2\Helper\ProductList::class);
    $img_helper = $this->helper(\Olegnax\Athlete2\Helper\ProductImage::class);
    $at_settings = $theme_helper->getModuleConfig();
    $width = $at_settings[ 'product_images' ][ 'listing_image_width' ];
    $height =  $at_settings[ 'product_images' ][ 'listing_image_height' ];
    $type = 'widget-product-grid';
    $mode = 'grid';
    $image = 'new_products_content_widget_grid';
	$image_hover	 = 'category_page_grid_hover';
    $items = $block->getProductCollection()->getItems();
    $showWishlist = true;
    $showCompare = true;
    $showCart = true;
    $templateType = ReviewRendererInterface::SHORT_VIEW;
    $description = $at_settings['products_listing']['description_on_grid'] ?: false;
    $descSource = $at_settings['products_listing']['description_on_grid_source'];
    $showDescMoreLink = $at_settings['products_listing']['description_on_grid_more'];
    $showAvailability =  $at_settings['products_listing']['stock_status'];
	$showQuickview	 = $theme_helper->isActivePlugin( 'Olegnax_Quickview' );
    $quickviewPosition = $at_settings['products_listing']['quickview_position'];
    $quickviewBtnClass = $at_settings['products_listing']['quickview_button_style'];
    $showReviewCount = $at_settings['products_listing']['review_count'];
    $thumbSlider = $at_settings['products_listing']['thumb_carousel'];
    $alignDetailsCenter = $at_settings['products_listing']['products_layout_centered'];
    $preloaderEnabled= $at_settings['products_listing']['preloader_enabled'];
    $preloaderClasses = $preloaderEnabled ? 'lazy-loader' : '';
    if($thumbSlider){
        $thumbsArrowsBlock = $block->getChildBlock('thumb_carousel_arrows');
        $thumbSliderShowDots = $theme_helper->getConfig('athlete2_design/appearance_product_listing_thumbs/show_dots');
        $thumbSliderDotsPos = $theme_helper->getConfig('athlete2_design/appearance_product_listing_thumbs/dots_position');
        $thumbOptions['carousel'] = true;
        $thumbOptions['selected_only'] = $at_settings['products_listing']['thumb_carousel_show_logic'] ?: '';
        $thumbOptions['max_items'] = $at_settings['products_listing']['thumb_carousel_max_items'] ?: '';
        $thumbOptions['min_items'] = $minThumbs = $at_settings['products_listing']['thumb_carousel_min_items'] ?: 2;
        $img_helper->setOptions($thumbOptions);
    }
    $classes[] = $showReviewCount ? 'show-review-count' : '';
    $classes[] = $quickviewPosition ? ('quickview-' . $quickviewPosition) : '';
    $classes[] = $thumbSlider ? ('thumb-slider-on') : '';
    $classes[] = $alignDetailsCenter ? 'align-details-center' : '';

    $cartIcon = '<svg version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" class="a2-icon-cart"><use xlink:href="#a2-cart-icon"></use></svg>';
	$compareIcon	 = '<svg version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" class="a2-icon-compare"><use xlink:href="#a2-compare-icon"></use></svg>';
	$wishlistIcon	 = '<svg version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" class="a2-icon-wishlist"><use xlink:href="#a2-wishlist-icon"></use></svg>';
	
?>
    <div class="block widget block-products-list products-grid__layout-default <?= $escaper->escapeHtmlAttr( $mode . ' ' . implode( ' ', $classes )) ?>">
        <?php if ($block->getTitle()): ?>
        <div class="block-title">
            <strong><?= $escaper->escapeHtml(__($block->getTitle())) ?></strong>
        </div>
        <?php endif ?>
        <div class="block-content">
            <?= /* @noEscape */ '<!-- ' . $image . '-->' ?>
            <div class="products-<?= /* @noEscape */ $mode ?> <?= /* @noEscape */ $mode ?>">
                <ol class="product-items <?= /* @noEscape */ $type ?>">
                    <?php $iterator = 1; ?>
                    <?php foreach ($items as $_item): ?>
                        <?php $productOutOfStock = $_item->isAvailable() ? '' : ' product-item-unavailable'; ?>
                        <?= /* @noEscape */ ($iterator++ == 1) ? '<li class="product-item">' : '</li><li class="product-item">' ?>
                        <div class="product-item-info <?= $escaper->escapeHtmlAttr($productOutOfStock) ?>">
							<div class="product-grid__image-wrapper">
                            <a href="<?= $block->escapeUrl($block->getProductUrl($_item)) ?>" class="product photo product-item-photo <?= $preloaderClasses ?>">
                                <?php
                                if($thumbSlider){
                                    $productImage = $img_helper->getResizedCatalogImages($_item, $image, $image_hover, [$width, $height] );
                                } else{
                                    /* not necessarily anymore but left it in case some data is passed in arg for image with hover template */
                                    $productImage = $img_helper->getResizedImageHover($_item, $image, $image_hover, [$width, $height]);
                                }
                                $_thumbSlider = $thumbSlider && (bool)($img_helper->getImagesCount() >= $minThumbs);
                                ?>
                                <?= $productImage->toHtml() ?>
                            </a>
							<?php if ( $showWishlist || $showCompare || $showCart || $showQuickview || $_thumbSlider): ?>
								<div class="product-item-inner">
                                    <a href="<?= $block->escapeUrl($block->getProductUrl($_item)) ?>" aria-label="View Product" class="overlay-link"><?= $block->escapeHtml($_item->getName()) ?></a>
                                    <?php if($_thumbSlider): ?>
                                        <?php if($thumbSliderDotsPos != 'below'){ echo $img_helper->getThumbImageDots($thumbSliderShowDots); } ?>
                                            <?php
                                            if($thumbsArrowsBlock){
                                                echo $thumbsArrowsBlock->toHtml();
                                            }
                                            ?>
                                    <?php endif; ?>
									<div class="product-item-actions">
										<div class="actions-primary">
											<?php if ($_item->isSaleable() && $showCart): ?>
                                                <?php $postParams = $block->getAddToCartPostParams($_item); ?>
												<form data-role="tocart-form" data-product-sku="<?= $escaper->escapeHtml($_item->getSku()) ?>" action="<?= $escaper->escapeUrl($postParams['action']) ?>" method="post">
                                                    <?php $options = method_exists($block, 'getOptionsData') ? $block->getOptionsData($_item) : false; ?>
                                                    <?php if($options && is_array($options)): ?>
                                                    <?php foreach ($options as $optionItem): ?>
                                                        <input type="hidden"
                                                                name="<?= $escaper->escapeHtml($optionItem['name']) ?>"
                                                                value="<?= $escaper->escapeHtml($optionItem['value']) ?>">
                                                    <?php endforeach; ?>
                                                    <?php endif; ?>
													<input type="hidden" name="product" value="<?= $escaper->escapeHtmlAttr($postParams['data']['product']) ?>">
													<input type="hidden" name="<?= /* @noEscape */ Action::PARAM_NAME_URL_ENCODED ?>" value="<?= /* @noEscape */ $postParams['data'][Action::PARAM_NAME_URL_ENCODED] ?>">
                                                    <?= $block->getBlockHtml('formkey') ?>
													<button type="submit"
															title="<?= $escaper->escapeHtml(__('Add to Cart')) ?>"
															class="action tocart primary">
                                                        <?= $cartIcon ?><span><?= $escaper->escapeHtml(__('Add to Cart')) ?></span>
													</button>
												</form>
											<?php else: ?>
												<?php if (!$_item->isAvailable() && $showOutofstock) :?>
													<div class="stock unavailable"><span><?= $escaper->escapeHtml(__('Out of stock')) ?></span></div>
												<?php endif; ?>
											<?php endif; ?>
											<?php if ( $showWishlist || $showCompare ): ?>
												<div class="actions-secondary" data-role="add-to-links">
                                                    <?php //phpcs:disable ?>
													<?php if ( $this->helper( Data::class )->isAllow() && $showWishlist ): ?>
                                                        <?php //phpcs:enable ?>
														<a href="#"
														   data-post='<?= /* @noEscape */ $block->getAddToWishlistParams( $_item ) ?>' class="action towishlist" data-action="add-to-wishlist" title="<?= $escaper->escapeHtmlAttr( __( 'Add to Wish List' ) ) ?>">
                                                           <?= $wishlistIcon ?><span><?= $escaper->escapeHtml( __( 'Add to Wish List' ) ) ?></span>
														</a>
													<?php endif; ?>
													<?php if ( $block->getAddToCompareUrl() && $showCompare ): ?>
                                                        <?php //phpcs:disable ?>
														<?php $compareHelper = $this->helper( Compare::class ); ?>
                                                        <?php //phpcs:enable ?>
														<a href="#" class="action tocompare" data-post='<?= /* @noEscape */ $compareHelper->getPostDataParams( $_item ) ?>' title="<?= $escaper->escapeHtmlAttr( __( 'Add to Compare' ) ) ?>">
															<?= $compareIcon ?><span><?= $escaper->escapeHtml( __( 'Add to Compare' ) ) ?></span>
														</a>
													<?php endif; ?>
												</div>
											<?php endif; ?>
										</div>
											<?php
											if ( $showQuickview ) {
												echo $this->helper( 'Olegnax\Quickview\Helper\Helper' )->getButton( $_item, 'button quick-view ' . $quickviewBtnClass );
											}
											?>
									</div>
									<a href="<?= $escaper->escapeUrl($block->getProductUrl($_item)) ?>" class="overlay-link"  aria-label="<?= $escaper->escapeHtmlAttr(__('View details for %1',  $escaper->escapeHtmlAttr($_item->getName()))) ?>">></a>
								</div>
							<?php endif; ?>
							<?php if ( $theme_helper->isActivePlugin( 'Olegnax_ProductLabel' ) ) {
								echo $this->helper( 'Olegnax\ProductLabel\Helper\Helper' )->showLabels( $_item );
							}  ?>
							</div>
							<div class="product-grid-overlay"></div>
                            <div class="product-item-details">
                                <?php if( $_thumbSlider && $thumbSliderDotsPos === 'below'){ echo $img_helper->getThumbImageDots($thumbSliderShowDots); } ?>
                                <strong class="product-item-name">
                                    <a title="<?= $escaper->escapeHtml($_item->getName()) ?>"
                                       href="<?= $escaper->escapeUrl($block->getProductUrl($_item)) ?>"
                                       class="product-item-link">
                                        <?= $escaper->escapeHtml($_item->getName()) ?>
                                    </a>
                                </strong>
                                <?php
                                echo $block->getProductPriceHtml($_item, $type);
                                ?>
                                <?= $block->getProductDetailsHtml($_item) ?>

                                <?php if ($description):  ?>
                                    <?php
                                    if($descSource === 'catalog-short'){
                                        $descContent = $_helper->productAttribute($_item,  $_item->getShortDescriptionCatalog(), 'short_description_catalog');
                                    } else {
                                        $descContent = $_helper->productAttribute($_item, $_item->getShortDescription(), 'short_description');
                                    } ?>
                                    <?php if (!empty($descContent)):?>
                                        <div class="product description product-item-description">
                                            <?= /* @noEscape */ $descContent ?>
                                            <?php if($showDescMoreLink): ?>
                                            <a href="<?= $escaper->escapeUrl($_item->getProductUrl()) ?>"
                                            class="action more"><?= $escaper->escapeHtml(__('Learn More')) ?></a>
                                            <?php endif; ?>
                                        </div>
                                    <?php endif; ?>
                                <?php endif; ?>
                                
                                <?php if ($templateType): ?>
                                    <?= $block->getReviewsSummaryHtml($_item, $templateType) ?>
                                <?php endif; ?>

                                <?php if ($_item->isAvailable()): ?>
                                    <?php if ( $showAvailability ): ?>
                                        <div class="stock-info-block">
                                            <div class="stock available"><span><?= $escaper->escapeHtml(__('In stock')) ?></span></div>
                                        </div>
                                    <?php endif; ?>
                                <?php else:?>
                                    <div class="stock-info-block">
                                        <div class="stock unavailable"><span><?= $escaper->escapeHtml(__('Out of stock')) ?></span></div>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                        <?= ($iterator == count($items) + 1) ? '</li>' : '' ?>
                    <?php endforeach ?>
                </ol>
            </div>
            <?= $block->getPagerHtml() ?>
        </div>
    </div>
    <?php if($_item->isSaleable() &&  $showCart && $block->getBlockHtml('formkey')): ?>
    <script type="text/x-magento-init">
    {
        ".block.widget [data-role=tocart-form]": {
            "Magento_Catalog/js/validate-product": {}
        }
    }
    </script>
    <?php endif;?>
    <?php if($thumbSlider): ?>
	<script type="text/x-magento-init">{"*":{"ox-thumb-carousel":{}}}</script> 
	<?php endif; ?>
<?php endif;?>
