<?php

namespace Solwin\ProductWidget\Block\Widget;

class BestList extends \Magento\Catalog\Block\Product\AbstractProduct implements \Magento\Widget\Block\BlockInterface {

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

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

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

    /**
     * url helper
     *
     * @var \Magento\Framework\Url\Helper\Data
     */
    protected $urlHelper;

    /**
     * Initialize
     *
     * @param \Magento\Catalog\Block\Product\Context $context
     * @param \Magento\Catalog\Model\ResourceModel\Product\Collection $collection
     * @param \Magento\Reports\Model\ResourceModel\Product\Sold\Collection $soldcollection
     * @param \Magento\Framework\Url\Helper\Data $urlHelper
     * @param array $data
     */
    public function __construct(
        \Magento\Catalog\Block\Product\Context $context,
        \Magento\Catalog\Model\ResourceModel\Product\Collection $collection,
        \Magento\Reports\Model\ResourceModel\Product\Sold\Collection $soldcollection,
        \Magento\Framework\Url\Helper\Data $urlHelper,
        array $data = []
    ) {
        $this->_soldcollection = $soldcollection;
        $this->_collection = $collection;
        $this->urlHelper = $urlHelper;
        parent::__construct($context, $data);
        $this->setTemplate('widget/tabs.phtml');

        if ($this->_storeManager->hasSingleStore()) {
            $this->setStoreId($this->_storeManager->getStore(true)->getId());
        }
    }

    /**
     * Get product collection
     */
    protected function getBestSellerProducts() {
        $limit = $this->getData('items');
        
        $itemsCollection = $this->_soldcollection
                ->addAttributeToSelect('*')
                ->addAttributeToSelect('id')
                ->addOrderedQty()
                ->setOrder('ordered_qty', 'desc');


        $itemsCollection->getSelect()->columns('item_id');

        $prod = array();
        if (sizeof($itemsCollection) > 0) {
            foreach ($itemsCollection as $item) {
                $prod[] = $item->getItemId();
            }
        }

        $collection = $this->_collection
                ->addMinimalPrice()
                ->addFinalPrice()
                ->addTaxPercents()
                ->addAttributeToSelect('name')
                ->addAttributeToSelect('image')
                ->addAttributeToSelect('small_image')
                ->addAttributeToSelect('thumbnail')
                ->addAttributeToFilter('is_saleable', 1, 'left');

        $collection->getSelect()->where('e.entity_id IN(?)', $prod)->order('rand()')->limit($limit);

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

    /* get loaded product collection */

    public function getBeastsellerLoadedProductCollection() {
        return $this->getBestSellerProducts();
    }

    public function getHotDealsProducts() {
        $limit = $this->getData('items');

        $this->_collection->clear()->getSelect()->reset('where');
        $todaydate = date('Y-m-d');
        $collection = $this->_collection
                ->addMinimalPrice()
                ->addFinalPrice()
                ->addTaxPercents()
                ->addAttributeToSelect('name')
                ->addAttributeToFilter('special_price', array('neq' => ''))
                ->addAttributeToSelect('special_from_date')
                ->addAttributeToSelect('special_to_date')
                ->addAttributeToSelect('image')
                ->addAttributeToSelect('small_image')
                ->addAttributeToSelect('thumbnail')
                ->addAttributeToFilter(array(
                    array(
                        'attribute' => 'special_from_date',
                        'lteq' => date('Y-m-d G:i:s', strtotime($todaydate)),
                        'date' => true,
                    ),
                    array(
                        'attribute' => 'special_to_date',
                        'gteq' => date('Y-m-d G:i:s', strtotime($todaydate)),
                        'date' => true,
                    )
                ))
                ->addAttributeToFilter('is_saleable', 1, 'left');

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

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

    /* get loaded product collection */

    public function getHotDealsLoadedProductCollection() {
        return $this->getHotDealsProducts();
    }

    public function getFeaturedProducts() {
        $limit = $this->getData('items');

        $this->_collection->clear()->getSelect()->reset('where');
        $collection = $this->_collection
                ->addMinimalPrice()
                ->addFinalPrice()
                ->addTaxPercents()
                ->addAttributeToSelect('name')
                ->addAttributeToSelect('image')
                ->addAttributeToSelect('small_image')
                ->addAttributeToSelect('thumbnail')
                ->addAttributeToFilter('is_saleable', 1, 'left')
                ->addAttributeToFilter('is_featured', 1, 'left');

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

        $this->_productCollection = $collection;
        return $this->_productCollection;
    }
    
    /* get loaded product collection */

    public function getFeaturedLoadedProductCollection() {
        return $this->getFeaturedProducts();
    }

    /* get mode */

    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),
            ]
        ];
    }

}
