<?php
if ($permissions->hasPermission('addAbsence')) {
    include('Views/HRM/addAbsence.php');
}
?>
<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('absence_details'); ?></div>
            <div class="clearfix"></div>
        </div>
        <div class="row form-group">
            <div class="col-md-12"><?php
                if ($permissions->hasPermission('addAbsence')) {
                    echo Forms::FloatingAddButton('4c0870', '#add_absence', CommonLanguage::getMessage('add'));
                }
                ?>

           

                <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 class="full-width pend-status" id="pend-status" data-init-plugin="select2">
                        <option value="" ><?php echo CommonLanguage::getMessage('All') ?></option>
                        <option value="0"><?php echo CommonLanguage::getMessage('awaiting_review') ?></option>
                        <option value="1"><?php echo CommonLanguage::getMessage('approved') ?></option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label><?php echo CommonLanguage::getMessage('employee_name') ?></label>
                    <input type="hidden" id="employee_select_id" name="employee_select_id" class='full-width employee_select_id'/>
                </div>
                <div class="col-md-2">
                    <label><?php echo CommonLanguage::getMessage('absence_reason') ?></label>
                    <input type="hidden" id="absence_reason_filter" name="absence_reason_filter" class='full-width absence_reason_filter'/>
                </div>

            </div>
        </div>
        <div class="panel-body">
            <div class="row">
                <div class="col-md-12 table-responsive">
                    <table class="table table-bordered hrm" id="tableWithSearch">
                        <thead>
                        <th class="text-center no-print" ><?php echo $permissions->hasPermission('ApproveLeave') ? '<input type="checkbox" class="select_all"/>' : ''; ?></th>
                        <th  class="text-center"><?php print CommonLanguage::getMessage('employee_name'); ?></th>
                        <th  class="text-center"><?php print CommonLanguage::getMessage('From'); ?></th>
                        <th  class="text-center"><?php print CommonLanguage::getMessage('To'); ?></th>
                        <th  class="text-center"><?php print CommonLanguage::getMessage('days_nb'); ?></th>
                        <th  class="text-center"><?php print CommonLanguage::getMessage('reason'); ?></th>
                        <th  class="text-center"><?php print CommonLanguage::getMessage('status'); ?></th>
                        <th  class="text-center" style="width:20%"><?php print CommonLanguage::getMessage('Action'); ?></th>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="row m-t-10">
                <div class="col-md-4">
                    <?php if ($permissions->hasPermission('ApproveLeave')) { ?>
                        <button type="button" class="btn btn-success" id="approve_all"><?php print CommonLanguage::getMessage('approve') ?></button>
                    <?php } if ($permissions->hasPermission('reject_absence_leave')) { ?>
                        <button type="button" class="btn btn-danger" id="reject_all"><?php print CommonLanguage::getMessage('Reject') ?></button>
                    <?php } ?>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="ConfirmDeleteRow" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title"><?php print CommonLanguage::getMessage('Confirm_Delete') ?></h4>
                <div id="delete_alert"></div>
            </div>
            <div class="modal-body">
                <div class="row">

                    <div class="col-md-12 m-t-10">
                        <p><?php print CommonLanguage::getMessage('About_To_Delete') ?></p>
                        <p><?php print CommonLanguage::getMessage('Proceed_Delete') ?></p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal"><?php print CommonLanguage::getMessage('Close') ?></button>
                <button type="button" class="btn btn-danger width-auto" id="Row_Delete"><?php print CommonLanguage::getMessage('delete') ?></button>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="confirm-approve-modal" 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>
                <h5 class="modal-title bold text-left"><?php print CommonLanguage::getMessage('confirm_approve') ?></h5>
            </div>
            <div class="modal-body">
                <input type="hidden" id="current_status_id"  name="current_status_id"/>
                <div class="row">
                    <div class="col-md-12 m-t-10">
                        <p class="confirm-message"><?php print CommonLanguage::getMessage('about_approve_data') ?></p>
                        <p><?php print CommonLanguage::getMessage('Proceed_Delete') ?></p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal"><?php print CommonLanguage::getMessage('Close') ?></button>
                <button type="button" class="btn btn-success" id="submit_confirm_approve_reject"><?php print CommonLanguage::getMessage('save') ?></button>
            </div>
            <?php echo Forms::ModalLoader('approveDisabler'); ?>
        </div>
    </div>
</div>
<script>
    var title = <?php echo json_encode(CommonLanguage::getMessage('absence_setting_list')) ?>,
            is_new = <?php echo json_encode($is_new); ?>,
            Deleted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Deleted_Successfully')) ?>,
            is_actual = <?php echo json_encode($is_actual); ?>,
            absenceStartDate = '', absenceEndDate = '',
            absence_id_filter = <?php echo json_encode($absence_id_filter); ?>,
            id_to_edit = 0, is_edit = false;
    $(function () {

        build_select2($("#absence_reason_filter"), "xhr/CommonSearch?col_id=Absence_Reason_ID&col_name=Absence_Reason_Name&table=tbl_hrm_absence_reasons")

        build_select2($('.employee_select_id'), 'xhr/employeeSearch?is_actual=' + is_actual + '&with_id=1');
        if (is_new == 1) {
            $("#add_absence").modal("show");
        }
        $("#tableWithSearch").on("click", "input.select_all", function (e) {
            var is_checked = $(this).is(":checked");
            var row = $("#tableWithSearch").dataTable().fnGetNodes();
            for (var i = 0; i < row.length; i++) {
                $(row[i]).find("input.employee_absence_check").prop("checked", is_checked);
            }
        });
        $('#approve_all,#reject_all').on('click', function () {
            var row = $("#tableWithSearch").dataTable().fnGetNodes();
            if ($('input.employee_absence_check:checked').length == 0) {
                toastr.error('<?php echo CommonLanguage::getMessage('choose_entry'); ?>')
                return;
            }
            $('#current_status_id').val($(this).attr('id') == 'approve_all' ? 1 : 2);
            $('#confirm-approve-modal .modal-title').html($(this).attr('id') == 'approve_all' ? '<?php echo CommonLanguage::getMessage('confirm_approve'); ?>' : '<?php echo CommonLanguage::getMessage('confirm_reject'); ?>');
            $('#confirm-approve-modal .confirm-message').html($(this).attr('id') == 'approve_all' ? '<?php echo CommonLanguage::getMessage('about_approve_data'); ?>' : '<?php echo CommonLanguage::getMessage('about_reject_data'); ?>');
            $('#confirm-approve-modal').modal('show');
        });
        $('#submit_confirm_approve_reject').on('click', function () {
            var Data = {employee_absence: [], status_id: $('#current_status_id').val()},
            row = $("#tableWithSearch").dataTable().fnGetNodes();
            for (var i = 0; i < row.length; i++) {
                if ($(row[i]).find("input.employee_absence_check").is(":checked")) {
                    Data.employee_absence.push($(row[i]).find('input.employee_absence_check').attr("data-id"));
                }
            }
            $('#approveDisabler').removeClass('hidden');
            $.ajax({
                url: "HRMAjax/submitMultiApproveAbsence",
                data: Data,
                method: "POST",
                complete: function (v1, v2) {
                    if (v2 == "success") {
                        if (v1.responseText == 'OK') {
                            toastr.success('<?php echo CommonLanguage::getMessage('Submitted_Successfully'); ?>')
                            build_table();
                            hideModalAlert('confirm-approve-modal');
                        }
                        $('#approveDisabler').addClass('hidden');
                    }
                }
            });
        });
        $("#EmployeeDate").daterangepicker({
            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')]
            }, locale: {
                cancelLabel: 'Clear'
            }, allowEmpty: false,
            autoUpdateInput: false
        });

        $("#EmployeeDate").on('apply.daterangepicker', function (ev, picker) {
            absenceStartDate = picker.startDate.format('YYYY-MM-DD'),
                    absenceEndDate = picker.endDate.format('YYYY-MM-DD');
            $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
            build_table()
        });
        $("#EmployeeDate").on('cancel.daterangepicker', function (ev, picker) {
            absenceStartDate = ''
            absenceEndDate = ''
            $(this).val('');
            build_table()
        });



        //        $('#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.absenceStartDate= start.format("YYYY-MM-DD"),
        //                    window.absenceEndDate= end.format("YYYY-MM-DD");
        //            build_table()
        //        })
        //        $("#pend-status").val(is_approved).select2()
        build_table()
        $(".actionButton").on("click", function () {
            id_to_edit = 0;
            is_edit = false;
        })
        $("#tableWithSearch").on("click", ".edit_absence", function () {
            id_to_edit = $(this).parents('.Action').attr('data-id');
            is_edit = true;
            $.ajax({
                url: "HRMAjax/view_absence_by_id",
                data: {id: $(this).parents('.Action').attr('data-id')},
                dataType: 'json',
                complete: function (v1, v2) {
                    if (v2 == 'success') {
                        var data = v1.responseJSON;
                        $("#Employee_ID").val(data['Employee_ID']).attr("data-select-name", data['Employee_Name'])
                        build_select2($('.Employee_ID'), 'xhr/employeeSearch?is_actual=' + is_actual);
                        $("#Absence_Reason_ID").val(data['Absence_Reason']).select2()
                        $("#From_To_Date").val(data['Absence_From_Date'] + ' - ' + data['Absence_To_Date'])
                        $("#add_absence").modal("show")
                        //                        build_table()
                    }
                }
            })
        })
        $("#tableWithSearch").on("click", ".Approve,.Reject", function () {
            $.ajax({
                url: "HRMAjax/approveAbsenceRequest",
                method: "POST",
                data: {id: $(this).attr('data-id'), status: $(this).attr('data-status')},
                complete: function (v1, v2) {
                    if (v2 == 'success' && v1.responseText == 'OK') {
                        build_table()
                    }
                }
            })
        })
        $("#pend-status,input.employee_select_id,#absence_reason_filter").on("change", function () {
            $(this).val() == 1 ? $('#reject_all,#approve_all').addClass('hidden') : $('#reject_all,#approve_all').removeClass('hidden')
            build_table()
        })
        $("#tableWithSearch").on("click", ".deleteAccrued", function () {
            $("#ConfirmDeleteRow").attr("data-id", $(this).parents(".Action").attr("data-id")).modal("show")
        })
        $("#Row_Delete").on("click", function () {
            $.ajax({
                url: "HRMAjax/delete_absence",
                method: "POST",
                data: {id: $("#ConfirmDeleteRow").attr("data-id")},
                complete: function (v1, v2) {
                    if (v2 == 'success' && v1.responseText == 'OK') {
                        $("#delete_alert").attr("class", "alert alert-success").html(Deleted_Successfully)
                        build_table()
                        setTimeout(function () {
                            $("#delete_alert").addClass("hidden")
                            $("#ConfirmDeleteRow").modal("hide")
                            $("#ConfirmDeleteRow").attr("data-id", 0)
                        }, 2000)
                    } else {
                        $("#delete_alert").attr("class", "alert alert-danger").html(v1.responseText)
                    }
                }
            })
        })
    })
    function build_table() {
        var data = {is_actual: is_actual, status: $("#pend-status").val(),
            employee_id: $("input.employee_select_id").val(),
            absence_reason_id: $("#absence_reason_filter").val(),
            start_date: absenceStartDate,
            end_date: absenceEndDate};
        if (absence_id_filter != '') {
            data.absence_id_filter = absence_id_filter;
        }

        var optns = {
            cb_ft: function (dt_optns) {
                // stop sorting for column since on click on header checkbox the sorting is triggered
                dt_optns.columnDefs.push({targets: [0], "orderable": false});
            },
        };
        RebuildDataTable(title, '', 'HRMAjax/EmployeeAbsenceList', data, '', '', optns);
        absence_id_filter = '';
    }
</script>