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

namespace WriteTextAI\WriteTextAI\Controller\Adminhtml\Edit\KeywordsOptimization;

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

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

    /**
     * @var Category
     */
    protected $category;

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

    /**
     * Execute action
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        $response = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        $entityType = $this->getRequest()->getParam('entity_type') ?? 'Product';
        $categoryProducts = [];
        if ($entityType === 'Category') {
            $categoryProducts = $this->category->getAllProductsNameRandomly(
                $this->getRequest()->getParam('record_id'),
                $this->getRequest()->getParam('store_id')
            );
        }
        try {
            $apiResponse = $this->keywords->updateOptimization(
                $this->getRequest()->getParam('store_id'),
                $this->getRequest()->getParam('record_id'),
                $this->getRequest()->getParam('url'),
                $this->getRequest()->getParam('name'),
                $this->getRequest()->getParam('search_intent_selected'),
                $this->getRequest()->getParam('seed_keywords') ?? [],
                $entityType,
                $categoryProducts,
                $this->getRequest()->getParam('image_id')
            );
            $result = [
                '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 = [
                'success' => false,
                'error' => $message,
                'trace' => $e->getTrace()
            ];
        }

        $response->setData($result);

        return $response;
    }
}
