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

namespace WriteTextAI\WriteTextAI\Controller\Adminhtml\Edit;

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 as CategoryGeneratedText;
use WriteTextAI\WriteTextAI\Model\GeneratedText;
use WriteTextAI\WriteTextAI\Helper\Store as StoreHelper;
use WriteTextAI\WriteTextAI\Model\OptionSource\Filter\Fields;

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

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

    /**
     * @var CategoryGeneratedText
     */
    protected $categoryGeneratedText;

    /**
     * @var StoreHelper
     */
    protected $storeHelper;
    
    /**
     * Constructor
     *
     * @param Context $context
     * @param ApiManager $apiManager
     * @param GeneratedText $generatedText
     * @param CategoryGeneratedText $categoryGeneratedText
     * @param StoreHelper $storeHelper
     */
    public function __construct(
        Context $context,
        ApiManager $apiManager,
        GeneratedText $generatedText,
        CategoryGeneratedText $categoryGeneratedText,
        StoreHelper $storeHelper
    ) {
        $this->apiManager = $apiManager;
        $this->generatedText = $generatedText;
        $this->categoryGeneratedText = $categoryGeneratedText;
        $this->storeHelper = $storeHelper;
        parent::__construct($context);
    }

    /**
     * Execute
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $response = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        
        try {
            $fieldType = $this->getRequest()->getParam('field_type');
            $storeId = $this->getRequest()->getParam('store_id');
            $recordId = $this->getRequest()->getParam('record_id');
            $rating = $this->getRequest()->getParam('rating');
            $comment = $this->getRequest()->getParam('comment');
            $entityType = $this->getRequest()->getParam('entity_type');

            $value = '';
            $id = '';
            $textfields = [];
            $ids = [];
            switch ($entityType) {
                case 'Product':
                    $mapping = [
                        'page_title' => Fields::PAGE_TITLE,
                        'page_description' => Fields::PAGE_DESCRIPTION,
                        'product_description' => Fields::PRODUCT_DESCRIPTION,
                        'short_product_description' => Fields::EXCERPT,
                        'open_graph' => Fields::OPEN_GRAPH,
                    ];

                    $ids = $this->generatedText->getTextIds($recordId, $storeId);
                    $textfields = $this->generatedText->getTextFields($recordId, $storeId);

                    $value = $textfields[$fieldType];
                    $id = $ids[$fieldType];
                    $fieldType = $mapping[$fieldType];

                    break;
                case 'Category':
                    $ids = $this->categoryGeneratedText->getTextIds($recordId, $storeId);
                    $textfields = $this->categoryGeneratedText->getTextFields($recordId, $storeId);

                    $value = $textfields[$fieldType];
                    $id = $ids[$fieldType];
                    $fieldType = Fields::CATEGORY_MAPPING[$fieldType];

                    break;
                case 'ImageAltText':
                    $value = $this->getRequest()->getParam('value');
                    $id = $this->getRequest()->getParam('alt_id');
                    $fieldType = '';

                    break;
            }

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

            $params = [
                'type' => $entityType,
                'language' => $language,
                'recordId' => $recordId,
                'storeId' => $storeId,
                'rating' => $rating,
                'comment' => $rating ? $comment : '',
                'fieldType' => $fieldType,
                'value' => $value,
                'textId' => $id
            ];
            $this->apiManager->sendFeedback(json_encode($params));

            $result = [
                'success' =>  true,
                'params' => $params
            ];
        } 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,
                'params' => $params ?? []
            ];
        }

        $response->setData($result);

        return $response;
    }
}
