<?php /* views/tamu/registrasi.php — versi multi-foto */ ?>
<style>
@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&display=swap');

:root {
  --teal-900:#0d3d38;--teal-800:#0b5a52;--teal-700:#0b7a6e;
  --teal-600:#0d9488;--teal-500:#14b8a6;--teal-400:#2dd4bf;
  --teal-100:#ccfbf1;--teal-50:#f0fdfa;
  --slate-50:#f8fafc;--slate-100:#f1f5f9;--slate-200:#e2e8f0;
  --slate-400:#94a3b8;--slate-500:#64748b;--slate-700:#334155;--slate-900:#0f172a;
}

.rg-wrap{font-family:'DM Sans',system-ui,sans-serif;color:var(--slate-900);}
.rg-wrap input:focus,.rg-wrap select:focus,.rg-wrap textarea:focus{
  border-color:var(--teal-500)!important;box-shadow:0 0 0 3px rgba(13,148,136,.12)!important;outline:none;
}
.rg-wrap input,.rg-wrap select,.rg-wrap textarea{
  border-radius:9px;border:1.5px solid #e5e7eb;font-size:.86rem;padding:9px 13px;
  font-family:'DM Sans',sans-serif;width:100%;display:block;background:#fff;color:var(--slate-900);transition:border-color .15s;
}
.rg-wrap textarea{resize:vertical;min-height:80px;}

/* Header */
.rg-header{display:flex;justify-content:space-between;align-items:flex-start;flex-wrap:wrap;gap:14px;margin-bottom:22px;}
.rg-header h4{font-size:1.2rem;font-weight:700;color:var(--teal-800);margin:0 0 4px;display:flex;align-items:center;gap:10px;}
.rg-header .hi{width:38px;height:38px;border-radius:10px;background:linear-gradient(135deg,var(--teal-600),var(--teal-500));display:flex;align-items:center;justify-content:center;color:#fff;font-size:1rem;box-shadow:0 4px 12px rgba(13,148,136,.32);flex-shrink:0;}
.rg-breadcrumb{font-size:.74rem;color:#94a3b8;padding-left:48px;}
.rg-breadcrumb a{color:var(--teal-600);text-decoration:none;font-weight:600;}

/* Card */
.rg-card{background:#fff;border-radius:16px;border:1px solid var(--slate-200);box-shadow:0 1px 3px rgba(0,0,0,.06),0 4px 20px rgba(0,0,0,.06);overflow:hidden;margin-bottom:16px;}
.rg-card-header{padding:14px 20px;background:linear-gradient(90deg,var(--teal-50),#fff);border-bottom:1px solid rgba(13,148,136,.1);display:flex;align-items:center;gap:8px;}
.rg-card-header .ch-icon{width:32px;height:32px;border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:.95rem;flex-shrink:0;}
.rg-card-header .ch-title{font-size:.9rem;font-weight:700;color:var(--slate-900);}
.rg-card-header .ch-sub{font-size:.74rem;color:var(--slate-400);}
.rg-card-body{padding:18px 20px;}

/* Labels */
.rg-label{font-size:.78rem;font-weight:700;color:var(--slate-700);margin-bottom:5px;display:block;}
.rg-hint{font-size:.72rem;color:var(--slate-400);margin-top:3px;}
.optional-badge{font-size:.64rem;font-weight:600;background:var(--slate-100);color:var(--slate-400);padding:1px 6px;border-radius:4px;margin-left:5px;vertical-align:middle;}

/* Type selector */
.type-select{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:4px;}
.type-card{border:2px solid #e5e7eb;border-radius:11px;padding:14px 12px;cursor:pointer;transition:all .15s;display:flex;align-items:center;gap:10px;}
.type-card.selected{border-color:var(--teal-500);background:var(--teal-50);}
.type-card:hover{border-color:var(--teal-400);background:#f0fdf9;}
.type-card .tc-icon{width:38px;height:38px;border-radius:9px;display:flex;align-items:center;justify-content:center;font-size:1.1rem;flex-shrink:0;}
.type-card .tc-title{font-size:.85rem;font-weight:700;}
.type-card .tc-desc{font-size:.72rem;color:var(--slate-400);margin-top:2px;}
.type-card input[type=radio]{display:none;}

/* Keperluan pills */
.kp-select{display:flex;flex-wrap:wrap;gap:7px;}
.kp-pill{border:1.5px solid #e5e7eb;border-radius:8px;padding:6px 12px;cursor:pointer;transition:all .15s;font-size:.79rem;font-weight:600;display:flex;align-items:center;gap:5px;}
.kp-pill:hover{border-color:var(--teal-400);color:var(--teal-700);}
.kp-pill.selected{border-color:var(--teal-500);background:var(--teal-50);color:var(--teal-700);}
.kp-pill input[type=radio]{display:none;}

/* ═══════════════════════════════════════════════
   MULTI FOTO UPLOAD AREA
═══════════════════════════════════════════════ */
.foto-drop-area {
  border: 2px dashed #d1d5db;
  border-radius: 12px;
  padding: 28px 20px;
  text-align: center;
  cursor: pointer;
  transition: all .2s;
  background: #fafafa;
  position: relative;
}
.foto-drop-area.drag-over {
  border-color: var(--teal-500);
  background: var(--teal-50);
}
.foto-drop-area:hover {
  border-color: var(--teal-400);
  background: #f7fffe;
}
.foto-drop-area .drop-icon {
  width: 52px; height: 52px;
  border-radius: 13px;
  background: var(--teal-50);
  color: var(--teal-500);
  display: flex; align-items: center; justify-content: center;
  font-size: 1.5rem;
  margin: 0 auto 12px;
}
.foto-drop-area .drop-title {
  font-size: .88rem; font-weight: 700; color: var(--slate-700); margin-bottom: 4px;
}
.foto-drop-area .drop-sub {
  font-size: .76rem; color: var(--slate-400);
}
.foto-drop-area .drop-btn {
  display: inline-flex; align-items: center; gap: 6px;
  margin-top: 12px; padding: 7px 16px;
  border: 1.5px solid var(--teal-300, #5eead4); border-radius: 8px;
  background: #fff; font-size: .8rem; font-weight: 700;
  color: var(--teal-700); cursor: pointer; transition: all .15s;
}
.foto-drop-area .drop-btn:hover { background: var(--teal-50); }
#fotoInput { display: none; }

/* Preview grid */
.foto-preview-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(110px, 1fr));
  gap: 10px;
  margin-top: 14px;
}
.foto-thumb {
  position: relative;
  border-radius: 10px;
  overflow: hidden;
  aspect-ratio: 1;
  background: var(--slate-100);
  border: 1.5px solid var(--slate-200);
  transition: transform .15s;
}
.foto-thumb:hover { transform: scale(1.02); }
.foto-thumb img {
  width: 100%; height: 100%; object-fit: cover; display: block;
}
.foto-thumb .ft-overlay {
  position: absolute; inset: 0;
  background: rgba(0,0,0,.5);
  opacity: 0; transition: opacity .15s;
  display: flex; flex-direction: column;
  align-items: center; justify-content: center; gap: 5px;
}
.foto-thumb:hover .ft-overlay { opacity: 1; }
.ft-remove {
  width: 28px; height: 28px; border-radius: 50%;
  background: #ef4444; color: #fff; border: none;
  display: flex; align-items: center; justify-content: center;
  cursor: pointer; font-size: .8rem; transition: background .15s;
}
.ft-remove:hover { background: #dc2626; }
.ft-label-badge {
  font-size: .62rem; color: #fff; font-weight: 600;
  background: rgba(0,0,0,.5); padding: 2px 6px; border-radius: 4px;
  max-width: 90%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
.foto-thumb .ft-num {
  position: absolute; top: 5px; left: 5px;
  width: 20px; height: 20px; border-radius: 50%;
  background: rgba(0,0,0,.55); color: #fff;
  font-size: .65rem; font-weight: 700;
  display: flex; align-items: center; justify-content: center;
}
.foto-count-badge {
  display: inline-flex; align-items: center; gap: 5px;
  background: var(--teal-50); color: var(--teal-700);
  border: 1px solid var(--teal-100);
  padding: 3px 10px; border-radius: 20px;
  font-size: .75rem; font-weight: 700;
  margin-top: 10px;
}
.foto-count-badge i { font-size: .8rem; }

/* Label modal (inline, bukan popup) */
.label-input-row {
  display: flex; gap: 8px; margin-top: 10px;
  align-items: center; flex-wrap: wrap;
}
.label-input-row label {
  font-size: .76rem; font-weight: 700; color: var(--slate-600); white-space: nowrap;
}
.label-input-row input {
  flex: 1; min-width: 140px; padding: 6px 10px !important; font-size: .8rem !important;
}
.label-suggestions {
  display: flex; flex-wrap: wrap; gap: 5px; margin-top: 7px;
}
.label-chip {
  padding: 3px 10px; border-radius: 20px; font-size: .73rem; font-weight: 600;
  background: var(--slate-100); color: var(--slate-600); border: 1px solid var(--slate-200);
  cursor: pointer; transition: all .12s;
}
.label-chip:hover { background: var(--teal-50); color: var(--teal-700); border-color: var(--teal-200, #99f6e4); }

/* Buttons */
.btn-submit{width:100%;padding:12px;border:none;border-radius:10px;background:linear-gradient(135deg,var(--teal-700),var(--teal-500));color:#fff;font-family:'DM Sans',sans-serif;font-size:.95rem;font-weight:700;cursor:pointer;transition:all .2s;display:flex;align-items:center;justify-content:center;gap:8px;}
.btn-submit:hover{background:linear-gradient(135deg,var(--teal-800),var(--teal-600));transform:translateY(-1px);}
.btn-back{display:inline-flex;align-items:center;gap:6px;padding:9px 16px;border-radius:9px;border:1.5px solid #e5e7eb;background:#fff;font-size:.82rem;font-weight:600;color:var(--slate-600);cursor:pointer;text-decoration:none;transition:all .15s;}
.btn-back:hover{border-color:var(--slate-400);color:var(--slate-900);}

@keyframes fadeUp{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:none}}
.rg-header{animation:fadeUp .3s ease both;}
.rg-card{animation:fadeUp .35s .05s ease both;}

@media(max-width:767px){
  .rg-header{flex-direction:column;}
  .type-select{grid-template-columns:1fr;}
  .foto-preview-grid{grid-template-columns:repeat(auto-fill,minmax(85px,1fr));}
}
</style>

<div class="rg-wrap">
<div class="container-fluid px-2 px-md-3 py-3">

<?php if($this->session->flashdata('warning')): ?>
<div class="alert alert-warning alert-dismissible fade show" style="border-radius:10px;font-size:.83rem;border:1.5px solid #fcd34d;font-family:'DM Sans',sans-serif;">
  <i class="bi bi-exclamation-triangle-fill me-2"></i><?php echo $this->session->flashdata('warning'); ?>
  <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<div class="rg-header">
  <div>
    <h4>
      <span class="hi"><i class="bi bi-person-plus-fill"></i></span>
      Registrasi Tamu
    </h4>
    <div class="rg-breadcrumb">
      <a href="<?php echo base_url('dashboard'); ?>">Dashboard</a> /
      <a href="<?php echo base_url('tamu'); ?>">E-Visitor</a> /
      <span>Registrasi</span>
    </div>
  </div>
  <a href="<?php echo base_url('tamu'); ?>" class="btn-back"><i class="bi bi-arrow-left"></i> Kembali</a>
</div>

<div class="row justify-content-center">
<div class="col-lg-8 col-xl-7">

<form action="<?php echo base_url('tamu/simpan'); ?>" method="post" enctype="multipart/form-data" id="rgForm">
<?php /* Inject CSRF token agar fetch() tidak ditolak CodeIgniter */ ?>
<?php if(function_exists('get_instance') && get_instance()->config->item('csrf_protection')): ?>
<input type="hidden" name="<?php echo get_instance()->security->get_csrf_token_name(); ?>"
       value="<?php echo get_instance()->security->get_csrf_hash(); ?>">
<?php endif; ?>

  <!-- TIPE KUNJUNGAN -->
  <div class="rg-card">
    <div class="rg-card-header">
      <div class="ch-icon" style="background:#f0fdf4;color:#059669;"><i class="bi bi-signpost-2-fill"></i></div>
      <div><div class="ch-title">Tipe Kunjungan</div><div class="ch-sub">Pilih sesuai kebutuhan tamu</div></div>
    </div>
    <div class="rg-card-body">
      <div class="type-select">
        <label class="type-card selected" id="tc-singkat">
          <input type="radio" name="tipe_kunjungan" value="singkat" checked>
          <div class="tc-icon" style="background:var(--teal-50);color:var(--teal-600);"><i class="bi bi-person-walking"></i></div>
          <div><div class="tc-title">Kunjungan Singkat</div><div class="tc-desc">Datang & pergi hari ini</div></div>
        </label>
        <label class="type-card" id="tc-menginap">
          <input type="radio" name="tipe_kunjungan" value="menginap">
          <div class="tc-icon" style="background:#dbeafe;color:#1d4ed8;"><i class="bi bi-moon-stars-fill"></i></div>
          <div><div class="tc-title">Tamu Menginap</div><div class="tc-desc">Tinggal lebih dari 1 hari</div></div>
        </label>
      </div>
    </div>
  </div>

  <!-- IDENTITAS -->
  <div class="rg-card">
    <div class="rg-card-header">
      <div class="ch-icon" style="background:var(--teal-50);color:var(--teal-600);"><i class="bi bi-person-vcard-fill"></i></div>
      <div><div class="ch-title">Identitas Tamu</div><div class="ch-sub">Nama wajib, sisanya opsional</div></div>
    </div>
    <div class="rg-card-body">
      <div class="row g-3">
        <div class="col-md-8">
          <label class="rg-label">Nama Lengkap Tamu <span style="color:#ef4444;">*</span></label>
          <input type="text" name="nama_tamu" placeholder="Masukkan nama lengkap tamu" required autofocus>
        </div>
        <div class="col-md-4">
          <label class="rg-label">NIK <span class="optional-badge">Opsional</span></label>
          <input type="text" name="nik_tamu" placeholder="16 digit NIK" maxlength="16">
        </div>
        <div class="col-md-6">
          <label class="rg-label">No. HP / WhatsApp <span class="optional-badge">Opsional</span></label>
          <input type="text" name="no_hp" placeholder="cth. 08123456789">
        </div>
        <div class="col-md-6">
          <label class="rg-label">Waktu Check-in</label>
          <div style="position:relative;">
            <input type="datetime-local" name="checkin_at" id="checkinAt"
                   style="padding-right:80px!important;">
            <button type="button" id="btnNow"
              style="position:absolute;right:6px;top:50%;transform:translateY(-50%);
                     padding:3px 9px;border:1.5px solid var(--teal-200,#99f6e4);
                     border-radius:6px;background:var(--teal-50);color:var(--teal-700);
                     font-size:.7rem;font-weight:700;cursor:pointer;white-space:nowrap;
                     font-family:'DM Sans',sans-serif;line-height:1.4;transition:all .15s;">
              ⟳ Sekarang
            </button>
          </div>
          <div style="display:flex;align-items:center;gap:6px;margin-top:5px;">
            <span id="clockDisplay"
              style="font-size:.75rem;color:var(--teal-600);font-weight:700;
                     background:var(--teal-50);border:1px solid var(--teal-100);
                     padding:2px 8px;border-radius:5px;font-family:monospace;letter-spacing:.04em;">
            </span>
            <span style="font-size:.7rem;color:var(--slate-400);">— waktu sekarang (live)</span>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- KENDARAAN -->
  <div class="rg-card">
    <div class="rg-card-header">
      <div class="ch-icon" style="background:#fef3c7;color:#d97706;"><i class="bi bi-car-front-fill"></i></div>
      <div><div class="ch-title">Kendaraan <span class="optional-badge" style="font-size:.72rem;">Semua Opsional</span></div><div class="ch-sub">Isi jika tamu membawa kendaraan</div></div>
    </div>
    <div class="rg-card-body">
      <div class="row g-3">
        <div class="col-md-6">
          <label class="rg-label">No. Plat Kendaraan</label>
          <input type="text" name="no_kendaraan" placeholder="cth. B 1234 XYZ"
                 oninput="this.value=this.value.toUpperCase()">
        </div>
        <div class="col-md-6">
          <label class="rg-label">Jenis Kendaraan</label>
          <select name="jenis_kendaraan">
            <option value="">— Pilih (opsional) —</option>
            <option>Motor</option><option>Mobil</option><option>Sepeda</option>
            <option>Truk</option><option>Lainnya</option>
          </select>
        </div>
      </div>
    </div>
  </div>

  <!-- TUJUAN & KEPERLUAN -->
  <div class="rg-card">
    <div class="rg-card-header">
      <div class="ch-icon" style="background:#ede9fe;color:#7c3aed;"><i class="bi bi-house-door-fill"></i></div>
      <div><div class="ch-title">Tujuan & Keperluan</div><div class="ch-sub">Informasi kunjungan</div></div>
    </div>
    <div class="rg-card-body">
      <div class="row g-3">
        <div class="col-md-6">
          <label class="rg-label">Tujuan / Blok Rumah <span class="optional-badge">Opsional</span></label>
          <input type="text" name="tujuan_blok" placeholder="cth. Blok A1-05, No. 12">
        </div>
        <div class="col-md-6">
          <label class="rg-label">Nama Tuan Rumah <span class="optional-badge">Opsional</span></label>
          <input type="text" name="nama_tuan_rumah" placeholder="Nama warga yang dikunjungi">
        </div>
        <div class="col-12">
          <label class="rg-label">Keperluan</label>
          <div class="kp-select">
            <label class="kp-pill selected" data-val="kunjungan">
              <input type="radio" name="keperluan" value="kunjungan" checked>
              <i class="bi bi-house-door"></i> Kunjungan Biasa
            </label>
            <label class="kp-pill" data-val="antar_paket">
              <input type="radio" name="keperluan" value="antar_paket">
              <i class="bi bi-box-seam"></i> Antar Paket
            </label>
            <label class="kp-pill" data-val="tamu_menginap">
              <input type="radio" name="keperluan" value="tamu_menginap">
              <i class="bi bi-moon-stars"></i> Menginap
            </label>
            <label class="kp-pill" data-val="kerja">
              <input type="radio" name="keperluan" value="kerja">
              <i class="bi bi-tools"></i> Kerja / Teknisi
            </label>
            <label class="kp-pill" data-val="lainnya">
              <input type="radio" name="keperluan" value="lainnya">
              <i class="bi bi-three-dots"></i> Lainnya
            </label>
          </div>
        </div>
        <div class="col-12">
          <label class="rg-label">Detail Keperluan <span class="optional-badge">Opsional</span></label>
          <input type="text" name="keperluan_detail" placeholder="cth. Service AC, titip paket, dll.">
        </div>
        <div class="col-md-6" id="menginapBox" style="display:none;">
          <label class="rg-label">Rencana Checkout / Selesai Menginap</label>
          <input type="date" name="rencana_checkout" min="<?php echo date('Y-m-d'); ?>">
          <div class="rg-hint">Estimasi tanggal selesai menginap</div>
        </div>
        <div class="col-12">
          <label class="rg-label">Catatan Tambahan <span class="optional-badge">Opsional</span></label>
          <textarea name="catatan" placeholder="Catatan atau informasi lain..."></textarea>
        </div>
      </div>
    </div>
  </div>

  <!-- ═══ MULTI FOTO ═══ -->
  <div class="rg-card">
    <div class="rg-card-header">
      <div class="ch-icon" style="background:#fdf4ff;color:#9333ea;"><i class="bi bi-images"></i></div>
      <div>
        <div class="ch-title">Foto Dokumentasi <span class="optional-badge" style="font-size:.72rem;">Semua Opsional</span></div>
        <div class="ch-sub">Upload sebanyak apapun — wajah, KTP, kendaraan, dll.</div>
      </div>
    </div>
    <div class="rg-card-body">

      <!-- Label opsional untuk batch ini -->
      <div class="label-input-row mb-3">
        <label>Label foto:</label>
        <input type="text" id="globalLabel" name="foto_label" placeholder="cth. Foto Wajah (opsional)" style="max-width:240px;">
      </div>
      <div class="label-suggestions">
        <span class="label-chip" onclick="setLabel('Foto Wajah')"><i class="bi bi-person-fill me-1"></i>Foto Wajah</span>
        <span class="label-chip" onclick="setLabel('Foto KTP')"><i class="bi bi-card-text me-1"></i>Foto KTP</span>
        <span class="label-chip" onclick="setLabel('Foto Kendaraan')"><i class="bi bi-car-front me-1"></i>Foto Kendaraan</span>
        <span class="label-chip" onclick="setLabel('Foto Barang')"><i class="bi bi-box-seam me-1"></i>Foto Barang</span>
        <span class="label-chip" onclick="setLabel('Lainnya')">Lainnya</span>
      </div>

      <!-- Drop area -->
      <div class="foto-drop-area mt-3" id="dropArea">
        <input type="file" name="foto_tamu[]" id="fotoInput" accept="image/*" multiple>
        <div class="drop-icon"><i class="bi bi-cloud-arrow-up-fill"></i></div>
        <div class="drop-title">Drag & drop foto ke sini</div>
        <div class="drop-sub">JPG, PNG, WEBP — maks 5MB per foto, bebas jumlah</div>
        <button type="button" class="drop-btn" onclick="document.getElementById('fotoInput').click()">
          <i class="bi bi-folder2-open"></i> Pilih dari Galeri
        </button>
      </div>

      <!-- Preview grid -->
      <div class="foto-preview-grid" id="previewGrid"></div>
      <div id="fotoCountWrap" style="display:none;">
        <span class="foto-count-badge" id="fotoCount"><i class="bi bi-images"></i> <span id="fotoCountNum">0</span> foto dipilih</span>
      </div>

    </div>
  </div>

  <!-- SUBMIT -->
  <div class="d-flex gap-2 mb-4">
    <a href="<?php echo base_url('tamu'); ?>" class="btn-back"><i class="bi bi-x-circle"></i> Batal</a>
    <button type="submit" class="btn-submit">
      <i class="bi bi-person-check-fill"></i> Simpan & Check-in
    </button>
  </div>

</form>
</div>
</div>
</div>
</div>

<script>
(function(){
  // ─ Live clock & checkin time ─
  var checkinInput = document.getElementById('checkinAt');
  var clockDisplay = document.getElementById('clockDisplay');
  var btnNow       = document.getElementById('btnNow');

  function toLocalISO(d) {
    // Format: YYYY-MM-DDTHH:mm  (local time, no timezone shift)
    var pad = function(n){ return String(n).padStart(2,'0'); };
    return d.getFullYear()+'-'+pad(d.getMonth()+1)+'-'+pad(d.getDate())
           +'T'+pad(d.getHours())+':'+pad(d.getMinutes());
  }

  function setNow() {
    var now = new Date();
    checkinInput.value = toLocalISO(now);
  }

  // Set on load
  setNow();

  // Live clock display (updates every second, does NOT override the input after user edits)
  setInterval(function(){
    var now = new Date();
    var pad = function(n){ return String(n).padStart(2,'0'); };
    clockDisplay.textContent =
      pad(now.getHours())+':'+pad(now.getMinutes())+':'+pad(now.getSeconds());
  }, 1000);

  // Button: reset to current time
  btnNow.addEventListener('click', function(){
    setNow();
    // Brief visual feedback
    btnNow.style.background = 'var(--teal-500)';
    btnNow.style.color = '#fff';
    btnNow.style.borderColor = 'var(--teal-500)';
    setTimeout(function(){
      btnNow.style.background = 'var(--teal-50)';
      btnNow.style.color = 'var(--teal-700)';
      btnNow.style.borderColor = 'var(--teal-200,#99f6e4)';
    }, 600);
  });

  // ─ Tipe toggle ─
  var tcSingkat  = document.getElementById('tc-singkat');
  var tcMenginap = document.getElementById('tc-menginap');
  var menginapBox= document.getElementById('menginapBox');
  function updateTipe(val){
    tcSingkat.classList.toggle('selected',  val==='singkat');
    tcMenginap.classList.toggle('selected', val==='menginap');
    menginapBox.style.display = val==='menginap' ? '' : 'none';
  }
  tcSingkat.addEventListener('click',  function(){ updateTipe('singkat'); });
  tcMenginap.addEventListener('click', function(){ updateTipe('menginap'); });

  // ─ Keperluan pills ─
  document.querySelectorAll('.kp-pill').forEach(function(p){
    p.addEventListener('click', function(){
      document.querySelectorAll('.kp-pill').forEach(function(x){ x.classList.remove('selected'); });
      this.classList.add('selected');
      if(this.dataset.val === 'tamu_menginap') updateTipe('menginap');
    });
  });

  // ─ Multi Foto Logic (FIXED: tanpa DataTransfer assignment) ─
  var dropArea    = document.getElementById('dropArea');
  var fotoInput   = document.getElementById('fotoInput');
  var previewGrid = document.getElementById('previewGrid');
  var countWrap   = document.getElementById('fotoCountWrap');
  var countNum    = document.getElementById('fotoCountNum');
  var rgForm      = document.getElementById('rgForm');

  // Simpan file objects di array JS
  var allFiles = [];

  // Container untuk input-input tersembunyi yang akan dikirim
  var hiddenContainer = document.createElement('div');
  hiddenContainer.style.display = 'none';
  rgForm.appendChild(hiddenContainer);

  function escHtml(s){
    return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
  }

  function renderPreviews() {
    previewGrid.innerHTML = '';
    allFiles.forEach(function(fileObj, idx) {
      var reader = new FileReader();
      reader.onload = function(e) {
        var thumb = document.createElement('div');
        thumb.className = 'foto-thumb';
        thumb.dataset.idx = idx;
        thumb.innerHTML =
          '<img src="' + e.target.result + '" alt="">' +
          '<div class="ft-num">' + (idx + 1) + '</div>' +
          '<div class="ft-overlay">' +
            '<button type="button" class="ft-remove" data-idx="' + idx + '" title="Hapus">' +
              '<i class="bi bi-trash-fill"></i>' +
            '</button>' +
            (fileObj.label ? '<span class="ft-label-badge">' + escHtml(fileObj.label) + '</span>' : '') +
          '</div>';
        previewGrid.appendChild(thumb);
      };
      reader.readAsDataURL(fileObj.file);
    });

    countWrap.style.display = allFiles.length > 0 ? '' : 'none';
    if (allFiles.length > 0) countNum.textContent = allFiles.length;
  }

  function rebuildHiddenInputs() {
    // Hapus semua hidden input lama
    hiddenContainer.innerHTML = '';

    // Buat satu input file hidden per file
    // Tidak bisa set .files langsung, jadi kita pakai pendekatan FormData intercept saat submit
    // (lihat onsubmit handler di bawah)
  }

  function addFiles(fileList) {
    var label = document.getElementById('globalLabel').value.trim();
    Array.from(fileList).forEach(function(f) {
      allFiles.push({ file: f, label: label });
    });
    renderPreviews();
  }

  fotoInput.addEventListener('change', function() {
    if (this.files.length > 0) {
      addFiles(this.files);
      // Reset value agar file yang sama bisa dipilih lagi
      this.value = '';
    }
  });

  // Drag & drop
  dropArea.addEventListener('dragover',  function(e) { e.preventDefault(); this.classList.add('drag-over'); });
  dropArea.addEventListener('dragleave', function()  { this.classList.remove('drag-over'); });
  dropArea.addEventListener('drop', function(e) {
    e.preventDefault();
    this.classList.remove('drag-over');
    if (e.dataTransfer.files.length > 0) addFiles(e.dataTransfer.files);
  });

  // Hapus foto dari preview
  previewGrid.addEventListener('click', function(e) {
    var btn = e.target.closest('.ft-remove');
    if (!btn) return;
    var idx = parseInt(btn.dataset.idx);
    allFiles.splice(idx, 1);
    renderPreviews();
  });

  // ── INTERCEPT SUBMIT: kirim via FormData + fetch, bukan native form submit ──
  rgForm.addEventListener('submit', function(e) {
    e.preventDefault();

    var submitBtn = rgForm.querySelector('.btn-submit');
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="bi bi-hourglass-split"></i> Menyimpan...';

    var fd = new FormData(rgForm);

    // Hapus entry foto_tamu[] yang kosong dari input asli
    fd.delete('foto_tamu[]');

    // Tambahkan file dari array allFiles
    allFiles.forEach(function(fileObj) {
      fd.append('foto_tamu[]', fileObj.file, fileObj.file.name);
    });

    // Kirim label global (ambil dari input)
    fd.set('foto_label', document.getElementById('globalLabel').value.trim());

    fetch(rgForm.action, {
      method: 'POST',
      body: fd,
      headers: { 'X-Requested-With': 'XMLHttpRequest' }
    })
    .then(function(res) {
      // CodeIgniter redirect → ikuti redirect-nya
      if (res.redirected) {
        window.location.href = res.url;
        return;
      }
      // Kalau tidak redirect otomatis (tergantung konfigurasi CI)
      return res.text().then(function(html) {
        // Cek apakah ada redirect header di response
        if (res.url && res.url !== window.location.href) {
          window.location.href = res.url;
        } else {
          // Fallback: redirect manual ke halaman tamu
          window.location.href = '<?php echo base_url("tamu"); ?>';
        }
      });
    })
    .catch(function(err) {
      console.error(err);
      // Fallback: submit form normal (tanpa foto JS)
      submitBtn.disabled = false;
      submitBtn.innerHTML = '<i class="bi bi-person-check-fill"></i> Simpan & Check-in';
      alert('Terjadi error koneksi. Coba submit ulang.');
    });
  });

  // ─ Label chip helper ─
  window.setLabel = function(lbl) {
    document.getElementById('globalLabel').value = lbl;
  };

})();
</script>