<?php

namespace Solwin\Cpanel\Block;

class PromotionalList extends \Magento\Catalog\Block\Product\AbstractProduct {

    /**
     * Product collection model
     *
     * @var Magento\Catalog\Model\Resource\Product\Collection
     */
    protected $_collection;

    /**
     * Product collection model
     *
     * @var Magento\Catalog\Model\Resource\Product\Collection
     */
    protected $_productCollection;

    protected $urlHelper;

    /**
     * Initialize
     *
     * @param Magento\Catalog\Block\Product\Context $context
     * @param array $data
     */
    
    public function __construct(
        \Magento\Catalog\Block\Product\Context $context,
        \Magento\Catalog\Model\ResourceModel\Product\Collection $collection,
        \Magento\Framework\Url\Helper\Data $urlHelper,
        array $data = []
    ) {
        $this->_collection = $collection;
        $this->urlHelper = $urlHelper;
        parent::__construct($context, $data);
        if ($this->getExtesionStatus()) {
            $this->pageConfig->getTitle()->set(__($this->getPageTitle()));
        }
    }

    /**
     * Get product collection
     */
    protected function getProducts() {
        $collection = $this->_collection
                ->addMinimalPrice()
                ->addFinalPrice()
                ->addTaxPercents()
                ->addAttributeToSelect('name')
                ->addAttributeToSelect('image')
                ->addAttributeToFilter('is_saleable', 1, 'left')
                ->addAttributeToFilter('is_promotional', 1, 'left');

        $collection->getSelect()
                ->order('rand()');

        // Set Pagination Toolbar for list page
        $pager = $this->getLayout()->createBlock('Magento\Theme\Block\Html\Pager', 'catalogpages.grid.record.pager')->setCollection($collection);
        $this->setChild('pager', $pager); // set pager block in layout

        $this->_productCollection = $collection;
        return $this->_productCollection;
    }

    public function getLoadedProductCollection() {
        return $this->getProducts();
    }

    public function getToolbarHtml() {
        return $this->getChildHtml('pager');
    }

    public function getMode() {
        return 'grid';
    }

    /**
     * Get image helper
     */
    public function getImageHelper() {
        return $this->_imageHelper;
    }

    public function getAddToCartPostParams(\Magento\Catalog\Model\Product $product) {
        $url = $this->getAddToCartUrl($product);
        return [
            'action' => $url,
            'data' => [
                'product' => $product->getEntityId(),
                \Magento\Framework\App\ActionInterface::PARAM_NAME_URL_ENCODED =>
                $this->urlHelper->getEncodedUrl($url),
            ]
        ];
    }

}
