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

<?php
/**
 * @var WriteTextAI\WriteTextAI\Block\Adminhtml\Setup\Index $block
 */

$fields = $block->getDataMappingFields();
$values = $block->getMappedAttributes() ?? [];
$categoryFields = $block->getCategoryDataMappingFields();
$categoryFieldValues = $block->getCategoryMappedAttributes() ?? [];
$categoryDefaultMapping = $block->getCategoryDefaultMapping() ?? [];
$defaultValues = $block->getDefaultMapping();
$customOpenGraph = $block->getCustomOpenGraph();
$openGraphCss = $customOpenGraph ? 'wtai-open_graph' : 'wtai-open_graph wtai-no-display';
if (!$customOpenGraph) {
    $fields['short_product_description'] = __('Product short description');
}
?>

<form
    action="<?= $escaper->escapeUrl($block->getSaveUrl()) ?>"
    method="post"
    id="wtaiStep2Form"
    class="wtai-step2-form">
    <input type="hidden" name="step" value="2" />
    <?= /* @noEscape */ $block->getBlockHtml('formkey') ?>
    <?php foreach ($fields as $name => $label): ?>
        <?php if ($name === 'open_graph'): ?>
            <div class="wtai-field-row">
                <input type="checkbox"
                    class="admin__control-checkbox"
                    id="wtaiCustomOpenGraph"
                    name="custom_open_graph"
                    value="1"
                    <?= /* @noEscape */ $customOpenGraph ? 'checked' : '' ?> />
                <label class="wtai-label admin__field-label" for="wtaiCustomOpenGraph">
                    <?= $escaper->escapeHtml(__('Custom Open Graph text field')) ?>
                </label>
            </div>
        <?php endif ?>

        <?php
        $class = ($name === 'open_graph') ? $openGraphCss : '';
        $class .= ($name === 'short_product_description') ? 'wtai-short_product_description' : '';
        ?>
        <div class="wtai-field-row required <?= /* @noEscape */ $class ?>">
            <label class="wtai-label"><?= $escaper->escapeHtml($label) ?><span class="wtai-required">*</span></label>
            <div class="wtai-field">
                <div class="<?= $escaper->escapeHtmlAttr($name) ?>"
                    data-bind="<?= /* @noEscape */ "scope: '" . $name . "_select'" ?>">
                    <div class="admin__action-multiselect-wrap action-select-wrap"
                        tabindex="0"
                        data-bind="
                            attr: {
                                id: uid
                            },
                            css: {
                                _active: listVisible,
                                'admin__action-multiselect-tree': isTree()
                            },
                            event: {
                                focusin: onFocusIn,
                                focusout: onFocusOut,
                                keydown: keydownSwitcher
                            },
                            outerClick: outerClick.bind($data)
                        ">
                        <!-- ko ifnot: chipsEnabled -->
                        <div class="action-select admin__action-multiselect"
                            data-role="advanced-select"
                            data-bind="
                                css: {_active: listVisible},
                                click: function(data, event) {
                                    toggleListVisible(data, event)
                                }
                        ">
                            <div class="admin__action-multiselect-text"
                                data-role="selected-option"
                                ifnot="validationLoading"
                                data-bind="
                                    css: {warning: warn().length},
                                    html: setCaption()
                            "></div>
                        </div>
                        <!-- /ko -->
                        <div class="action-menu" data-bind="css: {_active: listVisible}">
                            <!-- ko if: filterOptions -->
                            <div class="admin__action-multiselect-search-wrap">
                                <input class="admin__control-text admin__action-multiselect-search"
                                    data-role="advanced-select-text"
                                    type="text"
                                    data-bind="
                                        event: {
                                            keydown: filterOptionsKeydown
                                        },
                                        attr: {
                                            id: uid+2,
                                            placeholder: filterPlaceholder
                                        },
                                        valueUpdate: 'afterkeydown',
                                        value: filterInputValue,
                                        hasFocus: filterOptionsFocus
                                    ">
                                <label class="admin__action-multiselect-search-label"
                                    data-action="advanced-select-search"
                                    data-bind="attr: {for: uid+2}
                                "></label>
                                <div if="itemsQuantity"
                                    data-bind="text: itemsQuantity"
                                    class="admin__action-multiselect-search-count"></div>
                            </div>
                            <!-- /ko -->
                            <ul class="admin__action-multiselect-menu-inner _root" data-bind="
                                    event: {
                                        scroll: function(data, event){onScrollDown(data, event)}
                                    }
                                ">
                                <!-- ko foreach: { data: options, as: 'option'}  -->
                                <li class="admin__action-multiselect-menu-inner-item _root"
                                    data-bind="css: { _parent: $data.optgroup, _disabled: $parent.isDisabled(option) }"
                                    data-role="option-group">
                                    <div class="action-menu-item" data-bind="
                                        css: {
                                            _selected: $parent.isSelectedValue(option),
                                            _hover: $parent.isHovered(option, $element),
                                            _expended: $parent.getLevelVisibility($data) && $parent.showLevels($data),
                                            _unclickable: $parent.isLabelDecoration($data),
                                            _last: $parent.addLastElement($data),
                                            '_with-checkbox': $parent.showCheckbox
                                        },
                                        click: function(data, event) {
                                            $parent.toggleOptionSelected($data, $index(), event);
                                        },
                                        clickBubble: false
                                    ">
                                        <label class="admin__action-multiselect-label">
                                            <span data-bind="text: option.label"></span>
                                            <span if="$parent.getPath(option)"
                                                class="admin__action-multiselect-item-path"
                                                data-bind="text: $parent.getPath(option)"></span>
                                        </label>
                                    </div>
                                </li>
                                <!-- /ko -->
                            </ul>
                            <input class="admin__control-text custom-select"
                                type="hidden"
                                data-bind="
                                    event: {change: userChanges},
                                    value: value,
                                    hasFocus: focused,
                                    valueUpdate: valueUpdate,
                                    attr: {
                                        name: fieldName,
                                        'aria-describedby': noticeId,
                                        id: uid,
                                        disabled: disabled
                            }" />

                            <!-- ko if: $data.closeBtn -->
                            <div class="admin__action-multiselect-actions-wrap">
                                <button class="action-default"
                                    data-action="close-advanced-select"
                                    type="button"
                                    data-bind="click: outerClick">
                                    <span translate="closeBtnLabel"></span>
                                </button>
                            </div>
                            <!-- /ko -->
                        </div>
                    </div>
                </div>
            </div>
        </div>
    <?php endforeach ?>
    <?php foreach ($categoryFields as $name => $label): ?>
        <?php
        $class = '';
        $fieldPostName = $name;
        if ($name === 'page_title') {
            $fieldPostName = 'category_page_title';
        } elseif ($name === 'page_description') {
            $fieldPostName = 'category_page_description';
        }
        ?>
        <div class="wtai-field-row required <?= /* @noEscape */ $class ?>">
            <label class="wtai-label"><?= $escaper->escapeHtml($label) ?><span class="wtai-required">*</span></label>
            <div class="wtai-field">
                <div class="<?= $escaper->escapeHtmlAttr($name) ?>"
                    data-bind="<?= /* @noEscape */ "scope: '" . $fieldPostName . "_select'" ?>">
                    <div class="admin__action-multiselect-wrap action-select-wrap"
                        tabindex="0"
                        data-bind="
                            attr: {
                                id: uid
                            },
                            css: {
                                _active: listVisible,
                                'admin__action-multiselect-tree': isTree()
                            },
                            event: {
                                focusin: onFocusIn,
                                focusout: onFocusOut,
                                keydown: keydownSwitcher
                            },
                            outerClick: outerClick.bind($data)
                        ">
                        <!-- ko ifnot: chipsEnabled -->
                        <div class="action-select admin__action-multiselect"
                            data-role="advanced-select"
                            data-bind="
                                css: {_active: listVisible},
                                click: function(data, event) {
                                    toggleListVisible(data, event)
                                }
                        ">
                            <div class="admin__action-multiselect-text"
                                data-role="selected-option"
                                ifnot="validationLoading"
                                data-bind="
                                    css: {warning: warn().length},
                                    html: setCaption()
                            "></div>
                        </div>
                        <!-- /ko -->
                        <div class="action-menu" data-bind="css: {_active: listVisible}">
                            <!-- ko if: filterOptions -->
                            <div class="admin__action-multiselect-search-wrap">
                                <input class="admin__control-text admin__action-multiselect-search"
                                    data-role="advanced-select-text"
                                    type="text"
                                    data-bind="
                                        event: {
                                            keydown: filterOptionsKeydown
                                        },
                                        attr: {
                                            id: uid+2,
                                            placeholder: filterPlaceholder
                                        },
                                        valueUpdate: 'afterkeydown',
                                        value: filterInputValue,
                                        hasFocus: filterOptionsFocus
                                    ">
                                <label class="admin__action-multiselect-search-label"
                                    data-action="advanced-select-search"
                                    data-bind="attr: {for: uid+2}
                                "></label>
                                <div if="itemsQuantity"
                                    data-bind="text: itemsQuantity"
                                    class="admin__action-multiselect-search-count"></div>
                            </div>
                            <!-- /ko -->
                            <ul class="admin__action-multiselect-menu-inner _root" data-bind="
                                    event: {
                                        scroll: function(data, event){onScrollDown(data, event)}
                                    }
                                ">
                                <!-- ko foreach: { data: options, as: 'option'}  -->
                                <li class="admin__action-multiselect-menu-inner-item _root"
                                    data-bind="css: { _parent: $data.optgroup, _disabled: $parent.isDisabled(option) }"
                                    data-role="option-group">
                                    <div class="action-menu-item" data-bind="
                                        css: {
                                            _selected: $parent.isSelectedValue(option),
                                            _hover: $parent.isHovered(option, $element),
                                            _expended: $parent.getLevelVisibility($data) && $parent.showLevels($data),
                                            _unclickable: $parent.isLabelDecoration($data),
                                            _last: $parent.addLastElement($data),
                                            '_with-checkbox': $parent.showCheckbox
                                        },
                                        click: function(data, event) {
                                            $parent.toggleOptionSelected($data, $index(), event);
                                        },
                                        clickBubble: false
                                    ">
                                        <label class="admin__action-multiselect-label">
                                            <span data-bind="text: option.label"></span>
                                            <span if="$parent.getPath(option)"
                                                class="admin__action-multiselect-item-path"
                                                data-bind="text: $parent.getPath(option)"></span>
                                        </label>
                                    </div>
                                </li>
                                <!-- /ko -->
                            </ul>
                            <input class="admin__control-text"
                                type="hidden"
                                data-bind="
                                    event: {change: userChanges},
                                    value: value,
                                    hasFocus: focused,
                                    valueUpdate: valueUpdate,
                                    attr: {
                                        name: fieldName,
                                        'aria-describedby': noticeId,
                                        id: uid,
                                        disabled: disabled
                            }" />

                            <!-- ko if: $data.closeBtn -->
                            <div class="admin__action-multiselect-actions-wrap">
                                <button class="action-default"
                                    data-action="close-advanced-select"
                                    type="button"
                                    data-bind="click: outerClick">
                                    <span translate="closeBtnLabel"></span>
                                </button>
                            </div>
                            <!-- /ko -->
                        </div>
                    </div>
                </div>
            </div>
        </div>
    <?php endforeach ?>
    <div class="wtai-error-message"></div>
    <div class="wtai-actions">
        <button type="submit" id="wtaiNextButton" class="wtai-button">
            <?= $escaper->escapeHtml(__('Finish setup and start generating text')) ?>
            <span class="wtai-button-icon">&rarr;</span>
        </button>
    </div>
</form>
<script>
    require([
        "jquery",
        "mage/mage",
        "mage/validation"
    ], function($) {
        $('#wtaiStep2Form').mage('validation', {
            ignore: [],
            groups: {
                names: "<?= $escaper->escapeJs(implode(" ", array_keys($fields))) ?>"
            },
            rules: {
                <?php $counter = 0; ?>
                <?php foreach ($fields as $field => $label): ?>
                    <?php $counter++; ?>
                    <?= $escaper->escapeJs($field) ?>: {
                        <?php if ($field !== 'open_graph'): ?>
                            required: true,
                            'wtai-unique': [true, ".custom-select"]
                        <?php else: ?>
                            required: {
                                param: true,
                                depends: function(element) {
                                    return $("#wtaiCustomOpenGraph").is(":checked");
                                }
                            },
                            'wtai-unique': {
                                param: [true, ".custom-select"],
                                depends: function(element) {
                                    return $("#wtaiCustomOpenGraph").is(":checked");
                                }
                            }
                        <?php endif ?>
                    },
                <?php endforeach ?>
            },
            errorPlacement: function(error, element) {
                $(".wtai-error-message").html(error);
            }
        });

        $(document).ready(function() {
            $("#wtaiCustomOpenGraph").on("change", function() {
                if ($(this).is(":checked")) {
                    $(".wtai-field-row.wtai-open_graph").removeClass('wtai-no-display');
                    $(".wtai-field-row.wtai-short_product_description > label")
                        .html("<?= $escaper->escapeJs(__('Product short description')) ?>"+
                            "<span class='wtai-required'>*</span>");
                } else {
                    $(".wtai-field-row.wtai-open_graph").addClass('wtai-no-display');
                    $(".wtai-field-row.wtai-short_product_description > label")
                        .html("<?= $escaper->escapeJs(__('Product short description')) ?>"+
                            "<span class='wtai-required'>*</span>");
                }
            });
        });
    });
</script>
<?php foreach ($fields as $name => $label): ?>
    <?php
    $params = [
        "component" => "WriteTextAI_WriteTextAI/js/form/element/data-mapping",
        "elementTmpl" => "WriteTextAI_WriteTextAI/elements/data-mapping",
        "template" => "ui/form/field",
        "options" => $block->getDataMappingAttributesSelection(),
        "multiple" => false,
        "filterOptions" => true,
        "selectedPlaceholders" => [
            "defaultPlaceholder" => __('Select text field')
        ],
        "filterPlaceholder" => __('Search by keyword'),
        "labelVisible" => false,
        "value" => isset($values[$name]) ? $values[$name] : $defaultValues[$name],
        "fieldName" => $name
    ];
    ?>
    <script type="text/x-magento-init">
        {
            "*": {
                "Magento_Ui/js/core/app": {
                    "components": {
                        "<?= /* @noEscape */ $name . '_select' ?>": <?= /* @noEscape */ json_encode($params) ?>
                    }
                }
            }
        }
    </script>
<?php endforeach ?>
<?php foreach ($categoryFields as $name => $label): ?>
    <?php
    $fieldPostName = $name;
    if ($name === 'page_title') {
        $fieldPostName = 'category_page_title';
    } elseif ($name === 'page_description') {
        $fieldPostName = 'category_page_description';
    }
    $params = [
        "component" => "WriteTextAI_WriteTextAI/js/categories/form/element/data-mapping",
        "elementTmpl" => "WriteTextAI_WriteTextAI/elements/data-mapping",
        "template" => "ui/form/field",
        "options" => $block->getCategoryDataMappingAttributesSelection(),
        "multiple" => false,
        "filterOptions" => true,
        "selectedPlaceholders" => [
            "defaultPlaceholder" => __('Select text field')
        ],
        "filterPlaceholder" => __('Search by keyword'),
        "labelVisible" => false,
        "value" => isset($categoryFieldValues[$name]) ? $categoryFieldValues[$name] : $categoryDefaultMapping[$name],
        "fieldName" => $fieldPostName
    ];
    ?>
    <script type="text/x-magento-init">
        {
            "*": {
                "Magento_Ui/js/core/app": {
                    "components": {
                        "<?= /* @noEscape */ $fieldPostName . '_select' ?>": <?= /* @noEscape */ json_encode($params) ?>
                    }
                }
            }
        }
    </script>
<?php endforeach ?>
