<?php

namespace Leadlion\AutoRelated\Cron;

use Magento\Framework\App\ResourceConnection;
use Leadlion\AutoRelated\Helper\Data;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Filesystem\DirectoryList;

class Images
{
    const LINK_TYPE_UPSELL = 4;
    const CATEGORY_ID = 2118;

    protected $connection;
    protected $customHelper;
    protected $storeManager;

    /**
     * @var CollectionFactory
     */
    protected $collectionFactory;

    /**
     * @var SearchCriteriaBuilder
     */
    protected $criteriaBuilder;
    protected $directoryList;

    public function __construct(
        ResourceConnection $connection,
        Data $customHelper,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        SearchCriteriaBuilder $criteriaBuilder,
        CollectionFactory $collectionFactory,
        DirectoryList $directoryList
    ) {
        $this->collectionFactory = $collectionFactory;
        $this->connection = $connection;
        $this->customHelper = $customHelper;
        $this->storeManager = $storeManager;
        $this->criteriaBuilder = $criteriaBuilder;
        $this->directoryList = $directoryList;
    }

    public function execute()
    {
        $websiteProducts = $this->getWebsiteProducts();

        foreach ($websiteProducts as $product) {
            $mediaPath = $this->directoryList->getPath('media');
            $importDir = $mediaPath . '/catalog/product';


            $thumbnail = $product->getData('thumbnail');
            $smallImage = $product->getData('small_image');
            $baseImage = $product->getData('image');
            
            if (($thumbnail == "no_selection" && $smallImage == "no_selection") ||
                ($thumbnail == null && $smallImage == null)
            ) {
                $img_url = $importDir . $baseImage;
                $product->addImageToMediaGallery($img_url, ['image', 'small_image', 'thumbnail'], true, false);
                $product->save();
            }
        }
    }

    protected function getWebsiteProducts()
    {
        // $products = $this->productRepository->getList(
        //     $this->criteriaBuilder->addFilter(
        //         'visibility',
        //         $this->productVisibility->getVisibleInSiteIds(),
        //         'in'
        //     )->create()
        // );
        $productItems = $this->collectionFactory->create()
                            ->addAttributeToSelect('*')
                            ->addStoreFilter($this->storeManager->getStore()->getId())
                            ->addAttributeToFilter(
                                'attribute_set_id',
                                79
                            );
            
        return $productItems;
    }
}
