<div class="page-breadcrumbs">
    <ul class="breadcrumb">
        <li>
            <i class="fa fa-home"></i>
            <a href="#" style="color: #797979">主頁</a>
        </li>

        <li class='active' style='color:#ef4130'>時間表</li>
    </ul>
</div>

<div class="page-header position-relative">
    <div class="header-title">
        <h1>
            時段詳情
        </h1>
    </div>
    <!--Header Buttons-->
    <div class="header-buttons">
        <a class="sidebar-toggler" href="#">
            <i class="glyphicon glyphicon-resize-horizontal"></i>
        </a>
        <a class="refresh" id="refresh-toggler" href="#">
            <i class="glyphicon glyphicon-refresh"></i>
        </a>
        <a class="fullscreen" id="fullscreen-toggler" href="#">
            <i class="glyphicon glyphicon-fullscreen"></i>
        </a>
    </div>
</div>

<div class="content_no_padding">
    <div class="row no_margin">
        <a href="/backend/event/attendance?id=<?= $id ?>"><button class="col-1 btn btn-default">點名</button></a>
        <a href="/backend/event/makeup?id=<?= $id ?>"><button class="col-1 btn btn-default">調堂</button></a>
        <a href="/backend/event/add_new_student?id=<?= $id ?>"><button class="col-1 btn btn-default">加入學生</button></a>
        <a href="/backend/event/edit?id=<?= $id ?>"><button class="col-1 btn btn-default">編輯</button></a>
        <a href="/backend/event/delete?id=<?= $id?>"><button class="col-1 btn btn-default">刪除</button></a>
    </div>

    <div class="color_header_green">
        <span class="header_words"><?= $event_information['display_name'] ?></span>
        <!--<span class="header_words"><?= $course_title ?></span>-->
    </div>
    <div class="content_no_margin">
        <table class="partial_form_table">
            <thead></thead>
            <tbody>
                <tr>
                    <td class="partial_form_label">課程日期</td>
                    <td colspan="2"><input type='text' class="form-control" readonly value="<?= date("Y-m-d", $timeslot_information['startdate']) ?>"></td>
                    <td class="partial_form_label">課程時間</td>
                    <td colspan="2"><input type="text" class="form-control" readonly value="<?= $timeslot_information['starttime'] . " - " . $timeslot_information['endtime'] ?>"></td>
                </tr>
                <tr>
                    <td class="partial_form_label">課程名稱</td>
                    <td colspan="2"><input type='text' class="form-control" readonly value="<?= $event_information['display_name'] ?>"></td>
                    <td class="partial_form_label">授課導師</td>
                    <td colspan="2"><input type="text" class="form-control" readonly value="<?= $event_information['staff'] ?>"></td>
                </tr>
                <tr>
                    <td class="partial_form_label">授課地點</td>
                    <td colspan="5"><input type="text" class="form-control" readonly value="<?= $event_information['location'] ?>"></td>
                </tr>
                <tr>

                    <td colspan='6' style="border:1px solid black;padding:0px!important;">
                        <ul class="form-toolbar table-toolbar nobackground noborder" style="text-align: left;">

                            <li><a class="toolbar-element btn btn-default btn-update" attend="">報到</a></li>

                            <li><a class="toolbar-element btn btn-default btn-update" attend-leave="">報走</a></li>

                            <li><a class="toolbar-element btn btn-default btn-update" take-leave="">請假</a></li>

                            <li><a class="toolbar-element btn btn-default btn-update" absent="">沒有出席</a></li>

                        </ul>
                        <form method="post" action="/backend/event/attendace_update">
                        <table id="attendance" class="table table-bordered form_table">
                            <thead>
                                <tr>
                                    <th><input type="checkbox" id="select_all" class="checkbox-check-all"></th>
                                    <th>學員姓名</th>
                                    <th>報到時間</th>
                                    <th>報走時間</th>
                                    <th>請假日期時間</th>
                                    <th>缺席</th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody>
                                <!--  <tr>
                                    <td><input type="checkbox"></td>
                                    <td>123</td>
                                    <td>456</td>
                                    <td>789</td>
                                    <td>101112</td>
                                    <td>131415</td>
                                </tr> -->
                                <?php foreach ($enrollment_item as $student) { ?>
                                    <tr data-id="<?php echo $student['id'];?>">
                                        <td><input type="checkbox" class="checkbox-check"></td>
                                        <td><?= $student['chi_name'] ?></td>
                                        <td><?= $student['in_datetime']==""?"":date("d-m-Y H:i",$student['in_datetime']) ?></td>
                                        <td><?= $student['out_datetime']==""?"":date('d-m-Y H:i',$student['out_datetime']) ?></td>
                                        <td><?= $student['taken_leave_datetime']==""?"":date("d-m-Y H:i",$student['taken_leave_datetime']) ?></td>
                                        <td><?= $student['absent'] == 0 ? '' : "是" ?></td>
                                        <td></td>
                                        
                                    </tr>
                                <?php } ?>
                            </tbody>
                        </table>

                    </td>

                </tr>
                <tr>
                    <input type="hidden" name="event_id" value="<?=$event_information['id']?>">
                    <input type="hidden" name="timeslot_id" value="<?=$timeslot_information['id']?>">
                    <td colspan='2' style="padding-left:100px;"><button type="submit" class="btn green_button submit" style="background-color:rgba(121,201,66)!important;border:none!important;">確認</td>

                    <td colspan='3' style="padding-right:100px;"><button class="btn green_button" style="background-color:rgba(121,201,66)!important;border:none!important;">重設</td>
                            
                </tr>
            </tbody>
        </table>

    </div>
</div>

<script>
   $(document).ready(function() {

var li = $('#sidebar-menu li').filter(function(i) {

    return $(this).find('.menu-dropdown').find('.menu-text').text() === '時間表';

});

li.addClass('active open');

$(".checkbox-check-all").change(function() {

    if ($(this).is(":checked")) {

        $(".checkbox-check:checkbox").prop("checked", true);

    } else {

        $(".checkbox-check:checkbox").prop("checked", false);

    }

});

$(".widget-body table tbody tr").each(function(index, element) {

    if ($(element).data("txn_status") == "M") {

        const next_event_date = $(element).data("next_event_date");

        $(element).find("input").removeClass("checkbox-check").closest("td").append(

            '<div class="overlay"></div>');

        // const studentName = $(element).find("td:nth-child(2)").text();

        // $(element).find("td:nth-child(2)").html(

        //     `<span style="text-decoration:line-through;">${studentName}</span>`);

        $(element).find("td:nth-child(2)").append(

            '<span style="text-decoration: none !important; color: red; font-weight: 700;">（調至 ' +

            next_event_date + "）</span>");

        $(element).find(

            "td:nth-child(3), td:nth-child(4), td:nth-child(5), td:nth-child(6), td:nth-child(7)"

        ).text("");

    }

});

$(".widget-body table tbody tr").each((index, element) => {

    $(element).find("td:last-child").css('width', '34');

    console.log($(element).find("td:nth-child(3)").text());

    if ($(element).find("td:nth-child(3)").text() !== "") {

        $(element).find("td:last-child").html('<span class="attend-chop">到</span>');

    }

});

["attend", "attend-leave", "take-leave", "absent"].forEach(value => {

    const selector = `ul.form-toolbar a[${value}]`;

    $(selector).click(e => {

        if (ids.length === 0) {

            alert('請選擇最少一位學生!');

            return false;

        }

        const now = new Date();

        const datetime = moment(now).format("DD-MM-YYYY HH:mm");

        const date = moment(now).format("DD-MM-YYYY");

        const time = moment(now).format("HH:mm");

        $(".checkbox-check:checked").each((index, element) => {

            $(element).closest("tr").attr("mutated", true);

            switch (value) {

                case "attend":

                    $(element).closest("tr").find("td:nth-child(3)").html(

                        datetime);

                    $(element).closest("tr").find("td:last-child").html(

                        '<span class="attend-chop">到</span>');

                    break;

                case "attend-leave":

                    $(element).closest("tr").find("td:nth-child(4)").html(

                        datetime);

                    break;

                case "take-leave":

                    $(element).closest("tr").find("td:nth-child(5)").html(

                        datetime);

                    break;

                case "absent":

                    $(element).closest("tr").find("td:nth-child(6)").html("是");

                    break;

            }

        });

    });

});

if ($('#attendance[none]').length) {

    $('.submit').attr('disabled', 'disabled');

}

$('.submit').click(e => {

    $("#attendance tbody tr").each((index, element) => {

        const id = $(element).data("id");

        const inputNamePrefix = "item[" + id + "]";

        console.log('mutated');

        $("<input />").attr("type", "hidden").attr("name",

            `${inputNamePrefix}[in_datetime]`).attr("value", $(element).find(

            "td:nth-child(3)").text()).appendTo("form");

        $("<input />").attr("type", "hidden").attr("name",

            `${inputNamePrefix}[out_datetime]`).attr("value", $(element).find(

            "td:nth-child(4)").text()).appendTo("form");

        $("<input />").attr("type", "hidden").attr("name",

            `${inputNamePrefix}[taken_leave_datetime]`).attr("value", $(element)

            .find("td:nth-child(5)").text()).appendTo("form");

        $("<input />").attr("type", "hidden").attr("name", `${inputNamePrefix}[absent]`)

            .attr("value", $(element).find("td:nth-child(6)").text()).appendTo("form");

    });

    return validform();

});

});



function validform() {

var msg = '';

if (ids.length === 0) {

    msg += "請選擇至少一位學生!\n";

} else {

    var valid = [];

            $('#attendance tbody tr').each(function(i, e) {
            
                var emptytds = 0;

                var emptyabs = false;

                $(this).find('td').each(function(k, v) {
                
                    if ((k > 1 && k < 5) && ($(v).text().trim() === '')) {
                    
                        emptytds++;

                    } else {

                        if (k === 5 && $(v).find('span').text().trim() === '') {
                        
                            emptyabs = true;

                        }

                    }

                });

        valid[i] = !(emptytds === 3 && emptyabs);

    });

    var _valid = $.grep(valid, function(n, i) {

        return n === true;

    });

    if (_valid.length === 0) {
       
        msg += "請選擇 報到/報走/請假/沒有出席 任何一項\n";

    }

}

if (msg !== '') {

    alert(msg);

}

return msg === '';

}

var ids = [];

$(document).on('change', '.checkbox-check-all', function() {

if (this.checked) {

    $('#attendance tbody tr').each(function(i, e) {

        ids.push($(this).data('id'));

    });

} else {

    ids = [];

}

});



$(document).on('change', '.checkbox-check', function() {

var id = $(this).closest('td').closest('tr').data('id');

if (this.checked && ids.indexOf(id) === -1) {

    ids.push(id);

} else {

    var idx = ids.indexOf(id);

    if (idx > -1) {

        ids.splice(idx, 1);

    }

    $('.checkbox-check-all').prop('checked', false);

}

if (ids.length > 0) {

    $.each(ids, function(i, e) {

        if (e === id) {

            $(this).prop('checked', true);

        }

    });

}

});



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>