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

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

use Magento\Config\Block\System\Config\Form\Field;
use Magento\Framework\Data\Form\Element\AbstractElement;

class Mapping extends Field
{
    /**
     * @inheritdoc
     */
    protected function _getElementHtml(AbstractElement $element)
    {
        $html = parent::_getElementHtml($element);
        
        $html .= '<script type="text/javascript">
            require([
                "jquery",
                "jquery/ui"
            ], function ($) {
                $(document).ready(function () {
                    var elementName = "' . $element->getName() . '",
                        elementSelector = "[name=\"" + elementName + "\"]",
                        pageTitleName = "groups[category_mapping][fields][page_title][value]",
                        pageDescriptionName = "groups[category_mapping][fields][page_description][value]",
                        categoryDescriptionName = "groups[category_mapping][fields][category_description][value]",
                        fields = [
                            pageTitleName,
                            pageDescriptionName,
                            categoryDescriptionName,
                        ];

                    function disableSameValue() {
                        var value = $(elementSelector).val();
                        var selectedValues = [];
                        for (var i = 0; i < fields.length; i++) {
                            selectedValues.push($("[name=\"" + fields[i] + "\"]").val());
                        }
                        for (var i = 0; i < fields.length; i++) {
                            var selectedVal = $("[name=\"" + fields[i] + "\"]").val();
                            $("[name=\"" + fields[i] + "\"] > option").each(function() {
                                if (selectedValues.includes($(this).val())) {
                                    if ($(this).val() != selectedVal) {
                                        $(this).prop("disabled", true);
                                    }
                                } else {
                                    $(this).prop("disabled", false);
                                }
                            });
                        }
                        
                    }
                    
                    disableSameValue();

                    $(elementSelector).on("change", disableSameValue);
                });
            });
        </script>';
        
        return $html;
    }
}
