<link rel="stylesheet" type="text/css" href="/static/css/event-manage.css" />

<div id="page-event-manage">
    <div class="form-container">
        <form id="form" class="form-horizontal initialized" enctype="multipart/form-data" method="post" action="/event_pay">
            <div class="title">繳費</div>
            <?php if (isset($__alert_success_message)) : ?>
                <div class="alert alert-success" role="alert" style="text-align: left;"><?php echo $__alert_success_message; ?><button type="button" class="close" data-dismiss="alert" aria-label="Close"><a aria-hidden="true">×</a></button></div>
            <?php endif; ?>
            <?php if (isset($__alert_error_message)) : ?>
                <div class="alert alert-danger" role="alert" style="text-align: left;"><?php echo $__alert_error_message; ?><button type="button" class="close" data-dismiss="alert" aria-label="Close"><a aria-hidden="true">×</a></button></div>
            <?php endif; ?>
            <input type="hidden" name="enrollOrPay" value="pay" />
            <ul class="table-toolbar" style="text-align: left;">
                <li>
                    <a class="toolbar-element btn btn-default btn-create" href="/event">
                        <i class="fa fa-reply" style="margin-right: 8px;"></i>返回
                    </a>
                </li>
            </ul>
            <div class="form-group mas-col">
                <div class="col-sm-3 text-center mas-title"><label for="course_category_id">課程主分類 *</label></div>
                <div class="col-sm-9 mas-box">
                    <select id="course_category_id" style="width: 100%" select2>
                        <option value="-1">-- 請選擇課程主分類 --</option>
                        <?php foreach ($courseCategories as $k => $v) : ?>
                            <?php //TODO: id => student_id 
                            echo sprintf(
                                '<option value="%s"%s>%s</option>',
                                $v['id'],
                                $v['id'] == $course_category_id ? ' selected' : '',
                                $v['name']
                            );
                            ?>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <div class="form-group mas-col">
                <div class="col-sm-3 text-center mas-title"><label for="course_subcategory_id">課程次分類 *</label></div>
                <div class="col-sm-9 mas-box">
                    <select id="course_subcategory_id" name="course_subcategory_id" style="width: 100%" select2>
                        <option value="-1">-- 請選擇課程次分類 --</option>
                    </select>
                </div>
            </div>
            <div class="form-group mas-col">
                <div class="col-sm-3 text-center mas-title"><label for="course_id">課程名稱 *</label></div>
                <div class="col-sm-9 mas-box">
                    <select id="course_id" name="course_id" style="width: 100%" select2>
                        <option value="-1">-- 請選擇課程名稱 --</option>
                    </select>
                </div>
            </div>
            <div class="form-group mas-col">
                <div class="col-sm-3 text-center mas-title"><label for="event_id">課程時段 *</label></div>
                <div class="col-sm-9 mas-box">
                    <select id="event_id" name="event_id" style="width: 100%" select2>
                        <option value="-1">-- 請選擇課程時段 --</option>
                    </select>
                </div>
            </div>
            <?php echo $search_student; ?>
            <div id="enroll_mode"></div>
            <div class="form-group mas-col">
                <div class="col-sm-3 text-center mas-title">
                    <label for="first_date">開始上課日期 *</label>
                </div>
                <div class="col-sm-9 mas-box">
                    <div class="input-group clickable" datetimepicker format="YYYY-MM-DD">
                        <input class="form-control" type="text" id="first_date" name="first_date" value="<?php echo date('Y-m-d'); ?>">
                        <span class="input-group-addon">
                            <span class="glyphicon glyphicon-calendar"></span>
                        </span>
                    </div>
                </div>
            </div>
            <div class="form-group mas-col">
                <div class="col-sm-3 text-center mas-title">
                    <label for="enroll_date">報名日期</label>
                </div>
                <div class="col-sm-9 mas-box">
                    <div class="input-group clickable" datetimepicker format="YYYY-MM-DD">
                        <input class="form-control" type="text" name="enroll_date" value="<?php echo date('Y-m-d'); ?>">
                        <span class="input-group-addon">
                            <span class="glyphicon glyphicon-calendar"></span>
                        </span>
                    </div>
                </div>
            </div>
            <div class="form-group mas-col">
                <div class="col-sm-3 text-center mas-title">
                    <label for="remark">備註</label>
                </div>
                <div class="col-sm-9 mas-box">
                    <textarea id="remark" class="form-control mas-textarea" rows="3" name="remark" style="background-color: rgb(255, 255, 255);"></textarea>
                </div>
            </div>
            <div class="form-footer">
                <a class="btn btn-footer cancel" href="javascript:window.location.reload(true)">重設</a>
                <button class="btn btn-footer submit">儲存</button>
                <button id="submit-redirect" class="btn btn-footer submit">儲存後跳至學費</button>
            </div>
        </form>
    </div>
</div>
<script>
    let courseMode;
    let eventId;

    $(document).ready(function() {
        var li = $('#sidebar-menu li').filter(function(i) {
            return $(this).find('.menu-dropdown').find('.menu-text').text() === '時間表';
        });
        li.addClass('active open');
    });
	
	  const listing_month_date_close_handler = function() {
        $('#listing_month_dates_html').empty();
        $('.listing_month_dates').text('列出所有時段');
        listdates = false;
    }
	
    $('#course_category_id').on('change', function() {
        var course_category_id = $(this).val().trim();
        if (course_category_id != '-1') {
            $('#course_subcategory_id').empty().append('<option value="-1">-- 請選擇課程次分類 --</option>');
            $('#course_id').empty().append('<option value="-1">-- 請選擇課程名稱 --</option>');
            $.ajax({
                url: '/api/event/course_subcategory',
                method: 'get',
                data: {
                    course_category_id: course_category_id
                },
                dataType: 'json',
                success: function(response) {
                    if (response !== null) {
                        $.each(response['data']['result'], function(i, v) {
                            console.log(v);
                            $('#course_subcategory_id').append('<option value="' + v
                                .id + '">' + v
                                .name + '</option>');
                        });
                    }
                }
            });
        }
    });
    $('#course_subcategory_id').on('change', function() {
        var course_subcategory_id = $(this).val().trim();
        if (course_subcategory_id != '-1') {
            $('#course_id').empty().append('<option value="-1">-- 請選擇課程名稱 --</option>');
            $.ajax({
                url: '/api/event/course',
                method: 'get',
                data: {
                    course_category_id: $('#course_category_id').val().trim(),
                    course_subcategory_id: course_subcategory_id
                },
                dataType: 'json',
                success: function(response) {
                    if (response !== null) {
                        $.each(response['data']['result'], function(i, v) {
                            $('#course_id').append(`<option value="${v.id}">${v.name}</option>`);
                        });
                    }
                }
            });
        }
    });
    $('#course_id').on('change', function() {
        const course_id = $(this).val().trim();
        if (course_id != '-1') {
            $('#event_id').empty().append('<option value="-1">-- 請選擇課程時段 --</option>');
            $.ajax({
                url: '/api/event/select',
                method: 'get',
                data: {
                    course_id: course_id
                },
                dataType: 'json',
                success: function(response) {
                    //                    console.log('response:',response);
                    if (response !== null) {
                        $.each(response['data']['result'], function(i, v) {
                            $('#event_id').append(`<option value="${v.id}">${v.display_name}</option>`);
                        });
                    }
                }
            });
        }
    });
    $('#event_id').on('change', function() {
        eventId = $(this).val().trim();

        if (eventId != '-1') {
            $('#enroll_mode').empty();

            $.ajax({
                url: '/api/event/enroll_mode',
                method: 'get',
                data: {
                    event_id: eventId
                },
                dataType: 'json',
                success: function(response) {
                    if (response !== null) {
                        $('#enroll_mode').append(response['data']['result']);
                        if ($('#rate_sheet > option').length <= 1) {
                            alert('請先創建收費表');
                            window.location.reload();
                        };
                        // Datetimmepicker
                    }
                }
            });
        }
    });
	
	
	$('#form').keypress(
	function(event){
		if(event.which == "13"){
			event.preventDefault();
		}
	}
	);
	
	$(".wrapper .mas-input").keypress(
	function(event){
		if(event.which == "13")
		{
			$('#btnSearchStudent').trigger("click");
		}
	}
	);
	
	

    const formValidation = () => {
        if (courseMode == 'month') {
            const studentId = $('#student_id').find('option:selected').val();
            const studentChiName = $('#student_chi_name').val();
            const studentEngName = $('#student_eng_name').val();
            if (!studentId || studentId == -1) {
                if (!studentChiName || !studentEngName ) {
                    alert('請確定輸入: 現任學生。');
                    // alert('請確定輸入: 現任學生。\n或輸入: 中文姓名、英文名 (First Name)，英文姓 (Last Name)。');
                    return false;
                }
            }
            if (listdates) {
                let ids = [];
                $('#event-timeslot-table tr:not([data-skip]) .checkbox-check:checked').each(function() {
                    ids.push($(this).closest('tr').data('id'));
                });
                if (ids.length) {
                    $(`<input type="hidden" name="ids" value="${ids}"/>`).appendTo($('#form'));
                } else {
                    alert('請選擇至少一個時段！');
                    return false;
                }
            } else {
                if ($('.weekday-container [name="weekday-sun"]').is(":not(:checked)"))
                    $('[name="weekday-sun-time"]').val("");

                if ($('.weekday-container [name="weekday-mon"]').is(":not(:checked)"))
                    $('[name="weekday-sun-time"]').val("");

                if ($('.weekday-container [name="weekday-tue"]').is(":not(:checked)"))
                    $('[name="weekday-tue-time"]').val("");

                if ($('.weekday-container [name="weekday-wed"]').is(":not(:checked)"))
                    $('[name="weekday-wed-time"]').val("");

                if ($('.weekday-container [name="weekday-thu"]').is(":not(:checked)"))
                    $('[name="weekday-thu-time"]').val("");

                if ($('.weekday-container [name="weekday-fri"]').is(":not(:checked)"))
                    $('[name="weekday-fri-time"]').val("");

                if ($('.weekday-container [name="weekday-sat"]').is(":not(:checked)"))
                    $('[name="weekday-sat-time"]').val("");
            }
        } else if (courseMode == 'lesson') {
            let ids = [];
            let skipIds = [];
            const enrollDate = $('input[name="enroll_date"]').val();
            const firstDate = $('input[name="first_date"]').val();

            $('#event-timeslot-table tr:not([data-skip]) .checkbox-check:checked').each(function() {
                const timeslotEl = $(this).closest('tr');

                if (enrollDate <= timeslotEl.data('date') && firstDate <= timeslotEl.data('date')) {
                    ids.push(timeslotEl.data('id'));
                }
            });
            $('#event-timeslot-table tr[data-skip] .checkbox-check:checked').each(function() {
                skipIds.push($(this).closest('tr').data('id'));
            });
            let idsCount = ids.length;
            const rs = ids.filter(x => !skipIds.includes(x));
            console.log(123123);
            console.log(rs);
            console.log(ids);
            console.log(skipIds);

            if (ids.length > 0 && rs.length > 0) {
                $(`<input type="hidden" name="ids" value="${rs}"/>`).appendTo($('#form'));
                $(`<input type="hidden" name="skipIds" value="${skipIds}"/>`).appendTo($('#form'));
            } else {
                alert("沒有任何有效的課堂。\n 1.至少一個選擇時段的課堂日期必須大於開始上課日期及報名日期\n 2. 已勾選選擇時段的課堂日期");
                return false;
            }
        }
        return true;
    }

    $('.submit').click(e => {
        //courseMode = $('#course_mode').data('mode');
        return formValidation();
    });

    $('#submit-redirect').click(() => {
       // courseMode = $('#course_mode').data('mode');
        $(`<input type="hidden" name="submit_redirect" value="true"/>`).appendTo($('#form'));
    });
</script>