<?php
/**
 * @author    Webarian Team
 * @copyright Copyright (c) 2020 Webarian (https://www.webariansoftwares.com/)
 * @package   Webarian_PromoPopup
 */
namespace Webarian\Workshop\Controller\Adminhtml\Workshop;

use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;

class Edit extends \Magento\Backend\App\Action
{
	protected $resultPageFactory;

	public function __construct(
		Context $context,
		PageFactory $resultPageFactory
	) {
		$this->resultPageFactory = $resultPageFactory;
		parent::__construct($context);
	}

	protected function _initAction()
	{
		// load layout, set active menu and breadcrumbs
		/** @var \Magento\Backend\Model\View\Result\Page $resultPage */
		$resultPage = $this->resultPageFactory->create();
		$resultPage->setActiveMenu('Webarian_Workshop::workshop_workshop')
			->addBreadcrumb(__('Workshop Manager'), __('Workshop Manager'))
			->addBreadcrumb(__('Workshop Manager'), __('Workshop Manager'));
		return $resultPage;
	}

	public function execute()
	{	
		// 1. Get ID and create model
		$id = $this->getRequest()->getParam('id');
		$model = $this->_objectManager->create('Webarian\Workshop\Model\Workshop');

		// 2. Initial checking
		if ($id) {
			$model->load($id);
			if (!$model->getId()) {
				$this->messageManager->addError(__('This workshop no longer exists.'));
				/** \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
				$resultRedirect = $this->resultRedirectFactory->create();

				return $resultRedirect->setPath('*/*/');
			}
		}
		if ($model->getWorkshopId() || $id == 0) {
			// 3. Set entered data if was error when we do save
			$data = $this->_objectManager->get('Magento\Backend\Model\Session')->getFormData(true);
			if (!empty($data)) {
				$model->setData($data);
			}
			
			// 4. Register model to use later in blocks
			$_coreRegistry = $this->_objectManager->get('\Magento\Framework\Registry');
			$_coreRegistry->register('workshop_workshop', $model);

			// 5. Build edit form
			/** @var \Magento\Backend\Model\View\Result\Page $resultPage */
			$resultPage = $this->_initAction();
			$resultPage->addBreadcrumb(
				$id ? __('Edit Workshop') : __('New Workshop'),
				$id ? __('Edit Workshop') : __('New Workshop')
			);
			$resultPage->addContent(
				$this->_view->getLayout()->createBlock('\Webarian\Workshop\Block\Adminhtml\Workshop\Edit')
			);
			$resultPage->addLeft(
				$this->_view->getLayout()->createBlock('\Webarian\Workshop\Block\Adminhtml\Workshop\Edit\Tabs')
			);

			$resultPage->getConfig()->getTitle()->prepend(__('Workshop'));
			$resultPage->getConfig()->getTitle()
				->prepend($model->getId() ? $model->getTitle() : __('New Workshop'));
			return $resultPage;
		}
	}
}