<?= $this->extend('layout/main') ?>

<?= $this->section('content') ?>
<div class="app-content-header">
    <div class="container-fluid">
        <div class="row">
            <div class="col-sm-6"><h3 class="mb-0">Realtime</h3></div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-end">
                    <li class="breadcrumb-item"><a href="#">Home</a></li>
                    <li class="breadcrumb-item active" aria-current="page">Realtime</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<style>
  .device-card {
    border: 0;
    border-radius: 1rem;
    box-shadow: 0 6px 20px rgba(0,0,0,.08);
    transition: transform .15s ease, box-shadow .15s ease;
    height: 100%;
  }
  .device-card:hover { transform: translateY(-2px); box-shadow: 0 10px 26px rgba(0,0,0,.12); }
  .metric {
    font-size: 1.15rem;
    line-height: 1.2;
  }
  .metric .value { font-weight: 700; }
  .device-header {
    display: flex; justify-content: space-between; align-items: center;
  }
  .status-row .badge { min-width: 110px; }
  /* Untuk layar publik besar, perbesar sedikit typografi */
  @media (min-width: 1400px) {
    #greeting { font-size: 1.75rem; }
    .metric { font-size: 1.25rem; }
  }
</style>

<div class="app-content">
    <div class="container-fluid">
        <div class="row align-items-center mb-4">
            <div class="col-auto">
                <div id="greeting" class="h4 mb-0 fw-semibold"></div>
                <div class="text-muted small">Smart Modular IoT for Environmental Monitoring</div>
            </div>
            <div class="col text-end">
                <span class="badge bg-light text-dark">
                Terakhir sinkron: <span id="last-sync">—</span>
                </span>
            </div>
        </div>
        <div class="row mb-3">
            <div class="col-12">
                <div class="d-flex flex-wrap gap-2 align-items-center">
                    <span class="fw-semibold me-1">Legend:</span>
                    <span class="badge bg-success">Sehat / Normal</span>
                    <span class="badge bg-primary">Dingin / Lembab</span>
                    <span class="badge bg-warning text-dark">Sejuk / Kurang Sehat / Kering</span>
                    <span class="badge bg-danger">Panas / Tidak Sehat / Berbahaya</span>
                </div>
            </div>
        </div>

        <div class="row g-3" id="devices-row"></div>
    </div>
</div>
<?= $this->endSection() ?>

<?= $this->section('page_script') ?>
<script>

// --- Status Helpers (bisa disesuaikan) ---
function statusTemperature(t){
  if (t < 20) return {label:"Dingin", cls:"bg-primary"};
  if (t <= 28) return {label:"Sejuk", cls:"bg-warning text-dark"};
  return {label:"Panas", cls:"bg-danger"};
}
function statusHumidity(h){
  if (h < 40) return {label:"Kering", cls:"bg-warning text-dark"};
  if (h <= 70) return {label:"Normal", cls:"bg-success"};
  return {label:"Lembab", cls:"bg-primary"};
}
// CO2 thresholds per requirement: <=0.2 sehat, 0.2-0.5 kurang sehat, 0.5-1 tidak sehat, >1 berbahaya
function statusCO2(x){
  if (x <= 0.2) return {label:"Sehat", cls:"bg-success"};
  if (x <= 0.5) return {label:"Kurang Sehat", cls:"bg-warning text-dark"};
  if (x <= 1.0) return {label:"Tidak Sehat", cls:"bg-danger"};
  return {label:"Berbahaya", cls:"bg-danger"};
}

// --- Card Template ---
function deviceCard(d){
  const tStat = statusTemperature(d.temperature);
  const hStat = statusHumidity(d.humidity);
  const cStat = statusCO2(d.ppm_co2);

  return `
  <div class="col-12 col-md-6 col-xl-4">
    <div class="card device-card">
      <div class="card-body">
        <div class="device-header mb-2">
          <div>
            <div class="h6 mb-0">${d.name} (${d.model})</div>
            <div class="text-muted small">Serial: <span class="fw-semibold">${d.serial_id}</span></div>
          </div>
          <span class="badge bg-light text-dark">Last: ${formatTime(d.last_data_time)}</span>
        </div>

        <hr class="my-3">

        <div class="row g-3">
          <div class="col-6">
            <div class="metric">🌡️ Suhu<br><span class="value">${fmt(d.temperature,1)}°C</span></div>
          </div>
          <div class="col-6 text-end">
            <span class="badge ${tStat.cls}">${tStat.label}</span>
          </div>

          <div class="col-6">
            <div class="metric">💧 Kelembapan<br><span class="value">${fmt(d.humidity,0)}%</span></div>
          </div>
          <div class="col-6 text-end">
            <span class="badge ${hStat.cls}">${hStat.label}</span>
          </div>

          <div class="col-6">
            <div class="metric">🟢 CO₂ (PPM)<br><span class="value">${fmt(d.ppm_co2,2)}</span></div>
          </div>
          <div class="col-6 text-end">
            <span class="badge ${cStat.cls}">${cStat.label}</span>
          </div>
        </div>

      </div>
    </div>
  </div>`;
}

// --- Utils ---
function fmt(num, digits=1){
  return (typeof num === "number") ? num.toFixed(digits) : num;
}
function formatTime(iso){
  if (!iso) return "—";
  const dt = new Date(iso);
  if (isNaN(dt)) return iso;
  // tampilkan jam:menit:detik lokal + tanggal singkat
  return dt.toLocaleTimeString([], {hour:'2-digit', minute:'2-digit', second:'2-digit'}) +
         " • " +
         dt.toLocaleDateString();
}

// --- Data Fetching (mock + contoh replace ke API) ---
async function fetchDevices(){
  // Ganti dengan endpoint Anda:
  const res = await fetch('<?=base_url()?>realtime/log'); const data = await res.json();
  return data;

  // // Mock data untuk demo (acak nilai sedikit biar terasa real-time)
  // const now = new Date();
  // const base = [
  //   {serial_id:"A1-9F-22", model:"EnvNode S1", temperature:27.3, humidity:60, ppm_co2:0.18},
  //   {serial_id:"B7-3C-42", model:"EnvNode S1", temperature:29.1, humidity:55, ppm_co2:0.32},
  //   {serial_id:"CX-210",  model:"AirWatch M3", temperature:24.7, humidity:72, ppm_co2:0.51},
  //   {serial_id:"D5-77-AB",model:"AeroSense X", temperature:31.4, humidity:38, ppm_co2:1.12},
  //   {serial_id:"E0-14-Z", model:"AquaTherm Q", temperature:19.6, humidity:81, ppm_co2:0.12},
  //   {serial_id:"F9-88-K", model:"AirWatch M3", temperature:26.0, humidity:45, ppm_co2:0.41},
  // ];
  // // jitter untuk simulasi perubahan
  // const jitter = v => +(v + (Math.random()-.5)*0.4).toFixed(2);
  // return base.map(d => ({
  //   ...d,
  //   temperature: jitter(d.temperature),
  //   humidity: Math.max(10, Math.min(95, Math.round(d.humidity + (Math.random()-.5)*3))),
  //   ppm_co2: Math.max(0, +(d.ppm_co2 + (Math.random()-.5)*0.05).toFixed(2)),
  //   last_data_time: now.toISOString()
  // }));
}

async function renderDevices(){
  const devices = await fetchDevices();
  const html = devices.map(deviceCard).join("");
  $("#devices-row").html(html);
  $("#last-sync").text(new Date().toLocaleTimeString());
}

// --- Auto init & refresh ---
$(function(){
  renderDevices();
  // Refresh tiap 5 detik (atur sesuai kebutuhan)
  setInterval(renderDevices, 10000);
});
</script>
<?= $this->endSection() ?>
