<?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();
                                
                                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);
                                            }
                                        }
                                    }
                                }
                                break;
                            case stylesFieldName:
                                var value = $(elementSelector + ":checked").val();
        
                                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);
                                            }
                                        }
                                    }
                                }
                                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;
    }
}
