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

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

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
use WriteTextAI\WriteTextAI\Model\ApiManager;
use WriteTextAI\WriteTextAI\Helper\Product as ProductHelper;
use Magento\Catalog\Helper\Output as OutputHelper;

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

    /**
     * @var ProductHelper
     */
    protected $productHelper;

    /**
     * @var OutputHelper
     */
    protected $outputHelper;

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

    /**
     * Execute
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $response = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        
        try {
            $selected = $this->getRequest()->getParam('selected');
            $recordId = $this->getRequest()->getParam('product_id');
            $storeId = $this->getRequest()->getParam('store_id');
            $text = $this->getRequest()->getParam('product_name');

            $product = $this->productHelper->getProduct($recordId, $storeId);
            $productName = $this->outputHelper->productAttribute(
                $product,
                $text,
                'name'
            );

            $audience = $this->apiManager->selectAudience(
                $storeId,
                $recordId,
                $productName,
                $selected
            );

            $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;
    }
}
