<!--hr/views/leave/allocationUserlist-->

<style>
    .text-divider {
        margin: 10px 0px;
        display: flex;
        align-items: center;
        --text-divider-gap: 1rem;
        font-size: smaller;
    }

    .text-divider::before,
    .text-divider::after {
        content: '';
        height: 1px;
        background-color: silver;
        flex-grow: 1;
    }

    .text-divider::before {
        margin-right: var(--text-divider-gap);
    }

    .text-divider::after {
        margin-left: var(--text-divider-gap);
    }

</style>

<section class="container-fluid" style="padding-bottom: 2rem;">
    <div class="card bg-light-transparent">
        <div class="card-header bg-white">
            <div class="float-right">
                <div class="btn-group btn-group-sm">
                    <a target="_blank" href="<?php echo base_url('hr/leave/reports_entitlement/' . ($year + 1)); ?>"><button class="btn btn-outline-dark btn-sm"><i class="fas fa-print"></i> Print List</button></a>
                </div>
            </div>
        </div>
        <div class="card-body">
            <div class="card no-shadow">
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table display responsive table-striped">
                            <thead>
                            <th>Staff ID</th>
                            <th>Name & Position</th>
                            <th>Department & Branch</th>
                            <?php foreach ($leave_types as $type): ?>
                                <th data-trigger="hover" data-tooltip="tooltip" title="<?php echo $type['name']; ?>"><?php echo $type['code']; ?></th>
                            <?php endforeach; ?>
<!-- <th>Action</th> -->
                            </thead>
                            <tbody>
                                <?php if (isset($users)): foreach ($users as $user): ?>
                                        <tr>
                                            <td><?php echo $user['staff_id']; ?></td>
                                            <td nowrap><a href="<?php echo base_url('hr/leave_v2/allocation/' . $year . '/' . $user['department_id'] . '/' . $user['id']); ?>"><?php echo $user['name']; ?></a><br>
                                                <?php
                                                echo $user['position_name'];
                                                echo (!empty($user['position_category'])) ? '<br>[' . $user['position_category'] . ']' : '';
                                                ?></td>
                                            <td><a href="<?php echo base_url('hr/leave_v2/allocation/' . $year . '/' . $user['department_id']); ?>"><?php echo $user['department_name']; ?></a><br>
                                                <?php echo $user['branch_name']; ?></td>
                                            <?php foreach ($leave_types as $type): ?>
                                                <?php
                                                if (in_array($type['id'], explode(',', $user['type_id']))) {
                                                    // if($type['id'] == 7){ //study leave_v2
                                                    //   echo '<td><a href="javascript:openStudyLeaveAllocation('. $user['id'].','. $type['id'].','. $user['allocations'][$type['id']].');" class="text-success" ><i class="fas fa-check"></i></a></td>';
                                                    // }else{
                                                    //   echo '<td><a href="javascript:openAllocationModal('. $user['id'].','. $type['id'].','. $user['allocations'][$type['id']].');" class="text-success"><i class="fas fa-check"></i></a></td>';
                                                    // }
                                                    if($user['allocations'][$type['id']][1] == 1){
                                                        echo '<td><a href="javascript:openAllocationModal(' . $user['id'] . ',' . $type['id'] . ',' . $user['allocations'][$type['id']][0] . ');" class="text-success"><i class="fas fa-check"></i></a></td>';
                                                    }else{
                                                        echo '<td><a href="javascript:openAllocationModal(' . $user['id'] . ',' . $type['id'] . ',' . $user['allocations'][$type['id']][0] . ');" class="text-warning"><i class="fas fa-exclamation"></i></a></td>';
                                                    }
//                                                    echo '<td><a href="javascript:openAllocationModal(' . $user['id'] . ',' . $type['id'] . ',' . $user['allocations'][$type['id']][0] . ');" class="text-success"><i class="fas fa-check"></i></a></td>';
                                                } else {
                                                    // if($type['id'] == 7){ //study leave
                                                    //   echo '<td><a href="javascript:openStudyLeaveAllocation('. $user['id'].','. $type['id'].');" class="text-danger" ><i class="fas fa-times"></i></a></td>';
                                                    // }else{
                                                    //   echo '<td><a href="javascript:openAllocationModal('. $user['id'].','. $type['id'].');" class="text-danger"><i class="fas fa-times"></i></a></td>';
                                                    // }
                                                    echo '<td><a href="javascript:openAllocationModal(' . $user['id'] . ',' . $type['id'] . ');" class="text-danger"><i class="fas fa-times"></i></a></td>';
                                                }
                                                ?>
                                            <?php endforeach; ?>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!--newYearModal-->
<div class="modal fade" id="newYearModal">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="application-modal-title">New Year 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">

            </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="newYearAllocationModalSubmitBtn" onclick="createNewYearAllocation();" class="btn btn-light">Save</button>
                </div>
            </div>
        </div>
    </div>
</div>

<!--allocationModal-->
<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">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">
                <!--hidden values-->
                <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>

                <!--type, year, entitlement-->
                <div class="form-row">
                    <div class="col-md-4 mb-1">
                        <div class="input-group mr-sm-2">
                            <div class="input-group-prepend">
                                <div class="input-group-text">Year</div>
                            </div>
                            <input id="allocationYear" class="form-control" disabled value="<?php echo $year; ?>">
                        </div>
                    </div>
                    <div class="col-md-4 mb-1">
                        <div class="input-group mr-sm-2">
                            <div class="input-group-prepend">
                                <div class="input-group-text">Type</div>
                            </div>
                            <select id="allocationType" required data-parsley-error-message="Type is required." name="allocationType" class="custom-select" >
                                <option value="-1">Select Type</option>
                                <?php foreach ($types as $type): ?>
                                    <option value="<?php echo $type['id']; ?>"><?php echo $type['name']; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-4 mb-1">
                        <div class="input-group mr-sm-2">
                            <div class="input-group-prepend">
                                <div class="input-group-text">Entitlement</div>
                            </div>
                            <input id="allocationEntitlement" class="form-control" disabled value="">
                        </div>
                    </div>
                </div>

                <div class="text-divider text-muted">STAFF</div>

                <!--name-->
                <div class="form-row">
                    <div class="col-md-12 mb-3">
                        <div class="input-group mr-sm-2">
                            <div class="input-group-prepend">
                                <div class="input-group-text">Name</div>
                            </div>
                            <select id="allocationUser" required data-parsley-error-message="User is required." name="allocationUser" class="custom-select">
                                <option value="-1">Select Staff</option>
                                <?php foreach ($users as $user): ?>
                                    <option value="<?php echo $user['id']; ?>"><?php echo $user['name']; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                </div>

                <!--dept-->
                <div class="form-row">
                    <div class="col-md-12 mb-3">
                        <div class="input-group mr-sm-2">
                            <div class="input-group-prepend">
                                <div class="input-group-text">Department</div>
                            </div>
                            <select id="allocationDepartment" required data-parsley-error-message="Department is required." name="allocationDepartment" disabled class="custom-select">
                                <option value="-1">Select Department</option>
                                <?php foreach ($departments as $dept): ?>
                                    <option value="<?php echo $dept['id']; ?>"><?php echo $dept['name'] . " (" . $dept['branch_name'] . ")"; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                </div>

                <!--category, date join-->
                <div class="form-row">
                    <div class="col-md-6 mb-1">
                        <div class="input-group mr-sm-2">
                            <div class="input-group-prepend">
                                <div class="input-group-text">Category</div>
                            </div>
                            <select id="allocationCategory" required data-parsley-error-message="Category is required." name="allocationCategory" disabled class="custom-select">
                                <option value="-1">Select Category</option>
                                <?php foreach ($categories as $cat): ?>
                                    <option value="<?php echo $cat['id']; ?>"><?php echo $cat['position']; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6 mb-1">
                        <div class="input-group mr-sm-2">
                            <div class="input-group-prepend">
                                <div class="input-group-text">Date Joined</div>
                            </div>
                            <input id="allocationDateJoined" class="form-control" disabled value="">
                        </div>
                    </div>
                </div>

                <div class="text-divider text-muted">ALLOCATION</div>

                <div class="form-row">
                    <!--input-->
                    <div class="col-md-9">
                        <form class="form" id="annualForm">
                            <!--date-->
                            <div class="form-row">
                                <div class="col-md-4 mb-3">
                                    <div class="input-group mr-sm-2">
                                        <div class="input-group-prepend">
                                            <div class="input-group-text">From</div>
                                        </div>
                                        <input required data-parsley-error-message="Date From is required." type="text" class="form-control datepicker" id="dateFrom" placeholder="From date">
                                    </div>
                                </div> 
                                <div class="col-md-4 mb-3">
                                    <div class="input-group mr-sm-2">
                                        <div class="input-group-prepend">
                                            <div class="input-group-text">To</div>
                                        </div>
                                        <input required data-parsley-error-message="Date To is required." type="text" class="form-control datepicker" id="dateTo" placeholder="To date">
                                    </div>
                                </div> 
                                <div class="col-md-4 mb-3">
                                    <div class="input-group mr-sm-2">
                                        <div class="input-group-prepend">
                                            <div class="input-group-text">Expiry</div>
                                        </div>
                                        <input required data-parsley-error-message="Date Expiry is required." type="text" class="form-control datepicker" id="dateExpiry" placeholder="Expiry date">
                                    </div>
                                </div>
                            </div>
                            <!--entitled, allocation-->
                            <div class="form-row">
                                <div class="col-md-6 mb-3">
                                    <div class="input-group mr-sm-2">
                                        <div class="input-group-prepend">
                                            <div class="input-group-text">Entitled Leave</div>
                                        </div>
                                        <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 class="col-md-6 mb-3">
                                    <div class="input-group mr-sm-2">
                                        <div class="input-group-prepend">
                                            <div class="input-group-text">Leave Allocation</div>
                                        </div>
                                        <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> 
                            </div>
                            <!--balance, carry forward allowed-->
                            <div class="form-row">
                                <div class="col-md-6 mb-3">
                                    <div class="input-group mr-sm-2">
                                        <div class="input-group-prepend">
                                            <div class="input-group-text">Current Balance</div>
                                        </div>
                                        <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 class="col-md-6 mb-3">
                                    <div class="input-group mr-sm-2">
                                        <div class="input-group-prepend">
                                            <div class="input-group-text">Carry Forward Allowed</div>
                                        </div>
                                        <input type="number" class="form-control text-right" id="carry_forward_allow">
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>

                    <!--history-->
                    <div class="col-md-3">
                        <div class="form-group text-center" style="background-color: #e7e7e7; border-radius: 5px; padding: 5px;">
                            <label class="text-right">History</label>
                            <ul id="previousyearallocation" class="" style="list-style:none;"></ul>
                        </div>
                    </div>
                </div>
                <!--                <div class="modal-footer">
                <?php //if(balance > 0 && is_bring_forward == 1) {   ?>
                                    <div class="float-left" id="Carry_forward_button" style="margin-right: auto;">
                                        button type="button" id="carryForwardBtn" class="btn btn-primary" onclick="do_bring_forward()">Close Allocation & Carry Forward Balance</button
                                    </div><?php //}                                ?>
                                    <div class="float-right">
                                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                                        <button type="button" id="allocationModalSubmitBtn" class="btn btn-primary">Save</button>
                                    </div>
                                </div>-->
            </div>
            <div class="modal-footer">
                <?php //if(balance > 0 && is_bring_forward == 1) {   ?>
                <div class="float-left" id="Carry_forward_button" style="margin-right: auto;">
                    <!--button type="button" id="carryForwardBtn" class="btn btn-primary" onclick="do_bring_forward()">Close Allocation & Carry Forward Balance</button-->
                </div><?php //}                                ?>
                <div class="float-right">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="button" id="allocationModalSubmitBtn" class="btn btn-primary">Save</button>
                </div>
            </div>
        </div>
    </div>
</div>
<!--<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">
                <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="row">
                    <div class="col-8"><form class="form" id="annualForm">
                            <div class="form-group form-inline">
                                <label for="allocationUser" class="col-sm-2 text-right">Name</label>
                                <div class="col">
                                    <select id="allocationUser" required data-parsley-error-message="User is required." name="allocationUser" class="select" style="width: 100% !important;">
                                        <option value="-1">Select Staff</option>
<?php foreach ($users as $user): ?>
                                                                                                                                                                    <option value="<?php echo $user['id']; ?>"><?php echo $user['name']; ?></option>
<?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group form-inline">
                                <label for="allocationDepartment" class="col-sm-2 text-right">Department</label>
                                <div class="col">
                                    <select id="allocationDepartment" required data-parsley-error-message="Department is required." name="allocationDepartment" disabled class="select" style="width: 100% !important;">
                                        <option value="-1">Select Department</option>
<?php foreach ($departments as $dept): ?>
                                                                                                                                                                    <option value="<?php echo $dept['id']; ?>"><?php echo $dept['name'] . " (" . $dept['branch_name'] . ")"; ?></option>
<?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group form-inline">
                                <label for="allocationCategory" class="col-sm-2 text-right">Category</label>
                                <div class="col">
                                    <select id="allocationCategory" required data-parsley-error-message="Category is required." name="allocationCategory" disabled class="select" style="width: 100% !important;">
                                        <option value="-1">Select Category</option>
<?php foreach ($categories as $cat): ?>
                                                                                                                                                                    <option value="<?php echo $cat['id']; ?>"><?php echo $cat['position']; ?></option>
<?php endforeach; ?>
                                    </select>
                                </div>
                            </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): ?>
                                                                                                                                                                    <option value="<?php echo $type['id']; ?>"><?php echo $type['name']; ?></option>
<?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            <hr>
                            <div class="form-row">
                                <div class="col-4 form-group">
                                    <label for="dateFrom" >Date From</label>
                                    <input required data-parsley-error-message="Date From is required." type="text" class="form-control datepicker" id="dateFrom" placeholder="From">
                                </div> <div class="col-4 form-group">
                                    <label for="dateTo" >Date To</label>
                                    <input required data-parsley-error-message="Date To is required." type="text" class="form-control datepicker" id="dateTo" placeholder="To">
                                </div> <div class="col-4 form-group">
                                    <label for="dateExpiry" >Date Expiry</label>
                                    <input required data-parsley-error-message="Date Expiry is required." type="text" class="form-control datepicker" id="dateExpiry" placeholder="Date Expired">
                                </div>
                            </div>
                            <hr>
                            <div class="form-row">
                                <div class="form-group form-inline">
                                    <label for="annualEntitledLeave" class="col-sm-2 text-right">Entitled Leave</label>
                                    <div class="col">
                                        <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 class="form-group form-inline">
                                    <label for="annualAllocation" class="col-sm-2 text-right">Leave Allocation</label>
                                    <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>
                            </div>
                            <hr>
                            <div class="form-group form-inline">
                                <label for="annualBalance" class="col-sm-2 text-right">Current Balance</label>
                                <div class="col">
                                    <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>
                                <label for="annualBalance" class="col-sm-2 text-right">Carry Foward Allowed</label>
                                <div class="col-2 text-center">
                                    <label id="carry_forward_allow">0.0</label>
                                </div>
                            </div>
                    </div>
                    </form>
                    <div class="col-4">
                        <div class="form-group form-inline">
                            <label id="datejoin" class="text-right">Date Join: </label>
                        </div>
                        <div class="form-group form-inline">
                            <label id="userentitlement" class="text-right">Current Entitlement: </label>
                        </div>
                        <div class="form-group">
                            <label class="text-right">Allocation History</label>
                            <ul id="previousyearallocation" class="" style="list-style:none;"></ul>
                        </div>
                         do loop year allocation here
                        <hr>
                        <div class="form-group form-inline">
                            <label id="leaveTaken" class="text-right">Leave Taken :</label>
                        </div>
                        <div class="form-group form-inline">
                            <label id="leavePending" class="text-right">Leave Pending:</label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
<?php //if(balance > 0 && is_bring_forward == 1) {   ?>
                    <div class="btn-group float-left" id="Carry_forward_button">
                        button type="button" id="carryForwardBtn" class="btn btn-primary" onclick="do_bring_forward()">Close Allocation & Carry Forward Balance</button
                    </div><?php //}                                ?>
                    <div class="btn-group float-right">
                        <button type="button" class="btn btn-light" data-dismiss="modal">Cancel</button>
                        <button type="button" id="allocationModalSubmitBtn" class="btn btn-primary">Save</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>-->

<script>

    $(function () {

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

        $('#allocationType').change(function () {
            var type = $(this).find('option:selected').html();
//            $('#allocation-modal-title').html('<?php echo $year; ?>\'s ' + type + ' Allocation');

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

        $('#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() {
        var user_id = $('#allocationUser').val();
        var category_id = $('#allocationCategory').val();

        $.ajax({
            url: '<?php echo base_url('hr/leave/getBringForward'); ?>',
            type: 'GET',
            data: {
                user_id: user_id,
                category_id: 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 do_bring_forward() {
    }

    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: user_id,
                category_id: 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));
                }
            }
        })
    }

    function openStudyLeaveAllocation(user_id, type_id, allocation_id) {
        window.open('<?php echo base_url() . 'leave/studyLeaveAllocation/' ?>' + user_id + '/7/' + allocation_id, '_blank');
    }

    async function openAllocationModal(user_id, type_id, allocation_id) {
//    clearForm('#allocationForm');
        clearForm('#annualForm');

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

        (user_id) ? $('#allocationUser').val(user_id).trigger('change').attr('disabled', true) : $('#allocationUser').val('-1').trigger('change').attr('disabled', false);
        (type_id) ? $('#allocationType').val(type_id).trigger('change').attr('disabled', true) : $('#allocationType').val('-1').trigger('change').attr('disabled', false);

        $('#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));
        $('#carry_forward_allow').val(parseFloat(0).toFixed(1));


        var user;
        var entitlement;

        /**
         step 1:
         - dapatkan maklumat peribadi staff
         */
        await $.ajax({
            url: '<?php echo base_url('hr/leave/getUserDetail'); ?>',
            type: 'POST',
            data: {
                id: user_id
            },
            dataType: 'JSON',
            success: (data) => {
                console.log('yang ni patut sampai mula2');
                if (data.status.toLowerCase() == 'success') {
                    user = data.user;
                    $('#allocationDepartment').val(user.department_id).trigger('change');
                    $('#allocationCategory').val(user.position_category_id).trigger('change');
//                    $('#datejoin').text('Date Join: ' + user.date_joined);
                    $('#allocationDateJoined').val(moment(user.date_joined).format('DD-MM-YYYY'));

                }
            }
        })

        /* *
         step 2:
         - dapatkan default value
         1. category id
         2. min month of service
         3. month of service add leave
         4. additional leave
         5. max entitlement
         6. bring forward percentage
         7. entitled leave
         */
        await $.ajax({
            url: '<?php echo base_url('hr/leave_v2/AJAX_getEntitlementSetup'); ?>',
            type: 'POST',
            data: {
                year: '<?php echo $year; ?>',
                type_id: type_id,
                category_id: user.position_category_id
            },
            dataType: 'JSON',
            success: (data) => {
                console.log('yang ni patut sampai kedua ' + data.sql);
                if (data.status.toLowerCase() == 'success') {
                    entitlement = data.entitlement;
                    console.log(entitlement);
                    $('#entitlementID').val(entitlement.id);
                    $('#annualEntitledLeave').val(entitlement.entitled_leave);
//              $('#annualAllocation').val(entitlement.entitled_leave);
//                    $('#userentitlement').text('Entitlement: ' + entitlement.entitled_leave);
                    $('#allocationEntitlement').val(entitlement.entitled_leave);
                } else {
                    $('#entitlementID').val('');
                    $('#annualEntitledLeave').val(0);
//              $('#annualAllocation').val(0);
//                    $('#userentitlement').text('Entitlement: No Entitlement');
                    $('#allocationEntitlement').val('No Entitlement');
                }
            }
        })


        /**
         step 3:
         - kalau ada allocation yang ni run untuk replace step 2
         */
        if (allocation_id)
        {
            $("#allocationModalSubmitBtn").attr("onclick", "updateAllocation(" + allocation_id + ")");

            var allocation;

            /**
             step 4:
             - run untuk replace step 2.
             */
            await $.ajax({
                url: '<?php echo base_url('hr/leave_v2/AJAX_getAllocation'); ?>',
                type: 'POST',
                data: {
                    id: allocation_id
                },
                dataType: 'JSON',
                success: (data) => {
                    console.log('yang ni patut sampai ketiga ' + data.sql);
                    if (data.status.toLowerCase() == 'success') {
                        // allocation = data.allocation; //asal
                        allocation = data.allocation[0];

                        console.log('allocation value untuk staff : ' + data.sql);
                        console.log(allocation);
//                        $('#dateFrom').val(moment(allocation.date_from).format('DD-MM-YYYY'));
//                        $('#dateFrom').val(moment((allocation.date_from == null || allocation.date_from == '0000-00-00') ? (new Date().getFullYear() + '-01-01') : allocation.date_from).format('DD-MM-YYYY'));
                        $('#dateFrom').val(((allocation.date_from == null || allocation.date_from == '0000-00-00') ? '' : moment(allocation.date_from).format('DD-MM-YYYY')));
//                        $('#dateTo').val(moment(allocation.date_to).format('DD-MM-YYYY'));
//                        $('#dateTo').val(moment((allocation.date_to == null || allocation.date_to == '0000-00-00') ? (new Date().getFullYear() + '-12-31') : allocation.date_to).format('DD-MM-YYYY'));
                        $('#dateTo').val(((allocation.date_to == null || allocation.date_to == '0000-00-00') ? '' : moment(allocation.date_to).format('DD-MM-YYYY')));
//                        $('#dateExpiry').val(moment(allocation.expiry_date).format('DD-MM-YYYY'));
//                        $('#dateExpiry').val(moment((allocation.expiry_date == null || allocation.expiry_date == '0000-00-00') ? (new Date().getFullYear() + '-12-31') : allocation.expiry_date).format('DD-MM-YYYY'));
                        $('#dateExpiry').val(((allocation.expiry_date == null || allocation.expiry_date == '0000-00-00') ? '' : moment(allocation.expiry_date).format('DD-MM-YYYY')));
                        $('#annualBringForward').val(allocation.bring_forward_entitled);
                        $('#annualBringForwardBalance').val(allocation.bring_forward);
                        $('#annualEntitledLeave').val(allocation.leave_entitled);
                        $('#annualAllocation').val(allocation.balance_entitled);
                        $('#leaveTaken').text('Leave Taken: ' + allocation.leave_taken);
                        $('#leavePending').text('Leave Pending: ' + allocation.pending);
                        $('#annualBalance').val(allocation.leave_balance);
//                        $('#carry_forward_allow').html(allocation.carry_forward_allow);
                        $('#carry_forward_allow').val(parseFloat(allocation.carry_forward_allow).toFixed(1));
                        if (allocation.leave_balance > 0 && allocation.is_bring_forward > 0)
                            $('#Carry_forward_button').html('<button type="button" id="carryForwardBtn" class="btn btn-info" onclick="do_bring_forward()">Close Allocation & Carry Forward Balance</button>');
                        else
                            $('#Carry_forward_button').html('');

                        /* *
                         step 5:
                         - $('#annualEntitledLeave').val(allocation.leave_entitled);
                         - yang ni replaced value untuk annual leave
                         - 2019/09/18
                         : dapat report allocation untuk aswad salah sebab statement ni dikomen.
                         - persoalan kenapa dikomen?
                         */
                    }
                }
            })
        }

        //previous years allocation(allocation history)
        await $.ajax({
            url: '<?php echo base_url('hr/leave_v2/AJAX_getAllocationHistory'); ?>',
            type: 'POST',
            data: {
                user_id: user_id,
                type_id: type_id
            },
            dataType: 'JSON',
            success: (data) => {
                console.log('AJAX_getAllocationHistory' + data.sql);
                console.log(data.rsAllocationHistory);
                $('#previousyearallocation').html('');
                if (data.status.toLowerCase() == 'success') {
                    if (data.rsAllocationHistory.length > 0) {
                        $.each(data.rsAllocationHistory, function (index, value) {
                            $('#previousyearallocation').append('<li class="text-muted"><i>' + value.year + ' : ' + value.leave_entitled + '<i></li>');
                        });
                    } else {
                        $('#previousyearallocation').append('<li class="text-muted"><i>Not available<i></li>');
                    }

                } else {
                    $('#previousyearallocation').append('<li class="text-muted"><i>Not available<i></li>');
                }

            }
        })

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

    function createAllocation(type_id) {
//			if (type_id == 1) {

        var dateTo = moment($('#dateTo').val(), 'DD-MM-YYYY').format('YYYY-MM-DD');
        var dateFrom = moment($('#dateFrom').val(), 'DD-MM-YYYY').format('YYYY-MM-DD');
        var expiryDate = moment($('#dateExpiry').val(), 'DD-MM-YYYY').format('YYYY-MM-DD');

        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(),
                    date_from: dateFrom,
                    date_to: dateTo,
                    expiry_date: expiryDate,
                },
                dataType: 'JSON',
                success: (data) => {
                    if (data) {
                        localStorage.setItem("status", data.status);
                        localStorage.setItem("msg", data.msg);

                        location.reload();
                    }
                }
            })
        })
        /*      } else { //use only one way of allocation. akmal
         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();
         }
         }
         })
         })
         } */
    }

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

        var dateTo = moment($('#dateTo').val(), 'DD-MM-YYYY').format('YYYY-MM-DD');
        var dateFrom = moment($('#dateFrom').val(), 'DD-MM-YYYY').format('YYYY-MM-DD');
        var expiryDate = moment($('#dateExpiry').val(), 'DD-MM-YYYY').format('YYYY-MM-DD');

        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(),
                    date_from: dateFrom,
                    date_to: dateTo,
                    expiry_date: expiryDate,
                },
                dataType: 'JSON',
                success: (data) => {
                    if (data) {
                        console.log(data.data);
                        localStorage.setItem("status", data.status);
                        localStorage.setItem("msg", data.msg);
                        $('#allocationModal').modal('hide');
//                location.reload();
                    }
                }
            })
        });
    }

    function deleteAllocation(allocation_id) {

    }

    function newYearAllocation() {

    }

</script>