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

namespace WriteTextAI\WriteTextAI\Controller\Adminhtml\Settings;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
use WriteTextAI\WriteTextAI\ViewModel\TemplateSettings;
use WriteTextAI\WriteTextAI\Helper\Data;
use WriteTextAI\WriteTextAI\Model\ApiManager;
use WriteTextAI\WriteTextAI\Model\IntegrationApiManager;

class NeededData extends Action
{
    /**
     * @var TemplateSettings
     */
    protected $templateSettings;

    /**
     * @var Data
     */
    protected $helper;

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

    /**
     * @var IntegrationApiManager
     */
    protected $integrationApiManager;
    
    /**
     * Constructor
     *
     * @param Context $context
     * @param TemplateSettings $templateSettings
     * @param Data $helper
     * @param ApiManager $apiManager
     * @param IntegrationApiManager $integrationApiManager
     */
    public function __construct(
        Context $context,
        TemplateSettings $templateSettings,
        Data $helper,
        ApiManager $apiManager,
        IntegrationApiManager $integrationApiManager
    ) {
        parent::__construct($context);
        $this->templateSettings = $templateSettings;
        $this->helper = $helper;
        $this->apiManager = $apiManager;
        $this->integrationApiManager = $integrationApiManager;
    }

    /**
     * Execute
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $response = $this->resultFactory->create(ResultFactory::TYPE_JSON);

        $params = $this->getRequest()->getParams();
        $entityType = $params['entityType'] ?? 'Product';
        $entityType = $entityType === 'Product' ? 'Product' : 'Category';

        $currentTemplateSettings = $this->getCurrentTemplateSettings();
        $fields = $this->getFields();
            
        $responseData = [
            'success' => true,
            'entityType' => $entityType,
            'templates' => $currentTemplateSettings,
            'fieldsTemplateSettings' => $fields,
        ];

        try {
            if ($entityType === 'Category') {
                $responseData['templateOptions'] = [
                    'category_page_title' => $this->getTemplateOptionPerField('category_page_title'),
                    'category_description' => $this->getTemplateOptionPerField('category_description')
                ];
                $response->setData($responseData);
                return $response;
            }
            
            $responseData['templateOptions'] = [
                'page_title' => $this->getTemplateOptionPerField('page_title'),
                'product_description' => $this->getTemplateOptionPerField('product_description'),
                'short_product_description' => $this->getTemplateOptionPerField('short_product_description')
            ];
        } catch (\Exception $e) {
            $responseData['templateOptions'] = [];
        }
            
        //create token if necessary
        
        $this->checkApiIntegration();

        $responseData['pingSuccess'] = true;

        $response->setData($responseData);
        return $response;
    }

    /**
     * Get current template settings
     *
     * @return array
     */
    public function getCurrentTemplateSettings()
    {
        try {
            return $this->templateSettings->getCurrentTemplateSettings();
        } catch (\Exception $e) {
            return [];
        }
    }
    
    /**
     * Get text types
     *
     * @return array
     */
    public function getFields()
    {
        try {
            $fields = [[
                'value' => 'page_title',
                'label' =>  __('Meta title'),
                'hasTemplate' => true,
                'templates' => $this->getTemplateOptionPerField('page_title')
            ], [
                'value' => 'page_description',
                'label' =>  __('Meta description'),
                'hasTemplate' => false
            ], [
                'value' => 'product_description',
                'label' =>  __('Description'),
                'hasTemplate' => true,
                'templates' => $this->getTemplateOptionPerField('product_description')
            ], [
                'value' => 'short_product_description',
                'label' => __('Short description'),
                'hasTemplate' => true,
                'templates' => $this->getTemplateOptionPerField('short_product_description')
            ]];

            if ($this->helper->getCustomOpenGraph()) {
                $fields[] = [
                    'value' => 'open_graph',
                    'label' => __('Open Graph text'),
                    'hasTemplate' => false
                ];
            }

            return $fields;
        } catch (\Exception $e) {
            return [];
        }
    }

    /**
     * Check if api integration is valid
     *
     * @return bool
     */
    public function checkApiIntegration()
    {
        try {
            return $this->integrationApiManager->checkIfIntegrationIsStillValid();
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * Get template options per field
     *
     * @param string $field
     * @return array
     */
    public function getTemplateOptionPerField($field)
    {
        return $this->templateSettings->getCurrentTemplateSettings($field);
    }

    /**
     * Ping API
     *
     * @return array
     */
    public function pingApi()
    {
        try {
            return $this->apiManager->pingApi();
        } catch (\WriteTextAI\WriteTextAI\Exception\UnauthorizedException $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }
}
