<link rel="stylesheet" type="text/css" href="/static/css/event-manage.css" />
<div id="page-event-manage">
    <?php /** $__pathname, $__eventId, $__timeslotId from controller, will then be used inside this partial*/ ?>
    <?php include(__DIR__ . '/partials/topbar.php'); ?>
    <div class="form-container">
        <form id="form" class="form-horizontal initialized" role="form" method="post" action="/event">
            <div class="title"><?php echo $title; ?></div>
            <ul class="table-toolbar" style="text-align: left;">
                <li>
                    <a class="toolbar-element btn btn-default btn-create" href="/event?date=<?php echo $date; ?>">
                        <i class="fa fa-reply" style="margin-right: 8px;"></i>返回
                    </a>
                </li>
            </ul>
            <div class="form-group mas-col2">
                <div class="col-sm-3 text-center mas-title2">
                    <label for="date">日期</label>
                </div>
                <div class="col-sm-9 mas-box">
                    <label class="mas-text">
                        <span class="text block" name="date"><?php echo $date_tc; ?></span>
                    </label>
                </div>
            </div>
            <div class="form-group mas-col2">
                <div class="col-sm-3 text-center mas-title2">
                    <label for="time">時間</label>
                </div>
                <div class="col-sm-9 mas-box">
                    <label class="mas-text">
                        <span class="text block" name="time"><?php echo $daterange; ?></span>
                    </label>
                </div>
            </div>
            <div class="form-group mas-col2">
                <div class="col-sm-3 text-center mas-title2">
                    <label for="category_name">主分類</label>
                </div>
                <div class="col-sm-9 mas-box">
                    <label class="mas-text">
                        <span class="text block" name="category_name"><?php echo $course_category_name; ?></span>
                    </label>
                </div>
            </div>
            <div class="form-group mas-col2">
                <div class="col-sm-3 text-center mas-title2">
                    <label for="subcategory_name">次分類</label>
                </div>
                <div class="col-sm-9 mas-box">
                    <label class="mas-text">
                        <span class="text block" name="subcategory_name"><?php echo $course_category_sub_name; ?></span>
                    </label>
                </div>
            </div>
            <div class="form-group mas-col2">
                <div class="col-sm-3 text-center mas-title2">
                    <label for="course_name">課程</label>
                </div>
                <div class="col-sm-9 mas-box">
                    <label class="mas-text"><span class="text block" name="course_name"><?php echo $course_name; ?></span></label>
                </div>
            </div>
            <div class="form-group mas-col2">
                <div class="col-sm-3 text-center mas-title2">
                    <label for="teacher_name">教師</label>
                </div>
                <div class="col-sm-9 mas-box">
                    <label class="mas-text"><span class="text block" name="teacher_name"><?php echo $teacher_name; ?></span></label>
                </div>
            </div>
            <div class="form-group mas-col2">
                <div class="col-sm-3 text-center mas-title2"><label for="room_name">課室</label></div>
                <div class="col-sm-9 mas-box">
                    <label class="mas-text">
                        <span class="text block" name="room_name"><?php echo $room_name; ?></span>
                    </label>
                </div>
            </div>
            <div class="form-group mas-col">
                <div class="col-sm-3 text-center mas-title"><label for="operation">操作</label></div>
                <div class="col-sm-9 mas-box">
                    <select id="operation" name="operation" style="width: 100%" select2>
                        <option value="in" selected="">報到</option>
                        <option value="out">報走</option>
                    </select>
                </div>
            </div>
            <div class="form-group mas-col">
                <div class="col-sm-3 text-center mas-title"><label for="qrcode">學生號碼</label></div>
                <div class="col-sm-9 text-center mas-title mas-box "><input id="qrcode" type="text" class="form-control mas-input" name="qrcode" value="" placeholder="請掃描二維碼" style="background-color: rgb(255, 255, 255);"></div>
            </div>
            <table class="display table dataTable no-footer" style="text-align: left;">
                <thead>
                    <tr>
                        <th>學生</th>
                        <th>報到時間</th>
                        <th>報走時間</th>
                        <th>請假日期時間</th>
                        <th>缺席</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($items) > 0) : ?>
                        <?php foreach ($items as $item) : ?>
                            <tr data-id="<?php echo $item['id']; ?>" data-txn_status="<?php echo $item['txn_status']; ?>">
                                <td><button class="student_chi_name" data-studentid="<?php echo $item['student_id']; ?>"><?php echo $item['student_chi_name']; ?></button></td>
                                <?php
                                if (!empty($item['absent']) && $item['absent']) {
                                    echo '<td></td><td></td><td></td><td><span>是</span></td>';
                                } elseif (!empty($item['taken_leave_datetime'])) {
                                    echo '<td></td><td></td><td><span>' . date('Y-m-d H:i', $item['taken_leave_datetime']) . '</span></td><td></td>';
                                } else {
                                    if (!empty($item['in_datetime'])) {
                                        echo '<td><span>' . date('Y-m-d H:i', $item['in_datetime']) . '</span></td>';
                                    } else {
                                        echo '<td></td>';
                                    }


                                    if (!empty($item['out_datetime'])) {
                                        echo '<td><span>' . date('Y-m-d H:i', $item['out_datetime']) . '</span></td>';
                                    } else {
                                        echo '<td></td>';
                                    }

                                    echo '<td></td><td></td>';
                                }
                                ?>
                                <td style="width: 34px;"></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else : ?>
                        <tr>
                            <td colspan="7" style="text-align:center;">沒有任何報名記錄。</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
            <div class="form-footer" style=" text-align: left; margin: 30px 0;">
                <button class="btn btn-footer submit" type="button" id="btnBack">返回</button>
            </div>
        </form>
    </div>
</div>
<script>
    <?php if (isset($eventId) && isset($timeslotId)) : ?>
        const eventId = <?php echo $eventId; ?>;
        const timeslotId = <?php echo $timeslotId; ?>;
    <?php endif; ?>
    <?php if (isset($_json)) : ?>
        const _json = <?php echo $_json; ?>;
    <?php endif; ?>
</script>
<script>
    function getRemoteData(remote_url, data, callback, callbackFail) {
        $.ajax({
            //async: false,
            //timeout: 30000, //最長等候回應時間
            type: "GET", //提交類型
            url: remote_url, //提交地址
            data: data, //提交內容
            dataType: 'json', //返回數據類型
            success: function(data) { //請求完成並成功
                if (data.success) {
                    alert(data.message);
                    callback(data.data);
                } else {
                    callbackFail(data);
                }
            },
            error: function(data) { //請求返回錯誤信息
                callbackFail(data);
            },
            beforeSend: function(XHR) { //请求開始前执行
            },
            complete: function(XHR, status) { //请求完成后最终执行
            }
        });
    }

    function operationSuccess(data) {
        const studentNo = data.student_no;
        switch ($('select[name="operation"] option:selected').val()) {
            case "in":
                window.location.reload();
                if ($(`table tr[data-id="${data.id}"]`).length === 0) {
                    $('table tbody').append(`<tr data-id="${data.id}"><td>${data.student_name}</td><td>${data.in_datetime}</td><td class="endTime"></td></tr>`);
                } else {
                    $(`table tbody tr [data-id="${data.id}"]`).empty().append(
                        `<td>${studentNo}</td><td>${data.student_name}</td><td>${data.in_datetime}</td><td class="endTime"></td></tr>`);
                }
                break;
            case "out":
                $(`table tr[data-id="${data.id}"]`).find('.endTime').text(data.out_datetime);
                break;
        }
    }

    function operationFail(data) {
        alert(data.message);
    }
    $(document).ready(function() {
        var li = $('#sidebar-menu li').filter(function(i) {
            return $(this).find('.menu-dropdown').find('.menu-text').text() === '時間表';
        });
        li.addClass('active open');

        function _get_current_url() {
            return window.location.href.split('#')[0];
        }

        function _get_course_id() {
            const pieces = _get_current_url().split('/');
            return pieces[pieces.length - 1];
        }

        function _selector_toolbar(callToAction) {
            return '.toolbar-element[' + callToAction + ']';
        }

        function _selector_input(inputName) {
            return 'input[name=' + inputName + ']';
        }

        function _selector_select(inputName) {
            return 'select[name=' + inputName + ']';
        }
        $('#form')
            .addClass('initialized')
            .removeClass('initializing noheight');
        $('#btnBack').on('click', function() {
            window.location.href = window.location.href.replace('qrcode', 'attendance');
        });
        $('input[name="qrcode"]').on('blur', function() {
            if ($(this).val() == "") {
                return;
            }
            var studentUrl = $(this).val();
            // Transform the string if only student no is typed
            if (studentUrl.indexOf('https://') === -1 && studentUrl.indexOf('http://') === -1) {
                var studentNo = studentUrl;
                var url = window.location.href
                var arr = url.split("/");
                if (window.location.port) {
                    studentUrl = `${arr[0]}//${window.location.hostname}:${window.location.port}/event/qrcode`;
                } else {
                    studentUrl = `${arr[0]}//${window.location.hostname}/event/qrcode`;
                }
            }
            var data = {
                eventId: "<?php echo $__eventId; ?>",
                timeslotId: "<?php echo $__timeslotId; ?>",
                action: $('select[name="operation"] option:selected').val(),
                studentNo: studentNo
            };
            getRemoteData(studentUrl, data, operationSuccess, operationFail);
        });
    });
    const buttonFormEditPageRedirect = (actionUrl, id) => {
        var newForm = $('<form>', {
            'action': actionUrl,
            'method': 'post',
        }).append($('<input>', {
            'name': 'id',
            'value': id,
            'type': 'hidden'
        }));
        $(document.body).append(newForm);
        newForm.submit();
    }
    $(document).ready(() => {
        $('button.student_chi_name').click((e) => {
            const _this = $(e.currentTarget);
            e.stopPropagation();

            $('#form').unbind('submit').submit(() => {
                return false;
            });
            buttonFormEditPageRedirect('/student/edit', _this.data('studentid'));
        });
    });
</script>
<style>
    button.student_chi_name {
        outline: none;
        border: none;
        background: transparent;
        color: #333333;
    }

    button.student_chi_name:hover {
        opacity: .6;
    }
</style>