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

namespace WriteTextAI\WriteTextAI\Observer\Backend\Admin;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\App\Config\Storage\WriterInterface;
use WriteTextAI\WriteTextAI\Model\OptionSource\Filter\Fields;
use WriteTextAI\WriteTextAI\Model\Config\Source\TriggerActions;
use WriteTextAI\WriteTextAI\Model\Config\Source\AutomaticTextOptimization;
use WriteTextAI\WriteTextAI\Model\Api\Keywords;
use WriteTextAI\WriteTextAI\Model\ApiManager;
use WriteTextAI\WriteTextAI\Helper\Data;
use Magento\Framework\Exception\LocalizedException;

class SystemConfigChangedSectionWritetextaiSettings implements ObserverInterface
{
    public const XML_PATH_KEYWORD_OPTIMIZATION_APPLY_TO_ALL =
        'writetextai_settings/keyword_optimization/pipeline_keyword/apply_to_all';

    /**
     * @var RequestInterface
     */
    private $request;

    /**
     * @var WriterInterface
     */
    private $configWriter;

    /**
     * @var Keywords
     */
    private $keywords;

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

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

    /**
     * ConfigChange constructor.
     * @param RequestInterface $request
     * @param WriterInterface $configWriter
     * @param Keywords $keywords
     * @param Data $helper
     * @param ApiManager $apiManager
     */
    public function __construct(
        RequestInterface $request,
        WriterInterface $configWriter,
        Keywords $keywords,
        Data $helper,
        ApiManager $apiManager
    ) {
        $this->request = $request;
        $this->configWriter = $configWriter;
        $this->keywords = $keywords;
        $this->helper = $helper;
        $this->apiManager = $apiManager;
    }

    /**
     * Execute observer
     *
     * @param Observer $observer
     * @return void
     */
    public function execute(Observer $observer): void
    {
        try {
            $this->configWriter->save(self::XML_PATH_KEYWORD_OPTIMIZATION_APPLY_TO_ALL, '0');

            $keywordOptimizationParams = $this->request->getParam('groups');
            if (!$keywordOptimizationParams) {
                return;
            }
            $keywordOptimization = $keywordOptimizationParams['keyword_optimization'];
            $pipelineKeyword = $keywordOptimization['groups']['pipeline_keyword'] ?? null;
            $productTriggerParameter = [];
            $categoryTriggerParameter = [];
            $difficultyEquivalents = [
                'low' => 'Low',
                'low_mid' => 'LowMid',
                'mid' => 'Mid',
                'mid_high' => 'MidHigh'
            ];

            $optionsEquivalent = [
                TriggerActions::WHEN_PAGE_IS_RANKING => 'WhenRanking',
                TriggerActions::AFTER_N_DAYS => 'AfterSetDays',
                TriggerActions::NONE => 'None'
            ];
            $actionsEquivalent = [
                AutomaticTextOptimization::AUTO_REWRITE_AND_QUEUE => 'AutomaticRewrite',
                AutomaticTextOptimization::FLAG => 'FlagForRewrite',
                AutomaticTextOptimization::AUTO_REWRITE_AND_TRANSFER => 'FullAutomation'
            ];

            $valueReference = [
                TriggerActions::WHEN_PAGE_IS_RANKING => 'trigger_action_n_position',
                TriggerActions::AFTER_N_DAYS => 'trigger_action_n_days'
            ];

            $productFieldsMapping = [
                '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
            ];

            $categoryFieldsMapping = Fields::CATEGORY_MAPPING;

            $referenceSettingValue = $keywordOptimization['fields']['automatic_text_optimization']['value'] ?? null;
            $selectedProductsTextType = $keywordOptimization['fields']['products']['value'] ?? [];
            $selectedCategoryTextType = $keywordOptimization['fields']['categories']['value'] ?? [];

            $actionValue = $actionsEquivalent[$referenceSettingValue];
            
            if ($pipelineKeyword
                && isset($pipelineKeyword['fields']['apply_to_all']['value'])
            ) {
                $applyToAllRequestValue = $pipelineKeyword['fields']['apply_to_all']['value'];
                $difficultyGroups = $pipelineKeyword['groups'];
                if ($applyToAllRequestValue === '1') {
                    $productParamValues = [];
                    foreach ($selectedProductsTextType as $textType) {
                        $productParamValues[] = $productFieldsMapping[$textType];
                    }

                    $categoryParamValues = [];
                    foreach ($selectedCategoryTextType as $textType) {
                        $categoryParamValues[] = $categoryFieldsMapping[$textType];
                    }

                    foreach ($difficultyGroups as $key => $value) {
                        $optionValue = $value['fields']['trigger_action']['value'] ?? null;
                        $valueReferenceKey = $valueReference[$optionValue] ?? null;
                        $triggerParameter = ['option' => $optionsEquivalent[$optionValue]];
                        if ($valueReferenceKey !== TriggerActions::NONE) {
                            $triggerParameter['value'] = $value['fields'][$valueReferenceKey]['value'] ?? 0;
                        }

                        $productTriggerParameter[$difficultyEquivalents[$key]] = $triggerParameter;
                        $categoryTriggerParameter[$difficultyEquivalents[$key]] = $triggerParameter;
                    }

                    $productApiRequest = $this->keywords->updateGlobalTriggerSettings(
                        $productTriggerParameter,
                        'Product'
                    );
                    $categoyApiRequest = $this->keywords->updateGlobalTriggerSettings(
                        $categoryTriggerParameter,
                        'Category'
                    );
                }
            }

            if (!isset($keywordOptimizationParams['autotransfer'])) {
                return;
            }
            $autoTransferGroup = $keywordOptimizationParams['autotransfer'];
            $autoTransferGroupValue = $autoTransferGroup['fields']['cron_schedule']['value'] ?? null;

            if (!$autoTransferGroupValue) {
                return;
            }

            $cronTime = $this->helper->cronToTime($autoTransferGroupValue);
            $tokenTime = $this->helper->convertToConfigTimezone($cronTime);
            $bodyTokenTime = [
                'time' => $tokenTime
            ];
            $tokenTimeResponse = $this->apiManager->sendTokenTime($bodyTokenTime);
        } catch (\Exception $e) {
            return;
        }
    }
}
