<?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\ViewModel\Settings;

class Combination extends Field
{
    /**
     * @var Settings
     */
    protected $settings;

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

    /**
     * @inheritdoc
     */
    protected function _getElementHtml(AbstractElement $element)
    {
        $disallowedCombinations = $this->settings->getSettings('disallowedCombinations');

        $html = parent::_getElementHtml($element);
        
        $html .= '<script type="text/javascript">
            require([
                "jquery",
                "jquery/ui"
            ], function ($) {
                $(document).ready(function () {
                    var elementName = "' . $element->getName() . '",
                        elementSelector = "[name=\"" + elementName + "\"]",
                        disallowedCombinations = ' . json_encode($disallowedCombinations) . ',
                        toneFieldName = "groups[general][fields][tones][value][]",
                        tonesFieldSelector = "[name=\"groups[general][fields][tones][value][]\"]",
                        stylesFieldName = "groups[general][fields][styles][value]",
                        stylesFieldSelector = "[name=\"groups[general][fields][styles][value]\"]",
                        audiencesFieldName = "groups[general][fields][audiences][value][]",
                        audiencesFieldSelector = "[name=\"groups[general][fields][audiences][value][]\"]";
        
                    function disableCombination(event = null, onload = false) {
        
                        switch (elementName) {
                            case toneFieldName:
                                var value = $(elementSelector).val();
                                var customToneRowSelector = "#row_writetextai_settings_general_custom_tone";
                                var customToneValue = "custom";
                                var customToneInputSelector = customToneRowSelector + " input[type=\"text\"]";
                                if (!onload) {
                                    $(stylesFieldSelector).attr("disabled", false);
                                    $(audiencesFieldSelector + " option").attr("disabled", false);
                                    $(stylesFieldSelector).closest(".value").find("p.note").find(".notice").remove();
                                }
        
                                for (var i = 0; i < disallowedCombinations.length; i++) {
                                    var currentCombination = disallowedCombinations[i].combination,
                                        combination = currentCombination.find(function (obj) {
                                            return obj.type == "Tone" && value.includes(obj.id);
                                        });
        
                                    if (combination) {
                                        var combinationStyle = currentCombination.find(function (obj) {
                                                return obj.type == "Style";
                                            }),
                                            combinationAudience = currentCombination.find(function (obj) {
                                                return obj.type == "Audience";
                                            }),
                                            styleFieldSelector = stylesFieldSelector +
                                                    "[value=\"" + combinationStyle.id + "\"]";
                                        
                                        if (!combinationAudience) {
                                            $(styleFieldSelector).attr("disabled", true);
                                            $(styleFieldSelector).closest(".value").find("p.note")
                                            .append("<span class=\"notice\"><br><br>%s</span>".replace("%s",
                                                "' . __("%s style is unavailable when the %t tone is selected.") . '"
                                                    .replace("%s", combinationStyle.id)
                                                    .replace("%t", value)
                                            ));
                                        } else {
                                            var audienceFieldSelector = audiencesFieldSelector +
                                                    " [value=\"" + combinationAudience.id + "\"]";
        
                                            if ($(styleFieldSelector).is(":checked")) {
                                                $(audienceFieldSelector).attr("disabled", true);
                                            }
                                            if ($(audienceFieldSelector).is(":selected")) {
                                                $(styleFieldSelector).attr("disabled", true);
                                            }
                                        }
                                    }
                                }

                                if (Array.isArray(value) && value.includes(customToneValue)) {
                                    if (value.length !== 1 || value[0] !== customToneValue) {
                                        $(elementSelector).val([customToneValue]);
                                    }
                                    $("#custom_tone_counter").remove();
                                    $(customToneRowSelector).show();
                                    $(customToneInputSelector).prop("required", true);
                                    $(customToneInputSelector).attr("maxlength", "250");
                                    $(customToneInputSelector).after(
                                        "<span id=\"custom_tone_counter\" class=\"counter\" "
                                        + "style=\"font-size: 11px;float: right;margin-top: 7px;\">"
                                        + $(customToneInputSelector).val().length
                                        + "/250 char</span>"
                                    );
                                    $(customToneInputSelector).on("input", function () {
                                        $("#custom_tone_counter").text(
                                            $(this).val().length + "/250 char"
                                        );
                                    });
                                } else {
                                    $(customToneRowSelector).hide();
                                    $("#custom_tone_counter").remove();
                                    $(customToneInputSelector).prop("required", false);
                                    $(customToneInputSelector).val(null);
                                }
                                
                                break;
                            case stylesFieldName:
                                var value = $(elementSelector + ":checked").val();
                                var customStyleRowSelector = "#row_writetextai_settings_general_custom_style";
                                var customStyleValue = "custom";
                                var customStyleInputSelector = customStyleRowSelector + " input[type=\"text\"]";
                                
                               
                                if (!onload) {
                                    $(tonesFieldSelector + " option").attr("disabled", false);
                                    $(audiencesFieldSelector + " option").attr("disabled", false);
                                    $(tonesFieldSelector).closest(".value").find("p.note").find(".notice").remove();
                                }
        
                                for (var i = 0; i < disallowedCombinations.length; i++) {
                                    var currentCombination = disallowedCombinations[i].combination,
                                        combination = currentCombination.find(function (obj) {
                                            return obj.type == "Style" && obj.id == value;
                                        });
        
                                    if (combination) {
                                        var combinationTone = currentCombination.find(function (obj) {
                                                return obj.type == "Tone";
                                            }),
                                            combinationAudience = currentCombination.find(function (obj) {
                                                return obj.type == "Audience";
                                            }),
                                            toneFieldSelector = tonesFieldSelector +
                                                " [value=\"" + combinationTone.id + "\"]";
        
                                        if (!combinationAudience) {
                                            $(toneFieldSelector).attr("disabled", true);
                                            $(toneFieldSelector).closest(".value").find("p.note")
                                            .append("<span class=\"notice\"><br><br>%s</span>".replace("%s",
                                                "' . __("%s tone is unavailable when the %t style is selected.") . '"
                                                    .replace("%s", combinationTone.id)
                                                    .replace("%t", value)
                                            ));
                                        } else {
                                            var audienceFieldSelector = audiencesFieldSelector +
                                                " [value=\"" + combinationAudience.id + "\"]";
        
                                            if ($(toneFieldSelector).is(":selected")) {
                                                $(audienceFieldSelector).attr("disabled", true);
                                            }
                                            if ($(audienceFieldSelector).is(":selected")) {
                                                $(toneFieldSelector).attr("disabled", true);
                                            }
                                        }
                                    }
                                }
                                if (value === customStyleValue) {
                                    $("#custom_style_counter").remove();
                                    $(customStyleRowSelector).show();
                                    $(customStyleInputSelector).prop("required", true);
                                    $(customStyleInputSelector).attr("maxlength", "250");
                                    $(customStyleInputSelector).after(
                                        "<span id=\"custom_style_counter\" class=\"counter\" "
                                        + "style=\"font-size: 11px;float: right;margin-top: 7px;\">"
                                        + $(customStyleInputSelector).val().length
                                        + "/250 char</span>"
                                    );
                                    $(customStyleInputSelector).on("input", function () {
                                        $("#custom_style_counter").text(
                                            $(this).val().length + "/250 char"
                                        );
                                    });
                                } else {
                                    $(customStyleRowSelector).hide();
                                    $("#custom_style_counter").remove();
                                    $(customStyleInputSelector).prop("required", false);
                                    $(customStyleInputSelector).val(null);
                                }
                                break;
                            case audiencesFieldName:
                                var value = $(elementSelector).val();
        
                                if (!onload) {
                                    $(tonesFieldSelector + " option").attr("disabled", false);
                                    $(stylesFieldSelector).attr("disabled", false);
                                }
        
                                for (var i = 0; i < disallowedCombinations.length; i++) {
                                    var currentCombination = disallowedCombinations[i].combination,
                                        combination = currentCombination.find(function (obj) {
                                            return obj.type == "Audience" && obj.id == value;
                                        });
        
                                    if (combination) {
                                        var combinationTone = currentCombination.find(function (obj) {
                                                return obj.type == "Tone";
                                            }),
                                            combinationStyle = currentCombination.find(function (obj) {
                                                return obj.type == "Style";
                                            }),
                                            toneFieldSelector = tonesFieldSelector +
                                                " [value=\"" + combinationTone.id + "\"]",
                                            styleFieldSelector = stylesFieldSelector +
                                                "[value=\"" + combinationStyle.id + "\"]";
        
                                        if ($(toneFieldSelector).is(":selected")) {
                                            $(styleFieldSelector).attr("disabled", true);
                                        }
                                        if ($(styleFieldSelector).is(":checked")) {
                                            $(toneFieldSelector).attr("disabled", true);
                                        }
                                    }
                                }
                                break;
                            default:
                                break;
                        }
                    }
        
                    disableCombination(null, true);
        
                    $(elementSelector).on("change", disableCombination);
                });
            });
        </script>';
        
        return $html;
    }
}
