<div id="form_save">
  <div class="row">
    <input type="hidden" id="id_karyawan" value="">
    <input type="hidden" id="username_temp" value="">
    <input type="hidden" id="nik_temp" value="">
    <input type="hidden" id="jenis" value="tambah">
    <div class="form-group m-0 col-md-3 col-12 mb-1">
      <input type="text" class="form-control" placeholder="NIK" id="nik">
    </div>
    <div class="form-group m-0 col-md-3 col-12 mb-1">
      <input type="text" class="form-control" placeholder="Nama Staff" id="nama">
    </div>
    <div class="form-group m-0 col-md-3 col-12 mb-1">
      <select class="select2 form-control" id="cabang" style="width: 100%;"></select>
    </div>
    <div class="form-group m-0 col-md-3 col-12 mb-1">
      <select class="select2 form-control" id="departemen" style="width: 100%;"></select>
    </div>
    <div class="form-group m-0 col-md-3 col-12 mb-1">
      <input type="text" class="form-control" placeholder="Username (minimal 6 karakter)" id="username">
      <small class="text-muted"><i>*Password default sama dengan username</i></small>
    </div>
  </div>
  <div class="row">
    <div id="message" class="col-12 mb-1"></div>
  </div>
  <div class="row">
    <div id="btn_tambah_baru" class="form-group m-0 col-md-3 col-12 mb-1" style="display: none;">
      <button type="button" class="btn btn-primary mr-1 col-md-6 col-6" onclick="tambah_baru()"> Tambah Baru </button>
    </div>
    <div id="btn_save" class="form-group m-0 col-md-3 col-12 mb-1">
      <button type="button" id="tambah" class="btn btn-biru mr-1 ladda-button col-md-4 col-6" data-style="expand-left" onclick="save()"> Simpan </button>
      <button type="button" class="btn btn-outline-biru col-md-4 col-5" onclick="cancel()"> Batal </button>
    </div>
    <div id="btn_update" class="form-group m-0 col-md-3 col-12 mb-1" style="display: none;">
      <button type="button" id="update" class="btn btn-warning mr-1 ladda-button col-md-4 col-6" data-style="expand-left" onclick="update()"> Update </button>
      <button type="button" class="btn btn-outline-biru col-md-4 col-5" onclick="cancel_update()"> Batal </button>
    </div>
    <div id="btn_hapus" class="form-group m-0 col-md-3 col-12 mb-1" style="display: none;">
      <button type="button" id="hapus" class="btn btn-danger mr-1 ladda-button col-md-4 col-6" data-style="expand-left" onclick="delete_data()"> Hapus </button>
      <button type="button" class="btn btn-outline-biru col-md-4 col-5" onclick="cancel_hapus()"> Batal </button>
    </div>
  </div>
</div>
<script type="text/javascript">
$(function() {
  $('#cabang').select2({
      placeholder: 'Cabang',
      allowClear: true,
      ajax: {
          // type: 'POST',
          url: '<?= route("dropdown.cabang")  ?>',
          dataType: 'json',
          delay: 250,
          processResults: function (data) {
          return{
                  results: data
              };
          },
          cache: false
      },
  minLength: 3
  });

  $('#departemen').select2({
      placeholder: 'Departemen',
      allowClear: true,
      ajax: {
          // type: 'POST',
          url: '<?= route("dropdown.departemen")  ?>',
          dataType: 'json',
          delay: 250,
          processResults: function (data) {
          return{
                  results: data
              };
          },
          cache: false
      },
  minLength: 3
  });
});

$("#username").keyup(function() {
  var jenis         = $('#jenis').val();
  var username_temp = $('#username_temp').val();
  var temp          = $(this).val().replace(/\s/g, '');

  $(this).val(temp);
  if(jenis == 'edit' && temp == username_temp) {

  } else {
    var cek = username_min(temp);
    if(cek) {
      cek_username(temp);
    }
  }
});

$("#nik").keyup(function() {
  var jenis     = $('#jenis').val();
  var nik_temp  = $('#nik_temp').val();
  var temp      = $(this).val().replace(/\s/g, '');

  $(this).val(temp);
  if(jenis == 'edit' && temp == nik_temp) {

  } else {
    cek_nik(temp);
  }
});

function save() {
  $('#message').html("");
  var loading       = Ladda.create(document.querySelector('#tambah'));
  var nik           = $('#nik').val();
  var nama          = $('#nama').val();
  var cabang        = $('#cabang').val();
  var departemen    = $('#departemen').val();
  var username      = $('#username').val();

  if(nik == '') {
    $('#message').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> NIK belum diisi</font>");
    $("#nik").focus();
    return false;
  } else if(cek_nik(nik) > 0) {
    $('#message').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> NIK sudah digunakan</font>");
    $("#nik").focus();
    return false;
  } else if(nama == '') {
    $('#message').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> Nama belum diisi</font>");
    $("#nama").focus();
    return false;
  } else if(cabang == null) {
    $('#message').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> Cabang belum diisi</font>");
    $("#cabang").focus();
    return false;
  } else if(departemen == null) {
    $('#message').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> Departemen belum diisi</font>");
    $("#departemen").focus();
    return false;
  } else if(username == '') {
    $('#message').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> Username belum diisi</font>");
    $("#username").focus();
    return false;
  } else if(username.length < 6) {
    $('#message').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> Username minimal 6 karakter</font>");
    $("#username").focus();
    return false;
  } else if(cek_username($('#username').val()) != '') {
    return false;
  }

  loading.start();

  var param         = {};
  param.nik         = nik;
  param.nama        = nama;
  param.cabang      = cabang;
  param.departemen  = departemen;
  param.username    = username;

  $.ajax({
      type: 'POST',
      url: "<?= route('quick-setup.staff.save') ?>",
      data: param,
      dataType:'JSON',
      success: function(result) {
          if(result.success == true){
              if(result.type == 'save'){
                  $("#form_save input").prop("disabled", true);
                  $("#cabang, #departemen").prop("disabled", true);
                  $('#btn_save').hide();
                  $('#btn_tambah_baru').show();
              }

          }
          loading.stop();
          $('#message').show();
          $('#message').html(result.message);
      },
      error:function(){
          loading.stop();
          $('#message').show();
          $('#message').html('<font color="#eb3a28"><i class="fa fa-close(alias)">&nbsp;</i><strong>Gagal : Terjadi Kesalahan</strong></font>');
      }
  });
}

function update() {
  $('#message').html("");
  var loading       = Ladda.create(document.querySelector('#update'));
  var nik           = $('#nik').val();
  var nik_temp      = $('#nik_temp').val();
  var nama          = $('#nama').val();
  var cabang        = $('#cabang').val();
  var departemen    = $('#departemen').val();
  var username      = $('#username').val();
  var username_temp = $('#username').val();
  var id_karyawan   = $('#id_karyawan').val();

  if(nik == '') {
    $('#message').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> NIK belum diisi</font>");
    $("#nik").focus();
    return false;
  } else if(nik_temp != nik && cek_nik(nik) > 0) {
    $('#message').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> NIK sudah digunakan</font>");
    $("#nik").focus();
    return false;
  } else if(nama == '') {
    $('#message').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> Nama belum diisi</font>");
    $("#nama").focus();
    return false;
  } else if(cabang == null) {
    $('#message').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> Cabang belum diisi</font>");
    $("#cabang").focus();
    return false;
  } else if(departemen == null) {
    $('#message').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> Departemen belum diisi</font>");
    $("#departemen").focus();
    return false;
  } else if(username == '') {
    $('#message').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> Username belum diisi</font>");
    $("#username").focus();
    return false;
  } else if(username.length < 6) {
    $('#message').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> Username minimal 6 karakter</font>");
    $("#username").focus();
    return false;
  } else if(username_temp != username && cek_username($('#username').val()) != '') {
    return false;
  }

  loading.start();

  var param         = {};
  param.nik         = nik;
  param.nama        = nama;
  param.cabang      = cabang;
  param.departemen  = departemen;
  param.username    = username;
  param.id_karyawan = id_karyawan;

  $.ajax({
      type: 'POST',
      url: "<?= route('quick-setup.kepala.departemen.update') ?>",
      data: param,
      dataType:'JSON',
      success: function(result) {
          if(result.success == true){
              if(result.type == 'update'){
                  $("#form_save input").val('');
                  $('#btn_update').hide();
                  $('#btn_save').show();
                  $('#cabang, #departemen').val(null).trigger('change');
              }
          }
          loading.stop();
          $('#message').show();
          $('#message').html(result.message);
      },
      error:function(){
          loading.stop();
          $('#message').show();
          $('#message').html('<font color="#eb3a28"><i class="fa fa-close(alias)">&nbsp;</i><strong>Gagal : Terjadi Kesalahan</strong></font>');
      }
  });
}

function delete_data() {
  $('#message').html("");
  var loading     = Ladda.create(document.querySelector('#hapus'));
  var id_karyawan = $('#id_karyawan').val();

  loading.start();

  var param         = {};
  param.id_karyawan = id_karyawan;

  $.ajax({
      type: 'POST',
      url: "<?= route('quick-setup.kepala.cabang.delete') ?>",
      data: param,
      dataType:'JSON',
      success: function(result) {
          if(result.success == true){
            $('#form_save input').prop('disabled', false);
            $("#cabang, #departemen").prop("disabled", false);
            $('#btn_hapus').hide();
            $('#btn_save').show();
            cancel();
          }
          loading.stop();
          $('#message').show();
          $('#message').html(result.message);
      },
      error:function(){
          loading.stop();
          $('#message').show();
          $('#message').html('<font color="#eb3a28"><i class="fa fa-close(alias)">&nbsp;</i><strong>Gagal : Terjadi Kesalahan</strong></font>');
      }
  });
}

function edit(id_karyawan) {
  $('#jenis').val('edit');
  $('#cabang, #departemen').prop('disabled', false);
  detail(id_karyawan);
  $('#form_save input').prop('disabled', false);
  $('#btn_save, #btn_tambah_baru, #btn_hapus').hide();
  $('#btn_update').show();
  $('#form_save').focus();
}

function hapus(id_karyawan) {
  $('#jenis').val('hapus');
  detail(id_karyawan);
  $('#form_save').focus();
  $('#form_save input').prop('disabled', true);
  $('#cabang, #departemen').prop('disabled', true);
  $('#btn_save, #btn_update, #btn_tambah_baru').hide();
  $('#btn_hapus').show();
}

function detail(id_karyawan) {
  $('#message').html("");
  $.get('<?= route("quick-setup.kepala.departemen.detail") ?>/'+id_karyawan, function(result) {
    $('#nik').val(result.nik);
    $('#nik_temp').val(result.nik);
    $('#nama').val(result.nama);
    set_cabang_select2(result.id_cabang, result.text_cabang);
    set_departemen_select2(result.id_departemen, result.text_departemen);
    $('#username').val(result.username);
    $('#username_temp').val(result.username);
    $('#id_karyawan').val(result.id_karyawan);
  }, 'json');
}

function set_cabang_select2(id, text) {
  var data = {
    id    : id,
    text  : text
  };

  var newOption = new Option(data.text, data.id, false, false);
  $('#cabang').append(newOption).trigger('change');
  set_cabang_select2_fail(id);
}

function set_departemen_select2(id, text) {
  var data = {
    id    : id,
    text  : text
  };

  var newOption = new Option(data.text, data.id, false, false);
  $('#departemen').append(newOption).trigger('change');
  set_departemen_select2_fail(id);
}

function set_cabang_select2_fail(id) {
  var cabang = $('#cabang').val();
  if(cabang != id) {
    $('#cabang').val(id).trigger('change');
  }
}

function set_departemen_select2_fail(id) {
  var departemen = $('#departemen').val();
  if(departemen != id) {
    $('#departemen').val(id).trigger('change');
  }
}

function tambah_baru() {
  $("#form_save input").prop("disabled", false);
  $("#cabang, #departemen").prop("disabled", false);
  cancel();
  $('#btn_tambah_baru').hide();
  $('#btn_save').show();
}

function cancel_update() {
  cancel();
  $('#btn_update').hide();
  $('#btn_save').show();
}

function cancel_hapus() {
  cancel();
  $('#form_save input').prop('disabled', false);
  $("#cabang, #departemen").prop("disabled", false);
  $('#btn_hapus').hide();
  $('#btn_save').show();
}

function cancel() {
  $('#jenis').val('tambah');
  $('#message').html('');
  $('#form_save input').val('');
  $('#cabang, #departemen').val(null).trigger('change');
}

/*mengecek username sudah digunakan atau belum*/
function cek_username(name) {
  var result;
  $("#message").html("");
  $.ajax({
      url: "<?= site_url('wizard/cek_username') ?>",
      type: 'get',
      dataType: 'json',
      async: false,
      data : {username : name},
      success: function(data) {
          result = data.username;
          /*menampilkan pesan jika username sudah digunakan*/
          if(result) {
            $("#message").html("<span class='text-danger'>username sudah digunakan</span>");
          } else {
            $("#message").html("");
          }
      }
   });
   return result;
 }

 /*mengecek nik sudah digunakan atau belum*/
 function cek_nik(nik) {
   var result;
   $("#message").html("");
   $.ajax({
       url: "<?= route('quick-setup.kepala.cabang.cek_nik') ?>/"+nik,
       type: 'get',
       dataType: 'json',
       async: false,
       data : {username : name},
       success: function(data) {
           /*menampilkan pesan jika username sudah digunakan*/
           if(data > 0) {
             $("#message").html("<span class='text-danger'>nik sudah digunakan</span>");
           } else {
             $("#message").html("");
           }
       }
    });
    return result;
 }

 function username_min(name) {
   if(name.length < 6) {
     $('#message').html("<font style='color:Crimson'><i class='fa fa-exclamation-triangle'></i> Username minimal 6 karakter</font>");
     return false;
   } else {
     $('#message').html('');
     return true;
   }
 }
</script>
