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

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

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
use WriteTextAI\WriteTextAI\Model\ApiManager;
use WriteTextAI\WriteTextAI\Model\Categories\GeneratedText;
use WriteTextAI\WriteTextAI\Model\OptionSource\Filter\Fields;
use WriteTextAI\WriteTextAI\Helper\Store as StoreHelper;
use WriteTextAI\WriteTextAI\Model\AiCategoryManager;

class Reviewed extends Action
{
    public const ADMIN_RESOURCE = 'WriteTextAI_WriteTextAI::review';

    /**
     * @var ApiManager
     */
    protected $apiManager;

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

    /**
     * @var StoreHelper
     */
    protected $storeHelper;

    /**
     * @var AiCategoryManager
     */
    protected $aiCategoryManager;

    /**
     * Constructor
     *
     * @param Context $context
     * @param ApiManager $apiManager
     * @param GeneratedText $generatedText
     * @param StoreHelper $storeHelper
     * @param AiCategoryManager $aiCategoryManager
     */
    public function __construct(
        Context $context,
        ApiManager $apiManager,
        GeneratedText $generatedText,
        StoreHelper $storeHelper,
        AiCategoryManager $aiCategoryManager
    ) {
        $this->apiManager = $apiManager;
        $this->generatedText = $generatedText;
        $this->storeHelper = $storeHelper;
        $this->aiCategoryManager = $aiCategoryManager;
        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');
            $reviewed = filter_var($this->getRequest()->getParam('reviewed'), FILTER_VALIDATE_BOOLEAN);

            if ($this->processTexts($categoryId, $storeId, $reviewed)) {
                $this->aiCategoryManager->saveDate($categoryId, $storeId, 'reviewed');
                $result = [
                    'success' => true
                ];
            } else {
                $result = [
                    'success' => false,
                    'message' => __("You haven't generated any text yet.")
                ];
            }
        } 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;
    }

    /**
     * Process text fields
     *
     * @param int $categoryId
     * @param int $storeId
     * @param bool $reviewed
     *
     * @return void
     */
    private function processTexts($categoryId, $storeId, $reviewed)
    {
        $ids = $this->generatedText->getTextIds($categoryId, $storeId);
        $textfields = $this->generatedText->getTextFields($categoryId, $storeId, true);

        if (!empty($ids)) {
            $fields = [];
            $fieldMappings = Fields::CATEGORY_MAPPING;

            foreach ($fieldMappings as $key => $value) {
                if (isset($ids[$key]) &&
                    isset($textfields[$key]) &&
                    isset($textfields['status'][$key]) &&
                    !$textfields['status'][$key]
                ) {
                    $fields[] = [
                        "textId" => $ids[$key],
                        "field" => $value,
                        "platform" => "Magento",
                        "value" => $textfields[$key],
                        "reviewed" => $reviewed,
                        "publish" => false
                    ];
                }
            }

            $language = $this->storeHelper->getFormattedLanguage($storeId);

            $params = [
                'type' => 'Category',
                'language' => $language,
                'recordId' => $categoryId,
                'storeId' => $storeId,
                'fields' => $fields
            ];

            $this->apiManager->save($params);

            return true;
        } else {
            return false;
        }
    }
}
