<style>
    table {
        border-collapse: collapse;
    }

    table,
    th,
    td {
        border: 1px solid black;
    }

    td,
    th {
        padding: .5em;
    }
</style>

<h3 class="text-left">優惠推廣</h3>
<?php if ($this->Permission_model->readonly($_controller)) : ?>
    <!--Readonly-->
    <table datatables_existing filter="promotion">
        <thead>
            <tr>
                <th>標題</th>
                <th>內容</th>
                <th>截止日期</th>
                <th>發佈日期</th>
                <th>發佈狀態</th>
                <th>推播狀態</th>
                <th>顯示主頁banner</th>
            </tr>
        </thead>
        <tbody>
            <?php
            foreach ($items as $_ => $item) {
                $showInBannerStatus = $item['show_in_banner'] == 1 ? '顯示' : '不顯示';
                $pushStatus = $item['push'] == 1 ? '有推播' : '沒有推播';
                $publishedStatus = $item['published'] >= 1 ? '已發佈' : '未發佈';
                $item['due_datetime'] = $item['due_datetime'] == '0000-00-00 00:00:00' ? '-' : explode(' ', $item['due_datetime'])[0];
                echo "<tr data-id=" . $item['id'] .  ">
                    <td>{$item['title']}</td>
                    <td>{$item['content']}</td>
                    <td>{$item['due_datetime']}</td>
                    <td>{$item['issued_date']}</td>
                    <td>$publishedStatus</td>
                    <td>$pushStatus</td>
                    <td>$showInBannerStatus</td>
                </tr>";
            }
            ?>
        </tbody>
    </table>
<?php else : ?>
    <table datatables_existing filter="promotion_sortable" <?php if ($this->Permission_model->can($_controller, 'add')) : ?>data-add="/promotion/add" sortable<?php endif; ?>>
        <thead>
            <tr>
                <th></th>
                <th>標題</th>
                <th>內容</th>
                <th>截止日期</th>
                <th>發佈日期</th>
                <th>發佈狀態</th>
                <th>推播狀態</th>
                <th>顯示主頁banner</th>
                <th>動作</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $_actions = '';
            if ($this->Permission_model->can($_controller, 'edit')) {
                $_actions .= "<a href='/promotion/edit?id={ID}" . "'>修改</a>";
            }
            if ($this->Permission_model->can($_controller, 'delete')) {
                $_actions .= "<a class='del' href='javascript:void(0);' onclick='javascript:deleteRecord(\"{ID}\");'>刪除</a>";
            }
            foreach ($items as $_ => $item) {
                $showInBannerStatus = $item['show_in_banner'] == 1 ? '顯示' : '不顯示';
                $pushStatus = $item['push'] == 1 ? '有推播' : '沒有推播';
                $publishedStatus = $item['published'] >= 1 ? '已發佈' : '未發佈';
                $item['due_datetime'] = $item['due_datetime'] == '0000-00-00 00:00:00' ? '-' : explode(' ', $item['due_datetime'])[0];

                $actions = $_actions;
                $actions = str_replace("{ID}", $item['id'], $actions);
                echo "<tr data-id=" . $item['id'] .  ">
                    <td class='sortable_td'><span hidden>{$item['sort_order']}</span><i class='fa fa-sort'></i></td>
                    <td>{$item['title']}</td>
                    <td>{$item['content']}</td>
                    <td>{$item['due_datetime']}</td>
                    <td>{$item['issued_date']}</td>
                    <td>$showInBannerStatus</td>
                    <td>$pushStatus</td>
                    <td>$publishedStatus</td>
                    <td>$actions</td>
                </tr>";
            }
            ?>
        </tbody>
    </table>
    <?php if ($this->Permission_model->can($_controller, 'add')) : ?>
        <!--Sortable Javascript-->
        <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js" integrity="sha256-0YPKAwZP7Mp3ALMRVB2i8GXeEndvCq3eSl/WsAl1Ryk=" crossorigin="anonymous"></script>
        <script>
            $("table.sortable tbody").each((_, el) => {
                const $el = $(el);
                $el.sortable({
                    "update": (event, ui) => {
                        console.log('mutated order position');
                        let array = [];

                        // Finding the starting record from pagination
                        // const min = parseInt($('.dataTables_info').html().match(/[0-9]-[0-9]/).split('-')[0]);
                        // console.log(min);
                        console.log($('.dataTables_info').text());
                        const paginationString = $('.dataTables_info').text();
                        const min = parseInt(paginationString.match(/[0-9]-[0-9]/)[0].split('-')[0]);
                        console.log(min);


                        $('tr', $el).each((_, element) => {
                            console.log(element);
                            const id = parseInt($(element).data('id'));
                            array.push({
                                id: id,
                                sort_order: $(element).index() + min
                            });
                        });

                        console.log(JSON.stringify(array));
                        $.post('/update_sort_order/promotion', JSON.stringify(array)).done(() => {
                            alert('儲存順序成功');
                            // const $destEl = $el.parent().prev();
                            // if ($destEl.hasClass('update_sort_order')) {
                            //     $destEl.text('儲存順序成功。');
                            // } else {
                            //     $('<div class="update_sort_order">儲存順序成功。</div>').after($destEl);
                            // }
                        });
                    }
                });
            });
        </script>
    <?php endif; ?>

    <?php if ($this->Permission_model->can($_controller, 'delete')) : ?>
        <!--Delete record Javascript-->
        <script>
            function deleteRecord(id) {
                var url = '/promotion/delete?id=' + id;
                //        alert('url:'+url);return;
                if (confirm('確認刪除記錄?')) {
                    $.ajax({
                        url: url,
                        method: 'get',
                        dataType: 'json',
                        success: function(response) {
                            if (response !== null) {
                                alert('刪除成功');
                                location.reload();
                            }
                        }
                    });
                }
            }
        </script>
    <?php endif; ?>
<?php endif; ?>