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

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\Category;
use Mageplaza\Faqs\Helper\File as HelperFile;
use Mageplaza\Faqs\Model\Category as CategoryModel;
use Mageplaza\Faqs\Model\CategoryFactory;
use Mageplaza\Faqs\Model\Config\Source\IconType;
use RuntimeException;

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

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

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

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

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

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

        if ($data = $this->getRequest()->getPost('category')) {
            /** @var CategoryModel $category */
            $category = $this->initCategory();

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

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

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

                return $resultRedirect;
            }

            if ($category->getData('error') && !$category->getData('icon_custom_path')) {
                $this->messageManager->addErrorMessage(__('File size is too big.'));
            } else {
                try {
                    $category->save();

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

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

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

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

            return $resultRedirect;
        }

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

        return $resultRedirect;
    }

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

        if ($category->getCreatedAt() == null) {
            $data['created_at'] = $this->date->date();
        }
        $data['updated_at'] = $this->date->date();
        $category->addData($data);

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

        return $this;
    }
}
