<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<style>
:root{--t8:#0b5a52;--t7:#0b7a6e;--t6:#0d9488;--t5:#14b8a6;--t0:#f0fdfa;--r5:#ef4444;--r0:#fef2f2;--s0:#f8fafc;--s1:#f1f5f9;--s2:#e2e8f0;--s4:#94a3b8;--s5:#64748b;--s7:#334155;--s9:#0f172a;--rad:14px;--rsm:9px;--sha:0 4px 24px rgba(13,148,136,0.10),0 1px 4px rgba(0,0,0,0.05);}
*{box-sizing:border-box;}
.bsf-wrap{max-width:720px;margin:0 auto;}
.bsf-hdr{display:flex;justify-content:space-between;align-items:flex-start;flex-wrap:wrap;gap:14px;margin-bottom:22px;}
.bsf-hdr-l h4{font-size:1.2rem;font-weight:800;color:var(--t8);margin:0 0 5px;display:flex;align-items:center;gap:11px;}
.hi{width:40px;height:40px;border-radius:11px;background:linear-gradient(135deg,#0d9488,#14b8a6);display:flex;align-items:center;justify-content:center;color:#fff;font-size:1rem;box-shadow:0 4px 12px rgba(13,148,136,0.32);flex-shrink:0;}
.bsf-bc{display:flex;align-items:center;gap:6px;font-size:0.77rem;color:var(--s4);padding-left:51px;}
.bsf-bc a{color:var(--t6);text-decoration:none;font-weight:600;}
.bsf-bc .sep{color:var(--s2);}
.btn-back{display:inline-flex;align-items:center;gap:6px;padding:8px 18px;border-radius:50px;border:1.5px solid var(--s2);background:#fff;color:var(--s7);font-size:0.83rem;font-weight:600;text-decoration:none;transition:all .2s;}
.btn-back:hover{border-color:var(--t5);color:var(--t7);background:var(--t0);}
.bsf-card{background:#fff;border-radius:var(--rad);box-shadow:var(--sha);border:1.5px solid var(--s1);overflow:hidden;border-top:3px solid var(--t5);margin-bottom:16px;}
.bsf-ch{padding:15px 24px;border-bottom:1.5px solid var(--s1);background:var(--s0);font-size:0.9rem;font-weight:700;color:var(--t8);display:flex;align-items:center;gap:8px;}
.bsf-ch i{color:var(--t5);}
.bsf-cb{padding:24px;}
.alert-box{border-radius:var(--rsm);padding:12px 16px;font-size:0.83rem;margin-bottom:18px;display:flex;gap:10px;align-items:flex-start;}
.alert-err{background:var(--r0);border-left:4px solid var(--r5);color:#7f1d1d;}
.alert-err i{color:var(--r5);}
.fs{font-size:0.7rem;font-weight:800;text-transform:uppercase;letter-spacing:.6px;color:var(--s4);margin:20px 0 12px;padding-bottom:8px;border-bottom:1.5px solid var(--s1);}
.fs:first-child{margin-top:0;}
.fg{margin-bottom:16px;}
.fl{display:block;font-size:0.78rem;font-weight:700;color:var(--s5);margin-bottom:7px;}
.fl .req{color:var(--r5);}
.fl .hint{font-weight:400;color:var(--s4);font-size:0.72rem;margin-left:4px;}
.fi,.fsel,.fta{width:100%;padding:10px 14px;border:1.5px solid var(--s2);border-radius:var(--rsm);font-size:0.87rem;color:var(--s9);background:#fff;font-family:inherit;transition:border-color .2s,box-shadow .2s;}
.fi:focus,.fsel:focus,.fta:focus{border-color:var(--t6);box-shadow:0 0 0 3px rgba(13,148,136,0.12);outline:none;}
.fta{resize:vertical;min-height:90px;line-height:1.6;}
.fi[readonly]{background:var(--s0);color:var(--s4);}
.fg2{display:grid;grid-template-columns:1fr 1fr;gap:14px;}

/* ── Autocomplete ── */
.warga-wrap{position:relative;}
#wargaSearch{width:100%;}
.warga-sug{
  position:absolute;top:calc(100% + 4px);left:0;right:0;
  z-index:99999;
  background:#fff;
  border:2px solid var(--t5);
  border-radius:var(--rsm);
  box-shadow:0 20px 60px rgba(0,0,0,0.20);
  max-height:260px;overflow-y:auto;
  display:none;
}
.warga-sug.open{display:block !important;}
.ws-item{padding:11px 14px;cursor:pointer;border-bottom:1px solid var(--s1);}
.ws-item:last-child{border-bottom:none;}
.ws-item:hover,.ws-item.hov{background:var(--t0);}
.ws-nm{font-weight:700;color:var(--s9);font-size:0.88rem;}
.ws-sub{font-size:0.72rem;color:var(--s4);font-family:monospace;margin-top:2px;}
.ws-info-row{padding:11px 14px;color:var(--s4);font-size:0.83rem;text-align:center;}

/* Badge terpilih */
.warga-badge{
  display:none;padding:11px 14px;margin-top:0;
  background:var(--t0);border:2px solid var(--t5);border-radius:var(--rsm);
  align-items:center;gap:10px;
}
.warga-badge.show{display:flex;}
.warga-badge i{color:var(--t6);font-size:1.1rem;flex-shrink:0;}
.wb-info{flex:1;min-width:0;}
.wb-nm{font-weight:700;color:var(--t8);font-size:0.88rem;}
.wb-nik{font-size:0.72rem;color:var(--s5);font-family:monospace;margin-top:2px;}
.btn-ganti{flex-shrink:0;padding:5px 14px;border-radius:50px;border:1.5px solid var(--t6);background:#fff;color:var(--t7);font-size:0.75rem;font-weight:700;cursor:pointer;font-family:inherit;}
.btn-ganti:hover{background:var(--t0);}
.warga-warn{display:none;margin-top:6px;font-size:0.78rem;color:var(--r5);font-weight:600;}
.warga-warn.show{display:block;}

/* Jenis bantuan */
.jenis-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;}
.jenis-item{position:relative;border:2px solid var(--s2);border-radius:var(--rsm);padding:11px 12px 10px 38px;cursor:pointer;transition:all .18s;background:#fff;}
.jenis-item input{position:absolute;left:12px;top:50%;transform:translateY(-50%);width:17px;height:17px;cursor:pointer;accent-color:var(--t6);}
.jenis-item:hover{border-color:var(--t5);background:var(--t0);}
.jenis-item:has(input:checked){border-color:var(--t6);background:var(--t0);}
.ji-lbl{font-size:0.82rem;font-weight:700;color:var(--s9);}
.ji-dsc{font-size:0.7rem;color:var(--s4);margin-top:2px;}

/* Footer */
.bsf-ft{display:flex;justify-content:space-between;align-items:center;gap:10px;margin-top:22px;padding-top:18px;border-top:1.5px solid var(--s1);flex-wrap:wrap;}
.btn-sub{display:inline-flex;align-items:center;gap:7px;padding:11px 28px;border-radius:var(--rsm);border:none;background:linear-gradient(135deg,var(--t8),var(--t6));color:#fff;font-size:0.9rem;font-weight:700;cursor:pointer;box-shadow:0 4px 14px rgba(13,148,136,0.32);transition:all .2s;font-family:inherit;}
.btn-sub:hover{transform:translateY(-1px);}
.btn-sub:disabled{opacity:.7;cursor:not-allowed;transform:none;}
@media(max-width:600px){.bsf-cb{padding:16px;}.fg2,.jenis-grid{grid-template-columns:1fr;}.jenis-grid{grid-template-columns:repeat(2,1fr);}.bsf-ft{flex-direction:column-reverse;}.btn-sub,.btn-back{width:100%;justify-content:center;}}
</style>

<?php
$is_edit = isset($edit_mode) && $edit_mode;
if ($is_edit) {
    $val_nama  = htmlspecialchars($item->nama_lengkap ?? '');
    $val_warga = (int)$item->warga_id;
    $val_nik   = htmlspecialchars($item->nik ?? '');
    $val_nokk  = htmlspecialchars($item->no_kk ?? '');
} else {
    $val_nama  = htmlspecialchars(isset($post_nama)     ? $post_nama     : set_value('nama_cari'));
    $val_warga = (int)(isset($post_warga_id) ? $post_warga_id : set_value('warga_id', 0));
    $val_nik   = htmlspecialchars(isset($post_nik)      ? $post_nik      : set_value('nik_display'));
    $val_nokk  = htmlspecialchars(isset($post_nokk)     ? $post_nokk     : set_value('nokk_display'));
}

$jenis_aktif = [];
if ($is_edit && !empty($item->jenis_bantuan)) {
    $jenis_aktif = json_decode($item->jenis_bantuan, true) ?: [];
} else {
    $jp = $this->input->post('jenis_bantuan');
    if (!empty($jp) && is_array($jp)) $jenis_aktif = $jp;
}

$jenis_list = [
    'blt'     => ['lbl'=>'BLT',    'dsc'=>'Bantuan Langsung Tunai',   'ico'=>'bi-cash-coin',    'col'=>'#ef4444'],
    'sembako' => ['lbl'=>'Sembako','dsc'=>'Bantuan Pangan/Sembako',   'ico'=>'bi-basket-fill',  'col'=>'#10b981'],
    'pkh'     => ['lbl'=>'PKH',    'dsc'=>'Program Keluarga Harapan', 'ico'=>'bi-house-heart',  'col'=>'#3b82f6'],
    'bpnt'    => ['lbl'=>'BPNT',   'dsc'=>'Bantuan Pangan Non Tunai', 'ico'=>'bi-credit-card',  'col'=>'#f59e0b'],
    'lansia'  => ['lbl'=>'Lansia', 'dsc'=>'Bantuan Lanjut Usia',      'ico'=>'bi-person-heart', 'col'=>'#8b5cf6'],
    'lainnya' => ['lbl'=>'Lainnya','dsc'=>'Bantuan Lain-lain',        'ico'=>'bi-three-dots',   'col'=>'#64748b'],
];

$action   = $is_edit ? base_url('bansos/update/'.$item->id) : base_url('bansos/simpan');
$cari_url = base_url('bansos/cari_warga');
?>

<div class="bsf-wrap">

  <div class="bsf-hdr">
    <div class="bsf-hdr-l">
      <h4>
        <span class="hi"><i class="bi bi-heart-pulse-fill"></i></span>
        <?php echo $is_edit ? 'Edit Data Penerima' : 'Tambah Penerima Bantuan'; ?>
      </h4>
      <div class="bsf-bc">
        <a href="<?php echo base_url('dashboard'); ?>">Dashboard</a><span class="sep">/</span>
        <a href="<?php echo base_url('bansos'); ?>">Bantuan Sosial</a><span class="sep">/</span>
        <span><?php echo $is_edit ? 'Edit' : 'Tambah'; ?></span>
      </div>
    </div>
    <a href="<?php echo base_url('bansos'); ?>" class="btn-back"><i class="bi bi-arrow-left"></i> Kembali</a>
  </div>

  <div class="bsf-card">
    <div class="bsf-ch">
      <i class="bi bi-person-heart"></i>
      <?php echo $is_edit ? 'Form Edit Penerima Bantuan' : 'Form Pendataan Penerima Bantuan'; ?>
    </div>
    <div class="bsf-cb">

      <?php if ($this->session->flashdata('error')): ?>
      <div class="alert-box alert-err"><i class="bi bi-exclamation-triangle-fill"></i><div><?php echo $this->session->flashdata('error'); ?></div></div>
      <?php endif; ?>

      <?php if (validation_errors()): ?>
      <div class="alert-box alert-err"><i class="bi bi-exclamation-triangle-fill"></i><div><?php echo validation_errors(); ?></div></div>
      <?php endif; ?>

      <?php echo form_open($action, ['id'=>'formBansos']); ?>

        <input type="hidden" name="warga_id"     id="wargaId"  value="<?php echo $val_warga; ?>">
        <input type="hidden" name="nama_cari"    id="hNama"    value="<?php echo $val_nama; ?>">
        <input type="hidden" name="nik_display"  id="hNik"     value="<?php echo $val_nik; ?>">
        <input type="hidden" name="nokk_display" id="hNokk"    value="<?php echo $val_nokk; ?>">

        <div class="fs">Data Penerima</div>

        <div class="fg">
          <label class="fl">Pilih Warga <span class="req">*</span> <span class="hint">— ketik nama atau NIK</span></label>
          <div class="warga-wrap" id="wargaWrap">

            <!-- Input search -->
            <input type="text" id="wargaSearch" class="fi"
                   placeholder="Ketik minimal 2 huruf nama atau NIK..."
                   autocomplete="off" spellcheck="false"
                   style="<?php echo $val_warga ? 'display:none' : ''; ?>">

            <!-- Dropdown -->
            <div id="wargaSug" class="warga-sug"></div>

            <!-- Badge terpilih -->
            <div id="wargaBadge" class="warga-badge <?php echo $val_warga ? 'show' : ''; ?>">
              <i class="bi bi-person-check-fill"></i>
              <div class="wb-info">
                <div class="wb-nm"  id="wbNama"><?php echo $val_nama; ?></div>
                <div class="wb-nik" id="wbNik"><?php echo $val_nik ? 'NIK: '.$val_nik : ''; ?></div>
              </div>
              <?php if (!$is_edit): ?>
              <button type="button" class="btn-ganti" id="btnGanti"><i class="bi bi-arrow-repeat"></i> Ganti</button>
              <?php endif; ?>
            </div>

            <div class="warga-warn" id="wargaWarn"><i class="bi bi-exclamation-circle"></i> Silakan pilih warga dari daftar.</div>
          </div>
        </div>

        <div class="fg2">
          <div class="fg" style="margin-bottom:0;">
            <label class="fl">NIK</label>
            <input type="text" id="nikDisplay" class="fi" value="<?php echo $val_nik; ?>" placeholder="Otomatis terisi" readonly>
          </div>
          <div class="fg" style="margin-bottom:0;">
            <label class="fl">No KK</label>
            <input type="text" id="nokkDisplay" class="fi" value="<?php echo $val_nokk; ?>" placeholder="Otomatis terisi" readonly>
          </div>
        </div>

        <div class="fs" style="margin-top:22px;">Jenis Bantuan <span style="color:var(--r5);">*</span></div>
        <div class="jenis-grid">
          <?php foreach ($jenis_list as $key => $j): ?>
          <label class="jenis-item">
            <input type="checkbox" name="jenis_bantuan[]" value="<?php echo $key; ?>"
                   <?php echo in_array($key, $jenis_aktif) ? 'checked' : ''; ?>>
            <div class="ji-lbl"><i class="bi <?php echo $j['ico']; ?>" style="color:<?php echo $j['col']; ?>;margin-right:4px;"></i><?php echo $j['lbl']; ?></div>
            <div class="ji-dsc"><?php echo $j['dsc']; ?></div>
          </label>
          <?php endforeach; ?>
        </div>

        <div class="fs" style="margin-top:22px;">Info Bantuan</div>
        <div class="fg2">
          <div class="fg">
            <label class="fl">Tahun <span class="req">*</span></label>
            <select name="tahun" class="fsel" required>
              <?php for ($y = date('Y'); $y >= 2020; $y--):
                $sv = $is_edit ? $item->tahun : set_value('tahun', date('Y'));
                $sel = ($sv == $y) ? 'selected' : '';
              ?><option value="<?php echo $y; ?>" <?php echo $sel; ?>><?php echo $y; ?></option><?php endfor; ?>
            </select>
          </div>
          <div class="fg">
            <label class="fl">Status</label>
            <select name="status" class="fsel">
              <?php $cs = set_value('status', $is_edit ? $item->status : 'aktif'); ?>
              <option value="aktif"    <?php echo $cs==='aktif'    ?'selected':'';?>>Aktif</option>
              <option value="ditinjau" <?php echo $cs==='ditinjau' ?'selected':'';?>>Perlu Ditinjau</option>
              <option value="nonaktif" <?php echo $cs==='nonaktif' ?'selected':'';?>>Nonaktif</option>
            </select>
          </div>
        </div>

        <div class="fg">
          <label class="fl">Keterangan <span class="hint">— opsional</span></label>
          <textarea name="keterangan" class="fta" placeholder="Catatan tambahan..."><?php
            echo set_value('keterangan', $is_edit ? htmlspecialchars($item->keterangan ?? '') : '');
          ?></textarea>
        </div>

        <div class="bsf-ft">
          <a href="<?php echo base_url('bansos'); ?>" class="btn-back"><i class="bi bi-x-circle"></i> Batal</a>
          <button type="submit" class="btn-sub" id="btnSub">
            <i class="bi bi-floppy-fill"></i>
            <?php echo $is_edit ? 'Simpan Perubahan' : 'Tambahkan Data'; ?>
          </button>
        </div>

      <?php echo form_close(); ?>
    </div>
  </div>
</div>

<script>
/* ================================================================
   Warga Autocomplete — Vanilla JS (tidak bergantung jQuery timing)
   ================================================================ */
(function () {

  var CARI_URL = '<?php echo $cari_url; ?>';
  var IS_EDIT  = <?php echo $is_edit ? 'true' : 'false'; ?>;

  /* ── Elemen ── */
  var elSearch  = document.getElementById('wargaSearch');
  var elSug     = document.getElementById('wargaSug');
  var elBadge   = document.getElementById('wargaBadge');
  var elWbNama  = document.getElementById('wbNama');
  var elWbNik   = document.getElementById('wbNik');
  var elNik     = document.getElementById('nikDisplay');
  var elNokk    = document.getElementById('nokkDisplay');
  var elWargaId = document.getElementById('wargaId');
  var elHNama   = document.getElementById('hNama');
  var elHNik    = document.getElementById('hNik');
  var elHNokk   = document.getElementById('hNokk');
  var elWarn    = document.getElementById('wargaWarn');
  var elBtnGanti= document.getElementById('btnGanti');
  var elForm    = document.getElementById('formBansos');
  var elBtnSub  = document.getElementById('btnSub');
  var elWrap    = document.getElementById('wargaWrap');

  var timer = null;

  /* ── Helpers ── */
  function esc(str) {
    var d = document.createElement('div');
    d.textContent = str || '';
    return d.innerHTML;
  }

  function setSug(html) {
    elSug.innerHTML = html;
    elSug.classList.add('open');
  }

  function hideSug() {
    elSug.classList.remove('open');
    elSug.innerHTML = '';
  }

  function pilihWarga(id, nama, nik, kk) {
    elWargaId.value = id;
    elHNama.value   = nama;
    elHNik.value    = nik || '';
    elHNokk.value   = kk  || '';
    elNik.value     = nik || '';
    elNokk.value    = kk  || '';
    elWbNama.textContent = nama;
    elWbNik.textContent  = nik ? 'NIK: ' + nik : '';
    elBadge.classList.add('show');
    elSearch.style.display = 'none';
    hideSug();
    elWarn.classList.remove('show');
  }

  function resetWarga() {
    elWargaId.value = '';
    elHNama.value   = '';
    elHNik.value    = '';
    elHNokk.value   = '';
    elNik.value     = '';
    elNokk.value    = '';
    elBadge.classList.remove('show');
    elSearch.style.display = '';
    elSearch.value  = '';
    elSearch.focus();
    hideSug();
  }

  /* ── Fetch warga ── */
  function cariWarga(q) {
    setSug('<div class="ws-info-row"><i class="bi bi-hourglass-split"></i> Mencari...</div>');

    var url = CARI_URL + '?q=' + encodeURIComponent(q);

    fetch(url, {
      method: 'GET',
      headers: { 'X-Requested-With': 'XMLHttpRequest' }
    })
    .then(function (res) {
      if (!res.ok) throw new Error('HTTP ' + res.status);
      return res.json();
    })
    .then(function (data) {
      if (!Array.isArray(data) || data.length === 0) {
        setSug('<div class="ws-info-row"><i class="bi bi-inbox"></i> Warga tidak ditemukan</div>');
        return;
      }
      var html = '';
      data.forEach(function (d) {
        html += '<div class="ws-item"'
              + ' data-id="'   + esc(String(d.id)) + '"'
              + ' data-nama="' + esc(d.nama_lengkap || '') + '"'
              + ' data-nik="'  + esc(d.nik   || '') + '"'
              + ' data-kk="'   + esc(d.no_kk || '') + '">'
              + '<div class="ws-nm">'  + esc(d.nama_lengkap || '') + '</div>'
              + '<div class="ws-sub">NIK: ' + esc(d.nik || '-') + '</div>'
              + '</div>';
      });
      setSug(html);
    })
    .catch(function (err) {
      console.error('[bansos] cari_warga error:', err);
      setSug('<div class="ws-info-row" style="color:#ef4444;"><i class="bi bi-wifi-off"></i> Gagal memuat. Coba lagi.</div>');
    });
  }

  /* ── Event: mengetik di input ── */
  if (elSearch) {
    elSearch.addEventListener('input', function () {
      clearTimeout(timer);
      var q = elSearch.value.trim();
      elWargaId.value = ''; // reset pilihan
      elWarn.classList.remove('show');

      if (q.length < 2) { hideSug(); return; }
      timer = setTimeout(function () { cariWarga(q); }, 350);
    });

    /* Keyboard navigation */
    elSearch.addEventListener('keydown', function (e) {
      var items = elSug.querySelectorAll('.ws-item[data-id]');
      var hov   = elSug.querySelector('.ws-item.hov');
      if (e.key === 'ArrowDown') {
        e.preventDefault();
        items.forEach(function(i){ i.classList.remove('hov'); });
        var next = hov ? hov.nextElementSibling : items[0];
        if (next && next.dataset.id) next.classList.add('hov');
      } else if (e.key === 'ArrowUp') {
        e.preventDefault();
        items.forEach(function(i){ i.classList.remove('hov'); });
        var prev = hov ? hov.previousElementSibling : items[items.length - 1];
        if (prev && prev.dataset.id) prev.classList.add('hov');
      } else if (e.key === 'Enter') {
        var act = elSug.querySelector('.ws-item.hov');
        if (act && act.dataset.id) { e.preventDefault(); act.click(); }
      } else if (e.key === 'Escape') {
        hideSug();
      }
    });
  }

  /* ── Event: klik item sugesti (delegasi ke parent) ── */
  if (elSug) {
    elSug.addEventListener('click', function (e) {
      var item = e.target.closest('.ws-item[data-id]');
      if (!item) return;
      pilihWarga(item.dataset.id, item.dataset.nama, item.dataset.nik, item.dataset.kk);
    });
  }

  /* ── Event: tombol Ganti ── */
  if (elBtnGanti) {
    elBtnGanti.addEventListener('click', resetWarga);
  }

  /* ── Tutup dropdown saat klik luar ── */
  document.addEventListener('click', function (e) {
    if (elWrap && !elWrap.contains(e.target)) hideSug();
  });

  /* ── Validasi form sebelum submit ── */
  if (elForm) {
    elForm.addEventListener('submit', function (e) {
      /* Validasi warga */
      if (!elWargaId.value) {
        e.preventDefault();
        elWarn.classList.add('show');
        if (!IS_EDIT && elSearch) {
          elSearch.style.display = '';
          elSearch.focus();
        }
        elWrap.scrollIntoView({ behavior: 'smooth', block: 'center' });
        return;
      }
      /* Validasi jenis bantuan */
      var checked = document.querySelectorAll('input[name="jenis_bantuan[]"]:checked');
      if (!checked.length) {
        e.preventDefault();
        alert('Pilih minimal satu jenis bantuan.');
        return;
      }
      /* Disable tombol */
      if (elBtnSub) {
        elBtnSub.disabled = true;
        elBtnSub.innerHTML = '<i class="bi bi-hourglass-split"></i> Menyimpan...';
      }
    });
  }

  /* ── Restore state setelah validation error (mode tambah) ── */
  if (!IS_EDIT && elWargaId.value && elSearch) {
    elSearch.style.display = 'none';
    elBadge.classList.add('show');
  }

})();
</script>