<?php
/**
 * Webkul Software.
 * 
 * PHP version 7.0+
 *
 * @category  Webkul
 * @package   Webkul_MobikulCore
 * @author    Webkul <support@webkul.com>
 * @copyright 2010-2019 Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html ASL Licence
 * @link      https://store.webkul.com/license.html
 */
namespace Webkul\MobikulCore\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\App\Filesystem\DirectoryList;

/**
 * ProductSaveAfterOvserver Class
 */
class ProductSaveAfterObserver implements ObserverInterface
{
    /**
     * @var RequestInterface
     */
    protected $request;

    /**
     * @var \Magento\Catalog\Model\ProductRepository
     */
    protected $productRepository;

    /**
     * @var ObjectManagerInterface
     */
    protected $objectManager;

    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $storeManager;

    /**
     * @var \Magento\Catalog\Model\ResourceModel\Product\Action
     */
    protected $productAction;

    /**
     *
     * @param RequestInterface                                    $request           request
     * @param \Magento\Framework\Filesystem                       $filesystem        filesystem
     * @param \Magento\Framework\Filesystem\Driver\File           $file              file
     * @param \Magento\Catalog\Model\ProductRepository            $productRepository productRepository
     * @param \Magento\Framework\ObjectManagerInterface           $objectManager     objectManager
     * @param \Magento\Store\Model\StoreManagerInterface          $storeManager      storeManager
     * @param \Magento\Catalog\Model\ResourceModel\Product\Action $productAction     productAction
     * @param \Magento\MediaStorage\Model\File\UploaderFactory    $uploaderFactory   uploaderFactory
     */
    public function __construct(
        RequestInterface $request,
        \Magento\Framework\Filesystem $filesystem,
        \Magento\Framework\Filesystem\Driver\File $file,
        \Magento\Catalog\Model\ProductRepository $productRepository,
        \Magento\Framework\ObjectManagerInterface $objectManager,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Catalog\Model\ResourceModel\Product\Action $productAction,
        \Magento\MediaStorage\Model\File\UploaderFactory $uploaderFactory
    ) {
        $this->request = $request;
        $this->file = $file;
        $this->filesystem = $filesystem;
        $this->fileUploaderFactory = $uploaderFactory;
        $this->productRepository = $productRepository;
        $this->objectManager = $objectManager;
        $this->productAction = $productAction;
        $this->storeManager = $storeManager;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $product = $observer->getEvent()->getProduct();
        $productData = $this->request->getParam('product');
        $files = $this->request->getFiles();
        $deleteArray = $this->request->getParam("texture_image_delete");
        $storeId = $this->request->getParam("store");
        $path = $this->filesystem->getDirectoryRead(
            DirectoryList::MEDIA
        )->getAbsolutePath(
            'catalog/product/ar/textureimage/'
        ).$product->getId();
        $textureImages = json_decode($product->getArTextureImage());
        if (!empty($deleteArray)) {
            $imageForDelete = [];
            $finalTextureImages = [];
            foreach ($deleteArray as $url => $delete) {
                if ($delete) {
                    foreach ($textureImages as $image) {
                        if (strpos($image, $url) !== false) {
                            $imageForDelete[] = $image;
                            $exploadedFileArr = explode("/", $image);
                            $fileName = $exploadedFileArr[count($exploadedFileArr) - 1];
                            if ($this->file->isExists($path."/".$fileName)) {
                                $this->file->deleteFile($path."/".$fileName);
                            }
                        }
                    }
                }
            }
            $finalTextureImages = array_diff((array)$textureImages, $imageForDelete);
        } else {
            $finalTextureImages = json_decode($product->getArTextureImage());
        }
        if (!empty($files["ar_texture_image"])) {
            $keys = array_keys($files["ar_texture_image"]);
            foreach ($keys as $value) {
                try {
                    /** @var $uploader \Magento\MediaStorage\Model\File\Uploader */
                    $uploader = $this->fileUploaderFactory->create(['fileId' => 'ar_texture_image['.$value.']']);
                    $uploader->setAllowedExtensions(['png', 'jpg', 'jpeg']);
                    $uploader->setAllowRenameFiles(true);
                    $result = $uploader->save($path);
                    $url = $this->getMediaUrl()."catalog/product/ar/textureimage/".$product->getId()."/".$result['file'];
                    $finalTextureImages[] = $url;
                } catch (\Exception $e) {
                }
            }
        }
        $this->productAction->updateAttributes([$product->getId()], ['ar_texture_image' => json_encode($finalTextureImages)], $storeId);
    }

    public function getMediaUrl()
    {
        return $this->storeManager->getStore()
            ->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
    }
}
