<?= $this->extend('backend/layout/template_admin'); ?>

<?= $this->section('content'); ?>

<!-- /.content-header -->

<!-- Main content -->
<section class="content">
  <div class="container-fluid">
    <!-- Small boxes (Stat box) -->
    <div class="row justify-content-between">
      <div class="col-md-4 mb-3">
        <!-- Button trigger modal -->

        <button type="button" id="btntambahnilaibaru" class="btn btn-primary" data-toggle="modal" data-target="#tambahModal">
          Tambah
        </button>
        <button type="button" name="btndeletenilai" id="btndeletenilai" class="btn btn-danger">Hapus</button>
        <button type="button" id="btnimportnilaibaru" class="btn btn-info" data-toggle="modal" data-target="#importModal">
          Import
        </button>

        <!-- modal import -->
        <div class="modal fade" id="importModal" tabindex="-1" aria-labelledby="importModalLabel" aria-hidden="true">
          <div class="modal-dialog">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title" id="importModalLabel">Import Data Nilai Pegawai</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 Tambah Data -->
                <form action="" method="POST" id="importnilaipegawai" enctype="multipart/form-data">
                  <div class="form_group" style="margin-bottom: 5;">
                    <label for="">Unggah File</label>
                    <input type="file" id="filenilaipegawai" name="filenilaipegawai" class="form-control">
                  </div>
                  <br>
                  <p style="font-size: 15px;"><a href="<?= base_url(); ?>/asset/template/template_import_nilai_pegawai.xls">Download Template Import Nilai DP3 Pegawai</a></p>

              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="submit" id="btnimportnilai" class="btn btn-primary">Import</button>
              </div>
              </form>
            </div>
          </div>
        </div>

      </div>
      <!-- <div class="col-md-4"></div> -->
      <div class="col-md-4 ">
        <div class="form-group row">
          <label for="bulan" class="col-sm-2 col-form-label"></label>
          <div class="col-sm-4">

          </div>
          <label for="tahun" class="col-sm-2 col-form-label">Tahun</label>
          <div class="col-sm-4">
            <input type="text" class="form-control" id="searchtahun" name="searchtahun">
          </div>
        </div>
      </div>


    </div>


    <div class="row">
      <div class="col">
        <div class="table-responsive">
          <table class="table table-striped" id="tableNilaiPegawai">
            <thead class="bg-navy">
              <tr>
                <th scope="col"></th>
                <th><input type="checkbox" id='checkall'></th>
                <!-- <th scope="col">No</th> -->
                <th scope="col">Action</th>
                <th scope="col">NIP</th>
                <th scope="col">Nama Lengkap</th>
                <th scope="col">Tahun</th>
                <th scope="col">Kehadiran</th>
                <th scope="col">Disiplin</th>
                <th scope="col">Kinerja</th>
                <th scope="col">Etika</th>
                <th scope="col">Loyalitas</th>
                <th scope="col">Kesimpulan</th>
                <th scope="col">Created At</th>
                <th scope="col">Updated At</th>
                <th scope="col">Last User Update</th>

              </tr>
            </thead>


          </table>
        </div>


      </div>
    </div>


    <!-- Modal Tambah Nilai -->
    <div class="modal fade" id="tambahModal" tabindex="-1" aria-labelledby="tambahModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="tambahModalLabel">Tambah Nilai</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">

            <div class="alert alert-info" role="alert">
              <b>Isilah hanya dengan</b><br>
              I = Istimewa , SB = Sangat Baik , B = Baik , C = Cukup , R = Rendah , SR = Sangat Rendah
            </div>
            <form method="post" action="" id="tambahnilaiform">

              <div class="form-group row">
                <label for="namalengkap" class="col-sm-2 control-label">Nama Lengkap</label>
                <div class="col-sm-10">
                  <select id="namalengkap" class="form-control selectnamalengkap" name="namalengkap" onchange="tampil()">
                    <option selected disabled>Choose...</option>
                    <?php foreach ($pegawai as $pegawai) : ?>
                      <option value="<?= $pegawai['nip']; ?>"><?= $pegawai['nama_lengkap']; ?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
              </div>

              <div class="form-group row">
                <label for="nip" class="col-sm-2">NIP</label>
                <div class="col-sm-4">
                  <p id="textnip">NIP Pegawai</p>
                  <input type="hidden" class="form-control" id="nip" name="nip">
                </div>
              </div>
              <div class="form-group row">
                <label for="tahun" class="col-sm-2 col-form-label">Tahun</label>
                <div class="col-sm-4">
                  <input type="text" class="form-control" id="tahun" name="tahun">
                </div>
              </div>

              <div class="form-row">
                <div class="form-group col-md-2">
                  <center><label for="kehadiran">Kehadiran</label></center>
                  <input type="text" class="form-control" id="kehadiran" name="kehadiran">
                </div>
                <div class="form-group col-md-2">
                  <center><label for="disiplin">Disiplin</label></center>
                  <input type="text" class="form-control" id="disiplin" name="disiplin">
                </div>
                <div class="form-group col-md-2">
                  <center><label for="kinerja">Kinerja</label></center>
                  <input type="text" class="form-control" id="kinerja" name="kinerja">
                </div>
                <div class="form-group col-md-2">
                  <center><label for="etika">Etika</label></center>
                  <input type="text" class="form-control" id="etika" name="etika">
                </div>
                <div class="form-group col-md-2">
                  <center><label for="loyalitas">Loyalitas</label></center>
                  <input type="text" class="form-control" id="loyalitas" name="loyalitas">
                </div>
              </div>

          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            <button type="submit" id="btnsavenilai" class="btn btn-primary">Tambah</button>
          </div>


          </form>
        </div>
      </div>
    </div>

    <!-- Modal Edit Absen -->
    <div class="modal fade" id="editnilaiModal" tabindex="-1" aria-labelledby="editnilaiModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="editnilaiModalLabel">Edit Nilai</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <div class="alert alert-info" role="alert">
              <b>Isilah hanya dengan</b><br>
              I = Istimewa , SB = Sangat Baik , B = Baik , C = Cukup , R = Rendah , SR = Sangat Rendah
            </div>
            <form method="post" action="" id="editnilaiform">
              <input type="hidden" name="idnilai">
              <div class="form-group row">
                <label for="nip" class="col-sm-2">NIP</label>
                <div class="col-sm-10">
                  <p id="edittextnip">NIP Pegawai</p>
                  <input type="hidden" class="form-control" name="nip">
                </div>
                <label for="nip" class="col-sm-2">Nama</label>
                <div class="col-sm-4">
                  <input type="text" class="form-control" name="karyawan" readonly>
                </div>


              </div>
              <div class="form-group row">
                <label for="tahun" class="col-sm-2 col-form-label">Tahun</label>
                <div class="col-sm-4">
                  <input type="text" class="form-control" name="tahun" readonly>
                </div>
              </div>

              <div class="form-row">
                <div class="form-group col-md-2">
                  <center><label for="kehadiran">Kehadiran</label></center>
                  <input type="text" class="form-control" id="kehadiran" name="kehadiran">
                </div>
                <div class="form-group col-md-2">
                  <center><label for="disiplin">Disiplin</label></center>
                  <input type="text" class="form-control" id="disiplin" name="disiplin">
                </div>
                <div class="form-group col-md-2">
                  <center><label for="kinerja">Kinerja</label></center>
                  <input type="text" class="form-control" id="kinerja" name="kinerja">
                </div>
                <div class="form-group col-md-2">
                  <center><label for="etika">Etika</label></center>
                  <input type="text" class="form-control" id="etika" name="etika">
                </div>
                <div class="form-group col-md-2">
                  <center><label for="loyalitas">Loyalitas</label></center>
                  <input type="text" class="form-control" id="loyalitas" name="loyalitas">
                </div>
              </div>

          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            <button type="submit" id="btnupdatenilai" class="btn btn-primary">Update</button>
          </div>
          </form>
        </div>
      </div>
    </div>

  </div><!-- /.container-fluid -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->

<script>
  function tampil() {
    let nip = document.getElementById("namalengkap").value;
    // console.log(nip)
    document.getElementById("textnip").innerHTML = nip;
    document.getElementById("nip").value = nip;
  }
</script>

<script>
  $(document).ready(function() {

    $('.selectnamalengkap').select2({
      theme: "bootstrap"
    });


    function tabelnilai(dataks) {
      $('#tableNilaiPegawai').DataTable({
        "data": dataks,
        "responsive": true,
        "dom": "<'row'<'col-sm-12 col-md-4'l><'col-sm-12 col-md-4'B><'col-sm-12 col-md-4'f>>" +
          "<'row'<'col-sm-12'tr>>" +
          "<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
        "buttons": [{
            extend: 'copyHtml5',
            text: '<i class="far fa-fw fa-copy"></i>',
            titleAttr: 'Copy'
          },
          {
            extend: 'excelHtml5',
            text: '<i class="far fa-fw fa-file-excel"></i>',
            titleAttr: 'Excel'
          },
          {
            extend: 'pdfHtml5',
            text: '<i class="far fa-fw fa-file-pdf"></i>',
            titleAttr: 'Pdf'
          },
          {
            extend: 'print',
            text: '<i class="fas fa-fw fa-print"></i>',
            titleAttr: 'Print'
          },
          {
            extend: 'colvis',
            text: '',
            titleAttr: 'Colvis'
          }
        ],

        columnDefs: [{
            targets: [12, 13, 14],
            visible: false
          },
          {
            className: "text-center",
            targets: "_all"
          }
        ],


        "columns": [{
            "data": null,
            "render": function(data, type, row, meta) {
              let a = '';
              return a;
            }
          },
          {
            targets: 0,
            data: null,
            className: 'text-center',
            searchable: false,
            orderable: false,

            "render": function(data, type, row, meta) {
              var r =
                '<input type="checkbox" name="deletecheckbox" id = "' + row.id + '"  value = "' + row.id + '" class="deletecheckbox"></input>';

              return r;
            },
          },
          {
            "data": null,
            "render": function(data, type, row, meta) {
              let a = '';
              a = `
                            <center><a href="" class="badge badge-info editnilaipegawai" value="${row.id}"><i class="far fa-fw fa-edit"></i></a></center>`

              return a;
            }
          },

          {
            "data": "nip"
          },
          {
            "data": "karyawan"
          },
          {
            "data": "tahun"
          },
          {
            "data": null,
            "render": function(data, type, row, meta) {
              let b = row.kehadiran.toUpperCase();
              return b;
            }
          },
          {

            "data": null,
            "render": function(data, type, row, meta) {
              let b = row.disiplin.toUpperCase();
              return b;
            }
          },
          {

            "data": null,
            "render": function(data, type, row, meta) {
              let b = row.kinerja.toUpperCase();
              return b;
            }
          },
          {

            "data": null,
            "render": function(data, type, row, meta) {
              let b = row.etika.toUpperCase();
              return b;
            }
          },
          {

            "data": null,
            "render": function(data, type, row, meta) {
              let b = row.loyalitas.toUpperCase();
              return b;
            }
          },
          {

            "data": null,
            "render": function(data, type, row, meta) {
              let a = '';
              if (`${row.kesimpulan}` == 0) {
                a = `<span class="badge bg-warning">No</span>`;
              } else {
                a = `<span class="badge bg-primary">Ok</span>`;
              }

              return a;
            }
          },


          {
            "data": "created_at"
          },
          {
            "data": "updated_at"
          },
          {
            "data": "user_update"

          }

        ],

      });
    }


    //fungsi fetch absen
    function fetchNilai() {
      $.ajax({
        url: '<?= base_url(); ?>/pegawai/fetchnilaipegawai',
        type: 'post',
        dataType: 'json',
        success: function(data) {
          // console.log(data);
          let i = "1";
          tabelnilai(data.nilai);
        }
      });
    }

    fetchNilai();

    // #column3_search is a <input type="text"> element


    $('#searchtahun').on('keyup', function() {
      $('#tableNilaiPegawai').DataTable()
        .columns(5)
        .search(this.value)
        .draw();
    });

    $(document).on('click', '#btntambahnilaibaru', function() {
      $('#tambahnilaiform')[0].reset();
    })

    $(document).on('click', '#btnimportnilaibaru', function() {
      $('#importnilaipegawai')[0].reset();
    })

    // tambah nilai
    $('#tambahnilaiform').submit(function() {
      event.preventDefault();

      $.ajax({
        url: '<?= base_url('/pegawai/savenilaipegawai'); ?>',
        type: 'post',
        data: $(this).serialize(),
        dataType: 'json',
        beforeSend: function() {
          // setting a timeout
          $('#btnsavenilai').attr('disabled');
          $("#btnsavenilai").html(`<div class="spinner-border" role="status"><span class="sr-only">Loading...</span></div>`);

        },
        success: function(data) {
          if (data.responce == "success") {
            $('#tambahModal').modal('hide');
            $('#tableNilaiPegawai').DataTable().destroy();

            fetchNilai();
            toastr["success"](data.pesan);
          } else {
            // console.log(data);
            toastr["error"](data.pesan);
          }
        },
        complete: function() {
          $('#btnsavenilai').removeAttr('disabled');
          $("#btnsavenilai").html(`Simpan`);

        },
      });
    });

    // modal edit
    $(document).on("click", ".editnilaipegawai", function() {
      event.preventDefault();

      let idnilai = $(this).attr("value")
      $.ajax({
        url: '<?= base_url('/pegawai/editmodalnilai'); ?>',
        type: 'post',
        data: {
          idnilai: idnilai
        },
        dataType: 'json',
        success: function(data) {
          if (data.responce == 'success') {
            // console.log(data);
            $('#editnilaiModal').modal('show');
            $("input[name='idnilai']").val(data.nilai.id);

            $("input[name='nip']").val(data.nilai.nip);
            $("input[name='karyawan']").val(data.nilai.karyawan);

            $("#edittextnip").text(data.nilai.nip);

            $("input[name='tahun']").val(data.nilai.tahun);

            $("input[name='kehadiran']").val(data.nilai.kehadiran);
            $("input[name='disiplin']").val(data.nilai.disiplin);
            $("input[name='kinerja']").val(data.nilai.kinerja);
            $("input[name='etika']").val(data.nilai.etika);
            $("input[name='loyalitas']").val(data.nilai.loyalitas);
          } else {

            toastr["error"](data.pesan);
          }

        }
      });
    });

    // edit absen

    $("#editnilaiform").submit(function(event) {
      event.preventDefault();
      $.ajax({
        url: '<?= base_url(); ?>/pegawai/editnilaipegawai',
        type: 'post',
        data: $(this).serialize(),
        dataType: 'json',
        beforeSend: function() {
          // setting a timeout
          $('#btnupdatenilai').attr('disabled');
          $("#btnupdatenilai").html(`<div class="spinner-border" role="status"><span class="sr-only">Loading...</span></div>`);

        },
        success: function(data) {
          // console.log(data);
          if (data.responce == "success") {
            $('#editnilaiModal').modal('hide');
            $('#tableNilaiPegawai').DataTable().destroy();
            fetchNilai();
            toastr["success"](data.pesan);
          } else {
            toastr["error"](data.pesan);
          }
          $('#tambahnilaiform')[0].reset();
        },
        complete: function() {
          $('#btnupdatenilai').removeAttr('disabled');
          $("#btnupdatenilai").html(`Update`);

        },

      });
    })

    // Check all 
    $('#checkall').click(function() {
      if ($(this).is(':checked')) {
        $('.deletecheckbox').prop('checked', true);
      } else {
        $('.deletecheckbox').prop('checked', false);
      }
    });

    $('.deletecheckbox').click(function() {
      if ($(this).is(':checked')) {
        $(this).closest('tr').addClass('removeRow');
      } else {
        $(this).closest('tr').removeClass('removeRow');
      }
    });


    $('#btndeletenilai').click(function() {
      let checkbox = $('.deletecheckbox:checked');

      if (checkbox.length > 0) {
        Swal.fire({
          title: 'Apa kamu yakin ingin menghapus ' + checkbox.length + ' nilai pegawai?',
          text: "kamu tidak akan bisa mengembalikannya!",
          icon: 'warning',
          showCancelButton: true,
          confirmButtonColor: '#3085d6',
          cancelButtonColor: '#d33',
          confirmButtonText: 'Ya, hapus saja!'
        }).then((result) => {
          if (result.isConfirmed) {

            let checkbox_value = [];
            $(checkbox).each(function() {
              checkbox_value.push($(this).val());
            });

            // console.log(checkbox);
            $.ajax({
              url: '<?= base_url('/pegawai/deletenilaipegawai'); ?>',
              type: "POST",
              data: {
                checkbox_value: checkbox_value
              },
              dataType: 'json',
              success: function(data) {
                if (data.responce == "success") {

                  Swal.fire(
                    'Deleted!',
                    'Data berhasil dihapus.',
                    'success'
                  )
                  $('#tableNilaiPegawai').DataTable().destroy();
                  fetchNilai();
                } else {
                  Swal.fire({
                    icon: 'error',
                    title: 'Oops...',
                    text: 'Ada yang tidak beres!',
                  })
                }
              }
            })

          }
        })

      } else {
        Swal.fire({
          icon: 'error',
          title: 'Oops...',
          text: 'Pilih minimal satu data',
        })

      }
    });


    // import pegawai
    $('#importnilaipegawai').submit(function() {
      event.preventDefault();
      $.ajax({
        url: '<?= base_url('/pegawai/importnilaipegawai'); ?>',
        type: 'post',
        data: new FormData(this),
        dataType: 'json',
        cache: false,
        processData: false,
        contentType: false,
        beforeSend: function() {
          // setting a timeout
          $('#btnimportnilai').attr('disabled');
          $("#btnimportnilai").html(`<div class="spinner-border" role="status"><span class="sr-only">Loading...</span></div>`);

        },
        success: function(data) {
          if (data.responce == "errorkosong") {

            $('#importModal').modal('hide');
            Swal.fire({
              icon: 'error',
              title: 'Oops...',
              text: 'Nip tidak ada di database pada baris ' + data.barisgagal
            })

          } else if (data.responce == "success") {


            $('#tableNilaiPegawai').DataTable().destroy();
            fetchNilai();
            $('#importModal').modal('hide');
            toastr["success"](data.pesan);

          } else {
            console.log(data);
            // console.log(data);
            toastr["error"](data.pesan);
          }
        },
        complete: function() {
          $('#btnimportnilai').removeAttr('disabled');
          $("#btnimportnilai").html(`Update`);

        },
      });

    });



  });
</script>

<?= $this->endSection(); ?>