<?php
// index.php — Dashboard HEM (MySQLi)
require_once __DIR__.'/config.php';

function safe($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
function safe_int($v){ return (int)$v; }
function safe_float($v){ return (float)$v; }

// ================== Query Data ==================
// Attendance: rekod terakhir + 7 rekod terakhir
$att_today = null;
$att_rows = [];
if ($res = $mysqli->query("SELECT * FROM attendance ORDER BY tarikh ASC")) {
  while($row = $res->fetch_assoc()) $att_rows[] = $row;
  $res->free();
  if ($att_rows) $att_today = end($att_rows);
}
$last7_att = array_slice($att_rows, max(0, count($att_rows)-7));

// Disiplin: bulan terkini + 6 bulan terakhir
$disc_rows = [];
if ($res = $mysqli->query("SELECT * FROM discipline ORDER BY bulan ASC")) {
  while($row = $res->fetch_assoc()) $disc_rows[] = $row;
  $res->free();
}
$disc_now = $disc_rows ? end($disc_rows) : null;
$last6_disc = array_slice($disc_rows, max(0, count($disc_rows)-6));

// Welfare: ambil satu rekod terkini (id terbesar / updated_at)
$wel = null;
if ($res = $mysqli->query("SELECT * FROM welfare ORDER BY updated_at DESC, id DESC LIMIT 1")) {
  $wel = $res->fetch_assoc();
  $res->free();
}

// Health: 7 rekod terakhir
$health_rows = [];
if ($res = $mysqli->query("SELECT * FROM health ORDER BY id ASC")) {
  while($row = $res->fetch_assoc()) $health_rows[] = $row;
  $res->free();
}
$last7_health = array_slice($health_rows, max(0, count($health_rows)-7));
$health_today = $health_rows ? end($health_rows) : null;

// Demography: kiraan agregat
$totalL=0; $totalP=0; $totalM=0;
if ($res = $mysqli->query("SELECT COALESCE(SUM(lelaki),0) L, COALESCE(SUM(perempuan),0) P, COALESCE(SUM(jumlah),0) M FROM demography")) {
  $agg = $res->fetch_assoc();
  $totalL = (int)$agg['L']; $totalP = (int)$agg['P']; $totalM = (int)$agg['M'];
  $res->free();
}
$nisbahLP = $totalP>0 ? round($totalL/$totalP, 2) : 0;

// Pengumuman: 5 terbaharu
$ann = [];
if ($res = $mysqli->query("SELECT * FROM announcements ORDER BY tarikh DESC, id DESC LIMIT 5")) {
  while($row = $res->fetch_assoc()) $ann[] = $row;
  $res->free();
}

// Ticker aktif
$tickers = [];
if ($res = $mysqli->query("SELECT teks FROM ticker WHERE is_active=1 ORDER BY id DESC")) {
  while($row = $res->fetch_assoc()) $tickers[] = $row['teks'];
  $res->free();
}
$ticker_join = implode('    •    ', $tickers);

// Sekolah (boleh set manual / jadual khas jika perlu)
$NAMA_SEKOLAH = 'SMK MUHIBBAH SANDAKAN';
$LOGO = 'logo.png';
?>
<!DOCTYPE html>
<html lang="ms">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>Dashboard HEM</title>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<style>
  :root{
    --pad: clamp(10px, 1.6vw, 28px);
    --radius: 18px;
    --card-bg: rgba(0,0,0,0.35);
    --accent: #1976d2;
    --text-shadow: 1px 1px 4px rgba(0,0,0,0.5);
    --footer-h: 44px;
  }
  html, body { height:100%; background:#0b1d33; color:#fff; }
  body { margin:0; font-family: Segoe UI, system-ui, -apple-system, Roboto, Arial, sans-serif; }

  .header { display:flex; align-items:center; justify-content:space-between; padding:var(--pad); gap:var(--pad);
    background: linear-gradient(90deg, rgba(25,118,210,0.25), rgba(0,0,0,0)); border-bottom:1px solid rgba(255,255,255,0.08);}
  .brand { display:flex; align-items:center; gap:12px; }
  .brand img{ width:64px; height:64px; object-fit:contain; }
  .brand .name{ font-size:clamp(18px,2.2vw,32px); font-weight:700; text-shadow:var(--text-shadow); }
  .brand .subtitle{ font-size:clamp(12px,1.2vw,16px); opacity:.9; }
  .clock{ text-align:right; min-width:240px; }
  .clock .date{ font-size:clamp(12px,1.2vw,16px); opacity:.9; }
  .clock .time{ font-size:clamp(20px,3vw,40px); font-weight:700; letter-spacing:1px; }

  .container{ padding:var(--pad); padding-bottom:calc(var(--footer-h) + var(--pad));
    display:grid; grid-template-columns:repeat(12,1fr); grid-auto-rows:minmax(120px,auto); gap:var(--pad); }
  .card{ background:var(--card-bg); border-radius:var(--radius); padding:var(--pad); backdrop-filter:blur(4px); box-shadow:0 8px 22px rgba(0,0,0,.25); }
  .card h3{ margin:0 0 10px 0; font-size:clamp(14px,1.4vw,20px); font-weight:700; display:flex; align-items:center; gap:10px;}
  .kpi-row{ display:flex; gap:16px; flex-wrap:wrap; }
  .kpi{ flex:1 1 140px; min-width:140px; background:rgba(255,255,255,0.06); border-radius:14px; padding:12px 14px; border:1px solid rgba(255,255,255,0.06);}
  .kpi .label{ font-size:12px; opacity:.85; }
  .kpi .value{ font-size:clamp(18px,2.4vw,34px); font-weight:800; }
  .grid-6{ grid-column:span 6; } .grid-4{ grid-column:span 4; } .grid-12{ grid-column:1 / -1; }
  @media (max-width:1024px){ .grid-6,.grid-4{ grid-column:1 / -1; } }
  table.slim{ width:100%; border-collapse:collapse; font-size:clamp(12px,1.1vw,15px); }
  table.slim th,table.slim td{ border-bottom:1px dashed rgba(255,255,255,0.12); padding:6px 8px; text-align:left; }
  table.slim th{ opacity:.8; font-weight:600; }
  .muted{ opacity:.8; }
  .chip{ display:inline-block; padding:4px 8px; border-radius:999px; font-size:12px; background:rgba(25,118,210,.25); border:1px solid rgba(25,118,210,.4); }
  .up{ color:#66ff99;} .down{ color:#ff6b6b;}
  .ticker-wrap{ position:fixed; left:0; right:0; bottom:0; height:var(--footer-h); background:linear-gradient(90deg,#0e2647,#0b1d33); display:flex; align-items:center; overflow:hidden; border-top:1px solid rgba(255,255,255,.1);}
  .ticker-label{ flex:0 0 auto; padding:0 14px; font-weight:700; background:rgba(255,255,255,.06); height:100%; display:flex; align-items:center; border-right:1px solid rgba(255,255,255,.08);}
  .ticker{ white-space:nowrap; will-change:transform; padding-left:100%; animation:marquee 28s linear infinite; font-size:14px;}
  @keyframes marquee{0%{transform:translateX(0);}100%{transform:translateX(-100%);} }
</style>
</head>
<body>


<main class="container">
  <!-- Kehadiran -->
  <section class="card grid-6">
    <h3>📊 Kehadiran Murid (<?= safe($att_today['tarikh'] ?? '—') ?>)</h3>
    <div class="kpi-row">
      <div class="kpi"><div class="label">Peratus Hadir</div><div class="value"><?= safe($att_today ? $att_today['peratus'] : '—') ?>%</div></div>
      <div class="kpi"><div class="label">Hadir</div><div class="value"><?= safe($att_today['hadir'] ?? 0) ?></div></div>
      <div class="kpi"><div class="label">Tidak Hadir</div><div class="value"><?= safe($att_today['tidak_hadir'] ?? 0) ?></div></div>
      <div class="kpi"><div class="label">Lewat</div><div class="value"><?= safe($att_today['lewat'] ?? 0) ?></div></div>
    </div>
    <?php if ($last7_att): ?>
    <div style="margin-top:12px;">
      <table class="slim">
        <thead><tr><th>Tarikh</th><th class="muted">Hadir</th><th class="muted">Tidak Hadir</th><th class="muted">Lewat</th><th>Peratus %</th></tr></thead>
        <tbody>
          <?php foreach($last7_att as $r): ?>
          <tr>
            <td><?= safe($r['tarikh']) ?></td>
            <td class="muted"><?= safe($r['hadir']) ?></td>
            <td class="muted"><?= safe($r['tidak_hadir']) ?></td>
            <td class="muted"><?= safe($r['lewat']) ?></td>
            <td><span class="chip"><?= safe($r['peratus']) ?>%</span></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
    <?php endif; ?>
  </section>

  <!-- Disiplin -->
  <section class="card grid-6">
    <h3>⚠️ Disiplin Murid (Bulan Semasa)</h3>
    <div class="kpi-row">
      <div class="kpi"><div class="label">Jumlah Kes</div><div class="value"><?= safe($disc_now['kes'] ?? 0) ?></div></div>
      <?php
        $delta = (int)($disc_now['perubahan'] ?? 0);
        $cls = $delta >= 0 ? 'up' : 'down';
        $sign = $delta > 0 ? '▲' : ($delta < 0 ? '▼' : '—');
      ?>
      <div class="kpi"><div class="label">Perubahan</div><div class="value <?= $cls ?>"><?= $sign.' '.abs($delta) ?></div></div>
    </div>
    <div style="margin-top:12px;">
      <table class="slim">
        <thead><tr><th>Top Kategori Kes</th><th class="muted">No. 2</th><th class="muted">No. 3</th></tr></thead>
        <tbody>
          <tr>
            <td><span class="chip"><?= safe($disc_now['top1'] ?? '-') ?></span></td>
            <td class="muted"><?= safe($disc_now['top2'] ?? '-') ?></td>
            <td class="muted"><?= safe($disc_now['top3'] ?? '-') ?></td>
          </tr>
        </tbody>
      </table>
    </div>
    <?php if ($last6_disc): ?>
    <div style="margin-top:12px;">
      <table class="slim">
        <thead><tr><th>Bulan</th><th>Kes</th><th class="muted">Perubahan</th></tr></thead>
        <tbody>
          <?php foreach($last6_disc as $r): $d=(int)$r['perubahan']; $c=$d>=0?'up':'down'; $sgn=$d>0?'▲':($d<0?'▼':'—'); ?>
          <tr>
            <td><?= safe($r['bulan']) ?></td>
            <td><?= safe($r['kes']) ?></td>
            <td class="muted <?= $c ?>"><?= $sgn.' '.abs($d) ?></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
    <?php endif; ?>
  </section>

  <!-- Kebajikan -->
  <section class="card grid-6">
    <h3>🎓 Kebajikan & Bantuan</h3>
    <div class="kpi-row">
      <div class="kpi"><div class="label">Penerima RMT</div><div class="value"><?= safe($wel['rmt'] ?? 0) ?></div></div>
      <div class="kpi"><div class="label">KWAPM</div><div class="value"><?= safe($wel['kwapm'] ?? 0) ?></div></div>
      <div class="kpi"><div class="label">Zakat</div><div class="value"><?= safe($wel['zakat'] ?? 0) ?></div></div>
      <div class="kpi"><div class="label">BSH</div><div class="value"><?= safe($wel['bsh'] ?? 0) ?></div></div>
    </div>
    <div style="margin-top:12px;">
      <div class="chip">Anggaran B40: <strong><?= safe($wel['b40_peratus'] ?? 0) ?>%</strong></div>
      <?php if ($totalM): ?><div class="chip" style="margin-left:8px;">Jumlah Murid: <strong><?= number_format($totalM) ?></strong></div><?php endif; ?>
      <?php if ($totalP): ?><div class="chip" style="margin-left:8px;">Nisbah L:P <strong><?= safe($nisbahLP) ?></strong></div><?php endif; ?>
    </div>
    <?php if ($ann): ?>
    <div style="margin-top:14px;">
      <table class="slim">
        <thead><tr><th>Pengumuman HEM</th><th class="muted">Tarikh</th></tr></thead>
        <tbody>
          <?php foreach($ann as $a): ?>
          <tr>
            <td><?= safe($a['tajuk'].($a['butiran']? ' — '.$a['butiran'] : '')) ?></td>
            <td class="muted"><?= safe($a['tarikh']) ?></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
    <?php endif; ?>
  </section>

  <!-- Kesihatan & Keselamatan -->
  <section class="card grid-6">
    <h3>🏥 Kesihatan & Keselamatan (Hari Ini)</h3>
    <div class="kpi-row">
      <div class="kpi"><div class="label">Sakit</div><div class="value"><?= safe($health_today['sakit'] ?? 0) ?></div></div>
      <div class="kpi"><div class="label">Kemalangan</div><div class="value"><?= safe($health_today['kemalangan'] ?? 0) ?></div></div>
      <div class="kpi"><div class="label">Ponteng</div><div class="value"><?= safe($health_today['ponteng'] ?? 0) ?></div></div>
      <div class="kpi"><div class="label">Keluar Tanpa Izin</div><div class="value"><?= safe($health_today['keluar_tanpa_izin'] ?? 0) ?></div></div>
    </div>
    <?php if ($last7_health): ?>
    <div style="margin-top:12px;">
      <table class="slim">
        <thead><tr><th>Hari/Tarikh</th><th>Sakit</th><th>Kemalangan</th><th>Ponteng</th><th>Keluar Tanpa Izin</th></tr></thead>
        <tbody>
          <?php foreach($last7_health as $r): ?>
          <tr>
            <td><?= safe($r['hari']) ?></td>
            <td><?= safe($r['sakit']) ?></td>
            <td><?= safe($r['kemalangan']) ?></td>
            <td><?= safe($r['ponteng']) ?></td>
            <td><?= safe($r['keluar_tanpa_izin']) ?></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
    <?php endif; ?>
  </section>

  <!-- Info -->
  <section class="card grid-12">
    <h3>ℹ️ Nota / Info HEM</h3>
    <div class="muted">Letakkan SOP, nombor pegawai, atau arahan ringkas HEM di sini.</div>
  </section>
</main>

<!-- Footer Ticker -->
<div class="ticker-wrap">
  <div class="ticker-label">MAKLUMAN</div>
  <div class="ticker" id="tickerText"><?= safe($ticker_join ?: 'Selamat datang ke Dashboard HEM.') ?></div>
</div>

<script>
  const days = ['Ahad','Isnin','Selasa','Rabu','Khamis','Jumaat','Sabtu'];
  const months = ['Januari','Februari','Mac','April','Mei','Jun','Julai','Ogos','September','Oktober','November','Disember'];
  const pad = n => n.toString().padStart(2,'0');
  function tick(){
    const d = new Date();
    const day = days[d.getDay()];
    const dateStr = `${day}, ${pad(d.getDate())} ${months[d.getMonth()]} ${d.getFullYear()}`;
    const timeStr = `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
    document.getElementById('dateStr').textContent = dateStr;
    document.getElementById('timeStr').textContent = timeStr;
  }
  setInterval(tick, 1000); tick();
</script>
</body>
</html>
