<!--hr/views/leave/allocationUserlist_print--><section class="container-fluid" style="padding-bottom: 2rem;">
  <div class="card bg-light-transparent">
    <div class="card-header bg-white">
      <!-- <div class="float-left">
        <button class="btn btn-outline-dark btn-sm"><i class="fa fa-plus"></i> New Year Setup</button>
      </div> -->
<?php /*      <div class="float-right">
        <div class="btn-group btn-group-sm">
          <!-- <button id="btnShowFilters" type="button" class="btn btn-outline-dark btn-sm" data-toggle="collapse" data-target="#collapseFilter"><i class="fas fa-filter"></i> Show Filters</button> -->
          <button class="btn btn-outline-dark btn-sm"><i class="fas fa-print"></i> Print List</button>
        </div>
      </div-->
    </div> */ ?>
    <div class="card-body">
      <div class="card no-shadow">
        <div class="card-body">
          <div class="table-responsive">
            <!--table class="responsive table-striped"-->
			<table border="0" cellpadding="1" cellspacing="0" width="100%">
              <thead>
                <th>ID</th>
                <th>Staff Name</th>
                <th>Position</th>
                <th>Department</th>
                <th>Balance Previous Year</th> 
                <?php foreach ($leave_types as $type): ?>
                  <?php if($type['id'] != 2 && $type['id'] != 4): ?>
                    <th data-trigger="hover" data-tooltip="tooltip" title="<?php echo $type['name']; ?>"><?php echo $type['code']; ?></th>
                  <?php endif; ?>
                <?php endforeach; ?>
                <!--th>Action</th-->
              </thead>
              <tbody>
                <?php if(isset($users)): ?>
                  <?php foreach($users as $user): ?>
                    <tr>
                      <td><?php echo $user['staff_id']; ?></td>
                      <td nowrap><a href="<?php echo base_url('hr/leave/allocation/'.$year.'/'.$user['department_id'].'/'.$user['id']); ?>"><?php echo $user['name']; ?></a></td>
                      <td><?php echo $user['position_name']; ?> [<?php echo $user['position_category']; ?>]</td>
                      <td><a href="<?php echo base_url('hr/leave/allocation/'.$year.'/'.$user['department_id']); ?>"><?php echo $user['department_name']; ?></a></td>
                      <?php echo '<td>'.$this->model_leave->getUsersLeaveAllocationDayByYears(array('year'=>$year-1,'user_id'=>$user['id'],'leave_type_id'=>1)).' </td>';
                       foreach ($leave_types as $type): 
                        
						if($type['id'] != 2 && $type['id'] != 4) {
							echo '<td>'.$this->model_leave->getUsersLeaveAllocationDayByYears(array('year'=>$year,'user_id'=>$user['id'],'leave_type_id'=>$type['id'])).'</td>';
/*							if(in_array($type['id'],explode(',',$user['type_id']))) {
								echo '<td><a href="javascript:openAllocationModal('. $user['id'].','. $type['id'].','. $user['type_id'].');" class="text-success"><i class="fas fa-check"></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>';
							} */
						}  ?>
                      <?php endforeach; ?>
                      <!--td>
                        <div class="btn-group btn-group-sm">
                          <button class="btn btn-primary"><i class="fas fa-print"></i></button>
                          <button class="btn btn-danger"><i class="fas fa-trash"></i></button>
                        </div>
                      </td-->
                    </tr>
                  <?php endforeach; ?>
                <?php endif; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>
<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>
<div class="modal fade" id="allocationModal">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="allocation-modal-title"><?php echo $year; ?> Leave Allocation</h5>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
              <form class="form" id="userForm">
                <div class="form-group form-inline" hidden>
                    <label for="allocationID" class="col-sm-2 text-right">Allocation ID</label>
                    <input id="allocationID" name="allocationID" class="form-control col" type="text">
                </div>
                <div class="form-group form-inline" hidden>
                    <label for="entitlementID" class="col-sm-2 text-right">Entitlement ID</label>
                    <input id="entitlementID" name="entitlementID" class="form-control col" type="text">
                </div>
                <div class="form-group form-inline">
                  <label for="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): ?>
                        <?php if ($type['id'] != 2 && $type['id'] != 4): ?>
                          <option value="<?php echo $type['id']; ?>"><?php echo $type['name']; ?></option>
                        <?php endif; ?>
                      <?php endforeach; ?>
                    </select>
                  </div>
                </div>
              </form>
              <hr>
              <div id="annualFormContainer">
                <form class="form" id="annualForm">
                  <div class="row">
                    <div class="col-4"> 
                      <label for="annualBringForward">Bring Forward</label>
                    </div>
                    <div class="col-2">
                      <button type="button" class="btn btn-sm btn-primary" id="getBringForwardBtn" onclick="getBringForward();">GET</button>
                    </div>
                    <div class="col">
                      <div class="form-group">
                        <input type="number" step="0.5" required data-parsley-error-message="Bring Forward is required." class="form-control text-right" name="annualBringForward" id="annualBringForward" placeholder="Bring Forward">
                      </div>
                    </div>
                  </div>
                  <hr>
                  <div class="row">
                    <div class="col-4"> 
                      <label for="annualAdditionalLeave">Additional Leave</label>
                    </div>
                    <div class="col-2">
                      <button type="button" class="btn btn-sm btn-primary" id="getAdditionalLeaveBtn" onclick="getAdditionalLeave();">GET</button>
                    </div>
                    <div class="col">
                      <div class="form-group">
                        <input type="number" step="0.5" required data-parsley-error-message="Max Entitlement is required." class="form-control text-right" name="annualAdditionalLeave" id="annualAdditionalLeave" placeholder="Additional Leave">
                      </div>
                    </div>
                  </div>
                  <div class="row">
                    <div class="col">
                        <label for="annualEntitledLeave">Entitled Leave</label>
                    </div>
                    <div class="col">       
                      <div class="form-group">
                        <input type="number" step="0.5" required data-parsley-error-message="Entitled Leave is required." class="form-control text-right" name="annualEntitledLeave" id="annualEntitledLeave" placeholder="Entitled Leave">
                      </div>
                    </div>
                  </div>
                  <div class="row">
                    <div class="col"> 
                      <label for="annualAllocation">Leave Allocation</label>
                    </div>
                    <div class="col">
                      <input type="number" step="0.5" required data-parsley-error-message="Allocation is required." class="form-control text-right" name="annualAllocation" id="annualAllocation" placeholder="Leave Allocation">
                    </div>
                  </div>
                  <hr>
                  <div class="form-row">
                    <div class="col">
                      <div class="form-group">
                        <label for="annualBringForwardBalance">Bring Forward Balance</label>
                        <input type="number" step="0.5" required data-parsley-error-message="Bring Forward Balance is required." class="form-control text-right" name="annualBringForwardBalance" id="annualBringForwardBalance" placeholder="Leave Allocation">
                      </div>
                    </div>
                    <div class="col">
                      <div class="form-group">
                        <label for="annualBalance">Current Balance</label>
                        <input type="number" step="0.5" required data-parsley-error-message="Allocation Balance is required." class="form-control text-right" name="annualBalance" id="annualBalance" placeholder="Leave Balance">
                      </div>
                    </div>
                  </div>
                </form>
              </div>
              <div id="othersFormContainer">
                <form class="form" id="allocationForm">
                  <div class="form-row">
                    <div class="col">
                      <div class="form-group">
                        <label for="othersEntitledLeave">Entitled Leave</label>
                        <input type="text" required data-parsley-error-message="Entitled Leave is required." class="form-control text-right" name="othersEntitledLeave" id="othersEntitledLeave" placeholder="Entitled Leave">
                      </div>
                    </div>
                    <div class="col">
                      <div class="form-group">
                        <label for="othersBalance">Starting Balance</label>
                        <input type="text" required data-parsley-error-message="Percentage is required." class="form-control text-right" name="othersBalance" id="othersBalance" placeholder="Bring Forward Percentage">
                      </div>
                    </div>
                </form>
              </div>
            </div>
            <div class="modal-footer">
              <div class="btn-group float-right">
                <button type="button" class="btn btn-primary" data-dismiss="modal">Cancel</button>
                <button type="button" id="allocationModalSubmitBtn" class="btn btn-light">Save</button>
              </div>
            </div>
        </div>
    </div>
</div>
<script>
  $(function() {
    $('#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 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));
        }
      }
    })
  }

  async function openAllocationModal(user_id, type_id, allocation_id) {
    clearForm('#userForm');
    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));

    var user;
    var entitlement;

    // get user detail
    await $.ajax({
      url: '<?php echo base_url('hr/leave/getUserDetail'); ?>',
        type: 'POST',
        data: {
          id : user_id
        },
        dataType: 'JSON',
        success: (data) => {
          if (data.status.toLowerCase() == 'success') {
            user = data.user;
            $('#allocationDepartment').val(user.department_id).trigger('change');
            $('#allocationCategory').val(user.position_category_id).trigger('change');
          }
        }
    })

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

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

      var allocation;
      
      await $.ajax({
        url: '<?php echo base_url('hr/leave/getAllocation'); ?>',
        type: 'POST',
        data: {
          id : allocation_id
        },
        dataType: 'JSON',
        success: (data) => {
          if (data.status.toLowerCase() == 'success') {
            allocation = data.allocation;
            
            if (allocation.type_id == 1) {
              $('annualAllocation').val(allocation.balance_entitled);
              $('#annualBalance').val(allocation.leave_balance);
              $('#annualBringForward').val(allocation.bring_forward_entitled);
              $('#annualBringForwardBalance').val(allocation.bring_forward);
              $('#annualEntitledLeave').val(allocation.leave_entitled);
            } else {
              $('#othersEntitledLeave').val(allocation.leave_entitled);
              $('#othersBalance').val(allocation.leave_balance);
            }
          }
        }
      })
    }
    
    $('#allocationModal').modal('show');
  }

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

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

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

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

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

                location.reload();
              }
            }
          })
        })
      } else {

      }
  }

  function deleteAllocation(allocation_id) {

  }

  function newYearAllocation() {
    
  }

  // function calcTime() {
  //   var a = "12:30am";
  //   var b = "1:30pm";

  //   var startTime = moment(a, "HH:mmA");
  //   var endTime = moment(b, "HH:mmA");
  //   var refreshment = moment.duration(20, 'm');

  //   var duration = moment.duration(endTime.diff(startTime)).subtract(refreshment);
    
  //   var durationHrs = parseInt(duration.asHours());

  //   // round down to nearest half hour
  //   var durationMin = ((parseInt(duration.asMinutes())%60) >= 30) ? '30' : '00';
    
  //   var formatted = durationHrs + ':' + durationMin;
  //   var roundedDuration = moment.duration(formatted);

  //   alert(durationHrs + ' hours ' + durationMin + ' minutes');
  // }
</script>