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

declare(strict_types=1);

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\Helper\Settings;

class SaveConfig extends Action
{
    /**
     * @var Settings
     */
    protected $settings;

    /**
     * Constructor
     *
     * @param Context $context
     * @param Settings $settings
     */
    public function __construct(
        Context $context,
        Settings $settings
    ) {
        $this->settings = $settings;
        parent::__construct($context);
    }

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

        try {
            $params = $this->getRequest()->getParams();
            $flushCache = false;
            if (!array_key_exists('ko_optimization_only', $params)) {
                if (array_key_exists('is_brandvoice_selected', $params)
                    && $params['is_brandvoice_selected'] === 'false'
                ) {
                    if (array_key_exists('tones', $params)) {
                        $tones = is_array($params['tones'])
                            ? implode(',', $params['tones'])
                            : (string) $params['tones'];
                        $this->settings->setConfigNoFlush(Settings::GENERAL_SETTINGS_CONFIG_PATH . '/tones', $tones);
                        
                        if ($tones == 'custom') {
                            $this->settings->setConfigNoFlush(
                                Settings::GENERAL_SETTINGS_CONFIG_PATH . '/custom_tone',
                                $params['custom_tone']
                            );
                        } else {
                            $this->settings->setConfigNoFlush(
                                Settings::GENERAL_SETTINGS_CONFIG_PATH . '/custom_tone',
                                ''
                            );
                        }
                        $flushCache = true;
                    }

                    if (array_key_exists('styles', $params)) {
                        $styles = is_array($params['styles'])
                            ? implode(',', $params['styles'])
                            : (string) $params['styles'];
                        $this->settings->setConfigNoFlush(Settings::GENERAL_SETTINGS_CONFIG_PATH . '/styles', $styles);
                        
                        if ($styles == 'custom') {
                            $this->settings->setConfigNoFlush(
                                Settings::GENERAL_SETTINGS_CONFIG_PATH . '/custom_style',
                                $params['custom_style']
                            );
                        } else {
                             $this->settings->setConfigNoFlush(
                                 Settings::GENERAL_SETTINGS_CONFIG_PATH . '/custom_style',
                                 ''
                             );
                        }
                        $flushCache = true;
                    }

                    if (array_key_exists('audiences', $params)) {
                        $audiences = is_array($params['audiences'])
                            ? implode(',', $params['audiences'])
                            : (string) $params['audiences'];
                        $this->settings->setConfigNoFlush(
                            Settings::GENERAL_SETTINGS_CONFIG_PATH . '/audiences',
                            $audiences
                        );
                        $flushCache = true;
                    }
                }

                if (array_key_exists('attributes', $params)) {
                    $attributes = is_array($params['attributes'])
                        ? implode(',', $params['attributes'])
                        : (string) $params['attributes'];
                    $this->settings->setConfigNoFlush(
                        Settings::ATTRIBUTES_SETTINGS_CONFIG_PATH . 'attributes',
                        $attributes
                    );
                    $flushCache = true;
                }

                if (array_key_exists('description_min', $params)) {
                    $this->settings->setConfigNoFlush(
                        Settings::DESCRIPTION_SETTINGS_CONFIG_PATH . 'min',
                        (string) $params['description_min']
                    );
                    $flushCache = true;
                }
                if (array_key_exists('description_max', $params)) {
                    $this->settings->setConfigNoFlush(
                        Settings::DESCRIPTION_SETTINGS_CONFIG_PATH . 'max',
                        (string) $params['description_max']
                    );
                    $flushCache = true;
                }
                if (array_key_exists('excerpt_min', $params)) {
                    $this->settings->setConfigNoFlush(
                        Settings::EXCERPT_SETTINGS_CONFIG_PATH . 'min',
                        (string) $params['excerpt_min']
                    );
                    $flushCache = true;
                }
                if (array_key_exists('excerpt_max', $params)) {
                    $this->settings->setConfigNoFlush(
                        Settings::EXCERPT_SETTINGS_CONFIG_PATH . 'max',
                        (string) $params['excerpt_max']
                    );
                    $flushCache = true;
                }
            }
            
            //saving of Keyword Optimization settings
            if ((array_key_exists('ko_optimization_enabled', $params)
                    && $params['ko_optimization_enabled'] === 'true'
                ) || (array_key_exists('ko_optimization_only', $params)
                    && $params['ko_optimization_only'] === 'true'
                )
            ) {
                if (array_key_exists('cluster_based_pipelines_count', $params)) {
                    $this->settings->setConfigNoFlush(
                        Settings::KEYWORD_OPTIMIZATION_SETTINGS_CONFIG_PATH . '/cluster_based_pipelines_count',
                        (string) $params['cluster_based_pipelines_count']
                    );
                    $flushCache = true;
                }
                if (array_key_exists('auto_text_optimization', $params)) {
                    $this->settings->setConfigNoFlush(
                        Settings::KEYWORD_OPTIMIZATION_SETTINGS_CONFIG_PATH . '/automatic_text_optimization',
                        (string) $params['auto_text_optimization']
                    );
                    $flushCache = true;
                }
                if (array_key_exists('product_fields', $params)) {
                    $product_fields = is_array($params['product_fields'])
                        ? implode(',', $params['product_fields'])
                        : (string) $params['product_fields'];
                    $this->settings->setConfigNoFlush(
                        Settings::KEYWORD_OPTIMIZATION_SETTINGS_CONFIG_PATH . '/products',
                        $product_fields
                    );
                    $flushCache = true;
                }

                foreach (['low', 'low_mid', 'mid', 'mid_high'] as $pipelineGroup) {
                    $triggerActionKey = 'trigger_action_' . $pipelineGroup;
                    if (array_key_exists($triggerActionKey, $params)) {
                        $this->settings->setConfigNoFlush(
                            Settings::KEYWORD_OPTIMIZATION_SETTINGS_CONFIG_PATH
                            . '/pipeline_keyword/' . $pipelineGroup . '/trigger_action',
                            (string) $params[$triggerActionKey]
                        );
                        $flushCache = true;
                    }

                    if (array_key_exists('trigger_action_' . $pipelineGroup, $params)
                        && $params['trigger_action_' . $pipelineGroup] === 'when_page_is_ranking'
                    ) {
                        $nPositionKey = 'trigger_action_n_position_' . $pipelineGroup;
                        if (array_key_exists($nPositionKey, $params)) {
                            $this->settings->setConfigNoFlush(
                                Settings::KEYWORD_OPTIMIZATION_SETTINGS_CONFIG_PATH
                                . '/pipeline_keyword/' . $pipelineGroup . '/trigger_action_n_position',
                                (string) $params[$nPositionKey]
                            );
                            $flushCache = true;
                        }
                    }
                   
                    if (array_key_exists('trigger_action_' . $pipelineGroup, $params)
                        && $params['trigger_action_' . $pipelineGroup] === 'after_n_days'
                    ) {
                        $nDaysKey = 'trigger_action_n_days_' . $pipelineGroup;
                        if (array_key_exists($nDaysKey, $params)) {
                            $this->settings->setConfigNoFlush(
                                Settings::KEYWORD_OPTIMIZATION_SETTINGS_CONFIG_PATH
                                . '/pipeline_keyword/' . $pipelineGroup . '/trigger_action_n_days',
                                (string) $params[$nDaysKey]
                            );
                            $flushCache = true;
                        }
                    }
                }
            }

            if ($flushCache) {
                $this->settings->flushConfigCache();
            }
            $response->setData(['success' => true]);
        } 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.'
                );
            }

            $response->setData([
                'success' => false,
                'message' => $message
            ]);
        }

        return $response;
    }
}
