<style type="text/css">
    .emp_row{background:#4c0870;margin-top:20px;border:1px solid #000}
    .row_exist{background:lightsteelblue;border:1px solid #000}
    .row_new{background:whitesmoke;border:1px solid #000;}
    .row_no_attendence{background:#ccc;border:1px solid #000;}
    .row_error{border:4px solid #f00;}

    @media print{
        .form-control{
            border: 0;
            padding:0;
            overflow:visible;
        }
        .wrapper .panel-body .row > *{display:none;}
        #AttendanceSetting{display:block;}
        #AttendanceSetting .emp_row > div{text-align:center;font-size:24px;line-height:normal;background:#ccc;}
        #AttendanceSetting .AttendanceRowClass{padding:1px 7px !important;}
        #AttendanceSetting .submit-main-div{display:none;}
        #AttendanceSetting div.Setting{display:none;}
        #AttendanceSetting .select2-drop.select2-display-none{display:none;}
        .col-md-12 {width: 100%;}
        .col-md-11 {width: 91.66666667%}
        .col-md-10 {width: 83.33333333%}
        .col-md-9 {width: 75%}
        .col-md-8 {width: 66.66666667%}
        .col-md-7 {width: 58.33333333%}
        .col-md-6 {width: 50%}
        .col-md-5 {width: 41.66666667%}
        .col-md-4 {width: 33.33333333%}
        .col-md-3 {width: 25%}
        .col-md-2 {width: 16.66666667%}
        .col-md-1 {width: 8.33333333%}
        .col-md-1, .col-md-10, .col-md-11, .col-md-12, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9 {
            float: left;
        }
    }
</style>
<div class="wrapper">
    <div class="panel ">
        <div class="panel-body">
            <div class="row">
                <h3><?php print CommonLanguage::getMessage('add_emp_att_manual'); ?></h3>
                <div id="alertdiv"></div>
                <div class="col-md-12 form-group">
                    <div class="col-md-12">
                        <div class="col-md-3">
                            <label><?php echo CommonLanguage::getMessage('departments') ?></label>
                            <input type="hidden" id="department_id" class="full-width department_id" name="department_id" />
                        </div>
                        <div class="col-md-3">
                            <label><?php echo CommonLanguage::getMessage('employee_name') ?></label><span class="red-star">*</span>
                            <input type="hidden" id="employee_select_id" name="employee_select_id" class='full-width employee_select_id'/>
                        </div>
                        <div class="col-md-3  ">
                            <label><?php echo CommonLanguage::getMessage('Date') ?></label>
                            <input type="text" id="EmployeeDate" class="form-control EmployeeDate" name="EmployeeDate" />
                        </div>
                        <div class="col-md-2">
                            <label><?php echo CommonLanguage::getMessage('status') ?></label>
                            <select id="posted" class="full-width posted" name="posted" data-init-plugin="select2">
                                <option value="0"><?php echo CommonLanguage::getMessage('raw_data') ?></option>
                                <option value="1"><?php echo CommonLanguage::getMessage('posted') ?></option>
                                <option value="2"><?php echo CommonLanguage::getMessage('not_posted') ?></option>

                            </select>
                        </div>
                    </div>
                    <div class="col-md-12">         

                        <div class="col-md-3">
                            <label><?php echo CommonLanguage::getMessage('employee_location') ?></label>
                            <input type="hidden" id="emp_location_filter" class="full-width emp_location_filter" name="emp_location_filter" />
                        </div>
                        <div class="col-md-3">
                            <label><?php echo CommonLanguage::getMessage('attendance_location') ?></label>
                            <input type="hidden" id="att_location_filter" class="full-width att_location_filter" name="att_location_filter" />
                        </div>
                        <div class='col-md-2 '>
                            <label><?php echo CommonLanguage::getMessage('empty_check_types') ?></label>
                            <select id="check_type_empty" class="full-width" data-init-plugin="select2">
                                <option value="0"><?php echo CommonLanguage::getMessage('all') ?></option>
                                <option value="1"><?php echo CommonLanguage::getMessage('empty_check_in') ?></option>
                                <option value="2"><?php echo CommonLanguage::getMessage('empty_check_out') ?></option>
                                <option value="3"><?php echo CommonLanguage::getMessage('empty_both') ?></option>

                            </select>
                        </div>
                        <div class='col-md-2 m-t-25 pull-right'>
                            <button class='btn btn-success full-width' id='export_data'><?php echo CommonLanguage::getMessage('export') ?></button>
                        </div>
                        <div class='col-md-2 m-t-25 pull-right'>
                            <button class='btn btn-success full-width' id='search_attendance'><?php echo CommonLanguage::getMessage('search') ?></button>
                        </div>

                    </div>
                </div>
                <div style="color:white !important;" id="att-alert" class="alert alert-warning col-md-12 hidden" style="margin: 0px;"><?php echo CommonLanguage::getMessage('att_alert') ?></div>
                <div class="col-md-12" id='AttendanceSetting'>
                </div>
                <div class="col-md-12 p-t-10">
                    <button class="btn btn-success pull-right" disabled="disabled" id='submitdata'><?php echo CommonLanguage::getMessage('submit_all') ?></button>
                </div>
            </div>
            <?php echo Forms::ModalLoader('EmpAttManDisabler'); ?>
        </div>
    </div>
</div>
<script>
    var emp_id, from_date, to_date, dep_id, empty_type, emp_location_filter, att_location_filter;
    var Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>,
            Required_Fields = <?php echo json_encode(CommonLanguage::getMessage('Required_Fields')); ?>,
            leave_lang = <?php echo json_encode(CommonLanguage::getMessage('accrued_leave')); ?>,
            absence_lang = <?php echo json_encode(CommonLanguage::getMessage('absence')); ?>,
            nb_working_days = <?php echo json_encode(CommonLanguage::getMessage('working_days')); ?>,
            Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit')); ?>, start_date = <?php echo json_encode($from_date); ?>;
    var is_actual = <?php echo json_encode($is_actual); ?>;
    $(function () {
        build_select2($("#emp_location_filter,#att_location_filter"), "xhr/CommonSearch?col_id=Location_ID&col_name=Location_Name&table=tbl_employee_location")

        build_select2($('.department_id'), 'HRMAjax/searchDepartment');
        build_select2($('.employee_select_id'), 'xhr/employeeSearch?is_actual=' + is_actual + '&with_id=1', 1);
        //        build_select2($('.lcoation_id'), 'xhr/locationSearch');
        $('.to_time,.from_time').datetimepicker({format: 'YYYY-MM-DD HH:mm', useCurrent: false, extraFormats: ['DD-MM-YYYY']});
        $('#EmployeeDate').daterangepicker({locale: {
                format: 'YYYY-MM-DD',

            }, startDate: start_date,
            ranges: {
                'Today': [moment(), moment()],
                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                'This Month': [moment().startOf('month'), moment().endOf('month')],
                'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
            }
        }, function (start, end, label) {
            window.startDate = start.format("YYYY-MM-DD"),
                    window.endDate = end.format("YYYY-MM-DD")
        });
        $("#AttendanceSetting").on("click", " .Setting >.fa-plus-circle", function (e) {
            //            $(".Setting >.fa-minus-circle").css("display", "");
            var is_emp = $(this).hasClass('addFromEmployeeRow');
            var Parent = $(this).closest(is_emp ? ".emp_row" : ".AttendanceRowClass");
            var data_id = Parent.attr('data-id');
            var from = $(".emp_row[data-id=" + data_id + "]").attr("data-from");
            //, NewItem = Parent.clone(false).insertAfter(Parent);
            //            NewItem.find("input").val('');
            //            build_select2($('.employee_id'), 'xhr/employeeSearch');
            //            build_select2($('.lcoation_id'), 'xhr/locationSearch');
            var row = '';
            row += '<div class="col-md-12 p-t-10 p-b-10 AttendanceRowClass row_new" data-from="' + from + '" data-id="' + data_id + '">' +
                    //                    '<div class="col-md-3">' +
                    //                    '<input type="text"  name="date_time" value="" class="form-control date_time"/>' +
                    //                    '</div>' +
                    '<div class="col-md-3">' +
                    '<input type="text"  name="from_time" value="" class="form-control from_time"/>' +
                    '</div>' +
                    '<div class="col-md-3">' +
                    '<input type="text"  name="to_time" value="" class="form-control to_time"/>' +
                    '</div>' +
                    '<div class="col-md-3">' +
                    '<input type="hidden"  name="location_id"   class="full-width location_id"/>' +
                    '</div>' +
                    '<div class="col-md-2 Setting">' +
                    '<span class="fa fa-plus-circle" style="color: #4c0870 ;margin-left: 10px;cursor: pointer;font-size: 16px;"></span><span class="fa fa-minus-circle" style="color: #ed9421;margin-left: 5px;cursor: pointer;font-size: 16px;display:"none"  ></span>' +
                    '</div>' +
                    '</div>';
            //
            row = $(row).insertAfter(Parent);
            initialize_date_time_picker(row, 1);
            build_select2($("input.location_id", $(row)), "xhr/CommonSearch?col_id=Location_ID&col_name=Location_Name&table=tbl_employee_location")
        });
        $("#AttendanceSetting").on("click", ".Setting >.fa-minus-circle", function (e) {
            $(this).closest(".AttendanceRowClass").empty().remove();
            //            $("#AttendanceSetting .AttendanceRowClass").each(function () {
            //                $(".AttendanceRowClass .Setting>.fa-minus-circle", $(this).parent()).css({"display": $(".AttendanceRowClass .Setting", $(this).parent()).length <= 1 ? "none" : "inline-block"})
            //            });
        });

        $('#search_attendance').on('click', function () {
            $("#alertdiv").addClass('hidden');
            emp_id = $('#employee_select_id').val();
            from_date = (window.startDate ? window.startDate : start_date);
            to_date = (window.endDate ? window.endDate : today);
            dep_id = $('#department_id').val();
            empty_type = $("#check_type_empty").val();
            posted = $('#posted').val();
            emp_location_filter = $("#emp_location_filter").val();
            att_location_filter = $("#att_location_filter").val();
            $("#submitdata,.emp_submit").addClass("hidden")

//            if (empty_type != 0){
//                $("#submitdata").addClass("hidden")
//                $("#AttendanceSetting .emp_submit").addClass("hidden")
//            else
//                $("#submitdata,.emp_submit").removeClass("hidden")
            $.ajax({
                url: 'HRMAjax/returnAttForEmp?from_date=' + from_date + '&to_date=' + to_date + '&emp_id=' + emp_id + '&dep_id=' + dep_id + '&posted=' + posted + '&emp_location_filter=' + emp_location_filter + '&att_location_filter=' + att_location_filter + '&check_type_empty=' + empty_type,
                dataType: 'JSON',
                complete: function (v1, v2) {
                    if (v2 == 'success' && v1.responseJSON != 'error') {
                        var row = '';
                        var data = v1.responseJSON.data,
                                emp_arr = v1.responseJSON.emp_arr;
                        if (emp_arr != undefined && Object.keys(emp_arr).length) {
                            for (var i in emp_arr) {
                                var emp_row = emp_arr[i];
                                var emp_id = emp_row.Employee_ID;
                                var emp_html = '<div class="col-md-12 emp_row" data-id="' + emp_id + '" data-from="' + emp_row['srch_from_date'] + '" data-to="' + emp_row['srch_to_date'] + '">' +
                                        '<div style="color:white !important;" class="col-md-6 text-right">' + emp_row.Employee_Name + ' / ' + nb_working_days + ' : ' + emp_row.day_nb + '</div>' +
                                        '<div class="col-md-2 Setting"><span class="fa fa-plus-circle addFromEmployeeRow" style="color: #4c0870 ;margin-left: 10px;cursor: pointer;font-size: 16px;"></span>' +
                                        '<span class="fa fa-user m-l-10 openFrame" title="' + leave_lang + '" data-src="HRM/AccruedList?is_pop=1&is_new=1&emp_id=' + emp_id + '&emp_name=' + emp_row.Employee_Name + ' " style="color:#4c0870;cursor:pointer"></span>' +
                                        '<span class="fa fa-bars m-l-10 openFrame" title="' + absence_lang + '" data-src="HRM/AbsenceList?is_pop=1&is_new=1&emp_id=' + emp_id + '&emp_name=' + emp_row.Employee_Name + ' " style="color:#4c0870;cursor:pointer"></span></div>' +
                                        '</div>';
                                //
                                if (data != undefined && data[emp_id] != undefined && Object.keys(data[emp_id]).length) {
                                    for (var dt in data[emp_id]) {
                                        var data_rows = data[emp_id][dt];
                                        if (Object.keys(data_rows).length) {
                                            //
                                            row += emp_html;
                                            emp_html = '';
                                            //
                                            for (var j in data_rows) {
                                                var data_row = data_rows[j];
                                                var row_class = 'row_exist';
                                                if (data_row['is_auto'] != undefined)
                                                    row_class = 'row_new';
                                                if (j == 'no_attendence')
                                                    row_class = 'row_no_attendence';
                                                //
                                                row += '<div class="col-md-12 p-t-10 p-b-10 AttendanceRowClass ' + row_class + '" data-id="' + emp_id + '">';
                                                if (j == 'no_attendence') {
                                                    row += '<div class="col-md-3">' + dt + '</div>' +
                                                            '<div class="col-md-3">' + data_row + '</div>';
                                                } else {
                                                    row +=
                                                            //                                                            '<div class="col-md-3">' +
                                                            //                                                            '<input type="text"  name="date_time" ' + (row_class == 'row_exist' ? " readonly " : "") + ' value="' + dt + '" class="form-control date_time"/>' +
                                                            //                                                            '</div>' +
                                                            '<div class="col-md-3">' +
                                                            '<input type="text"  name="from_time" value="' + (data_row['date_time_in'] == null ? '' : data_row['date_time_in']) + '" class="form-control from_time"/>' +
                                                            '</div>' +
                                                            '<div class="col-md-3">' +
                                                            '<input type="text"  name="to_time" value="' + (data_row['date_time_out'] == null ? '' : data_row['date_time_out']) + '" class="form-control to_time"/>' +
                                                            '</div>' +
                                                            '<div class="col-md-3">' +
                                                            '<input type="hidden"  name="location_id"  value="' + (data_row['location_id'] == null ? '' : data_row['location_id']) + '" data-select-name="' + (data_row['location_name'] == undefined ? '' : data_row['location_name']) + '" class="full-width location_id"/>' +
                                                            '</div>';
                                                }
                                                row +=
                                                        '<div class="col-md-2 Setting">' +
                                                        '<span class="fa fa-plus-circle" style="color: #4c0870 ;margin-left: 10px;cursor: pointer;font-size: 16px;"></span>' +
                                                        (j == 'no_attendence' ? '' : '<span class="fa fa-minus-circle" style="color: #ed9421;margin-left: 5px;cursor: pointer;font-size: 16px;"  ></span>') +
                                                        '</div>' +
                                                        '</div>';
                                            }
                                        }
                                    }
                                } else {
                                    row += emp_html;
                                    emp_html = '';
                                }
                                row += '<div class="col-md-12 m-t-10 submit-main-div" data-id="' + emp_id + '" data-from="' + emp_row['srch_from_date'] + '" data-to="' + emp_row['srch_to_date'] + '">' +
                                        '<div class="col-md-2 pull-right"><button type="button" class="emp_submit btn btn-complete full-width">submit</button></div>' +
                                        '</div>';
                            }
                        }
                        if (row == '') {
                            $('#submitdata').attr('disabled', 'disabled');
                        } else
                            $('#submitdata').removeAttr('disabled');

                        row = $(row).appendTo($('#AttendanceSetting').empty());
                        initialize_date_time_picker(row);
                        build_select2($("input.location_id", $(row)), "xhr/CommonSearch?col_id=Location_ID&col_name=Location_Name&table=tbl_employee_location")
                        if (empty_type != 0) {
                            $("#submitdata,.emp_submit").addClass("hidden")
//                            $("#AttendanceSetting .emp_submit").addClass("hidden")
                        } else
                            $("#submitdata,.emp_submit").removeClass("hidden")
                    }
                    if ($("#posted").val() == 0) {
                        $('#att-alert').removeClass('hidden');
                    } else {
                        $('#att-alert').addClass("hidden")
                    }
                }
            });
        });
        $('#export_data').on('click', function () {
            $("#alertdiv").addClass('hidden');
            var tmp_emp_id = $('#employee_select_id').val();
            var tmp_from_date = (window.startDate ? window.startDate : today);
            var tmp_to_date = (window.endDate ? window.endDate : today);
            var tmp_dep_id = $('#department_id').val();
            var tmp_posted = $('#posted').val();
            var tmp_empty_type = $("#check_type_empty").val();
            $('#export_excel_iframe').remove();
            $("<iframe id='export_excel_iframe' style='display:none;' src='HRMAjax/exportAttForEmp?from_date=" + tmp_from_date + '&to_date=' + tmp_to_date + '&emp_id=' + tmp_emp_id + '&dep_id=' + tmp_dep_id + '&posted=' + tmp_posted + '&emp_location_filter=' + $("#emp_location_filter").val() + '&att_location_filter=' + $("#att_location_filter").val() + '&check_type_empty=' + tmp_empty_type + "'></iframe>").appendTo('body');
        });
    });
    function initialize_date_time_picker(Rows, flag) {
        $('.to_time,.from_time').datetimepicker({
            format: 'YYYY-MM-DD HH:mm'
        });
//            .on("dp.change", function (e) {
//            var Parent = $(this).closest('.AttendanceRowClass');
//             $('.to_time', Parent).data("DateTimePicker").minDate(e.date);
//        });
//        $('.to_time,.from_time').datetimepicker({
//            format: 'YYYY-MM-DD HH:mm'
//        }).on("dp.change", function (e) {
//            //        $('.to_time,.from_time', Rows).datetimepicker({useCurrent: false/*put it for min/max date bug See issue #1075*/, format: 'HH:mm'}).on("dp.change", function (e) {
//            var Parent = $(this).closest('.AttendanceRowClass');
//            var is_from_change = $(e.target).hasClass('from_time');
//            if (is_from_change)
//                $('.to_time', Parent).data("DateTimePicker").minDate(e.date);
//            else
//                $('.from_time', Parent).data("DateTimePicker").maxDate(e.date);
//        })
        if (flag == 1) {
            var my_date = (Rows.attr("data-from") == undefined || Rows.attr("data-from") == '') ? from_date : Rows.attr("data-from");
            $('.to_time,.from_time', Rows).val(my_date + ' 08:00');
        }
        $('.date_time', Rows).datetimepicker({format: 'YYYY-MM-DD', useCurrent: false, extraFormats: ['DD-MM-YYYY'], minDate: from_date + ' 00:00:00', maxDate: to_date + ' 23:59:59' /*, disabledDates:['2017-11-05','2017-11-04']*//*, daysOfWeekDisabled: [0] */});
    }
    $("#AttendanceSetting").on("click", ".emp_submit", function () {
        var is_empty = false;
        var employee_id = $(this).parents(".submit-main-div").attr("data-id");
        var Data = {
            from_date: from_date,
            to_date: to_date,
            emp_id: employee_id, //emp_id,
            dep_id: dep_id,
            emp_location_filter: emp_location_filter,
            att_location_filter: att_location_filter,
            attendance_sheet: [],
            emp_arr: [],
            del_arr: []
        };
//        $(".emp_row").each(function(){
        Data.del_arr.push({
            Employee_ID: employee_id,
            from_date: $(".emp_row[data-id=" + employee_id + "]").attr('data-from'),
            to_date: $(".emp_row[data-id=" + employee_id + "]").attr('data-to')
        })
//        })
        $(".AttendanceRowClass:not(.row_no_attendence)[data-id=" + employee_id + "]").each(function (e) {

            var me = $(this);
            Data.emp_arr.push(employee_id);
            var data_row = {
                Employee_ID: me.attr('data-id'),
                Time_In: (me.find('.from_time').val() == '' ? '' : (me.find('.from_time').val())),
                Time_Out: (me.find('.to_time').val() == '' ? '' : (me.find('.to_time').val())),
                location_id: me.find("input.location_id").val(),
                indx: e
            };
            $(this).removeClass('row_error');
            if (me.find('.from_time').val() == '' || me.find('.to_time').val() == '' || me.find('.from_time').val() > me.find('.to_time').val()) {
                $(this).addClass('row_error');
                is_empty = true;
            }
            Data.attendance_sheet.push(data_row);
        })
        if (is_empty) {
            $("#alertdiv").attr("class", "alert alert-danger").empty().html(Required_Fields);
            $('html, body').animate({
                scrollTop: ($('.AttendanceRowClass.row_error').first().offset().top - 60)
            }, 500);
            return false;
        }
        submit_data(Data)
    })
    //
    $('#submitdata').on('click', function () {
        var is_empty = false;
        var Data = {
            from_date: from_date,
            to_date: to_date,
            emp_id: emp_id,
            dep_id: dep_id,
            emp_location_filter: emp_location_filter,
            att_location_filter: att_location_filter,
            attendance_sheet: [],
            emp_arr: [],
            del_arr: []
        };
        $(".emp_row").each(function () {
            Data.del_arr.push({
                Employee_ID: $(this).attr('data-id'),
                from_date: $(this).attr('data-from'),
                to_date: $(this).attr('data-to')
            })
        })
        $('.AttendanceRowClass:not(.row_no_attendence)').each(function (e) {
            var me = $(this);
            Data.emp_arr.push(me.attr('data-id'));
            var data_row = {
                Employee_ID: me.attr('data-id'),
                Time_In: (me.find('.from_time').val() == '' ? '' : (me.find('.from_time').val())),
                Time_Out: (me.find('.to_time').val() == '' ? '' : (me.find('.to_time').val())),
                location_id: me.find("input.location_id").val(),
                indx: e
            };
            $(this).removeClass('row_error');
            if (me.find('.from_time').val() == '' || me.find('.to_time').val() == '' || me.find('.from_time').val() > me.find('.to_time').val()) {
                $(this).addClass('row_error');
                is_empty = true;
            }
            Data.attendance_sheet.push(data_row);
        });
        if (is_empty) {
            $("#alertdiv").attr("class", "alert alert-danger").empty().html(Required_Fields);
            $('html, body').animate({
                scrollTop: ($('.AttendanceRowClass.row_error').first().offset().top - 60)
            }, 500);
            return false;
        }
        submit_data(Data)
    });
    function submit_data(Data) {
        $.ajax({
            url: 'HRMAjax/insertAttForEmp',
            data: Data,
            type: 'POST',
            dataType: 'json',
            complete: function (v1, v2) {
                if (v2 == 'success' && v1.responseJSON == 'ok') {
                    $('#alertdiv').attr('class', ' alert alert-success').empty().html(Submitted_Successfully);
                } else {
                    if ('duplicate' in v1.responseJSON) {
                        $('.AttendanceRowClass:not(.row_no_attendence):eq(' + v1.responseJSON['duplicate'][0] + ')').addClass('row_error');
                        $('#alertdiv').attr('class', ' alert alert-danger').empty().html(v1.responseJSON['duplicate'][1]);
                    } else {
                        $('#alertdiv').attr('class', ' alert alert-danger').empty().html(v1.responseJSON);
                    }
                }
                $(document.body).animate({scrollTop: 0}, 800)
            }
        });
    }
</script>
