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

declare(strict_types=1);

namespace WriteTextAI\WriteTextAI\Controller\Adminhtml\Settings;

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

class SaveAdditionalPrompt extends Action
{
    /**
     * @var AiProductManager
     */
    protected $aiProductManager;

    /**
     * @var AiCategoryManager
     */
    protected $aiCategoryManager;

    /**
     * Constructor
     *
     * @param Context $context
     * @param AiProductManager $aiProductManager
     * @param AiCategoryManager $aiCategoryManager
     */
    public function __construct(
        Context $context,
        AiProductManager $aiProductManager,
        AiCategoryManager $aiCategoryManager
    ) {
        $this->aiProductManager = $aiProductManager;
        $this->aiCategoryManager = $aiCategoryManager;
        parent::__construct($context);
    }

    /**
     * Execute
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $response = $this->resultFactory->create(ResultFactory::TYPE_JSON);

        try {
            $params = $this->getRequest()->getParams();
            
            if ($params['entity_type'] === 'Product') {
                $this->aiProductManager->saveAdditionalPrompt(
                    $params['record_id'],
                    $params['store_id'],
                    $params['additional_prompt']
                );
            } else {
                $this->aiCategoryManager->saveAdditionalPrompt(
                    $params['record_id'],
                    $params['store_id'],
                    $params['additional_prompt']
                );
            }
            
            $result = [
                'success' => true
            ];
        } catch (\Exception $e) {
            $message = $e->getMessage();
            if (!$message) {
                $message = __(
                    'A system error has occurred. Please try again. If the issue persists,'
                    . ' please contact our support team at support@writetext.ai.'
                );
            }

            $result = [
                'success' => false,
                'message' => $message
            ];
        }

        $response->setData($result);

        return $response;
    }
}
