<?php

declare(strict_types=1);

namespace Leadlion\Autogedal\Cron;

use Magento\InventoryApi\Api\Data\SourceItemInterfaceFactory;
use Magento\InventoryCatalog\Model\ResourceModel\SetDataToLegacyStockItem;
use Magento\InventoryCatalog\Model\ResourceModel\SetDataToLegacyStockStatus;
use Magento\Catalog\Model\Product\Action;

class OosProducts
{
    protected $resource;
    protected $productCollectionFactory;
    protected $storeManager;
    protected $emulation;
    protected $customHelper;
    protected $historyFactory;
    protected $stockRegistry;
    protected $jobRepo;

    /**
     * @var Action
     */
    private $productAction;

    /**
     * @var SourceItemInterfaceFactory
     */
    private $sourceItemFactory;

    /**
     * @var SetDataToLegacyStockItem
     */
    private $setDataToLegacyStockItem;
    
    /**
     * @var SetDataToLegacyStockStatus
     */
    private $setDataToLegacyStockStatus;

    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,
        \Leadlion\Autogedal\Helper\Data $customHelper,
        \Firebear\ImportExport\Model\Import\HistoryFactory $historyFactory,
        \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry,
        \Firebear\ImportExport\Api\JobRepositoryInterface $jobRepo,
        SourceItemInterfaceFactory $sourceItemFactory,
        SetDataToLegacyStockItem $setDataToLegacyStockItem,
        SetDataToLegacyStockStatus $setDataToLegacyStockStatus,
        Action $productAction
    ) {
        $this->customHelper = $customHelper;
        $this->storeManager = $storeManager;
        $this->emulation = $emulation;
        $this->resource = $resource;
        $this->productCollectionFactory = $productCollectionFactory;
        $this->historyFactory = $historyFactory;
        $this->stockRegistry = $stockRegistry;
        $this->jobRepo = $jobRepo;
        $this->sourceItemFactory = $sourceItemFactory;
        $this->setDataToLegacyStockItem = $setDataToLegacyStockItem;
        $this->setDataToLegacyStockStatus = $setDataToLegacyStockStatus;
        $this->productAction = $productAction;
    }

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

    private function updateQtysByJobId($jobId){

        $skus=$this->getImportedSkus($jobId);
        if (!empty($skus)) {
            foreach ($skus as $key => $info) {
                $productCollection = $this->productCollectionFactory->create()
                    ->addAttributeToSelect('sku')
                    ->addAttributeToSelect('sku_fz')
                    ->addStoreFilter($this->storeManager->getStore()->getId())
                    ->addAttributeToFilter(
                        'sku_fz',
                        ['eq' => [$info['sku']]]
                    );
                foreach ($productCollection as $product) {
                    $stockItem = $this->stockRegistry->getStockItemBySku($product->getData('sku'));
                    $isInStock = false;
                    if ($info['qty'] > 0) {
                        $isInStock = true;
                    }
                    $stockItem->setManageStock(1);
                    $stockItem->setUseConfigManageStock(0);
                    $stockItem->setIsInStock($isInStock);
                    $stockItem->setQty((int)$info['qty']);
                    $this->stockRegistry->updateStockItemBySku($product->getData('sku'), $stockItem);
                }
                $this->deleteImportedSku($info['sku'],$jobId);
            }
        }

    }
    private function deleteImportedSku($sku,$jobId){
        $connection = $this->resource->getConnection();
        $oosProdTable = $this->resource->getTableName('leadlion_imported_skus');

        $connection->delete(
            $oosProdTable,
            ['job_id = ?' => $jobId],
            ['sku = ?' => $sku]
        );
    }
    private function getImportedSkus($jobId){
        $connection = $this->resource->getConnection();
        $oosProdTable = $this->resource->getTableName('leadlion_imported_skus');

        $select = $connection->select();
        $select->from(
            ['e' => $oosProdTable],
            ['id', 'job_id', 'sku','qty']
        )->where(
            'e.job_id = ?',
            $jobId
        );
        return $connection->fetchAll($select);
    }
}
