<?php
/**
 * Mageplaza
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Mageplaza.com license that is
 * available through the world-wide-web at this URL:
 * https://www.mageplaza.com/LICENSE.txt
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade this extension to newer
 * version in the future.
 *
 * @category    Mageplaza
 * @package     Mageplaza_DeliveryTime
 * @copyright   Copyright (c) Mageplaza (https://www.mageplaza.com/)
 * @license     https://www.mageplaza.com/LICENSE.txt
 */

// @codingStandardsIgnoreFile

/** @var Mageplaza\DeliveryTime\Block\Adminhtml\Config\Backend\DateOff $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>
                    <input type="hidden" class="mpdeliverytime-dropdown-attribute-required"
                           name="groups[general][fields][default_wishlist][value][dropdown_attribute_validation_unique]"/>
                </td>
            </tr>
            </tfoot>
            <tbody id="addRow<?= $_htmlId ?>"></tbody>
        </table>
    </div>
    <input type="hidden" name="<?= $block->getElement()->getName() ?>[__empty]" value=""/>

    <script>
        require([
            'mage/template',
            'jquery',
            'prototype',
            'mage/translate',
            'mage/backend/validation'
        ], function (mageTemplate, $j) {
            $j.validator.addMethod('mpdeliverytime-dropdown-attribute-required',
                function (value, element) {
                    var empty = $j(element).closest('table')
                    .find('input.input-date:visible')
                    .filter(function (i, el) {
                        return $j.mage.isEmpty(el.value);
                    }).length;
                    return empty === 0;
                },
                $j.mage.__('Date value must not be empty.')
            );

            // 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(),
                            id = '_' + d.getTime() + '_' + d.getMilliseconds();
                        templateValues = {
                        <?php foreach ($block->getColumns() as $columnName => $column): ?>
                        <?=  $columnName ?>:
                        '',
                            'option_extra_attrs'
                    :
                        {
                        }
                    ,
                        <?php endforeach; ?>
                        _id: id
                    }
                        ;
                    }

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

                    $j('#' + id).trigger('contentUpdated');

                    // 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
                    <?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>
