<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">Manajemen Lembur</li>
        </ol>
      </div>
    </div>
  </div>
</section>

<section class="content">
  <div class="container-fluid">
    <div class="card card-danger card-outline">
      <div class="card-header">
        <h3 class="card-title"><i class="fa fa-filter mr-1"></i> Filter Data</h3>
      </div>
      <div class="card-body">
        <form id="form-filter" method="get" action="<?php echo site_url('transaksi/lembur'); ?>">
          <div class="row">
            <div class="col-sm-2">
              <div class="form-group">
                <label>Bulan</label>
                <select name="bulan" id="filter_bulan" class="form-control">
                  <?php for ($b = 1; $b <= 12; $b++): ?>
                    <option value="<?php echo $b; ?>" <?php echo ((int) $f_bulan === $b) ? 'selected' : ''; ?>>
                      <?php echo bulan_indonesia($b); ?>
                    </option>
                  <?php endfor; ?>
                </select>
              </div>
            </div>
            <div class="col-sm-2">
              <div class="form-group">
                <label>Tahun</label>
                <select name="tahun" id="filter_tahun" class="form-control">
                  <?php for ($y = ((int) date('Y') + 1); $y >= ((int) date('Y') - 5); $y--): ?>
                    <option value="<?php echo $y; ?>" <?php echo ((int) $f_tahun === $y) ? 'selected' : ''; ?>><?php echo $y; ?></option>
                  <?php endfor; ?>
                </select>
              </div>
            </div>
            <div class="col-sm-5">
              <div class="form-group">
                <label>Divisi</label>
                <select name="divisi" id="filter_divisi" class="form-control">
                  <option value="">-- Semua Divisi --</option>
                  <?php foreach ($divisi_list as $div): ?>
                    <option value="<?php echo (int) $div->id_divisi; ?>" <?php echo ((string) $f_divisi === (string) $div->id_divisi) ? 'selected' : ''; ?>>
                      <?php echo html_escape($div->nama_divisi); ?>
                    </option>
                  <?php endforeach; ?>
                </select>
              </div>
            </div>
            <div class="col-sm-3">
              <div class="form-group">
                <label>Status</label>
                <select name="status" id="filter_status" class="form-control">
                  <option value="">-- Semua Status --</option>
                  <option value="DRAFT" <?php echo ($f_status === 'DRAFT') ? 'selected' : ''; ?>>Draft</option>
                  <option value="APPROVED" <?php echo ($f_status === 'APPROVED') ? 'selected' : ''; ?>>Disetujui</option>
                  <option value="REJECTED" <?php echo ($f_status === 'REJECTED') ? 'selected' : ''; ?>>Ditolak</option>
                </select>
              </div>
            </div>
          </div>
        </form>
      </div>
    </div>

    <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-clock-o mr-1"></i> Daftar Pengajuan Lembur</h3>
        <a href="<?php echo site_url('transaksi/lembur/tambah'); ?>" class="btn btn-danger btn-sm">
          <i class="fa fa-plus mr-1"></i> Tambah Manual
        </a>
      </div>
      <div class="card-body">
        <table id="tbl-lembur" class="table table-bordered table-hover table-striped">
          <thead>
            <tr>
              <th style="width:40px;">#</th>
              <th>NIP</th>
              <th>Nama Lengkap</th>
              <th>Divisi</th>
              <th>Tanggal</th>
              <th>Jam Mulai</th>
              <th>Jam Selesai</th>
              <th style="text-align:center;">Jam</th>
              <th>Alasan</th>
              <th>Status</th>
              <th style="width:150px;">Aksi</th>
            </tr>
          </thead>
          <tbody></tbody>
        </table>
      </div>
    </div>
  </div>
</section>

<!-- Modal Reject -->
<div class="modal fade" id="modal-reject" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Tolak Pengajuan</h5>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>
      <div class="modal-body">
        <div class="form-group">
          <label>Catatan Penolakan</label>
          <textarea id="catatan-reject" class="form-control" rows="4" placeholder="Alasan penolakan..."></textarea>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
        <button type="button" class="btn btn-danger" id="btn-confirm-reject">Tolak</button>
      </div>
    </div>
  </div>
</div>

<script>
function initLemburWhenReady(retry) {
  if (!window.jQuery || !window.jQuery.fn || !window.jQuery.fn.DataTable) {
    if (retry < 50) {
      setTimeout(function () { initLemburWhenReady(retry + 1); }, 100);
      return;
    }
    console.error('jQuery/DataTables gagal dimuat.');
    return;
  }

  var $ = window.jQuery;
  var csrfTokenName = '<?php echo $this->security->get_csrf_token_name(); ?>';
  var csrfCookieName = '<?php echo $this->config->item('csrf_cookie_name'); ?>';
  var idLemburToReject = null;

  function readCookie(name) {
    var cookies = document.cookie ? document.cookie.split('; ') : [];
    for (var i = 0; i < cookies.length; i++) {
      var parts = cookies[i].split('=');
      var key = parts.shift();
      if (key === name) {
        return decodeURIComponent(parts.join('='));
      }
    }
    return '';
  }

  var table = $('#tbl-lembur').DataTable({
    processing: true,
    serverSide: true,
    ajax: {
      url: '<?php echo site_url('transaksi/lembur/ajax_list'); ?>',
      type: 'GET',
      data: function (d) {
        d.tahun = $('#filter_tahun').val();
        d.bulan = $('#filter_bulan').val();
        d.divisi = $('#filter_divisi').val();
        d.filter_status = $('#filter_status').val();
      }
    },
    columns: [
      { data: null, orderable: false, render: function (data, type, row, meta) { return meta.row + meta.settings._iDisplayStart + 1; } },
      { data: 'nip' },
      { data: 'nama_lengkap' },
      { data: 'nama_divisi' },
      { data: 'tanggal' },
      { data: 'jam_mulai', className: 'text-center' },
      { data: 'jam_selesai', className: 'text-center' },
      { data: 'durasi_jam', className: 'text-center' },
      { data: 'alasan' },
      { data: 'status', className: 'text-center' },
      { data: 'aksi', className: 'text-center', orderable: false, searchable: 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: [[4, 'desc']]
  });

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

  $(document).on('click', '.btn-approve', function () {
    var id = $(this).data('id');
    Swal.fire({
      icon: 'question',
      title: 'Setujui pengajuan ini?',
      showCancelButton: true,
      confirmButtonText: 'Ya, setujui',
      cancelButtonText: 'Batal',
      confirmButtonColor: '#800000'
    }).then(function (result) {
      if (!result.isConfirmed) {
        return;
      }
      var postData = {};
      postData[csrfTokenName] = readCookie(csrfCookieName);

      $.ajax({
        url: '<?php echo site_url('transaksi/lembur/approve'); ?>/' + id,
        type: 'POST',
        data: postData,
        dataType: 'json',
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
      }).done(function (response) {
        if (!response.success) {
          Swal.fire({ icon: 'error', title: 'Gagal', text: response.message || 'Proses gagal' });
          return;
        }
        Swal.fire({ icon: 'success', title: 'Berhasil', text: response.message || 'Pengajuan disetujui', timer: 1200, showConfirmButton: false });
        table.draw(false);
      }).fail(function () {
        Swal.fire({ icon: 'error', title: 'Gagal', text: 'Request approve gagal.' });
      });
    });
  });

  $(document).on('click', '.btn-reject', function () {
    idLemburToReject = $(this).data('id');
    $('#catatan-reject').val('');
    $('#modal-reject').modal('show');
  });

  $('#btn-confirm-reject').on('click', function () {
    if (!idLemburToReject) {
      return;
    }
    var postData = {
      catatan: $('#catatan-reject').val()
    };
    postData[csrfTokenName] = readCookie(csrfCookieName);

    $.ajax({
      url: '<?php echo site_url('transaksi/lembur/reject'); ?>/' + idLemburToReject,
      type: 'POST',
      data: postData,
      dataType: 'json',
      headers: { 'X-Requested-With': 'XMLHttpRequest' }
    }).done(function (response) {
      if (!response.success) {
        Swal.fire({ icon: 'error', title: 'Gagal', text: response.message || 'Proses gagal' });
        return;
      }
      $('#modal-reject').modal('hide');
      Swal.fire({ icon: 'success', title: 'Berhasil', text: response.message || 'Pengajuan ditolak', timer: 1200, showConfirmButton: false });
      table.draw(false);
    }).fail(function () {
      Swal.fire({ icon: 'error', title: 'Gagal', text: 'Request reject gagal.' });
    });
  });

  $(document).on('click', '.btn-confirm-delete', function () {
    var id = $(this).data('id');
    Swal.fire({
      icon: 'warning',
      title: 'Hapus pengajuan ini?',
      text: 'Data yang dihapus tidak dapat dikembalikan.',
      showCancelButton: true,
      confirmButtonText: 'Ya, hapus',
      cancelButtonText: 'Batal',
      confirmButtonColor: '#800000'
    }).then(function (result) {
      if (result.isConfirmed) {
        window.location.href = '<?php echo site_url('transaksi/lembur/hapus'); ?>/' + id;
      }
    });
  });
}

initLemburWhenReady(0);
</script>
