<?php
/**
 * Copyright © Codazon, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
?>
<?php
$_productCollection = $block->getLoadedProductCollection();

?>
<?php if ($_productCollection->count()) :?>
<?php
$_helper = $this->helper(Magento\Catalog\Helper\Output::class);
$imageHelper = $this->helper(Magento\Catalog\Helper\Image::class);
$ampHelper = $this->helper(Codazon\GoogleAmpManager\Helper\Data::class);
$formKeyHtml = $block->getBlockHtml('formkey');
$addToCartText = __('Add to cart');
$addingText = __('Adding...');
$viewProductText = __('View details');
$width = $ampHelper->getConfig('googleampmanager/images/product_list_image_width') ? : 200;
$height = $ampHelper->getConfig('googleampmanager/images/product_list_image_height') ? : 200;
$showCartBtn = $ampHelper->displayOnListing('addtocart');
$showPrice = $ampHelper->displayOnListing('price');
$showThumbnail = $ampHelper->displayOnListing('thumbnail');
$showRating = $ampHelper->displayOnListing('rating');

if ($block->getMode() == 'grid') {
    $viewMode = 'grid';
    $image = 'category_page_grid';
    $showDescription = $ampHelper->displayOnListing('description');
    $descLength = (int)$ampHelper->getConfig('googleampmanager/category_view/max_desc_length');
    $templateType = \Magento\Catalog\Block\Product\ReviewRendererInterface::SHORT_VIEW;
    $imageClass = '';
    $detailClass = '';
} else {
    $viewMode = 'list';
    $descLength = false;
    $showDescription = true;
    $image = 'category_page_list';
    $templateType = \Magento\Catalog\Block\Product\ReviewRendererInterface::FULL_VIEW;
    $imageClass = ' cdz-list-left';
    $detailClass = $showThumbnail ? ' cdz-list-right' : '';
}
$layout = $this->getLayout();
$swatchesRenderer = $layout->createBlock(\Magento\Swatches\Block\Product\Renderer\Listing\Configurable::class)
     ->setTemplate('Codazon_GoogleAmpManager::amp/product/list/swatch-renderer.phtml');
$reviewRenderer = $layout->createBlock(\Magento\Review\Block\Product\ReviewRenderer::class)->setDisplayIfEmpty(true)
    ->setTemplate('Codazon_GoogleAmpManager::amp/product/list/review-info-content.phtml');
$showDescTop = $showDescription && ($viewMode != 'list');
$showDescBot = $showDescription && ($viewMode == 'list');
?>
<div class="cdz-products products-<?= $viewMode ?>">
    <?= $block->getToolbarHtml() ?>
    <?= $block->getBlockHtml('amp-catalog-navigation-state') ?>
    <ul class="cdz-product-listing cdz-<?= $viewMode ?>">
        <?php foreach ($_productCollection as $_product) :?><?php
            $productNameStripped = $block->stripTags($_product->getName(), null, true);
            $productUrl = $ampHelper->transformToAmpUrl($block->escapeUrl($_product->getProductUrl()));
            $mainImage = $_product->getData('small_image');
            $canAddToCart = $_product->getTypeInstance()->isPossibleBuyFromList($_product);
            $canAddToCart = $canAddToCart && $_product->isSaleable() && $showCartBtn;
            $addToCartUrl = $ampHelper->filterUrl($ampHelper->filterCartUrl($block->getAddToCartUrl($_product, ['_escape' => false])));
            $productId = (int)$_product->getId();
        ?><li class="cdz-item">
            <div class="product-item-info cdz-list-inner">
                <?php if ($showThumbnail) : ?>
                <div class="product-item-top<?= $imageClass ?>">
                    <a href="<?= $productUrl ?>" class="product-item-photo">
                        <amp-img class="product-image-photo cdz-list-img" layout="responsive" src="<?php echo $imageHelper->init($_product, $image)->setImageFile($mainImage)->resize($width, $height)->getUrl() ?>" width="<?= $width ?>" height="<?= $height ?>"></amp-img>
                    </a>
                </div>
                <?php endif ?>
                <div class="product-item-detail<?= $detailClass ?>">
                    <strong class="product-item-name"><a class="product-item-link" title="<?= $productNameStripped ?>" href="<?= $productUrl ?>"><?= $productNameStripped ?></a></strong>
                    <?= $showPrice ? $block->getProductPrice($_product) : '' ?>
                    <?= $showRating ? $reviewRenderer->setProduct($_product)->toHtml() : ''; ?>
                    <?php if ($showDescTop) : ?>
                    <div class="product-item-description _mg-bottom-10">
                        <?= $ampHelper->subString($_helper->productAttribute($_product, $_product->getShortDescription(), 'short_description'), $descLength) ?>
                    </div>
                    <?php endif ?>
                    <div class="actions">
                        <?php if ($canAddToCart): ?>
                        <form class="cdz-amp-form" action-xhr="<?= $addToCartUrl ?>" method="post"
                            on="submit: AMP.setState({
                                adding_<?= $productId ?>: true
                            });
                            submit-success: AMP.setState({
                               page_message: event.response.message,
                               page_message_type: event.response.message_type,
                               adding_<?= $productId ?>: false
                            }), cdz-page-message-popup.show, cartInfo.refresh, cdz-minicart-list.refresh">
                            <input type="hidden" name="ajax" value="1" />
                            <input type="hidden" name="product" value="<?= $productId ?>" />
                            <?= $formKeyHtml ?>
                            <?= ($_product->getTypeId() === 'configurable')?$swatchesRenderer->setProduct($_product)->toHtml():''; ?>
                            <button class="btn-small btn-primary _btn-cart" [text]="adding_<?= $productId ?> ? '<?= $addingText ?>' : '<?= $addToCartText ?>'"><?= $addToCartText ?></button>
                        </form>
                        <?php elseif ($_product->getIsSalable()): ?>
                        <a class="btn-small btn-primary _btn-cart" href="<?= $productUrl ?>"><?= $viewProductText ?></a>
                        <?php else: ?>
                        <span class="btn-small btn-primary _btn-cart _disabled"><?= __('Out of stock') ?></span>
                        <?php endif ?>
                    </div>
                    <?php if ($showDescBot) : ?>
                    <div class="product-item-description _mg-top-10">
                        <?= $ampHelper->subString($_helper->productAttribute($_product, $_product->getShortDescription(), 'short_description'), $descLength) ?>
                    </div>
                    <?php endif ?>
                </div>
            </div>
        </li>
        <?php endforeach ?>
    </ul>
    <?= $layout->getBlock('product_list_toolbar')->setToolbarPosition('bottom')->toHtml() ?>
</div>
<?php else : ?>
<?= $block->getBlockHtml('amp-catalog-navigation-state') ?>
<p class="cdz-amp-msg notice">
    <span class="cdz-amp-text"><?= __('We can\'t find products matching the selection.') ?></span>
</p>
<?php endif ?>