<?php

namespace FiloBlu\Flow\Controller\Adminhtml\Channel;

use Exception;
use FiloBlu\Flow\Model\ChannelFactory;
use Magento\Backend\App\Action;
use Magento\Backend\Model\Session;
use Magento\Framework\View\Result\PageFactory;
use RuntimeException;
use Throwable;

/**
 * Class Save
 * @package FiloBlu\Flow\Controller\Adminhtml\Channel
 */
class Save extends Action
{
    /**
     * @var ChannelFactory
     */
    protected $channelFactory;

    /**
     * Save constructor.
     * @param Action\Context $context
     * @param ChannelFactory $channelFactory
     */
    public function __construct(Action\Context $context, ChannelFactory $channelFactory)
    {
        $this->channelFactory = $channelFactory;
        parent::__construct($context);
    }

    /**
     * @var PageFactory
     */
    public function execute()
    {

        $data = $this->getRequest()->getParams();
        if ($data) {
            $model = $this->channelFactory->create();

            if (($id = $this->getRequest()->getParam('id')) !== null) {
                $model->load($id);
            }

            $model->setData($data);

            try {
                $model->save();
                $this->messageManager->addSuccessMessage(__('The Frist Grid Has been Saved.'));
                $this->_objectManager->get(Session::class)->setFormData(false);
                if ($this->getRequest()->getParam('back')) {
                    $this->_redirect('*/*/edit', ['id' => $model->getId(), '_current' => true]);
                    return;
                }
                $this->_redirect('*/*/');
                return;
            } catch (Exception $e) {
                $this->messageManager->addExceptionMessage($e, $e->getMessage());
            } catch (Throwable $t) {
                $this->messageManager->addExceptionMessage($t, __($t->getMessage()));
            }

            $this->_getSession()->setFormData($data);
            $this->_redirect('*/*/edit', ['banner_id' => $this->getRequest()->getParam('banner_id')]);
            return;
        }
        $this->_redirect('*/*/');
    }
}
