<?php /* views/tamu/index.php */ ?>
<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;
  --card-shadow: 0 1px 3px rgba(0,0,0,.06), 0 4px 20px rgba(0,0,0,.06);
}

.ev-wrap { font-family: 'DM Sans', system-ui, sans-serif; color: var(--slate-900); }
.ev-wrap .btn:focus, .ev-wrap input:focus, .ev-wrap select:focus { box-shadow: none; }
.ev-wrap input:focus, .ev-wrap select:focus { border-color: var(--teal-500); box-shadow: 0 0 0 3px rgba(13,148,136,.12); }
.ev-wrap input, .ev-wrap select { border-radius: 8px; border: 1.5px solid #e5e7eb; font-size: .86rem; padding: 7px 11px; font-family: 'DM Sans', sans-serif; }

/* ─ PAGE HEADER ─ */
.ev-header { display: flex; justify-content: space-between; align-items: flex-start; flex-wrap: wrap; gap: 14px; margin-bottom: 22px; }
.ev-header-left h4 { font-size: 1.2rem; font-weight: 700; color: var(--teal-800); margin: 0 0 4px; display: flex; align-items: center; gap: 10px; }
.ev-header-left h4 .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; }
.ev-breadcrumb { font-size: .74rem; color: #94a3b8; padding-left: 48px; }
.ev-breadcrumb a { color: var(--teal-600); text-decoration: none; font-weight: 600; }

/* ─ STAT CARDS ─ */
.ev-stat-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 14px; margin-bottom: 20px; }
.ev-stat-card { border-radius: 14px; padding: 18px 16px; position: relative; overflow: hidden; color: #fff; transition: transform .2s; }
.ev-stat-card:hover { transform: translateY(-3px); }
.ev-stat-card::before { content: ''; position: absolute; top: -24px; right: -24px; width: 100px; height: 100px; border-radius: 50%; background: rgba(255,255,255,.1); }
.ev-stat-card .sc-label { font-size: .7rem; font-weight: 600; opacity: .82; text-transform: uppercase; letter-spacing: .06em; margin-bottom: 6px; position: relative; z-index: 1; }
.ev-stat-card .sc-value { font-size: 1.6rem; font-weight: 700; line-height: 1.1; position: relative; z-index: 1; }
.ev-stat-card .sc-sub { font-size: .7rem; opacity: .7; margin-top: 4px; position: relative; z-index: 1; }
.ev-stat-card .sc-icon { position: absolute; right: 14px; top: 50%; transform: translateY(-50%); width: 46px; height: 46px; background: rgba(255,255,255,.15); border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 1.2rem; z-index: 1; }
.sc-teal   { background: linear-gradient(135deg,#0b7a6e,#0d9488,#2dd4bf); box-shadow: 0 8px 24px rgba(13,148,136,.28); }
.sc-green  { background: linear-gradient(135deg,#059669,#10b981,#34d399); box-shadow: 0 8px 24px rgba(16,185,129,.28); }
.sc-amber  { background: linear-gradient(135deg,#d97706,#f59e0b,#fbbf24); box-shadow: 0 8px 24px rgba(245,158,11,.28); }
.sc-blue   { background: linear-gradient(135deg,#1d4ed8,#3b82f6,#60a5fa); box-shadow: 0 8px 24px rgba(59,130,246,.28); }

/* ─ FILTER BAR ─ */
.ev-filter { background: var(--teal-50); border: 1.5px solid var(--teal-100); border-radius: 10px; padding: 10px 14px; margin-bottom: 14px; display: flex; flex-wrap: wrap; gap: 10px; align-items: center; }
.ev-filter .fb-label { font-size: .72rem; font-weight: 700; color: var(--teal-700); white-space: nowrap; display: flex; align-items: center; gap: 5px; }
.ev-search-box { display: flex; align-items: center; gap: 6px; background: #fff; border: 1.5px solid #e5e7eb; border-radius: 8px; padding: 5px 10px; flex: 1; min-width: 180px; }
.ev-search-box input { border: none !important; padding: 0 !important; outline: none; font-size: .84rem; background: transparent; flex: 1; }
.ev-search-box i { color: var(--slate-400); font-size: .9rem; }
.filter-count-pill { font-size: .75rem; font-weight: 700; color: var(--teal-600); background: var(--teal-100); padding: 2px 10px; border-radius: 20px; white-space: nowrap; }

/* ─ BTN ─ */
.btn-reg { display: inline-flex; align-items: center; gap: 7px; padding: 9px 18px; border-radius: 50px; border: none; font-size: .82rem; font-weight: 700; cursor: pointer; background: linear-gradient(135deg, var(--teal-700), var(--teal-500)); color: #fff; box-shadow: 0 4px 12px rgba(13,148,136,.28); text-decoration: none; transition: all .2s; }
.btn-reg:hover { transform: translateY(-2px); color: #fff; box-shadow: 0 8px 20px rgba(13,148,136,.38); }

/* ─ SECTION CARD ─ */
.ev-section { border-radius: 14px; border: 1px solid var(--slate-200); box-shadow: var(--card-shadow); overflow: hidden; background: #fff; }
.ev-section-header { padding: 13px 18px; display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px; background: linear-gradient(90deg, var(--teal-50), #fff); border-bottom: 1px solid rgba(13,148,136,.1); }
.ev-section-header .title { font-size: .92rem; font-weight: 700; color: var(--slate-900); display: flex; align-items: center; gap: 7px; }
.ev-section-header .title i { color: var(--teal-600); }
.record-pill { background: var(--teal-50); color: var(--teal-700); border: 1px solid rgba(13,148,136,.2); padding: 3px 10px; border-radius: 20px; font-size: .72rem; font-weight: 700; }

/* ─ TABLE ─ */
.ev-table { width: 100%; border-collapse: collapse; font-size: .82rem; min-width: 700px; }
.ev-table thead th { font-size: .72rem; text-transform: uppercase; letter-spacing: .04em; color: var(--slate-500); font-weight: 700; padding: 9px 13px; background: var(--slate-50); border-bottom: 2px solid var(--slate-200); white-space: nowrap; }
.ev-table tbody tr { border-bottom: 1px solid #f8fafc; transition: background .12s; }
.ev-table tbody tr:last-child { border-bottom: none; }
.ev-table tbody tr:hover { background: var(--teal-50); }
.ev-table tbody td { padding: 10px 13px; vertical-align: middle; }

/* ─ BADGES ─ */
.badge-status { display: inline-flex; align-items: center; gap: 4px; padding: 3px 9px; border-radius: 999px; font-size: .7rem; font-weight: 700; white-space: nowrap; }
.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); }
.bs-menginap { background: #dbeafe; color: #1e40af; border: 1px solid #93c5fd; }
.bs-singkat  { background: #f0fdf4; color: #15803d; border: 1px solid #86efac; }

.keperluan-pill { display: inline-flex; align-items: center; gap: 4px; padding: 2px 8px; border-radius: 6px; font-size: .71rem; font-weight: 600; white-space: nowrap; }
.kp-paket    { background: #fef3c7; color: #92400e; }
.kp-menginap { background: #dbeafe; color: #1e40af; }
.kp-kerja    { background: #ede9fe; color: #5b21b6; }
.kp-kunjungan{ background: #f0fdf4; color: #166534; }
.kp-lainnya  { background: #f3f4f6; color: #4b5563; }

/* ─ DURASI BADGE ─ */
.dur-badge {
  display: inline-flex; align-items: center; gap: 3px;
  padding: 3px 9px; border-radius: 20px;
  font-size: .73rem; font-weight: 700; white-space: nowrap;
}
.dur-new    { background: #f0fdf4; color: #15803d; border: 1px solid #86efac; }
.dur-short  { background: #f0fdf4; color: #15803d; border: 1px solid #86efac; }
.dur-medium { background: #fef3c7; color: #92400e; border: 1px solid #fde68a; }
.dur-long   { background: #fee2e2; color: #991b1b; border: 1px solid #fecaca; }
.dur-done   { opacity: .7; }
.dur-live   { }
.time-block { display: flex; flex-direction: column; gap: 1px; }
.time-in  { display: flex; align-items: center; gap: 5px; color: #059669; font-weight: 700; font-size: .83rem; }
.time-out { display: flex; align-items: center; gap: 5px; color: #dc2626; font-weight: 600; font-size: .8rem; }
.time-date{ font-size: .7rem; color: var(--slate-400); margin-top: 2px; }

/* ─ GUEST CELL ─ */
.guest-cell { display: flex; align-items: center; gap: 9px; }
.guest-avatar { width: 34px; height: 34px; border-radius: 9px; background: var(--teal-50); color: var(--teal-600); display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: .95rem; flex-shrink: 0; border: 1.5px solid var(--teal-100); }
.guest-name { font-weight: 700; font-size: .85rem; }
.guest-sub  { font-size: .72rem; color: var(--slate-400); }

/* ─ ACTION BUTTONS ─ */
.btn-co { display: inline-flex; align-items: center; gap: 5px; padding: 5px 12px; border-radius: 8px; border: 1.5px solid #e5e7eb; background: #fff; font-size: .76rem; font-weight: 700; cursor: pointer; transition: all .15s; text-decoration: none; color: var(--slate-700); }
.btn-co:hover { background: #dc2626; border-color: #dc2626; color: #fff; }
.btn-detail { display: inline-flex; align-items: center; gap: 5px; padding: 5px 10px; border-radius: 8px; border: 1.5px solid var(--teal-100); background: var(--teal-50); font-size: .76rem; font-weight: 600; cursor: pointer; transition: all .15s; text-decoration: none; color: var(--teal-700); }
.btn-detail:hover { background: var(--teal-600); color: #fff; border-color: var(--teal-600); }

/* ─ MOBILE CARD ─ */
.ev-mobile-list { display: none; flex-direction: column; gap: 8px; padding: 10px; }
.ev-desktop-table { display: block; }

/* ─ EMPTY ─ */
.ev-empty { padding: 50px 20px; text-align: center; color: var(--slate-400); }
.ev-empty .ei { width: 60px; height: 60px; border-radius: 14px; background: var(--teal-50); color: var(--teal-400); display: flex; align-items: center; justify-content: center; font-size: 1.6rem; margin: 0 auto 12px; }

/* ─ LIVE DOT ─ */
@keyframes pulse { 0%,100%{opacity:1} 50%{opacity:.4} }
.live-dot { width: 8px; height: 8px; border-radius: 50%; background: #10b981; display: inline-block; margin-right: 4px; animation: pulse 1.6s infinite; }

/* ─ ANIM ─ */
@keyframes fadeUp { from{opacity:0;transform:translateY(10px)} to{opacity:1;transform:none} }
.ev-stat-grid { animation: fadeUp .3s ease both; }
.ev-filter    { animation: fadeUp .35s .05s ease both; }
.ev-section   { animation: fadeUp .4s .1s ease both; }

/* ─ RESPONSIVE ─ */
@media (max-width: 991px) { .ev-stat-grid { grid-template-columns: repeat(2,1fr); } }
@media (max-width: 767px) {
  .ev-header { flex-direction: column; }
  .ev-stat-grid { grid-template-columns: repeat(2,1fr); gap: 10px; }
  .ev-desktop-table { display: none !important; }
  .ev-mobile-list { display: flex !important; }
  .btn-reg { width: 100%; justify-content: center; }
}
</style>

<div class="ev-wrap">

<!-- Modal Konfirmasi Checkout -->
<div class="modal fade" id="modalCheckout" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" style="max-width:380px;">
    <div class="modal-content" style="border-radius:16px;border:none;overflow:hidden;font-family:'DM Sans',sans-serif;">
      <div class="modal-header" style="background:linear-gradient(135deg,#0b7a6e,#0d9488);border:none;padding:18px 20px;">
        <div class="d-flex align-items-center gap-2">
          <div style="width:36px;height:36px;background:rgba(255,255,255,.2);border-radius:10px;display:flex;align-items:center;justify-content:center;">
            <i class="bi bi-box-arrow-right" style="color:#fff;font-size:1rem;"></i>
          </div>
          <h6 class="modal-title mb-0" style="color:#fff;font-weight:700;font-size:.95rem;">Konfirmasi Checkout</h6>
        </div>
        <button type="button" class="btn-close btn-close-white btn-sm" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body" style="padding:20px;">
        <p style="font-size:.85rem;color:#334155;margin-bottom:6px;">Proses checkout untuk:</p>
        <div style="background:#f0fdfa;border:1.5px solid #ccfbf1;border-radius:10px;padding:10px 14px;display:flex;align-items:center;gap:10px;">
          <div id="modalTamuAvatar" style="width:36px;height:36px;border-radius:9px;background:var(--teal-600);color:#fff;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:1rem;flex-shrink:0;">A</div>
          <div>
            <div id="modalTamuNama" style="font-weight:700;font-size:.9rem;color:#0b5a52;"></div>
            <div id="modalTamuBlok" style="font-size:.73rem;color:#0d9488;"></div>
          </div>
        </div>
        <p style="font-size:.78rem;color:#94a3b8;margin-top:10px;margin-bottom:0;">
          <i class="bi bi-clock me-1"></i>Waktu checkout akan dicatat otomatis sekarang.
        </p>
      </div>
      <div class="modal-footer" style="border:none;padding:0 20px 18px;gap:8px;">
        <button type="button" class="btn" data-bs-dismiss="modal"
          style="border-radius:8px;border:1.5px solid #e5e7eb;font-size:.82rem;font-weight:600;color:#64748b;padding:7px 18px;flex:1;">
          <i class="bi bi-x-lg me-1"></i>Batal
        </button>
        <button type="button" id="btnConfirmCheckout"
          style="border-radius:8px;border:none;font-size:.82rem;font-weight:700;color:#fff;padding:7px 18px;flex:1;background:linear-gradient(135deg,#0b7a6e,#0d9488);box-shadow:0 4px 12px rgba(13,148,136,.28);cursor:pointer;">
          <i class="bi bi-box-arrow-right me-1"></i>Ya, Checkout
        </button>
      </div>
    </div>
  </div>
</div>

<!-- Modal Konfirmasi Hapus Tamu -->
<div class="modal fade" id="modalHapusTamu" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" style="max-width:380px;">
    <div class="modal-content" style="border-radius:16px;border:none;overflow:hidden;font-family:'DM Sans',sans-serif;">
      <div class="modal-header" style="background:#fef2f2;border-bottom:1.5px solid #fecaca;padding:18px 20px;">
        <div class="d-flex align-items-center gap-2">
          <div style="width:36px;height:36px;background:#fee2e2;border-radius:10px;display:flex;align-items:center;justify-content:center;">
            <i class="bi bi-trash-fill" style="color:#dc2626;font-size:1rem;"></i>
          </div>
          <h6 class="modal-title mb-0" style="color:#991b1b;font-weight:700;font-size:.95rem;">Hapus Data Tamu</h6>
        </div>
        <button type="button" class="btn-close btn-sm" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body" style="padding:20px;">
        <p style="font-size:.85rem;color:#334155;margin-bottom:10px;">Anda akan menghapus data kunjungan:</p>
        <div style="background:#fef2f2;border:1.5px solid #fecaca;border-radius:10px;padding:11px 14px;display:flex;align-items:center;gap:10px;">
          <div id="hapusTamuAvatar" style="width:34px;height:34px;border-radius:9px;background:var(--teal-600);color:#fff;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:1rem;flex-shrink:0;">?</div>
          <div style="font-weight:700;font-size:.88rem;color:#991b1b;" id="hapusTamuNama">-</div>
        </div>
        <div style="background:#fffbeb;border:1.5px solid #fde68a;border-radius:8px;padding:9px 14px;margin-top:12px;font-size:.78rem;color:#92400e;">
          <i class="bi bi-exclamation-triangle-fill me-1"></i>
          Data akan <strong>terhapus permanen</strong> dan tidak dapat dikembalikan.
        </div>
      </div>
      <div class="modal-footer" style="border:none;padding:0 20px 18px;gap:8px;">
        <button type="button" class="btn" data-bs-dismiss="modal"
          style="border-radius:8px;border:1.5px solid #e5e7eb;font-size:.82rem;font-weight:600;color:#64748b;padding:7px 18px;flex:1;">
          <i class="bi bi-x-lg me-1"></i>Batal
        </button>
        <a href="#" id="btnKonfirmasiHapusTamu"
          style="border-radius:8px;border:none;font-size:.82rem;font-weight:700;color:#fff;padding:7px 18px;flex:1;background:linear-gradient(135deg,#dc2626,#ef4444);box-shadow:0 4px 12px rgba(220,38,38,.28);cursor:pointer;display:inline-flex;align-items:center;justify-content:center;gap:6px;text-decoration:none;">
          <i class="bi bi-trash-fill"></i>Ya, Hapus
        </a>
      </div>
    </div>
  </div>
</div>

<!-- Toast Notifikasi -->
<div class="toast-container position-fixed bottom-0 end-0 p-3" style="z-index:9999;">
  <div id="toastCheckout" class="toast align-items-center border-0" role="alert" aria-live="assertive" aria-atomic="true"
       style="border-radius:12px;font-family:'DM Sans',sans-serif;min-width:280px;">
    <div class="d-flex">
      <div class="toast-body d-flex align-items-center gap-2" id="toastBody" style="font-size:.83rem;font-weight:600;padding:12px 14px;">
        <i id="toastIcon" class="bi"></i>
        <span id="toastMsg"></span>
      </div>
      <button type="button" class="btn-close me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
    </div>
  </div>
</div>

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

<!-- PAGE HEADER -->
<div class="ev-header">
  <div class="ev-header-left">
    <h4>
      <span class="hi"><i class="bi bi-person-badge-fill"></i></span>
      E-Visitor
    </h4>
    <div class="ev-breadcrumb">
      <a href="<?php echo base_url('dashboard'); ?>">Dashboard</a>
      <span> / </span>
      <span>Monitor Tamu</span>
    </div>
  </div>
  <?php if($this->session->userdata('role') !== 'warga'): ?>
  <a href="<?php echo base_url('tamu/registrasi'); ?>" class="btn-reg">
    <i class="bi bi-person-plus-fill"></i> Registrasi Tamu
  </a>
  <?php endif; ?>
</div>

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

<!-- STAT CARDS -->
<div class="ev-stat-grid">
  <div class="ev-stat-card sc-teal">
    <div class="sc-label"><i class="bi bi-calendar-check me-1"></i>Tamu Hari Ini</div>
    <div class="sc-value"><?php echo $statistik['total_hari_ini']; ?></div>
    <div class="sc-sub">kunjungan tercatat</div>
    <div class="sc-icon"><i class="bi bi-calendar-day-fill"></i></div>
  </div>
  <div class="ev-stat-card sc-green">
    <div class="sc-label"><span class="live-dot"></span>Sedang di Dalam</div>
    <div class="sc-value"><?php echo $statistik['sedang_dalam']; ?></div>
    <div class="sc-sub">belum checkout</div>
    <div class="sc-icon"><i class="bi bi-door-open-fill"></i></div>
  </div>
  <div class="ev-stat-card sc-amber">
    <div class="sc-label"><i class="bi bi-moon-stars me-1"></i>Tamu Menginap</div>
    <div class="sc-value"><?php echo $statistik['menginap_aktif']; ?></div>
    <div class="sc-sub">sedang menginap</div>
    <div class="sc-icon"><i class="bi bi-house-heart-fill"></i></div>
  </div>
  <div class="ev-stat-card sc-blue">
    <div class="sc-label"><i class="bi bi-archive me-1"></i>Total Semua</div>
    <div class="sc-value"><?php echo $statistik['total_semua']; ?></div>
    <div class="sc-sub">riwayat lengkap</div>
    <div class="sc-icon"><i class="bi bi-journal-bookmark-fill"></i></div>
  </div>
</div>

<!-- FILTER BAR -->
<div class="ev-filter">
  <span class="fb-label"><i class="bi bi-funnel-fill"></i> Filter:</span>
  <div class="ev-search-box">
    <i class="bi bi-search"></i>
    <input type="text" id="evSearch" placeholder="Cari nama, blok, plat nomor..."
           value="<?php echo htmlspecialchars($filter['keyword'] ?? ''); ?>">
  </div>
  <select id="evStatus" class="form-select form-select-sm" style="width:auto;">
    <option value="">Semua Status</option>
    <option value="checkin"  <?php if(($filter['status']??'')==='checkin')  echo 'selected'; ?>>Masih Check-in</option>
    <option value="checkout" <?php if(($filter['status']??'')==='checkout') echo 'selected'; ?>>Sudah Checkout</option>
  </select>
  <select id="evTipe" class="form-select form-select-sm" style="width:auto;">
    <option value="">Semua Tipe</option>
    <option value="singkat"  <?php if(($filter['tipe']??'')==='singkat')  echo 'selected'; ?>>Kunjungan Singkat</option>
    <option value="menginap" <?php if(($filter['tipe']??'')==='menginap') echo 'selected'; ?>>Menginap</option>
  </select>
  <input type="date" id="evTanggal" value="<?php echo $filter['tanggal'] ?? ''; ?>"
         style="width:auto;" title="Filter tanggal">
  <a href="<?php echo base_url('tamu'); ?>" style="font-size:.76rem; color:var(--slate-500); text-decoration:none; white-space:nowrap;">
    <i class="bi bi-x-circle"></i> Reset
  </a>
  <div class="ms-auto">
    <span id="filterCount" class="filter-count-pill" style="display:none;"></span>
  </div>
</div>

<!-- TABLE SECTION -->
<div class="ev-section">
  <div class="ev-section-header">
    <div class="title"><i class="bi bi-clipboard2-check"></i>Daftar Kunjungan</div>
    <span class="record-pill"><?php echo count($tamu); ?> data</span>
  </div>

  <?php if(!empty($tamu)): ?>

  <!-- Desktop Table -->
  <div class="ev-desktop-table table-responsive">
    <table class="ev-table" id="evTable">
      <thead>
        <tr>
          <th style="width:44px;">No</th>
          <th>Jam / Tgl</th>
          <th>Durasi</th>
          <th>Identitas Tamu</th>
          <th>Tujuan</th>
          <th>Keperluan</th>
          <th>Kendaraan</th>
          <th>Status</th>
          <th>Manajemen Check</th>
        </tr>
      </thead>
      <tbody>
      <?php $no=1; foreach($tamu as $t):
        $keperluan_map = [
          'kunjungan'    => ['label'=>'Kunjungan',  'cls'=>'kp-kunjungan','icon'=>'bi-house-door'],
          'antar_paket'  => ['label'=>'Antar Paket','cls'=>'kp-paket',    'icon'=>'bi-box-seam'],
          'tamu_menginap'=> ['label'=>'Menginap',   'cls'=>'kp-menginap', 'icon'=>'bi-moon-stars'],
          'kerja'        => ['label'=>'Kerja',       'cls'=>'kp-kerja',    'icon'=>'bi-tools'],
          'lainnya'      => ['label'=>'Lainnya',     'cls'=>'kp-lainnya',  'icon'=>'bi-three-dots'],
        ];
        $kp           = $keperluan_map[$t->keperluan] ?? ['label'=>ucfirst($t->keperluan),'cls'=>'kp-lainnya','icon'=>'bi-three-dots'];
        $initial      = strtoupper(substr($t->nama_tamu, 0, 1));
        $checkin_date = date('Y-m-d', strtotime($t->checkin_at));
        $is_today     = ($checkin_date === date('Y-m-d'));
        $dur_done     = !empty($t->checkout_at);
      ?>
      <tr data-status="<?php echo $t->status; ?>"
          data-tipe="<?php echo $t->tipe_kunjungan; ?>"
          data-checkin="<?php echo $t->checkin_at; ?>"
          data-checkout="<?php echo $t->checkout_at ?: ''; ?>">

        <td style="color:var(--slate-400);font-weight:600;font-size:.78rem;"><?php echo $no++; ?></td>

        <td>
          <div class="time-block">
            <!-- Jam checkin — dirender JS pakai timezone browser -->
            <div class="time-in" data-dt="<?php echo $t->checkin_at; ?>">
              <i class="bi bi-box-arrow-in-right"></i>
              <span class="jam-ci">--:--</span>
            </div>
            <?php if($t->checkout_at): ?>
            <!-- Jam checkout — dirender JS pakai timezone browser -->
            <div class="time-out" data-dt="<?php echo $t->checkout_at; ?>">
              <i class="bi bi-box-arrow-right"></i>
              <span class="jam-co">--:--</span>
            </div>
            <?php elseif($t->tipe_kunjungan === 'menginap' && !empty($t->rencana_checkout)): ?>
            <div style="font-size:.7rem;color:#7c3aed;">
              <i class="bi bi-calendar-event"></i> s/d <?php echo date('d/m', strtotime($t->rencana_checkout)); ?>
            </div>
            <?php endif; ?>
            <div class="time-date"><?php echo $is_today ? 'Hari ini' : date('d/m/Y', strtotime($t->checkin_at)); ?></div>
          </div>
        </td>

        <td>
          <div class="dur-badge dur-short<?php echo $dur_done ? ' dur-done' : ' dur-live'; ?>"
               data-checkin="<?php echo $t->checkin_at; ?>"
               data-checkout="<?php echo $t->checkout_at ?: ''; ?>">
            <?php if(!$dur_done): ?>
            <span class="live-dot" style="width:5px;height:5px;margin-right:3px;flex-shrink:0;"></span>
            <?php endif; ?>
            <span class="dur-text">...</span>
          </div>
          <?php if($t->tipe_kunjungan === 'menginap'): ?>
          <div style="font-size:.68rem;color:#7c3aed;margin-top:3px;"><i class="bi bi-moon-stars me-1"></i>Menginap</div>
          <?php endif; ?>
        </td>

        <td>
          <div class="guest-cell">
            <div class="guest-avatar"><?php echo $initial; ?></div>
            <div>
              <div class="guest-name"><?php echo htmlspecialchars($t->nama_tamu); ?></div>
              <?php if(!empty($t->no_hp)): ?>
              <div class="guest-sub"><i class="bi bi-whatsapp me-1" style="color:#25d366;"></i><?php echo htmlspecialchars($t->no_hp); ?></div>
              <?php elseif(!empty($t->nik_tamu)): ?>
              <div class="guest-sub" style="font-family:monospace;"><?php echo htmlspecialchars($t->nik_tamu); ?></div>
              <?php endif; ?>
            </div>
          </div>
        </td>

        <td>
          <?php if(!empty($t->tujuan_blok)): ?>
          <div style="font-weight:700;color:var(--teal-700);font-size:.84rem;">
            <i class="bi bi-geo-alt-fill me-1"></i><?php echo htmlspecialchars($t->tujuan_blok); ?>
          </div>
          <?php endif; ?>
          <?php if(!empty($t->nama_tuan_rumah)): ?>
          <div style="font-size:.72rem;color:var(--slate-400);"><?php echo htmlspecialchars($t->nama_tuan_rumah); ?></div>
          <?php endif; ?>
          <?php if(!empty($t->no_hp) && !empty($t->tujuan_blok)): ?>
          <div style="font-size:.7rem;color:var(--slate-400);">WA: <?php echo htmlspecialchars($t->no_hp); ?></div>
          <?php endif; ?>
        </td>

        <td>
          <span class="keperluan-pill <?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:.7rem;color:var(--slate-400);margin-top:3px;">
            <?php echo htmlspecialchars(substr($t->keperluan_detail,0,30)); ?>
            <?php if(strlen($t->keperluan_detail)>30) echo '...'; ?>
          </div>
          <?php endif; ?>
        </td>

        <td>
          <?php if(!empty($t->no_kendaraan)): ?>
          <div style="font-family:monospace;font-weight:700;font-size:.82rem;background:#f8fafc;padding:2px 7px;border-radius:5px;border:1px solid #e5e7eb;display:inline-block;">
            <?php echo htmlspecialchars(strtoupper($t->no_kendaraan)); ?>
          </div>
          <?php if(!empty($t->jenis_kendaraan)): ?>
          <div style="font-size:.7rem;color:var(--slate-400);margin-top:2px;"><?php echo htmlspecialchars($t->jenis_kendaraan); ?></div>
          <?php endif; ?>
          <?php else: ?>
          <span style="color:var(--slate-300);font-size:.8rem;">—</span>
          <?php endif; ?>
        </td>

        <td>
          <?php if($t->status === 'checkin'): ?>
          <span class="badge-status bs-checkin"><span class="live-dot" style="width:6px;height:6px;margin-right:2px;"></span>Check-in</span>
          <?php if($t->tipe_kunjungan === 'menginap'): ?>
          <br><span class="badge-status bs-menginap mt-1"><i class="bi bi-moon-stars me-1"></i>Menginap</span>
          <?php endif; ?>
          <?php else: ?>
          <span class="badge-status bs-checkout"><i class="bi bi-check2 me-1"></i>Checkout</span>
          <?php endif; ?>
        </td>

        <td>
          <div class="d-flex gap-1 align-items-center">
            <?php if($t->status === 'checkin' && $this->session->userdata('role') !== 'warga'): ?>
            <button class="btn-co btn-checkout-ajax" data-id="<?php echo $t->id; ?>" title="Proses Checkout">
              <i class="bi bi-box-arrow-right"></i> Checkout
            </button>
            <?php endif; ?>
            <a href="<?php echo base_url('tamu/detail/'.$t->id); ?>" class="btn-detail">
              <i class="bi bi-eye"></i>
            </a>
            <?php if($this->session->userdata('role') !== 'warga'): ?>
            <a href="<?php echo base_url('tamu/edit/'.$t->id); ?>" class="btn-detail"
               style="border-color:#fde68a;background:#fffbeb;color:#92400e;" title="Edit">
              <i class="bi bi-pencil-fill"></i>
            </a>
            <?php endif; ?>
            <?php if($this->session->userdata('role') === 'admin'): ?>
            <button class="btn-detail" title="Hapus"
               style="border-color:#fecaca;background:#fff5f5;color:#dc2626;"
               onclick="konfirmasiHapusTamu('<?php echo base_url('tamu/hapus/'.$t->id); ?>','<?php echo addslashes($t->nama_tamu); ?>')">
              <i class="bi bi-trash"></i>
            </button>
            <?php endif; ?>
          </div>
        </td>

      </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>

  <!-- Mobile List -->
  <div class="ev-mobile-list" id="evMobileList">
    <?php foreach($tamu as $t):
      $initial = strtoupper(substr($t->nama_tamu,0,1));
      $bc = $t->status === 'checkin' ? '#0d9488' : '#94a3b8';
    ?>
    <div style="border-radius:11px;border:1.5px solid #f1f3f5;border-left:4px solid <?php echo $bc; ?>;background:#fff;padding:11px 14px;"
         data-status="<?php echo $t->status; ?>" data-tipe="<?php echo $t->tipe_kunjungan; ?>">
      <div class="d-flex justify-content-between align-items-start mb-2">
        <div class="d-flex align-items-center gap-2">
          <div class="guest-avatar"><?php echo $initial; ?></div>
          <div>
            <div class="guest-name"><?php echo htmlspecialchars($t->nama_tamu); ?></div>
            <?php if(!empty($t->tujuan_blok)): ?>
            <div style="font-size:.73rem;color:var(--teal-600);font-weight:600;"><i class="bi bi-geo-alt-fill me-1"></i><?php echo htmlspecialchars($t->tujuan_blok); ?></div>
            <?php endif; ?>
          </div>
        </div>
        <?php if($t->status==='checkin'): ?>
        <span class="badge-status bs-checkin"><span class="live-dot" style="width:6px;height:6px;margin-right:2px;"></span>Dalam</span>
        <?php else: ?>
        <span class="badge-status bs-checkout">Selesai</span>
        <?php endif; ?>
      </div>
      <div class="d-flex flex-wrap gap-2" style="font-size:.73rem;color:var(--slate-500);">
        <!-- Jam checkin mobile — dirender JS -->
        <span><i class="bi bi-box-arrow-in-right me-1" style="color:#059669;"></i><span class="jam-ci-mob" data-dt="<?php echo $t->checkin_at; ?>">--:--</span></span>
        <?php if($t->checkout_at): ?>
        <span>· <i class="bi bi-box-arrow-right me-1" style="color:#dc2626;"></i><span class="jam-co-mob" data-dt="<?php echo $t->checkout_at; ?>">--:--</span></span>
        <?php endif; ?>
        <?php if(!empty($t->no_kendaraan)): ?>
        <span>· <i class="bi bi-car-front me-1"></i><?php echo strtoupper($t->no_kendaraan); ?></span>
        <?php endif; ?>
        <?php if(!empty($t->no_hp)): ?>
        <span>· <i class="bi bi-whatsapp me-1" style="color:#25d366;"></i><?php echo $t->no_hp; ?></span>
        <?php endif; ?>
      </div>
      <?php if($t->status === 'checkin'): ?>
      <div class="mt-2">
        <button class="btn-co btn-checkout-ajax" data-id="<?php echo $t->id; ?>" style="font-size:.73rem;padding:4px 10px;">
          <i class="bi bi-box-arrow-right"></i> Checkout
        </button>
      </div>
      <?php endif; ?>
    </div>
    <?php endforeach; ?>
  </div>

  <?php else: ?>
  <div class="ev-empty">
    <div class="ei"><i class="bi bi-person-badge"></i></div>
    <div style="font-weight:700;font-size:.9rem;color:var(--slate-600);margin-bottom:4px;">Belum ada data tamu</div>
    <small>Klik "Registrasi Tamu" untuk mencatat tamu baru</small>
  </div>
  <?php endif; ?>
</div>

</div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function(){

  // ── Helper: parse datetime string → Date (browser timezone) ──
  function parseDT(str) {
    if(!str) return null;
    return new Date(str.replace(' ', 'T'));
  }

  // ── Helper: format jam H:i pakai locale browser ──
  function fmtJam(str) {
    var dt = parseDT(str);
    if(!dt) return '--:--';
    return dt.toLocaleTimeString('id-ID', { 
        hour: '2-digit', minute: '2-digit', hour12: false 
    });
}

  // ── Render semua jam checkin & checkout di tabel (desktop) ──
  document.querySelectorAll('.time-in[data-dt]').forEach(function(el) {
    var span = el.querySelector('.jam-ci');
    if(span) span.textContent = fmtJam(el.dataset.dt);
  });
  document.querySelectorAll('.time-out[data-dt]').forEach(function(el) {
    var span = el.querySelector('.jam-co');
    if(span) span.textContent = fmtJam(el.dataset.dt);
  });

  // ── Render semua jam di mobile list ──
  document.querySelectorAll('.jam-ci-mob[data-dt]').forEach(function(el) {
    el.textContent = fmtJam(el.dataset.dt);
  });
  document.querySelectorAll('.jam-co-mob[data-dt]').forEach(function(el) {
    el.textContent = fmtJam(el.dataset.dt);
  });

  // ─ Client-side filter ─
  var search  = document.getElementById('evSearch');
  var status  = document.getElementById('evStatus');
  var tipe    = document.getElementById('evTipe');
  var tanggal = document.getElementById('evTanggal');
  var counter = document.getElementById('filterCount');

  function applyFilter(){
    var kw  = (search  ? search.value.toLowerCase()  : '');
    var st  = (status  ? status.value                : '');
    var tp  = (tipe    ? tipe.value                  : '');
    var cnt = 0;
    document.querySelectorAll('#evTable tbody tr').forEach(function(r){
      var text = r.textContent.toLowerCase();
      var match = true;
      if(kw && !text.includes(kw)) match=false;
      if(st && r.dataset.status !== st) match=false;
      if(tp && r.dataset.tipe   !== tp) match=false;
      r.style.display = match ? '' : 'none';
      if(match) cnt++;
    });
    document.querySelectorAll('.ev-mobile-list > div[data-status]').forEach(function(c){
      var text = c.textContent.toLowerCase();
      var match = true;
      if(kw && !text.includes(kw)) match=false;
      if(st && c.dataset.status !== st) match=false;
      if(tp && c.dataset.tipe   !== tp) match=false;
      c.style.display = match ? '' : 'none';
    });
    if(counter){
      if(kw||st||tp){ counter.textContent = cnt + ' data ditampilkan'; counter.style.display='inline-flex'; }
      else { counter.style.display='none'; }
    }
  }

  if(search)  search.addEventListener('input',  applyFilter);
  if(status)  status.addEventListener('change', applyFilter);
  if(tipe)    tipe.addEventListener('change',   applyFilter);
  if(tanggal) tanggal.addEventListener('change', function(){
    var url = new URL(window.location.href);
    if(this.value) url.searchParams.set('tanggal', this.value);
    else url.searchParams.delete('tanggal');
    window.location.href = url.toString();
  });

  // ─ Checkout AJAX (Bootstrap Modal) ─
  var _checkoutId  = null;
  var _checkoutBtn = null;
  var modalEl  = document.getElementById('modalCheckout');
  var toastEl  = document.getElementById('toastCheckout');
  var bsModal  = modalEl ? new bootstrap.Modal(modalEl) : null;
  var bsToast  = toastEl ? new bootstrap.Toast(toastEl, { delay: 3000 }) : null;

  function showToast(msg, type){
    if(!toastEl || !bsToast) return;
    var icon  = document.getElementById('toastIcon');
    var msgEl = document.getElementById('toastMsg');
    if(type === 'success'){
      toastEl.style.background = '#0d9488'; toastEl.style.color = '#fff';
      if(icon) icon.className = 'bi bi-check-circle-fill';
    } else {
      toastEl.style.background = '#dc2626'; toastEl.style.color = '#fff';
      if(icon) icon.className = 'bi bi-exclamation-circle-fill';
    }
    var closeBtn = toastEl.querySelector('.btn-close');
    if(closeBtn) closeBtn.style.filter = 'invert(1)';
    if(msgEl) msgEl.textContent = msg;
    bsToast.show();
  }

  document.addEventListener('click', function(e){
    var btn = e.target.closest('.btn-checkout-ajax');
    if(!btn) return;
    _checkoutId  = btn.dataset.id;
    _checkoutBtn = btn;
    var row    = btn.closest('tr') || btn.closest('[data-status]');
    var namaEl = row ? row.querySelector('.guest-name') : null;
    var blokEl = row ? row.querySelector('[style*="geo-alt"]') : null;
    if(!blokEl && row) blokEl = row.querySelector('.guest-sub');
    var nama    = namaEl ? namaEl.textContent.trim() : '—';
    var blok    = blokEl ? blokEl.textContent.trim() : '';
    var elNama   = document.getElementById('modalTamuNama');
    var elBlok   = document.getElementById('modalTamuBlok');
    var elAvatar = document.getElementById('modalTamuAvatar');
    if(elNama)   elNama.textContent   = nama;
    if(elBlok)   elBlok.textContent   = blok;
    if(elAvatar) elAvatar.textContent = nama.charAt(0).toUpperCase();
    if(bsModal) bsModal.show();
  });

  var confirmBtn = document.getElementById('btnConfirmCheckout');
  if(confirmBtn){
    confirmBtn.addEventListener('click', function(){
      if(!_checkoutId) return;
      var self = this;
      self.disabled = true;
      self.innerHTML = '<i class="bi bi-hourglass-split me-1"></i>Proses...';

      var fd = new FormData();
      fd.append('id', _checkoutId);
      fetch('<?php echo base_url("tamu/checkout_ajax"); ?>', {
        method: 'POST', body: fd,
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
      })
      .then(function(r){ return r.json(); })
      .then(function(res){
        if(bsModal) bsModal.hide();
        self.disabled = false;
        self.innerHTML = '<i class="bi bi-box-arrow-right me-1"></i>Ya, Checkout';

        if(res.status === 'ok'){
          // Jam dari browser timezone
          var jamCo = fmtJam(res.checkout_at);
          showToast('Checkout berhasil pukul ' + jamCo, 'success');

          var row = _checkoutBtn ? (_checkoutBtn.closest('tr') || _checkoutBtn.closest('[data-status]')) : null;
          if(row){
            row.dataset.status = 'checkout';
            var badge = row.querySelector('.bs-checkin');
            if(badge){ badge.className='badge-status bs-checkout'; badge.innerHTML='<i class="bi bi-check2 me-1"></i>Checkout'; }
            var ldot = row.querySelector('.badge-status .live-dot');
            if(ldot) ldot.remove();

            // Tambah baris jam checkout di desktop
            var timeIn = row.querySelector('.time-in');
            if(timeIn){
              var tout = document.createElement('div');
              tout.className = 'time-out';
              tout.setAttribute('data-dt', res.checkout_at);
              tout.innerHTML = '<i class="bi bi-box-arrow-right"></i><span class="jam-co">' + jamCo + '</span>';
              timeIn.parentNode.insertBefore(tout, timeIn.nextSibling);
            }

            // ubah dur-badge dari live ke done
            var durBadge = row.querySelector('.dur-badge');
            if(durBadge){
              durBadge.classList.remove('dur-live');
              durBadge.classList.add('dur-done');
              durBadge.dataset.checkout = res.checkout_at;
              var dot = durBadge.querySelector('.live-dot');
              if(dot) dot.remove();
            }

            if(_checkoutBtn){
              var btnWrap = _checkoutBtn.closest('.d-flex') || _checkoutBtn.closest('.mt-2');
              try { if(btnWrap) btnWrap.removeChild(_checkoutBtn); else _checkoutBtn.remove(); } catch(ex){}
            }
          }
          _checkoutId = null; _checkoutBtn = null;
        } else {
          showToast(res.msg || 'Gagal checkout, coba lagi.', 'error');
        }
      })
      .catch(function(){
        if(bsModal) bsModal.hide();
        self.disabled = false;
        self.innerHTML = '<i class="bi bi-box-arrow-right me-1"></i>Ya, Checkout';
        showToast('Koneksi bermasalah, coba lagi.', 'error');
      });
    });
  }

  // ─ Hapus Tamu Modal ─
  var _bsModalHapusTamu = null;
  window.konfirmasiHapusTamu = function(url, nama) {
    var elNama   = document.getElementById('hapusTamuNama');
    var elAvatar = document.getElementById('hapusTamuAvatar');
    var elBtn    = document.getElementById('btnKonfirmasiHapusTamu');
    if(elNama)   elNama.textContent   = nama || '-';
    if(elAvatar) elAvatar.textContent = nama ? nama.charAt(0).toUpperCase() : '?';
    if(elBtn)    elBtn.href           = url;
    var modalEl = document.getElementById('modalHapusTamu');
    if(!modalEl) return;
    if(!_bsModalHapusTamu) _bsModalHapusTamu = new bootstrap.Modal(modalEl);
    _bsModalHapusTamu.show();
  };

  // ── Durasi ──
  function formatDurasi(diffSec){
    if(diffSec < 60) return 'Baru masuk';
    var m = Math.floor(diffSec / 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 getDurClass(diffSec){
    var h = diffSec / 3600;
    if(h < 1) return 'dur-badge dur-short';
    if(h < 4) return 'dur-badge dur-medium';
    return 'dur-badge dur-long';
  }

  function tickDurasi(){
    var now = new Date();
    document.querySelectorAll('.dur-badge.dur-live').forEach(function(el){
      var ci = parseDT(el.dataset.checkin);
      if(!ci) return;
      var diff = Math.max(0, Math.floor((now - ci) / 1000));
      var txt = el.querySelector('.dur-text');
      if(txt) txt.textContent = formatDurasi(diff);
      var base = getDurClass(diff);
      el.className = base + ' dur-live';
      if(!el.querySelector('.live-dot')){
        var dot = document.createElement('span');
        dot.className = 'live-dot';
        dot.style.cssText = 'width:5px;height:5px;margin-right:3px;flex-shrink:0;display:inline-block;';
        el.insertBefore(dot, el.firstChild);
      }
    });
    document.querySelectorAll('.dur-badge.dur-done').forEach(function(el){
      if(el.dataset.rendered) return;
      var ci = parseDT(el.dataset.checkin);
      var co = parseDT(el.dataset.checkout);
      if(!ci || !co) return;
      var diff = Math.max(0, Math.floor((co - ci) / 1000));
      var txt = el.querySelector('.dur-text');
      if(txt) txt.textContent = formatDurasi(diff);
      el.className = getDurClass(diff) + ' dur-done';
      el.dataset.rendered = '1';
    });
  }

  tickDurasi();
  setInterval(tickDurasi, 60000);

}); // end DOMContentLoaded
</script>