<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/** @var \Magento\Framework\View\Helper\SecureHtmlRenderer $secureRenderer */
?>

<?php
$_htmlId = $block->getHtmlId() ? $block->getHtmlId() : '_' . uniqid();
$_colspan = $block->isAddAfter() ? 2 : 1;
?>

<div class="design_theme_ua_regexp" id="grid<?= $block->escapeHtmlAttr($_htmlId) ?>">
    <div class="admin__control-table-wrapper">
        <table class="admin__control-table" id="<?= $block->escapeHtmlAttr($block->getElement()->getId()) ?>">
            <thead>
            <tr>
                <?php foreach ($block->getColumns() as $columnName => $column): ?>
                    <th><?= $block->escapeHtml($column['label']) ?></th>
                <?php endforeach; ?>
                <th class="col-actions" colspan="<?= (int)$_colspan ?>"><?= $block->escapeHtml(__('Action')) ?></th>
            </tr>
            </thead>
            <tfoot>
            <tr>
                <td colspan="<?= count($block->getColumns())+$_colspan ?>" class="col-actions-add">
                    <button id="addToEndBtn<?= $block->escapeHtmlAttr($_htmlId) ?>"
                            class="action-add"
                            title="<?= $block->escapeHtmlAttr(__('Add')) ?>"
                            type="button">
                        <span><?= $block->escapeHtml($block->getAddButtonLabel()) ?></span>
                    </button>
                </td>
            </tr>
            </tfoot>
            <tbody id="addRow<?= $block->escapeHtmlAttr($_htmlId) ?>"></tbody>
        </table>
    </div>
    <input type="hidden" name="<?= $block->escapeHtmlAttr($block->getElement()->getName()) ?>[__empty]" value="" />

    <?php $scriptString = <<<script
        require([
            'mage/template',
            'prototype'
        ], function (mageTemplate) {
        // create row creator
        window.arrayRow{$block->escapeJs($_htmlId)} = {

            // define row prototypeJS template
            template: mageTemplate(
                    '<tr id="row_<%- _id %>">'
script;
    foreach ($block->getColumns() as $columnName => $column):
        $scriptString .= <<<script

                        + '<td>'
                        + '{$block->escapeJs($block->renderCellTemplate($columnName))}'
                        + '<\/td>'
script;
    endforeach;

    if ($block->isAddAfter()):
        $scriptString .= <<<script

                        + '<td><button class="action-add" type="button" id="addAfterBtn<%- _id %>"><span>'
                        + '{$block->escapeJs(__('Add after'))}'
                        + '<\/span><\/button><\/td>'
script;
    endif;
    $scriptString .= <<<script

                    + '<td class="col-actions"><button '
                    + 'class="action-delete" type="button">'
                    + '<span>{$block->escapeJs(__('Delete'))}<\/span><\/button><\/td>'
                    + '<\/tr>'

script;
    $scriptString1 = /* $noEscape */ $secureRenderer->renderEventListenerAsTag(
        'onclick',
        "arrayRow" . $block->escapeJs($_htmlId) . ".del('row_<%- _id %>')",
        "tr#row_<%- _id %> button.action-delete"
    );

    $scriptString .= " + '" . $block->escapeJs($scriptString1) . "'" . PHP_EOL;

    $scriptString .= <<<script
            ),

            add: function(rowData, insertAfterId) {
                // generate default template data
                var templateValues;

                // Prepare template values
                if (rowData) {
                    templateValues = rowData;
                } else {
                    var d = new Date();
                    templateValues = {
script;
    foreach ($block->getColumns() as $columnName => $column):
        $scriptString .= <<<script

                            {$block->escapeJs($columnName)}: '',
                                'option_extra_attrs': {},
script;
    endforeach;
    $scriptString .= <<<script

                        _id: '_' + d.getTime() + '_' + d.getMilliseconds()
                };
            }

            // Insert new row after specified row or at the bottom
            if (insertAfterId) {
                Element.insert($(insertAfterId), {after: this.template(templateValues)});
            } else {
                Element.insert($('addRow{$block->escapeJs($_htmlId)}'), {bottom: this.template(templateValues)});
            }

            // Fill controls with data
            if (rowData) {
                var rowInputElementNames = Object.keys(rowData.column_values);
                for (var i = 0; i < rowInputElementNames.length; i++) {
                    if ($(rowInputElementNames[i])) {
                        $(rowInputElementNames[i]).setValue(rowData.column_values[rowInputElementNames[i]]);
                    }
                }
            }

            // Add event for {addAfterBtn} button

script;
    if ($block->isAddAfter()):
        $scriptString .= <<<script

            Event.observe('addAfterBtn' + templateValues._id, 'click', this.add.bind(this, false, templateValues._id));

script;
    endif;
    $scriptString .= <<<script

            },

            del: function(rowId) {
                $(rowId).remove();
            }
        }

        // bind add action to "Add" button in last row
        Event.observe('addToEndBtn{$block->escapeJs($_htmlId)}',
            'click',
            arrayRow{$block->escapeJs($_htmlId)}.add.bind(
                arrayRow{$block->escapeJs($_htmlId)}, false, false
            )
        );

        // add existing rows

script;

    foreach ($block->getArrayRows() as $_rowId => $_row) {
        $scriptString .= /** @noEscape */ " arrayRow" .$block->escapeJs($_htmlId) .
            ".add(" . /** @noEscape */ $_row->toJson() . ");\n";
    }
    $scriptString .= <<<script

        // Toggle the grid availability, if element is disabled (depending on scope)
script;
    if ($block->getElement()->getDisabled()):
        $scriptString .= <<<script

        toggleValueElements({checked: true}, $('grid{$block->escapeJs($_htmlId)}').parentNode);
script;
    endif;
    $scriptString .= <<<script

        });
script;
    ?>
    <?= /* @noEscape */ $secureRenderer->renderTag('script', [], $scriptString, false) ?>
</div>
