<?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\Tag;

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\LocalizedException;
use Magento\Framework\Registry;
use Magento\Framework\Stdlib\DateTime\DateTime;
use Mageplaza\Faqs\Controller\Adminhtml\Tag;
use Mageplaza\Faqs\Model\Tag as TagModel;
use Mageplaza\Faqs\Model\TagFactory;
use RuntimeException;

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

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

    /**
     * Save constructor.
     *
     * @param Context $context
     * @param Registry $registry
     * @param TagFactory $tagFactory
     * @param Js $jsHelper
     * @param DateTime $date
     */
    public function __construct(
        Context $context,
        Registry $registry,
        TagFactory $tagFactory,
        Js $jsHelper,
        DateTime $date
    ) {
        $this->jsHelper = $jsHelper;
        $this->date     = $date;

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

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

        if ($data = $this->getRequest()->getPost('tag')) {
            /** @var TagModel $tag */
            $tag = $this->initTag();

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

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

            if (!$tag->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_tag_data', $tag->getData());
                $resultRedirect->setPath('mpfaqs/*/edit', ['id' => $tag->getId(), '_current' => true]);

                return $resultRedirect;
            }

            try {
                $tag->save();

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

                if ($this->getRequest()->getParam('back')) {
                    $resultRedirect->setPath('mpfaqs/*/edit', ['id' => $tag->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 Tag.')
                );
            }

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

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

            return $resultRedirect;
        }

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

        return $resultRedirect;
    }

    /**
     * @param TagModel $tag
     * @param array $data
     *
     * @return $this
     */
    protected function _prepareData($tag, $data = [])
    {
        if ($tag->getCreatedAt() === null) {
            $data['created_at'] = $this->date->date();
        }

        $data['updated_at'] = $this->date->date();
        $tag->addData($data);

        $articles = $this->getRequest()->getPost('articles');
        if (isset($articles)) {
            $tag->setIsArticleGrid(true);
            $tag->setArticlesIds(
                $this->jsHelper->decodeGridSerializedInput($articles)
            );
        }

        return $this;
    }
}
