<?php /* views/tamu/detail.php — versi multi-foto */ ?>
<style>
@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&display=swap');
:root{
  --teal-600:#0d9488;--teal-500:#14b8a6;--teal-50:#f0fdfa;--teal-100:#ccfbf1;
  --teal-700:#0b7a6e;--teal-800:#0b5a52;
  --slate-50:#f8fafc;--slate-100:#f1f5f9;--slate-200:#e2e8f0;
  --slate-400:#94a3b8;--slate-500:#64748b;--slate-700:#334155;--slate-900:#0f172a;
}
.dt-wrap{font-family:'DM Sans',system-ui,sans-serif;color:var(--slate-900);}
.dt-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;margin-bottom:18px;}
.dt-back:hover{border-color:var(--slate-400);color:var(--slate-900);}
.dt-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:14px;}
.dt-card-header{padding:13px 20px;background:linear-gradient(90deg,var(--teal-50),#fff);border-bottom:1px solid rgba(13,148,136,.1);}
.dt-card-body{padding:18px 20px;}
.dt-row{display:flex;gap:12px;padding:9px 0;border-bottom:1px solid var(--slate-50);}
.dt-row:last-child{border-bottom:none;padding-bottom:0;}
.dt-lbl{font-size:.73rem;font-weight:700;color:var(--slate-400);text-transform:uppercase;letter-spacing:.04em;width:130px;flex-shrink:0;padding-top:1px;}
.dt-val{font-size:.85rem;color:var(--slate-900);flex:1;}
.avatar-big{width:68px;height:68px;border-radius:13px;background:var(--teal-50);border:2px solid var(--teal-100);display:flex;align-items:center;justify-content:center;font-size:1.5rem;font-weight:700;color:var(--teal-600);}
.badge-status{display:inline-flex;align-items:center;gap:4px;padding:4px 11px;border-radius:999px;font-size:.73rem;font-weight:700;}
.bs-checkin{background:#dcfce7;color:#166534;border:1px solid #bbf7d0;}
.bs-checkout{background:var(--slate-100);color:var(--slate-500);border:1px solid var(--slate-200);}
.btn-co-big{display:inline-flex;align-items:center;gap:7px;padding:10px 20px;border-radius:10px;border:none;background:#dc2626;color:#fff;font-family:'DM Sans',sans-serif;font-size:.86rem;font-weight:700;cursor:pointer;transition:all .2s;text-decoration:none;}
.btn-co-big:hover{background:#b91c1c;color:#fff;}

/* ═══════════ FOTO GALLERY ═══════════ */
.foto-gallery-header {
  display: flex; align-items: center; justify-content: space-between;
  flex-wrap: wrap; gap: 8px;
}
.foto-gallery-header .title {
  font-size: .9rem; font-weight: 700; display: flex; align-items: center; gap: 7px;
}
.foto-gallery-header .title i { color: var(--teal-600); }
.foto-count-pill {
  background: var(--teal-50); color: var(--teal-700); border: 1px solid var(--teal-100);
  padding: 3px 10px; border-radius: 20px; font-size: .73rem; font-weight: 700;
}

/* Grid */
.foto-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 10px;
  margin-top: 14px;
}
.foto-item {
  border-radius: 11px; overflow: hidden; position: relative;
  aspect-ratio: 1; background: var(--slate-100);
  border: 1.5px solid var(--slate-200); cursor: pointer;
  transition: transform .15s, box-shadow .15s;
}
.foto-item:hover { transform: scale(1.03); box-shadow: 0 4px 16px rgba(0,0,0,.12); }
.foto-item img { width: 100%; height: 100%; object-fit: cover; display: block; }

/* Overlay on hover */
.foto-item .fi-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: 6px;
}
.foto-item:hover .fi-overlay { opacity: 1; }
.fi-btn-del {
  width: 32px; height: 32px; border-radius: 50%;
  background: #ef4444; color: #fff; border: none;
  display: flex; align-items: center; justify-content: center;
  cursor: pointer; font-size: .85rem;
  transition: background .15s;
}
.fi-btn-del:hover { background: #dc2626; }
.fi-btn-view {
  width: 32px; height: 32px; border-radius: 50%;
  background: rgba(255,255,255,.2); color: #fff; border: 1.5px solid rgba(255,255,255,.4);
  display: flex; align-items: center; justify-content: center;
  cursor: pointer; font-size: .85rem;
  transition: background .15s;
}
.fi-btn-view:hover { background: rgba(255,255,255,.35); }

/* Label badge on foto */
.fi-label {
  position: absolute; bottom: 0; left: 0; right: 0;
  background: linear-gradient(transparent, rgba(0,0,0,.65));
  padding: 18px 6px 5px;
  font-size: .65rem; color: #fff; font-weight: 600;
  text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}

/* Add foto card */
.foto-add-card {
  border-radius: 11px; aspect-ratio: 1;
  border: 2px dashed #d1d5db; background: #fafafa;
  display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px;
  cursor: pointer; transition: all .15s;
  font-size: .73rem; font-weight: 700; color: var(--slate-400);
}
.foto-add-card:hover { border-color: var(--teal-400); color: var(--teal-600); background: var(--teal-50); }
.foto-add-card i { font-size: 1.4rem; }

/* Empty state */
.foto-empty {
  padding: 32px 20px; text-align: center;
  color: var(--slate-400); border: 2px dashed #e5e7eb;
  border-radius: 12px; margin-top: 14px;
}
.foto-empty i { font-size: 2.2rem; display: block; margin-bottom: 8px; }
.foto-empty .fe-title { font-size: .85rem; font-weight: 700; color: var(--slate-500); }

/* ─ Upload panel (inline, slide down) ─ */
.upload-panel {
  display: none; margin-top: 14px;
  background: var(--teal-50); border: 1.5px solid var(--teal-100);
  border-radius: 12px; padding: 16px;
}
.upload-panel.show { display: block; animation: fadeUp .2s ease; }
.upload-panel .up-drop {
  border: 2px dashed var(--teal-300, #5eead4); border-radius: 9px;
  padding: 20px; text-align: center; cursor: pointer;
  background: #fff; transition: all .15s;
}
.upload-panel .up-drop:hover, .upload-panel .up-drop.drag-over {
  border-color: var(--teal-500); background: var(--teal-50);
}
.upload-panel .up-drop i { font-size: 1.4rem; color: var(--teal-500); display: block; margin-bottom: 6px; }
.upload-panel .up-drop span { font-size: .8rem; font-weight: 600; color: var(--teal-700); }
.upload-panel .up-drop small { display: block; font-size: .72rem; color: var(--slate-400); margin-top: 3px; }

/* Upload label + quick chips */
.up-label-row { display: flex; gap: 8px; margin-top: 12px; align-items: center; flex-wrap: wrap; }
.up-label-row label { font-size: .75rem; font-weight: 700; color: var(--slate-600); white-space: nowrap; }
.up-label-row input { flex: 1; min-width: 120px; border-radius: 7px; border: 1.5px solid #e5e7eb; padding: 6px 10px; font-size: .8rem; font-family: 'DM Sans',sans-serif; }
.label-chips { display: flex; flex-wrap: wrap; gap: 5px; margin-top: 7px; }
.label-chip { padding: 3px 9px; border-radius: 20px; font-size: .71rem; font-weight: 600; background: #fff; 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-300, #5eead4); }

/* Upload mini preview */
.up-preview-row { display: flex; flex-wrap: wrap; gap: 7px; margin-top: 12px; }
.up-preview-thumb { width: 52px; height: 52px; border-radius: 7px; overflow: hidden; border: 1.5px solid var(--slate-200); position: relative; }
.up-preview-thumb img { width: 100%; height: 100%; object-fit: cover; }
.up-preview-thumb .up-rm { position: absolute; top: -4px; right: -4px; width: 16px; height: 16px; border-radius: 50%; background: #ef4444; color: #fff; border: none; font-size: .55rem; display: flex; align-items: center; justify-content: center; cursor: pointer; }

.btn-upload-go { display: inline-flex; align-items: center; gap: 6px; margin-top: 12px; padding: 8px 18px; border: none; border-radius: 8px; background: linear-gradient(135deg,var(--teal-700),var(--teal-500)); color: #fff; font-family: 'DM Sans',sans-serif; font-size: .82rem; font-weight: 700; cursor: pointer; transition: all .15s; }
.btn-upload-go:hover { transform: translateY(-1px); }
.btn-upload-go:disabled { opacity: .6; cursor: not-allowed; transform: none; }
.btn-cancel-up { display: inline-flex; align-items: center; gap: 6px; margin-top: 12px; padding: 8px 14px; border: 1.5px solid #e5e7eb; border-radius: 8px; background: #fff; color: var(--slate-600); font-family: 'DM Sans',sans-serif; font-size: .82rem; font-weight: 600; cursor: pointer; }
.btn-cancel-up:hover { border-color: var(--slate-400); }

/* Lightbox */
.ev-lightbox {
  position: fixed; inset: 0; z-index: 9999;
  background: rgba(0,0,0,.88);
  display: flex; align-items: center; justify-content: center;
  backdrop-filter: blur(4px);
  -webkit-backdrop-filter: blur(4px);
}
.ev-lightbox.hidden { display: none; }
.ev-lightbox img {
  max-width: 90vw; max-height: 88vh;
  border-radius: 10px; object-fit: contain;
  box-shadow: 0 8px 40px rgba(0,0,0,.6);
}
.ev-lightbox-close {
  position: absolute; top: 16px; right: 16px;
  width: 40px; height: 40px; border-radius: 50%;
  background: rgba(255,255,255,.15); color: #fff; border: none;
  font-size: 1.1rem; display: flex; align-items: center; justify-content: center;
  cursor: pointer;
}
.ev-lightbox-info {
  position: absolute; bottom: 20px; left: 50%; transform: translateX(-50%);
  background: rgba(0,0,0,.55); color: #fff;
  font-size: .78rem; padding: 6px 14px; border-radius: 20px;
  font-family: 'DM Sans',sans-serif; white-space: nowrap;
}
.ev-lightbox-nav {
  position: absolute; top: 50%; transform: translateY(-50%);
  width: 40px; height: 40px; border-radius: 50%;
  background: rgba(255,255,255,.15); color: #fff; border: none;
  font-size: 1.1rem; display: flex; align-items: center; justify-content: center;
  cursor: pointer; transition: background .15s;
}
.ev-lightbox-nav:hover { background: rgba(255,255,255,.28); }
.ev-lightbox-nav.prev { left: 16px; }
.ev-lightbox-nav.next { right: 16px; }

/* Toast */
.ev-toast {
  position: fixed; bottom: 80px; right: 20px; z-index: 9998;
  background: #1e293b; color: #fff; border-radius: 10px;
  padding: 10px 16px; font-size: .82rem; font-family: 'DM Sans',sans-serif;
  display: flex; align-items: center; gap: 8px; font-weight: 600;
  box-shadow: 0 4px 20px rgba(0,0,0,.2);
  transform: translateY(20px); opacity: 0; transition: all .2s;
  pointer-events: none;
}
.ev-toast.show { transform: translateY(0); opacity: 1; }
.ev-toast.toast-ok { border-left: 4px solid #10b981; }
.ev-toast.toast-err { border-left: 4px solid #ef4444; }

@keyframes fadeUp{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:none}}
.dt-card{animation:fadeUp .35s ease both;}
@keyframes pulse{0%,100%{opacity:1}50%{opacity:.4}}

@media(max-width:767px){
  .foto-grid{ grid-template-columns: repeat(auto-fill, minmax(90px,1fr)); gap:7px; }
}
</style>

<div class="dt-wrap">
<div class="container-fluid px-2 px-md-3 py-3">
<div class="row justify-content-center">
<div class="col-lg-7 col-xl-6">

<?php
  $t = $tamu;
  $keperluan_map = [
    'kunjungan'    =>['label'=>'Kunjungan Biasa','icon'=>'bi-house-door','cls'=>'background:#f0fdf4;color:#166534;'],
    'antar_paket'  =>['label'=>'Antar Paket','icon'=>'bi-box-seam','cls'=>'background:#fef3c7;color:#92400e;'],
    'tamu_menginap'=>['label'=>'Tamu Menginap','icon'=>'bi-moon-stars','cls'=>'background:#dbeafe;color:#1e40af;'],
    'kerja'        =>['label'=>'Kerja / Teknisi','icon'=>'bi-tools','cls'=>'background:#ede9fe;color:#5b21b6;'],
    'lainnya'      =>['label'=>'Lainnya','icon'=>'bi-three-dots','cls'=>'background:#f3f4f6;color:#4b5563;'],
  ];
  $kp      = $keperluan_map[$t->keperluan] ?? ['label'=>ucfirst($t->keperluan),'icon'=>'bi-question','cls'=>'background:#f3f4f6;color:#4b5563;'];
  $initial = strtoupper(substr($t->nama_tamu,0,1));
  $dur_live = empty($t->checkout_at);
?>

  <div class="d-flex align-items-center gap-2 mb-3 flex-wrap">
    <a href="<?php echo base_url('tamu'); ?>" class="dt-back" style="margin-bottom:0;"><i class="bi bi-arrow-left"></i> Kembali</a>
    <?php if($this->session->userdata('role') !== 'warga'): ?>
    <a href="<?php echo base_url('tamu/edit/'.$t->id); ?>"
       style="display:inline-flex;align-items:center;gap:6px;padding:9px 16px;border-radius:9px;
              border:1.5px solid #fde68a;background:#fffbeb;font-size:.82rem;font-weight:600;
              color:#92400e;text-decoration:none;transition:all .15s;">
      <i class="bi bi-pencil-fill"></i> Edit
    </a>
    <?php endif; ?>
  </div>

  <!-- IDENTITAS -->
  <div class="dt-card">
    <div class="dt-card-header">
      <div class="d-flex align-items-center justify-content-between">
        <div class="d-flex align-items-center gap-3">
          <div class="avatar-big"><?php echo $initial; ?></div>
          <div>
            <div style="font-size:1rem;font-weight:700;margin-bottom:2px;"><?php echo htmlspecialchars($t->nama_tamu ?? ''); ?></div>
            <div style="font-size:.76rem;color:var(--slate-400);font-family:monospace;"><?php echo $t->kode_tamu; ?></div>
          </div>
        </div>
        <?php if($t->status==='checkin'): ?>
        <span class="badge-status bs-checkin"><span style="width:7px;height:7px;border-radius:50%;background:#10b981;display:inline-block;margin-right:3px;animation:pulse 1.6s infinite;"></span>Check-in</span>
        <?php else: ?>
        <span class="badge-status bs-checkout"><i class="bi bi-check2 me-1"></i>Checkout</span>
        <?php endif; ?>
      </div>
    </div>
    <div class="dt-card-body">
      <?php if(!empty($t->nik_tamu)): ?><div class="dt-row"><div class="dt-lbl">NIK</div><div class="dt-val" style="font-family:monospace;"><?php echo htmlspecialchars($t->nik_tamu ?? ''); ?></div></div><?php endif; ?>
      <?php if(!empty($t->no_hp)): ?><div class="dt-row"><div class="dt-lbl">No. HP</div><div class="dt-val"><i class="bi bi-whatsapp me-1" style="color:#25d366;"></i><?php echo htmlspecialchars($t->no_hp ?? ''); ?></div></div><?php endif; ?>
      <div class="dt-row"><div class="dt-lbl">Check-in</div><div class="dt-val" style="color:#059669;font-weight:700;"><i class="bi bi-box-arrow-in-right me-1"></i><?php echo date('d/m/Y H:i',strtotime($t->checkin_at)); ?></div></div>

      <div class="dt-row">
        <div class="dt-lbl">Durasi</div>
        <div class="dt-val">
          <span id="detailDurBadge"
            style="display:inline-flex;align-items:center;gap:5px;padding:4px 12px;border-radius:20px;font-size:.8rem;font-weight:700;background:#f0fdf4;color:#166534;border:1px solid #bbf7d0;"
            data-checkin="<?php echo $t->checkin_at; ?>"
            data-checkout="<?php echo $t->checkout_at ?: ''; ?>">
            <?php if($dur_live): ?>
            <span style="width:7px;height:7px;border-radius:50%;background:currentColor;display:inline-block;opacity:.7;animation:pulse 1.6s infinite;"></span>
            <?php else: ?>
            <i class="bi bi-check2-circle"></i>
            <?php endif; ?>
            <span id="detailDurText">...</span>
          </span>
          <?php if($dur_live): ?>
          <small style="font-size:.7rem;color:var(--slate-400);margin-left:6px;" id="detailDurSince"></small>
          <?php else: ?>
          <small style="font-size:.7rem;color:var(--slate-400);margin-left:6px;">total kunjungan</small>
          <?php endif; ?>
        </div>
      </div>
      <?php if($t->checkout_at): ?><div class="dt-row"><div class="dt-lbl">Checkout</div><div class="dt-val" style="color:#dc2626;font-weight:700;"><i class="bi bi-box-arrow-right me-1"></i><?php echo date('d/m/Y H:i',strtotime($t->checkout_at)); ?></div></div><?php endif; ?>
      <?php if($t->tipe_kunjungan==='menginap' && $t->rencana_checkout): ?><div class="dt-row"><div class="dt-lbl">Rencana CO</div><div class="dt-val"><i class="bi bi-calendar-event me-1" style="color:#7c3aed;"></i><?php echo date('d/m/Y',strtotime($t->rencana_checkout)); ?></div></div><?php endif; ?>
      <?php if(!empty($t->tujuan_blok)): ?><div class="dt-row"><div class="dt-lbl">Tujuan</div><div class="dt-val" style="font-weight:700;color:var(--teal-700);"><i class="bi bi-geo-alt-fill me-1"></i><?php echo htmlspecialchars($t->tujuan_blok ?? ''); ?></div></div><?php endif; ?>
      <?php if(!empty($t->nama_tuan_rumah)): ?><div class="dt-row"><div class="dt-lbl">Tuan Rumah</div><div class="dt-val"><?php echo htmlspecialchars($t->nama_tuan_rumah ?? ''); ?></div></div><?php endif; ?>
      <div class="dt-row"><div class="dt-lbl">Keperluan</div><div class="dt-val"><span style="display:inline-flex;align-items:center;gap:5px;padding:3px 9px;border-radius:7px;font-size:.75rem;font-weight:700;<?php echo $kp['cls']; ?>"><i class="bi <?php echo $kp['icon']; ?>"></i><?php echo $kp['label']; ?></span><?php if(!empty($t->keperluan_detail)): ?><div style="font-size:.77rem;color:var(--slate-500);margin-top:4px;"><?php echo htmlspecialchars($t->keperluan_detail ?? ''); ?></div><?php endif; ?></div></div>
      <?php if(!empty($t->no_kendaraan)): ?><div class="dt-row"><div class="dt-lbl">Kendaraan</div><div class="dt-val"><span style="font-family:monospace;font-weight:700;font-size:.88rem;background:#f8fafc;padding:2px 8px;border-radius:5px;border:1px solid #e5e7eb;"><?php echo strtoupper($t->no_kendaraan); ?></span><?php if(!empty($t->jenis_kendaraan)): ?> <span style="font-size:.75rem;color:var(--slate-400);"><?php echo $t->jenis_kendaraan; ?></span><?php endif; ?></div></div><?php endif; ?>
      <?php if(!empty($t->catatan)): ?><div class="dt-row"><div class="dt-lbl">Catatan</div><div class="dt-val" style="color:var(--slate-500);font-style:italic;"><?php echo nl2br(htmlspecialchars($t->catatan ?? '')); ?></div></div><?php endif; ?>
    </div>
  </div>

  <!-- ═══ FOTO GALLERY ═══ -->
  <div class="dt-card">
    <div class="dt-card-header">
      <div class="foto-gallery-header">
        <div class="title"><i class="bi bi-images"></i> Foto Dokumentasi</div>
        <div class="d-flex align-items-center gap-2">
          <span class="foto-count-pill" id="fotoCountPill">
            <i class="bi bi-images me-1"></i><span id="fotoCountNum"><?php echo count($fotos); ?></span> foto
          </span>
          <button type="button" class="btn-detail" id="btnTambahFoto"
            style="display:inline-flex;align-items:center;gap:5px;padding:5px 12px;border-radius:8px;border:1.5px solid var(--teal-100);background:var(--teal-50);font-size:.76rem;font-weight:600;cursor:pointer;color:var(--teal-700);transition:all .15s;">
            <i class="bi bi-plus-circle-fill"></i> Tambah Foto
          </button>
        </div>
      </div>
    </div>
    <div class="dt-card-body" style="padding-top:12px;">

      <!-- Upload panel (tersembunyi, toggle) -->
      <div class="upload-panel" id="uploadPanel">
        <div class="up-drop" id="upDrop">
          <input type="file" id="upInput" accept="image/*" multiple style="display:none;">
          <i class="bi bi-cloud-arrow-up-fill"></i>
          <span>Klik atau drag foto ke sini</span>
          <small>JPG, PNG, WEBP — maks 5MB per foto, bebas jumlah</small>
        </div>
        <div class="up-label-row">
          <label>Label:</label>
          <input type="text" id="upLabel" placeholder="cth. Foto Wajah (opsional)">
        </div>
        <div class="label-chips">
          <span class="label-chip" onclick="setUpLabel('Foto Wajah')"><i class="bi bi-person-fill me-1"></i>Foto Wajah</span>
          <span class="label-chip" onclick="setUpLabel('Foto KTP')"><i class="bi bi-card-text me-1"></i>Foto KTP</span>
          <span class="label-chip" onclick="setUpLabel('Foto Kendaraan')"><i class="bi bi-car-front me-1"></i>Foto Kendaraan</span>
          <span class="label-chip" onclick="setUpLabel('Foto Barang')"><i class="bi bi-box-seam me-1"></i>Foto Barang</span>
          <span class="label-chip" onclick="setUpLabel('Lainnya')">Lainnya</span>
        </div>
        <div class="up-preview-row" id="upPreviewRow"></div>
        <div class="d-flex gap-2 flex-wrap">
          <button type="button" class="btn-upload-go" id="btnDoUpload" disabled>
            <i class="bi bi-cloud-arrow-up"></i> Upload Foto
          </button>
          <button type="button" class="btn-cancel-up" id="btnCancelUp">Batal</button>
        </div>
      </div>

      <!-- Foto Grid -->
      <div class="foto-grid" id="fotoGrid">
        <?php if(!empty($fotos)): ?>
          <?php foreach($fotos as $i => $f): ?>
          <div class="foto-item" data-id="<?php echo $f->id; ?>" data-url="<?php echo base_url('uploads/foto_tamu/'.$f->nama_file); ?>" data-label="<?php echo htmlspecialchars($f->label ?? ''); ?>">
            <img src="<?php echo base_url('uploads/foto_tamu/'.$f->nama_file); ?>" alt="Foto <?php echo $i+1; ?>" loading="lazy">
            <?php if(!empty($f->label)): ?>
            <div class="fi-label"><?php echo htmlspecialchars($f->label ?? ''); ?></div>
            <?php endif; ?>
            <div class="fi-overlay">
              <div class="d-flex gap-2">
                <button type="button" class="fi-btn-view btn-lightbox" data-idx="<?php echo $i; ?>" title="Lihat"><i class="bi bi-arrows-fullscreen"></i></button>
                <button type="button" class="fi-btn-del btn-del-foto" data-id="<?php echo $f->id; ?>" title="Hapus foto ini"><i class="bi bi-trash-fill"></i></button>
              </div>
              <span class="ft-label-badge" style="font-size:.62rem;color:rgba(255,255,255,.8);"><?php echo date('d/m H:i',strtotime($f->created_at)); ?></span>
            </div>
          </div>
          <?php endforeach; ?>
        <?php else: ?>
          <div class="foto-empty" style="grid-column:1/-1;" id="fotoEmpty">
            <i class="bi bi-images"></i>
            <div class="fe-title">Belum ada foto</div>
            <small>Klik "Tambah Foto" untuk upload dokumentasi</small>
          </div>
        <?php endif; ?>
      </div>

    </div>
  </div>

  <!-- CHECKOUT ACTION -->
  <?php if($t->status === 'checkin'): ?>
  <div class="dt-card">
    <div class="dt-card-body">
      <div class="d-flex gap-3 align-items-center flex-wrap">
        <a href="<?php echo base_url('tamu/checkout/'.$t->id); ?>"
           class="btn-co-big"
           data-confirm="Konfirmasi checkout tamu <strong><?php echo addslashes($t->nama_tamu); ?></strong>?" 
           data-title="Checkout Tamu" data-type="danger">
          <i class="bi bi-box-arrow-right"></i> Proses Checkout Sekarang
        </a>
        <div style="font-size:.78rem;color:var(--slate-400);">
          Sekarang: <strong id="localClockCO">--:--</strong>
        </div>
      </div>
    </div>
  </div>
  <?php endif; ?>

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

<!-- LIGHTBOX -->
<div class="ev-lightbox hidden" id="lightbox">
  <button class="ev-lightbox-close" id="lbClose"><i class="bi bi-x-lg"></i></button>
  <button class="ev-lightbox-nav prev" id="lbPrev"><i class="bi bi-chevron-left"></i></button>
  <img src="" id="lbImg" alt="">
  <button class="ev-lightbox-nav next" id="lbNext"><i class="bi bi-chevron-right"></i></button>
  <div class="ev-lightbox-info" id="lbInfo"></div>
</div>

<!-- TOAST -->
<div class="ev-toast" id="evToast"><i class="bi bi-check-circle-fill"></i> <span id="toastMsg"></span></div>

<script>
(function(){
  var tamuId     = <?php echo (int)$t->id; ?>;
  var uploadUrl  = '<?php echo base_url("tamu/upload_foto/".$t->id); ?>';
  var hapusFotoUrl='<?php echo base_url("tamu/hapus_foto"); ?>';

  // ─ Helpers ─
  function toast(msg, ok){
    var el = document.getElementById('evToast');
    var ms = document.getElementById('toastMsg');
    ms.textContent = msg;
    el.className = 'ev-toast show ' + (ok===false ? 'toast-err' : 'toast-ok');
    setTimeout(function(){ el.className = 'ev-toast'; }, 2800);
  }
  function esc(s){ return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }
  window.setUpLabel = function(l){ document.getElementById('upLabel').value=l; };

  // ─ Toggle upload panel ─
  var btnTambah = document.getElementById('btnTambahFoto');
  var panel     = document.getElementById('uploadPanel');
  var btnCancel = document.getElementById('btnCancelUp');
  btnTambah.addEventListener('click', function(){
    panel.classList.toggle('show');
    btnTambah.style.background = panel.classList.contains('show') ? 'var(--teal-100)' : '';
  });
  btnCancel.addEventListener('click', function(){
    panel.classList.remove('show');
    btnTambah.style.background = '';
    clearUpPreview();
  });

  // ─ Upload file selection ─
  var upInput   = document.getElementById('upInput');
  var upDrop    = document.getElementById('upDrop');
  var upPreview = document.getElementById('upPreviewRow');
  var btnGo     = document.getElementById('btnDoUpload');
  var pendingFiles = [];

  upDrop.addEventListener('click', function(){ upInput.click(); });
  upDrop.addEventListener('dragover', function(e){ e.preventDefault(); this.classList.add('drag-over'); });
  upDrop.addEventListener('dragleave', function(){ this.classList.remove('drag-over'); });
  upDrop.addEventListener('drop', function(e){
    e.preventDefault(); this.classList.remove('drag-over');
    addUpFiles(e.dataTransfer.files);
  });
  upInput.addEventListener('change', function(){
    addUpFiles(this.files);
    this.value='';
  });

  function addUpFiles(files){
    Array.from(files).forEach(function(f){ pendingFiles.push(f); });
    renderUpPreview();
  }
  function clearUpPreview(){ pendingFiles=[]; renderUpPreview(); }
  function renderUpPreview(){
    upPreview.innerHTML='';
    btnGo.disabled = pendingFiles.length === 0;
    pendingFiles.forEach(function(f,i){
      var reader=new FileReader();
      reader.onload=function(e){
        var t=document.createElement('div');
        t.className='up-preview-thumb';
        t.innerHTML='<img src="'+e.target.result+'" alt=""><button type="button" class="up-rm" data-idx="'+i+'">×</button>';
        upPreview.appendChild(t);
      };
      reader.readAsDataURL(f);
    });
  }
  upPreview.addEventListener('click',function(e){
    var btn=e.target.closest('.up-rm');
    if(!btn) return;
    pendingFiles.splice(parseInt(btn.dataset.idx),1);
    renderUpPreview();
  });

  // ─ Do upload ─
  btnGo.addEventListener('click', function(){
    if(pendingFiles.length===0) return;
    btnGo.disabled=true;
    btnGo.innerHTML='<i class="bi bi-hourglass-split"></i> Mengupload...';

    var fd=new FormData();
    pendingFiles.forEach(function(f){ fd.append('foto[]',f); });
    var label=document.getElementById('upLabel').value.trim();
    if(label) fd.append('label',label);

    fetch(uploadUrl,{ method:'POST', body:fd, headers:{'X-Requested-With':'XMLHttpRequest'} })
    .then(function(r){ return r.json(); })
    .then(function(res){
      if(res.status==='ok'){
        toast(''+res.uploaded+' foto berhasil diupload');
        renderFotoGrid(res.fotos, res.total);
        panel.classList.remove('show');
        btnTambah.style.background='';
        clearUpPreview();
        document.getElementById('upLabel').value='';
      } else {
        toast('Gagal upload', false);
      }
      btnGo.disabled=false;
      btnGo.innerHTML='<i class="bi bi-cloud-arrow-up"></i> Upload Foto';
    })
    .catch(function(){
      toast('Koneksi error', false);
      btnGo.disabled=false;
      btnGo.innerHTML='<i class="bi bi-cloud-arrow-up"></i> Upload Foto';
    });
  });

  // ─ Render foto grid from server response ─
  function renderFotoGrid(fotos, total){
    var grid=document.getElementById('fotoGrid');
    grid.innerHTML='';
    lbFotos=[];
    if(!fotos||fotos.length===0){
      grid.innerHTML='<div class="foto-empty" style="grid-column:1/-1;" id="fotoEmpty"><i class="bi bi-images"></i><div class="fe-title">Belum ada foto</div><small>Klik "Tambah Foto" untuk upload dokumentasi</small></div>';
    } else {
      fotos.forEach(function(f,i){
        lbFotos.push({url:f.url,label:f.label});
        var div=document.createElement('div');
        div.className='foto-item';
        div.dataset.id=f.id;
        div.dataset.url=f.url;
        div.dataset.label=f.label||'';
        div.innerHTML='<img src="'+esc(f.url)+'" alt="Foto '+(i+1)+'" loading="lazy">'
          +(f.label?'<div class="fi-label">'+esc(f.label)+'</div>':'')
          +'<div class="fi-overlay"><div class="d-flex gap-2">'
          +'<button type="button" class="fi-btn-view btn-lightbox" data-idx="'+i+'" title="Lihat"><i class="bi bi-arrows-fullscreen"></i></button>'
          +'<button type="button" class="fi-btn-del btn-del-foto" data-id="'+f.id+'" title="Hapus"><i class="bi bi-trash-fill"></i></button>'
          +'</div><span class="ft-label-badge" style="font-size:.62rem;color:rgba(255,255,255,.8);">'+esc(f.created)+'</span></div>';
        grid.appendChild(div);
      });
    }
    document.getElementById('fotoCountNum').textContent=total||0;
  }

  // ─ Delete foto ─
  document.getElementById('fotoGrid').addEventListener('click',function(e){
    var btn=e.target.closest('.btn-del-foto');
    if(!btn) return;
    
    GlobalModal.confirm({
        title: 'Hapus Foto',
        message: 'Hapus foto dokumentasi ini? Tindakan ini tidak dapat dibatalkan.',
        type: 'danger',
        onConfirm: function() {
            var fotoId=btn.dataset.id;
            var fd=new FormData(); fd.append('foto_id',fotoId);
            fetch(hapusFotoUrl,{method:'POST',body:fd,headers:{'X-Requested-With':'XMLHttpRequest'}})
            .then(function(r){ return r.json(); })
            .then(function(res){
              if(res.status==='ok'){
                var item=btn.closest('.foto-item');
                if(item){ item.style.opacity='0'; item.style.transform='scale(.85)'; item.style.transition='all .2s'; setTimeout(function(){ item.remove(); refreshGrid(); },200); }
                document.getElementById('fotoCountNum').textContent=res.total;
                toast('Foto dihapus');
              } else { toast('Gagal menghapus', false); }
            });
        }
    });
  });

  function refreshGrid(){
    var grid=document.getElementById('fotoGrid');
    var items=grid.querySelectorAll('.foto-item');
    lbFotos=[];
    items.forEach(function(item,i){
      lbFotos.push({url:item.dataset.url,label:item.dataset.label});
      var vb=item.querySelector('.btn-lightbox');
      if(vb) vb.dataset.idx=i;
    });
    if(items.length===0){
      grid.innerHTML='<div class="foto-empty" style="grid-column:1/-1;"><i class="bi bi-images"></i><div class="fe-title">Belum ada foto</div><small>Klik "Tambah Foto" untuk upload</small></div>';
    }
  }

  // ─ LIGHTBOX ─
  var lbFotos = <?php echo json_encode(array_values(array_map(function($f) use ($t) {
    return ['url' => base_url('uploads/foto_tamu/'.$f->nama_file), 'label' => $f->label ?? ''];
  }, $fotos))); ?>;
  var lbCurrent = 0;
  var lb  = document.getElementById('lightbox');
  var lbImg = document.getElementById('lbImg');
  var lbInfo= document.getElementById('lbInfo');

  function openLightbox(idx){
    if(!lbFotos.length) return;
    lbCurrent=idx;
    var f=lbFotos[idx];
    lbImg.src=f.url;
    lbInfo.textContent=(f.label||'Foto '+(idx+1)) + '  ('+(idx+1)+'/'+lbFotos.length+')';
    lb.classList.remove('hidden');
    document.body.style.overflow='hidden';
  }
  function closeLightbox(){ lb.classList.add('hidden'); document.body.style.overflow=''; }

  document.getElementById('lbClose').addEventListener('click', closeLightbox);
  document.getElementById('lbPrev').addEventListener('click', function(){
    openLightbox((lbCurrent-1+lbFotos.length)%lbFotos.length);
  });
  document.getElementById('lbNext').addEventListener('click', function(){
    openLightbox((lbCurrent+1)%lbFotos.length);
  });
  lb.addEventListener('click', function(e){ if(e.target===lb) closeLightbox(); });
  document.addEventListener('keydown', function(e){
    if(lb.classList.contains('hidden')) return;
    if(e.key==='Escape') closeLightbox();
    if(e.key==='ArrowLeft') document.getElementById('lbPrev').click();
    if(e.key==='ArrowRight') document.getElementById('lbNext').click();
  });

  document.getElementById('fotoGrid').addEventListener('click', function(e){
    var btn=e.target.closest('.btn-lightbox');
    if(!btn) return;
    openLightbox(parseInt(btn.dataset.idx)||0);
  });

  // ── Live Durasi Detail — timezone otomatis dari browser ──
  var detailBadge = document.getElementById('detailDurBadge');
  var detailText  = document.getElementById('detailDurText');
  var detailSince = document.getElementById('detailDurSince');

  function parseLocalDT(str) {
    if (!str) return null;
    // "2026-03-15 12:46:00" → parse sebagai local time browser
    return new Date(str.replace(' ', 'T'));
  }

  function formatDur(sec) {
    if (sec < 60) return 'Baru masuk';
    var m = Math.floor(sec / 60);
    var h = Math.floor(m / 60);
    var d = Math.floor(h / 24);
    if (h < 1)  return m + ' menit';
    if (d < 1)  return (m % 60) > 0 ? h + ' jam ' + (m % 60) + ' menit' : h + ' jam';
    return (h % 24) > 0 ? d + ' hari ' + (h % 24) + ' jam' : d + ' hari';
  }

  function applyDurColor(el, sec) {
    var h = sec / 3600;
    if (h < 1) {
      el.style.background = '#f0fdf4'; el.style.color = '#166534'; el.style.borderColor = '#bbf7d0';
    } else if (h < 4) {
      el.style.background = '#fef3c7'; el.style.color = '#92400e'; el.style.borderColor = '#fde68a';
    } else {
      el.style.background = '#fee2e2'; el.style.color = '#991b1b'; el.style.borderColor = '#fecaca';
    }
  }

  if (detailBadge) {
    var ciDT = parseLocalDT(detailBadge.dataset.checkin);
    var coDT = detailBadge.dataset.checkout ? parseLocalDT(detailBadge.dataset.checkout) : null;

    // Tampilkan "berjalan sejak HH:mm" pakai jam lokal browser
    if (detailSince && ciDT) {
      var pad = function(n){ return String(n).padStart(2,'0'); };
      detailSince.textContent = 'berjalan sejak ' + pad(ciDT.getHours()) + ':' + pad(ciDT.getMinutes());
    }

    function tickDetail() {
      if (!ciDT) return;
      var endTime = coDT ? coDT : new Date();
      var diff    = Math.max(0, Math.floor((endTime - ciDT) / 1000));
      detailText.textContent = formatDur(diff);
      applyDurColor(detailBadge, diff);
    }

    tickDetail();
    if (!coDT) setInterval(tickDetail, 60000); // live update hanya jika masih checkin
  }

  // ── Jam lokal browser untuk tombol checkout ──
  var clockEl = document.getElementById('localClockCO');
  if (clockEl) {
    function updateClock() {
      var now  = new Date();
      var pad  = function(n){ return String(n).padStart(2,'0'); };
      clockEl.textContent = pad(now.getHours()) + ':' + pad(now.getMinutes());
    }
    updateClock();
    setInterval(updateClock, 1000);
  }

})();
</script>