<style>
    .table thead tr >th{
        background-color:#4c0870;
        color:#fff;
        text-align: center;
    }
    #error_list_row thead tr>th{
        background-color:#ba1d1d;
        text-align: center !important;
    }
    .table tbody tr >td,.table tbody tr >td input{
        text-align: center;
    }
    .table thead tr th[class*='sorting_'] {
        color: #fff;
    }
    #InputFile{
        width:227px;
        color:#fff;
    }
    #InputFile > input{
        position:absolute;
        cursor:pointer;
        left:0px;
        top:0px;
        width:100%;
        height:100%;
        opacity:0.01;
    }
    .wrong{
        background:rgba(255, 0, 0, 0.05) !important;
    }
    .shift_left,.shift_right{
        line-height:2.5;
        cursor:pointer;
    }
    .shift_right{
        color:#4c0870;
    }
    .shift_left{
        color:#ba1d1d;
    }
</style>
<div class="container-fluid container-fixed-lg bg-white">
    <div class="panel panel-transparent">
        <div class="panel-heading">
            <div class="panel-title"><?php print CommonLanguage::getMessage('employeeAttendance'); ?></div>
            <div class="clearfix"></div>
        </div>
        <div class="panel-body">
            <div class="col-md-12" style="padding:5px">
                <div  id="alert_xls" style="margin-top:10px;"></div>

                <form method="post" enctype="multipart/form-data" id="Upload_Excel" onsubmit="return false">
                    <div class="row" style="display: flex;">
                        <div class=" col-md-3" style="border:2px solid #4c0870">
                            <div class="col-md-12"  style="padding:5px">    
                                <h4><?php print CommonLanguage::getMessage('Upload_Downloaded_File'); ?> </h4>
                                <label class="btn btn-success" id="InputFile" style="cursor:pointer;"><i class="fa fa-upload"></i> <?php print CommonLanguage::getMessage('Upload'); ?> <input type="file" onchange="window.NewCurrentFileUploadadd = event.target.files; ValidateForNewFile(this, '#InputFile')" name="Document_File_Name" value="Upload"></label>
                            </div>
                            <div class=" pull-right " style="padding:10px">
                                <button class="btn btn-success " id="UploadExcelSheet"><?php print CommonLanguage::getMessage('Save') ?></button>
                                <button  class="btn btn-default hidden"  id="CancelUpload"><?php print CommonLanguage::getMessage('Close'); ?></button>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="col-md-12">
                                <label><?php echo CommonLanguage::getMessage('att_template') ?></label>
                                <select id="template_id" class="full-width" data-init-plugin="select2">
                                    <?php foreach ($template as $temp) { ?>
                                        <option value="<?php echo $temp['template_id']; ?>" data-col='<?php echo $temp['template_columns']; ?>' data-hrs="<?php echo $temp['max_hrs_shift'] ?>"><?php echo $temp['template_name']; ?></option>
                                    <?php } ?>
                                </select>
                            </div>
                            <?php if ($permissions->hasPermission('activate_temp_att')) { ?>
                                <div class="col-md-12 m-t-10 p-l-0 p-r-5">
                                    <button class="btn btn-success full-width" id="get_temp_att"><?php echo CommonLanguage::getMessage('temp_att_sheet') ?></button>
                                </div>
                            <?php } ?>
                        </div>
                        <div class="col-md-5 temp_info" style="border:2px solid #4c0870;display:flex;">
                            <?php echo Forms::build_att_template_html($template[0]['template_columns']) ?>
                        </div>
                    </div>
                </form>
            </div>
            <div class="table table-responsive">
                <table class="table table-bordered table-hover demo-table-search" id="tableWithSearch">
                    <thead>
                        <tr>
                            <th class="text-center" style="width:10%" ><?php print CommonLanguage::getMessage('employee_name'); ?></th>
                            <th class="text-center" style="width:5%"><?php print CommonLanguage::getMessage('time_in'); ?></th>
                            <th class="text-center" style="width:5%"><?php print CommonLanguage::getMessage('time_out'); ?></th>
                            <th class="text-center" style="width:5%"><?php print CommonLanguage::getMessage('location'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                    </tbody>
                </table>
            </div>
            <div class='table table-responsive'>
                <table class="table table-bordered" id='error_list_row'>
                    <thead>
                        <tr>
                            <th><?php print CommonLanguage::getMessage('number') ?></th>
                            <th><?php print CommonLanguage::getMessage('problem') ?></th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
            <div class="col-md-12">
                <div class="col-md-2  pull-right">
                    <button class="btn btn-success btn-lg full-width" id="SaveExcel"> <?php echo CommonLanguage::getMessage('Save') ?></button>
                </div>
                <div class="col-md-2  ">
                    <button class="btn btn-success btn-lg full-width temp_save"  id="temp_save"> <?php echo CommonLanguage::getMessage('temp_save') ?></button>
                </div>
                <div class="col-md-2  ">
                    <button class="btn btn-success btn-lg full-width temp_save hidden"  id="edit_temp_save"> <?php echo CommonLanguage::getMessage('edit_temp_save') ?></button>
                </div>
            </div>

        </div>
    </div>
</div>
<div class="modal fade" id="temp_modal" data-backdrop="static" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="pg-close fs-20"></i></button>
                <h4 class="modal-title"><?php print CommonLanguage::getMessage('temp_save') ?></h4>
            </div>
            <div class="modal-body">
                <div class="row form-group">
                    <div class="col-md-12 m-t-10">
                        <label><?php echo CommonLanguage::getMessage('title') ?></label>
                        <input type="text" class="form-control" id="temp_title"/>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger Cancel" data-dismiss="modal"  ><?php print CommonLanguage::getMessage('Close') ?></button>
                <button type="button" class="btn btn-success width-auto" id="save_temp_data" ><?php print CommonLanguage::getMessage('Save') ?></button>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="temp_att_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="temp_att_list" >
                                <thead>
                                    <tr>
                                        <th class="text-center" ><?php echo CommonLanguage::getMessage('title'); ?></th>
                                        <th class="text-center" ><?php echo CommonLanguage::getMessage('time'); ?></th>
                                        <th class="text-center"  ><?php echo CommonLanguage::getMessage('Action'); ?></th>
                                    </tr>
                                </thead>
                                <tbody>
                                </tbody>

                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    var Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>,
            Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit')); ?>,
            Required_Fields = <?php echo json_encode(CommonLanguage::getMessage('Required_Fields')); ?>,
            emp_empty_alert = <?php echo json_encode(CommonLanguage::getMessage('emp_empty_alert')); ?>,
            loc_empty_alert = <?php echo json_encode(CommonLanguage::getMessage('loc_empty_alert')); ?>,
            time_empty_alert = <?php echo json_encode(CommonLanguage::getMessage('time_empty_alert')); ?>,
            time_out_in_empty_alert = <?php echo json_encode(CommonLanguage::getMessage('time_out_in_empty_alert')); ?>,
            alert_excel = <?php echo json_encode(CommonLanguage::getMessage('excel_type_err')); ?>,
            manual_add_sub_time_col = <?php echo json_encode($permissions->hasPermission('manual_add_sub_time_col')); ?>,
            required_location = <?php echo json_encode(smc_session()['default_setting']['attendace_import_required_location']); ?>,
            temp_id = 0, temp_title = '';
    //    emp_empty_alert loc_empty_alert time_empty_alert time_out_in_empty_alert
    $(function () {
        $("#CancelUpload").on("click", function () {
            $("#InputFile >.fa-check,#NewFilewarning2").hide();
            $("#InputFile >input").val('')
        });

        $("#template_id").on("change", function () {
            $.ajax({
                url: 'HRMAjax/build_att_template_html',
                data: {template: $("#template_id option:selected").attr("data-col")},
                complete: function (v1, v2) {
                    if (v2 == 'success') {
                        $(".temp_info").empty().html(v1.responseText)
                    }
                }
            })
        })
        $("#UploadExcelSheet").on("click", function () {
            $("#ValidationAlert").remove();
            var FileName = $.trim($("#InputFile > input").val())
            var FileType = FileName.substring(FileName.lastIndexOf("."));
            if (FileType == ".xlsx" || FileType == ".xls"/* || FileType == ".csv"*/) {
                var Data = new FormData(document.getElementById("Upload_Excel"));
                var columns = $("#template_id option:selected").attr("data-col"),
                        max_hrs_shift = $("#template_id option:selected").attr("data-hrs");
                Data.append("columns", columns);
                Data.append("max_hrs_shift", max_hrs_shift);
                $.ajax({
                    url: 'HRMAjax/importAttendanceSheet',
                    data: Data,
                    method: "POST",
                    processData: false,
                    contentType: false,
                    dataType: 'JSON',
                    complete: function (v1, v2) {
                        if (v2 == 'success') {
                            if (v1.responseJSON[0] == 'OK') {
                                var Data = v1.responseJSON[1];
                                $("#alert_xls").attr('class', 'alert alert-success').html(Submitted_Successfully);
                                var table_row = '';
                                var error_row = '';
                                if (Data.data.length) {
                                    var in_indx = 0, out_indx = 1, old_emp = 0;
                                    $(Data.data).each(function (i, v) {
                                        if (old_emp != v.emp_id) {
                                            in_indx = 0;
                                            out_indx = 1;
                                        }
                                        old_emp = v.emp_id
                                        var time_in = '', time_out = '';
                                        if (manual_add_sub_time_col) {
                                            time_in += '<span class="fa fa-minus-circle shift_left"></span>';
                                            time_out += '<span class="fa fa-minus-circle shift_left"></span>';
                                        }
                                        time_in += '<input type="text" class="form-control input_picker time_in time_in_picker" value="' + v.time_in + '"  data-indx="' + (in_indx) + '" data-emp="' + v.emp_id + '"/>';
                                        time_out += '<input type="text" class="form-control input_picker time_out time_out_picker" value="' + v.time_out + '" data-indx="' + (out_indx) + '" data-emp="' + v.emp_id + '"/>';
                                        if (manual_add_sub_time_col) {
                                            time_in += '<span class="fa fa-plus-circle shift_right"></span>';
                                            time_out += '<span class="fa fa-plus-circle shift_right"></span>';
                                        }
                                        table_row += '<tr data-row="' + v.row_nb + '" data-id="' + v.emp_id + '" location-id="' + v.location_id + '" ><td>' + Data.employee[v.emp_id] + '</td><td><div style="display:flex;">' + time_in + '</div></td><td><div style="display:flex;">' + time_out + '</div></td><td>' + (v.location_id == '' ? '' : Data.location[v.location_id]) + '</td></tr>';
                                        in_indx += 2;
                                        out_indx += 2;
                                    });
                                }
                                if (Object.keys(Data.error).length) {
                                    for (var key in Data.error)
                                        error_row += '<tr><td>' + key + ' </td><td>' + Data.error[key] + '</td></tr>';
                                }
                                $('#tableWithSearch tbody').html(table_row);
                                $('#error_list_row tbody').html(error_row);
                                $('.time_in_picker,.time_out_picker').datetimepicker({format: 'YYYY-MM-DD HH:mm', useCurrent: false, extraFormats: ['DD-MM-YYYY']});
                                setTimeout(function () {
                                    $("#alert_xls").addClass("hidden");
                                }, 2000);
                                $("#InputFile >input").val('');
                                $("#InputFile >.fa-check").hide();
                                $("#edit_temp_save").addClass("hidden")
                            } else {
                                $("#alert_xls").attr('class', 'alert alert-danger').html(v1.responseJSON);
                            }
                        }
                    }
                });
            } else {
                $("#alert_xls").attr('class', 'alert alert-danger').html(alert_excel)
                setTimeout(function () {
                    $("#alert_xls").addClass("hidden");
                }, 2000);
            }
        });
        $("#tableWithSearch").on("click", ".shift_left", function () {
            var emp_id = $(this).parents("td").find("input.input_picker").attr("data-emp"),
                    indx = parseInt($(this).parents("td").find("input.input_picker").attr("data-indx")) - 1;
            $("input[data-emp=" + emp_id + "]").filter(function (index) {
                return parseInt($(this).attr("data-indx")) > parseInt(indx);
            }).each(function () {
                var cur_indx = parseInt($(this).attr("data-indx"));
                $(this).val($("input[data-emp=" + emp_id + "][data-indx=" + (cur_indx + 1) + "]").val())
            })
            if ($("input[data-emp=" + emp_id + "]").eq(-2).val() == '' && $("input[data-emp=" + emp_id + "]").eq(-1).val() == '') {
                $("input[data-emp=" + emp_id + "]").eq(-2).parents("tr").remove()
            }
        })
        $("#tableWithSearch").on("click", ".shift_right", function () {
            var emp_id = $(this).parents("td").find("input.input_picker").attr("data-emp"),
                    indx = parseInt($(this).parents("td").find("input.input_picker").attr("data-indx"));
            if ($("input[data-emp=" + emp_id + "]").eq(-1).val() != '') {
                var tr = $("tr[data-id=" + emp_id + "]:last").clone(),
                        last_indx = parseInt($("tr[data-id=" + emp_id + "]:last input.time_out").attr("data-indx"));
                tr.insertAfter($("tr[data-id=" + emp_id + "]:last"))
                tr.attr("data-row", "")
                $("input.time_in", tr).val('').attr("data-indx", (last_indx + 1))
                $("input.time_out", tr).val('').attr("data-indx", (last_indx + 2))

            }
            $($("input[data-emp=" + emp_id + "]").filter(function (index) {
                return parseInt($(this).attr("data-indx")) > parseInt(indx);
            }).get().reverse()).each(function () {
                var cur_indx = parseInt($(this).attr("data-indx"));
                $(this).val($("input[data-emp=" + emp_id + "][data-indx=" + (cur_indx - 1) + "]").val())
            })
            $(this).parents("td").find('input').val('')
//        if ($("input[data-emp=" + emp_id + "]").eq(-2).val() == '' && $("input[data-emp=" + emp_id + "]").eq(-1).val() == '') {
//            $("input[data-emp=" + emp_id + "]").eq(-2).parents("tr").remove()
//        }
        })

        $('#SaveExcel').on('click', function () {
            var is_empty = false;
            var Data = {
                attendance_sheet: []
            };
            var crnt_row;
            $("#tableWithSearch tbody tr td.wrong").removeClass("wrong")
            $("#tableWithSearch tbody tr").each(function (e) {
                crnt_row = $(this);
                var data_row = {
                    Employee_ID: crnt_row.attr('data-id'),
                    Location_ID: crnt_row.attr('location-id'),
                    Time_In: crnt_row.find('.time_in').val(),
                    Time_Out: crnt_row.find('.time_out').val(),
                    tr_index: crnt_row.attr("data-row")
                };
                if (data_row.Employee_ID == '') {
                    $("#alert_xls").attr("class", "alert alert-danger").empty().html(emp_empty_alert);
                    $("td", crnt_row).addClass("wrong")
                    is_empty = true;
//                    return false;
                }
                if (data_row.Location_ID == '' && required_location == 1) {
                    $("#alert_xls").attr("class", "alert alert-danger").empty().html(loc_empty_alert);
                    $("td", crnt_row).addClass("wrong")
                    is_empty = true;
//                    return false;
                }
                if (data_row.Time_In == '' || data_row.Time_Out == '') {
                    //                alert()
                    $("#alert_xls").attr("class", "alert alert-danger").empty().html(time_empty_alert);
                    $("td", crnt_row).addClass("wrong")
                    is_empty = true;
//                    return false;
                }
                if (data_row.Time_Out <= data_row.Time_In) {
                    $("#alert_xls").attr("class", "alert alert-danger").empty().html(time_out_in_empty_alert);
                    $("td", crnt_row).addClass("wrong")
                    is_empty = true;
//                    return false;
                }
                Data.attendance_sheet.push(data_row);
            });
            if (is_empty) {
                $('html, body').animate({
                    scrollTop: ($("#tableWithSearch tbody td.wrong").first().offset().top - 66)
                }, 500);
//                $("td", crnt_row).addClass("wrong")
                return false;
            }
            $.ajax({
                url: 'HRMAjax/insertAttendanceSheet',
                data: Data,
                type: 'POST',
                dataType: 'json',
                complete: function (v1, v2) {
                    if (v2 == 'success' && v1.responseJSON == 'ok') {
                        $("#alert_xls").attr("class", "alert alert-success").empty().html(Submitted_Successfully);
                        setTimeout(function () {
                            $("#alert_xls").addClass("hidden");
                        }, 4000);
                        $('#SaveExcel').attr('disabled', 'disabled');
                        $(document.body).animate({scrollTop: 0}, 800)
                    } else {
                        if (v1.responseJSON.length > 0) {
                            var error_row = '';
                            if (v1.responseJSON.length) {
                                for (var key in v1.responseJSON) {
                                    error_row += '<tr><td>' + v1.responseJSON[key][0] + ' </td><td>' + v1.responseJSON[key][1] + '</td></tr>';
                                    $("#tableWithSearch tr[data-row=" + v1.responseJSON[key][0] + "] td").addClass("wrong")
//                                    console.log("#tableWithSearch tr[data-row=" + v1.responseJSON[key][0] + "] td")
                                }
//                                console.log()
                                $('html, body').animate({
                                    scrollTop: ($("#tableWithSearch tbody td.wrong").first().offset().top - 66)
                                }, 500);
                            }

                            $('#error_list_row tbody').html(error_row);
                        } else {
                            $("#alert_xls").attr("class", "alert alert-danger").empty().html(Failed_Submit);
                            $(document.body).animate({scrollTop: 0}, 800)
                        }
                    }

                }
            });
        });
        $("#temp_save").on("click", function () {
            temp_id = 0;
            if ($("#tableWithSearch tbody tr").length > 0)
                $("#temp_modal").modal("show")
        })
        $("#edit_temp_save").on("click", function () {
            $("#temp_title").val(temp_title)
            if ($("#tableWithSearch tbody tr").length > 0)
                $("#temp_modal").modal("show")
        })
        $("#save_temp_data").on("click", function () {
            var data = {
                temp_id: temp_id,
                title: $("#temp_title").val(),
                att: []
            };
//            console.log(data)
//            return;
            $("#tableWithSearch tbody tr").each(function () {
                data.att.push({
                    data_row: $(this).attr("data-row"),
                    data_id: $(this).attr("data-id"),
                    loc_id: $(this).attr("location-id"),
                    emp_name: $(this).find("td:eq(0)").text(),
                    time_in: $(this).find("input.time_in").val(),
                    time_in_indx: $(this).find("input.time_in").attr("data-indx"),
                    time_out: $(this).find("input.time_out").val(),
                    time_out_indx: $(this).find("input.time_out").attr("data-indx"),
                    loc_name: $(this).find("td:eq(3)").text()
                })
            })
            $.ajax({
                url: 'HRMAjax/save_temp_att_data',
                data: data,
                type: 'POST',
                complete: function (v1, v2) {
                    if (v2 == 'success' && v1.responseText == 'OK')
                        toastr.success('<?php echo CommonLanguage::getMessage('Submmitted_Successfully') ?>')
                    else
                        toastr.error('<?php echo CommonLanguage::getMessage('Failed_Submit') ?>')
                }
            })
        })

        $("#get_temp_att").on("click", function () {
            RebuildDataTable('<?php echo CommonLanguage::getMessage('temp_att_sheet') ?>', [], "HRMAjax/get_temp_att_list", {}, "#temp_att_list");
            $("#temp_att_list").css("width", "100%")
            $("#temp_att_modal").modal("show")
        })

        $("#temp_att_list").on("click", ".retreive_temp", function () {
            temp_id = $(this).attr("data-id");
            temp_title = $(this).attr("data-title");
            $.ajax({
                url: 'HRMAjax/get_temp_att_data',
                data: {temp_id: temp_id},
                dataType: 'json',
                complete: function (v1, v2) {
                    var Data = v1.responseJSON;
                    var table_row = '';
                    if (Data.length) {
                        $(Data).each(function (i, v) {

                            var time_in = '', time_out = '';
                            if (manual_add_sub_time_col) {
                                time_in += '<span class="fa fa-minus-circle shift_left"></span>';
                                time_out += '<span class="fa fa-minus-circle shift_left"></span>';
                            }
                            time_in += '<input type="text" class="form-control input_picker time_in time_in_picker" value="' + v.time_in + '"  data-indx="' + (v.time_in_indx) + '" data-emp="' + v.data_id + '"/>';
                            time_out += '<input type="text" class="form-control input_picker time_out time_out_picker" value="' + v.time_out + '" data-indx="' + (v.time_out_indx) + '" data-emp="' + v.data_id + '"/>';
                            if (manual_add_sub_time_col) {
                                time_in += '<span class="fa fa-plus-circle shift_right"></span>';
                                time_out += '<span class="fa fa-plus-circle shift_right"></span>';
                            }
                            table_row += '<tr data-row="' + v.data_row + '" data-id="' + v.data_id + '" location-id="' + v.location_id + '" ><td>' + v.emp_name + '</td><td><div style="display:flex;">' + time_in + '</div></td><td><div style="display:flex;">' + time_out + '</div></td><td>' + (v.location_id == '' ? '' : v.loc_name) + '</td></tr>';
                        });
                    }
                    $('#tableWithSearch tbody').html(table_row);
                    $('.time_in_picker,.time_out_picker').datetimepicker({format: 'YYYY-MM-DD HH:mm', useCurrent: false, extraFormats: ['DD-MM-YYYY']});

                    $("#temp_att_modal").modal("hide")
                    $("#edit_temp_save").removeClass('hidden')
                }
            })
        })

        $('#temp_att_list').on('click', '.delete_temp', function () {
            var entry_value = $(this).attr('data-id')
            IncludeDeleteModal(common_delete_modal, {id: entry_value}, function () {
                RebuildDataTable('<?php echo CommonLanguage::getMessage('temp_att_sheet') ?>', [], "HRMAjax/get_temp_att_list", {}, "#temp_att_list");
            }, "HRMAjax/delete_temp_att");
        });

    });
    // ValidateFunction for file
    function ValidateForNewFile(input, inputID) {
        var IsFileOK = false;
        $(inputID + " .fa-check").remove()
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function () {
                $(inputID + " > .fa-times").hide()
                $(inputID).append(" <span class='fa fa-check'></span>")
            }
            reader.readAsDataURL(input.files[0]);
            return true;
        }
        return false;
    }
</script>