<?php
$theads = [
    [
        "label" => "ID",
        "name" => "id",
        "type" => "text",
        "hidden" => false,
        "disabled" => true,
    ],
    [
        "label" => "Title",
        "name" => "title",
        "type" => "text",
        "hidden" => false,
        "disabled" => false,
    ],
    [
        "label" => "HTML",
        "name" => "html",
        "type" => "textarea",
        "hidden" => false,
        "disabled" => false,
    ],
    [
        "label" => "Redirect",

        "name" => "redirect",
        "type" => "text",
        "hidden" => false,
        "disabled" => false,
    ],
    [
        "label" => "Created At",
        "name" => "created_at",
        "type" => "text",
        "hidden" => false,
        "disabled" => true,
    ],
    [
        "label" => "Updated At",
        "name" => "updated_at",
        "type" => "text",
        "hidden" => false,
        "disabled" => true,
    ],
    [
        "label" => "Status",
        "name" => "status",
        "type" => "text",
        "hidden" => false,
        "disabled" => true,
    ],
    [
        "label" => "Operation",
        "type" => "text",
        "hidden" => true,
        "disabled" => true,
    ],
];
?>
<head>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body>
    <div class="relative overflow-x-auto">
        <caption class="px-6 flex items-start">
            <button
                data-action="add"
                class="show-modal bg-green-700 text-white py-2 px-5 border-none"
            >
                Add
            </button>
        </caption>
        <table
            class="w-ful text-left rtl:text-right text-gray-7000 dark:text-gray-400"
        >
            <thead
                class="text-gray-700 uppercase bg-gray-700 dark:bg-gray-700 dark:text-gray-400"
            >
                <tr>
                    <?php foreach ($theads as $thead): ?>
                    <th scope="col" class="px-6 py-3"><?=$thead['label'] ?></th>
                    <?php endforeach; ?>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($block->getAll() as $row): ?>
                <tr
                    class="bg-white border-b dark:bg-gray-800 dark:border-gray-700"
                    id="row-<?=$row['id'] ?>"
                >
                    <th data-name="id" data-value="<?= $row['id'] ?>" class="px-6 py-4"><?=$row['id'] ?></th>
                    <td data-name="title" data-value="<?= $row['title'] ?>" class="px-6 py-4">
                        <?=$row['title'] ?>
                    </td>
                    <td data-name="html" data-value="<?= htmlentities($row['html']) ?>" class="px-6 py-4">
                        <code>
                            <?=html_entity_decode($row['html']) ?>
                        </code>
                    </td>
                    <td data-name="redirect" data-value="<?= $row['redirect'] ?>" class="px-6 py-4">
                        <?=$row['redirect'] ?>
                    </td>
                    <td data-name="created_at" data-value="<?= $row['created_at'] ?>" class="px-6 py-4">
                        <?=$row['created_at'] ?>
                    </td>
                    <td data-name="updated_at" data-value="<?= $row['updated_at'] ?>" class="px-6 py-4">
                        <?=$row['updated_at'] ?>
                    </td>
                    <td data-name="status" data-value="<?= $row['status'] ?>" class="px-6 py-4">
                        <?=$row['status'] ?>
                    </td>
                    <td class="px-6">
                        <div class="flex items-end">
                            <button
                                data-action="edit"
                                data-id="<?=$row['id'] ?>"
                                class="show-modal bg-blue-700 text-white py-2 px-5 border-none"
                            >
                                Edit
                            </button>
                            <button
                                data-action="delete"
                                data-id="<?=$row['id'] ?>"
                                class="show-modal bg-red-700 text-white py-2 px-5 border-none"
                            >
                                Delete
                            </button>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <!-- Modal -->
    <form id="modal_form" class="w-full p-5" style="display: none">
        <?php foreach ($theads as $thead): ?>
        <?php if (false === $thead['hidden']): ?>
        <div class="flex items-center justify-center mb-6">
            <div class="md:w-1/3 min-w-[20%]">
                <label
                    class="block text-gray-500 font-bold md:text-right mb-1 md:mb-0 pr-4"
                    ><?=$thead['label'] ?></label
                >
            </div>
            <div class="md:w-2/3">
                <?php if ('text' === $thead['type']): ?>
                <input class="appearance-none border-2 rounded w-full py-2 px-4
                text-gray-700 leading-tight focus:outline-none focus:bg-white
                focus:border-purple-500" type="text" name="<?=$thead['name'] ?>"
                <?=$thead['disabled'] ? 'disabled' : '' ?>
                />
                <?php endif ?>
                <?php if ('textarea' === $thead['type']): ?>
                <textarea
                    rows="4"
                    class="appearance-none border-2 rounded w-full py-2 px-4 text-gray-700 leading-tight focus:outline-none focus:bg-white focus:border-purple-500"
                    name="<?=$thead['name'] ?>"
                ></textarea>
                <?php endif ?>
            </div>
        </div>
        <?php endif; ?>
        <?php endforeach; ?>
        <div class="flex items-center justify-center">
            <div class="md:w-1/3 min-w-[20%]"></div>
            <div class="md:w-2/3">
                <button
                    class="shadow bg-blue-500 hover:bg-blue-400 focus:shadow-outline focus:outline-none text-white font-bold py-2 px-4 rounded"
                    type="submit"
                >
                    Submit
                </button>
            </div>
        </div>
    </form>

    <script>
    const URL_API = location.origin + "/rest/V1/banner";
    const MODAL_OPTION = {
        type: "popup",
        responsive: true,
        innerScroll: true,
        buttons: [{
            class: "",
            click: function() {
                this.closeModal();
            },
        }, ],
    };
    require([
        "jquery",
        "mage/translate",
        "uiComponent",
        "ko",
        "Magento_Ui/js/modal/alert",
        "Magento_Ui/js/modal/confirm",
        "Magento_Ui/js/modal/modal",
    ], function($, $t, Component, ko, alertModal, confirmModal, modal) {
        "use strict";
        (function init() {
            $.ajaxSetup({
                contentType: "application/json;",
                headers: {
                    API_KEY: "<?=$block->getApiKey() ?>",
                },
                success: function(data) {
                    // do something before xhr
                },
                fail: function(error) {
                    console.error(error)
                    alertModal({
                        content: error.message,
                    });
                },
            });
        })($);
        $(document).ready(function($) {
            const MODAL = modal(MODAL_OPTION, $("#modal_form"));
            let action = "";
            $(document).on("click", ".show-modal[data-action]", function() {
                action = $(this).attr("data-action");
                if (action == "add") {
                    $("#modal_form")[0].reset();
                    $("#modal_form").modal("openModal");
                }
                if (action == "edit") {
                    const id = $(this).attr("data-id");
                    $(`#row-${id} [data-name]`)
                        .each((i, el) => {
                            const name = $(el).attr('data-name');
                            const value = $(el).attr('data-value');
                            $(`#modal_form [name="${name}"]`)?.val(value);
                        })

                    $("#modal_form").modal("openModal");
                }
                if (action === 'delete') {
                    confirmModal({
                        title: "Are you sure?",
                        // content: '',
                        actions: {
                            confirm: () => {
                                $.get(URL_API + '?method=delete&id=' + $(this).attr('data-id'))
                                    .then(_ => window.location.reload())
                            },

                            cancel: () => {
                                // do something choose "no"
                            },
                        }
                    })
                }
            });
            $(document).on("submit", "#modal_form", function(e) {
                e.preventDefault();
                if (action === "add") {
                    $.post(URL_API + "?method=create", $(this).serialize())
                        .then((res) => {
                            res.status ?
                                alertModal({
                                    content: "Added new record!",
                                    actions: {
                                        always: () => window.location.reload()
                                    }
                                }) :
                                alertModal({
                                    content: "Some errors: " + data.message,
                                });
                        })
                        .then(() => $("#modal_form").modal("closeModal"));
                }
                if (action === "edit") {
                    const id = $(this).find("[name=id").val();
                    $.post(
                            URL_API + "?method=update&id=" + id,
                            $("#modal_form").serialize()
                        )
                        .then((res) => {
                            res.status ?
                                alertModal({
                                    content: "Edited new record!",
                                    actions: {
                                        always: () => window.location.reload()
                                    }
                                }) :
                                alertModal({
                                    content: "Some errors: " + data.message,
                                });
                        })
                        .then(() => $("#modal_form").modal("closeModal"));
                }
            });
        });
    });
</script>
</body>
