<?php

declare(strict_types=1);

namespace Leadlion\Autogedal\Cron;

use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\Catalog\Model\Product\Action;
use Psr\Log\LoggerInterface;

class GoogleDesc
{
    const XML_GOOGLE_FEED_PATH = 'leadlion/google_feed/product_type';
    const GOOGLE_DESC = 'google_descrip';

    private $scopeConfig;
    private $serializer;
    protected $resource;
    protected $productCollectionFactory;
    protected $storeManager;
    protected $emulation;
    private $productAction;
    protected $logger;

    public function __construct(
        \Magento\Framework\App\ResourceConnection $resource,
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Store\Model\App\Emulation $emulation,
        LoggerInterface $logger,
        ScopeConfigInterface $scopeConfig,
        SerializerInterface $serializer,
        Action $productAction
    ) {
        $this->storeManager = $storeManager;
        $this->emulation = $emulation;
        $this->resource = $resource;
        $this->productCollectionFactory = $productCollectionFactory;
        $this->scopeConfig = $scopeConfig;
        $this->serializer = $serializer;
        $this->productAction = $productAction;
        $this->logger = $logger;
    }

    public function execute()
    {
        $this->emulation->startEnvironmentEmulation(1, \Magento\Framework\App\Area::AREA_FRONTEND, true);

        $productCollection = $this->productCollectionFactory->create()
                                ->addAttributeToSelect('*')
                                ->addStoreFilter($this->storeManager->getStore()->getId());

        foreach ($productCollection as $product) {
            if (!$product->getGoogleDescrip()) {
                try {
                    $feedConfig = $this->getGoogleFeedConfig();
                    $categoriesIds = $product->getCategoryIds();
                    if (!empty($categoriesIds)) {
                        $googleCategoryDesc = $product->getName();
                        foreach ($categoriesIds as $key => $categoryId) {
                            if (isset($feedConfig[$categoryId])) {
                                $attrCodesArray = explode(',', $feedConfig[$categoryId]);
                                foreach ($attrCodesArray as $attrCode) {
                                    $value = $product->getAttributeText($attrCode);
                                    if ($value) {
                                        $googleCategoryDesc .= ', '.$value;
                                    }
                                }
                            }
                        }
                        $this->productAction->updateAttributes(
                            [$product->getEntityId()],
                            [self::GOOGLE_DESC => $googleCategoryDesc],
                            0
                        );
                        $this->logger->info($product->getSku());
                        $this->logger->info($googleCategoryDesc);
                    }
                } catch (\Throwable $exception) {
                    $this->logger->critical($exception);
                }
            }
        }

        $this->emulation->stopEnvironmentEmulation();
    }

    private function getGoogleFeedConfig()
    {
        $confSettings = $this->scopeConfig->getValue(
            self::XML_GOOGLE_FEED_PATH,
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
        $info = [];
        if ($confSettings) {
            $feedConfig = $this->serializer->unserialize($confSettings);

            $info = [];
            foreach ($feedConfig as $config) {
                $info[$config['category_id']] = $config['attributes_code'];
            }
        }
        
        return $info;
    }
}
