<?php

namespace MGS\FakeOrder\Block;

use Magento\Catalog\Helper\Image as ImageHelper;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\View\Element\Template;
use MGS\FakeOrder\Model\FakeOrder;
use Magento\Framework\App\Config\ScopeConfigInterface;

class FakeOrderPopUp extends Template
{
    /**
     * @var FakeOrder
     */
    protected $fakeOrder;

    /**
     * @var ScopeConfigInterface
     */
    protected $scopeConfig;

    public    $themeSettingConfig;
    protected $_productRepository;
    protected $_productCollectionFactory;
    protected $imageHelper;
    protected $categoryCollectionFactory;


    /**
     *
     * @param Template\Context $context
     * @param FakeOrder $fakeOrder
     * @param ScopeConfigInterface $scopeConfig
     * @param array $data
     */
    public function __construct(
        Template\Context                                               $context,
        FakeOrder                                                      $fakeOrder,
        ScopeConfigInterface                                           $scopeConfig,
        \MGS\ThemeSettings\Helper\Config                               $themeSettingConfig,
        \Magento\Catalog\Model\ProductRepository                       $productRepository,
        ImageHelper                                                    $imageHelper,
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
        array                                                          $data = []
    )
    {
        $this->fakeOrder = $fakeOrder;
        $this->scopeConfig = $scopeConfig;
        $this->themeSettingConfig = $themeSettingConfig;
        $this->_productRepository = $productRepository;
        $this->imageHelper = $imageHelper;
        $this->_productCollectionFactory = $productCollectionFactory;
        parent::__construct($context, $data);
    }

    public function getProductById($id)
    {
        return $this->_productRepository->getById($id);
    }

    public function getProductCollectionByCategories($id, $limit = 0)
    {
        $collection = $this->_productCollectionFactory->create();
        $collection->addAttributeToSelect('*');
        $collection->addCategoriesFilter(['in' => [$id]]);
        $collection->setPageSize($limit ?? 5);
        return $collection;
    }

    /**
     *
     * @return array
     */
    public function getFakeOrders()
    {
        $type = (int)$this->themeSettingConfig->getStoreConfig('fakeorder/fakeorder_settings/get_product_by');
        $limit = $this->themeSettingConfig->getStoreConfig('fakeorder/fakeorder_settings/number_product') ?? 5;
        if ($type == 1) {
            $ids = $this->themeSettingConfig->getStoreConfig('fakeorder/fakeorder_settings/select2_product');
            $aIds = explode(',', $ids ?? '');
            if (!empty($aIds)) {
                $aProducts = [];
                $aIds = array_slice($aIds, 1, $limit);
                foreach ($aIds as $id) {
                    $oProducts = $this->getProductById($id);
                    $imageUrl = $this->imageHelper->init($oProducts, 'product_base_image')
                        ->setImageFile($oProducts->getImage())
                        ->getUrl();
                    $aProducts[] = [
                        'title'    => $oProducts->getName(),
                        'image'    => $imageUrl,
                        'url'      => $oProducts->getProductUrl(),
                        'location' => $this->getRandomLocation()
                    ];
                }

                return $aProducts;
            }

        }
        if ($type == 2) {
            $catId = $this->themeSettingConfig->getStoreConfig('fakeorder/fakeorder_settings/select_by_catalog');
            $aProductCollection = $this->getProductCollectionByCategories($catId, $limit);
            if (!empty($aProductCollection)) {
                $aProducts = [];
                foreach ($aProductCollection as $oProducts) {
                    $imageUrl = $this->imageHelper->init($oProducts, 'product_base_image')
                        ->setImageFile($oProducts->getImage())
                        ->getUrl();
                    $aProducts[] = [
                        'title'    => $oProducts->getName(),
                        'image'    => $imageUrl,
                        'url'      => $oProducts->getProductUrl(),
                        'location' => $this->getRandomLocation()
                    ];
                }

                return $aProducts;
            }
        }
        return $this->fakeOrder->getFakeOrders();
    }

    private function getRandomLocation()
    {
        $locations = ['New York, USA', 'London, UK', 'Sydney, Australia', 'Tokyo, Japan', 'Berlin, Germany'];
        return $locations[array_rand($locations)];
    }

    /**
     *
     * @return int
     */
    public function getProductsCount()
    {
        return $this->themeSettingConfig->getStoreConfig('fakeorder/fakeorder_settings/number_product')??5;
    }

    /**
     *
     * @return int
     */
    public function getPopupInterval()
    {
        return (int)$this->themeSettingConfig->getStoreConfig('fakeorder/fakeorder_settings/number_product')??5;
    }
    public function getPopupDisplayAfterSeconds()
    {
        return (int)$this->themeSettingConfig->getStoreConfig('fakeorder/fakeorder_settings/display_after_seconds')??20;
    }

    /**
     * @return bool
     */
    public function isPopupEnabled()
    {
        return !empty($this->themeSettingConfig->getStoreConfig('fakeorder/fakeorder_settings/active'));
    }

    /**
     *
     * @return array
     */
    public function getSelectedProductIds()
    {
        return explode(',', $this->scopeConfig->getValue(
            'fakeorder/settings/product_collection',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        ));
    }
}
