<?php /* var_dump($permission); */ ?>
<?php (empty($permission) ? redirect(base_url("error404")) : ""); ?>
<?php if (!empty($this->app->is_can($permission, "view"))) { /* Can View */ ?>
    <!-- SweetAlert2 -->
    <link rel="stylesheet" href="<?php echo base_url(); ?>vendor/sweetalert2-theme-bootstrap-4/bootstrap-4.min.css">
    <!-- Toastr -->
    <link rel="stylesheet" href="<?php echo base_url(); ?>vendor/toastr/toastr.min.css">
    <!-- DataTables -->
    <link rel="stylesheet" href="<?php echo base_url(); ?>vendor/datatables-bs4/css/dataTables.bootstrap4.min.css">
    <link rel="stylesheet" href="<?php echo base_url(); ?>vendor/datatables-responsive/css/responsive.bootstrap4.min.css">
    <link rel="stylesheet" href="<?php echo base_url(); ?>vendor/datatables-buttons/css/buttons.bootstrap4.min.css">
    <link rel="stylesheet" href="<?php echo base_url(); ?>vendor/datatables-rowreorder/css/rowReorder.bootstrap4.min.css">
    <!-- Bootstrap-Switch  & Plugins -->
    <link rel="stylesheet" href="<?php echo base_url(); ?>vendor/bootstrap-switch/css/bootstrap3/bootstrap-switch.min.css">

    <style>
        .btn-xs {
            height: 22px;
            padding: 2px 5px;
            font-size: 12px;
            line-height: 1.5;
            /* If Placeholder of the input is moved up, rem/modify this. */
            border-radius: 3px;
        }

        .table td,
        .table th {

            font-size: 13px;
        }

        th.dt-center,
        td.dt-center {
            width: 5px;
            text-align: center;
        }

        th.dt-active,
        td.dt-active {
            width: 15px;
            text-align: center;
        }
    </style>

    <!-- ============================================================== -->
    <!-- Start Page Content -->
    <!-- ============================================================== -->

    <div class="col-12 pt-3">
        <h2>
            ทำรายการยื่น<?php echo $leavetype->leavetype_name; ?>
        </h2>
        <div class="m-t-40">
            <form id="leaveForm" action="<?php echo base_url(); ?>leave/form/save" method="POST" enctype="multipart/form-data" novalidate="novalidate">

                <input type="hidden" id="leave_qty" name="leave_qty" value="">

                <input type="hidden" name="leave_status" value="0">

                <input type="hidden" name="company_leavetype_id" value="<?php echo $leave->company_leavetype_id; ?>">

                <input type="hidden" id="per_round" value="<?php echo $leavetype->per_round; ?>">

                <input type="hidden" id="advance_notice_day" value="<?php echo $leavetype->advance_notice_day; ?>">

                <div class="row">
                    <div class="col-6 form-group <?php echo ($leavetype->num > 0 ? '' : 'd-none'); ?> ">
                        <div class="alert alert-warning alert-bordered">
                            <i class="ti-comment-alt"></i> วัน<?php echo $leavetype->leavetype_name; ?>ในปีนี้คงเหลือ <?php echo ($leave->num - $leave->leave_qty); ?> วัน
                        </div>
                    </div>
                    <div class="col-<?php echo ($leavetype->num > 0 ? '6' : '12'); ?>  form-group">
                        <div class="alert alert-warning alert-bordered">
                            จำนวนวันที่ลา <span class="badge badge-warning badge-circle m-r-5 m-b-5 leave-day">0</span> วัน
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-12 col-12 form-group">
                        <label>ช่วงเวลาการลา <span class="text-danger">*</span></label>
                        <div>
                            <label class="ui-radio ui-radio-primary ui-radio-inline">
                                <input type="radio" class="period_full" name="period" value="1 เต็มวัน" checked="checked">
                                <span class="input-span"></span>ลาเต็มวัน
                            </label>
                            <label class="ui-radio ui-radio-primary ui-radio-inline">
                                <input type="radio" class="period_half" name="period" value="0.5 ครึ่งวันเช้า">
                                <span class="input-span"></span>ลาครึ่งเช้า
                            </label>
                            <label class="ui-radio ui-radio-primary ui-radio-inline">
                                <input type="radio" name="period" class="period_half" value="0.5 ครึ่งวันบ่าย">
                                <span class="input-span"></span>ลาครึ่งบ่าย
                            </label>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-6 col-12 form-group">
                        <label>วันที่ลา <span class="text-danger">*</span></label>
                        <div class="input-group date start-date">
                            <div class="input-group-prepend">
                                <span class="input-group-text input-group-addon"><i class="fa fa-calendar"></i></span>
                            </div>
                            <input type="date" id="leave_from" name="leave_from" value="" class="form-control" autocomplete="off" required>
                        </div>
                    </div>
                    <div class="col-sm-6 col-12 form-group display-end-date ">
                        <label>ถึงวันที่</label>
                        <div class="input-group date end-date">
                            <div class="input-group-prepend">
                                <span class="input-group-text input-group-addon"><i class="fa fa-calendar"></i></span>
                            </div>
                            <input type="date" id="leave_to" name="leave_to" value="" class="form-control" autocomplete="off" placeholder="ใส่กรณีที่วันลามากกว่า 1 วัน" required>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-6 col-12 form-group">
                        <label>เบอร์โทรติดต่อ <span class="text-danger">*</span></label>
                        <div class="input-group date end-date">
                            <div class="input-group-prepend">
                                <span class="input-group-text input-group-addon"><i class="fa fa-phone"></i></span>
                            </div>
                            <input type="text" id="leave_tel" name="leave_tel" value="" class="form-control" autocomplete="off" placeholder="ใส่เบอร์ที่สามารถติดต่อได้ขณะวันที่ลา" required>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-12 col-12 form-group">
                        <label>ที่อยู่ (สามารถติดต่อได้) <span class="text-danger">*</span></label>
                        <textarea name="leave_address" cols="40" rows="3" value="" class="form-control" required></textarea>

                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-12 col-12 form-group">
                        <label>ลาเนื่องจาก <span class="text-danger">*</span></label>
                        <textarea name="leave_remark" cols="40" rows="3" value="" class="form-control" required></textarea>

                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-12 col-12 form-group">
                        <div class="input-group">
                            <div class="input-group-prepend">
                                <span class="input-group-text"><i class="fa fa-upload"></i></span>
                            </div>
                            <div class="custom-file">
                                <input type="file" class="custom-file-input" id="files" name="files">
                                <label class="custom-file-label">เลือกไฟล์</label>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-12 form-group text-right">
                        <a href="<?php echo base_url(); ?>leave/form/<?php echo $leavetype->leavetype_id; ?>" class="btn btn-default">ยกเลิก</a>
                        <button type="submit" class="btn btn-primary">บันทึก</button>
                    </div>
                </div>
            </form>
        </div>
    </div>


    <!-- jQuery -->
    <script src="<?php echo base_url(); ?>vendor/jquery/jquery.min.js"></script>
    <!-- jQuery UI 1.11.4 -->
    <script src="<?php echo base_url(); ?>vendor/jquery-ui/jquery-ui.min.js"></script>
    <!-- SweetAlert2 -->
    <script src="<?php echo base_url(); ?>vendor/sweetalert2/sweetalert2.min.js"></script>
    <!-- DataTables  & Plugins -->
    <script src="<?php echo base_url(); ?>vendor/datatables/jquery.dataTables.min.js"></script>
    <script src="<?php echo base_url(); ?>vendor/datatables-bs4/js/dataTables.bootstrap4.min.js"></script>
    <script src="<?php echo base_url(); ?>vendor/datatables-responsive/js/dataTables.responsive.min.js"></script>
    <script src="<?php echo base_url(); ?>vendor/datatables-responsive/js/responsive.bootstrap4.min.js"></script>
    <script src="<?php echo base_url(); ?>vendor/datatables-buttons/js/dataTables.buttons.min.js"></script>
    <script src="<?php echo base_url(); ?>vendor/datatables-buttons/js/buttons.bootstrap4.min.js"></script>
    <script src="<?php echo base_url(); ?>vendor/datatables-rowreorder/js/dataTables.rowReorder.min.js"></script>
    <script src="<?php echo base_url(); ?>vendor/datatables-rowreorder/js/rowReorder.bootstrap4.min.js"></script>
    <!-- Bootstrap-Switch  & Plugins -->
    <script src="<?php echo base_url(); ?>vendor/bootstrap-switch/js/bootstrap-switch.min.js"></script>
    <!-- jquery-validation -->
    <script src="<?php echo base_url(); ?>vendor/jquery-validation/jquery.validate.min.js"></script>
    <script src="<?php echo base_url(); ?>vendor/jquery-validation/additional-methods.min.js"></script>
    <!-- jquery-Moment -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

    <script type="text/javascript">
        $('.custom-file-input').on('change', function() {
            var fileName = document.getElementById("files").files[0].name;
            $(this).next('.custom-file-label').addClass("selected").html(fileName);
        })

        //ตรวจสอบวันลาเริ่มต้น
        var leaveDays = calculateBusinessDays($('#leave_to').val(), $('#leave_from').val());
        $('.leave-day').text(leaveDays);
        $('#leave_qty').val(leaveDays);

        $('#leaveForm').validate({
            rules: {
                division_name: {
                    required: true
                },
                division_email: {
                    required: true
                },
            },
            messages: {},
            errorElement: 'span',
            errorPlacement: function(error, element) {
                error.addClass('invalid-feedback');
                element.closest('.form-group').append(error);
            },
            highlight: function(element, errorClass, validClass) {
                $(element).addClass('is-invalid');
            },
            unhighlight: function(element, errorClass, validClass) {
                $(element).removeClass('is-invalid');
            }
        });

        $('.period_full').click(function() {
            $('.display-end-date').removeClass('d-none');
            $('#leave_to').val($('#leave_from').val());
            var leaveDays = calculateBusinessDays($('#leave_to').val(), $('#leave_from').val());
            $('.leave-day').text(leaveDays);
            $('#leave_qty').val(leaveDays);
        });

        $('.period_half').click(function() {
            $('.display-end-date').addClass('d-none');
            $('#leave_to').val($('#leave_from').val());
            var leaveDays = calculateBusinessDays($('#leave_to').val(), $('#leave_from').val());
            $('.leave-day').text('0.5');
            $('#leave_qty').val('0.5');
        });

        $('#leave_from, #leave_to').change(function() {
            var leaveDays = calculateBusinessDays($('#leave_to').val(), $('#leave_from').val());
            if (leaveDays < 0) {
                alert('ช่วงเวลาที่กำหนดไม่มีวันทำงาน');
                $('#leave_from').val('');
                $('#leave_to').val('');
                leaveDays = calculateBusinessDays($('#leave_to').val(), $('#leave_from').val());
            }


            let today = new Date(<?php date('Y-m-d'); ?>);
            let per_round = $('#per_round').val();
            let advance_notice_day = new Date();
            advance_notice_day.setDate(advance_notice_day.getDate() + parseInt(($('#advance_notice_day').val())))
            let from = new Date($('#leave_from').val());
            let to = new Date($('#leave_to').val());
            let leave_day = new Date($('.leave-day').text());

            /*
            if (from < today) {
                alert('ไม่สามารถทำการลาย้อนหลังได้');
            }
            */

            if (advance_notice_day > from && parseInt($('#advance_notice_day').val()) > 0) {
                alert('ต้องทำการแจ้งล่วงหน้าก่อนวันลา ' + parseInt($('#advance_notice_day').val()) + ' วัน');
                $('#leave_from').val('<?php date('Y-m-d'); ?>');
                $('#leave_to').val('<?php date('Y-m-d'); ?>');
                leaveDays = calculateBusinessDays($('#leave_from').val(), $('#leave_from').val());
            } else if (from > to && $('.period_full').prop('checked') == true) { // ถ้าวันเริ่มต้นมากกว่าวันสิ้นสุด
                alert('ช่วงเวลาที่กำหนดไม่ถูกต้องโปรดตรวจสอบอีกครั้ง');
                $('#leave_to').val($('#leave_from').val());
                leaveDays = calculateBusinessDays($('#leave_from').val(), $('#leave_from').val());
            } else if (leaveDays > per_round) {
                alert('จำนวนวันลาเกินกว่าที่กำหนด ' + per_round + ' วัน/ครั้ง');
                $('#leave_to').val($('#leave_from').val());
                leaveDays = calculateBusinessDays($('#leave_from').val(), $('#leave_from').val());
            }

            $('.leave-day').text(leaveDays);
            $('#leave_qty').val(leaveDays);

            //
            $('.period_half').each(function() {
                console.log($(this).prop('checked'));
                if ($(this).prop('checked')) {
                    $('#leave_to').val($('#leave_from').val());
                    $('.leave-day').text('0.5');
                    $('#leave_qty').val('0.5');
                }
            });

        });

        function calculateBusinessDays(firstDate, secondDate) {
            // EDIT : use of startOf
            let day1 = moment(firstDate).startOf('day');
            let day2 = moment(secondDate).startOf('day');
            // EDIT : start at 1
            let adjust = 1;

            /*
            if ((day1.dayOfYear() === day2.dayOfYear()) && (day1.year() === day2.year())) {
                return 0;
            }
            */

            if (day2.isBefore(day1)) {
                const temp = day1;
                day1 = day2;
                day2 = temp;
            }

            //Check if first date starts on weekends
            if (day1.day() === 6) { //Saturday
                //Move date to next week monday
                day1.day(8);
            } else if (day1.day() === 0) { //Sunday
                //Move date to current week monday
                day1.day(1);
            }

            //Check if second date starts on weekends
            if (day2.day() === 6) { //Saturday
                //Move date to current week friday
                day2.day(5);
            } else if (day2.day() === 0) { //Sunday
                //Move date to previous week friday
                day2.day(-2);
            }

            const day1Week = day1.week();
            let day2Week = day2.week();

            //Check if two dates are in different week of the year
            if (day1Week !== day2Week) {
                //Check if second date's year is different from first date's year
                if (day2Week < day1Week) {
                    day2Week += day1Week;
                }
                //Calculate adjust value to be substracted from difference between two dates
                // EDIT: add rather than assign (+= rather than =)
                adjust += -2 * (day2Week - day1Week);
            }
            const rt = isNaN(day2.diff(day1, 'days') + adjust) ? 0 : day2.diff(day1, 'days') + adjust;
            return rt;
        }
    </script>
<?php
} /* Can View */ ?>