<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/lembur'); ?>">Manajemen Lembur</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-clock-o mr-1"></i> Form Pengajuan Lembur</h3></div>
      <div class="card-body">
        <?php
          $form_action = site_url('transaksi/lembur/simpan');
          echo form_open($form_action, ['id'=>'form-lembur']);
          if ($row): echo form_hidden('id_lembur', $row->id_lembur); 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($row->nip . ' - ' . $row->nama_lengkap); ?>" 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>Tanggal <span class="text-danger">*</span></label>
          <input type="date" name="tanggal" id="tanggal"
                 class="form-control <?php echo form_error('tanggal') ? 'is-invalid' : ''; ?>"
                 value="<?php echo set_value('tanggal', ($row ? $row->tanggal : date('Y-m-d'))); ?>">
          <?php if(form_error('tanggal')): ?><div class="invalid-feedback"><?php echo form_error('tanggal'); ?></div><?php endif; ?>
        </div>

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

        <div class="form-group">
          <label>Durasi (Jam) <span class="text-danger">*</span></label>
          <div class="input-group">
            <input type="number" name="durasi_jam" id="durasi_jam" min="0.5" step="0.5" readonly
                   class="form-control <?php echo form_error('durasi_jam') ? 'is-invalid' : ''; ?> bg-light"
                   value="<?php echo set_value('durasi_jam', ($row ? $row->durasi_jam : '0.5')); ?>">
            <div class="input-group-append">
              <span class="input-group-text">jam</span>
            </div>
          </div>
          <?php if(form_error('durasi_jam')): ?><div class="invalid-feedback"><?php echo form_error('durasi_jam'); ?></div><?php endif; ?>
          <small class="form-text text-muted">Dihitung otomatis dari jam mulai dan selesai. Validasi final mengikuti jadwal shift saat simpan.</small>
        </div>

        <div class="form-group">
          <label>Alasan <span class="text-danger">*</span></label>
          <textarea name="alasan" class="form-control <?php echo form_error('alasan') ? 'is-invalid' : ''; ?>" 
                    rows="4" placeholder="Jelaskan alasan lembur..."><?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/lembur'); ?>" 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 durasiInput = document.getElementById('durasi_jam');
  var jamMulaiInput = document.getElementById('jam_mulai');
  var jamSelesaiInput = document.getElementById('jam_selesai');

  function refreshDurasi() {
    var mulai = jamMulaiInput ? jamMulaiInput.value : '';
    var selesai = jamSelesaiInput ? jamSelesaiInput.value : '';

    if (mulai && selesai) {
      var partsMulai = mulai.split(':');
      var partsSelesai = selesai.split(':');
      var jamMulai = parseInt(partsMulai[0], 10) + parseInt(partsMulai[1], 10) / 60;
      var jamSelesai = parseInt(partsSelesai[0], 10) + parseInt(partsSelesai[1], 10) / 60;
      var durasi = jamSelesai - jamMulai;

      if (durasi <= 0) {
        durasi += 24;
      }

      durasi = Math.round(durasi * 100) / 100;
      if (durasiInput) durasiInput.value = durasi.toFixed(2);
      return;
    }

    if (durasiInput) durasiInput.value = '0.50';
  }

  if (jamMulaiInput) {
    jamMulaiInput.addEventListener('change', refreshDurasi);
    jamMulaiInput.addEventListener('keyup', refreshDurasi);
  }
  if (jamSelesaiInput) {
    jamSelesaiInput.addEventListener('change', refreshDurasi);
    jamSelesaiInput.addEventListener('keyup', refreshDurasi);
  }
  refreshDurasi();

  <?php if (!$row): ?>
  var keywordInput = document.getElementById('pegawai_keyword');
  var idPegawaiInput = document.getElementById('id_pegawai');
  var suggestBox = document.getElementById('pegawai-suggest');
  var formLembur = document.getElementById('form-lembur');
  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/lembur/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();
      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 || ''));
      keywordInput.value = label;
      idPegawaiInput.value = selected.id_pegawai || '';
      hideSuggest();
    });
  }

  if (formLembur) {
    formLembur.addEventListener('submit', function (e) {
      if (!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>
