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

namespace WriteTextAI\WriteTextAI\Controller\Adminhtml\Edit\Pipelines;

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

class Save extends Action
{
    /**
     * @var Keywords
     */
    protected $keywords;

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

    /**
     * Execute action
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        $result = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        $pipeline = $this->getRequest()->getParam('pipeline');
        $keywords = [];
        $triggers = [];
        if (empty($pipeline)) {
            $result->setData([
                'error' => 'Pipeline data is empty'
            ]);
            return $result;
        }
        foreach ($pipeline['keywords'] as $key => $keyword) {
            $keywords[$key] = $keyword['keyword'];
        }
        $triggers = $pipeline['triggers'] ?? [];
        $pipelineId = $pipeline['id'] ?? null;

        try {
            if (empty($pipelineId)) {
                $apiResponse = $this->keywords->createPipeline(
                    $this->getRequest()->getParam('store_id'),
                    $this->getRequest()->getParam('record_id'),
                    $keywords,
                    $this->getRequest()->getParam('entity_type') ?? 'Product'
                );
            } else {
                $apiResponse = $this->keywords->updatePipeline(
                    $this->getRequest()->getParam('store_id'),
                    $this->getRequest()->getParam('record_id'),
                    $pipelineId,
                    $keywords,
                    $triggers,
                    $this->getRequest()->getParam('entity_type') ?? 'Product'
                );
            }
            $result->setData([
                'success' => true,
                'api_response' => $apiResponse ?? []
            ]);
        } 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->setData([
                'error' => $message,
                'trace' => $e->getTrace()
            ]);
        }

        return $result;
    }
}
