<?php
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_AdvanceSeoManager
 * @author    Webkul
 * @copyright Copyright (c) Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */

namespace Webkul\AdvanceSeoManager\Observer;

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

/**
 * Webkul AdvanceSeoManager AfterProductSave Observer.
 */
class AfterProductSave implements ObserverInterface
{

    /**
     * @var Webkul\AdvanceSeoManager\Model\PingService
     */
    protected $_pingService;

    /**
     * @var \Webkul\AdvanceSeoManager\Helper\Data
     */
    protected $helper;

    /**
     * @var \Magento\Framework\App\RequestInterface
     */
    protected $request;

    /**
     * @var Magento\Catalog\Model\Product
     */
    protected $productFactory;

    /**
     * @var \Magento\MediaStorage\Model\File\UploaderFactory
     */
    protected $_fileUploaderFactory;
    
    /**
     * @var string
     */
    protected $_mediaDirectory;

    /**
     * @var \Magento\Framework\Filesystem\Io\File
     */
    protected $io;

    public function __construct(
        \Webkul\AdvanceSeoManager\Model\PingService $pingService,
        \Webkul\AdvanceSeoManager\Helper\Data $helper,
        \Magento\Framework\App\RequestInterface $request,
        \Magento\Catalog\Model\ProductFactory $productFactory,
        Filesystem $filesystem,
        \Webkul\AdvanceSeoManager\Logger\PingLogger $logger,
        \Magento\MediaStorage\Model\File\UploaderFactory $fileUploaderFactory,
        \Magento\Framework\Filesystem\Io\File $io,
        \Webkul\AdvanceSeoManager\Model\Sitemap $sitemap,
        \Magento\Sitemap\Model\ResourceModel\Sitemap\CollectionFactory $collectionFactory
    ) {
        $this->_mediaDirectory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA);
        $this->_fileUploaderFactory = $fileUploaderFactory;
        $this->_pingService = $pingService;
        $this->helper = $helper;
        $this->request = $request;
        $this->logger = $logger;
        $this->productFactory = $productFactory;
        $this->io = $io;
        $this->sitemap = $sitemap;
        $this->collectionFactory = $collectionFactory;
    }

     /**
      * send ping after product save
      *
      * @param \Magento\Framework\Event\Observer $observer
      */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        if ($this->helper->getIsEnable()) {
            try {
                if ($this->helper->getIsAutoPingEnable()) {
                    $serviceData = [];
                    $product = $observer->getProduct();
                    $frontProduct = clone $product;
                    if ($product && $product->getId()) {
                        $serviceData['title'] =  $frontProduct->getName();
                        $serviceData['url'] =  $frontProduct->setStoreId(1)->getProductUrl();
                        $serviceData['rss_url'] =  '';
                        $serviceData['service'] = $this->helper->getAutoPingService();
                        if ($this->helper->getAutoPingService() == 'custom') {
                            $serviceData['custom_url'] = $this->helper->getAutoPingCustomService();
                        }
                        $response = $this->_pingService->send($serviceData);
                        $this->saveProductData($product);
                        //@TODO log response
                    }
                }
            } catch (\Exception $e) {
                //@TODO log any errro message
                $this->logger->debug('After Save Product - '.$e->getMessage());
            }
            $collection = $this->collectionFactory->create();
            /* @var $collection \Magento\Sitemap\Model\ResourceModel\Sitemap\Collection */
            foreach ($collection as $sitemap) {
                /* @var $sitemap \Magento\Sitemap\Model\Sitemap */
                try {
                    $sitemap->generateXml();
                } catch (\Exception $e) {
                    $this->logger->debug($e->getMessage());
                }
            }
        }
    }

    /**
     * save seo attributes
     *
     * @return void
     */
    protected function saveProductData($product)
    {
        $images = (array)$this->request->getFiles();
        try {
            $flag = 0;
            if (isset($images['product']['facebook_image'])) {
                $target = $this->_mediaDirectory->getAbsolutePath('productseo/images/facebook/'.$product->getId().'/');
                if (!$this->io->fileExists($target)) {
                    $this->io->mkdir($target);
                }
    
                $uploader = $this->_fileUploaderFactory->create(
                    ['fileId' => 'product[facebook_image]']
                );
                $uploader->setAllowedExtensions(
                    ['jpg', 'jpeg', 'gif', 'png']
                );
                $uploader->setAllowRenameFiles(true);
                $this->removeFilesBeforeUpload($target);
                $result = $uploader->save($target);
                if (isset($result['name'])) {
                    $product->setData("facebook_image", $result['name']);
                    $flag = 1;
                }
            }

            if (isset($images['product']['twitter_image'])) {
                $target = $this->_mediaDirectory->getAbsolutePath('productseo/images/twitter/'.$product->getId().'/');
                if (!$this->io->fileExists($target)) {
                    $this->io->mkdir($target);
                }

                $uploader = $this->_fileUploaderFactory->create(
                    ['fileId' => 'product[twitter_image]']
                );
                $uploader->setAllowedExtensions(
                    ['jpg', 'jpeg', 'gif', 'png']
                );
                $uploader->setAllowRenameFiles(true);
                $this->removeFilesBeforeUpload($target);
                $result = $uploader->save($target);
                if (isset($result['name'])) {
                    $product->setData("twitter_image", $result['name']);
                    $flag = 1;
                }
            }

            if ($flag) {
                $product->save();
            }
        } catch (\Exception $e) {
            //@TODO log error
            $this->logger->debug('After Save Product - '.$e->getMessage());
        }
    }

    /**
     * remove all the files from the folder before uploading image
     *
     * @param  string $path
     * @return void
     */
    protected function removeFilesBeforeUpload($path)
    {
        $files = Glob::glob($path.'*');
        foreach ($files as $file) {
            if ($this->io->isFile($file)) {
                $this->io->deleteFile($file);
            }
        }
    }
}
