<?php
/**
 * Mageplaza
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Mageplaza.com license that is
 * available through the world-wide-web at this URL:
 * https://www.mageplaza.com/LICENSE.txt
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade this extension to newer
 * version in the future.
 *
 * @category    Mageplaza
 * @package     Mageplaza_Faqs
 * @copyright   Copyright (c) Mageplaza (https://www.mageplaza.com/)
 * @license     https://www.mageplaza.com/LICENSE.txt
 */

namespace Mageplaza\Faqs\Controller\Adminhtml\Article;

use Exception;
use Magento\Backend\App\Action\Context;
use Magento\Backend\Helper\Js;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\Exception\FileSystemException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Registry;
use Magento\Framework\Stdlib\DateTime\DateTime;
use Mageplaza\Faqs\Controller\Adminhtml\Article;
use Mageplaza\Faqs\Helper\Data;
use Mageplaza\Faqs\Helper\File as HelperFile;
use Mageplaza\Faqs\Model\Article as ArticleModel;
use Mageplaza\Faqs\Model\ArticleFactory;
use Mageplaza\Faqs\Model\Config\Source\IconType;
use RuntimeException;

/**
 * Class Save
 * @package Mageplaza\Faqs\Controller\Adminhtml\Article
 */
class Save extends Article
{
    /**
     * JS helper
     *
     * @var Js
     */
    public $jsHelper;

    /**
     * @var DateTime
     */
    public $date;

    /**
     * @var Data
     */
    protected $_helperData;

    /**
     * @var HelperFile
     */
    protected $helperFile;

    /**
     * Save constructor.
     *
     * @param Context $context
     * @param Registry $registry
     * @param ArticleFactory $articleFactory
     * @param Js $jsHelper
     * @param DateTime $date
     * @param Data $helperData
     * @param HelperFile $helperFile
     */
    public function __construct(
        Context $context,
        Registry $registry,
        ArticleFactory $articleFactory,
        Js $jsHelper,
        DateTime $date,
        Data $helperData,
        HelperFile $helperFile
    ) {
        $this->jsHelper    = $jsHelper;
        $this->date        = $date;
        $this->_helperData = $helperData;
        $this->helperFile  = $helperFile;

        parent::__construct($articleFactory, $registry, $context);
    }

    /**
     * Save data action
     *
     * @return ResponseInterface|Redirect|ResultInterface
     * @throws FileSystemException
     */
    public function execute()
    {
        $resultRedirect = $this->resultRedirectFactory->create();

        if ($data = $this->getRequest()->getPost('article')) {
            /** @var ArticleModel $article */
            $article = $this->initArticle();

            $this->_prepareData($article, $data);

            $this->_eventManager->dispatch(
                'mageplaza_faqs_article_prepare_save',
                ['article' => $article, 'request' => $this->getRequest()]
            );

            if (!$article->getIsUniqueFormToStores($data['store_ids'], $data['url_key'])) {
                $this->messageManager->addErrorMessage(__('The URL Key with the same properties already exists in the selected store.'));
                $this->_getSession()->setData('mageplaza_faqs_article_data', $article->getData());
                $resultRedirect->setPath('*/*/edit', ['id' => $article->getId(), '_current' => true]);

                return $resultRedirect;
            }

            if ($article->getData('error') && !$article->getData('icon_custom_path')) {
                $this->messageManager->addErrorMessage(__('File size is too big.'));
            } else {
                try {
                    /** send email to customer when the question is answered */
                    if (!empty($article->getArticleContent())) {
                        $this->_helperData->sendEmailToCustomer($article);
                    }

                    $article->save();

                    $this->messageManager->addSuccessMessage(__('The article has been saved.'));
                    $this->_getSession()->setData('mageplaza_faqs_article_data', false);

                    if ($this->getRequest()->getParam('back')) {
                        $resultRedirect->setPath('mpfaqs/*/edit', ['id' => $article->getId(), '_current' => true]);
                    } else {
                        $resultRedirect->setPath('mpfaqs/*/');
                    }

                    return $resultRedirect;
                } catch (LocalizedException $e) {
                    $this->messageManager->addErrorMessage($e->getMessage());
                } catch (RuntimeException $e) {
                    $this->messageManager->addErrorMessage($e->getMessage());
                } catch (Exception $e) {
                    $this->messageManager->addExceptionMessage(
                        $e,
                        __('Something went wrong while saving the Article.')
                    );
                }
            }

            $this->_getSession()->setData('mageplaza_faqs_article_data', $data);

            $resultRedirect->setPath('mpfaqs/*/edit', ['id' => $article->getId(), '_current' => true]);

            return $resultRedirect;
        }

        $resultRedirect->setPath('mpfaqs/*/');

        return $resultRedirect;
    }

    /**
     * Set specific data
     *
     * @param ArticleModel $article
     * @param array $data
     *
     * @return $this
     * @throws FileSystemException
     */
    protected function _prepareData($article, $data = [])
    {
        /** @var ArticleModel $article */
        if ((int) $data['icon_type'] === IconType::CUSTOM) {
            $this->helperFile->uploadFile(
                $data,
                'icon_custom_path',
                HelperFile::TEMPLATE_MEDIA_TYPE_FILE,
                $article->getIconCustomPath()
            );
        } else {
            $data['icon_custom_path']   = null;
            $data['icon_custom_width']  = null;
            $data['icon_custom_height'] = null;
        }

        if (!$article->getCreatedAt()) {
            $data['created_at'] = $this->date->date();
        }

        if (!isset($data['email_notify'])) {
            $data['email_notify'] = 0;
        }

        $data['updated_at']     = $this->date->date();
        $data['categories_ids'] = (isset($data['categories_ids']) && $data['categories_ids'])
            ? explode(',', $data['categories_ids']) : [];
        $data['tags_ids']       = (isset($data['tags_ids']) && $data['tags_ids'])
            ? explode(',', $data['tags_ids']) : [];

        $article->addData($data);

        if ($tags = $this->getRequest()->getPost('tags', false)) {
            $article->setTagsData(
                $this->jsHelper->decodeGridSerializedInput($tags)
            );
        }

        $products = $this->getRequest()->getPost('products');
        if (isset($products)) {
            $article->setIsProductGrid(true);
            $article->setProductsIds(
                $this->jsHelper->decodeGridSerializedInput($products)
            );
        }

        $articles = $this->getRequest()->getPost('articles');
        if (isset($articles)) {
            $article->setIsRelatedArticleGrid(true);
            $article->setRelatedArticlesIds(
                $this->jsHelper->decodeGridSerializedInput($articles)
            );
        }

        return $this;
    }
}
