<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 form-inline">
                    <div class="input-group">
                        <div class="input-group-prepend">
                            <div class="input-group-text" >Year</div>
                        </div>
                        <input id="allocationYear" type="text" style="width: 100px; text-align: end;" class="form-control" value="<?php echo $selection['year']; ?>" disabled>
                    </div>
                </div>
                <div class="float-right form-inline">
                    <!--type-->
                    <div class="input-group">
                        <select class="form-control" onchange="typeChanged()" id="select-type">
                            <?php foreach ($leaveTypes as $lt) { ?>
                                <option value="<?php echo $lt['id']; ?>" 
                                <?php
                                if ($selection['type'] && $selection['type'] == $lt['id'])
                                    echo ' selected ';
                                ?>
                                        ><?php echo $lt['name']; ?></option>
<?php } ?>                       
                        </select>
                    </div>
                    <!--department filter-->
                    <div class="input-group ml-2">
                        <div class="input-group-prepend">
                            <label class="input-group-text" for="select-department">Department</label>
                        </div>                        
                        <select id="select-department" class="custom-select">
                            <option value="">All departments</option>
                            <?php foreach ($departments as $dept) { ?>
                                <option value="<?php echo $dept['id']; ?>"
                                <?php
                                if ($selection['department'] && $selection['department'] == $dept['id'])
                                    echo ' selected ';
                                ?>                                
                                        ><?php echo $dept['name']; ?> (<?php echo $dept['branch_name']; ?>)</option>
<?php } ?>
                        </select> 
                    </div>
                    <!--position filter-->
                    <div class="input-group ml-2">
                        <div class="input-group-prepend">
                            <label class="input-group-text" for="select-position">Position</label>
                        </div>
                        <select id="select-position" class="custom-select">
                            <option value="">All positions</option>
                            <?php foreach ($positions as $pos) { ?>
                                <option value="<?php echo $pos['id']; ?>"
                                <?php
                                if ($selection['position'] && $selection['position'] == $pos['id'])
                                    echo ' selected ';
                                ?>                                        
                                        ><?php echo $pos['position']; ?></option>
<?php } ?>                            
                        </select>                        
                    </div>
                    <!--status filter-->
                    <div class="input-group ml-2">
                        <div class="input-group-prepend">
                            <label class="input-group-text" for="select-status">Status</label>
                        </div>
                        <select id="select-status" class="custom-select">
                            <!--                            <option value="">All statuses</option>
                                                        <option value="1">Allocated</option>
                                                        <option value="2">Unallocated</option>-->
<?php foreach ($statuses as $sK => $sV) { ?>
                                <option value="<?php echo $sK; ?>" <?php if ($sK == $selection['status']) echo 'selected' ?>><?php echo $sV ?></option>
<?php } ?>
                        </select>                        
                    </div>                    
                    <div class="input-group ml-2">
                        <button class="btn btn-primary" type="button" onclick="filter()">
                            <i class="fas fa-filter"></i>
                        </button>                        
                    </div>                   
                </div>
            </div>
            <div class="card-body">
                <!--view only noti-->
                <?php
                if($selection['year'] < date('Y')){
                    $viewOnly = true;
                    echo '<div class="card no-shadow mb-2 bg-info"><div class="card-body">';
                    echo '<div class="text-white text-center">View-only mode. Allocation for this year no longer possible</div>';
                    echo '</div></div>';
                }elseif (in_array($selection['type'], ['7','8'])) {
                    $viewOnly = true;
                    echo '<div class="card no-shadow mb-2 bg-info"><div class="card-body">';
                    echo '<div class="text-white text-center">View-only mode. Allocation for this leave type can only be done on its own sub module page</div>';
                    echo '</div></div>';
                } else {
                    $viewOnly = false;
                }
                ?>
                <!--leave details-->
                <div class="card no-shadow mb-2">
                    <div class="card-body">
                        <?php
                        $typeTK = array_search($selection['type'], array_column($leaveTypes, 'id'));
                        if (gettype($typeTK) == 'integer') {
                            echo '<div><span style="display:inline-block;width:50px;background-color:' . $leaveTypes[$typeTK]['colour'] . ';text-align:center;" class="mr-3">' . $leaveTypes[$typeTK]['code'] . '</span>' . $leaveTypes[$typeTK]['description'] . '</div>';
                        }
                        ?>
                    </div>
                </div>
                <!--staff-->
                <div class="card no-shadow">
                    <div class="card-body">
                        <div class="table-responsive">
                            <table id="tblStaff" class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th style="width:4%;">
                                            <input type="checkbox" style="line-height: normal; margin: 0;" <?php if ($viewOnly) echo 'disabled'; ?>
                                                   name="checkAll" id="checkAll">
                                        </th>
                                        <th style="width:8%; text-align: center;">Type Allocated</th>
                                        <th style="width:6%;">Staff ID</th>
                                        <th>Staff Name & Date Joined</th>
                                        <th>Department & Position</th>
                                        <!-- <th class="text-center" style="width:5%;">Position Entitlement</th> -->
                                        <th class="text-center" style="width:8%;">Date From</th>
                                        <th class="text-center" style="width:8%;">Date To</th>
                                        <th class="text-center" style="width:12%;">Total Entitled</th>
                                        <th class="text-center" style="width:12%;">Current Allocation</th>
                                        <th class="text-center" style="width:8%;">Leave Taken</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if ($all_staff): ?>
                                        <?php foreach ($all_staff as $staff) {
                                            $typeArr = explode(',', $staff['type_id']); ?>
                                            <tr id="staff-row-<?php echo $staff['id']; ?>"
                                                data-staff="<?php echo htmlspecialchars(json_encode($staff), ENT_QUOTES, 'UTF-8'); ?>"
                                                 data-allocation="<?php echo $staff['curr_allocation_id']; ?>">
                                                <!-- staff id -->
                                                <td>
                                                    <input type="checkbox" class="checkbox"
                                                           style="line-height: normal; margin: 0;"
                                                           id="checkbox-<?php echo $staff['id']; ?>" 
                                                           <?php if ($viewOnly) echo 'disabled="true"  data-trigger="hover" data-tooltip="tooltip" title="View-only mode"'; ?>
                                                           <?php if ($selection['type'] == 18 && (date('Y', strtotime($staff['date_joined'])) == $selection['year'])) echo 'disabled="true"  data-trigger="hover" data-tooltip="tooltip" title="Not entitled for current year allocation"'; ?>
                                                           >
                                                </td>
                                                <td>
                                                    <?php
                                                    if ($staff['type_id']) {
                                                        foreach ($typeArr as $sti) {
                                                            $k = array_search($sti, array_column($leaveTypes, 'id'));
                                                            echo '<a href="" data-toggle="tooltip" title="' . $leaveTypes[$k]['name'] . '" style="color: #000;"><span class="badge badge-pill mr-1" style="background-color:' . $leaveTypes[$k]['colour'] . '">' . $leaveTypes[$k]['code'] . '</span></a>';
                                                        }
                                                    }
                                                    ?>
                                                </td>
                                                <td><?php echo $staff['staff_id'] ?></td>
                                                <!-- staff name and date joined -->
                                                <td>
                                                    <p style="padding:0;margin:0">
                                                        <?php echo strtoupper($staff['name']); ?>
                                                    </p>
                                                    <?php if ($staff['date_joined']) { ?>
                                                        <p style="padding:0;margin:0" class="text-muted">
                                                        <?php
                                                        echo date('d/m/Y', strtotime($staff['date_joined']));
                                                        if ($staff['date_termination'])
                                                            echo ' (till ' . date('d/m/Y', strtotime($staff['date_termination'])) . ')';
                                                        ?>
                                                        </p>
                                                    <?php } ?>
                                                    <?php if (in_array($selection['type'], [5, 9, 11])) { ?>
                                                        <p style="padding:0;margin:0;font-size: smaller;" class="text-muted font-italic">
                                                        <?php if ($staff['marital_status']) echo $maritalStatuses[$staff['marital_status']]; ?>  
                                                        <span class="ml-1">
                                                        <?php if($staff['gender_id'] > 0) echo ($staff['gender_id'] == 1 ? '<i class="fas fa-mars"></i>' : '<i class="fas fa-venus"></i>'); ?>  
                                                        </span>
                                                        </p>
                                                        <p style="padding:0;margin:0">
                                                        <?php if ($staff['spouse_count'] > 0) { ?>
                                                            <button class="btn btn-sm btn-light mb-1" type="button" data-trigger="hover" data-tooltip="tooltip" title="Spouse">
                                                                <i class="fas fa-heart"></i> <span class="badge badge-light"><?php echo $staff['spouse_count'] ?></span>
                                                            </button>
                                                        <?php } ?>
                                                        <?php if ($staff['children_count'] > 0) { ?>
                                                            <button class="btn btn-sm btn-light mb-1" type="button" data-trigger="hover" data-tooltip="tooltip" title="Children">
                                                                <i class="fas fa-child"></i> <span class="badge badge-light"><?php echo $staff['children_count'] ?></span>
                                                            </button>
                                                        <?php } ?>
                                                        <?php if ($staff['other_family_count'] > 0) { ?>
                                                            <button class="btn btn-sm btn-light mb-1" type="button" data-trigger="hover" data-tooltip="tooltip" title="Other family members">
                                                                <i class="fas fa-home"></i> <span class="badge badge-light"><?php echo $staff['other_family_count'] ?></span>
                                                            </button>
                                                        <?php } ?>
                                                        </p>
                                                    <?php } ?>
                                                </td>
                                                <!-- department and position -->
                                                <td>
                                                    <p style="padding:0;margin:0">
                                                        <?php echo $staff['department_name'] ?>    
                                                        <?php if ($staff['branch_name']) echo '<br>(' . $staff['branch_name'] . ')' ?>
                                                    </p>
                                                    <p style="padding:0;margin:0" class="text-muted">
                                                        <?php echo $staff['position_name']; ?>
                                                    </p>
                                                    <?php if($selection['type'] == 10){ ?>
                                                    <p style="padding:0;margin:0" class="text-muted font-italic">
                                                        <span style="font-size: smaller;"><?php echo $staff['employee_group_name'] . ' ' . $staff['employee_contract_type_name']; ?></span>
                                                    </p>
                                                    <?php } ?>
                                                </td>
                                                <!-- position entitlement-->
                                                <!-- <td nowrap>
                                                    <input style="width:80px;" disabled type="number" step="0.5"
                                                           class="form-control text-right"
                                                           value="<?php echo number_format($staff['entitled_leave'], 1); ?>">
                                                </td> -->

                                                <!--date from and to. with global expiry and without-->
                                                <?php if($selection['type'] == 18){?>
                                                <td>
                                                    <!-- default start -->
                                                    <input data-ori-value="<?php echo date('d-m-Y', strtotime(date('Y', strtotime($selection['year'])) . '-01-01'));
                                                            ?>" 
                                                            readonly="true" id="date-from-<?php echo $staff['id']; ?>" required type="text" class="form-control leave_date" name="dateOn" value="
                                                            <?php echo date('d-m-Y', strtotime(date('Y', strtotime($selection['year'])) . '-01-01'));
                                                            ?>
                                                            ">
                                                </td>
                                                <td>
                                                    <!-- global expiry or resign date whichever come first -->
                                                    <input data-ori-value="<?php echo ($staff['date_termination'] && strtotime($staff['date_termination']) < strtotime($selection['year'] . '-03-31')) ?
                                                                   date('d-m-Y', strtotime($staff['date_termination'])) : date('d-m-Y', strtotime($selection['year'] . '-03-31'));
                                                           ?>" 
                                                           readonly="true" id="date-to-<?php echo $staff['id']; ?>" required type="text" class="form-control leave_date" name="dateOn" value="
                                                           <?php echo ($staff['date_termination'] && strtotime($staff['date_termination']) < strtotime($selection['year'] . '-03-31')) ?
                                                                   date('d-m-Y', strtotime($staff['date_termination'])) : date('d-m-Y', strtotime($selection['year'] . '-03-31'));
                                                           ?>
                                                           ">
                                                </td>
                                                <?php } else { ?>
                                                <!--if join current year, set date_from to date_joined. else 1/1/year-->
                                                <td>
                                                    <input data-ori-value="<?php echo (($staff['date_joined'] && date('Y', strtotime($selection['year'])) == date('Y', strtotime($staff['date_joined']))) ?
                                                        date('d-m-Y', strtotime($staff['date_joined'])) : date('d-m-Y', strtotime(date('Y', strtotime($selection['year'])) . '-01-01')));
                                                        ?>" 
                                                           readonly="true" id="date-from-<?php echo $staff['id']; ?>" required type="text" class="form-control leave_date" name="dateOn" value="
                                                           <?php echo (($staff['date_joined'] && date('Y', strtotime($selection['year'])) == date('Y', strtotime($staff['date_joined']))) ?
                                                                   date('d-m-Y', strtotime($staff['date_joined'])) : date('d-m-Y', strtotime(date('Y', strtotime($selection['year'])) . '-01-01')));
                                                           ?>
                                                           ">
                                                </td>
                                                <!--if resign current year, set date_to to date_termination. else 31/12/year-->
                                                <td>
                                                    <input data-ori-value="<?php echo ($staff['date_termination'] ?
                                                                   date('d-m-Y', strtotime($staff['date_termination'])) : date('d-m-Y', strtotime(date('Y', strtotime($selection['year'])) . '-12-31')));
                                                           ?>" 
                                                           readonly="true" id="date-to-<?php echo $staff['id']; ?>" required type="text" class="form-control leave_date" name="dateOn" value="
                                                <?php echo ($staff['date_termination'] ?
                                                        date('d-m-Y', strtotime($staff['date_termination'])) : date('d-m-Y', strtotime(date('Y', strtotime($selection['year'])) . '-12-31')));
                                                ?>
                                                           ">
                                                </td>
                                                <?php } ?>

                                                <!-- Study leave only -->
                                                <?php //if ($selection['type'] == 7) { ?>
                                                <!-- <td nowrap><input disabled type="number" step="0.5"
                                                                      class="form-control text-right"
                                                                      value="<?php //echo number_format($staff['exam_count'], 0); ?>">
                                                </td>                                         -->
                                                <?php //} ?>

                                                <!-- total entitled-->
                                                <td nowrap class="text-right">
                                                    <div class="form-inline text-right">
                                                        <input id="total-entitled-<?php echo $staff['id'] ?>" style="width:80px;" disabled type="number" step="0.5"
                                                               class="form-control text-right"
                                                               value="<?php echo number_format($staff['leave_allocation'], 1); ?>"
                                                               data-ori-value="<?php echo number_format($staff['leave_allocation'], 1); ?>">
                                                        <?php if (!$viewOnly) { ?>
                                                        <button
                                                            id="info-btn-<?php echo $staff['id'] ?>"
                                                            class="btn btn-primary ml-2" type="button" data-trigger="hover"
                                                            data-tooltip="tooltip" title="Show Calculation"
                                                            onclick="showCalcModal(<?php echo $staff['id']; ?>);" style="width: 40px;">
                                                            <i class="fas fa-info-circle"></i>
                                                        </button>
                                                        <?php } ?> 
                                                    </div>
                                                </td>

                                                <!-- current allocation -->
                                                <td class="text-right">
                                                    <div class="form-inline">
                                                               <?php if (!$viewOnly && !$staff['curr_leave']) { ?>
                                                            <button id="copy-btn-<?php echo $staff['id']; ?>" disabled class="btn btn-primary mr-2 copy-btn" type="button" data-trigger="hover"
                                                                    data-tooltip="tooltip" title="Copy from Total Entitled" style="width: 40px;">
                                                                <i class="fas fa-angle-double-right"></i>
                                                            </button>  
                                                               <?php } ?>  
                                                        <input style="width:80px;" id="leave-<?php echo $staff['id']; ?>" disabled type="number"
                                                               step="0.5" class="form-control text-right leave-allocation"
        <?php
        echo (($staff['leave_max_entitlement'] && $staff['leave_max_entitlement'] != 0) ? ('max="' . number_format($staff['leave_max_entitlement'], 1) . '"') : ('max="' . number_format(365, 1) . '"'));
        ?>
                                                               value="<?php
//                                                echo ($staff['curr_leave'] ? number_format($staff['curr_leave'], 1) : number_format($staff['leave_allocation'], 1)); 
                                                echo ($staff['curr_leave'] ? number_format($staff['curr_leave'], 1) : number_format(0, 1));
                                                ?>" data-ori-value="<?php
                                                        echo ($staff['curr_leave'] ? number_format($staff['curr_leave'], 1) : number_format(0, 1));
                                                        ?>">
        <?php if ($staff['type_id']) { ?>
            <?php $tk = array_search($selection['type'], $typeArr);
            if (gettype($tk) == 'integer') { ?>
                                                                <button class="btn btn btn-success ml-2" type="button" data-trigger="hover"
                                                                        data-tooltip="tooltip" title="Allocated" style="width: 40px;">
                                                                    <i class="fas fa-check"></i>
                                                                </button>                                                 
            <?php } else { ?>
                                                                <button class="btn btn-danger ml-2" type="button" data-trigger="hover"
                                                                        data-tooltip="tooltip" title="Unallocated" style="width: 40px;">
                                                                    <i class="fas fa-times"></i>
                                                                </button>                                            
                                                                   <?php } ?>  
                                                               <?php } else { ?>
                                                            <button class="btn btn-danger ml-2" type="button" data-trigger="hover"
                                                                    data-tooltip="tooltip" title="Unallocated" style="width: 40px;">
                                                                <i class="fas fa-times"></i>
                                                            </button>
                                                        <?php } ?>                                                
                                                    </div>
                                                    <input type="hidden" id="current-allocation-id-<?php echo $staff['id']; ?>" value="<?php if($staff['curr_allocation_id']){ echo $staff['curr_allocation_id']; } ?>">
                                                </td>                                        
                                                <!-- leave taken -->
                                                <td>
                                                    <input  disabled type="number" step="0.5"
                                                               class="form-control text-right"
                                                               value="<?php echo ($staff['curr_taken'] ? number_format($staff['curr_taken'], 1) : number_format(0, 1)); ?>">
                                                </td>
                                            </tr>
    <?php } ?>
<?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="saveAllocation2()" <?php if ($viewOnly) echo 'disabled'; ?>>Save</button>
                </div>
            </div>
        </div>
    </form>
</section>

<!--show calculation model-->
<div class="modal fade" id="calcModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <div>
                    <p style="padding:0;margin:0;font-size:large">Allocation Calculation</p>
                    <p style="padding:0;margin:0;font-size:smaller" class="text-muted" id="cm-type"></p>
                    <p style="padding:0;margin:5px 0 0 0;font-size:smaller" class="text-muted" id="cm-name"></p>
                </div>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <nav>
                    <div class="nav nav-tabs" id="nav-tab" role="tablist">
                        <a class="nav-link active" id="nav-main-tab" data-toggle="tab" href="#nav-main" role="tab" aria-controls="nav-main" aria-selected="true">Main</a>
                        <a class="nav-link" id="nav-history-tab" data-toggle="tab" href="#nav-history" role="tab" aria-controls="nav-history" aria-selected="false">History</a>
                    </div>
                </nav>
                <div class="tab-content" id="nav-tabContent">
                    <div class="tab-pane fade show active" id="nav-main" role="tabpanel" aria-labelledby="nav-main-tab">
                        <!--year-->
                        <div class="row mt-3">
                            <div class="col-8"> 
                                <label for="year-in">
                                    <p style="padding: 0; margin: 0">Year</p>
                                </label>
                            </div>
                            <div class="col-4">
                                <div class="form-group">
                                    <input disabled type="text" required data-parsley-error-message="Max Entitlement is required." 
                                           class="form-control text-right" id="year-in" placeholder="Year">
                                </div>
                            </div>
                        </div>
                        <!--max entitlement-->
                        <div class="row">
                            <div class="col-8"> 
                                <label for="max-entitlement-in">
                                    <p style="padding: 0; margin: 0">Max Entitlement</p>
                                    <p style="padding: 0; margin: 0; font-size: smaller; font-style: italic" class="text-muted">
                                        Total entitlement and allocation cannot exceed this value
                                    </p>
                                </label>
                            </div>
                            <div class="col-4">
                                <div class="form-group">
                                    <input disabled type="text"  required 
                                           class="form-control text-right" id="max-entitlement-in" placeholder="0">
                                </div>
                            </div>
                        </div>
                        <!--position entitlement-->
                        <div class="row">
                            <div class="col-8"> 
                                <label for="position-entitlement-in">
                                    <p style="padding: 0; margin: 0">Position Entitlement</p>
                                    <p style="padding: 0; margin: 0; font-size: smaller;" class="text-muted" id="position-entitlement-lbl"></p>
                                </label>
                            </div>
                            <div class="col-4">
                                <div class="form-group">
                                    <input disabled type="text"  required  
                                           class="form-control text-right" id="position-entitlement-in" placeholder="0">
                                </div>
                            </div>
                        </div>
                        <!--leave entitled-->
                        <div class="row">
                            <div class="col-8"> 
                                <label for="eligible-entitlement-in">
                                    <p style="padding: 0; margin: 0">Leave Entitled</p>
                                    <p style="padding: 0; margin: 0; font-size: smaller;" class="text-muted" id="eligible-entitlement-lbl"></p>
                                    <?php if($leaveTypes[$typeTK]['is_prorate'] == 1){ ?>
                                    <p style="padding: 0; margin: 0; font-size: smaller; font-style: italic" class="text-muted" >
                                        Rounded to the nearest integer
                                    </p>
                                    <?php } ?>
                                </label>
                            </div>
                            <div class="col-4">
                                <div class="form-group">
                                    <input disabled type="text"  required 
                                           class="form-control text-right" id="eligible-entitlement-in" placeholder="0">
                                </div>
                            </div>
                        </div>
                        <!--additional leave - length of service-->
                        <div class="row">
                            <div class="col-8"> 
                                <label for="los-in">
                                    <p style="padding: 0; margin: 0">Additional From Length of Service</p>
                                    <p style="padding: 0; margin: 0; font-size: smaller;" class="text-muted" id="los-lbl"></p>
                                    <p style="padding: 0; margin: 0; font-size: smaller; font-style: italic" class="text-muted" id="los-extra"></p>
                                </label>
                            </div>
                            <div class="col-4">
                                <div class="form-group">
                                    <input disabled type="text"  required
                                           class="form-control text-right" id="los-in" placeholder="0">
                                </div>
                            </div>
                        </div>
                        <!--total entitled-->
                        <div class="row">
                            <div class="col-8"> 
                                <label for="los-in">
                                    <p style="padding: 0; margin: 0; font-weight: bold;">Total Entitled</p>
                                </label>
                            </div>
                            <div class="col-4">
                                <div class="form-group">
                                    <input style="font-weight: bold;" disabled type="text"  
                                        class="form-control text-right" id="total-in" placeholder="0">
                                </div>
                            </div>
                        </div>
                        <!--bf-->
                        <?php if($leaveTypes[$typeTK]['is_bring_forward'] == 1){ ?>
                        <div class="row">
                            <div class="col-8"> 
                                <label for="bf-in">
                                    <p style="padding: 0; margin: 0">Bring Forward Entitled</p>
                                    <p style="padding: 0; margin: 0; font-size: smaller; font-style: italic" class="text-muted" >
                                        Max number of leave (<?php echo $staff['leave_bring_forward_percentage']; ?> % of total entitled) that can be carried forward to next year. Rounded to the nearest integer
                                    </p>
                                </label>
                            </div>
                            <div class="col-4">
                                <div class="form-group">
                                    <input  disabled type="text"  
                                        class="form-control text-right" id="bf-in" placeholder="0">
                                </div>
                            </div>
                        </div>
                        <?php } ?>
                    </div>
                    <div class="tab-pane fade" id="nav-history" role="tabpanel" aria-labelledby="nav-history-tab">
                        <div class="history-head mt-3">
                            <div class="row">
                                <div class="col-1 font-weight-bold text-left">Year</div>
                                <div class="col-2 font-weight-bold">Allocated</div>
                                <div class="col-2 font-weight-bold">Taken</div>
                                <div class="col-2 font-weight-bold">Balance</div>
                                <div class="col-5 font-weight-bold text-right">BF Available / Entitled</div>
                            </div>
                        </div>
                        <div id="history-data">
                            
                        </div>
                        <!-- dependee history table. hardcoded for now until leave setup/setting page complete -->
                        <?php if($selection['type'] == 18){ ?>
                            <div class="history-head mt-3">
                                <span class="font-weight-bold" style="text-decoration: underline;">Dependee: Annual Leave</span>  <!--hardcoded for now until leave setup/setting page complete-->
                                <div class="row">
                                    <div class="col-1 font-weight-bold text-left">Year</div>
                                    <div class="col-2 font-weight-bold">Allocated</div>
                                    <div class="col-2 font-weight-bold">Taken</div>
                                    <div class="col-2 font-weight-bold">Balance</div>
                                    <div class="col-5 font-weight-bold text-right">BF Available / Entitled</div>
                                </div>
                            </div>
                            <div id="dependee-history-data">
                                
                            </div>
                        <?php } ?>
                    </div>
                </div>
            </div>
<!--            <div class="modal-footer">
                <div class="float-left mr-auto">
                    <p style="padding: 0; margin: 0; font-weight: bold;">Total Entitled</p>
                </div>
                <div class="float-right">
                    <input style="font-weight: bold;width: 140px" disabled type="text"  
                           class="form-control text-right" id="total-in" placeholder="0">
                </div>
            </div>-->
        </div>
    </div>
</div>

<!-- loader modal -->
<div class="modal fade" id="loader-modal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-body text-center">
                <div class="spinner-border" role="status" style="text-align: center;">
                </div>
                <div class="h5">
                    Processing...
                </div>
            </div>
        </div>
    </div>
</div>

<!--show allocation detail modal-->
<div class="modal fade" id="allocation-detail-modal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="allocation-modal-title">Allocation Details</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>
    // leaveTypes
    // typeTK
    var startDate = moment(['<?php echo $selection['year']; ?>']).startOf('year').format('DD-MM-YYYY');
    var endDate = moment(['<?php echo $selection['year']; ?>']).endOf('year').format('DD-MM-YYYY');
    var loaded = false;
    var selection = <?php echo json_encode($selection) ?>;
    var leaveTypes = <?php echo json_encode($leaveTypes) ?>;
    var typeTK = <?php echo json_encode($typeTK) ?>;

    $(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');
        })

        $(".leave_date").datepicker({
            uiLibrary: 'bootstrap4',
            format: 'dd-mm-yyyy',
            autoclose: true,
            changeMonth: true,
            changeYear: true,
            startDate: startDate,
            endDate: endDate,
            enableOnReadonly: false
        });

        $(".leave_date").each(function () {
            $(this).datepicker('setDate', $(this).val());
            $(this).datepicker().on('changeDate', function () {
                var staff = $(this).closest('tr').data('staff');
                if (loaded) {
                    date1 = (($('#date-from-' + staff.id).val()).split('-')).reverse();
                    date2 = (($('#date-to-' + staff.id).val()).split('-')).reverse();
                    if (new Date(date2.join('-')) <= new Date(date1.join('-'))) {
                        alert('Date From must be before Date To. Values will revert');
                        $('#date-from-' + staff.id).datepicker('update', $('#date-from-' + staff.id).data('ori-value'));
                        $('#date-to-' + staff.id).datepicker('update', $('#date-to-' + staff.id).data('ori-value'));
                    } else {
                        recalculateTotalEntitled();
                    }
                }
            });
        });

        loaded = true;

//        $("#date-from-539").datepicker({
//            showOn: "button",
//            format: 'dd-mm-yyyy',
//            buttonImage: "https://jqueryui.com/resources/demos/datepicker/images/calendar.gif",
//            buttonImageOnly: true,
//            buttonText: "Select date",
//            startDate: startDate,
//            endDate: endDate
//        });

        test();

    })

    function test(){
        let v1 = $('#date-from-18').val();
        let v2 = $('#date-to-18').val();
        let userId = <?php echo $this->logged_user['id']; ?>;
        console.log('dates for user id 18: ' + moment(v1, 'DD-MM-YYYY').format('YYYY-MM-DD') + ' ' + moment(v2, 'DD-MM-YYYY').format('YYYY-MM-DD'));
        console.log('by: ' + userId);
        console.log('on: ' + moment().format('YYYY-MM-DD HH:mm:ss'));
    }

    $(".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").not(':disabled').prop('checked', true).change();
        } else {
            $(".checkbox").prop('checked', false).change();
        }
    })

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

        if (this.checked) {

            $('#leave-' + staff.id).prop('disabled', false);
            $('#copy-btn-' + staff.id).prop('disabled', false);
            $('#date-from-' + staff.id).prop('readonly', false);
            $('#date-to-' + staff.id).prop('readonly', false);
        } else {
            $(this).prop('checked', false);

            $('#leave-' + staff.id).prop('disabled', true);
            $('#copy-btn-' + staff.id).prop('disabled', true);
            $('#date-from-' + staff.id).prop('readonly', true);
            $('#date-to-' + staff.id).prop('readonly', true);
            $('#leave-' + staff.id).val($('#leave-' + staff.id).data('ori-value'));
            $('#date-from-' + staff.id).datepicker('update', $('#date-from-' + staff.id).data('ori-value'));
            $('#date-to-' + staff.id).datepicker('update', $('#date-to-' + staff.id).data('ori-value'));
        }
    });

    $('.leave-allocation').change(function () {
        var staff = $(this).closest('tr').data('staff');
        if (staff.leave_max_entitlement && staff.leave_max_entitlement != 0 && parseFloat($(this).val()) > parseFloat(staff.leave_max_entitlement)) {
            alert(`Current Allocation cannot exceed Max Entitlement (${staff.leave_max_entitlement} days). Values will revert`);
            $('#leave-' + staff.id).val($('#leave-' + staff.id).data('ori-value'));
        } else if (parseFloat($(this).val()) > 365) {
            alert(`Current Allocation cannot exceed 365 days. Values will revert`);
            $('#leave-' + staff.id).val($('#leave-' + staff.id).data('ori-value'));
        }

    });

    $('.copy-btn').click(function () {
        var staff = $(this).closest('tr').data('staff');
        $('#leave-' + staff.id).val($('#total-entitled-' + staff.id).val());
    });



    function typeChanged() {

    }

    function recalculateTotalEntitled(ele) {
        console.log('recalculating...');
    }

    function filter() {
        reqType = $('#select-type').val();
        reqYear = $('#allocationYear').val();
        reqDepartment = $('#select-department').val();
        reqPosition = $('#select-position').val();
        reqStatus = $('#select-status').val();
//        alert(`type: ${reqType} year: ${reqYear} dept: ${reqDepartment} pos: ${reqPosition}`);
        baseUrl = '<?php echo base_url('/hr/leave/allocation'); ?>';
        url = `?year=${reqYear}&type=${reqType}`;
        if (reqDepartment)
            url += `&department=${reqDepartment}`;
        if (reqPosition)
            url += `&position=${reqPosition}`;
        if (reqStatus)
            url += `&status=${reqStatus}`;
//        alert(baseUrl + url);
        window.location.replace(baseUrl + url);
    }

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

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

        if (staff) {
            console.log(JSON.stringify(staff));
            console.log(selection);

            $('#cm-name').html(staff.name.toUpperCase());
            $('#cm-type').html(leaveTypes[typeTK].name);
            $('#year-in').val(selection.year);
            $('#position-entitlement-lbl').html(staff.position_category);
            $('#position-entitlement-in').val(staff.entitled_leave ? parseFloat(staff.entitled_leave).toFixed(1) : '0.0');
            $('#eligible-entitlement-lbl').html(
                    'From ' + ((staff.date_joined).includes(selection.year) ? (moment(staff.date_joined).format('DD-MM-YYYY') + ' (joined)') : $('#date-from-' + staff.id).val()) +
                    ' to ' + ((staff.date_termination) ? (moment(staff.date_termination).format('DD-MM-YYYY') + ' (detach)') : $('#date-to-' + staff.id).val())
                    );
            $('#eligible-entitlement-in').val((staff.leave_elligible) ? (parseFloat(staff.leave_elligible).toFixed(1)) : '0.0');
            $('#los-lbl').html(`Date joined: ${moment(staff.date_joined).format('DD-MM-YYYY')}`);
            $('#los-extra').html(`Additional ${staff.leave_additional_leave_per_cycle} day(s) every ${staff.leave_month_cycle} months`);
            $('#los-in').val(staff.additional_leave ? parseFloat(staff.additional_leave).toFixed(1) : '0.0');
            $('#total-in').val((staff.leave_allocation) ? (parseFloat(staff.leave_allocation).toFixed(1)) : '0.0');
            $('#max-entitlement-in').val(staff.leave_max_entitlement ? parseFloat(staff.leave_max_entitlement).toFixed(1) : '0.0');
            if(leaveTypes[typeTK].is_bring_forward){
                console.log('bf');
                $('#bf-in').val(parseFloat(floorToFraction((parseFloat(staff.leave_allocation) * parseInt(staff.leave_bring_forward_percentage) / 100), true, 2)).toFixed(1));   
            }

            $('#history-data').empty();
            $.ajax({
                url: "<?php echo base_url('hr/leave/getUserAllocations'); ?>",
                type: "POST",
                data: {
                    user_id: staff.id,
                    type_id: selection.type,
                    year_limit: selection.year
                },
                dataType: "JSON",
                success: (data) => {
                    console.log(JSON.stringify(data));
                    if(data.status == 'success' && data.data.length > 0){
                        data.data.forEach(alloc => {
                            $('#history-data').append(`
                            <div class="row mt-1">
                                <div class="col-1 text-left">${alloc.year}</div>
                                <div class="col-2 text-right">${alloc.leave_entitled}</div>
                                <div class="col-2 text-right">${alloc.leave_taken}</div>
                                <div class="col-2 text-right">${alloc.leave_balance}</div>
                                <div class="col-5 text-right">${alloc.bring_forward} / ${alloc.bring_forward_entitled}</div>
                            </div>
                            `);
                        });
                    }else{
                        $('#history-data').append(`
                            <div class="row mt-1">
                                <div class="col-12 text-center">No data available</div>
                            </div>
                        `);
                    }
                },
                error: (jqXHR, textStatus, errorThrown) => {
                    console.log('ajax error');
                    console.log(textStatus);
                    console.log(errorThrown);
                }
            });

            // load dependee history table. hardcoded for now until leave setup/setting page complete
            if(selection.type == 18){
                $('#dependee-history-data').empty();
                $.ajax({
                url: "<?php echo base_url('hr/leave/getUserAllocations'); ?>",
                type: "POST",
                data: {
                    user_id: staff.id,
                    type_id: 1, // hardcoded for now until leave setup/setting page complete
                    year_limit: selection.year
                },
                dataType: "JSON",
                success: (data) => {
                    console.log(JSON.stringify(data));
                    if(data.status == 'success' && data.data.length > 0){
                        data.data.forEach(alloc => {
                            $('#dependee-history-data').append(`
                            <div class="row mt-1">
                                <div class="col-1 text-left">${alloc.year}</div>
                                <div class="col-2 text-right">${alloc.leave_entitled}</div>
                                <div class="col-2 text-right">${alloc.leave_taken}</div>
                                <div class="col-2 text-right">${alloc.leave_balance}</div>
                                <div class="col-5 text-right">${alloc.bring_forward} / ${alloc.bring_forward_entitled}</div>
                            </div>
                            `);
                        });
                    }else{
                        $('#dependee-history-data').append(`
                            <div class="row mt-1">
                                <div class="col-12 text-center">No data available</div>
                            </div>
                        `);
                    }
                },
                error: (jqXHR, textStatus, errorThrown) => {
                    console.log('ajax error');
                    console.log(textStatus);
                    console.log(errorThrown);
                }
            });
            }

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

    function showAllocationDetailModal(id) {
        $('#allocation-detail-modal').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?", () => {

    //         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: $('#leave-' + 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;
    //             }
    //         })
    //     })
    // }
    
    // handle both create and update
    function saveAllocation2() {
        toastConfirm("Are you sure you want to save Leave Allocation?", () => {

            $('#loader-modal').modal('show');

            var year = selection.year;
            var createData = [];
            var updateData = [];

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

                if(currentAllocationId){
                    // update
                    let bfEntitled = 0;
                    let bfBalance = 0;
                    if(leaveTypes[typeTK].is_bring_forward == 1){
                        //bfEntitled = parseFloat($('#leave-' + staff.id).val()) * parseInt(staff.leave_bring_forward_percentage) / 100;
                        bfEntitled = parseFloat(floorToFraction((parseFloat($('#leave-' + staff.id).val()) * parseInt(staff.leave_bring_forward_percentage) / 100), true, 2)).toFixed(1);
                    }
                    updateData.push({
                        id: currentAllocationId,
                        user_id: staff.id,
                        year: selection.year,
                        date_from: moment($('#date-from-' + staff.id).val(), 'DD-MM-YYYY').format('YYYY-MM-DD'),
                        date_to: moment($('#date-to-' + staff.id).val(), 'DD-MM-YYYY').format('YYYY-MM-DD'),
                        expiry_date: moment($('#date-to-' + staff.id).val(), 'DD-MM-YYYY').format('YYYY-MM-DD'),
                        type_id: selection.type,
                        leave_entitled: parseFloat($('#leave-' + staff.id).val()).toFixed(1),
                        bring_forward_entitled: bfEntitled, // update bring_forward on db site relative to their current value there
                        updated_by: <?php echo $this->logged_user['id']; ?>,
                        updated_ts: moment().format('YYYY-MM-DD HH:mm:ss')
                    });
                }else{
                    // create
                    let bfEntitled = 0;
                    let bfBalance = 0;
                    if(leaveTypes[typeTK].is_bring_forward == 1){
                        //bfEntitled = parseFloat($('#leave-' + staff.id).val()) * parseInt(staff.leave_bring_forward_percentage) / 100;
                        bfEntitled = parseFloat(floorToFraction((parseFloat($('#leave-' + staff.id).val()) * parseInt(staff.leave_bring_forward_percentage) / 100), true, 2)).toFixed(1);
                    }
                    createData.push({
                        user_id: staff.id,
                        entitlement_id: staff.entitlement_id,
                        year: selection.year,
                        date_from: moment($('#date-from-' + staff.id).val(), 'DD-MM-YYYY').format('YYYY-MM-DD'),
                        date_to: moment($('#date-to-' + staff.id).val(), 'DD-MM-YYYY').format('YYYY-MM-DD'),
                        expiry_date: moment($('#date-to-' + staff.id).val(), 'DD-MM-YYYY').format('YYYY-MM-DD'),
                        type_id: selection.type,
                        leave_entitled: parseFloat($('#leave-' + staff.id).val()).toFixed(1),
                        bring_forward_entitled: bfEntitled, 
                        bring_forward: bfEntitled,
                        leave_taken: 0,
                        balance_entitled: parseFloat($('#leave-' + staff.id).val()).toFixed(1),
                        leave_balance: parseFloat($('#leave-' + staff.id).val()).toFixed(1),
                        created_by: <?php echo $this->logged_user['id']; ?>,
                        created_ts: moment().format('YYYY-MM-DD HH:mm:ss'),
                        updated_by: <?php echo $this->logged_user['id']; ?>,
                        updated_ts: moment().format('YYYY-MM-DD HH:mm:ss')
                    });
                }
                
            });

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

                    window.location.replace(window.location.href);
                },
                error: (jqXHR, textStatus, errorThrown) => {
                    console.log('ajax error');
                    console.log(textStatus);
                    console.log(errorThrown);
                },
                complete: (xhr,status) => {
                    $("#loader-modal").modal('hide');
                }
            })
        })
    }
    
    
    function floorToFraction(someVal, standardRound, denom = 2, useCeil = true){
        if(standardRound){
            x = Math.round(someVal);
        }else{
            x = someVal * denom;
            x = (useCeil ? (Math.ceil(x)) : (Math.floor(x)));
            x = x / denom;   
        }
        return x;
    }
</script>