<style type="text/css">
    .min_hrs{background:#ed9421 !important;margin-top:20px;border:1px solid #000;color:#fff}
    .add_hrs{background:lightsteelblue !important;border:1px solid #000}
    .non_hrs{background:#ccc !important;border:1px solid #000;}
    .table thead tr >th{
        background-color: #4c0870 ;
        color:#fff;
    }
    .table thead tr th[class*='sorting_'] {
        color: #FFFFFF;
    }
</style>
<div class="wrapper">
    <div class="panel ">
        <div class="panel-body">
            <h5 class="bold"><?php print CommonLanguage::getMessage('attendance_report'); ?></h5>
            <div id="alertdiv"></div>
            <div class="row form-group">
                <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-2 m-t-25'>
                    <button class='btn btn-success' id='search_attendance'><?php echo CommonLanguage::getMessage('search') ?></button>
                </div>
            </div>
            <div class="row form-group">
                <div class="col-md-3 ">
                    <label><?php echo CommonLanguage::getMessage('type') ?></label>
                    <select id="shift_type" class="full-width " name="" data-init-plugin="select2">
                        <option value="0"><?php echo CommonLanguage::getMessage('fixed_shift') ?></option>
                        <option value="1"><?php echo CommonLanguage::getMessage('dynamic_week') ?></option>
                        <option value="2"><?php echo CommonLanguage::getMessage('dynamic_month') ?></option>
                    </select>
                </div>
                <div class="col-md-3 date-div month-div hidden">
                    <label><?php echo CommonLanguage::getMessage('month') ?></label>
                    <input class="month_year form-control" type="text" data-date-format="yyyy-mm" value=""  />
                </div>
                <div class=" week-div date-div  hidden">
                    <div class=" col-md-3">
                        <label><?php echo CommonLanguage::getMessage('start_date') ?></label>
                        <input class="from_date form-control" type="text"  />
                    </div>
                    <div class=" col-md-3">
                        <label><?php echo CommonLanguage::getMessage('end_date') ?></label>
                        <input class="to_date form-control" type="text"  readonly/>
                    </div>
                </div>
                <div class="col-md-3 range-div date-div ">
                    <label><?php echo CommonLanguage::getMessage('Date') ?></label>
                    <input type="text" id="EmployeeDate" class="form-control EmployeeDate" name="EmployeeDate" />
                </div>
            </div>
            <div class="row m-t-10">
                <div class="col-md-12 table-responsive">
                    <table class="table table-bordered" id="tableWithSearch">
                        <thead>
                            <tr>
                                <th class="text-center"><?php echo CommonLanguage::getMessage('employee_name') ?></th>
                                <th class="text-center"><?php echo CommonLanguage::getMessage('days_nb_wrk') ?></th>
                                <th class="text-center"><?php echo CommonLanguage::getMessage('total_absence') ?></th>
                                <th class="text-center"><?php echo CommonLanguage::getMessage('total_leave') ?></th>
                                <th class="text-center"><?php echo CommonLanguage::getMessage('must_work') ?></th>
                                <th class="text-center"><?php echo CommonLanguage::getMessage('real_work') ?></th>
                                <th class="text-center"><?php echo CommonLanguage::getMessage('overtime_hrs') ?></th>
                                <th class="text-center"><?php echo CommonLanguage::getMessage('diff_hrs') ?></th><th class="text-center"><?php echo CommonLanguage::getMessage('overtime') ?></th>
                                <th class="text-center"><?php echo CommonLanguage::getMessage('deduction') ?></th>
                                <th class="text-center"><?php echo CommonLanguage::getMessage('cumulative') ?></th>
                                <?php if (smc_session()['default_setting']['seperate_overtime_deduction_in_att_report'] == 0) { ?>
                                    <th class="text-center"><?php echo CommonLanguage::getMessage('overall_diff') ?><span class="fill_all_input"><i class="fa fa-pencil"></i></span></th>
                                <?php } else { ?>
                                    <th class="text-center"><?php echo CommonLanguage::getMessage('overall_overtime') ?><span class="fill_all_input_over"><i class="fa fa-pencil"></i></span></th>
                                    <th class="text-center"><?php echo CommonLanguage::getMessage('overall_deduction') ?><span class="fill_all_input_ded"><i class="fa fa-pencil"></i></span></th>

                                <?php } ?>
                                <th class="text-center"><?php echo CommonLanguage::getMessage('Action') ?></th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="row <?php echo $permissions->hasPermission('submit_overall_deduction') ? '' : 'hidden' ?>">
                <button class=" btn btn-success btn-cons m-b-10 pull-right " id="submit_deduction" style="padding-top: 10px;top: 20px;min-width:253px;" type="button">
                    <i class="pg-form"></i> <span class="bold"><?php print CommonLanguage::getMessage('Save'); ?></span></button>
                <?php if ($permissions->hasPermission('submit_cumulative_deduction')) { ?>
                    <button class=" btn btn-success btn-cons m-b-10 pull-right " id="submit_cum_deduction" style="padding-top: 10px;top: 20px;min-width:253px;" type="button">
                        <i class="pg-form"></i> <span class="bold"><?php print CommonLanguage::getMessage('submit_cumulative'); ?></span></button>
                <?php } ?>
            </div>
        </div>    
    </div>
</div>
<div class="modal fade" id="absence_leave_modal" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
    <div class="modal-dialog" >
        <div class="modal-content">
            <div class="modal-header clearfix text-left">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="pg-close fs-20"></i></button>
                <h4 class="modal-title text-center"></h4>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div id="col-md-12">
                        <div class="">
                            <table class="table table-hover demo-table-search full-width" id="absence_leave_table" >
                                <thead>
                                    <tr>
                                        <th class="text-center" style="width:7%" ><?php echo CommonLanguage::getMessage('type'); ?></th>
                                        <th class="text-center" style="width:7%" ><?php echo CommonLanguage::getMessage('from'); ?></th>
                                        <th class="text-center" style="width:7%" ><?php echo CommonLanguage::getMessage('to'); ?></th>
                                        <th class="text-center" style="width:10%" ><?php echo CommonLanguage::getMessage('nb_days'); ?></th>
                                        <!--<th class="text-center" style="width:10%" ><?php echo CommonLanguage::getMessage('Status'); ?></th>-->
                                    </tr>
                                </thead>
                                <tbody>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    var emp_id, from_date, to_date, dep_id, total = 0.0, total_wrk = 0.0, must_work = 0.0, real_work = 0.0,
            Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>,
            Required_Fields = <?php echo json_encode(CommonLanguage::getMessage('Required_Fields')); ?>,
            info_lang = <?php echo json_encode(CommonLanguage::getMessage('info')); ?>,
            Action = <?php echo json_encode(CommonLanguage::getMessage('Action')); ?>,
            Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit')); ?>,
            titel = <?php echo json_encode(CommonLanguage::getMessage('attendance_report')); ?>,
            choose_date = <?php echo json_encode(CommonLanguage::getMessage('choose_date')); ?>,
            auto_ded_lang = <?php echo json_encode(CommonLanguage::getMessage('auto_ded_lang')); ?>,
            cumulative_lang = <?php echo json_encode(CommonLanguage::getMessage('cumulative')); ?>,
            startDate =<?php echo json_encode($today); ?>, endDate =<?php echo json_encode($today); ?>,
            change_overall_perm =<?php echo json_encode($permissions->hasPermission('change_overall_diff')) ?>,
            error = <?php echo json_encode(CommonLanguage::getMessage('err_msg')); ?>,
            local_currency =<?php echo json_encode(smc_session()['local_currency']) ?>,
            seperate_ov_ded =<?php echo json_encode(smc_session()['default_setting']['seperate_overtime_deduction_in_att_report']) ?>,
            is_actual = <?php echo json_encode($is_actual); ?>, clear_msg = true;
    //   change_overall_diff
    $(function () {
        build_select2($('.department_id'), 'HRMAjax/searchDepartment');
        build_select2($('.employee_select_id'), 'xhr/employeeSearch?is_actual=' + is_actual);
        $('#EmployeeDate').daterangepicker({locale: {
                format: 'YYYY-MM-DD'
            }, 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");
        })
        $(".month_year").datepicker({autoclose: true,
            viewMode: "months",
            minViewMode: "months"})
        //        build_select2($('.Payment_Method'), 'xhr/accSearch?type=Payroll')
        $(".month_year").on("changeDate", function () {
            var date = new Date($(this).val() + '-01T12:00:00');
            var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
            window.startDate = $(this).val() + '-01';
            window.endDate = $(this).val() + '-' + lastDay;
            //            to_date: endDate,
            //            console.log(startDate + '==' + endDate)
        })
        $(".from_date,.to_date").datepicker({autoclose: true})
        $(".from_date").on("changeDate", function () {
            var date2 = $(this).datepicker('getDate', '+6d');
            date2.setDate(date2.getDate() + 6);
            $('.to_date').datepicker('setDate', date2);
            window.startDate = $(this).val()
            window.endDate = $('.to_date').val()
        })
        $("#shift_type").on("change", function () {
            $(".date-div").addClass("hidden")
            if ($(this).val() == 0) {
                $("#EmployeeDate").val(window.startDate + ' - ' + window.endDate)
                $(".range-div").removeClass("hidden")
            } else
            if ($(this).val() == 1) {
                $(".week-div").removeClass("hidden")
            } else
            if ($(this).val() == 2) {
                $(".month-div").removeClass("hidden")
            }
        })
        $(".fill_all_input,.fill_all_input_over,.fill_all_input_ded").on("click", function () {
            var rows = $("#tableWithSearch").dataTable().fnGetNodes(),
                    class_str = ($(this).hasClass('fill_all_input_over') ? 'overall_overtime' : ($(this).hasClass('fill_all_input_ded') ? 'overall_deduction' : 'overall_diff')),
                    attr_str = ($(this).hasClass('fill_all_input_over') ? 'data-overtime' : ($(this).hasClass('fill_all_input_ded') ? 'data-deduction' : 'data-diff'));

            for (var i = 0; i < rows.length; i++) {
                var myinput = $(rows[i]).find('.' + class_str);
                myinput.val(myinput.attr(attr_str))
            }
        });
        $("#tableWithSearch").on("click", "span.fill-input", function () {
            var input = $(this).parent("td").find("input.overall_diff");
            input.val(input.attr("data-diff"));
        });
        $("#tableWithSearch").on("click", "span.fill-input-ov", function () {
            var input = $(this).parent("td").find("input.overall_overtime");
            input.val(input.attr("data-overtime"));
        });
        $("#tableWithSearch").on("click", "span.fill-input-ded", function () {
            var input = $(this).parent("td").find("input.overall_deduction");
            input.val(input.attr("data-deduction"));
        });
        $('#search_attendance').on('click', function () {
            emp_id = $('#employee_select_id').val();
            if (clear_msg)
                $('#alertdiv').addClass("hidden");
            clear_msg = true;
            if (($("#shift_type").val() == 0 && (window.startDate == undefined || window.startDate == undefined))
                    || ($("#shift_type").val() == 1 && ($(".from_date").val() == '' || $(".to_date").val() == ''))
                    || ($("#shift_type").val() == 2 && $(".month_year").val() == '')) {
                $('#alertdiv').attr('class', ' alert alert-danger').empty().html(choose_date)
                return;
            }
            from_date = (window.startDate ? window.startDate : today);
            to_date = (window.endDate ? window.endDate : today);
            dep_id = $('#department_id').val();
            $.ajax({
                url: 'HRMAjax/attendanceReport?from_date=' + from_date + '&to_date=' + to_date + '&emp_id=' + emp_id + '&dep_id=' + dep_id + '&shift_type=' + $("#shift_type").val() + '&is_actual=' + is_actual,
                dataType: "JSON",
                complete: function (v1, v2) {
                    if (v2 == 'success' && v1.responseJSON != 'error') {
                        var row = '';
                        var data = v1.responseJSON.data;
                        if (data != undefined) {
                            for (var i in data) {
                                must_work = addCommas(parseFloat(data[i]['must_work']).toFixed(2));
                                real_work = addCommas(parseFloat(data[i]['real_work']).toFixed(2));
                                overtime = addCommas(parseFloat(data[i]['overtime']).toFixed(2));
                                var hrs_diff = (parseFloat(data[i]['must_work']) - parseFloat(data[i]['real_work'])),
                                        overall_deduction = (hrs_diff > 0 ? hrs_diff : 0) - parseFloat(data[i]['total_deduction'] || 0),
                                        overall_overtime = (hrs_diff < 0 ? Math.abs(hrs_diff) : 0) + parseFloat(data[i]['overtime'] || 0) - parseFloat(data[i]['total_overtime'] || 0);
                                if (overall_overtime < 0)    //in case if inserted overtime greater than real overtime
                                    overall_overtime = 0;
                                if (overall_deduction < 0)  //in case if inserted deduction greater than real deduction
                                    overall_deduction = 0;

                                total = addCommas(parseFloat(data[i]['real_work'] - data[i]['must_work'] + data[i]['overtime']).toFixed(2)),
                                        overall_diff = (parseFloat((data[i]['real_work'] || 0) - (data[i]['must_work'] || 0) - (data[i]['total_overtime'] || 0) + (data[i]['total_deduction'] || 0) + (data[i]['overtime'] || 0)));

                                row += '<tr>' +
                                        '<td>' + data[i]['emp_name'] + '</td>' +
                                        '<td>' + data[i]['days_no'] + '</td>' +
                                        '<td>' + data[i]['absence_days'] + '</td>' +
                                        '<td>' + data[i]['leave_days'] + '</td>' +
                                        '<td>' + must_work + '</td>' +
                                        '<td>' + real_work + '</td>' +
                                        '<td>' + overtime + /*(overtime > 0 ? '&nbsp;<i  class="overtime openFrame fa fa-plus-circle" data-src="HRM/addOvertime?is_pop=1&date=' + to_date + '&emp_id=' + i + '&emp_name=' + data[i]['emp_name'] + '&duration=' + Math.abs(overtime) + '"  type="button" style="color:#4c0870;margin-top:15px;margin-right:25px;cursor:pointer;"></i>' : '') + */' </td>' +
                                        '<td class="' + (total < 0 ? 'min_hrs' : (total == 0 ? 'non_hrs' : 'add_hrs')) + '">' + (total < 0 ? +(total) : (total == 0 ? total : '+ ' + (total))) + '</td>' +
                                        '<td>' + (parseFloat(data[i]['total_overtime']) || 0) + '</td>' +
                                        '<td>' + (parseFloat(data[i]['total_deduction']) || 0) + '</td>' +
                                        '<td>' + (parseFloat(data[i]['cumulative']) || 0) + '</td>';
                                if (seperate_ov_ded == 0)
                                    row += '<td><input type="number" class="form-control overall_diff" data-emp="' + i + '" ' + (change_overall_perm ? '' : 'readonly') + ' data-diff="' + (parseFloat(overall_diff).toFixed(2)) + '" value="0"/><span class="fill-input" style="cursor:pointer;"><i class="fa fa-pencil"></i></span></td>';
                                else {
                                    row += '<td><input type="number" min="0" step="any" class="form-control overall_overtime" data-emp="' + i + '" ' + (change_overall_perm ? '' : 'readonly') + ' data-overtime="' + (parseFloat(overall_overtime).toFixed(2)) + '" value="0"/><span class="fill-input-ov" style="cursor:pointer;"><i class="fa fa-pencil"></i></span></td>';
                                    row += '<td><input type="number" min="0" step="any" class="form-control overall_deduction" data-emp="' + i + '" ' + (change_overall_perm ? '' : 'readonly') + ' data-deduction="' + (parseFloat(overall_deduction).toFixed(2)) + '" value="0"/><span class="fill-input-ded" style="cursor:pointer;"><i class="fa fa-pencil"></i></span></td>';
                                }
                                //                                        '<td class="' + (total < 0 ? 'min_hrs' : (total == 0 ? 'non_hrs' : 'add_hrs')) + '">' + (total < 0 ? +(total * 60) : (total == 0 ? total : '+ ' + (total * 60))) + '</td>' +
                                row += '<td><div class="btn-group m-b-sm Action " data-id="' + i + '">' +
                                        '<button type="button" class="btn bg-success dropdown-toggle" data-toggle="dropdown" aria-expanded="true">' + Action + '<span class="caret"></span></button> ' +
                                        '<ul class="dropdown-menu" role="menu">' +
                                        '<li> <a  data-id="' + i + '" class=" data-info"> <i class="fa fa-trash" type="button"></i> ' + info_lang + '</a></li>';
                                if (seperate_ov_ded == 1) {
                                    row += '<li> <a  class="overtime openFrame" data-src="HRM/addOvertime' + (total < 0 ? '/ded' : '') + '?is_pop=1&date=' + to_date + '&emp_id=' + i + '&emp_name=' + data[i]['emp_name'] + '&duration=' + Math.abs(overall_diff) + '"> <i class="fa fa-pencil" type="button"></i> ' + auto_ded_lang + '</a></li>' +
                                            '<li> <a  class="overtime openFrame" data-src="HRM/addOvertime' + (total < 0 ? '/ded' : '') + '?is_pop=1&date=' + to_date + '&emp_id=' + i + '&emp_name=' + data[i]['emp_name'] + '&duration=' + Math.abs((parseFloat(data[i]['cumulative']) || 0)) + '"> <i class="fa fa-pencil" type="button"></i> ' + cumulative_lang + '</a></li>';
                                }
                                row += '</ul></div>' +
                                        //<button data-id="' + i + '"class="btn btn-success data-info">' + info_lang + '</button></td>' +
                                        '</tr>';
                            }
                            $('#tableWithSearch').DataTable().destroy();
                            $('#tableWithSearch tbody').html($(row));
                            RebuildDataTable(titel, [0, 1, 2, 3, 4], false, false, '#tableWithSearch', [], {
                                extra_columnDefs: [{"targets": [11, 12], "orderable": false}]
                            });
                        }
                    } else {
                        $('#alertdiv').attr('class', ' alert alert-danger').empty().html(error)
                    }
                }
            });
        });
        $("#frameModal button").on("click", function () {
            $('#search_attendance').trigger('click')
        })
        $("#tableWithSearch").on("click", ".data-info", function () {
            var data = {
                from_date: (window.startDate ? window.startDate : today),
                to_date: (window.endDate ? window.endDate : today),
                emp_id: $(this).attr("data-id")
            }
            $('#absence_leave_table').DataTable().destroy();
            $("#absence_leave_table tbody").empty()
            $.ajax({
                url: 'HRMAjax/absence_leave_list',
                data: data,
                complete: function (v1, v2) {
                    if (v2 == 'success') {
                        //                        console.log(v1.responseText)
                        $("#absence_leave_table tbody").html(v1.responseText)
                        RebuildDataTable(titel, [0, 1, 2, 3, 4], '', [], '#absence_leave_table');
                        $('#absence_leave_table').css("width", "100%")
                        $("#absence_leave_modal").modal("show")
                    }
                }
            })
        })
    });
    $("#submit_deduction,#submit_cum_deduction").on("click", function () {
        var is_cumulative = 0;
        if ($(this).attr("id") == "submit_cum_deduction") {
            is_cumulative = 1;
        }
        var data = {
            deductions: []
        }
        var rows = $("#tableWithSearch").dataTable().fnGetNodes();
        for (var i = 0; i < rows.length; i++) {
            var row = rows[i];
            if ($(row).find('.overall_diff').val() != '' && $(row).find('.overall_diff').val() != 0 && seperate_ov_ded == 0) {
                data.deductions.push({
                    hrs: $(row).find('.overall_diff').val(),
                    Employee_ID: $(row).find('.overall_diff').attr('data-emp'),
                    to_date: (window.endDate ? window.endDate : today),
                    is_actual: is_actual,
                    is_cumulative: is_cumulative
                })
            }
            if ($(row).find('.overall_overtime').val() != '' && $(row).find('.overall_overtime').val() != 0 && seperate_ov_ded == 1) {
                data.deductions.push({
                    hrs: $(row).find('.overall_overtime').val(),
                    Employee_ID: $(row).find('.overall_overtime').attr('data-emp'),
                    to_date: (window.endDate ? window.endDate : today),
                    is_actual: is_actual,
                    is_cumulative: is_cumulative
                })
            }
            if ($(row).find('.overall_deduction').val() != '' && $(row).find('.overall_deduction').val() != 0 && seperate_ov_ded == 1) {
                data.deductions.push({
                    hrs: ($(row).find('.overall_deduction').val()) * -1,
                    Employee_ID: $(row).find('.overall_deduction').attr('data-emp'),
                    to_date: (window.endDate ? window.endDate : today),
                    is_actual: is_actual,
                    is_cumulative: is_cumulative
                })
            }
        }
        if (data.deductions.length == 0) {
            $('#alertdiv').attr('class', ' alert alert-danger').empty().html(Required_Fields)
            $(document.body).animate({scrollTop: 0}, 800)
            return false;

        }
        $.ajax({
            url: 'HRMAjax/submit_multi_deduction',
            data: data,
            method: 'POST',
            complete: function (v1, v2) {
                if (v2 == 'success') {
                    if (v1.responseText == 'OK') {
                        $('#alertdiv').attr('class', ' alert alert-success').empty().html(Submitted_Successfully)
                        clear_msg = false;
                        $('#search_attendance').trigger("click")
                    } else {
                        $('#alertdiv').attr('class', ' alert alert-danger').empty().html(Failed_Submit)
                    }
                    $(document.body).animate({scrollTop: 0}, 800)
                }
            }
        })
    })
</script>