<?php defined('BASEPATH') OR exit('No direct script access allowed');
$edit = $edit_mode ?? false;
$item = $item ?? null;
$fotos_lama = $item ? (json_decode($item->foto_rumah??'[]',true)?:[]) : [];
?>
<style>
:root{--t8:#0b5a52;--t7:#0b7a6e;--t6:#0d9488;--t5:#14b8a6;--t1:#ccfbf1;--t0:#f0fdfa;--a2:#d97706;--a4:#fef3c7;--a5:#fffbeb;--r5:#ef4444;--r0:#fef2f2;--r1:#fee2e2;--s0:#f8fafc;--s1:#f1f5f9;--s2:#e2e8f0;--s4:#94a3b8;--s5:#64748b;--s7:#334155;--s9:#0f172a;--rad:14px;--rsm:9px;--rxs:6px;--sha:0 4px 24px rgba(13,148,136,0.10),0 1px 4px rgba(0,0,0,0.05);}
.wf-hdr{display:flex;justify-content:space-between;align-items:flex-start;flex-wrap:wrap;gap:14px;margin-bottom:20px;}
.wf-hdr-l h4{font-size:1.2rem;font-weight:800;color:var(--t8);margin:0 0 5px;display:flex;align-items:center;gap:11px;}
.wf-hdr-l h4 .hi{width:38px;height:38px;border-radius:10px;background:linear-gradient(135deg,#d97706,#f59e0b);display:flex;align-items:center;justify-content:center;color:#fff;font-size:1rem;box-shadow:0 4px 12px rgba(217,119,6,0.3);flex-shrink:0;}
.wf-bc{display:flex;align-items:center;gap:6px;font-size:0.77rem;color:var(--s4);padding-left:49px;}
.wf-bc a{color:var(--t6);text-decoration:none;font-weight:600;}
.wf-box{background:#fff;border-radius:var(--rad);box-shadow:var(--sha);border:1.5px solid var(--s1);overflow:hidden;max-width:780px;margin:0 auto;}
.wf-sec{border-bottom:1.5px solid var(--s1);}
.wf-sec:last-child{border-bottom:none;}
.wf-sh{background:var(--s0);padding:13px 22px;display:flex;align-items:center;gap:8px;}
.wf-sh h6{margin:0;font-size:0.85rem;font-weight:800;color:var(--t8);}
.wf-sh .sico{width:28px;height:28px;border-radius:7px;background:var(--t0);color:var(--t6);display:flex;align-items:center;justify-content:center;font-size:0.78rem;}
.wf-body{padding:20px 22px;}
.frow{display:grid;grid-template-columns:1fr 1fr;gap:14px;margin-bottom:14px;}
.frow.full{grid-template-columns:1fr;}
.fg{display:flex;flex-direction:column;}
.fg label{font-size:0.78rem;font-weight:700;color:var(--s5);margin-bottom:5px;}
.fg label .req{color:var(--r5);}
.fc{padding:9px 12px;border-radius:var(--rsm);border:1.5px solid var(--s2);font-size:0.84rem;color:var(--s7);transition:border-color .18s;background:#fff;width:100%;box-sizing:border-box;}
.fc:focus{border-color:var(--t5);outline:none;box-shadow:0 0 0 3px rgba(20,184,166,0.12);}
.fc.err{border-color:var(--r5);}
select.fc{cursor:pointer;}
.err-msg{font-size:0.74rem;color:var(--r5);margin-top:4px;}
/* warga search */
.ws-wrap{position:relative;}
.ws-res{display:none;position:absolute;top:100%;left:0;right:0;background:#fff;border:1.5px solid var(--t5);border-radius:var(--rsm);box-shadow:var(--sha);z-index:50;max-height:220px;overflow-y:auto;}
.ws-item{padding:9px 13px;cursor:pointer;font-size:0.82rem;color:var(--s7);border-bottom:1px solid var(--s1);transition:background .13s;}
.ws-item:hover,.ws-item:focus{background:var(--t0);}
.ws-item:last-child{border-bottom:none;}
.ws-nm{font-weight:700;color:var(--s9);}
.ws-nik{font-size:0.72rem;color:var(--s4);font-family:monospace;}
.warga-info{display:flex;gap:10px;align-items:center;background:var(--t0);border:1.5px solid var(--t1);border-radius:var(--rsm);padding:10px 14px;margin-top:8px;}
.warga-ico{width:36px;height:36px;border-radius:9px;background:var(--t6);color:#fff;display:flex;align-items:center;justify-content:center;font-size:0.9rem;flex-shrink:0;}
/* foto upload */
.foto-drop{border:2px dashed var(--s2);border-radius:var(--rsm);padding:28px 20px;text-align:center;cursor:pointer;transition:all .2s;background:var(--s0);}
.foto-drop:hover,.foto-drop.drag{border-color:var(--t5);background:var(--t0);}
.foto-drop i{font-size:2rem;color:var(--s4);margin-bottom:8px;}
.foto-drop p{font-size:0.8rem;color:var(--s4);margin:4px 0;}
.foto-drop small{font-size:0.72rem;color:var(--s4);}
.foto-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(130px,1fr));gap:10px;margin-top:12px;}
.foto-item{position:relative;border-radius:var(--rsm);overflow:hidden;aspect-ratio:1;border:1.5px solid var(--s2);}
.foto-item img{width:100%;height:100%;object-fit:cover;display:block;}
.foto-del{position:absolute;top:4px;right:4px;width:22px;height:22px;background:rgba(239,68,68,0.9);border:none;border-radius:50%;color:#fff;font-size:0.7rem;display:flex;align-items:center;justify-content:center;cursor:pointer;transition:opacity .15s;}
.foto-del:hover{opacity:.8;}
.foto-lama-badge{position:absolute;bottom:4px;left:4px;background:rgba(0,0,0,0.55);color:#fff;font-size:0.62rem;padding:1px 6px;border-radius:50px;font-weight:700;}
/* kondisi visual selector */
.kondisi-opts{display:grid;grid-template-columns:repeat(4,1fr);gap:8px;}
.kopt{border:2px solid var(--s2);border-radius:var(--rsm);padding:10px 8px;text-align:center;cursor:pointer;transition:all .18s;background:#fff;}
.kopt:hover{border-color:var(--t4);}
.kopt.sel-baik{border-color:#10b981;background:var(--g0);}
.kopt.sel-sedang{border-color:var(--a3);background:var(--a5);}
.kopt.sel-buruk{border-color:var(--r5);background:var(--r0);}
.kopt.sel-sangat_buruk{border-color:#9d174d;background:#fdf2f8;}
.kopt input[type=radio]{display:none;}
.kopt-ico{font-size:1.4rem;margin-bottom:4px;}
.kopt-lbl{font-size:0.72rem;font-weight:700;color:var(--s7);}
/* action bar */
.wf-acts{padding:16px 22px;background:var(--s0);border-top:1.5px solid var(--s1);display:flex;gap:10px;justify-content:flex-end;}
.btn-sv{padding:10px 28px;border-radius:50px;border:none;background:var(--t6);color:#fff;font-size:0.85rem;font-weight:700;cursor:pointer;box-shadow:0 3px 12px rgba(13,148,136,0.28);transition:all .2s;}
.btn-sv:hover{background:var(--t7);}
.btn-bk{padding:10px 20px;border-radius:50px;border:1.5px solid var(--s2);background:#fff;color:var(--s5);font-size:0.85rem;font-weight:700;text-decoration:none;transition:all .2s;}
.btn-bk:hover{background:var(--s1);}
/* admin status section */
.adm-status{background:var(--a5);border:1.5px solid var(--a4);border-radius:var(--rsm);padding:14px 16px;margin-bottom:14px;}
.adm-status h6{font-size:0.8rem;font-weight:800;color:var(--a2);margin:0 0 10px;}
@media(max-width:600px){.frow{grid-template-columns:1fr;}.kondisi-opts{grid-template-columns:repeat(2,1fr);}  }
</style>

<div class="pg-wrapper">

<div class="wf-hdr">
  <div class="wf-hdr-l">
    <h4><span class="hi"><i class="bi bi-<?php echo $edit?'pencil':'plus-circle';?>-fill"></i></span><?php echo $edit?'Edit Pengajuan':'Ajukan Data Warga Kurang Mampu';?></h4>
    <div class="wf-bc">
      <a href="<?php echo base_url('dashboard');?>">Dashboard</a><span style="color:var(--s2);">/</span>
      <a href="<?php echo base_url('warga_kurang_mampu');?>">Warga Kurang Mampu</a><span style="color:var(--s2);">/</span>
      <span><?php echo $edit?'Edit':'Tambah';?></span>
    </div>
  </div>
</div>

<div class="wf-box">
  <form method="post"
    action="<?php echo $edit ? base_url('warga_kurang_mampu/update/'.$item->id) : base_url('warga_kurang_mampu/simpan');?>"
    enctype="multipart/form-data" id="wkmForm">

    <?php echo form_hidden($this->security->get_csrf_token_name(), $this->security->get_csrf_hash());?>

    <!-- SECTION: Data Warga -->
    <div class="wf-sec">
      <div class="wf-sh"><div class="sico"><i class="bi bi-person-fill"></i></div><h6>Data Warga</h6></div>
      <div class="wf-body">

        <?php if($is_admin): // Admin bisa pilih warga ?>
        <div class="frow full">
          <div class="fg">
            <label>Cari Warga <span class="req">*</span></label>
            <div class="ws-wrap">
              <input type="text" id="wargaSearch" class="fc" placeholder="Ketik nama atau NIK warga..."
                autocomplete="off"
                value="<?php echo $edit ? htmlspecialchars($item->nama_lengkap??'') : '';?>">
              <div class="ws-res" id="wargaRes"></div>
            </div>
            <input type="hidden" name="warga_id" id="wargaId" value="<?php echo $edit ? $item->warga_id : '';?>" required>
          </div>
        </div>
        <div id="wargaInfo" style="<?php echo ($edit&&$item->nama_lengkap)?'':'display:none;';?>">
          <div class="warga-info">
            <div class="warga-ico"><i class="bi bi-person"></i></div>
            <div>
              <div style="font-weight:700;font-size:0.88rem;" id="wi-nama"><?php echo $edit?htmlspecialchars($item->nama_lengkap??''):'' ;?></div>
              <div style="font-size:0.75rem;color:var(--s5);">NIK: <span id="wi-nik"><?php echo $edit?htmlspecialchars($item->nik??''):'' ;?></span> | KK: <span id="wi-kk"><?php echo $edit?htmlspecialchars($item->no_kk??''):'' ;?></span></div>
            </div>
          </div>
        </div>

        <?php else: // Non-admin: tampilkan info warga dirinya ?>
        <div class="warga-info">
          <div class="warga-ico"><i class="bi bi-person"></i></div>
          <div>
            <div style="font-weight:700;font-size:0.88rem;"><?php echo htmlspecialchars($this->session->userdata('nama_lengkap')??$this->session->userdata('username')??'');?></div>
            <div style="font-size:0.75rem;color:var(--s5);">Data pengajuan atas nama akun Anda</div>
          </div>
        </div>
        <?php endif;?>

      </div>
    </div>

    <!-- SECTION: Data Ekonomi -->
    <div class="wf-sec">
      <div class="wf-sh"><div class="sico"><i class="bi bi-cash-stack"></i></div><h6>Data Ekonomi</h6></div>
      <div class="wf-body">
        <div class="frow">
          <div class="fg">
            <label>Penghasilan / Bulan (Rp) <span class="req">*</span></label>
            <input type="number" name="penghasilan_bulan" class="fc <?php echo form_error('penghasilan_bulan')?'err':'';?>"
              placeholder="0" min="0" value="<?php echo set_value('penghasilan_bulan', $item->penghasilan_bulan??'');?>">
            <?php echo form_error('penghasilan_bulan','<div class="err-msg">','</div>');?>
          </div>
          <div class="fg">
            <label>Pekerjaan</label>
            <input type="text" name="pekerjaan" class="fc" placeholder="Buruh harian, petani, dll..."
              value="<?php echo set_value('pekerjaan', $item->pekerjaan??'');?>">
          </div>
        </div>
        <div class="frow">
          <div class="fg">
            <label>Jumlah Tanggungan <span class="req">*</span></label>
            <input type="number" name="jml_tanggungan" class="fc <?php echo form_error('jml_tanggungan')?'err':'';?>"
              placeholder="0" min="0" max="20" value="<?php echo set_value('jml_tanggungan', $item->jml_tanggungan??'');?>">
            <?php echo form_error('jml_tanggungan','<div class="err-msg">','</div>');?>
          </div>
          <div class="fg">
            <label>Status Kepemilikan Rumah</label>
            <select name="status_rumah" class="fc">
              <?php
              $sr_opts = ['milik_sendiri'=>'Milik Sendiri','sewa'=>'Sewa/Kontrak','numpang'=>'Numpang','dinas'=>'Rumah Dinas','lainnya'=>'Lainnya'];
              $sr_val  = $item->status_rumah ?? 'milik_sendiri';
              foreach($sr_opts as $v=>$l): ?>
              <option value="<?php echo $v;?>" <?php echo $sr_val==$v?'selected':'';?>><?php echo $l;?></option>
              <?php endforeach;?>
            </select>
          </div>
        </div>
      </div>
    </div>

    <!-- SECTION: Kondisi Rumah -->
    <div class="wf-sec">
      <div class="wf-sh"><div class="sico"><i class="bi bi-house-fill"></i></div><h6>Kondisi Rumah</h6></div>
      <div class="wf-body">
        <div class="frow full">
          <div class="fg">
            <label>Kondisi Fisik Rumah <span class="req">*</span></label>
            <?php
            $kr_val = $item->kondisi_rumah ?? 'sedang';
            $kr_opts = [
              'baik'        => ['🏠','Baik','sel-baik'],
              'sedang'      => ['🏡','Sedang','sel-sedang'],
              'buruk'       => ['🏚','Buruk','sel-buruk'],
              'sangat_buruk'=> ['🪨','Sangat Buruk','sel-sangat_buruk'],
            ];
            ?>
            <div class="kondisi-opts">
              <?php foreach($kr_opts as $v=>[$ico,$lbl,$cls]): ?>
              <label class="kopt <?php echo $kr_val==$v ? $cls : '';?>" id="kopt-<?php echo $v;?>">
                <input type="radio" name="kondisi_rumah" value="<?php echo $v;?>" <?php echo $kr_val==$v?'checked':'';?> onchange="selectKondisi('<?php echo $v;?>','<?php echo $cls;?>')">
                <div class="kopt-ico"><?php echo $ico;?></div>
                <div class="kopt-lbl"><?php echo $lbl;?></div>
              </label>
              <?php endforeach;?>
            </div>
            <?php echo form_error('kondisi_rumah','<div class="err-msg">','</div>');?>
          </div>
        </div>
      </div>
    </div>

    <!-- SECTION: Alasan & Keterangan -->
    <div class="wf-sec">
      <div class="wf-sh"><div class="sico"><i class="bi bi-chat-text-fill"></i></div><h6>Alasan Pengajuan</h6></div>
      <div class="wf-body">
        <div class="frow full" style="margin-bottom:0;">
          <div class="fg">
            <label>Alasan Pengajuan Bantuan <span class="req">*</span></label>
            <textarea name="alasan_pengajuan" class="fc <?php echo form_error('alasan_pengajuan')?'err':'';?>"
              rows="4" placeholder="Jelaskan kondisi dan alasan pengajuan bantuan sosial..."><?php echo set_value('alasan_pengajuan', $item->alasan_pengajuan??'');?></textarea>
            <?php echo form_error('alasan_pengajuan','<div class="err-msg">','</div>');?>
          </div>
        </div>
        <div class="frow full" style="margin-top:12px;margin-bottom:0;">
          <div class="fg">
            <label>Keterangan Tambahan</label>
            <textarea name="keterangan_tambahan" class="fc" rows="2" placeholder="Informasi tambahan (opsional)..."><?php echo set_value('keterangan_tambahan', $item->keterangan_tambahan??'');?></textarea>
          </div>
        </div>
      </div>
    </div>

    <!-- SECTION: Foto Rumah -->
    <div class="wf-sec">
      <div class="wf-sh"><div class="sico"><i class="bi bi-images"></i></div><h6>Foto Rumah</h6></div>
      <div class="wf-body">

        <!-- Foto lama (edit mode) -->
        <?php if($edit && !empty($fotos_lama)): ?>
        <div style="margin-bottom:12px;">
          <div style="font-size:0.78rem;font-weight:700;color:var(--s5);margin-bottom:8px;">📷 Foto Existing (centang untuk hapus):</div>
          <div class="foto-grid" id="fotoLamaGrid">
            <?php foreach($fotos_lama as $i => $fn): ?>
            <div class="foto-item" id="foto-lama-<?php echo $i;?>">
              <img src="<?php echo base_url('uploads/wkm/'.$fn);?>" alt="Foto <?php echo $i+1;?>">
              <div class="foto-lama-badge">Foto <?php echo $i+1;?></div>
              <label style="position:absolute;top:4px;left:4px;cursor:pointer;">
                <input type="checkbox" name="hapus_foto[]" value="<?php echo $i;?>" class="hapus-foto-cb"
                  onchange="toggleFotoHapus(this, <?php echo $i;?>)"
                  style="width:16px;height:16px;accent-color:var(--r5);">
              </label>
            </div>
            <?php endforeach;?>
          </div>
        </div>
        <?php endif;?>

        <!-- Upload foto baru -->
        <div class="foto-drop" id="fotoDrop" onclick="document.getElementById('fotoInput').click()">
          <i class="bi bi-cloud-arrow-up"></i>
          <p style="font-weight:700;margin:0;"><?php echo $edit?'Upload Foto Tambahan':'Upload Foto Rumah';?></p>
          <p>Klik atau seret file ke sini</p>
          <small>JPG, PNG, WEBP — Maksimal 5 MB per foto — Bisa pilih banyak</small>
        </div>
        <input type="file" name="foto_rumah[]" id="fotoInput" multiple accept=".jpg,.jpeg,.png,.webp" style="display:none;">
        <div class="foto-grid" id="previewGrid"></div>

      </div>
    </div>

    <!-- SECTION: Status (admin edit only) -->
    <?php if($is_admin && $edit): ?>
    <div class="wf-sec">
      <div class="wf-sh"><div class="sico"><i class="bi bi-shield-check"></i></div><h6>Status Pengajuan (Admin)</h6></div>
      <div class="wf-body">
        <div class="adm-status">
          <h6><i class="bi bi-info-circle me-1"></i>Ubah status pengajuan warga ini</h6>
          <div class="frow">
            <div class="fg">
              <label>Status</label>
              <select name="status_pengajuan" class="fc">
                <?php
                $st_opts = ['menunggu'=>'⏳ Menunggu','diverifikasi'=>'🔵 Diverifikasi','disetujui'=>'✅ Disetujui','ditolak'=>'❌ Ditolak'];
                $st_val  = $item->status_pengajuan ?? 'menunggu';
                foreach($st_opts as $v=>$l):?>
                <option value="<?php echo $v;?>" <?php echo $st_val==$v?'selected':'';?>><?php echo $l;?></option>
                <?php endforeach;?>
              </select>
            </div>
            <div class="fg">
              <label>Catatan Verifikasi</label>
              <input type="text" name="catatan_verifikasi" class="fc" placeholder="Catatan untuk warga..."
                value="<?php echo htmlspecialchars($item->catatan_verifikasi??'');?>">
            </div>
          </div>
        </div>
      </div>
    </div>
    <?php endif;?>

    <!-- Action Bar -->
    <div class="wf-acts">
      <a href="<?php echo base_url('warga_kurang_mampu');?>" class="btn-bk"><i class="bi bi-arrow-left me-1"></i>Batal</a>
      <button type="submit" class="btn-sv"><i class="bi bi-<?php echo $edit?'check2':'plus-circle';?> me-1"></i><?php echo $edit?'Perbarui Data':'Ajukan';?></button>
    </div>

  </form>
</div>
</div><!-- /pg-wrapper -->

<script>
// ── Kondisi Rumah visual ──
var krCls = {baik:'sel-baik',sedang:'sel-sedang',buruk:'sel-buruk',sangat_buruk:'sel-sangat_buruk'};
function selectKondisi(val, cls) {
  Object.keys(krCls).forEach(function(k){
    var el = document.getElementById('kopt-'+k);
    if(el) el.className = 'kopt';
  });
  var sel = document.getElementById('kopt-'+val);
  if(sel) sel.className = 'kopt '+krCls[val];
}

// ── Foto preview ──
var newFiles = [];
document.getElementById('fotoInput').addEventListener('change', function(){
  Array.from(this.files).forEach(function(f){ addPreview(f); });
  updateFileInput();
});
// Drag & drop
var drop = document.getElementById('fotoDrop');
drop.addEventListener('dragover', function(e){ e.preventDefault(); this.classList.add('drag'); });
drop.addEventListener('dragleave', function(){ this.classList.remove('drag'); });
drop.addEventListener('drop', function(e){
  e.preventDefault(); this.classList.remove('drag');
  Array.from(e.dataTransfer.files).forEach(function(f){ addPreview(f); });
  updateFileInput();
});
function addPreview(file) {
  if(!file.type.match('image.*')) return;
  newFiles.push(file);
  var idx = newFiles.length-1;
  var reader = new FileReader();
  reader.onload = function(e){
    var grid = document.getElementById('previewGrid');
    var div = document.createElement('div');
    div.className = 'foto-item'; div.id='prev-'+idx;
    div.innerHTML = '<img src="'+e.target.result+'" alt="preview"><button type="button" class="foto-del" onclick="removePrev('+idx+')"><i class="bi bi-x"></i></button>';
    grid.appendChild(div);
  };
  reader.readAsDataURL(file);
}
function removePrev(idx) {
  newFiles[idx] = null;
  var el = document.getElementById('prev-'+idx);
  if(el) el.remove();
  updateFileInput();
}
function updateFileInput() {
  var dt = new DataTransfer();
  newFiles.forEach(function(f){ if(f) dt.items.add(f); });
  document.getElementById('fotoInput').files = dt.files;
}
function toggleFotoHapus(cb, idx) {
  var el = document.getElementById('foto-lama-'+idx);
  if(el) el.style.opacity = cb.checked ? '0.4' : '1';
}

// ── Warga Search (admin) ──
<?php if($is_admin):?>
var wsTimer;
document.getElementById('wargaSearch')?.addEventListener('input', function(){
  clearTimeout(wsTimer);
  var q = this.value.trim();
  if(q.length < 2){ document.getElementById('wargaRes').style.display='none'; return; }
  wsTimer = setTimeout(function(){
    fetch('<?php echo base_url("warga_kurang_mampu/cari_warga");?>?q='+encodeURIComponent(q))
      .then(r=>r.json()).then(function(data){
        var res = document.getElementById('wargaRes');
        if(!data.length){ res.style.display='none'; return; }
        res.innerHTML = data.map(function(w){
          return '<div class="ws-item" tabindex="0" onclick="pilihWarga('+w.id+',\''+w.nama_lengkap+'\',\''+w.nik+'\',\''+w.no_kk+'\')">'
            +'<div class="ws-nm">'+w.nama_lengkap+'</div>'
            +'<div class="ws-nik">NIK: '+w.nik+' | KK: '+(w.no_kk||'-')+'</div>'
            +'</div>';
        }).join('');
        res.style.display='block';
      });
  }, 280);
});
function pilihWarga(id,nama,nik,nokk){
  document.getElementById('wargaId').value = id;
  document.getElementById('wargaSearch').value = nama;
  document.getElementById('wargaRes').style.display='none';
  document.getElementById('wi-nama').textContent=nama;
  document.getElementById('wi-nik').textContent=nik;
  document.getElementById('wi-kk').textContent=nokk||'-';
  document.getElementById('wargaInfo').style.display='block';
}
document.addEventListener('click',function(e){
  if(!e.target.closest('.ws-wrap')) document.getElementById('wargaRes').style.display='none';
});
<?php endif;?>
</script>