<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;}
    .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">

            <h3><?php print CommonLanguage::getMessage('attendance_sheet'); ?></h3>
            <div id="alertdiv"></div>
            <div class="col-md-12 p-b-15">
                <div class="row">
                    <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 m-t-25'>
                            <button class='btn btn-success' id='search_attendance'><?php echo CommonLanguage::getMessage('search') ?></button>
                        </div>
                    </div>
                </div>
            </div>


            <div class="col-md-12" id='AttendanceSetting'>
                <div class="table-responsive">
                    <table class="table table-bordered" id='emp_attnd'>
                        <thead>
                            <tr>
                                <th class="text-center" style="width:10%"><?php echo CommonLanguage::getMessage('Date')?></th>
                                <th class="text-center" style="width:15%"><?php echo CommonLanguage::getMessage('attnd_manual')?></th>
                                <th class="text-center" style="width:15%"><?php echo CommonLanguage::getMessage('attnd_finger')?></th>
                                <th class="text-center" style="width:40%"><?php echo CommonLanguage::getMessage('attnd_sug')?></th>

                            </tr>    
                        </thead>
                        <tbody>

                        </tbody>

                    </table>

                </div>

            </div>

            <div class="col-md-12 p-t-10">
                <button class="btn btn-success pull-right" id='submitdata'><?php echo CommonLanguage::getMessage('Save') ?></button>
            </div>




        </div>
    </div>
</div>
</div>


<script>
    var emp_id, from_date, to_date, dep_id;
    var Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>,
            Required_Fields = <?php echo json_encode(CommonLanguage::getMessage('Required_Fields')); ?>,
            Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit')); ?>;
    $(function () {

        build_select2($('.department_id'), 'xhr/searchDepartment');
        build_select2($('.employee_select_id'), 'xhr/employeeSearch');
        $('#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")
        });









        $('#search_attendance').on('click', function () {
            emp_id = $('#employee_select_id').val();
            from_date = (window.startDate ? window.startDate : today);
            to_date = (window.endDate ? window.endDate : today);
            dep_id = $('#department_id').val();
            $.ajax({
                url: 'HRMAjax/returnComapreData?from_date=' + from_date + '&to_date=' + to_date + '&emp_id=' + emp_id + '&dep_id=' + dep_id,
                dataType: "JSON",
                complete: function (v1, v2) {

                    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;
                            row += '  <tr>' +
                                    '<td class="text-center" style="background:#ed9421 !important;color:#fff" colspan="4">' + emp_row.Employee_Name + '</td>' +
                                    '</tr>';
                            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 += '<tr class="AttendanceRowClass" emp-id =' + emp_id + ' attnd-date =' + dt + '><td class="text-center">' + dt + '<span class="fa fa-plus-circle" style="color: #4c0870 ;float:left;cursor: pointer;font-size: 16px;"></span></td>';
                                        //Manual Employee Attendance
                                        row += '<td class="text-center">';
                                        if (data_rows[2] != undefined) {
                                            for (var j in data_rows[2]) {
                                                var mnul_row = data_rows[2][j];
                                                if (j != 0)
                                                    row += '<br/>';
                                                row += '<div style="width:40%;display:inline-block;">' + (mnul_row['date_time_in'] == null ? '' : mnul_row['date_time_in'].split(' ')[1]) + '</div>';
                                                row += '<div style="width:20%;display:inline-block;text-align:center;"> <==> </div>';
                                                row += '<div style="width:40%;display:inline-block;">' + (mnul_row['date_time_out'] == null ? '' : mnul_row['date_time_out'].split(' ')[1]) + '</div>';
                                            }
                                        }
                                        row += '</td>';
                                        //FingePrint Excel Attendance
                                        row += '<td class="text-center">';
                                        if (data_rows[3] != undefined) {
                                            for (var j in data_rows[3]) {
                                                var fngr_row = data_rows[3][j];
                                                if (j != 0)
                                                    row += '<br/>';
                                                row += '<div style="width:40%;display:inline-block;">' + (fngr_row['date_time_in'] == null ? '' : fngr_row['date_time_in'].split(' ')[1]) + '</div>';
                                                row += '<div style="width:20%;display:inline-block;text-align:center;"> <==> </div>';
                                                row += '<div style="width:40%;display:inline-block;">' + (fngr_row['date_time_out'] == null ? '' : fngr_row['date_time_out'].split(' ')[1]) + '</div>';
                                            }
                                        }
                                        row += '</td>';
                                        //Final/Suggestion Attendance
                                        row += '<td class="sug_row">';
                                        if (data_rows[1] != undefined) {
                                            for (var j in data_rows[1]) {
                                                var sugs_row = data_rows[1][j];
                                                if (j != 0)
                                                    row += '<br/>';
                                                if (j == 'no_attendence')
                                                    row += '<div class="no_attendence row_no_attendence"><div style="text-align:center;width:20%;display:inline-block;">' + sugs_row + '</div></div>';
                                                else {
                                                    row += '<div class="sugg_attendence_row row_exist"><div style="width:20%;display:inline-block;"><input type="text" class="from_time form-control" value="' + (sugs_row['date_time_in'] == null ? '' : sugs_row['date_time_in'].split(' ')[1]) + '"/> </div>';
                                                    row += '<div style="width:10%;display:inline-block;text-align:center;"> <==> </div>';
                                                    row += '<div style="width:20%;display:inline-block;"><input type="text" class="to_time form-control" value="' + (sugs_row['date_time_out'] == null ? '' : sugs_row['date_time_out'].split(' ')[1]) + '"/></div><span class="fa fa-minus-circle" style="color: #ed9421; margin-right:5px;cursor: pointer;font-size: 16px;"></span></div>';

                                                }
                                            }
                                        }
                                        row += '</td>';
                                        //
                                        row += '</tr>';
                                    }
                                }
                            }
                        }
                    }
                    $('#emp_attnd tbody').html($(row));
                    initialize_date_time_picker()
                    $("#emp_attnd .AttendanceRowClass").on("click", " span.fa-plus-circle", function (e) {
                        var parent = $(this).closest('tr').find('.sug_row');

                        var row = '<div class="row_new sugg_attendence_row"><td><div style="width:20%;display:inline-block;"><input type="text" class="from_time form-control"/> </div>';
                        row += '<div style="width:10%;display:inline-block;text-align:center;"> <==> </div>';
                        row += '<div style="width:20%;display:inline-block;"><input type="text" class="to_time form-control"/></div>';
                        row += '<span class="fa fa-minus-circle" style="color: #ed9421; margin-right:5px;cursor: pointer;font-size: 16px;"></span></div></td>';
                        parent.append($(row));
                        initialize_date_time_picker();

                    });


                    $('.sug_row').on('click', " span.fa-minus-circle", function () {
                        $(this).closest('.sugg_attendence_row').empty().remove();
                    });
                }
            });

        });

    });



    function initialize_date_time_picker() {

        $('.to_time,.from_time').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('.sug_row').find('.no_attendence');

            var is_from_change = $(e.target).hasClass('from_time');
            if (is_from_change)
                $('.to_time').data("DateTimePicker").minDate(e.date);
            else
                $('.from_time').data("DateTimePicker").maxDate(e.date);
        });

    }


     $('#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,
            data_type: 1,
            

            attendance_sheet: []
        };

        $('.AttendanceRowClass .sugg_attendence_row').each(function () {
            var me = $(this);
            var parent = $(this).closest('.AttendanceRowClass');
            var data_row = {
                Employee_ID: parent.attr('emp-id'),
                Time_In: (me.find('.from_time').val() == '' ? '' : (parent.attr('attnd-date') + ' ' + me.find('.from_time').val())),
                Time_Out: (me.find('.to_time').val() == '' ? '' : (parent.attr('attnd-date') + ' ' + me.find('.to_time').val())),
                employee_note: '',
                data_type: 1
            };
            $(this).removeClass('row_error');
            if (me.find('.from_time').val() == '' || me.find('.to_time').val() == '') {
                me.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;
        }
        $.ajax({
            url: 'HRMAjax/insertAttForEmp',
            data: Data,
            type: 'POST',
            complete: function (v1, v2) {
                if (v2 == 'success' && v1.responseText == 'ok') {
                    $('#alertdiv').attr('class', ' alert alert-success').empty().html(Submitted_Successfully);
                } else {
                    $('#alertdiv').attr('class', ' alert alert-danger').empty().html(Failed_Submit);
                }
            }
        });

    });

</script>

