<section class="container-fluid" style="padding-bottom: 2rem;">
    <form id="allocationForm" class="form">
        <div class="card bg-light-transparent">
            <div class="card-header bg-light">
                <div class="float-left">
                    <h5>Setup Leave Allocation</h5>
                </div>
                <div class="float-right">
                    <div class="form-inline">
                        <label for="setupYearRef">For The Year</label>
                        <input id="allocationYear" type="text" class="form-control yearpicker text-right" style="margin-left: 1rem;" placeholder="Choose Year" <?php if(isset($year)) echo "value='".$year."' disabled" ?>>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div class="card no-shadow">
                    <div class="card-body">
                        <div class="table-responsive">
                            <table id="tblStaff" class="table table-bordered table-hover">
                                <thead>
                                <tr>
                                    <th rowspan="2">
                                        <input type="checkbox" style="line-height: normal; margin: 0;" name="checkAll" id="checkAll">
                                    </th>
                                    <th rowspan="2">Staff ID</th>
                                    <th rowspan="2">Staff Name & Date Joined</th>
                                    <th rowspan="2" width="17%">Department</th>
                                    <!-- <th rowspan="2">Branch</th> -->
                                    <th rowspan="2">Position & Entitlement</th>
                                    <th rowspan="2">Previous Year Allocation</th>
									<th rowspan="2">Additional Leave</th>
                                    <th colspan="2" class="text-center">Leave Allocation</th>
                                    <th rowspan="2"></th>
                                </tr>
                                <tr>
                                    <th class="text-center">AL</th>
                                    <th class="text-center">MC</th>
                                </tr>
                                </thead>
                                <tbody>
                                    <?php if ($unallocated_staffs): ?>
                                        <?php foreach($unallocated_staffs as $unallocated): 
//	if ($unallocated['id'] == 24) {var_dump($unallocated); die();} ?>
                                            <tr id="staff-row-<?php echo $unallocated['id']; ?>" data-staff="<?php echo htmlspecialchars(json_encode($unallocated), ENT_QUOTES, 'UTF-8'); ?>">
                                                <td><input type="checkbox" class="checkbox" style="line-height: normal; margin: 0;" id="checkbox-<?php echo $unallocated['id']; ?>"></td>
                                                <td><?php echo $unallocated['staff_id'] ?></td>
                                                <td><?php echo $unallocated['name'].'<br>';
echo ($unallocated['date_joined']) ? date('d/m/Y', strtotime($unallocated['date_joined'])) : ''; 												?></td>
                                                <td>
                                                    <?php echo $unallocated['department_name'] ?>
                                                    <?php if ($unallocated['branch_name']) echo '<br>('.$unallocated['branch_name'].')' ?>
                                                </td>
                                                <!-- <td><?php echo $unallocated['branch_name'] ?></td> -->
                                                <td><?php echo $unallocated['position_name'].'<br>'.number_format($unallocated['al_entitled_leave']); ?></td>
                                                <td nowrap><input disabled type="number" step="0.5" class="form-control text-right" value="<?php echo number_format($unallocated['prev_al']); ?>"></td>
												<td nowrap><input disabled type="number" step="0.5" class="form-control text-right" value="<?php echo number_format($unallocated['additional_leave'], 1); ?>"></td>
                                                <td><input id="al-<?php echo $unallocated['id']; ?>" disabled type="number" step="0.5" class="form-control text-right" value="<?php echo number_format($unallocated['al_allocation'], 1); ?>"></td>
                                                <td><input id="mc-<?php echo $unallocated['id']; ?>" disabled type="number" step="0.5" class="form-control text-right" value="<?php echo number_format(floatval($unallocated['mc_allocation']), 1); ?>"></td>
                                                <td class="text-center"><button disabled id="allocationCalcBtn-<?php echo $unallocated['id'] ?>" class="btn btn-sm btn-primary" type="button" data-trigger="hover" data-tooltip="tooltip" title="Show Calculation" onclick="showCalcModal(<?php echo $unallocated['id']; ?>);"><i class="fas fa-info-circle"></i></button></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <div class="card-footer bg-white">
                <div class="float-right">
                    <button type="button" class="btn btn-primary" onclick="saveAllocation()">Save</button>
                </div>
            </div>
        </div>
    </form>
</section>
<!--<section class="container" style="padding-bottom: 2rem;">
    <div class="card bg-light-transparent">
            <div class="card-header bg-light">
                <div class="float-left">
                    <h5>Allocated Staffs</h5>
                </div>
            </div>
            <div class="card-body">
                <div class="card no-shadow">
                    <div class="card-body">
                        <div class="table-responsive">
                            <table id="tblAllocatedStaff" class="table table-bordered table-hover">
                                <thead>
                                <tr>
                                    <th>Staff ID</th>
                                    <th>Staff Name</th>
                                    <th width="17%">Department</th>
                                     <th>Branch</th> 
                                    <th>Position</th>
                                    <th>Date Joined</th>
                                </tr>
                                </thead>
                                <tbody>
                                    <?php if (isset($allocated_staffs)): ?>
                                        <?php foreach($allocated_staffs as $allocated): ?>
                                            <tr data-staff="<?php echo htmlspecialchars(json_encode($allocated), ENT_QUOTES, 'UTF-8'); ?>">
                                                <td><?php echo $allocated['staff_id'] ?></td>
                                                <td><a href="<?php echo base_url("hr/leave/allocation/").$year."/".$allocated['department_id']."/".$allocated['id']; ?>"><?php echo $allocated['name'] ?></a></td>
                                                <td>
                                                    <?php echo $allocated['department_name'] ?>
                                                    <?php if ($allocated['branch_name']) echo '<br>('.$allocated['branch_name'].')' ?>
                                                </td>
                                                 <td><?php echo $allocated['branch_name'] ?></td> 
                                                <td><?php echo $allocated['position_name'] ?></td>
                                                <td nowrap><?php echo ($allocated['date_joined']) ? date('d/m/Y', strtotime($allocated['date_joined'])) : ''; ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
</section>
<section class="container" style="padding-bottom: 2rem;">
    <div class="card bg-light-transparent">
            <div class="card-header bg-light">
                <div class="float-left"><h5>Staff's Leave Allocation Setup Errors</h5></div>
                <div class="float-right">
                    <button id="btnShowFilters" type="button" class="btn btn-outline-dark btn-sm" data-toggle="collapse" data-target="#collapseFilter"><i class="fas fa-filter"></i> Show Filters</button>
                </div>
            </div>
            <div class="collapse" id="collapseFilter">
                <div class="card-header">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="card no-shadow">
                                <div class="card-body">
                                    Lorem, ipsum dolor sit amet consectetur adipisicing elit. Recusandae explicabo, minima tempore dolor consequatur placeat libero hic, quas animi vitae veniam ex harum! Dolorum, iure. Cupiditate enim pariatur officia saepe?
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="card no-shadow">
                                <div class="card-body">
                                    Lorem ipsum dolor sit amet consectetur adipisicing elit. Vero, temporibus! Ratione voluptatibus porro harum accusamus eligendi inventore sequi tempore illo officiis tenetur. Possimus libero ullam doloremque impedit, ex est dolorem!
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div class="card no-shadow">
                    <div class="card-body">
                        <div class="table-responsive">
                            <table id="tblStaffErrors" class="table table-bordered table-hover">
                                <thead>
                                <tr>
                                    <th>Staff ID</th>
                                    <th>Staff Name</th>
                                    <th width="17%">Department</th>
                                    <th>Status</th>
                                    <th>Action</th>
                                </tr>
                                </thead>
                                <tbody>
                                    <?php if(isset($unable_staffs)): ?>
                                        <?php foreach($unable_staffs as $unable): ?>
                                            <tr data-staff="<?php echo htmlspecialchars(json_encode($unable), ENT_QUOTES, 'UTF-8'); ?>">
                                                <td><?php echo $unable['staff_id'] ?></td>
                                                <td><?php echo $unable['name'] ?></td>
                                                <td>
                                                    <?php echo $unable['department_name'] ?>
                                                    <?php if ($unable['branch_name']) echo '<br>('.$unable['branch_name'].')' ?>
                                                </td>
                                                <td>
                                                    <ul>
                                                    <?php 
                                                        if (!$unable['date_joined']) echo '<li>No Date Joined</li>';
                                                        if (!$unable['department_id']) echo '<li>No Department</li>';
                                                        if (!$unable['position_category_id']) echo '<li>No Position</li>';
                                                    ?>
                                                    </ul>
                                                </td>
                                                <td class="text-center">
                                                    <a target="_blank" class="btn btn-sm btn-primary" href="<?php echo base_url('hr/StaffProfile/new_action_type/'.$unable['id']); ?>" data-trigger="hover" data-tooltip="tooltip" title="Update Staff Profile"><i class="fas fa-edit"></i></a>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
</section>-->

<div class="modal fade" id="calcModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="allocation-modal-title">Allocation Calculation</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form class="form" id="calcAllocationForm">
                    <div class="row">
                        <div class="col">
                            <label for="annualEntitledLeave">Previous Year Entitlement</label>
                        </div>
                        <div class="col">       
                            <div class="form-group">
                                <input type="number" step="0.5" disabled class="form-control text-right" name="previousYearEntitlement" id="previousYearEntitlement" placeholder="Previous Year Entitlement">
                            </div>
                        </div>
                    </div>
					<div class="row">
                        <div class="col-4"> 
                            <label for="annualBringForward">Bring Forward</label>
                        </div>
                        <div class="col-2">
                            <!--button type="button" class="btn btn-sm btn-primary" id="getBringForwardBtn" onclick="getBringForward();">GET</button-->
                        </div>
                        <div class="col">
                            <div class="form-group">
                                <input type="number" step="0.5" required data-parsley-error-message="Bring Forward is required." class="form-control text-right" name="annualBringForward" id="annualBringForward" placeholder="Bring Forward">
                            </div>
                        </div>
                    </div>
                    <hr>
                    <div class="row">
                        <div class="col-4"> 
                            <label for="annualAdditionalLeave">Additional Leave</label>
                        </div>
                        <div class="col-2">
                            <!--button type="button" class="btn btn-sm btn-primary" id="getBringForwardBtn" onclick="getBringForward();">GET</button-->
                        </div>
                        <div class="col">
                            <div class="form-group">
                                <input type="number" step="0.5" required data-parsley-error-message="Max Entitlement is required." class="form-control text-right" name="annualAdditionalLeave" id="annualAdditionalLeave" placeholder="Additional Leave">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col">
                            <label for="annualEntitledLeave">Entitled Leave</label>
                        </div>
                        <div class="col">       
                            <div class="form-group">
                                <input type="number" step="0.5" required data-parsley-error-message="Entitled Leave is required." class="form-control text-right" name="annualEntitledLeave" id="annualEntitledLeave" placeholder="Entitled Leave">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col"> 
                            <label for="annualAllocation">Leave Allocation</label>
                        </div>
                        <div class="col">
                            <input type="number" step="0.5" required data-parsley-error-message="Allocation is required." class="form-control text-right" name="annualAllocation" id="annualAllocation" placeholder="Leave Allocation">
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <div class="btn-group float-right">
                    <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    $(function() {
        $('#tblStaff').DataTable().destroy();
        $('#tblStaff').DataTable({ paging: false });

        $('#collapseFilter').on('show.bs.collapse', function () {
            $('#btnShowFilters').addClass('active');
        })
        $('#collapseFilter').on('hide.bs.collapse', function () {
            $('#btnShowFilters').removeClass('active');
        })
    })

    $( ".yearpicker" ).datepicker({
        uiLibrary: 'bootstrap4',
        format: 'yyyy',
        autoclose: true,
        changeYear: true,
        viewMode: "years", 
        minViewMode: "years"
    });

    $("#checkAll, .checkbox").click(function(e) {
        var year = $("#allocationYear").val();

        if (!year) {
            e.preventDefault();
            alert('Please input year');
        }
    })

    $("#checkAll").change(function(e) {
        if (this.checked) {
            $(".checkbox").prop('checked', true).change();
            
/*            // var getData = {
            //     year: $("#allocationYear").val(),
            //     users: []
            // };

            // // get row data
            // $(".checkbox:checked").each(function () {
            //     let staff = $(this).closest('tr').data('staff');

            //     getData.users.push({
            //         id: staff.id, 
            //         category_id: (staff.position_category_id != 0) ? staff.position_category_id : staff.position_id
            //     })
            // })

            // if(getData.users.length > 0) {
            //     $.ajax({
            //         url: "<?php //echo base_url('hr/leave/getNewAllocationBulk'); ?>",
            //         type: "GET",
            //         data: getData,
            //         dataType: "JSON",
            //         success: (data) => {
            //             if (data.status.toLowerCase() == 'success') {
            //                 var users = data.users;
                            
            //                 $.each(users, function(k, v) {
            //                     let allocation = v.new_allocation;

            //                     $('#checkbox-'+v.user_id).data('allocation', allocation);
                                
            //                     $('#al-' + v.user_id).val(allocation.al_allocation.toFixed(1)).prop('disabled', false);
            //                     $('#mc-' + v.user_id).val(allocation.mc_allocation).prop('disabled', false);
            //                     $('#allocationCalcBtn-' + v.user_id).val(allocation.mc_allocation).prop('disabled', false);

            //                     $('#staff-row-' + v.user_id).attr('data-allocation', JSON.stringify(allocation));
            //                 })
            //             } else {
            //                 console.log('err');
            //             }
            //         }
            //     })
            // } else {
            //     $(this).prop('checked', false);
            // }  */
        } else {
            $(".checkbox").prop('checked', false).change();
        }
    })

    $(".checkbox").change(function() {
        var year = $("#allocationYear").val();
        var staff = $(this).closest('tr').data('staff');

        if(this.checked) {

 /*           // $.ajax({
            //     url: "<?php echo base_url('hr/leave/getNewAllocation'); ?>",
            //     type: "GET",
            //     data: { 
            //         year, 
            //         id: staff.id, 
            //         category_id: (staff.position_category_id != 0) ? staff.position_category_id : staff.position_id
            //     },
            //     dataType: "JSON",
            //     success: (data) => {
            //         if (data.status.toLowerCase() == 'success') {
            //             var allocation = data.new_allocation;

            //             console.log(allocation);
                            
            //             $('#al-' + staff.id).val(allocation.al_allocation.toFixed(1)).prop('disabled', false);
            //             $('#mc-' + staff.id).val(allocation.mc_allocation).prop('disabled', false);
            //             $('#allocationCalcBtn-' + staff.id).prop('disabled', false);

            //             $('#staff-row-' + staff.id).attr('data-allocation', JSON.stringify(allocation));

            //         } else {
            //             $(this).prop('checked', false);

            //             $('#al-' + staff.id).val('').prop('disabled', true);
            //             $('#mc-' + staff.id).val('').prop('disabled', true);
            //             $('#allocationCalcBtn-' + staff.id).prop('disabled', true);
            //         }
            //     }
            // }) */
                
            $('#al-' + staff.id).prop('disabled', false);
            $('#mc-' + staff.id).prop('disabled', false);
            $('#allocationCalcBtn-' + staff.id).prop('disabled', false);
        } else {
            $(this).prop('checked', false);

            $('#al-' + staff.id).prop('disabled', true);
            $('#mc-' + staff.id).prop('disabled', true);
            $('#allocationCalcBtn-' + staff.id).prop('disabled', true);
        }
    });

    function showCalcModal(id) {
        clearForm('#calcAllocationForm');

        var staff = $('#staff-row-' + id).data('staff');

        if (staff) {
            console.log(staff);

            $('#annualBringForward').val(parseFloat(staff.bring_forward).toFixed(1));
            $('#annualAdditionalLeave').val(parseFloat(staff.additional_leave.total_additional_leave).toFixed(1));
            $('#annualEntitledLeave').val(parseFloat(staff.al_entitled_leave).toFixed(1));
            $('#annualAllocation').val(parseFloat(staff.al_allocation).toFixed(1));
			$('#previousYearEntitlement').val(parseFloat(staff.prev_al).toFixed(1));

            $('#calcModal').modal('show');
        }
    }

    function updateAllocation() {
        $('#annualUserID').val();
        $('#annualBringForward').val();
        $('#annualAdditionalLeave').val();
        $('#annualEntitledLeave').val();
        $('#annualAllocation').val();
    }

    function saveAllocation() {
        toastConfirm("Are you sure you want to save Leave Allocation?", () => {
            console.log('unallocated staff: ' + JSON.stringify(<?php echo (json_encode($unallocated_staffs)); ?>));
            
            var year = $("#allocationYear").val();
            var save_data = [];

            $(".checkbox:checked").each(function () {
                let staff      = $(this).closest('tr').data('staff');
                let allocation = $(this).data('allocation');

                save_data.push({
                    user_id: staff.id,
                    year: year,
                    new_allocation: {
                        al_data: {
                            entitlement_id: staff.al_entitlement_id,
                            allocate_leave: $('#al-' + staff.id).val(),
                            bring_forward: staff.bring_forward
                        },
                        mc_data: {
                            entitlement_id: staff.mc_entitlement_id,
                            allocate_leave: $('#mc-' + staff.id).val(),
                        }
                    }
                })
            })

            $.ajax({
                url: "<?php echo base_url('hr/leave/createAllocationBulk'); ?>",
                type: "POST",
                data: { save_data },
                dataType: "JSON",
                success: (data) => {
                    localStorage.setItem("status", data.status);
                    localStorage.setItem("msg", data.msg);

                    location.href = "<?php echo base_url('hr/leave/allocation/'); ?>" + year;
                }
            })
        })
    }
</script>