<?php

/**search the modal div id, type the value, and replace what you want*/ ?>

<div class="form-group mas-col">
    <div class="col-sm-3 text-center mas-title"><label for="student_id">現任學生</label></div>
    <div class="col-sm-9 mas-box">
        <div id="student-id-container" style="display: flex; justify-content: space-between;">
            <label class="mas-text col-xs-8">
                <span class="text block">-- 請先搜尋學生 --</span>
            </label>
            <a class="btn btn-footer col-xs-2 modal_search_student"><i class="fa fa-search" style="margin-right: 5px;"></i>搜尋學生</a>
        </div>
    </div>
</div>

<div class="form-group mas-col">
    <div class="col-sm-3 text-center mas-title"><label for="grade">就讀年級</label></div>
    <div class="col-sm-9 mas-box">
        <div id="grade_containers" style="display: flex; justify-content: space-between;">
            <label class="mas-text col-xs-8">
                <span class="text block">-- 請先搜尋學生 --</span>
            </label>
        </div>
    </div>
</div>

<div class="form-group mas-col">
    <div class="col-sm-3 text-center mas-title"><label for="student_id">推薦學生</label></div>
    <div class="col-sm-9 mas-box">
        <div id="referrer_student-id-container" style="display: flex; justify-content: space-between;">
            <label class="mas-text col-xs-8">
                <span class="text block">-- 請搜尋推薦學生(如有) --</span>
            </label>
            <a class="btn btn-footer col-xs-2 modal_search_student" data-action="referrer"><i class="fa fa-search" style="margin-right: 5px;"></i>搜尋學生</a>
        </div>
    </div>
</div>

<input type="hidden" id="student_id" name="student_id" value="" />
<input type="hidden" id="referrer_student_id" name="referrer_student_id" value="" />

<div class="modal" id="modal" tabindex="-1" role="dialog" aria-labelledby="modal-editTitle" aria-hidden="true">
    <div class="modal-lg modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div id="search-student-container" class="form-container" style="padding: 0 7px;">
                <div class="modal-body">
                    <h5 class="modal-title">搜尋學生</h5>
                    <div class="wrapper">
                        <!-- <div class="sub-title">套用在</div>
                        <div>
                            <input type="radio" id="apply-current" name="apply" value="current" checked>
                            <label for="apply-current">目前時段</label>
                        </div>
                        <div>
                            <input type="radio" id="apply-future" name="apply" value="future">
                            <label for="apply-future">目前及往後時段</label>
                        </div> -->
                        <?php echo $content; ?>
                    </div>

                </div>
                <div class="modal-footer">
                    <a class="btn btn-footer modal-confirm">確定</a>
                    <a class="btn btn-footer modal-close" data-dismiss="modal">關閉</a>
                </div>
            </div>
            <div id="add-student-container" class="form-container" style="padding: 0 7px;" hidden>
                <div class="modal-body">
                    <h5 class="modal-title">創建學生</h5>
                    <div class="wrapper">
                        <div class="form-group mas-col">
                            <div class="col-sm-2 text-center mas-title"><label for="student_chi_name">中文姓名</label></div>
                            <div class="col-sm-10 text-center mas-title mas-box "><input id="student_chi_name" type="text" class="form-control mas-input" name="chi_name" value="" /></div>
                        </div>
                        <div class="form-group mas-col">
                            <div class="col-sm-2 text-center mas-title"><label for="student_remark">備註</label></div>
                            <div class="col-sm-10 mas-box"><textarea id="student_remark" class="form-control mas-textarea" rows="3" name="student_remark"></textarea></div>
                        </div>
                        <fieldset>
                            <div style="margin-bottom: 15px;">主要聯絡人 *</div>
                            <div class="form-group mas-col">
                                <div class="col-sm-2 text-center mas-title">
                                    <label for="student_content1_name">姓名</label>
                                </div>
                                <div class="col-sm-4 mas-box">
                                    <input type="text" id="student_content1_name" name="student_content1_name" class="form-control mas-input" placeholder="" value="">
                                    <p class="help-block red hidden">Error Msg</p>
                                </div>
                                <div class="col-sm-2 text-center mas-title">
                                    <label for="student_content1_relationship">親屬關係</label>
                                </div>
                                <div class="col-sm-4 mas-box">
                                    <select id="student_content1_relationship" name="student_content1_relationship" class="select mas-select" select2>
                                        <option value="0" selected="selected">--- 請選擇親屬關係 ---</option>
                                        <?php
                                        foreach ($relationship as $idx => $g) {
                                            echo sprintf('<option value="%s">%s</option>', $idx, $g);
                                        }
                                        ?>
                                    </select>
                                    <p class="help-block red hidden">Error Msg</p>
                                </div>
                            </div>
                            <div class="form-group mas-col">
                                <div class="col-sm-2 text-center mas-title">
                                    <label for="student_content1_phone">聯絡電話</label>
                                </div>
                                <div class="col-sm-4 mas-box">
                                    <input type="text" id="student_content1_phone" name="student_content1_phone" class="form-control mas-input" placeholder="" value="">
                                    <p class="help-block red hidden">Error Msg</p>
                                </div>
                                <div class="col-sm-2 text-center mas-title">
                                    <label for="student_content1_email">電郵</label>
                                </div>
                                <div class="col-sm-4 mas-box">
                                    <input type="email" id="student_content1_email" name="student_content1_email" class="form-control mas-input" placeholder="" value="">
                                    <p class="help-block red hidden">Error Msg</p>
                                </div>
                            </div>
                        </fieldset>
                        <div class="success-wrapper" hidden>創建學生成功</div>
                    </div>
                </div>
                <div class="modal-footer">
                    <a class="btn btn-footer" id="btnSearchStudent2">返回搜尋</a>
                    <a class="btn btn-footer modal-confirm">確定</a>
                    <a class="btn btn-footer modal-close" data-dismiss="modal">關閉</a>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    function translateGradeHandler(el) {
        function handler() {
            switch (grade) {
                case "1":
                    return "小一";
                case "2":
                    return "小二";
                    break;
                case "3":
                    return "小三";
                    break;
                case "4":
                    return "小四";
                    break;
                case "5":
                    return "小五";
                    break;
                case "6":
                    return "小六";
                    break;
                case "7":
                    return "中一";
                    break;
                case "8":
                    return "中二";
                    break;
                case "9":
                    return "中三";
                    break;
                case "10":
                    return "中四";
                    break;
                case "11":
                    return "中五";
                    break;
                case "12":
                    return "中六";
                    break;
                case "13":
                    return "K1";
                    break;
                case "14":
                    return "K2";
                    break;
                case "15":
                    return "K3";
                    break;
                default:
                    return "未有就讀年級資料";
                    break
            }
        }

        let grade = el.closest('tr').find('#grade').val();
        $('#grade_containers span').text(handler(grade));
    }

    function listingEventMonthHandler(eventId, studentId) {
        $.ajax({
            url: '/api/event/listing_selected_months',
            method: 'get',
            data: {
                event_id: eventId,
                student_id: studentId
            },
            dataType: 'json',
            success: function(response) {
                console.log('response:', response);
                if (response !== null) {
                    $('#selected-month-container').empty();
                    listing_month_date_close_handler();
                    console.log("Month:" + response);
                    $.each(response['data']['months'], function(i, v) {
                        console.log(v);
                        console.log(i);

                        const name = `selected_month[${i+1}]`;
                        const value = v;
                        $('#selected-month-container').append(`<div style="display: inline-block; margin-left: 12px;"><input type="checkbox" id="${name}" name="${name}" value="${value}" style="margin-right: 0;"/><label for="${name}" style="margin-left: 10px; cursor: pointer;">${value}</label></div>`);
                    });

                    // from parent view: enroll_mode_month
                    calculationReset('all');
                }
            },
            error: function(xhr, textStatus, errorThrown) {
                alert(xhr.responseJSON);
                // console.log();
                // console.log(textStatus);
                // console.log(errorThrown);
            }
        });
    }

    $('.modal_search_student').click(function(e) {
        $('#modal').modal('show').find('.modal-confirm').removeAttr('data-action');
        if ($(e.currentTarget).attr('data-action') == "referrer") {
            $('#modal .modal-confirm').attr('data-action', 'referrer');
        }

        $('#btnAddStudent').remove();
        $('<a class="btn btn-footer" id="btnAddStudent">創建學生</a>').insertAfter($('#btnSearchStudent'));

        $('#btnAddStudent').click(function() {
            goToCreateStudent();
        });
    });

    function initializeStudent(studentId, studentChiName, referrer) {
        if (referrer) {
            $('#referrer_student_id').val(studentId);
            $('#referrer_student-id-container span').text(studentChiName);
        } else {
            $('#student_id').val(studentId);
            $('#student-id-container span').text(studentChiName);

            listingEventMonthHandler(eventId, studentId);
        }
    }

    $('#search-student-container .modal-close').click(function() {});
    $('#search-student-container .modal-confirm').click(function() {
        const el = $('#modal input[name="student_code"]:checked');

        $('#btnAddStudent').remove();
        $('#modal').modal('hide');
        if (el.length > 0) {
            const student_id = el.prev().val();
            const hasReferrer = $(this).attr('data-action') == "referrer";
            initializeStudent(student_id, el.closest('tr').find('td').eq(2).find('span').text(), hasReferrer);
            if (!hasReferrer) translateGradeHandler(el);

            $('#student-id-container span').text();
        }
    });


    // Create Student Modal 
    $('#btnSearchStudent2').click(function() {
        $('#add-student-container').attr('hidden', true);
        $('#search-student-container').removeAttr('hidden');
    });

    function goToCreateStudent() {
        function createParent(studentNo) {
            $.ajax({
                url: '/api/createparentwithstudentno',
                method: 'post',
                data: {
                    student_no: studentNo
                },
                dataType: 'json',
                success: function(response) {},
                error: function(xhr, textStatus, errorThrown) {
                    alert(xhr.responseJSON);
                    // console.log();
                    // console.log(textStatus);
                    // console.log(errorThrown);
                }
            });
        }

        function goToCreateStudentSuccessfully() {
            $('#add-student-container .success-wrapper').removeAttr('hidden');

            $('#add-student-container').removeAttr('hidden');

            $('#add-student-container .modal-confirm').unbind('click').click(function() {
                $('#add-student-container .modal-close').trigger('click');
            });
        }

        $('#search-student-container').attr('hidden', true);
        $('#add-student-container .success-wrapper').attr('hidden', true);
        $('#add-student-container .submitted-success').attr('hidden', true);

        $('#add-student-container').removeAttr('hidden');

        $('#add-student-container .modal-confirm').click(function() {
            const hasReferrer = $(this).attr('data-action') == "referrer";

            const student_chi_name = $('#student_chi_name').val();
            const student_remark = $('#student_remark').val();
            const student_content1_name = $('#student_content1_name').val();
            const student_content1_relationship = $('#student_content1_relationship option:checked').val();
            const student_content1_phone = $('#student_content1_phone').val();
            const student_content1_email = $('#student_content1_email').val();

            if (!student_chi_name) {
                alert('請填寫學生中文姓名');
                return false;
            }
            if (!student_content1_name) {
                alert('請填寫主要聯絡人姓名');
                return false;
            }
            if (!student_content1_relationship) {
                alert('請填寫主要聯絡人親屬關係');
                return false;
            }
            if (!student_content1_phone) {
                alert('請填寫主要聯絡人聯絡電話');
                return false;
            }
            $.ajax({
                url: '/api/createstudent',
                method: 'POST',
                data: {
                    remark: student_remark,
                    chi_name: student_chi_name,
                    content1_name: student_content1_name,
                    content1_phone: student_content1_phone,
                    content1_email: student_content1_email,
                    content1_relationship: student_content1_relationship,
                    completed_information: 0
                },

                success: function(response) {
                    console.log('response:', response);
                    if (response !== null) {
                        var res = JSON.parse(response);
                        const newStudentId = res.data.result.id;
                        const newStudentNo = res.data.result.student_no;
                        // const data = response['data'];
                        //const newStudentId = data.result.id;
                        // const newStudentNo = data.result.student_no;


                        createParent(newStudentNo);
                        goToCreateStudentSuccessfully();

                        initializeStudent(newStudentId, student_chi_name, hasReferrer);
                    }
                },
                error: function(xhr, textStatus, errorThrown) {
                    alert(xhr.responseJSON);
                    // console.log();
                    console.log(xhr);
                    console.log(textStatus);
                    console.log(errorThrown);
                }
            });
        });
    }

    $('#add-student-container .modal-close').click(function() {
        goToCreateStudent();
    });
</script>