<section class="content-header">
  <div class="container-fluid">
    <div class="row mb-2">
      <div class="col-sm-6">
        <h1><?php echo $page_title; ?></h1>
        <p class="text-muted mb-0"><?php echo $page_subtitle; ?></p>
      </div>
      <div class="col-sm-6 text-right">
        <ol class="breadcrumb float-sm-right">
          <li class="breadcrumb-item"><a href="<?php echo site_url('dashboard'); ?>">Dashboard</a></li>
          <li class="breadcrumb-item active">Data Pegawai</li>
        </ol>
      </div>
    </div>
  </div>
</section>

<section class="content">
  <div class="container-fluid">
    <div class="card card-danger card-outline">
      <div class="card-header d-flex align-items-center flex-wrap gap-2">
        <h3 class="card-title mr-auto"><i class="fa fa-users mr-1"></i> Daftar Pegawai</h3>

        <div class="d-flex align-items-center mr-2">
          <select id="filter_divisi" class="form-control form-control-sm mr-2" style="min-width:160px;">
            <option value="">Semua Divisi</option>
            <?php foreach ($list_divisi as $d): ?>
              <option value="<?php echo $d->id_divisi; ?>"><?php echo html_escape($d->nama_divisi); ?></option>
            <?php endforeach; ?>
          </select>
          <select id="filter_status" class="form-control form-control-sm mr-2" style="min-width:130px;">
            <option value="">Semua Status</option>
            <option value="AKTIF">Aktif</option>
            <option value="NONAKTIF">Nonaktif</option>
            <option value="CUTI_PANJANG">Cuti Panjang</option>
          </select>
        </div>

        <div class="d-flex" style="gap: 12px;">
          <a href="<?php echo site_url('master/pegawai/tambah'); ?>" class="btn btn-danger btn-sm">
            <i class="fa fa-plus mr-1"></i> Tambah Pegawai
          </a>
          <a href="<?php echo site_url('master/import_pegawai'); ?>" class="btn btn-info btn-sm">
            <i class="fa fa-upload mr-1"></i> Import Pegawai
          </a>
        </div>
      </div>
      <div class="card-body">
        <div class="table-responsive">
          <table id="tbl-pegawai" class="table table-bordered table-striped table-hover" style="width:100%">
            <thead>
              <tr>
                <th>NIP</th>
                <th>Nama Lengkap</th>
                <th>Divisi</th>
                <th>Jabatan</th>
                <th>Tgl Masuk</th>
                <th>Telepon</th>
                <th>Status</th>
                <th style="width:165px;">Aksi</th>
              </tr>
            </thead>
          </table>
        </div>
      </div>
    </div>
  </div>
</section>

<script>
document.addEventListener('DOMContentLoaded', function () {
  function initPegawaiTable() {
    if (!window.jQuery || !jQuery.fn || !jQuery.fn.DataTable) {
      return false;
    }

    var $ = window.jQuery;
    $.fn.dataTable.ext.errMode = 'none';
    var csrfTokenName = '<?php echo $this->security->get_csrf_token_name(); ?>';
    var csrfCookieName = '<?php echo $this->config->item('csrf_cookie_name'); ?>';

    function getCookie(name) {
      var escaped = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
      var match = document.cookie.match(new RegExp('(?:^|; )' + escaped + '=([^;]*)'));
      return match ? decodeURIComponent(match[1]) : '';
    }

    var table = $('#tbl-pegawai').DataTable({
      processing: true,
      serverSide: true,
      ajax: {
        url: '<?php echo site_url('master/pegawai/ajax_list'); ?>',
        type: 'POST',
        error: function (xhr) {
          console.error('Pegawai ajax_list error:', xhr.status, xhr.responseText);
          Swal.fire({
            icon: 'error',
            title: 'Gagal Memuat Data Pegawai',
            text: 'Silakan refresh halaman. Jika masih gagal, hubungi admin sistem.',
            confirmButtonColor: '#800000'
          });
        },
        data: function (d) {
          d.filter_divisi = $('#filter_divisi').val();
          d.filter_status = $('#filter_status').val();
          d[csrfTokenName] = getCookie(csrfCookieName);
        }
      },
      columns: [
        { data: 'nip' },
        { data: 'nama_lengkap' },
        { data: 'nama_divisi' },
        { data: 'nama_jabatan' },
        { data: 'tanggal_masuk' },
        { data: 'no_telepon', orderable: false },
        { data: 'status_pegawai', orderable: false },
        { data: 'aksi', orderable: false }
      ],
      language: {
        processing: 'Memuat... ',
        search: 'Cari:',
        lengthMenu: 'Tampilkan _MENU_ data',
        info: 'Menampilkan _START_ sampai _END_ dari _TOTAL_ data',
        infoEmpty: 'Tidak ada data',
        infoFiltered: '(difilter dari _MAX_ data)',
        zeroRecords: 'Data tidak ditemukan',
        paginate: {
          first: 'Awal',
          last: 'Akhir',
          next: 'Berikutnya',
          previous: 'Sebelumnya'
        }
      },
      pageLength: 25,
      order: [[1, 'asc']]
    });

    $('#tbl-pegawai').on('error.dt', function (e, settings, techNote, message) {
      console.error('DataTables error:', techNote, message);
    });

    $('#filter_divisi, #filter_status').on('change', function () { table.draw(); });

    $(document).on('click', '.btn-confirm', function (e) {
      e.preventDefault();
      var href = $(this).attr('href');
      var msg  = $(this).data('msg') || 'Lanjutkan aksi ini?';
      Swal.fire({
        title: 'Konfirmasi', text: msg, icon: 'question',
        showCancelButton: true, confirmButtonColor: '#800000',
        cancelButtonText: 'Batal', confirmButtonText: 'Ya, lanjutkan'
      }).then(function (r) { if (r.isConfirmed) window.location.href = href; });
    });

    return true;
  }

  if (!initPegawaiTable()) {
    window.addEventListener('load', initPegawaiTable, { once: true });
  }
});
</script>
