<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"><a href="<?php echo site_url('transaksi/izin_cuti'); ?>">Manajemen Izin</a></li>
          <li class="breadcrumb-item active"><?php echo $row ? 'Edit' : 'Tambah'; ?></li>
        </ol>
      </div>
    </div>
  </div>
</section>

<section class="content">
  <div class="container-fluid">
    <div class="card card-danger card-outline" style="max-width:700px;">
      <div class="card-header"><h3 class="card-title"><i class="fa fa-info-circle mr-1"></i> Form Pengajuan Izin</h3></div>
      <div class="card-body">
        <?php
          $form_action = site_url('transaksi/izin_cuti/simpan');
          echo form_open($form_action, ['id'=>'form-izincuti']);
          if ($row): echo form_hidden('id_izin', $row->id_izin); endif;
        ?>
        <div class="form-group">
          <label>Pegawai <span class="text-danger">*</span></label>
          <?php if ($row): ?>
            <input type="text" class="form-control" value="<?php echo html_escape((string) ($pegawai_label ?? '')); ?>" readonly>
            <?php echo form_hidden('id_pegawai', $row->id_pegawai); ?>
          <?php else: ?>
            <div class="position-relative">
              <input type="text" id="pegawai_keyword" class="form-control <?php echo form_error('id_pegawai') ? 'is-invalid' : ''; ?>" placeholder="Ketik NIP atau nama pegawai..." autocomplete="off">
              <div id="pegawai-suggest" class="list-group position-absolute w-100 shadow-sm" style="z-index: 1050; display:none; max-height: 220px; overflow-y: auto;"></div>
            </div>
            <input type="hidden" name="id_pegawai" id="id_pegawai" value="<?php echo set_value('id_pegawai'); ?>">
            <small class="form-text text-muted">Minimal 2 karakter. Pilih dari saran agar ID pegawai terisi otomatis.</small>
          <?php endif; ?>
          <?php if(form_error('id_pegawai')): ?><div class="invalid-feedback"><?php echo form_error('id_pegawai'); ?></div><?php endif; ?>
        </div>

        <div class="form-group">
          <label>Tipe Pengajuan <span class="text-danger">*</span></label>
          <select name="tipe" class="form-control <?php echo form_error('tipe') ? 'is-invalid' : ''; ?>">
            <option value="">-- Pilih Tipe --</option>
            <option value="IZIN" <?php echo set_select('tipe', 'IZIN', $row && $row->tipe === 'IZIN'); ?>>Izin Pribadi</option>
            <option value="SAKIT" <?php echo set_select('tipe', 'SAKIT', $row && $row->tipe === 'SAKIT'); ?>>Sakit</option>
            <option value="TIDAK_MASUK" <?php echo set_select('tipe', 'TIDAK_MASUK', $row && $row->tipe === 'TIDAK_MASUK'); ?>>Tidak Masuk</option>
            <option value="CUTI_TAHUNAN" <?php echo set_select('tipe', 'CUTI_TAHUNAN', $row && $row->tipe === 'CUTI_TAHUNAN'); ?>>Cuti Tahunan</option>
            <option value="CUTI_BERSAMA" <?php echo set_select('tipe', 'CUTI_BERSAMA', $row && $row->tipe === 'CUTI_BERSAMA'); ?>>Cuti Bersama</option>
            <option value="CUTI_KHUSUS" <?php echo set_select('tipe', 'CUTI_KHUSUS', $row && $row->tipe === 'CUTI_KHUSUS'); ?>>Cuti Khusus</option>
          </select>
          <?php if(form_error('tipe')): ?><div class="invalid-feedback"><?php echo form_error('tipe'); ?></div><?php endif; ?>
        </div>

        <div class="row">
          <div class="col-sm-6">
            <div class="form-group">
              <label>Tanggal Mulai <span class="text-danger">*</span></label>
              <input type="date" name="tanggal_mulai" id="tanggal_mulai"
                     class="form-control <?php echo form_error('tanggal_mulai') ? 'is-invalid' : ''; ?>"
                     value="<?php echo set_value('tanggal_mulai', ($row ? $row->tanggal_mulai : '')); ?>">
              <?php if(form_error('tanggal_mulai')): ?><div class="invalid-feedback"><?php echo form_error('tanggal_mulai'); ?></div><?php endif; ?>
            </div>
          </div>
          <div class="col-sm-6">
            <div class="form-group">
              <label>Tanggal Selesai <span class="text-danger">*</span></label>
              <input type="date" name="tanggal_selesai" id="tanggal_selesai"
                     class="form-control <?php echo form_error('tanggal_selesai') ? 'is-invalid' : ''; ?>"
                     value="<?php echo set_value('tanggal_selesai', ($row ? $row->tanggal_selesai : '')); ?>">
              <?php if(form_error('tanggal_selesai')): ?><div class="invalid-feedback"><?php echo form_error('tanggal_selesai'); ?></div><?php endif; ?>
            </div>
          </div>
        </div>

        <div class="form-group">
          <label>Durasi (Hari) <span class="text-danger">*</span></label>
          <div class="input-group">
            <input type="number" name="durasi_hari" id="durasi_hari" min="1"
                   class="form-control <?php echo form_error('durasi_hari') ? 'is-invalid' : ''; ?>"
                   value="<?php echo set_value('durasi_hari', ($row ? $row->durasi_hari : '1')); ?>">
            <div class="input-group-append">
              <span class="input-group-text">hari</span>
            </div>
          </div>
          <?php if(form_error('durasi_hari')): ?><div class="invalid-feedback"><?php echo form_error('durasi_hari'); ?></div><?php endif; ?>
          <small class="form-text text-muted">Dihitung otomatis dari tanggal mulai dan selesai</small>
        </div>

        <div class="form-group">
          <label>Alasan/Keterangan <span class="text-danger">*</span></label>
          <textarea name="alasan" class="form-control <?php echo form_error('alasan') ? 'is-invalid' : ''; ?>" 
                    rows="4" placeholder="Jelaskan alasan pengajuan..."><?php echo set_value('alasan', ($row ? $row->alasan : '')); ?></textarea>
          <?php if(form_error('alasan')): ?><div class="invalid-feedback"><?php echo form_error('alasan'); ?></div><?php endif; ?>
        </div>

        <?php if ($row && $row->status !== 'DRAFT'): ?>
        <div class="alert alert-info">
          <strong>Status:</strong> <?php echo $row->status; ?><br>
          <?php if ($row->approved_by && $row->approved_at): ?>
            <strong>Disetujui oleh:</strong> <?php echo $row->approved_by; ?> pada <?php echo format_tanggal_waktu($row->approved_at); ?>
          <?php elseif ($row->catatan): ?>
            <strong>Catatan:</strong> <?php echo html_escape($row->catatan); ?>
          <?php endif; ?>
        </div>
        <?php endif; ?>

        <div class="d-flex justify-content-between">
          <a href="<?php echo site_url('transaksi/izin_cuti'); ?>" class="btn btn-secondary"><i class="fa fa-arrow-left mr-1"></i> Kembali</a>
          <?php if (!$row || $row->status === 'DRAFT'): ?>
          <button type="submit" class="btn btn-danger"><i class="fa fa-save mr-1"></i> Simpan</button>
          <?php endif; ?>
        </div>
        <?php echo form_close(); ?>
      </div>
    </div>
  </div>
</section>

<script>
document.addEventListener('DOMContentLoaded', function () {
  var tanggalMulaiInput = document.getElementById('tanggal_mulai');
  var tanggalSelesaiInput = document.getElementById('tanggal_selesai');
  var durasiInput = document.getElementById('durasi_hari');

  function refreshDurasiHari() {
    var mulai = tanggalMulaiInput ? tanggalMulaiInput.value : '';
    var selesai = tanggalSelesaiInput ? tanggalSelesaiInput.value : '';

    if (!mulai || !selesai) {
      return;
    }

    var d1 = new Date(mulai);
    var d2 = new Date(selesai);
    var diff = Math.ceil((d2 - d1) / (1000 * 60 * 60 * 24)) + 1;

    if (diff > 0 && durasiInput) {
      durasiInput.value = diff;
    }
  }

  if (tanggalMulaiInput) {
    tanggalMulaiInput.addEventListener('change', refreshDurasiHari);
    tanggalMulaiInput.addEventListener('keyup', refreshDurasiHari);
  }
  if (tanggalSelesaiInput) {
    tanggalSelesaiInput.addEventListener('change', refreshDurasiHari);
    tanggalSelesaiInput.addEventListener('keyup', refreshDurasiHari);
  }

  <?php if (!$row): ?>
  var keywordInput = document.getElementById('pegawai_keyword');
  var idPegawaiInput = document.getElementById('id_pegawai');
  var suggestBox = document.getElementById('pegawai-suggest');
  var formIzin = document.getElementById('form-izincuti');
  var debounceTimer = null;
  var suggestions = [];

  function escapeHtml(text) {
    var div = document.createElement('div');
    div.textContent = text == null ? '' : String(text);
    return div.innerHTML;
  }

  function hideSuggest() {
    if (!suggestBox) return;
    suggestBox.style.display = 'none';
    suggestBox.innerHTML = '';
  }

  function renderSuggest(items) {
    if (!suggestBox) return;
    suggestions = items || [];
    if (!suggestions.length) {
      suggestBox.innerHTML = '<div class="list-group-item text-muted">Tidak ada pegawai ditemukan</div>';
      suggestBox.style.display = 'block';
      return;
    }

    var html = '';
    suggestions.forEach(function (item, index) {
      var label = item.label || ((item.nip || '') + ' - ' + (item.nama_lengkap || ''));
      html += '<button type="button" class="list-group-item list-group-item-action py-2" data-index="' + index + '">' + escapeHtml(label) + '</button>';
    });
    suggestBox.innerHTML = html;
    suggestBox.style.display = 'block';
  }

  function searchPegawai(keyword) {
    var url = '<?php echo site_url('transaksi/izin_cuti/ajax_pegawai_search'); ?>?q=' + encodeURIComponent(keyword);
    fetch(url, { credentials: 'same-origin' })
      .then(function (resp) { return resp.json(); })
      .then(function (rows) { renderSuggest(rows || []); })
      .catch(function () { hideSuggest(); });
  }

  if (keywordInput) {
    keywordInput.addEventListener('input', function () {
      var keyword = (keywordInput.value || '').trim();
      if (idPegawaiInput) idPegawaiInput.value = '';

      if (keyword.length < 2) {
        hideSuggest();
        return;
      }

      clearTimeout(debounceTimer);
      debounceTimer = setTimeout(function () {
        searchPegawai(keyword);
      }, 250);
    });

    keywordInput.addEventListener('blur', function () {
      setTimeout(hideSuggest, 180);
    });

    keywordInput.addEventListener('focus', function () {
      var keyword = (keywordInput.value || '').trim();
      if (keyword.length >= 2 && suggestBox && suggestBox.innerHTML !== '') {
        suggestBox.style.display = 'block';
      }
    });
  }

  if (suggestBox) {
    suggestBox.addEventListener('click', function (event) {
      var target = event.target.closest('button[data-index]');
      if (!target) return;

      var idx = parseInt(target.getAttribute('data-index'), 10);
      var selected = suggestions[idx];
      if (!selected) return;

      var label = selected.label || ((selected.nip || '') + ' - ' + (selected.nama_lengkap || ''));
      if (keywordInput) keywordInput.value = label;
      if (idPegawaiInput) idPegawaiInput.value = selected.id_pegawai || '';
      hideSuggest();
    });
  }

  if (formIzin) {
    formIzin.addEventListener('submit', function (e) {
      if (!idPegawaiInput || !idPegawaiInput.value) {
        e.preventDefault();
        if (window.Swal) {
          Swal.fire({
            icon: 'warning',
            title: 'Pegawai belum valid',
            text: 'Pilih pegawai dari daftar autocomplete berdasarkan NIP atau nama.'
          });
        }
      }
    });
  }
  <?php endif; ?>
});
</script>
