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

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Registry;
use Mageplaza\Faqs\Model\Tag as TagModel;
use Mageplaza\Faqs\Model\TagFactory;

/**
 * Class Tag
 * @package Mageplaza\Faqs\Controller\Adminhtml
 */
abstract class Tag extends Action
{
    /** Authorization level of a basic admin session */
    const ADMIN_RESOURCE = 'Mageplaza_Faqs::tag';

    /**
     * Article model factory
     *
     * @var TagFactory
     */
    public $tagFactory;

    /**
     * Core registry
     *
     * @var Registry
     */
    public $coreRegistry;

    /**
     * Article constructor.
     *
     * @param TagFactory $tagFactory
     * @param Registry $coreRegistry
     * @param Context $context
     */
    public function __construct(
        TagFactory $tagFactory,
        Registry $coreRegistry,
        Context $context
    ) {
        $this->tagFactory   = $tagFactory;
        $this->coreRegistry = $coreRegistry;

        parent::__construct($context);
    }

    /**
     * @param bool $register
     *
     * @return bool|TagModel
     */
    protected function initTag($register = false)
    {
        $tagId = (int) $this->getRequest()->getParam('id');

        if (!$tagId && $this->_session->getData('tag_id')) {
            $tagId = $this->_session->getData('tag_id');
        }
        /** @var TagModel $tag */
        $tag = $this->tagFactory->create();

        if ($tagId) {
            $tag->load($tagId);
            if (!$tag->getId()) {
                $this->messageManager->addErrorMessage(__('This tag no longer exists.'));

                return false;
            }
        }
        if ($register) {
            $this->coreRegistry->register('mageplaza_faqs_tag', $tag);
        }

        return $tag;
    }
}
