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

// phpcs:disable Magento2.Templates.ThisInTemplate.FoundThis
// phpcs:disable Generic.WhiteSpace.ScopeIndent.Incorrect

/* @var $block \Magento\Catalog\Block\Product\AbstractProduct */
?>

<?php
$columns = "columns4";
$_imagehelper = $this->helper('Magento\Catalog\Helper\Image');
$_portohelper = $this->helper('Smartwave\Porto\Helper\Data');
$review_model = $_portohelper->getModel('\Magento\Review\Model\Review');
$_category_config = $_portohelper->getConfig('porto_settings/category');
$_category_grid_config = $this->helper('Smartwave\Porto\Helper\Data')->getConfig('porto_settings/category_grid');
switch ($type = $block->getType()) {

    case 'related-rule':
        if ($exist = $block->hasItems()) {
            $type = 'related';
            $class = $type;

            $image = 'related_products_list';
            $title = __('Related Products');
            $items = $block->getAllItems();
            $limit = $block->getPositionLimit();
            $shuffle = (int) $block->isShuffled();
            $canItemsAddToCart = $block->canItemsAddToCart();

            $showWishlist = true;
            $showCompare = true;
            $showCart = false;
            $templateType = \Magento\Catalog\Block\Product\ReviewRendererInterface::SHORT_VIEW;
            $description = false;
        }
    break;

    case 'related':
        /** @var \Magento\Catalog\Block\Product\ProductList\Related $block */
        if ($exist = $block->getItems()->getSize()) {
            $type = 'related';
            $class = $type;

            $image = 'related_products_list';
            $title = __('Related Products');
            $items = $block->getItems();
            $limit = 0;
            $shuffle = 0;
            $canItemsAddToCart = $block->canItemsAddToCart();

            $showWishlist = true;
            $showCompare = true;
            $showCart = false;
            $templateType = \Magento\Catalog\Block\Product\ReviewRendererInterface::SHORT_VIEW;
            $description = false;
        }
    break;

    case 'upsell-rule':
        if ($exist = $block->hasItems()) {
            $type = 'upsell';
            $class = $type;

            $image = 'upsell_products_list';
            $title = __('We found other products you might like!');
            $items = $block->getAllItems();
            $limit = $block->getPositionLimit();
            $shuffle = (int) $block->isShuffled();

            $showWishlist = false;
            $showCompare = false;
            $showCart = false;
            $templateType = \Magento\Catalog\Block\Product\ReviewRendererInterface::SHORT_VIEW;
            $description = false;
            $canItemsAddToCart = false;
        }
    break;

    case 'upsell':
        /** @var \Magento\Catalog\Block\Product\ProductList\Upsell $block */
        if ($exist = count($block->getItemCollection()->getItems())) {
            $type = 'upsell';
            $class = $type;
            $upsell_columns = $_portohelper->getConfig('porto_settings/product/upsell_columns');
            if($upsell_columns)
                $columns = "";
            $image = 'upsell_products_list';
            $title = __('We found other products you might like!');
            $items = $block->getItemCollection()->getItems();
            $limit = $block->getItemLimit('upsell');
            $shuffle = 0;

            $showWishlist = false;
            $showCompare = false;
            $showCart = false;
            $templateType = \Magento\Catalog\Block\Product\ReviewRendererInterface::SHORT_VIEW;
            $description = false;
            $canItemsAddToCart = false;
        }
    break;

    case 'crosssell-rule':
        /** @var \Magento\Catalog\Block\Product\ProductList\Crosssell $block */
        if ($exist = $block->hasItems()) {
            $type = 'crosssell';
            $class = $type;

            $image = 'cart_cross_sell_products';
            $title = __('More Choices:');
            $items = $block->getItemCollection();

            $showWishlist = true;
            $showCompare = false;
            $showCart = true;
            $templateType = \Magento\Catalog\Block\Product\ReviewRendererInterface::SHORT_VIEW;
            $description = false;
            $canItemsAddToCart = false;
        }
    break;

    case 'crosssell':
        /** @var \Magento\Catalog\Block\Product\ProductList\Crosssell $block */
        if ($exist = $block->getItemCount()) {
            $type = 'crosssell';
            $class = $type;

            $image = 'cart_cross_sell_products';
            $title = __('More Choices:');
            $items = $block->getItems();
            $columns = "columns4";

            $showWishlist = true;
            $showCompare = false;
            $showCart = true;
            $templateType = \Magento\Catalog\Block\Product\ReviewRendererInterface::SHORT_VIEW;
            $description = false;
            $canItemsAddToCart = false;
        }
    break;

    case 'new':
        if ($exist = $block->getProductCollection()) {
            $type = 'new';
            $mode = 'grid';
            $type = $type . ' ' . $mode;

            $class = 'widget' . ' ' . $type;

            $image = 'new_products_content_widget_grid';
            $title = __('New Products');
            $items = $exist;

            $showWishlist = true;
            $showCompare = true;
            $showCart = true;
            $templateType = \Magento\Catalog\Block\Product\ReviewRendererInterface::SHORT_VIEW;
            $description = ($mode == 'list') ? true : false;
            $canItemsAddToCart = false;
        }
    break;

    case 'other':
    break;
}

$image = 'category_page_grid';
$hover_image = 'category_page_grid-hover';
$image_width = ($_category_config['ratio_width'])?$_category_config['ratio_width']:300;
$image_height = ($_category_config['ratio_height'])?$_category_config['ratio_height']:300;
?>

<?php if ($exist) :?>

<?php if ($type == 'related' || $type == 'upsell') :?>
<?php if ($type == 'related') :?>
<div class="block <?= $block->escapeHtmlAttr($class) ?>" data-mage-init='{"relatedProducts":{"relatedCheckbox":".related.checkbox"}}' data-limit="<?= $block->escapeHtmlAttr($limit) ?>" data-shuffle="<?= /* @noEscape */ $shuffle ?>">
    <?php else :?>
    <div class="block <?= $block->escapeHtmlAttr($class) ?> porto-products title-border-bottom" data-mage-init='{"upsellProducts":{}}' data-limit="<?= $block->escapeHtmlAttr($limit) ?>" data-shuffle="<?= /* @noEscape */ $shuffle ?>">
        <?php endif; ?>
        <?php else :?>
        <div class="block <?= $block->escapeHtmlAttr($class) ?>">
            <?php endif; ?>
            <div class="section-title slider-title">
                <strong id="block-<?= $block->escapeHtmlAttr($class) ?>-heading" role="heading" aria-level="2"><?= $block->escapeHtml($title) ?></strong>
            </div>
            <div class="block-content content" aria-labelledby="block-<?= $block->escapeHtmlAttr($class) ?>-heading">
                <?php if ($type == 'related' && $canItemsAddToCart) :?>
                    <div class="block-actions">
                        <?= $block->escapeHtml(__('Check items to add to the cart or')) ?>
                        <button type="button" class="action select" role="button" data-role="select-all"><span><?= $block->escapeHtml(__('select all')) ?></span></button>
                    </div>
                <?php endif; ?>
                <div class="products wrapper grid products-grid  <?php if ($type == 'upsell' || $type == 'crosssell'): ?><?php echo $columns; ?><?php endif; ?> products-grid products-<?php /* @escapeNotVerified */ echo $type; ?><?php if($type  == 'related'):?> small-list<?php endif;?>">
                    <div class="products list items product-items <?php if ($type == 'related' || $type == 'upsell'): ?><?php if ($type == 'upsell'): ?>products-slider <?php endif;?>owl-carousel<?php endif; ?><?php if ($type == 'upsell'): ?> show-dots-title-right dots-style-1<?php endif; ?><?php if($type  == 'related'):?> show-nav-title<?php endif;?>">
                        <?php $iterator = 0; ?>
													<?php foreach ($items as $_item): ?>
													<?php $available = ''; ?>
													<?php if (!$_item->isComposite() && $_item->isSaleable() && $type == 'related'): ?>
														<?php if (!$_item->getRequiredOptions()): ?>
															<?php $available = 'related-available'; ?>
														<?php endif; ?>
													<?php endif; ?>
													<?php if ($type == 'related'): ?>
														<?php
															$iterator ++;
															if($iterator % 2 == 1)
																echo '<div class="item product product-item" style="display: none;">';
														?>
													<?php elseif ($type == 'upsell'): ?>
														<?php echo($iterator++ == 0) ? '<div class="item product product-item" style="display: none;">' : '</div><div class="item product product-item" style="display: none;">' ?>
													<?php else: ?>
														<?php /* @escapeNotVerified */ echo($iterator++ == 0) ? '<div class="item product product-item">' : '</div><div class="item product product-item">' ?>
													<?php endif; ?>
                            <div class="product-item-info <?= /* @noEscape */ $available ?>">
                                <?php /* @escapeNotVerified */ echo '<!-- ' . $image . '-->' ?>
																<a href="<?php echo $_item->getProductUrl() ?>" class="product photo product-item-photo" tabindex="-1">
																	<?php
																		if($type == 'related') {
																			$_category_config['aspect_ratio'] = 0;
																			$image_width = 300;
																			$image_height = 300;
																		}
																		if($_category_config['aspect_ratio'])
																			$productImage = $_imagehelper->init($_item, $image)->constrainOnly(FALSE)->keepAspectRatio(TRUE)->keepFrame(FALSE)->resize($image_width);
																		else
																			$productImage = $_imagehelper->init($_item, $image)->resize($image_width, $image_height);
																		$productImageUrl = $productImage->getUrl();
																	?>
																		<img class="product-image-photo default_image" src="<?php echo $productImageUrl; ?>" alt="<?php echo $productImage->getLabel(); ?>" alt=""/>
																	<?php if($_category_config['alternative_image']): ?>
																	<?php
																		if($_category_config['aspect_ratio'])
																			$productHoverImage = $_imagehelper->init($_item, $hover_image)->constrainOnly(FALSE)->keepAspectRatio(TRUE)->keepFrame(FALSE)->resize($image_width);
																		else
																			$productHoverImage = $_imagehelper->init($_item, $hover_image)->resize($image_width, $image_height);
																		$productHoverImageUrl = $productHoverImage->getUrl();
																	?>
																		<?php if($productImageUrl != str_replace("/thumbnail/","/small_image/",$productHoverImageUrl)): ?>
																		<img class="product-image-photo hover_image" src="<?php echo $productHoverImageUrl; ?>" alt="<?php echo $productHoverImage->getLabel(); ?>" alt=""/>
																		<?php endif; ?>
																	<?php endif; ?>
																</a>
																<div class="product details product-item-details">
																	<strong class="product name product-item-name"><a class="product-item-link" title="<?php echo $block->escapeHtml($_item->getName()) ?>" href="<?php /* @escapeNotVerified */ echo $block->getProductUrl($_item) ?>">
																		<?php echo $block->escapeHtml($_item->getName()) ?></a>
																	</strong>

																	<?php if($_category_config['rating_star']): ?>
																	<?php
																		$review_model->getEntitySummary($_item);
																		$review_html = $block->getReviewsSummaryHtml($_item, $templateType);
																	?>
																	<?php if($review_html): ?>
																		<?php echo $review_html; ?>
																	<?php else: ?>
																	<div class="product-reviews-summary short">
																		<div class="rating-summary">
																			<span class="label"><span>Rating:</span></span>
																			<div class="rating-result" title="0%">
																				<span style="width:0"><span>0%</span></span>
																			</div>
																		</div>
																	</div>
																	<?php endif; ?>
																	<?php endif; ?>
																	<?php /* @escapeNotVerified */ echo $block->getProductPrice($_item); ?>

																		<?php if (!$_item->isComposite() && $_item->isSaleable() && $type == 'related'): ?>
																			<?php if (!$_item->getRequiredOptions()): ?>
																				<div class="field choice related">
																					<input type="checkbox" class="checkbox related" id="related-checkbox<?php /* @escapeNotVerified */ echo $_item->getId() ?>" name="related_products[]" value="<?php /* @escapeNotVerified */ echo $_item->getId() ?>" />
																					<label class="label" for="related-checkbox<?php /* @escapeNotVerified */ echo $_item->getId() ?>"><span><?php /* @escapeNotVerified */ echo __('Add to Cart') ?></span></label>
																				</div>
																			<?php endif; ?>
																		<?php endif; ?>

																		<?php if ($showWishlist || $showCompare || $showCart): ?>
																			<div class="product actions product-item-actions">
																				<?php if ($showCart): ?>
																					<div class="actions-primary">
																						<?php if ($_item->isSaleable()): ?>
																							<?php if ($_item->getTypeInstance()->hasRequiredOptions($_item)): ?>
																								<button class="action tocart primary" data-mage-init='{"redirectUrl": {"url": "<?php /* @escapeNotVerified */ echo $block->getAddToCartUrl($_item) ?>"}}' type="button" title="<?php /* @escapeNotVerified */ echo __('Add to Cart') ?>">
																									<span><?php /* @escapeNotVerified */ echo __('Add to Cart') ?></span>
																								</button>
																							<?php else: ?>
																								<?php $postDataHelper = $this->helper('Magento\Framework\Data\Helper\PostHelper');
																								$postData = $postDataHelper->getPostData($block->getAddToCartUrl($_item), ['product' => $_item->getEntityId()])
																								?>
																								<button class="action tocart primary"
																										data-post='<?php /* @escapeNotVerified */ echo $postData; ?>'
																										type="button" title="<?php /* @escapeNotVerified */ echo __('Add to Cart') ?>">
																									<span><?php /* @escapeNotVerified */ echo __('Add to Cart') ?></span>
																								</button>
																							<?php endif; ?>
																						<?php else: ?>
																							<?php if ($_item->getIsSalable()): ?>
																								<div class="stock available"><span><?php /* @escapeNotVerified */ echo __('In stock') ?></span></div>
																							<?php else: ?>
																								<div class="stock unavailable"><span><?php /* @escapeNotVerified */ echo __('Out of stock') ?></span></div>
																							<?php endif; ?>
																						<?php endif; ?>
																					</div>
																				<?php endif; ?>

																				<?php if ($showWishlist || $showCompare): ?>
																					<div class="secondary-addto-links actions-secondary" data-role="add-to-links">
																						<?php if ($this->helper('Magento\Wishlist\Helper\Data')->isAllow() && $showWishlist): ?>
																							<a href="#" data-post='<?php /* @escapeNotVerified */ echo $block->getAddToWishlistParams($_item); ?>'  class="action towishlist" data-action="add-to-wishlist" title="<?php /* @escapeNotVerified */ echo __('Add to Wish List') ?>">
																								<span><?php /* @escapeNotVerified */ echo __('Add to Wish List') ?></span>
																							</a>
																						<?php endif; ?>
																						<?php if ($block->getAddToCompareUrl() && $showCompare): ?>
																							<?php
																							$compareHelper = $this->helper('Magento\Catalog\Helper\Product\Compare');
																							?>
																							<a href="#" class="action tocompare"
																								 data-post='<?php /* @escapeNotVerified */ echo $compareHelper->getPostDataParams($_item);?>'
																								 data-role="add-to-links"
																								 title="<?php /* @escapeNotVerified */ echo __('Add to Compare'); ?>">
																								<span><?php /* @escapeNotVerified */ echo __('Add to Compare') ?></span>
																							</a>
																						<?php endif; ?>
																					</div>
																				<?php endif; ?>
																			</div>
																		<?php endif; ?>
																	</div>
                            </div>
													<?php if ($type == 'related'): ?>
													<?php
														if($iterator == count($items) || $iterator % 2 == 0)
															echo '</div>';
													?>
													<?php else: ?>
													<?php echo($iterator == count($items)) ? '</div>' : '' ?>
													<?php endif; ?>
													<?php endforeach ?>
                    </div>
                </div>
            </div>
        </div>
					<?php if ($type == 'related'): ?>
						<script type="text/javascript">
								require([
										'jquery',
										'owl.carousel/owl.carousel.min'
								], function ($) {
										$(".products-related .owl-carousel").owlCarousel({
												nav: true,
												dots: false,
												items: 1,
												nav: true
										});
								});
						</script>
					<?php endif; ?>
					<?php if ($type == 'upsell'): ?>
							<script type="text/javascript">
									require([
										'jquery',
										'owl.carousel/owl.carousel.min'
									], function ($) {
										$(".products-upsell .owl-carousel").owlCarousel({
											margin: 0,
											nav: false,
											dots: true,
											responsive: {
												0: {
													items:2
												},
												768: {
													items:3
												},
												992: {
													items:<?php echo $upsell_columns-1; ?>
												},
												1200: {
													items:<?php echo $upsell_columns; ?>
												}
											}
										});
									});
							</script>
					<?php endif; ?>
        <?php endif;?>
