<!--hr/views/leave/usersAllocationlist-->
<section class="container" style="padding-bottom: 2rem;">
    <div class="card bg-light-transparent">
        <div class="card-header bg-white">
        <div class="float-right">
		<?php if (!empty($this->logged_module['role']) && $this->logged_module['role'] != 'user') { ?>
		<button class="btn btn-sm btn-outline-dark" onclick="openAllocationModal()"><i class="fas fa-plus"></i> New Allocation</button><?php } ?>
        </div>
        </div>
        <div class="card-body">
            <div class="card no-shadow">
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered table-hover" id="allocation-table">
                            <thead>
                                <th>Leave Type</th>
                                <th>Allocation</th>
                                <th>Action</th>
                            </thead>
                            <tbody>
                                <?php if(isset($allocations)): ?>
                                    <?php foreach($allocations as $row): ?>
                                        <tr>
                                            <td><?php echo $row['name']; ?></td>
                                            <td>
                                                <table class="table-bordered w-100">
                                                    <thead>
                                                        <th></th>
                                                        <th class="text-center">Amount</th>
                                                    </thead>
                                                    <tbody>
                                                        <tr <?php if ($row['type_id'] != 1) echo 'hidden'; ?>>
                                                            <th width="50%">Carried Forward (<?php echo $year; ?>)</th>
                                                            <td width="50%" class="text-center"><?php echo $row['bring_forward_entitled']; ?></td>
                                                        </tr>
                                                        <tr <?php if ($row['type_id'] == 2 || $row['type_id'] == 4) echo 'hidden'; ?>>
                                                            <th width="50%">Entitled Leave</th>
                                                            <td width="50%" class="text-center"><?php echo $row['leave_entitled']; ?></td>
                                                        </tr>
                                                        <tr>
                                                            <th width="50%">Leave Taken</th>
                                                            <td width="50%" class="text-center"><?php echo $row['leave_taken']; ?></td>
                                                        </tr>
                                                        <tr <?php if ($row['type_id'] != 1) echo 'hidden'; ?>>
                                                            <th width="50%">Carried Forward Balance</th>
                                                            <td width="50%" class="text-center">
<?php //pls refer to view/leave/application function function openSummaryModal()
	//balance_brought_forward = (bf - b4);
	//balance_brought_forward  = bring_forward_entitled - takenB4 
	//there was no col cf balance in table leave allocation. need to calculate. 
	//echo $row['bring_forward'];
	$bring_forward_balance = ($row['bring_forward_entitled'] - $row['takenB4'] < 0)?0:$row['bring_forward_entitled'] - $row['takenB4']; 
	echo $bring_forward_balance; ?>														
															</td>
                                                        </tr>
                                                        <tr <?php if ($row['type_id'] == 2 || $row['type_id'] == 4) echo 'hidden'; ?>>
                                                            <th width="50%">Entitled Balance</th>
                                                            <td width="50%" class="text-center"><?php echo $row['leave_balance']; ?></td>
                                                        </tr>
                                                    </tbody>
                                                </table>
                                            </td>
                                            <td class="text-center">
				<?php if (!empty($this->logged_module['role']) && $this->logged_module['role'] != 'user') { ?>
                                                <div class="btn-group btn-group-justified" <?php if ($row['type_id'] == 2 || $row['type_id'] == 4) echo 'hidden'; ?>>
                                                    <button class="btn btn-primary" onclick="openAllocationModal(<?php echo $row['id']; ?>);"><i class="fas fa-edit"></i></button>
                                                    <button class="btn btn-danger" onclick="deleteAllocation(<?php echo $row['id']; ?>);"><i class="fas fa-trash"></i></button>
                                                </div>
				<?php } ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>
<div class="modal fade" id="allocationModal">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="allocation-modal-title"><?php echo $year; ?> Leave Allocation</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="userForm">
                <div class="form-group form-inline" hidden>
                    <label for="allocationUser" class="col-sm-2 text-right">User ID</label>
                    <input type="text" class="form-control col" name="allocationUser" id="allocationUser" value="<?php echo $user['id']; ?>">
                </div>
                <div class="form-group form-inline" hidden>
                    <label for="allocationID" class="col-sm-2 text-right">Allocation ID</label>
                    <input id="allocationID" name="allocationID" class="form-control col" type="text">
                </div>
                <div class="form-group form-inline" hidden>
                    <label for="entitlementID" class="col-sm-2 text-right">Entitlement ID</label>
                    <input id="entitlementID" name="entitlementID" class="form-control col" type="text">
                </div>
                <div class="form-group form-inline">
                  <label for="allocationType" class="col-sm-2 text-right">Leave Type</label>
                  <div class="col">
                    <select id="allocationType" required data-parsley-error-message="Type is required." name="allocationType" class="select" style="width: 100% !important;">
                      <option value="-1">Select Type</option>
                      <?php foreach ($types as $type): ?>
                        <?php if ($type['id'] != 2 && $type['id'] != 4): ?>
                          <option value="<?php echo $type['id']; ?>"><?php echo $type['name']; ?></option>
                        <?php endif; ?>
                      <?php endforeach; ?>
                    </select>
                  </div>
                </div>
              </form>
              <hr>
              <div id="annualFormContainer">
                <form class="form" id="annualForm">
                  <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="getAdditionalLeaveBtn" onclick="getAdditionalLeave();">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>
                  <hr>
                  <div class="form-row">
                    <div class="col">
                      <div class="form-group">
                        <label for="annualBringForwardBalance">Bring Forward Balance</label>
                        <input type="number" step="0.5" required data-parsley-error-message="Bring Forward Balance is required." class="form-control text-right" name="annualBringForwardBalance" id="annualBringForwardBalance" placeholder="Leave Allocation">
                      </div>
                    </div>
                    <div class="col">
                      <div class="form-group">
                        <label for="annualBalance">Current Balance</label>
                        <input type="number" step="0.5" required data-parsley-error-message="Allocation Balance is required." class="form-control text-right" name="annualBalance" id="annualBalance" placeholder="Leave Balance">
                      </div>
                    </div>
                  </div>
                </form>
              </div>
              <div id="othersFormContainer">
                <form class="form" id="allocationForm">
                  <div class="form-row">
                    <div class="col">
                      <div class="form-group">
                        <label for="othersEntitledLeave">Entitled Leave</label>
                        <input type="text" required data-parsley-error-message="Entitled Leave is required." class="form-control text-right" name="othersEntitledLeave" id="othersEntitledLeave" placeholder="Entitled Leave">
                      </div>
                    </div>
                    <div class="col">
                      <div class="form-group">
                        <label for="othersBalance">Starting Balance</label>
                        <input type="text" required data-parsley-error-message="Percentage is required." class="form-control text-right" name="othersBalance" id="othersBalance" placeholder="Bring Forward Percentage">
                      </div>
                    </div>
                </form>
              </div>
            </div>
            <div class="modal-footer">
              <div class="btn-group float-right">
                <button type="button" class="btn btn-primary" data-dismiss="modal">Cancel</button>
                <button type="button" id="allocationModalSubmitBtn" class="btn btn-light">Save</button>
              </div>
            </div>
        </div>
    </div>
</div>
<script>
    $(function() {
        $('#annualBringForwardBalance, #annualBalance').on('blur', function(e) {
            $(this).val(parseFloat($(this).val()).toFixed(1));
        })
    })

    function overwriteBringForwardBalance() {
        $('#annualBringForwardBalance').val($('#annualBringForward').val());
    }

    function overwriteBalance() {
        $('#annualBalance').val($('#annualAllocation').val());
    }

    function getBringForward() {
        $.ajax({
        url: '<?php echo base_url('hr/leave/getBringForward'); ?>',
        type: 'GET',
        data: {
            user_id: '<?php echo $user['id']; ?>',
            category_id: '<?php echo $user['position_category_id']; ?>',
            year: '<?php echo $year; ?>'
        },
        dataType: 'JSON',
        success: (data) => {
            if (data.status.toLowerCase() == 'success') {
                var bring_forward = data.bring_forward;
                
                $('#annualBringForward').val(parseFloat(bring_forward.bring_forward).toFixed(1));
            }
        }
        });
    }

    function getAdditionalLeave() {
        var user_id = $('#allocationUser').val();
        var category_id = $('#allocationCategory').val();
        
        $.ajax({
        url: '<?php echo base_url('hr/leave/getAdditionalLeave'); ?>',
        type: 'GET',
        data: {
            user_id: '<?php echo $user['id']; ?>',
            category_id: '<?php echo $user['position_category_id']; ?>',
            year: '<?php echo $year; ?>'
        },
        dataType: 'JSON',
        success: (data) => {
            if (data.status.toLowerCase() == 'success') {
                var additional_leave = data.additional_leave;
                console.log(additional_leave);
                $('#annualAdditionalLeave').val(parseFloat(additional_leave.total_additional_leave).toFixed(1));
                // $('#annualAllocation').val((parseFloat($('#annualAdditionalLeave').val()) + parseFloat($('#annualEntitledLeave').val())).toFixed(1));
                $('#annualAllocation').val(parseFloat(additional_leave.leave_allocation).toFixed(1));
            }
        }
        })
    }

    $('#allocationType').change(async function() {
        var type_id = this.value;

        await $.ajax({
            url: '<?php echo base_url('hr/leave/getEntitlementSetup'); ?>',
            type: 'POST',
            data: {
                year : '<?php echo $year; ?>',
                type_id: type_id,
                category_id : '<?php echo $user['position_category_id']; ?>'
            },
            dataType: 'JSON',
            success: (data) => {
                if (data.status.toLowerCase() == 'success') {
                    entitlement = data.entitlement;
                    
                    if(type_id == 1) {
                        $('#entitlementID').val(entitlement.id);
                        $('#annualEntitledLeave').val(entitlement.entitled_leave);
                        // $('#annualAllocation').val(entitlement.entitled_leave);
                    } else {
                        $('#othersEntitledLeave').val(entitlement.entitled_leave);
                        $('#othersBalance').val(entitlement.entitled_leave);
                    }
                }
            }
        })

        if ($(this).val() == 1) {
            $('#annualFormContainer').show();
            $('#othersFormContainer').hide();
        } else {
            $('#annualFormContainer').hide();
            $('#othersFormContainer').show();
        }
    });

    async function openAllocationModal(allocation_id) {
        // clearForm('#userForm');
        clearForm('#allocationForm');
        clearForm('#annualForm');

        $("#allocationModalSubmitBtn").attr("onclick", "createAllocation()");

        $('#annualBringForward').val(parseFloat(0).toFixed(1));
        $('#annualAdditionalLeave').val(parseFloat(0).toFixed(1));
        $('#annualEntitledLeave').val(parseFloat(0).toFixed(1));
        $('#annualAllocation').val(parseFloat(0).toFixed(1));
        $('#annualBringForwardBalance').val(parseFloat(0).toFixed(1));
        $('#annualBalance').val(parseFloat(0).toFixed(1));
        $('#othersEntitledLeave').val(parseFloat(0).toFixed(1));
        $('#othersBalance').val(parseFloat(0).toFixed(1));

        if (allocation_id) {
            $("#allocationModalSubmitBtn").attr("onclick", "updateAllocation(" + allocation_id + ")");

            var allocation;
            
            await $.ajax({
                url: '<?php echo base_url('hr/leave/getAllocation2'); ?>',
                type: 'POST',
                data: {
                    id: allocation_id
                },
                dataType: 'JSON',
                success: (data) => {
                    if (data.status.toLowerCase() == 'success') {
                        allocation = data.allocation;

                        $('#allocationType').val(allocation.type_id).trigger('change').attr('disabled', true);

                        if (allocation.type_id == 1) {
                            $('#annualAllocation').val(allocation.leave_entitled);
                            $('#annualBalance').val(allocation.leave_balance);
                            $('#annualBringForward').val(allocation.bring_forward_entitled);
                            //echo $row['bring_forward_entitled'] - $row['takenB4'];						
                            //$('#annualBringForwardBalance').val(allocation.bring_forward);
                            //$('#annualEntitledLeave').val(allocation.leave_entitled);

                            //start sini
							console.log(allocation); 
                            var bring_forward_entitled = allocation.bring_forward_entitled; //$('#annualBringForward').val(allocation.bring_forward_entitled);
                            var takenB4                = allocation.takenB4; //$('#annualBringForward').val(allocation.takenB4);
                            var balance                = bring_forward_entitled - takenB4;
							if(balance < 0) balance =0;
							console.log(bring_forward_entitled);
							console.log(takenB4); 
							console.log(balance.toFixed(1));  

                            $("#annualBringForwardBalance").val(balance.toFixed(1));
                            $("#annualBringForwardBalance").attr("disabled","disabled");
                            //sampai sini 
                            //$('#annualEntitledLeave').val(allocation.leave_entitled);
                        } else {
                            $('#othersEntitledLeave').val(allocation.leave_entitled);
                            $('#othersBalance').val(allocation.leave_balance);
                        }
                    }
                }
            })
        } else {
            await $.ajax({
            url: '<?php echo base_url('hr/leave/getEntitlementSetup'); ?>',
            type: 'POST',
            data: {
                year : '<?php echo $year; ?>',
                type_id: type_id,
                category_id : '<?php echo $user['position_category_id']; ?>'
            },
            dataType: 'JSON',
            success: (data) => {
                if (data.status.toLowerCase() == 'success') {
                    entitlement = data.entitlement;
                    
                    if(type_id == 1) {
                        $('#entitlementID').val(entitlement.id);
                        $('#annualEntitledLeave').val(entitlement.entitled_leave);
                        $('#annualAllocation').val(entitlement.entitled_leave);
                    } else {
                        $('#othersEntitledLeave').val(entitlement.entitled_leave);
                        $('#othersBalance').val(entitlement.entitled_leave);
                    }
                }
            }
        })
        }

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

    async function createAllocation(type_id) {
        var user_id = $('#allocationUser').val();
        var year = '<?php echo $year; ?>';
        var type_id = $('#allocationType').val();

        var checkAllocation;

        await $.ajax({
            url: "<?php echo base_url('hr/leave/getAllocation'); ?>",
            type: 'POST',
            data: { 'user_id': user_id, 'year': year, 'type_id': type_id },
            dataType: 'JSON',
            success: (data) => {
                console.log(data);
                if (data.allocation) {
                    checkAllocation = false;
                } else {
                    checkAllocation = true;
                }
                
            }
        });

        if (checkAllocation == true) {
            if (type_id == 1) {
                validateForm('#annualForm', 'Are you sure you want to allocate Annual Leave for this user?', () => {
                    $.ajax({
                        url: '<?php echo base_url('hr/leave/createAllocation'); ?>',
                        type: 'POST',
                        data: {
                            user_id: $('#allocationUser').val(),
                            entitlement_id: $('#entitlementID').val(),
                            year: '<?php echo $year; ?>',
                            type_id: $('#allocationType').val(),
                            balance_entitled: $('#annualAllocation').val(),
                            leave_balance: $('#annualBalance').val(),
                            bring_forward_entitled: $('#annualBringForward').val(),
//                            bring_forward: $('#annualBringForwardBalance').val(),
                            leave_entitled: $('#annualEntitledLeave').val()
                        },
                        dataType: 'JSON',
                        success: (data) => {
                            if (data) {
                                localStorage.setItem("status", data.status);
                                localStorage.setItem("msg", data.msg);

                                location.reload();
                            }
                        }
                    })
                })
            } else {
                var leaveTypeName = $('#allocationType').find('option:selected').html();

                validateForm('#allocationForm', 'Are you sure you want to allocate ' + leaveTypeName + ' for this user?', () => {
                    $.ajax({
                        url: '<?php echo base_url('hr/leave/createAllocation'); ?>',
                        type: 'POST',
                        data: {
                            user_id: $('#allocationUser').val(),
                            entitlement_id: $('#entitlementID').val(),
                            year: '<?php echo $year; ?>',
                            type_id: $('#allocationType').val(),
                            balance_entitled: $('#othersEntitledLeave').val(),
                            leave_balance: $('#othersBalance').val(),
                            leave_entitled: $('#othersEntitledLeave').val()
                        },
                        dataType: 'JSON',
                        success: (data) => {
                            if (data) {
                                localStorage.setItem("status", data.status);
                                localStorage.setItem("msg", data.msg);

                                location.reload();
                            }
                        }
                    })
                })
            }
        } else {
            alert('This allocation has already been setup.');
        }
    }

    function updateAllocation(allocation_id) {
        var type_id = $('#allocationType').val();

        if (type_id == 1) {
            validateForm('#annualForm', 'Are you sure you want to update Annual Leave Allocation for this user?', async () => {
                await $.ajax({
                    url: '<?php echo base_url('hr/leave/updateAllocation'); ?>',
                    type: 'POST',
                    data: {
                        id: allocation_id,
                        year: '<?php echo $year; ?>',
                        balance_entitled: $('annualAllocation').val(),
                        leave_balance: $('#annualBalance').val(),
                        bring_forward_entitled: $('#annualBringForward').val(),
//                        bring_forward: $('#annualBringForwardBalance').val(),
                        leave_entitled: $('#annualEntitledLeave').val()
                    },
                    dataType: 'JSON',
                    success: (data) => {
                        if (data) {
                            localStorage.setItem("status", data.status);
                            localStorage.setItem("msg", data.msg);

                            location.reload();
                        }
                    }
                })
            })
        } else {
            validateForm('#allocationForm', 'Are you sure you want to update Leave Allocation for this user?', async () => {
                await $.ajax({
                    url: '<?php echo base_url('hr/leave/updateAllocation'); ?>',
                    type: 'POST',
                    data: {
                        id: allocation_id,
                        balance_entitled: $('#othersEntitledLeave').val(),
                        leave_balance: $('#othersBalance').val(),
                        leave_entitled: $('#othersEntitledLeave').val()
                    },
                    dataType: 'JSON',
                    success: (data) => {
                        if (data) {
                            localStorage.setItem("status", data.status);
                            localStorage.setItem("msg", data.msg);

                            location.reload();
                        }
                    }
                })
            })
        }
    }

    function deleteAllocation(allocation_id) {
        toastConfirm("Are you sure you want to delete this application?", function(){
			$.ajax({
				type: 'POST',
				url: '<?php echo base_url('hr/leave/deleteAllocation'); ?>',
				data: {
					'id' : allocation_id
				},
				dataType: 'JSON',
				success: function(data) {
					if(data.status == 'Success') {
						localStorage.setItem("status",data.status);
						localStorage.setItem("msg",data.msg);

						location.reload();
					}
				}
			});
		});
    }
</script>