<?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\Data;
use WriteTextAI\WriteTextAI\Model\Config\Source\ProductAttributes;
use WriteTextAI\WriteTextAI\Model\Config\Source\CategoryAttributes;
use WriteTextAI\WriteTextAI\Model\Config\Source\TriggerActions;
use WriteTextAI\WriteTextAI\Model\Config\Source\AutomaticTextOptimization;
use WriteTextAI\WriteTextAI\Model\Config\Source\CategoryTexts;
use WriteTextAI\WriteTextAI\Model\GenerateOptionsManager;
use WriteTextAI\WriteTextAI\Model\UserFieldsSelectedManager;
use WriteTextAI\WriteTextAI\ViewModel\Tooltip;
use WriteTextAI\WriteTextAI\ViewModel\Permissions;
use WriteTextAI\WriteTextAI\ViewModel\Settings;
use WriteTextAI\WriteTextAI\ViewModel\UserFieldsSelected;
use WriteTextAI\WriteTextAI\ViewModel\TemplateSettings;
use Magento\Framework\View\LayoutInterface;
use WriteTextAI\WriteTextAI\Model\Config\Source\ProductTexts;
use WriteTextAI\WriteTextAI\Model\Config\Source\DefaultValues\ProductTexts as DefaultProductTexts;
use WriteTextAI\WriteTextAI\Helper\CronStatus;
use WriteTextAI\WriteTextAI\Helper\Settings as SettingsHelper;

class Prompt extends Action
{
    /**
     * @var Data
     */
    protected $helper;

    /**
     * @var ProductAttributes
     */
    protected $attributes;

    /**
     * @var GenerateOptionsManager
     */
    protected $generateOptionsManager;

    /**
     * @var UserFieldsSelected
     */
    protected $userFieldsSelected;

    /**
     * @var Tooltip
     */
    protected $tooltip;

    /**
     * @var Permissions
     */
    protected $permissions;

    /**
     * @var Settings
     */
    protected $settings;

    /**
     * @var UserFieldsSelectedManager
     */
    protected $userFieldsSelectedManager;

    /**
     * @var LayoutInterface
     */
    protected $layout;

    /**
     * @var TemplateSettings
     */
    protected $templateSettings;

    /**
     * @var ProductTexts
     */
    protected $productTexts;

    /**
     * @var DefaultProductTexts
     */
    protected $defaultProductTexts;

    /**
     * @var CronStatus
     */
    protected $cronStatus;

    /**
     * @var SettingsHelper
     */
    protected $settingsHelper;

    /**
     * @var CategoryAttributes
     */
    protected $categoryAttributes;

    /**
     * @var CategoryTexts
     */
    protected $categoryTexts;

    /**
     * Constructor
     *
     * @param Context $context
     * @param Data $helper
     * @param ProductAttributes $attributes
     * @param GenerateOptionsManager $generateOptionsManager
     * @param UserFieldsSelected $userFieldsSelected
     * @param Tooltip $tooltip
     * @param Permissions $permissions
     * @param Settings $settings
     * @param UserFieldsSelectedManager $userFieldsSelectedManager
     * @param LayoutInterface $layout
     * @param TemplateSettings $templateSettings
     * @param ProductTexts $productTexts
     * @param DefaultProductTexts $defaultProductTexts
     * @param CronStatus $cronStatus
     * @param SettingsHelper $settingsHelper
     * @param CategoryAttributes $categoryAttributes
     * @param CategoryTexts $categoryTexts
     */
    public function __construct(
        Context $context,
        Data $helper,
        ProductAttributes $attributes,
        GenerateOptionsManager $generateOptionsManager,
        UserFieldsSelected $userFieldsSelected,
        Tooltip $tooltip,
        Permissions $permissions,
        Settings $settings,
        UserFieldsSelectedManager $userFieldsSelectedManager,
        LayoutInterface $layout,
        TemplateSettings $templateSettings,
        ProductTexts $productTexts,
        DefaultProductTexts $defaultProductTexts,
        CronStatus $cronStatus,
        SettingsHelper $settingsHelper,
        CategoryAttributes $categoryAttributes,
        CategoryTexts $categoryTexts
    ) {
        $this->helper = $helper;
        $this->attributes = $attributes;
        $this->generateOptionsManager = $generateOptionsManager;
        $this->userFieldsSelected = $userFieldsSelected;
        $this->tooltip = $tooltip;
        $this->permissions = $permissions;
        $this->settings = $settings;
        $this->userFieldsSelectedManager = $userFieldsSelectedManager;
        $this->layout = $layout;
        $this->templateSettings = $templateSettings;
        $this->productTexts = $productTexts;
        $this->defaultProductTexts = $defaultProductTexts;
        $this->cronStatus = $cronStatus;
        $this->settingsHelper = $settingsHelper;
        $this->categoryAttributes = $categoryAttributes;
        $this->categoryTexts = $categoryTexts;
        parent::__construct($context);
    }

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

        try {
            $params = $this->getRequest()->getParams();
            $entityType = $params['entity_type'] ?? 'product';
            $actionType = $params['action_type'] ?? '';
            $getTemplateSettings = $params['getTemplateSettings'] ?? 'false';
            $getTemplateSettings = $getTemplateSettings === 'true';

            $rules = $this->getRules();
            $triggerActions = $this->getTriggerActions();

            $data = [
                'tones' => $this->getTones(),
                'tones_selected' => $this->getTonesSelected(),
                'custom_tone' => $this->getCustomTone(),
                'styles' => $this->getStyles(),
                'styles_selected' => $this->getStylesSelected(),
                'custom_style' => $this->getCustomStyle(),
                'audiences' => $this->getAudience(),
                'audience_selected' => $this->getAudienceSelected(),
                'attributes' => $entityType === 'category' ? $this->getCategoryAttributes() : $this->getAttributes(),
                'attributes_selected' => $this->getAttributesSelected($entityType),
                'desc_min' => $this->getDescriptionMin(),
                'desc_max' => $this->getDescriptionMax(),
                'exc_min' => $this->getExcerptMin(),
                'exc_max' => $this->getExcerptMax(),
                'special_instructions' => $this->getSpecialInstructions($entityType),
                'selected_fields' => $this->getFieldsSelected($entityType, (string) $actionType),
                'rules' => $rules,
                'maxOutputWords' => $rules['maxOutputWords'],
                'minOutputWords' => $rules['minOutputWords'],
                'maxOtherDetailsLength' => $rules['maxOtherDetailsLength'],
                'disallowedCombinations' => $this->getDisallowedCombinations(),
                'attrAllowed' => $this->isAttrAllowed(),
                'toneStyleAllowed' => $this->isToneStyleAllowed(),
                'wordsAllowed' => $this->isWordsAllowed(),
                'transferAllowed' => $this->isTransferAllowed(),
                "autoTextOptimizationSelected" => $this->getAutomaticTextOptimizationSelected($entityType),
                "searchIntent" => $this->getSearchIntent($entityType),
                "clusterCount" => $this->getClusterCount($entityType),
                "maxClusterCount" => (int)(($rules['maxKeywords'] ?? 6) - 1),
                "minClusterCount" => $rules['minClusterBasedPipelinesCount'] ?? 1,
                "isCronAvailable" => $this->isCronRunning(),
                "triggerActions" => $triggerActions,
                "triggerActionNPositionLow" => $triggerActions['low']['trigger_action_n_position'] ?? '',
                "triggerActionNDaysLow" => $triggerActions['low']['trigger_action_n_days'] ?? '',
                "triggerActionNPositionLowMid" => $triggerActions['low_mid']['trigger_action_n_position'] ?? '',
                "triggerActionNDaysLowMid" => $triggerActions['low_mid']['trigger_action_n_days'] ?? '',
                "triggerActionNPositionMid" => $triggerActions['mid']['trigger_action_n_position'] ?? '',
                "triggerActionNDaysMid" => $triggerActions['mid']['trigger_action_n_days'] ?? '',
                "triggerActionNPositionMidHigh" => $triggerActions['mid_high']['trigger_action_n_position'] ?? '',
                "triggerActionNDaysMidHigh" => $triggerActions['mid_high']['trigger_action_n_days'] ?? '',
                "minTriggerActionNPosition" => $rules['minTriggerActionNPosition'] ?? 2,
                "maxTriggerActionNPosition" => $rules['maxTriggerActionNPosition'] ?? 100,
                "minTriggerActionNDays" => $rules['minTriggerActionNDays'] ?? 1,
                "maxTriggerActionNDays" => $rules['maxTriggerActionNDays'] ?? 365,
                "productFields" => $this->getDefaultProductTexts(),
                "allProductFields" => array_column($this->getProductFields(), 'value'),
                "categoryFields" => $this->getDefaultCategoryTexts(),
                "allCategoryFields" => array_column($this->getCategoryTexts(), 'value'),
                "automaticTextOptimizationOptions" => $this->getAutomaticTextOptimizationOptions()
            ];
            
            if ($getTemplateSettings) {
                $data['currentTemplateSettings'] = $this->getCurrentTemplateSettings();
                $data['fields'] = $this->getFields($entityType);
            }
            
            $result = [
                'success' => true,
                'data' => $data
            ];
        } 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;
    }

    /**
     * Get automatic text optimization options
     *
     * @return array
     */
    public function getAutomaticTextOptimizationOptions()
    {
        return $this->helper->getAutomaticTextOptimizationOptions();
    }

    /**
     * Is Attribute Allowed
     *
     * @return bool
     */
    public function isAttrAllowed()
    {
        return $this->permissions->isAttrAllowed();
    }

    /**
     * Is Tone Style Allowed
     *
     * @return bool
     */
    public function isToneStyleAllowed()
    {
        return $this->permissions->isToneStyleAllowed();
    }

    /**
     * Is Words Allowed
     *
     * @return bool
     */
    public function isWordsAllowed()
    {
        return $this->permissions->isWordsAllowed();
    }

    /**
     * Is Transfer Allowed
     *
     * @return bool
     */
    public function isTransferAllowed()
    {
        return $this->permissions->isTransferAllowed();
    }

    /**
     * Get tooltip
     *
     * @param string $block
     * @return string
     */
    public function getTooltip($block)
    {
        return $this->tooltip->getTooltip($block);
    }

    /**
     * Get tones
     *
     * @return array
     */
    public function getTones()
    {
        return $this->generateOptionsManager->getOptions('tones');
    }

    /**
     * Get tones selected
     *
     * @return array
     */
    public function getTonesSelected()
    {
        $userPreference = $this->userFieldsSelected->getUserFieldsSelected(
            UserFieldsSelectedManager::ACTION_TYPE_TONES,
            'global',
            'grid'
        );

        if (!empty($userPreference)) {
            return $userPreference;
        } else {
            return $this->getTonesFromGlobalSettings();
        }
    }

    /**
     * Get custom tone
     *
     * @return string
     */
    public function getCustomTone()
    {
        $userTones = $this->getTonesSelected();
        $isCustomToneSelected = is_array($userTones) && in_array('custom', $userTones, true);

        $customTone = $this->userFieldsSelected->getUserFieldsSelected(
            UserFieldsSelectedManager::ACTION_TYPE_CUSTOM_TONE,
            'global',
            'grid'
        );
        
        if (empty($customTone)) {
            return $isCustomToneSelected ?  $this->settingsHelper->getGeneralSettings('custom_tone'): "";
        }
        
        return $customTone;
    }

    /**
     * Get custom style
     *
     * @return string
     */
    public function getCustomStyle()
    {
        $userStyles = $this->getStylesSelected();
        $isCustomStyleSelected = $userStyles === 'custom';

        $customStyle = $this->userFieldsSelected->getUserFieldsSelected(
            UserFieldsSelectedManager::ACTION_TYPE_CUSTOM_STYLE,
            'global',
            'grid'
        );
        
        if (empty($customStyle)) {
            return $isCustomStyleSelected ?  $this->settingsHelper->getGeneralSettings('custom_style') : "";
        }
        
        return $customStyle;
    }

    /**
     * Get tones from global settings
     *
     * @return array
     */
    private function getTonesFromGlobalSettings()
    {
        $tones = $this->getTones();

        if (!is_array($tones)) {
            return [];
        }

        $tonesSelected = array_filter($tones, function ($tone) {
            return isset($tone['default']) && $tone['default'] === true;
        });

        if (empty($tonesSelected)) {
            return [];
        }

        $tonesSelected = array_column($tonesSelected, 'id');

        return $tonesSelected;
    }

    /**
     * Get styles
     *
     * @return array
     */
    public function getStyles()
    {
        return $this->generateOptionsManager->getOptions('styles');
    }

    /**
     * Get styles selected
     *
     * @return string
     */
    public function getStylesSelected()
    {
        $userPreference = $this->userFieldsSelected->getUserFieldsSelected(
            UserFieldsSelectedManager::ACTION_TYPE_STYLE,
            'global',
            'grid'
        );

        if ($userPreference) {
            return $userPreference;
        } else {
            return $this->getStylesFromGlobalSettings();
        }
    }

    /**
     * Get styles from global settings
     *
     * @return string
     */
    private function getStylesFromGlobalSettings()
    {
        $styles = $this->getStyles();

        if (!is_array($styles)) {
            return [];
        }

        $stylesSelected = array_filter($styles, function ($style) {
            return isset($style['default']) && $style['default'] === true;
        });

        if (empty($stylesSelected)) {
            return [];
        }

        $stylesSelected = array_column($stylesSelected, 'id');

        return array_shift($stylesSelected);
    }

    /**
     * Get audience
     *
     * @return array
     */
    public function getAudience()
    {
        return $this->generateOptionsManager->getOptions('audience');
    }

    /**
     * Get audiences selected
     *
     * @return array
     */
    public function getAudienceSelected()
    {
        $userPreference = $this->userFieldsSelected->getUserFieldsSelected(
            UserFieldsSelectedManager::ACTION_TYPE_AUDIENCES,
            'global',
            'grid'
        );

        if ($userPreference) {
            return $userPreference;
        } else {
            return $this->getAudienceFromGlobalSettings();
        }
    }

    /**
     * Get audience selected from global settings
     *
     * @return array
     */
    private function getAudienceFromGlobalSettings()
    {
        $audience = $this->getAudience();

        if (!is_array($audience)) {
            return [];
        }

        $audienceSelected = array_filter($audience, function ($audience) {
            return isset($audience['default']) && $audience['default'] === true;
        });

        if (empty($audienceSelected)) {
            return [];
        }

        $audienceSelected = array_column($audienceSelected, 'id');

        return $audienceSelected;
    }

    /**
     * Get attributes
     *
     * @return array
     */
    public function getAttributes()
    {
        return $this->generateOptionsManager->getOptions('attributes');
    }

    /**
     * Get attributes selected from global settings
     *
     * @return array
     */
    private function getAttributesSelectedFromGlobalSettings()
    {
        $attributes = $this->getAttributes();

        $defaultAttributes = array_filter($attributes, function ($attribute) {
            return $attribute['default'];
        });
        $attributesSelected = array_map(function ($attribute) {
            return $attribute['value'];
        }, $defaultAttributes);

        return array_values($attributesSelected);
    }

    /**
     * Get attributes selected
     *
     * @param string $entityType
     * @return array
     */
    public function getAttributesSelected($entityType = 'product')
    {
        $userPreference = $this->userFieldsSelectedManager->checkUserFieldsSelected(
            UserFieldsSelectedManager::ACTION_TYPE_ATTRIBUTES_SELECTED,
            $entityType,
            'grid'
        );

        $productResearchDataSelected = $this->userFieldsSelectedManager->checkUserFieldsSelected(
            UserFieldsSelectedManager::ACTION_TYPE_PRODUCT_RESEARCH_DATA,
            'product',
            'grid'
        );

        if ($userPreference) {
            $selectedAttributes = $this->userFieldsSelected->getUserFieldsSelected(
                UserFieldsSelectedManager::ACTION_TYPE_ATTRIBUTES_SELECTED,
                $entityType,
                'grid'
            );
            if ($productResearchDataSelected) {
                $selectedAttributes = $this->processProductResearchData(
                    $selectedAttributes,
                    $productResearchDataSelected
                );
            }

            return $selectedAttributes;
        } else {
            $globalAttributes = $entityType === 'category'
                ? $this->getCategoryAttributesSelectedFromDefaults()
                : $this->getAttributesSelectedFromGlobalSettings();
            if ($productResearchDataSelected) {
                $globalAttributes = $this->processProductResearchData($globalAttributes, $productResearchDataSelected);
            }
            return $globalAttributes;
        }
    }

    /**
     * Get category attributes
     *
     * @return array
     */
    public function getCategoryAttributes(): array
    {
        return $this->categoryAttributes->toOptionArray();
    }

    /**
     * Get default category attributes selected
     *
     * @return array
     */
    private function getCategoryAttributesSelectedFromDefaults(): array
    {
        $attributes = $this->getCategoryAttributes();
        return array_column($attributes, 'value');
    }

    /**
     * Get category text fields options
     *
     * @return array
     */
    public function getCategoryTexts(): array
    {
        return $this->categoryTexts->toOptionArray();
    }

    /**
     * Process product research data
     *
     * @param array $selectedAttributes
     * @param string $researchDataUserPreference
     * @return array
     */
    public function processProductResearchData($selectedAttributes, $researchDataUserPreference)
    {
        $researchDataUserPreference = $this->userFieldsSelected->getUserFieldsSelected(
            UserFieldsSelectedManager::ACTION_TYPE_PRODUCT_RESEARCH_DATA,
            'product',
            'grid'
        );

        if ($researchDataUserPreference === 'true') {
            if (!in_array('wtai_product_research_data', $selectedAttributes)) {
                $selectedAttributes[] = 'wtai_product_research_data';
            }
        }

        if ($researchDataUserPreference === 'false') {
            $selectedAttributes = array_values(array_filter($selectedAttributes, function ($attribute) {
                return $attribute !== 'wtai_product_research_data';
            }));
        }
        return $selectedAttributes;
    }

    /**
     * Get special instructions
     *
     * @param string $entityType
     * @return string
     */
    public function getSpecialInstructions($entityType = 'product')
    {
        return $this->userFieldsSelected->getUserFieldsSelected(
            UserFieldsSelectedManager::ACTION_TYPE_SPECIAL_INSTRUCTIONS,
            $entityType,
            'grid'
        );
    }

    /**
     * Get description min
     *
     * @return string
     */
    public function getDescriptionMin()
    {
        // global settings by default
        return $this->helper->getDescriptionSettings('min');
    }

    /**
     * Get description max
     *
     * @return string
     */
    public function getDescriptionMax()
    {
        // global settings by default
        return $this->helper->getDescriptionSettings('max');
    }

    /**
     * Get excerpt min
     *
     * @return string
     */
    public function getExcerptMin()
    {
        // global settings by default
        return $this->helper->getExcerptSettings('min');
    }

    /**
     * Get excerpt max
     *
     * @return string
     */
    public function getExcerptMax()
    {
        // global settings by default
        return $this->helper->getExcerptSettings('max');
    }

    /**
     * Get rules
     *
     * @return array
     */
    public function getRules()
    {
        return $this->settings->getSettings('rules');
    }

    /**
     * Get disallowed combinations
     *
     * @return array
     */
    public function getDisallowedCombinations()
    {
        return $this->settings->getSettings('disallowedCombinations');
    }
    
    /**
     * Get text types
     *
     * @param string $entityType
     * @return array
     */
    public function getFields($entityType = 'product')
    {
        if ($entityType === 'category') {
            return [[
                'value' => 'page_title',
                'label' => __('Meta title'),
                'hasTemplate' => true,
                'templates' => $this->getTemplateOptionPerField('category_page_title')
            ], [
                'value' => 'page_description',
                'label' => __('Meta description'),
                'hasTemplate' => false,
                'templates' => $this->getTemplateOptionPerField('category_page_description')
            ], [
                'value' => 'category_description',
                'label' => __('Category description'),
                'hasTemplate' => true,
                'templates' => $this->getTemplateOptionPerField('category_description')
            ]];
        }

        $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;
    }

    /**
     * Get fields selected
     *
     * @param string $entityType
     * @param string $actionType
     * @return array
     */
    public function getFieldsSelected($entityType = 'product', string $actionType = '')
    {
        $selected = $this->userFieldsSelected->getUserFieldsSelected(
            UserFieldsSelectedManager::ACTION_TYPE_BULK_GENERATE_FIELDS,
            $entityType,
            'grid'
        );

        $allowed = array_column($this->getFields($entityType), 'value');
        if (!is_array($allowed)) {
            $allowed = [];
        }

        if ($entityType === 'product') {
            $allowed[] = 'alt_text';
        }

        if (is_array($selected) && $allowed) {
            $selected = array_values(array_intersect($selected, $allowed));
        }

        if (!is_array($selected) || !$selected) {
            if ($entityType === 'category') {
                $globalSelected = (string) $this->helper->getKeywordOptimizationSettings('categories');

                if (!empty($globalSelected)) {
                    $selected = array_values(array_filter(explode(',', $globalSelected)));
                } else {
                    $selected = [
                        'page_title',
                        'page_description',
                        'category_description'
                    ];
                }
            } else {
                $selected = [
                    'page_title',
                    'page_description',
                    'product_description',
                    'short_product_description',
                    'alt_text'
                ];

                if ($this->helper->getCustomOpenGraph()) {
                    $selected[] = 'open_graph';
                }
            }

            if ($allowed) {
                $selected = array_values(array_intersect($selected, $allowed));
            }
        }

        return $selected;
    }

    /**
     * Get search intent
     *
     * @param string $entityType
     * @return array
     */
    public function getSearchIntent($entityType = 'product')
    {
        $searchIntent = $this->userFieldsSelected->getUserFieldsSelected(
            UserFieldsSelectedManager::ACTION_TYPE_SEARCH_INTENT,
            $entityType,
            'grid'
        );
        if ($searchIntent) {
            $searchIntent = explode(',', $searchIntent);
        } else {
            $searchIntent = explode(',', $this->helper->getKeywordOptimizationSettings('search_intent'));
        }
        return $searchIntent;
    }

    /**
     * Get cluster count
     *
     * @param string $entityType
     * @return int
     */
    public function getClusterCount($entityType = 'product')
    {
        if ($entityType === 'category') {
            return $this->userFieldsSelected->getUserFieldsSelected(
                UserFieldsSelectedManager::ACTION_TYPE_CLUSTER_COUNT_CATEGORY,
                'category',
                'grid'
            );
        }

        return $this->userFieldsSelected->getUserFieldsSelected(
            UserFieldsSelectedManager::ACTION_TYPE_CLUSTER_COUNT,
            'product',
            'grid'
        );
    }

    /**
     * Get global settings for keyword optimization
     *
     * @param string $path
     * @return string
     */
    public function getKeywordOptimizationSettings($path)
    {
        return $this->helper->getKeywordOptimizationSettings($path);
    }

    /**
     * Get automatic text optimization selected
     *
     * @param string $entityType
     * @return string
     */
    public function getAutomaticTextOptimizationSelected($entityType = 'product')
    {
        $userPreference = $this->userFieldsSelected->getUserFieldsSelected(
            UserFieldsSelectedManager::ACTION_TYPE_AUTO_TEXT_OPTIMIZATION,
            $entityType,
            'grid'
        );

        if ($userPreference) {
            return $userPreference;
        }

        return (string) $this->helper->getKeywordOptimizationSettings('automatic_text_optimization');
    }

    /**
     * Get current template settings
     *
     * @return array
     */
    public function getCurrentTemplateSettings()
    {
        return $this->templateSettings->getCurrentTemplateSettings();
    }

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

    /**
     * Get trigger actions
     *
     * @return array
     */
    public function getTriggerActions()
    {
        $lowTriggerAction = $this->getKeywordOptimizationSettings('pipeline_keyword/low');
        $lowMidTriggerAction = $this->getKeywordOptimizationSettings('pipeline_keyword/low_mid');
        $midTriggerAction = $this->getKeywordOptimizationSettings('pipeline_keyword/mid');
        $midHighTriggerAction = $this->getKeywordOptimizationSettings('pipeline_keyword/mid_high');
        
        $triggerActions = [
            'low' => $lowTriggerAction,
            'low_mid' => $lowMidTriggerAction,
            'mid' => $midTriggerAction,
            'mid_high' => $midHighTriggerAction
        ];

        return $triggerActions;
    }

    /**
     * Get product texts
     *
     * @return array
     */
    public function getProductFields()
    {
        return $this->productTexts->toOptionArray();
    }

    /**
     * Get global product fields
     *
     * @return array
     */
    public function getGlobalProductFields()
    {
        $selected = $this->helper->getKeywordOptimizationSettings('products');
        if ($selected) {
            return explode(',', $selected);
        }

        return [];
    }

    /**
     * Get default product texts
     *
     * @return array
     */
    public function getDefaultProductTexts()
    {
        $selected = $this->helper->getKeywordOptimizationSettings('products');
        if ($selected) {
            $selected = explode(',', $selected);
            if (!$this->helper->getCustomOpenGraph()) {
                $noOpenGraph = array_diff($selected, ['open_graph']);
                return $noOpenGraph;
            }
            return $selected;
        }

        $defaultProductTexts = $this->defaultProductTexts->getDefaultValues();

        return explode(',', $defaultProductTexts);
    }
    /**
     * Get default product texts
     *
     * @return array
     */
    public function getDefaultCategoryTexts()
    {
        $selected = $this->helper->getKeywordOptimizationSettings('categories');
        if ($selected) {
            $selected = explode(',', $selected);
            if (!$this->helper->getCustomOpenGraph()) {
                $noOpenGraph = array_diff($selected, ['open_graph']);
                return $noOpenGraph;
            }
            return $selected;
        }

        $defaultProductTexts = $this->defaultProductTexts->getDefaultValues();

        return explode(',', $defaultProductTexts);
    }

    /**
     * Returns true if cron is available (running recently)
     *
     * @return bool
     */
    public function isCronRunning(): bool
    {
        return $this->cronStatus->isCronRunning();
    }
}
