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

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

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
use WriteTextAI\WriteTextAI\Model\Categories\GeneratedText;
use WriteTextAI\WriteTextAI\Model\Categories\MarkReview;

class Get extends Action
{
    public const ADMIN_RESOURCE = 'WriteTextAI_WriteTextAI::menu';

    /**
     * @var GeneratedText
     */
    protected $generatedText;

    /**
     * @var MarkReview
     */
    protected $markReview;

    /**
     * Constructor
     *
     * @param Context $context
     * @param GeneratedText $generatedText
     * @param MarkReview $markReview
     */
    public function __construct(
        Context $context,
        GeneratedText $generatedText,
        MarkReview $markReview
    ) {
        $this->generatedText = $generatedText;
        $this->markReview = $markReview;
        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');
            
            $generatedText = $this->generatedText->getGenerated($categoryId, $storeId, 'Category');
            
            $textfields = $this->generatedText->getTextFields($categoryId, $storeId, false, $generatedText);
            
            $result = [
                'success' => true,
                'generated_texts' => $textfields,
                'feedback' => $this->generatedText->getTextsFeedback($generatedText),
                'reviewed' => $this->markReview->getReviewed($categoryId, $storeId, $generatedText)
            ];
        } 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;
    }
}
