<section class="container" style="padding-bottom: 2rem;">
  <div class="card bg-light-transparent">
    <div class="card-header bg-light">
      <h5 class="card-title float-left">Leave Entitlement List</h5>
      <div class="float-right">
        <button class="btn btn-sm btn-outline-dark" onclick="setupEntitlement()"><i class="fas fa-plus"></i> New Entitlement</button>
      </div>
    </div>
    <div class="card-body">
      <div class="card no-shadow">
        <div class="card-body">
          <div class="table-responsive">
            <table class="table">
              <thead>
                <th>Year</th>
                <?php foreach($leave_types as $type): ?>
                  <th data-tooltip="tooltip"  data-trigger="hover" title="<?php echo $type['name']; ?>"><?php echo $type['code']; ?></th>
                <?php endforeach; ?>
              </thead>
              <tbody>
                <?php foreach($years as $year): ?>
                  <tr>
                    <td class="text-center"><?php echo $year['year'] ?></td>
                    <?php foreach($leave_types as $type): ?>
                      <td class="text-center">
                        <?php if ($type['entitlement'][$year['year']]) { ?>
                          <a href="<?php echo base_url('hr/leave/entitlement/'.$year['year'].'/'.$type['id']); ?>" data-trigger="hover" data-tooltip="tooltip" title="View <?php echo $type['name']; ?> Entitlement for the Year <?php echo $year['year']; ?>"><i class="fas fa-check"></i></a>
                        <?php } else { ?>
                          <a href="javascript:openEntitlementModal(<?php echo $year['year']; ?>, <?php echo $type['id'] ?>)" data-tooltip="tooltip" title="Setup Entitlement"><i class="fas fa-times" style="color: red;"></i></a>
                        <?php } ?>
                      </td>
                    <?php endforeach; ?>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>
<div class="modal fade" id="setupEntitlementModal">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
          <h5 class="modal-title" id="entitlement-setup-modal-title">New Entitlement Setup</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
          </button>
      </div>
      <div class="modal-body">
        <h6>Leave Type</h6>
        <div class="row container">
            <div class="form-check">
              <input class="form-check-input type" type="checkbox" name="all" id="check_all_type" checked="checked" >
              <label class="form-check-label">All</label>
            </div>&nbsp;&nbsp;&nbsp;
            <?php foreach($leave_types as $type): ?>
              <div class="form-check">
                <input class="form-check-input type-checkbox" type="checkbox" name="leave_type[]" value="<?php echo $type['id']; ?>" id="check-type-<?php echo $type['id']; ?>" checked="checked">
                <label class="form-check-label">
                  <?php echo $type['name'] ?>
                </label>
              </div>&nbsp;&nbsp;&nbsp;
            <?php endforeach; ?>
        </div>
      </div>
      <div class="modal-body" id="setupYear">
        <div class="form-group row">
          <label for="setupEntitlementYear" class="col-sm-2 col-form-label">For The Year</label>
          <div class="col-sm-7">
            <input type="text" id="setupEntitlementYear" class="form-control datepicker-yyyy">
          </div>
          <div class="col-auto text-center">
            <div class="btn-group" role="group">
              <button type="button" class="btn btn-primary" onclick="newEntitlement()">New</button>
              <button type="button" class="btn btn-secondary" onclick="copyEntitlement()">Clone</button>
            </div>
          </div>
        </div>
      </div>
      <div class="modal-body" id="setupYearRefBody" style="display:none;">
          <div class="form-group row">
            <label for="setupYearRef" class="col-sm-2 col-form-label">Reference Year</label>
            <div class="col-sm-7">
              <select class="form-control" name="setupYearRef" id="setupYearRef">
                <option value="">Select Year</option>
                <?php if(!empty($years)) foreach($years as $year): ?>
                  <option value="<?php echo $year['year']; ?>"><?php echo $year['year']; ?></option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>
      </div>
      <div class="modal-body" id ="setupBody" style="display:none;">
        <!-- <div class="row justify-content-center"> -->
          <!-- <?php $count = 0; ?> -->
          <div class="card no-shadow">
            <ul id="accordion" class="list-group list-group-flush">
              <li id="list-header-type-<?php echo $leave_types[1]['id']; ?>" class="list-group-item" style="display:none;" data-type="<?php echo $leave_types[1]['id']; ?>"  data-typename="<?php echo $leave_types[1]['name']; ?>">
                <div id="type-<?php echo $leave_types[1]['id']; ?>">
                  <h5 class="mb-0">
                    <button class="btn btn-link" data-toggle="collapse" data-target="#collapse-<?php echo $leave_types[1]['id']; ?>" aria-expanded="true" aria-controls="collapse-<?php echo $leave_types[1]['id']; ?>">
                      <?php echo $leave_types[1]['name']; ?>
                    </button>
                  </h5>
                </div>
                <div id="collapse-<?php echo $leave_types[1]['id']; ?>" class="collapse hide" aria-labelledby="headingOne" data-parent="#accordion">
                    <div class="row">
                      <div class="col-9">
                        <div class="tab-content">
                          <?php foreach($categories as $cat): ?>
                            <div class="tab-pane fade <?php if ($cat['id'] == 1) echo 'show active'; ?>" id="<?php echo $leave_types[1]['id'].'-'.$cat['id'];?>" role="tabpanel">
                              <form id="entitlementSetupForm-<?php echo $leave_types[1]['id'].'-'.$cat['id']; ?>" class="form entitlement-form" data-type="<?php echo $leave_types[1]['id']; ?>" data-category="<?php echo $cat['id']; ?>">
                                <div class="card-body">
                                  <div class="form-row">
                                    <div class="col">
                                      <div class="form-group">
                                        <label for="entitledLeave-<?php echo $leave_types[1]['id'].'-'.$cat['id']; ?>">Entitled Leave</label>
                                        <input type="text" required class="form-control text-right" name="entitledLeave-<?php echo $leave_types[1]['id'].'-'.$cat['id']; ?>" id="entitledLeave-<?php echo $leave_types[1]['id'].'-'.$cat['id']; ?>" placeholder="Amount">
                                      </div>
                                    </div>
                                    <div class="col">
                                      <div class="form-group">
                                        <label for="maxEntitlement-<?php echo $leave_types[1]['id'].'-'.$cat['id']; ?>">Max Entitlement</label>
                                        <input type="text" required class="form-control text-right" name="maxEntitlement-<?php echo $leave_types[1]['id'].'-'.$cat['id']; ?>" id="maxEntitlement-<?php echo $leave_types[1]['id'].'-'.$cat['id']; ?>" placeholder="Amount">
                                      </div>
                                    </div>
                                  </div>
                                  <div class="form-row">
                                    <div class="col">
                                      <div class="form-group">
                                        <label for="additionalLeave-<?php echo $leave_types[1]['id'].'-'.$cat['id']; ?>">Additional Leave</label>
                                        <input type="text" required class="form-control text-right" name="additionalLeave-<?php echo $leave_types[1]['id'].'-'.$cat['id']; ?>" id="additionalLeave-<?php echo $leave_types[1]['id'].'-'.$cat['id']; ?>" placeholder="Amount">
                                      </div>
                                    </div>
                                    <div class="col">
                                      <div class="form-group">
                                        <label for="additionalLeaveMonth-<?php echo $leave_types[1]['id'].'-'.$cat['id']; ?>">Additional Leave Every</label>
                                        <input type="text" required class="form-control text-right" name="additionalLeaveMonth-<?php echo $leave_types[1]['id'].'-'.$cat['id']; ?>" id="additionalLeaveMonth-<?php echo $leave_types[1]['id'].'-'.$cat['id']; ?>" placeholder="Month Cycle">
                                      </div>
                                    </div>
                                  </div>
                                  <div class="form-row">
                                    <div class="col">
                                      <div class="form-group">
                                        <label for="bringForwardPercent-<?php echo $leave_types[1]['id'].'-'.$cat['id']; ?>">Bring Forward (%)</label>
                                        <input type="text" required class="form-control text-right" name="bringForwardPercent-<?php echo $leave_types[1]['id'].'-'.$cat['id']; ?>" id="bringForwardPercent-<?php echo $leave_types[1]['id'].'-'.$cat['id']; ?>" placeholder="Percentage">
                                      </div>
                                    </div>
                                    <div class="col">
                                      <div class="form-group">
                                        <label for="remarks-<?php echo $leave_types[1]['id'].'-'.$cat['id']; ?>">Remarks</label>
                                        <input type="text" class="form-control text-right" name="remarks-<?php echo $leave_types[1]['id'].'-'.$cat['id']; ?>" id="remarks-<?php echo $leave_types[1]['id'].'-'.$cat['id']; ?>" placeholder="Description">
                                      </div>
                                    </div>
                                  </div>
                                </div>
                              </form>
                            </div>
                          <?php endforeach; ?>
                        </div>
                      </div>
                      <div class="col-3">
                        <ul class="nav nav-pills flex-column">
                          <?php foreach($categories as $cat): ?>
                            <li class="nav-item">
                              <a class="nav-link <?php if ($cat['id'] == 1) echo 'active'; ?>" data-toggle="tab" href="#<?php echo $leave_types[1]['id'].'-'.$cat['id'];?>"><?php echo $cat['position']; ?></a>
                            </li>
                          <?php endforeach; ?>
                        </ul>
                      </div>
                    </div>
                </div>
              </li>

              <?php foreach($leave_types as $type): ?>
              <?php if ($type['id'] != 1): ?>
                <li id="list-header-type-<?php echo $type['id']; ?>" class="list-group-item" style="display:none;" data-type="<?php echo $type['id']; ?>" data-typename="<?php echo $type['name']; ?>">
                  <div id="type-<?php echo $type['id']; ?>">
                    <h5 class="mb-0">
                      <button class="btn btn-link" data-toggle="collapse" data-target="#collapse-<?php echo $type['id']; ?>" aria-expanded="true" aria-controls="collapse-<?php echo $type['id']; ?>">
                        <?php echo $type['name']; ?>
                      </button>
                    </h5>
                  </div>
                  <div id="collapse-<?php echo $type['id']; ?>" class="collapse hide" aria-labelledby="headingOne" data-parent="#accordion">
                      <div class="row">
                          <div class="col-9">
                            <div class="tab-content">
                              <?php foreach($categories as $cat): ?>
                                <div class="tab-pane fade <?php if ($cat['id'] == 1) echo 'show active'; ?>" id="<?php echo $type['id'].'-'.$cat['id'];?>" role="tabpanel">
                                  <form id="entitlementSetupForm-<?php echo $type['id'].'-'.$cat['id'];?>" class="form entitlement-form" data-type="<?php echo $type['id']; ?>" data-category="<?php echo $cat['id']; ?>">
                                    <div class="card-body">
                                      <div class="form-row">
                                        <div class="col">
                                          <div class="form-group">
                                            <label for="entitledLeave-<?php echo $type['id'].'-'.$cat['id']; ?>">Entitled Leave</label>
                                            <input type="text" required class="form-control text-right" name="entitledLeave-<?php echo $type['id'].'-'.$cat['id']; ?>" id="entitledLeave-<?php echo $type['id'].'-'.$cat['id']; ?>" placeholder="Amount">
                                          </div>
                                        </div>
                                        <div class="col">
                                          <div class="form-group">
                                            <label for="remarks-<?php echo $type['id'].'-'.$cat['id']; ?>">Remarks</label>
                                            <input type="text" class="form-control text-right" name="remarks-<?php echo $type['id'].'-'.$cat['id']; ?>" id="remarks-<?php echo $type['id'].'-'.$cat['id']; ?>" placeholder="Description">
                                          </div>
                                        </div>
                                      </div>
                                    </div>
                                  </form>
                                </div>
                              <?php endforeach; ?>
                            </div>
                          </div>

                          <div class="col-3">
                            <ul class="nav nav-pills flex-column">
                              <?php foreach($categories as $cat): ?>
                              <li class="nav-item">
                                <a class="nav-link <?php if ($cat['id'] == 1) echo 'active'; ?>" data-toggle="tab" href="#<?php echo $type['id'].'-'.$cat['id'];?>"><?php echo $cat['position']; ?></a>
                              </li>
                              <?php endforeach; ?>
                            </ul>
                          </div>
                      </div>
                  </div>
                </li>
              <?php endif; ?>
              <?php endforeach; ?>
            </ul>
          </div>
            
          <div class="btn-group float-right" style="padding-top: 2rem;">
            <button type="button" class="btn btn-primary" data-dismiss="modal">Cancel</button>
            <button type="button" id="entitlementSetupModalSubmitBtn" onclick="saveEntitlement()" class="btn btn-light">Save</button>
          </div>
        <!-- </div> -->
      </div>
    </div>
  </div>
</div>
<div class="modal fade" id="entitlementModal">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="entitlement-modal-title"></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
              <h6 style="text-decoration: underline;">Entitlement Detail</h6>
                  <div class="form-row">
                      <div class="col">
                          <div class="form-group">
                              <label for="formYear">Year</label>
                              <input disabled type="text" class="form-control text-right" name="formYear" id="formYear" value="">
                          </div>
                      </div>
                      <div class="col">
                          <div class="form-group">
                              <label for="formType">Leave Type</label>
                              <select disabled required data-parsley-error-message="Type is required." class="form-control" id="formType">
                                  <option selected value="">Select Type</option>
                                  <?php foreach ($leave_types as $type): ?>
                                    <option value="<?php echo $type['id']; ?>"><?php echo $type['name'] ?></option>
                                  <?php endforeach; ?>
                              </select>
                          </div>
                      </div>
                  </div>
            </div>
            <form id="entitlementForm" class="form">
                <div class="modal-body">
                    <div class="form-group" hidden>
                        <label for="entitlementID">ID</label>
                        <input type="text" class="form-control" name="entitlementID" id="entitlementID" value="">
                    </div>
                    <div class="form-row">
                      <div class="col">
                        <div class="form-group">
                          <label for="entitledLeave">Entitled Leave</label>
                          <input type="text" required data-parsley-error-message="Entitled Leave is required." class="form-control text-right" name="entitledLeave" id="entitledLeave" placeholder="Entitled Leave">
                        </div>
                      </div>
                      <div class="col">
                        <div class="form-group">
                          <label for="maxEntitlement">Max Entitlement</label>
                          <input type="text" required data-parsley-error-message="Max Entitlement is required." class="form-control text-right" name="maxEntitlement" id="maxEntitlement" placeholder="Maximum Entitlement">
                        </div>
                      </div>
                    </div>
                    <div class="form-row">
                      <div class="col">
                        <div class="form-group">
                          <label for="additionalLeave">Additional Leave</label>
                          <input type="text" required data-parsley-error-message="Additional Leave is required." class="form-control text-right" name="additionalLeave" id="additionalLeave" placeholder="Enter Additional Leave">
                        </div>
                      </div>
                      <div class="col">
                        <div class="form-group">
                          <label for="additionalLeaveMonth">Additional Leave Every</label>
                          <input type="text" required data-parsley-error-message="Month Cycle is required." class="form-control text-right" name="additionalLeaveMonth" id="additionalLeaveMonth" placeholder="Month Cycle">
                        </div>
                      </div>
                    </div>
                    <div class="form-row">
                      <div class="col">
                        <div class="form-group">
                          <label for="bringForwardPercent">Bring Forward (%)</label>
                          <input type="text" required data-parsley-error-message="Percentage is required." class="form-control text-right" name="bringForwardPercent" id="bringForwardPercent" placeholder="Bring Forward Percentage">
                        </div>
                      </div>
                      <div class="col">
                        <div class="form-group">
                          <label for="remarks">Remarks</label>
                          <input type="text" class="form-control" name="remarks" id="remarks" placeholder="Remarks">
                        </div>
                      </div>
                    </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="entitlementModalSubmitBtn" class="btn btn-light">Save</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
<script>
  $(function(){
    $('#check_all_type').click(function() {
      var checkedStatus = this.checked;
      $('.type-checkbox').each(function() {
        $(this).prop('checked', checkedStatus);
      });
    });

    $('#setupYearRef').change(() => {
      $.ajax({
        url: '<?php echo base_url('hr/leave/getEntitlementByFilter'); ?>',
        type: 'GET',
        data: {
          year: $('#setupYearRef').val()
        },
        dataType: 'JSON',
        success: (data) => {
          console.log(data);
          if (data.status.toLowerCase() == 'success') {
            var entitlements = data.entitlements;

            $.each(entitlements, (k, v) => {
              $('#entitledLeave-'+v.type_id+'-'+v.category_id).val(v.entitled_leave);
              $('#maxEntitlement-'+v.type_id+'-'+v.category_id).val(v.max_entitlement);
              $('#additionalLeave-'+v.type_id+'-'+v.category_id).val(v.additional_leave);
              $('#additionalLeaveMonth-'+v.type_id+'-'+v.category_id).val(v.month_of_service_add_leave);
              $('#bringForwardPercent-'+v.type_id+'-'+v.category_id).val(v.bring_forward_percentage);
              $('#remarks-'+v.type_id+'-'+v.category_id).val(v.remarks);
            })

            $('#setupBody').show();
          } else {
            $('#setupBody').hide();
          }
        }
      });
    });
  })

  function setupEntitlement() {

    $('#setupYearRef').val('');
    $('#setupYearRefBody').hide();
    $('#setupBody').hide();

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

  function newEntitlement() {
    $(".entitlement-form").each(function() {
      clearForm('#'+this.id);
    })
  
    var types = [];
    
    $('.type-checkbox:checked').each(function(i){
      types[i] = $(this).val();
    });

    if($('#setupEntitlementYear').val()) {
      $('[id^=list-header-type-]').hide();
      $('#setupBody :input').val('');
      $('#setupYearRef').val('');
      $('#setupYearRefBody').hide();
      $('#setupBody').hide();

      $.each(types, function(i, v) {
        $.ajax({
          url: '<?php echo base_url('hr/leave/getEntitlementByYear'); ?>',
          type: 'GET',
          data: {
            year: $('#setupEntitlementYear').val(),
            type_id: v
          },
          dataType: 'JSON',
          success: (data) => {
              if (data.status.toLowerCase() == 'success') {
                $("#list-header-type-" + v).hide();
                $('[id^=entitlementSetupForm-' + v + '-' + ']').removeClass('active');
                alert('Entitlement for the year selected has already been setup.');
              } else {
                $("#list-header-type-" + v).show();
                $('[id^=entitlementSetupForm-' + v + '-' + ']').addClass('active');
                $('#setupBody').show();
              }
          }
        })
      })

      // $.ajax({
      //   url: '<?php echo base_url('hr/leave/getEntitlementByYear'); ?>',
      //   type: 'GET',
      //   data: {
      //     year: $('#setupEntitlementYear').val(),
      //     types
      //   },
      //   dataType: 'JSON',
      //   success: (data) => {
      //       if (data.status.toLowerCase() == 'success') {
      //         alert ('Entitlement for the year selected has already been setup.');
      //       } else {
      //         $('#setupEntitlementYear').prop('disabled', true);
      //         $('.type-checkbox').prop('disabled', true);
      //         $('#setupBody').show();
      //       }
      //   }
      // })
    }
  }

  function copyEntitlement() {
    $(".entitlement-form").each(function() {
      clearForm('#'+this.id);
    })
  
    var types = [];
    
    $('.type-checkbox:checked').each(function(i){
      types[i] = $(this).val();
    });

    console.log(types);
    
    if($('#setupEntitlementYear').val()) {
      $('[id^=list-header-type-]').hide();
      $('#setupBody :input').val('');
      $('#setupYearRef').val('');
      $('#setupYearRefBody').hide();
      $('#setupBody').hide();

      $.each(types, function(i, v) {
        $.ajax({
          url: '<?php echo base_url('hr/leave/getEntitlementByYear'); ?>',
          type: 'GET',
          data: {
            year: $('#setupEntitlementYear').val(),
            type_id: v
          },
          dataType: 'JSON',
          success: (data) => {
              if (data.status.toLowerCase() == 'success') {
                $("#list-header-type-" + v).hide();
                $('[id^=entitlementSetupForm-' + v + '-' + ']').removeClass('active');
                alert('Entitlement for the year selected has already been setup.');
              } else {
                $("#list-header-type-" + v).show();
                $('[id^=entitlementSetupForm-' + v + '-' + ']').addClass('active');
                $('#setupYearRefBody').show();
              }
          }
        })
      })
    }

    if ($('#setupEntitlementYear').val()) {
      $('#setupBody :input').val('');
      $('#setupYearRef').val('');
      $('#setupYearRefBody').hide();
      $('#setupBody').hide();

      $.ajax({
        url: '<?php echo base_url('hr/leave/getEntitlementsForClone'); ?>',
        type: 'POST',
        data: {
          year: $('#setupEntitlementYear').val(),
          types
        },
        dataType: 'JSON',
        success: (data) => {
            if (data.status.toLowerCase() == 'success') {
              alert ('Entitlement for the year selected has already been setup.');
            } else {
              $('#setupYearRefBody').show();
            }
        }
      })
    }
  }

  function saveEntitlement() {
    toastConfirm('Are you sure you want to save this entitlement?', () => {
      var insert_data = new Array;
      var validate = true;

      $(".entitlement-form.active").each(function() {
        var form_id     = $(this).attr('id');
        var type_id     = $(this).data('type');
        var category_id = $(this).data('category');

        var form = $('#'+form_id).parsley();
        
        if (form.validate() == false) {
          //console.log(form_id);
          validate = false;
        } else {
          if (type_id == 1) {
            insert_data.push({
              year: $('#setupEntitlementYear').val(),
              type_id: type_id,
              category_id: category_id,
              entitled_leave: $('#entitledLeave-'+type_id+'-'+category_id).val(),
              max_entitlement: $('#maxEntitlement-'+type_id+'-'+category_id).val(),
              additional_leave: $('#additionalLeave-'+type_id+'-'+category_id).val(),
              month_of_service_add_leave: $('#additionalLeaveMonth-'+type_id+'-'+category_id).val(),
              bring_forward_percentage: $('#bringForwardPercent-'+type_id+'-'+category_id).val(),
              remarks : $('#remarks-'+type_id+'-'+category_id).val()
            });
          } else {
             insert_data.push({
              year: $('#setupEntitlementYear').val(),
              type_id: type_id,
              category_id: category_id,
              entitled_leave: $('#entitledLeave-'+type_id+'-'+category_id).val(),
              remarks : $('#remarks-'+type_id+'-'+category_id).val()
            });
          }
        }
      });

      if (validate == true) {
        //console.log(insert_data);

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

              location.reload();
            }
          }
        })
      } else {
        alert("Please check accordingly.");
      }

      // var new_data = new Array;

      // $.each(positions, (a, b) => {
      //   new_data.push({
      //     year: $('#setupEntitlementYear').val(),
      //     type_id: 1,
      //     category_id: b.id,
      //     entitled_leave: $('#entitledLeave-'+b.id).val(),
      //     max_entitlement: $('#maxEntitlement-'+b.id).val(),
      //     additional_leave: $('#additionalLeave-'+b.id).val(),
      //     month_of_service_add_leave: $('#additionalLeaveMonth-'+b.id).val(),
      //     bring_forward_percentage: $('#bringForwardPercent-'+b.id).val(),
      //     remarks : $('#remarks-'+b.id).val()
      //   });
      // })

      // console.log(new_data);

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

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

  // function openEntitlementModal(year, position_id, entitlement_id) {
  //   $('#formYear').val(year);
  //   $('#formPosition').val(position_id);

  //   var position = $('#formPosition option:selected').text();

  //   $('#entitlement-modal-title').text(year + ' Entitlement Setup: ' + position);
    
  //   $('#entitledLeave').val('');
  //   $('#maxEntitlement').val('');
  //   $('#additionalLeave').val('');
  //   $('#additionalLeaveMonth').val('');
  //   $('#bringForwardPercent').val('');
  //   $('#remarks').val('');

  //   if(entitlement_id) {
  //     $.ajax({
  //         url: '<?php echo base_url('hr/leave/getEntitlement'); ?>',
  //         type: 'GET',
  //         data: {
  //           id: entitlement_id
  //         },
  //         dataType: 'JSON',
  //         success: (data) => {
  //             if (data.status.toLowerCase() == 'success') {
  //               var entitlement = data.entitlement;

  //               $('#entitlementID').val(entitlement.id);
  //               $('#entitledLeave').val(entitlement.entitled_leave);
  //               $('#maxEntitlement').val(entitlement.max_entitlement_per_year);
  //               $('#additionalLeave').val(entitlement.additional_leave);
  //               $('#additionalLeaveMonth').val(entitlement.month_of_service_add_leave);
  //               $('#bringForwardPercent').val(entitlement.bring_forward_by_percent);
  //               $('#remarks').val(entitlement.remarks);
  //             }
  //         }
  //     })

  //     $('#entitlementModalSubmitBtn').attr('onclick', 'updateEntitlement()');
  //   } else {
  //     $('#entitlementModalSubmitBtn').attr('onclick', 'createEntitlement()');
  //   }
    
  //   $('#entitlementModal').modal('show');
  // }

  // function openEntitlementModal(year, type_id) {
  //   $('#formYear').val(year);
  //   $('#formType').val(type_id);

  //   var type = $('#formType option:selected').text();

  //   $('#entitlement-modal-title').text(year + ' Entitlement Setup: ' + type);
    
  //   $('#entitledLeave').val('');
  //   $('#maxEntitlement').val('');
  //   $('#additionalLeave').val('');
  //   $('#additionalLeaveMonth').val('');
  //   $('#bringForwardPercent').val('');
  //   $('#remarks').val('');

  //   if(type_id) {
  //     $.ajax({
  //         url: '<?php echo base_url('hr/leave/getEntitlementByFilter'); ?>',
  //         type: 'GET',
  //         data: {
  //           year, type_id
  //         },
  //         dataType: 'JSON',
  //         success: (data) => {
  //           console.log(data);
  //             if (data.status.toLowerCase() == 'success') {
  //               var entitlement = data.entitlement;
                
  //               $('#entitlementID').val(entitlement.id);
  //               $('#entitledLeave').val(entitlement.entitled_leave);
  //               $('#maxEntitlement').val(entitlement.max_entitlement_per_year);
  //               $('#additionalLeave').val(entitlement.additional_leave);
  //               $('#additionalLeaveMonth').val(entitlement.month_of_service_add_leave);
  //               $('#bringForwardPercent').val(entitlement.bring_forward_by_percent);
  //               $('#remarks').val(entitlement.remarks);
  //             }
  //         }
  //     })

  //     $('#entitlementModalSubmitBtn').attr('onclick', 'updateEntitlement()');
  //   } else {
  //     $('#entitlementModalSubmitBtn').attr('onclick', 'createEntitlement()');
  //   }
    
  //   $('#entitlementModal').modal('show');
  // }

  function openEntitlementModal(year, type_id) {
    $('#setupEntitlementYear').val(year);
    $("#list-header-type-" + type_id).show();
    $('[id^=entitlementSetupForm-' + type_id + '-' + ']').addClass('active');
    $('#setupBody').show();
    $('#check_all_type').prop('checked', false);
    $('.type-checkbox').prop('checked', false);

    $('.type-checkbox').each(function() {
      if ($(this).val() == type_id) $(this).prop('checked', true);
    });

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

  function createEntitlement() {
    validateForm('#entitlementForm', 'Are you sure you want to create this entitlement?', function () {
      $.ajax({
        url: '<?php echo base_url('hr/leave/createEntitlement'); ?>',
        type: 'POST',
        data: {
          leave_type_id : 1,
          year : $('#formYear').val(),
          position_id : $('#formPosition').val(),
          entitled_leave : $('#entitledLeave').val(),
          max_entitlement_per_year : $('#maxEntitlement').val(),
          additional_leave : $('#additionalLeave').val(),
          month_of_service_add_leave : $('#additionalLeaveMonth').val(),
          bring_forward_by_percent : $('#bringForwardPercent').val(),
          remarks : $('#remarks').val()
        },
        dataType: 'JSON',
        success: (data) => {
          if (data.status.toLowerCase() == 'success') {
            localStorage.setItem("status", data.status);
            localStorage.setItem("msg", data.msg);

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

  function updateEntitlement() {
    validateForm('#entitlementForm', 'Are you sure you want to update this entitlement?', function () {
      $.ajax({
        url: '<?php echo base_url('hr/leave/updateEntitlement'); ?>',
        type: 'POST',
        data: {
          id : $('#entitlementID').val(),
          entitled_leave : $('#entitledLeave').val(),
          max_entitlement_per_year : $('#maxEntitlement').val(),
          additional_leave : $('#additionalLeave').val(),
          month_of_service_add_leave : $('#additionalLeaveMonth').val(),
          bring_forward_by_percent : $('#bringForwardPercent').val(),
          remarks : $('#remarks').val()
        },
        dataType: 'JSON',
        success: (data) => {
          if (data.status.toLowerCase() == 'success') {
            localStorage.setItem("status", data.status);
            localStorage.setItem("msg", data.msg);

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

  function clearForm(e) {
		$(e).parsley().reset();
        
		$(e).find("select").val('').trigger('change');
		$(e).find("input, textarea").val("");
	}
</script>