<?php
/**
 * @author    Webarian Team
 * @copyright Copyright (c) 2020 Webarian (https://www.webariansoftwares.com/)
 * @package   Webarian_PromoPopup
 */
namespace Webarian\Workshop\Observer;
use Magento\Framework\App\PageCache\Version;
use Magento\Framework\App\Cache\TypeListInterface;
use Magento\Framework\App\Cache\Frontend\Pool;

class AdminWorkshopObserver implements \Magento\Framework\Event\ObserverInterface {
    
      protected $_objectManager;
      protected $_workshopFactory;
      protected $_request;
      protected $redirect;
      protected $_messageManager;
      protected $cacheTypeList;
      protected $cacheFrontendPool;
      protected $_resource;

      public function __construct(
          \Magento\Framework\ObjectManagerInterface $objectManager,
          \Webarian\Workshop\Model\WorkshopFactory $workshopFactory,
          \Magento\Framework\App\RequestInterface $request,
          \Magento\Framework\App\Response\RedirectInterface $redirect,
          \Magento\Framework\Message\ManagerInterface $messageManager,
          TypeListInterface $cacheTypeList,
          Pool $cacheFrontendPool,
          \Magento\Framework\App\ResourceConnection $resource
      ) {
          $this->_objectManager = $objectManager;
          $this->_workshopFactory = $workshopFactory;
          $this->_request = $request;
          $this->redirect = $redirect;
          $this->_messageManager = $messageManager;
          $this->cacheTypeList = $cacheTypeList;
          $this->cacheFrontendPool = $cacheFrontendPool;
          $this->_resource = $resource;
      }

      public function execute(\Magento\Framework\Event\Observer $observer) {
        //$data = $this->getRequest()->getParams();
         $data = $observer->getData('custom_data');
         $price = $data['price'] + 0;
         $sku = strtolower($data['title']);
         $sku = str_replace(' ', '_', $sku);

         
         $workshopObj = $this->_workshopFactory->create();
         $product = $this->_objectManager->create('Magento\Catalog\Model\Product');    

         if(isset($data['workshop_id']) && $data['workshop_id'] != ''){
            $workshopId = $data['workshop_id'];
            $workshopObj->load($workshopId);
            $productId = $workshopObj->getData('product_id');

            $productId = $product->getIdBySku($sku);

            if($product->getIdBySku($sku) == $productId) {
              $product->load($productId);
            }else{
              $this->_messageManager->addError('"'.$sku.'" is already exist. please change workshop name.!!');
              return $this;
            }
         }else{

            if($product->getIdBySku($sku)) {
              //$this->_request->setPostValue('product_id', $product->getIdBySku($sku));
              //return $this;
              //$productId = $product->getIdBySku($sku);
              //$product->load($productId);
              $this->_messageManager->addError('"'.$sku.'" is already exist. please change workshop name.!!');
              return $this;
            }
         }

          $storeManager = $this->_objectManager->get(\Magento\Store\Model\StoreManagerInterface::class);
          $baseUrl = $storeManager->getStore()->getBaseUrl();

          $product->setName($data['title']); // Set Product Name
          $product->setTypeId('virtual'); // Set Product Type Id
          $product->setAttributeSetId(4); // Set Attribute Set ID
          $product->setSku($sku); // Set SKU
          $product->setStatus(1); // Set Status

          $product->setDescription('<p>virtual Product Description</p>');
          $product->setShortDescription('<p>virtual Product Short Description</p>');

          $product->setTaxClassId(0); // Set Tax Class Id
          $product->setWebsiteIds([1]); // Set Website Ids
          $product->setVisibility(4);
          $product->setCategoryIds([]); // Assign Category Ids
          $product->setPrice($price); // Product Price
          $product->setPriceType(0);
          $product->setPriceView(0);
          $product->setStockData(
                        array(
                            'use_config_manage_stock' => 0,
                            'manage_stock' => 1,
                            'is_in_stock' => 1,
                            'qty' => $data['capacity']
                        )
                    );
          //$product->setImage('/downloadable/test.jpg'); // Image Path
          //$product->setSmallImage('/downloadable/test.jpg'); // Small Image Path
          //$product->setThumbnail('/downloadable/test.jpg'); // Thumbnail Image Path
          try {
             $product->save();
          } catch (Exception $ex) {
              return $this;
          }
          
            $productId = $product->getId();
            $this->_request->setPostValue('product_id',$productId);
          return $this;
      }

      public function reindexAll() {
          $indexerFactory = $this->_objectManager->get('Magento\Indexer\Model\IndexerFactory');
          $indexerIds = array(
              'catalog_category_product',
              'catalog_product_category',
              'catalog_product_price',
              'catalog_product_attribute',
              'cataloginventory_stock',
              'catalogrule_product',
              'catalogsearch_fulltext',
          );
          foreach ($indexerIds as $indexerId) {
              //echo " create index: ".$indexerId."\n";
              $indexer = $indexerFactory->create();
              $indexer->load($indexerId);
              $indexer->reindexAll();
          }
      }

      public function flushCache(Version $subject)
      {
        $_types = [
                  'config',
                  'layout',
                  'block_html',
                  'collections',
                  'reflection',
                  'db_ddl',
                  'eav',
                  'config_integration',
                  'config_integration_api',
                  'full_page',
                  'translate',
                  'config_webservice'
                  ];
       
          foreach ($_types as $type) {
              $this->cacheTypeList->cleanType($type);
          }
          foreach ($this->cacheFrontendPool as $cacheFrontend) {
              $cacheFrontend->getBackend()->clean();
          }
      }

}