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

namespace WriteTextAI\WriteTextAI\Block\Adminhtml\System\Config\Field;

use Magento\Config\Block\System\Config\Form\Field;
use Magento\Framework\Data\Form\Element\AbstractElement;
use Magento\Backend\Block\Template\Context;
use Magento\Framework\View\Helper\SecureHtmlRenderer;
use WriteTextAI\WriteTextAI\Model\SettingManager;

class MinMax extends Field
{
    /**
     * @var SettingManager
     */
    protected $settingManager;

    /**
     * @param Context $context
     * @param SettingManager $settingManager
     * @param array $data
     * @param SecureHtmlRenderer|null $secureRenderer
     */
    public function __construct(
        Context $context,
        SettingManager $settingManager,
        array $data = [],
        ?SecureHtmlRenderer $secureRenderer = null
    ) {
        $this->settingManager = $settingManager;
        parent::__construct(
            $context,
            $data,
            $secureRenderer
        );
    }

    /**
     * @inheritdoc
     */
    protected function _getElementHtml(AbstractElement $element)
    {
        $rules = $this->getRules();

        $minOutputWords = $rules['minOutputWords'] ?? '';
        $maxOutputWords = $rules['maxOutputWords'] ?? '';
        $minClusterBasedPipelinesCount = $rules['minClusterBasedPipelinesCount'] ?? '1';
        $maxClusterBasedPipelinesCount = (int)(($rules['maxKeywords'] ?? 6) - 1);
        $minClusterBasedPipelinesCountCategory = $rules['minClusterBasedPipelinesCountCategory'] ?? '1';
        $maxClusterBasedPipelinesCountCategory = (int)(($rules['maxKeywords'] ?? 6) - 1);
        $minTriggerActionNPosition = $rules['minTriggerActionNPosition'] ?? '2';
        $maxTriggerActionNPosition = $rules['maxTriggerActionNPosition'] ?? '100';
        $minTriggerActionNDays = $rules['minTriggerActionNDays'] ?? '1';
        $maxTriggerActionNDays = $rules['maxTriggerActionNDays'] ?? '365';

        $element->setData('type', 'number');

        $html = parent::_getElementHtml($element);
        
        $html .= '<script type="text/javascript">
            require(["jquery", "jquery/ui"], function ($) {
                $(document).ready(function () {
                    var id = "' . $element->getHtmlId() . '";

                    $("#" + id).on("change", function () {
                        var value = $(this).val(),
                            max = ' . $maxOutputWords . ',
                            min = ' . $minOutputWords . ';
                            
                        var keywordSettingsPrefix = "writetextai_settings_keyword_optimization_pipeline_keyword";

                        switch (id) {
                            case "writetextai_settings_description_min":
                                max = Number($("#writetextai_settings_description_max").val()) - 1;
                                break;
                            case "writetextai_settings_description_max":
                                min = Number($("#writetextai_settings_description_min").val()) + 1;
                                break;
                            case "writetextai_settings_excerpt_min":
                                max = Number($("#writetextai_settings_excerpt_max").val()) - 1;
                                break;
                            case "writetextai_settings_excerpt_max":
                                min = Number($("#writetextai_settings_excerpt_min").val()) + 1;
                                break;
                            case "writetextai_settings_keyword_optimization_cluster_based_pipelines_count":
                                min = ' . $minClusterBasedPipelinesCount . ';
                                max = ' . $maxClusterBasedPipelinesCount . ';
                                break;
                            case "writetextai_settings_keyword_optimization_cluster_based_pipelines_count_category":
                                min = ' . $minClusterBasedPipelinesCountCategory . ';
                                max = ' . $maxClusterBasedPipelinesCountCategory . ';
                                break;
                            case keywordSettingsPrefix + "_low_trigger_action_n_position":
                            case keywordSettingsPrefix + "_low_mid_trigger_action_n_position":
                            case keywordSettingsPrefix + "_mid_trigger_action_n_position":
                            case keywordSettingsPrefix + "_mid_high_trigger_action_n_position":
                                min = ' . $minTriggerActionNPosition . ';
                                max = ' . $maxTriggerActionNPosition . ';
                                break;
                            case keywordSettingsPrefix + "_low_trigger_action_n_days":
                            case keywordSettingsPrefix + "_low_mid_trigger_action_n_days":
                            case keywordSettingsPrefix + "_mid_trigger_action_n_days":
                            case keywordSettingsPrefix + "_mid_high_trigger_action_n_days":
                                min = ' . $minTriggerActionNDays . ';
                                max = ' . $maxTriggerActionNDays . ';
                                break;
                            default:
                                break;
                        }

                        if (value < min) {
                            $(this).val(min);
                        } else if (value > max) {
                            $(this).val(max);
                        }
                    });
                });
            });
        </script>';
        
        return $html;
    }

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