<?php

declare(strict_types=1);

namespace FiloBlu\Refilo\Plugins\CatalogWidget\Block\Product;

use FiloBlu\Refilo\Helper\Data;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Model\ResourceModel\Product\Collection;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\CatalogWidget\Block\Product\ProductsList;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\EntityManager\MetadataPool;
use Magento\Framework\Exception\LocalizedException;

/**
 * @class ProductsListPlugin
 * @package FiloBlu\Refilo\Plugins
 */
class ProductsListPlugin
{

    /**
     * @var Data
     */
    public $helper;

    /**
     * @param Data $helper
     */
    public function __construct(Data $helper)
    {
        $this->helper = $helper;
    }

    /**
     * Limit the product shown to the value given to the form
     *
     * @param ProductsList $subject
     * @param Collection $result
     * @return Collection
     * @see \Magento\CatalogWidget\Block\Product\ProductsList::createCollection
     */
    public function afterCreateCollection(ProductsList $subject, Collection $result)
    {
        if ($this->helper->getEnableFilteringByWebsiteOnProductWidgetCollection()) {
            $result->getSelect()->where('`price_index`.website_id = ?', 2);
        }

        if (!$subject->getProductsCount()) {
            return $result;
        }

        try {
            if (count($result->getItems()) <= $subject->getProductsCount()) {
                return $result;
            }

            /** reload the items with the limitations already set in the query */
            return $result->clear()->load();
        } catch (\Exception $e) {
            return $result;
        }


    }
}
