<?php

namespace FiloBlu\ActiveCampaign\Controller\Adminhtml\Jobs;

use FiloBlu\ActiveCampaign\Model\Jobs;
use Magento\Backend\App\Action;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Framework\Controller\ResultInterface;

/**
 * Class Save
 * @package FiloBlu\ActiveCampaign\Controller\Adminhtml\Jobs
 */
class Save extends Action
{
    /**
     * @return ResponseInterface|Redirect|ResultInterface
     */
    public function execute()
    {
        $id = $this->getRequest()->getParam('id');
        $status = $this->getRequest()->getParam('status');

        if (!($job = $this->_objectManager->create(Jobs::class)->load($id))) {
            $this->messageManager->addErrorMessage(__('Unable to proceed. Please, try again.'));
            $resultRedirect = $this->resultRedirectFactory->create();
            return $resultRedirect->setPath('*/*/edit/id/' . $id, ['_current' => true]);
        }

        try {
            $job->setStatus($status)->save();
            $this->messageManager->addSuccessMessage(__('Your job has been saved !'));
        } catch (\Exception $e) {
            $this->messageManager->addErrorMessage(__('Error while trying to save job: '));
            $resultRedirect = $this->resultRedirectFactory->create();
            return $resultRedirect->setPath('*/*/edit/id/' . $id, ['_current' => true]);
        }

        $resultRedirect = $this->resultRedirectFactory->create();
        return $resultRedirect->setPath('*/*/edit/id/' . $id, ['_current' => true]);
    }
}
