<?php
/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */

namespace WriteTextAI\WriteTextAI\Controller\Adminhtml\Grid;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use WriteTextAI\WriteTextAI\Model\UserFieldsSelectedManager;
use Magento\Framework\Controller\ResultFactory;

class SaveSettings extends Action
{
    /**
     * @var UserFieldsSelectedManager
     */
    protected $userFieldsSelectedManager;

    /**
     * Constructor
     *
     * @param Context $context
     * @param UserFieldsSelectedManager $userFieldsSelectedManager
     */
    public function __construct(
        Context $context,
        UserFieldsSelectedManager $userFieldsSelectedManager
    ) {
        $this->userFieldsSelectedManager = $userFieldsSelectedManager;
        parent::__construct($context);
    }

    /**
     * Execute
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $response = [];
        try {
            $params = $this->getRequest()->getParams();
            $entityType = $params['entity_type'] ?? 'product';
            foreach ($params as $param => $value) {
                if (in_array($param, [
                    UserFieldsSelectedManager::ACTION_TYPE_ENABLE_COMPARISON_POPUP
                ])) {
                    $this->userFieldsSelectedManager->saveUserFieldsSelected($value, $param, $entityType, 'grid');
                }
            }

            $response['success'] = true;
            $response['message'] = __('Settings successfully saved.');
        } catch (\Exception $e) {
            $response['success'] = false;
            $response['message'] = __(
                'A system error has occurred. Please try again. If the issue persists,'
                . ' please contact our support team at support@writetext.ai.'
            );
            $response['error'] = $e->getMessage();
            $response['trace'] = $e->getTrace();
        }

        return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($response);
    }
}
