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

// @codingStandardsIgnoreFile

/** @var Mageplaza\DeliveryTime\Block\Adminhtml\Config\Backend\DeliveryTime $block */
$_htmlId = $block->getHtmlId() ? $block->getHtmlId() : '_' . uniqid();
$_colspan = $block->isAddAfter() ? 2 : 1;
?>

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

    <script>
        require([
            'jquery',
            'mage/template',
            'prototype'
        ], function ($j, mageTemplate) {
            // create row creator
            window.arrayRow<?=  $_htmlId ?> = {
                // define row prototypeJS template
                template: mageTemplate(
                    '<tr id="<%- _id %>">'
                    <?php foreach ($block->getColumns() as $columnName => $column): ?>
                    + '<td>'
                    + '<?=  $block->renderCellTemplate($columnName) ?>'
                    + '<\/td>'
                    <?php endforeach; ?>

                    <?php if ($block->isAddAfter()): ?>
                    + '<td><button class="action-add" type="button" id="addAfterBtn<%- _id %>"><span><?=  __('Add after') ?><\/span><\/button><\/td>'
                    <?php endif; ?>

                    + '<td class="col-actions"><button onclick="arrayRow<?=  $_htmlId ?>.del(\'<%- _id %>\')" class="action-delete" type="button"><span><?=  __('Delete') ?><\/span><\/button><\/td>'
                    + '<\/tr>'
                ),

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

                    // Prepare template values
                    if (rowData) {
                        templateValues = rowData;
                    } else {
                        var d = new Date();
                        templateValues = {
                        <?php foreach ($block->getColumns() as $columnName => $column): ?>
                        <?=  $columnName ?>:
                        '',
                            'option_extra_attrs'
                    :
                        {
                        }
                    ,
                        <?php endforeach; ?>
                        _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<?=  $_htmlId ?>'), {bottom: this.template(templateValues).replace(new RegExp(':&nbsp;', 'g'), '')});
                    }

                    // 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]]);

                                var deliveryTime = $j('#' + rowInputElementNames[i]).siblings('select');

                                for (var j = 0; j < deliveryTime.length; j++) {
                                    deliveryTime[j].setValue(rowData.column_values[rowInputElementNames[i]][j]);
                                }
                            }
                        }
                    }

                    // Add event for {addAfterBtn} button
                    <?php if ($block->isAddAfter()): ?>
                    Event.observe('addAfterBtn' + templateValues._id, 'click', this.add.bind(this, false, templateValues._id));
                    <?php endif; ?>
                },

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

            // bind add action to "Add" button in last row
            Event.observe('addToEndBtn<?=  $_htmlId ?>', 'click', arrayRow<?=  $_htmlId ?>.add.bind(arrayRow<?=  $_htmlId ?>, false, false));

            // add existing rows
            <?php
            foreach ($block->getArrayRows() as $_rowId => $_row) {
                echo "arrayRow{$_htmlId}.add(" . $_row->toJson() . ");\n";
            }
            ?>

            // Toggle the grid availability, if element is disabled (depending on scope)
            <?php if ($block->getElement()->getDisabled()):?>
            toggleValueElements({checked: true}, $('grid<?=  $_htmlId ?>').parentNode);
            <?php endif;?>
        });
    </script>
</div>

<style type="text/css">
    #mpdeliverytime_general_delivery_time tbody tr select:nth-of-type(1) {
        margin-right: 10px;
    }

    #mpdeliverytime_general_delivery_time tbody tr select:nth-of-type(3) {
        display: none; /*hide second selector*/
    }
</style>
