<?php
namespace Autogedal\BlogInternalLinking\Controller\Adminhtml\Group;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Autogedal\BlogInternalLinking\Model\GroupFactory;

class Save extends Action
{
    protected $groupFactory;

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

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

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

        if (!$postData) {
            return $redirect->setPath('*/*/');
        }

        // UI component forms nest field values under the fieldset name
        $data = $postData['general'] ?? $postData;
        if (isset($data['carousel_category_id']) && is_array($data['carousel_category_id'])) {
            $data['carousel_category_id'] = implode(',', array_filter(array_map('intval', $data['carousel_category_id'])));
        }

        $id   = (int)($data['group_id'] ?? 0);
        if (!$id) {
            unset($data['group_id']);
        }

        $group = $this->groupFactory->create();
        if ($id) {
            $group->load($id);
        }
        $group->addData($data);

        try {
            $group->save();
            $this->messageManager->addSuccess(__('Group saved successfully.'));
            if ($this->getRequest()->getParam('back')) {
                return $redirect->setPath('*/*/edit', ['group_id' => $group->getId()]);
            }
            return $redirect->setPath('*/*/');
        } catch (\Exception $e) {
            $this->messageManager->addError($e->getMessage());
            return $redirect->setPath('*/*/edit', ['group_id' => $id ?: null]);
        }
    }
}
