<?php
namespace PortalPeople\DisabledDates\Controller\Adminhtml\Date;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use PortalPeople\DisabledDates\Model\DisabledDateFactory;
use PortalPeople\DisabledDates\Model\ResourceModel\DisabledDate;

class Save extends Action
{
    protected $disabledDateFactory;
    protected $disabledDateResource;

    public function __construct(
        Context $context,
        DisabledDateFactory $disabledDateFactory,
        DisabledDate $disabledDateResource
    ) {
        parent::__construct($context);
        $this->disabledDateFactory = $disabledDateFactory;
        $this->disabledDateResource = $disabledDateResource;
    }

    public function execute()
    {
        $resultRedirect = $this->resultRedirectFactory->create();
        $data = $this->getRequest()->getPostValue();

        if ($data) {
            $id = $this->getRequest()->getParam('entity_id');
            $model = $this->disabledDateFactory->create();

            if ($id) {
                $this->disabledDateResource->load($model, $id);
                if (!$model->getId()) {
                    $this->messageManager->addErrorMessage(__('This disabled date no longer exists.'));
                    return $resultRedirect->setPath('*/*/');
                }
            }

            $model->setData($data);

            try {
                $this->disabledDateResource->save($model);
                $this->messageManager->addSuccessMessage(__('You saved the disabled date.'));

                if ($this->getRequest()->getParam('back')) {
                    return $resultRedirect->setPath('*/*/edit', ['entity_id' => $model->getId()]);
                }
                return $resultRedirect->setPath('*/*/');
            } catch (\Exception $e) {
                $this->messageManager->addErrorMessage($e->getMessage());
                return $resultRedirect->setPath('*/*/edit', ['entity_id' => $this->getRequest()->getParam('entity_id')]);
            }
        }

        return $resultRedirect->setPath('*/*/');
    }

    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed('PortalPeople_DisabledDates::disabled_dates');
    }
}
