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

namespace WriteTextAI\WriteTextAI\Controller\Adminhtml\Categories\Edit\Audience;

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

class Get extends Action
{
    /**
     * @var ApiManager
     */
    protected $apiManager;

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

    /**
     * Execute
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $response = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        
        try {
            $categoryId = $this->getRequest()->getParam('category_id');
            $storeId = $this->getRequest()->getParam('store_id');
            $keywords = $this->getRequest()->getParam('keywords');
            $categoryName = $this->getRequest()->getParam('category_name');
            $regenerate = $this->getRequest()->getParam('regenerate', 'true');

            $allKeywords = [$categoryName];
            if (!empty($keywords)) {
                $allKeywords = array_merge($allKeywords, array_map('strtolower', $keywords));
            }
            $audience = $this->apiManager->getSuggestedAudience(
                $storeId,
                $categoryId,
                $allKeywords,
                $regenerate,
                'Category'
            );
            
            $result = [
                'success' => true,
                'selected' => $audience['selected'] ?? [],
                'values' => $audience['values'] ?? []
            ];
        } 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;
    }
}
