<?php
if ($permissions->hasPermission('AssignLeave')) {
    include('Views/HRM/AssignAcruedLeave.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 $title; ?></div>
            <div class="clearfix"></div>

        </div>
        <div id="AssignLeaveValidationAlert"></div>
        <div class="panel-body">
            <div class="row">
                <div class="col-md-12">
                    <?php
                    if ($permissions->hasPermission($is_holiday ? ($is_actual ? 'add_employee_holiday_act' : 'add_employee_holiday'): 'AssignLeave')) {
                        echo Forms::FloatingAddButton('4c0870', '#AssignAcruedLeave', 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-3">
                        <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><span class="red-star">*</span>
                        <input type="hidden" id="employee_select_id" name="employee_select_id" class='full-width employee_select_id'/>
                    </div>


                </div>
            </div>
            <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('day_number'); ?></th>
                        <th  class="text-center"><?php print CommonLanguage::getMessage('status'); ?></th>
                        <th  class="text-center"><?php print CommonLanguage::getMessage('Action'); ?></th>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="row">
                <?php if ($permissions->hasPermission('ApproveLeave')) { ?>
                    <div class="col-md-2 m-t-20">
                        <button type="button" class="btn btn-success" id="approve_all"><?php print CommonLanguage::getMessage('approve') ?></button>
                    </div>
                <?php } ?>

            </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">
                <h4 class="modal-title"><?php print CommonLanguage::getMessage('confirm_approve') ?></h4>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-12 m-t-10">
                        <p><?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"><?php print CommonLanguage::getMessage('save') ?></button>
            </div>
            <?php echo Forms::ModalLoader('approveDisabler'); ?>
        </div>
    </div>
</div>
<script>
    var title = <?php echo json_encode(CommonLanguage::getMessage('assign_accrued_leave')) ?>,
            Deleted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Deleted_Successfully')) ?>,
            is_new = <?php echo json_encode($is_new); ?>,
            is_actual = <?php echo json_encode($is_actual); ?>,
            is_holiday = <?php echo json_encode($is_holiday); ?>,
            accruedStartDate = '', accruedEndDate = '',
            leave_id_filter = <?php echo json_encode($leave_id_filter); ?>, id_to_edit = 0, is_edit = false;

    $(function () {
        build_select2($('.employee_select_id'), 'xhr/employeeSearch?is_actual=' + is_actual + '&with_id=1');

        if (is_new == 1) {
            $("#AssignAcruedLeave").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_accrued_check").prop("checked", is_checked);
            }
        });
        $('#approve_all').on('click', function () {
            var row = $("#tableWithSearch").dataTable().fnGetNodes();
            if ($('input.employee_accrued_check:checked').length == 0) {
                toastr.error('<?php echo CommonLanguage::getMessage('choose_entry'); ?>')
                return;
            }
            $('#confirm-approve-modal').modal('show')
        })
        $('#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')]
            }, locale: {
                cancelLabel: 'Clear'
            }, allowEmpty: false,
            autoUpdateInput: false
        })
        $("#EmployeeDate").on('apply.daterangepicker', function (ev, picker) {
            accruedStartDate = picker.startDate.format('YYYY-MM-DD'),
                    accruedEndDate = 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) {
            accruedStartDate = ''
            accruedEndDate = ''
            $(this).val('');
            build_table()
        });
        //        $("#pend-status").val(is_approved).select2()
        build_table()
        $("#pend-status,input.employee_select_id").on("change", function () {
            build_table()
        })
        $(".actionButton").on("click", function () {
            id_to_edit = 0;
            is_edit = false;
        })
        $("#tableWithSearch").on("click", ".edit_leave", function () {
            id_to_edit = $(this).parents('.Action').attr('data-id');
            is_edit = true;
            $.ajax({
                url: "HRMAjax/view_leave_by_id",
                data: {id: $(this).parents('.Action').attr('data-id')},
                dataType: 'json',
                complete: function (v1, v2) {
                    if (v2 == 'success') {
                        var data = v1.responseJSON;
                        $("#Employee_AssignAcruedLeave").val(data['Employee_ID']).select2()
                        $("#is_half_day").prop("checked", data['is_half_day'] ? true : false)
                        $("#trs_dys").prop("checked", data['trs_dys'] ? true : false)
                        //                        build_select2($('.Employee_ID'), 'xhr/employeeSearch?is_actual=' + is_actual);
                        $("#From_To_Date").val(data['Date_From'] + ' - ' + data['Date_To'])
                        $("#AssignAcruedLeave").modal("show")
                        //                        build_table()
                    }
                }
            })
        })
        $("#tableWithSearch").on("click", ".Approve,.Reject", function () {
            $.ajax({
                url: "HRMAjax/approveAccruedRequest",
                method: "POST",
                dataType: 'json',
                data: {id: $(this).attr('data-id'), status: $(this).attr('data-status')},
                complete: function (v1, v2) {
                    if (v2 == 'success' && v1.responseJSON[0] == 'OK') {
                        build_table()
                        //                        RebuildDataTable(title, [0, 1, 2], 'HRMAjax/EmployeeAccruedList', {is_actual: is_actual});
                    } else {
                        $('#AssignLeaveValidationAlert').attr('class', ' alert alert-danger').html(v1.responseJSON[1])
                        setTimeout(function () {
                            $("#AssignLeaveValidationAlert").addClass('hidden')
                        }, 3000)
                    }
                }
            })
        });
        $('#submit_confirm_approve').on('click', function () {
            var Data = {employee_accrued: []}, row = $("#tableWithSearch").dataTable().fnGetNodes();
            for (var i = 0; i < row.length; i++) {
                if ($(row[i]).find("input.employee_accrued_check").is(":checked")) {
                    Data.employee_accrued.push($(row[i]).find('input.employee_accrued_check').attr("data-id"));
                }
            }
            $('#approveDisabler').removeClass('hidden');
            $.ajax({
                url: "HRMAjax/submitMultiApproveAccrued",
                data: Data,
                method: "POST",
                dataType: "json",
                complete: function (v1, v2) {
                    if (v2 == "success") {
                        if (v1.responseJSON[0] === 'OK') {
                            toastr.success('<?php echo CommonLanguage::getMessage('Submitted_Successfully'); ?>')
                            build_table();
                            hideModalAlert('confirm-approve-modal');
                        }
                        $('#approveDisabler').addClass('hidden');
                    }
                }
            });
        });

        $("#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_accrued_leave",
                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(),
            start_date: accruedStartDate,
            is_holiday: is_holiday,
            employee_id: $("input.employee_select_id").val(),
            end_date: accruedEndDate};
        if (leave_id_filter != '')
            data.leave_id_filter = leave_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/EmployeeAccruedList', data, '', '', optns);
        leave_id_filter = '';
    }
</script>