<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<style>
:root{--t8:#0b5a52;--t7:#0b7a6e;--t6:#0d9488;--t5:#14b8a6;--t1:#ccfbf1;--t0:#f0fdfa;--r5:#ef4444;--r0:#fef2f2;--r1:#fee2e2;--g5:#10b981;--g0:#f0fdf4;--a5:#fffbeb;--a2:#d97706;--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);}
.ukf-wrap{max-width:760px;margin:0 auto;}
.ukf-hdr{display:flex;justify-content:space-between;align-items:flex-start;flex-wrap:wrap;gap:14px;margin-bottom:22px;}
.ukf-hdr-l h4{font-size:1.2rem;font-weight:800;color:var(--t8);margin:0 0 5px;display:flex;align-items:center;gap:11px;}
.ukf-hdr-l h4 .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;}
.ukf-bc{display:flex;align-items:center;gap:6px;font-size:0.77rem;color:var(--s4);padding-left:51px;}
.ukf-bc a{color:var(--t6);text-decoration:none;font-weight:600;}
.ukf-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);}
/* Info box */
.info-box{display:flex;gap:10px;background:var(--t0);border-left:4px solid var(--t5);border-radius:var(--rsm);padding:12px 16px;margin-bottom:18px;font-size:0.83rem;color:var(--t8);}
.info-box i{color:var(--t5);flex-shrink:0;margin-top:1px;}
/* Card */
.ukf-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;}
.ukf-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;}
.ukf-ch i{color:var(--t5);}
.ukf-cb{padding:24px;}
.val-err{background:var(--r0);border-left:4px solid var(--r5);border-radius:var(--rsm);padding:12px 16px;font-size:0.83rem;color:#7f1d1d;margin-bottom:18px;display:flex;gap:10px;align-items:flex-start;}
.val-err i{color:var(--r5);flex-shrink:0;}
.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;box-sizing:border-box;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;}
.fg2{display:grid;grid-template-columns:1fr 1fr;gap:14px;}
.fg3{display:grid;grid-template-columns:1fr 1fr 1fr;gap:14px;}
/* Input icon */
.fi-wrap{position:relative;}
.fi-wrap i{position:absolute;left:12px;top:50%;transform:translateY(-50%);color:var(--s4);pointer-events:none;}
.fi-wrap .fi{padding-left:34px;}
/* Kategori cards */
.kat-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;}
.kat-item{position:relative;border:2px solid var(--s2);border-radius:var(--rsm);padding:11px 12px 10px 38px;cursor:pointer;transition:all .18s;background:#fff;}
.kat-item input{position:absolute;left:12px;top:50%;transform:translateY(-50%);width:17px;height:17px;cursor:pointer;accent-color:var(--t6);}
.kat-item:hover{border-color:var(--t5);background:var(--t0);}
.kat-item:has(input:checked){border-color:var(--t6);background:var(--t0);}
.ki-lbl{font-size:0.82rem;font-weight:700;color:var(--s9);}
/* File upload */
.file-zone{border:2px dashed var(--s2);border-radius:var(--rsm);padding:24px;text-align:center;cursor:pointer;transition:all .2s;background:var(--s0);}
.file-zone:hover{border-color:var(--t5);background:var(--t0);}
.file-zone i{font-size:2rem;color:var(--s4);display:block;margin-bottom:8px;}
.file-zone.has-file{border-color:var(--t5);background:var(--t0);}
.file-zone.has-file i{color:var(--t5);}
.fz-txt{font-size:0.82rem;color:var(--s5);}
.fz-hint{font-size:0.73rem;color:var(--s4);margin-top:4px;}
/* Footer */
.ukf-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;}
.char-count{font-size:0.72rem;color:var(--s4);text-align:right;margin-top:4px;}
@media(max-width:600px){.ukf-cb{padding:16px;}.fg2,.fg3{grid-template-columns:1fr;}.kat-grid{grid-template-columns:repeat(2,1fr);}.ukf-ft{flex-direction:column-reverse;}.btn-sub,.btn-back{width:100%;justify-content:center;}}
</style>

<div class="ukf-wrap">
<div class="ukf-hdr">
  <div class="ukf-hdr-l">
    <h4>
      <span class="hi"><i class="bi bi-shop-window"></i></span>
      <?php
      if(isset($mode)){
        if($mode=='daftar') echo 'Daftarkan Usaha Saya';
        elseif($mode=='edit') echo 'Edit Data UMKM';
        else echo 'Tambah UMKM';
      }
      ?>
    </h4>
    <div class="ukf-bc">
      <a href="<?php echo base_url('dashboard');?>">Dashboard</a><span class="sep">/</span>
      <a href="<?php echo base_url('umkm');?>">Direktori UMKM</a><span class="sep">/</span>
      <span><?php echo isset($mode)?ucfirst($mode):'Form';?></span>
    </div>
  </div>
  <a href="<?php echo base_url('umkm');?>" class="btn-back"><i class="bi bi-arrow-left"></i> Kembali</a>
</div>

<!-- Info untuk warga yang daftar sendiri -->
<?php if(isset($mode)&&$mode=='daftar'):?>
<div class="info-box">
  <i class="bi bi-info-circle-fill"></i>
  <div>
    Usaha Anda akan <strong>ditinjau oleh admin RT</strong> sebelum ditampilkan di direktori.
    Data nama dan kontak Anda diambil otomatis dari profil warga yang sudah terdaftar.
    Proses verifikasi biasanya berlangsung 1–2 hari kerja.
  </div>
</div>
<?php endif;?>

<div class="ukf-card">
  <div class="ukf-ch"><i class="bi bi-building"></i>Form Data Usaha / UMKM</div>
  <div class="ukf-cb">

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

    <?php
    $mode_val = isset($mode)?$mode:'tambah';
    if($mode_val=='edit'&&isset($item)){
      $action = base_url('umkm/update/'.$item->id);
    } elseif($mode_val=='daftar'){
      $action = base_url('umkm/simpan_daftar');
    } else {
      $action = base_url('umkm/simpan');
    }
    echo form_open_multipart($action,['id'=>'formUmkm']);
    ?>

    <!-- Info pemilik (admin: pilih warga; warga: otomatis dari session) -->
    <?php if($is_admin&&$mode_val!='daftar'):?>
    <div class="fs">Pemilik Usaha</div>
    <div class="fg">
      <label class="fl">Nama Pemilik / Warga <span class="req">*</span> <span class="hint">— ketik nama atau NIK</span></label>
      <div class="warga-wrap" style="position:relative;">
        <input type="text" id="wargaSearch" class="fi" autocomplete="off"
               placeholder="Ketik nama atau NIK warga..."
               value="<?php echo isset($item)?htmlspecialchars($item->nama_pemilik??''):set_value('nama_cari');?>">
        <div id="wargaSug" style="position:absolute;top:100%;left:0;right:0;z-index:99;background:#fff;border:1.5px solid var(--s2);border-top:none;border-radius:0 0 var(--rsm) var(--rsm);box-shadow:0 8px 24px rgba(0,0,0,0.10);max-height:210px;overflow-y:auto;display:none;"></div>
      </div>
      <input type="hidden" name="warga_id" id="wargaId" value="<?php echo isset($item)?$item->warga_id:set_value('warga_id');?>">
      <input type="hidden" name="user_id_owner" id="userIdOwner" value="<?php echo isset($item)?$item->user_id_owner:set_value('user_id_owner');?>">
    </div>
    <?php else:?>
    <!-- Warga daftar sendiri → ambil dari session -->
    <input type="hidden" name="warga_id" value="<?php echo $this->session->userdata('warga_id')??'';?>">
    <input type="hidden" name="user_id_owner" value="<?php echo $this->session->userdata('user_id');?>">
    <?php endif;?>

    <div class="fs">Informasi Usaha</div>

    <div class="fg">
      <label class="fl">Nama Usaha <span class="req">*</span></label>
      <input type="text" name="nama_usaha" class="fi" required maxlength="150"
             placeholder="Contoh: Warung Makan Bu Sari, Jasa Service AC Pak Budi"
             value="<?php echo set_value('nama_usaha',isset($item)?$item->nama_usaha:'');?>">
    </div>

    <div class="fs">Kategori <span style="color:var(--r5);">*</span></div>
    <?php
    $kats=[
      'kuliner'    =>['ico'=>'bi-egg-fried',      'col'=>'#ef4444'],
      'fashion'    =>['ico'=>'bi-bag-fill',        'col'=>'#8b5cf6'],
      'jasa'       =>['ico'=>'bi-tools',           'col'=>'#3b82f6'],
      'pertanian'  =>['ico'=>'bi-tree-fill',       'col'=>'#10b981'],
      'kerajinan'  =>['ico'=>'bi-scissors',        'col'=>'#d97706'],
      'teknologi'  =>['ico'=>'bi-cpu-fill',        'col'=>'#0d9488'],
      'kesehatan'  =>['ico'=>'bi-heart-pulse-fill','col'=>'#a21caf'],
      'pendidikan' =>['ico'=>'bi-book-fill',       'col'=>'#15803d'],
      'lainnya'    =>['ico'=>'bi-three-dots',      'col'=>'#64748b'],
    ];
    $cur_kat=set_value('kategori',isset($item)?$item->kategori:'');
    ?>
    <div class="kat-grid">
      <?php foreach($kats as $k=>$kv):?>
      <label class="kat-item">
        <input type="radio" name="kategori" value="<?php echo $k;?>" <?php echo $cur_kat==$k?'checked':'';?> required>
        <div class="ki-lbl"><i class="bi <?php echo $kv['ico'];?>" style="color:<?php echo $kv['col'];?>;margin-right:4px;"></i><?php echo ucfirst($k);?></div>
      </label>
      <?php endforeach;?>
    </div>

    <div class="fs" style="margin-top:22px;">Deskripsi & Layanan</div>

    <div class="fg">
      <label class="fl">Deskripsi Usaha <span class="req">*</span> <span class="hint">— ceritakan usaha Anda</span></label>
      <textarea name="deskripsi" class="fta" required maxlength="500" id="deskArea"
                placeholder="Contoh: Warung makan yang menyajikan masakan rumahan khas Jawa..."><?php echo set_value('deskripsi',isset($item)?$item->deskripsi:'');?></textarea>
      <div class="char-count"><span id="deskCount">0</span>/500 karakter</div>
    </div>

    <div class="fg">
      <label class="fl">Produk / Layanan <span class="hint">— opsional, pisah dengan koma</span></label>
      <textarea name="produk_layanan" class="fta" style="min-height:70px;"
                placeholder="Contoh: Nasi goreng, Mie ayam, Catering, Delivery order..."><?php echo set_value('produk_layanan',isset($item)?$item->produk_layanan:'');?></textarea>
    </div>

    <div class="fs">Lokasi & Jam Operasional</div>

    <div class="fg">
      <label class="fl">Alamat / Lokasi <span class="hint">— opsional</span></label>
      <div class="fi-wrap"><i class="bi bi-geo-alt-fill"></i>
        <input type="text" name="alamat" class="fi" maxlength="255"
               placeholder="Contoh: Jl. Melati No. 12, RT 03 / RW 05"
               value="<?php echo set_value('alamat',isset($item)?$item->alamat:'');?>">
      </div>
    </div>

    <div class="fg">
      <label class="fl">Jam Operasional <span class="hint">— opsional</span></label>
      <div class="fi-wrap"><i class="bi bi-clock-fill"></i>
        <input type="text" name="jam_operasional" class="fi" maxlength="100"
               placeholder="Contoh: Senin–Sabtu 08.00–17.00, Setiap hari kecuali Jumat"
               value="<?php echo set_value('jam_operasional',isset($item)?$item->jam_operasional:'');?>">
      </div>
    </div>

    <div class="fs">Kontak</div>

    <div class="fg3">
      <div class="fg" style="margin-bottom:0;">
        <label class="fl">No. Telepon</label>
        <div class="fi-wrap"><i class="bi bi-telephone-fill"></i>
          <input type="text" name="no_telp" class="fi" maxlength="20"
                 placeholder="08xxxxxxxxxx"
                 value="<?php echo set_value('no_telp',isset($item)?$item->no_telp:'');?>">
        </div>
      </div>
      <div class="fg" style="margin-bottom:0;">
        <label class="fl">WhatsApp</label>
        <div class="fi-wrap"><i class="bi bi-whatsapp"></i>
          <input type="text" name="whatsapp" class="fi" maxlength="20"
                 placeholder="08xxxxxxxxxx"
                 value="<?php echo set_value('whatsapp',isset($item)?$item->whatsapp:'');?>">
        </div>
      </div>
      <div class="fg" style="margin-bottom:0;">
        <label class="fl">Instagram</label>
        <div class="fi-wrap"><i class="bi bi-instagram"></i>
          <input type="text" name="instagram" class="fi" maxlength="80"
                 placeholder="username (tanpa @)"
                 value="<?php echo set_value('instagram',isset($item)?$item->instagram:'');?>">
        </div>
      </div>
    </div>

    <div class="fs" style="margin-top:20px;">Foto Usaha <span class="hint"> — opsional, max 2MB</span></div>

    <div class="fg">
      <div class="file-zone" id="fileZone" onclick="document.getElementById('fotoInput').click()">
        <i class="bi bi-image" id="fileIcon"></i>
        <div class="fz-txt" id="fileTxt">Klik untuk upload foto usaha</div>
        <div class="fz-hint">JPG, PNG, WebP · Maksimal 2MB</div>
      </div>
      <input type="file" name="foto" id="fotoInput" accept="image/*" style="display:none;">
      <?php if(isset($item)&&!empty($item->foto)):?>
      <div style="margin-top:8px;font-size:0.78rem;color:var(--s5);">
        <i class="bi bi-image me-1" style="color:var(--t5);"></i>Foto saat ini: <strong><?php echo htmlspecialchars($item->foto);?></strong>
        <span style="font-size:0.72rem;color:var(--s4);"> — upload baru untuk mengganti</span>
      </div>
      <?php endif;?>
    </div>

    <?php if($is_admin):?>
    <div class="fg">
      <label class="fl">Status</label>
      <select name="status" class="fsel">
        <?php $cs=set_value('status',isset($item)?$item->status:'aktif');?>
        <option value="aktif"    <?php echo $cs=='aktif'   ?'selected':'';?>>Aktif</option>
        <option value="pending"  <?php echo $cs=='pending' ?'selected':'';?>>Pending</option>
        <option value="nonaktif" <?php echo $cs=='nonaktif'?'selected':'';?>>Nonaktif</option>
      </select>
    </div>
    <?php endif;?>

    <div class="ukf-ft">
      <a href="<?php echo base_url('umkm');?>" 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
        if(isset($mode)){
          if($mode=='daftar') echo 'Daftarkan Usaha';
          elseif($mode=='edit') echo 'Simpan Perubahan';
          else echo 'Simpan';
        }
        ?>
      </button>
    </div>

    <?php echo form_close();?>
  </div>
</div>
</div><!-- /ukf-wrap -->

<script>
$(document).ready(function(){
  // Char counter deskripsi
  var $da=$('#deskArea'),$dc=$('#deskCount');
  function updateCount(){ $dc.text($da.val().length); }
  $da.on('input',updateCount); updateCount();

  // File upload preview
  $('#fotoInput').on('change',function(){
    var file=this.files[0];
    if(file){
      var zone=$('#fileZone');
      zone.addClass('has-file');
      $('#fileIcon').removeClass().addClass('bi bi-check-circle-fill');
      $('#fileTxt').text(file.name+' ('+Math.round(file.size/1024)+' KB)');
    }
  });

  // Warga autocomplete (admin only)
  <?php if($is_admin&&isset($mode)&&$mode!='daftar'):?>
  var timer;
  $('#wargaSearch').on('input',function(){
    clearTimeout(timer);
    var q=$(this).val().trim();
    if(q.length<2){$('#wargaSug').hide();return;}
    timer=setTimeout(function(){
      $.getJSON('<?php echo base_url('umkm/cari_warga');?>',{q:q},function(data){
        var html='';
        if(data.length){
          $.each(data,function(i,d){
            html+='<div class="ws-item" style="padding:10px 14px;cursor:pointer;font-size:0.84rem;border-bottom:1px solid #f1f5f9;transition:background .12s;" '
                 +'data-id="'+d.id+'" data-uid="'+d.user_id+'" data-nama="'+d.nama_lengkap+'">'
                 +'<div style="font-weight:700;color:#0f172a;">'+d.nama_lengkap+'</div>'
                 +'<div style="font-size:0.72rem;color:#94a3b8;font-family:monospace;">NIK: '+d.nik+'</div>'
                 +'</div>';
          });
        } else {
          html='<div style="padding:10px 14px;font-size:0.82rem;color:#9ca3af;cursor:default;"><i class="bi bi-search me-2"></i>Warga tidak ditemukan</div>';
        }
        $('#wargaSug').html(html).show();
      });
    },320);
  });
  $(document).on('click','.ws-item',function(){
    var $t=$(this);
    if(!$t.data('id')) return;
    $('#wargaSearch').val($t.data('nama'));
    $('#wargaId').val($t.data('id'));
    $('#userIdOwner').val($t.data('uid'));
    $('#wargaSug').hide();
  });
  $(document).on('mouseover','.ws-item',function(){$(this).css('background','#f0fdfa');});
  $(document).on('mouseout','.ws-item',function(){$(this).css('background','');});
  $(document).on('click',function(e){if(!$(e.target).closest('.warga-wrap').length)$('#wargaSug').hide();});
  <?php endif;?>

  // Submit
  $('#formUmkm').on('submit',function(){
    <?php if($is_admin&&isset($mode)&&$mode!='daftar'):?>
    if(!$('#wargaId').val()){
      alert('Pilih pemilik usaha terlebih dahulu.');
      return false;
    }
    <?php endif;?>
    if(!$('input[name="kategori"]:checked').length){
      alert('Pilih kategori usaha terlebih dahulu.');
      return false;
    }
    $('#btnSub').prop('disabled',true).html('<i class="bi bi-hourglass-split"></i> Menyimpan...');
  });
});
</script>