<?php
$pageTitle = 'Laman Utama';
require_once __DIR__.'/config/functions.php';

// Stats
$stats['total_pegawai'] = $pdo->query("SELECT COUNT(*) FROM pegawai WHERE status=1")->fetchColumn();
$stats['total_aktiviti'] = $pdo->query("SELECT COUNT(*) FROM takwim WHERE status=1")->fetchColumn();
$stats['aktiviti_bulan'] = $pdo->query("SELECT COUNT(*) FROM takwim WHERE MONTH(tarikh_mula)=MONTH(CURDATE()) AND YEAR(tarikh_mula)=YEAR(CURDATE()) AND status=1")->fetchColumn();
$units = $pdo->query("SELECT u.*,(SELECT COUNT(*) FROM pegawai p WHERE p.unit_id=u.id AND p.status=1) as jml_pegawai FROM unit u WHERE u.status=1 ORDER BY u.urutan ASC, u.id ASC")->fetchAll();
$announcements = $pdo->query("SELECT * FROM announcements WHERE status=1 ORDER BY id DESC LIMIT 3")->fetchAll();
$unitColors=[1=>'#0d6efd',2=>'#dc3545',3=>'#198754'];
$unitIcons=[1=>'fas fa-star',2=>'fas fa-users',3=>'fas fa-trophy'];

if(isLoggedIn()){
  $stats['total_unit']=$pdo->query("SELECT COUNT(*) FROM unit WHERE status=1")->fetchColumn();
  $pegawai_terkini=$pdo->query("SELECT p.*,j.nama_jawatan,u.nama_unit,u.warna FROM pegawai p JOIN jawatan j ON p.jawatan_id=j.id JOIN unit u ON p.unit_id=u.id WHERE p.status=1 ORDER BY p.urutan,j.urutan,p.nama LIMIT 12")->fetchAll();
  $aktiviti_akan=$pdo->query("SELECT t.*,u.nama_unit,u.warna FROM takwim t LEFT JOIN unit u ON t.unit_id=u.id WHERE t.tarikh_mula>=CURDATE() AND t.status=1 ORDER BY t.tarikh_mula LIMIT 5")->fetchAll();
  $breadcrumb=null;
  require_once __DIR__.'/templates/header.php';
  ?>
  <meta name="base-url" content="<?=BASE_URL?>">
  <meta name="csrf-token" content="<?=$csrf?>">
  <?php require_once __DIR__.'/templates/sidebar.php'; ?>
  <div class="main-content">
  <?php require_once __DIR__.'/templates/topbar.php'; ?>
  <div style="padding:2rem">
  <?php if($announcements): foreach($announcements as $ann): ?>
  <div class="alert alert-dismissible mb-3" style="background:rgba(13,110,253,0.08);border:1px solid rgba(13,110,253,0.2);color:#e0e0e0;border-radius:12px" role="alert">
    <i class="fas fa-info-circle me-2" style="color:#0d6efd"></i><strong><?=htmlspecialchars($ann['tajuk'])?></strong> — <?=htmlspecialchars($ann['kandungan'])?>
    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="alert"></button>
  </div>
  <?php endforeach; endif; ?>
  <div style="background:linear-gradient(135deg,rgba(204,0,1,0.12),rgba(26,26,46,0.8) 50%,rgba(13,110,253,0.08) 100%);border:1px solid rgba(204,0,1,0.2);border-radius:24px;padding:2.5rem;margin-bottom:2rem;position:relative;overflow:hidden">
    <div style="position:absolute;top:-50px;right:-50px;width:200px;height:200px;border-radius:50%;background:rgba(204,0,1,0.06);filter:blur(40px)"></div>
    <div style="position:relative">
      <div style="font-size:.8rem;color:#cc0001;text-transform:uppercase;letter-spacing:3px;font-weight:600;margin-bottom:.5rem">Portal Rasmi</div>
      <h1 style="font-size:clamp(1.5rem,4vw,2.5rem);font-weight:900;color:#fff;margin-bottom:.5rem">Selamat Datang ke <span style="color:#cc0001">S.P.M</span> Dashboard</h1>
      <p style="color:#888;margin-bottom:1.5rem">Sektor Pembangunan Murid — Portal Pengurusan Pegawai & Aktiviti</p>
      <div style="display:flex;gap:1rem;flex-wrap:wrap">
        <a href="modules/pegawai/" class="btn-hero btn" style="font-size:.9rem;padding:.65rem 1.75rem"><i class="fas fa-users me-2"></i>Senarai Pegawai</a>
        <a href="modules/takwim/" class="btn btn-outline-light" style="border-radius:50px;padding:.65rem 1.75rem;font-size:.9rem"><i class="fas fa-calendar me-2"></i>Lihat Takwim</a>
      </div>
    </div>
  </div>
  <div class="row g-3 mb-4">
    <div class="col-6 col-md-3"><div class="stat-card"><div class="stat-icon" style="color:#cc0001"><i class="fas fa-users"></i></div><div class="stat-number" data-count="<?=$stats['total_pegawai']?>"><?=$stats['total_pegawai']?></div><div class="stat-label">Jumlah Pegawai</div></div></div>
    <div class="col-6 col-md-3"><div class="stat-card"><div class="stat-icon" style="color:#0d6efd"><i class="fas fa-calendar-check"></i></div><div class="stat-number" data-count="<?=$stats['total_aktiviti']?>"><?=$stats['total_aktiviti']?></div><div class="stat-label">Jumlah Aktiviti</div></div></div>
    <div class="col-6 col-md-3"><div class="stat-card"><div class="stat-icon" style="color:#198754"><i class="fas fa-building"></i></div><div class="stat-number" data-count="<?=$stats['total_unit']?>"><?=$stats['total_unit']?></div><div class="stat-label">Jumlah Unit</div></div></div>
    <div class="col-6 col-md-3"><div class="stat-card"><div class="stat-icon" style="color:#ffc107"><i class="fas fa-star"></i></div><div class="stat-number" data-count="<?=$stats['aktiviti_bulan']?>"><?=$stats['aktiviti_bulan']?></div><div class="stat-label">Aktiviti Bulan Ini</div></div></div>
  </div>
  <div class="mb-2 d-flex align-items-center justify-content-between mb-3"><h2 class="section-title">Unit Dalam Sektor</h2></div>
  <div class="row g-3 mb-4">
  <?php foreach($units as $u): $col=$unitColors[$u['id']]??'#888';$icon=$unitIcons[$u['id']]??'fas fa-building'; ?>
  <div class="col-md-4"><a href="modules/pegawai/?unit=<?=$u['id']?>" style="text-decoration:none">
  <div class="unit-card" style="--unit-color:<?=$col?>">
    <div class="unit-icon" style="background:<?=$col?>22"><i class="<?=$icon?>" style="color:<?=$col?>"></i></div>
    <h3 style="font-size:1.1rem;font-weight:700;color:#fff;margin-bottom:.5rem"><?=htmlspecialchars($u['nama_unit'])?></h3>
    <p style="font-size:.85rem;color:#666;margin-bottom:1.5rem"><?=htmlspecialchars($u['deskripsi']??'')?></p>
    <div style="display:flex;align-items:center;justify-content:space-between">
      <div><div style="font-size:1.8rem;font-weight:800;color:#fff"><?=$u['jml_pegawai']?></div><div style="font-size:.75rem;color:#555;text-transform:uppercase;letter-spacing:1px">Pegawai</div></div>
      <div style="background:<?=$col?>22;border:1px solid <?=$col?>44;border-radius:50px;padding:.4rem 1rem;font-size:.8rem;color:<?=$col?>;font-weight:600"><i class="fas fa-arrow-right me-1"></i>Lihat</div>
    </div>
  </div></a></div>
  <?php endforeach; ?>
  </div>
  <div class="row g-4">
    <div class="col-lg-8">
      <div class="d-flex align-items-center justify-content-between mb-3"><h2 class="section-title" style="font-size:1.3rem">Pegawai Aktif</h2><a href="modules/pegawai/" class="btn btn-sm btn-outline-primary">Lihat Semua</a></div>
      <div class="row g-3">
      <?php foreach($pegawai_terkini as $p): ?>
      <div class="col-6 col-md-4"><div class="staff-card">
        <img src="<?=getPegawaiImage($p['gambar'])?>" alt="<?=htmlspecialchars($p['nama'])?>" class="staff-avatar">
        <div class="staff-name"><?=htmlspecialchars($p['nama'])?></div>
        <div class="staff-position"><?=htmlspecialchars($p['nama_jawatan'])?></div>
        <span class="staff-unit-badge" style="background:<?=$p['warna']??'#888'?>22;color:<?=$p['warna']??'#888'?>;border:1px solid <?=$p['warna']??'#888'?>44"><?=htmlspecialchars($p['nama_unit'])?></span>
      </div></div>
      <?php endforeach; ?>
      </div>
    </div>
    <div class="col-lg-4">
      <h2 class="section-title mb-3" style="font-size:1.3rem">Aktiviti Akan Datang</h2>
      <div class="content-card">
      <?php if($aktiviti_akan): foreach($aktiviti_akan as $a): ?>
      <div style="display:flex;gap:1rem;padding:.75rem 0;border-bottom:1px solid rgba(255,255,255,0.04)">
        <div style="min-width:45px;height:45px;background:<?=$a['warna']??'#cc0001'?>22;border:1px solid <?=$a['warna']??'#cc0001'?>44;border-radius:12px;display:flex;flex-direction:column;align-items:center;justify-content:center">
          <span style="font-size:1rem;font-weight:800;color:<?=$a['warna']??'#cc0001'?>;line-height:1"><?=date('d',strtotime($a['tarikh_mula']))?></span>
          <span style="font-size:.6rem;color:#555;text-transform:uppercase"><?=date('M',strtotime($a['tarikh_mula']))?></span>
        </div>
        <div><div style="font-size:.9rem;font-weight:600;color:#fff"><?=htmlspecialchars($a['tajuk'])?></div><div style="font-size:.75rem;color:#555"><?=htmlspecialchars($a['tempat']??'-')?></div></div>
      </div>
      <?php endforeach; else: ?>
      <div style="text-align:center;padding:2rem;color:#555"><i class="fas fa-calendar fa-2x mb-2"></i><p>Tiada aktiviti akan datang</p></div>
      <?php endif; ?>
      <a href="modules/takwim/" class="btn btn-sm btn-outline-primary w-100 mt-3">Takwim Penuh</a>
      </div>
    </div>
  </div>
  </div></div>
<?php
} else {
  // PUBLIC VIEW
  // Timbalan Pengarah - tiada unit / jawatan_id=1
  $timbalan=$pdo->query("SELECT p.*,j.nama_jawatan FROM pegawai p JOIN jawatan j ON p.jawatan_id=j.id WHERE p.status=1 AND (p.unit_id IS NULL OR j.urutan=1) ORDER BY p.nama")->fetchAll();
  // Semua pegawai lain (bukan Timbalan)
  $pegawaiAll=$pdo->query("SELECT p.*,j.nama_jawatan,j.urutan as j_urutan,u.nama_unit,u.warna,su.nama_subunit 
    FROM pegawai p 
    JOIN jawatan j ON p.jawatan_id=j.id 
    JOIN unit u ON p.unit_id=u.id 
    LEFT JOIN subunit su ON p.subunit_id=su.id
    WHERE p.status=1 AND j.urutan>1 
    ORDER BY u.id,j.urutan,p.nama")->fetchAll();
  
  $pegawaiByUnit=[];
  foreach($pegawaiAll as $p) {
    $sid = $p['subunit_id'] ?? 0;
    $pegawaiByUnit[$p['unit_id']][$sid]['nama'] = $p['nama_subunit'] ?? 'Utama / Umum';
    $pegawaiByUnit[$p['unit_id']][$sid]['pegawai'][] = $p;
  }
  $takwimPublic=$pdo->query("SELECT t.*,u.nama_unit,u.warna FROM takwim t LEFT JOIN unit u ON t.unit_id=u.id WHERE t.status=1 AND t.tarikh_mula>=CURDATE() ORDER BY t.tarikh_mula LIMIT 8")->fetchAll();
  
  $stories=$pdo->query("SELECT s.*,u.nama_unit,u.warna FROM success_stories s LEFT JOIN unit u ON s.unit_id=u.id WHERE s.status=1 ORDER BY s.tarikh DESC,s.id DESC LIMIT 12")->fetchAll();
  $storiesByUnit=[];
  foreach($units as $u) $storiesByUnit[$u['id']]=[];
  foreach($stories as $s) if(!empty($s['unit_id'])) $storiesByUnit[$s['unit_id']][]=$s;
  
  $infosPublic=$pdo->query("SELECT i.*,p.nama as nama_pegawai,p.gambar,u.nama_unit,u.warna,u.id as unit_id FROM informasi i JOIN pegawai p ON i.pegawai_id=p.id JOIN unit u ON p.unit_id=u.id WHERE i.status=1 ORDER BY i.created_at DESC LIMIT 12")->fetchAll();
  $infosByUnit=[];
  foreach($units as $u) $infosByUnit[$u['id']]=[];
  foreach($infosPublic as $i) if(!empty($i['unit_id'])) $infosByUnit[$i['unit_id']][]=$i;

  // DASHBOARD LINKS PER SUBUNIT
  $linksPublic = $pdo->query("SELECT l.*, s.nama_subunit, u.nama_unit, u.warna FROM links l JOIN unit u ON l.unit_id=u.id LEFT JOIN subunit s ON l.subunit_id = s.id WHERE l.status=1 AND l.awam=1 ORDER BY l.unit_id, s.id, l.urutan")->fetchAll();
  $linksByUnit = [];
  foreach($linksPublic as $l) {
    $sid = $l['subunit_id'] ?? 0;
    $linksByUnit[$l['unit_id']][$sid]['nama'] = $l['nama_subunit'] ?? 'Utama / Umum';
    $linksByUnit[$l['unit_id']][$sid]['links'][] = $l;
  }
  $sektorData = getSektorData();
  require_once __DIR__.'/templates/header.php';
?>
<meta name="base-url" content="<?=BASE_URL?>">
<!-- PUBLIC NAV -->
<nav class="navbar navbar-expand-lg">
<div class="container-fluid px-4">
  <a class="navbar-brand" href="<?=BASE_URL?>" style="display:flex;align-items:center;gap:.5rem;text-decoration:none">
    <?=getSektorLogo('small')?>
  </a>
  <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navMenu" style="border-color:rgba(204,0,1,0.3);color:#fff"><i class="fas fa-bars"></i></button>
  <div class="collapse navbar-collapse" id="navMenu">
    <ul class="navbar-nav ms-auto align-items-lg-center gap-1">
      <li class="nav-item"><a class="nav-link active" href="#hero">Utama</a></li>
      <li class="nav-item"><a class="nav-link" href="#pegawai">Pegawai</a></li>
      <li class="nav-item"><a class="nav-link" href="#takwim">Takwim</a></li>
      <li class="nav-item"><a class="nav-link" href="#links">Dashboard Unit</a></li>
      <li class="nav-item"><a class="nav-link" href="#informasi">Informasi</a></li>
      <li class="nav-item"><a class="nav-link" href="#stories">Success Stories</a></li>
      <li class="nav-item ms-2"><a href="<?=BASE_URL?>modules/auth/login.php" class="btn btn-sm" style="background:rgba(204,0,1,0.15);border:1px solid rgba(204,0,1,0.4);color:#fff;border-radius:10px;padding:.5rem 1.25rem"><i class="fas fa-sign-in-alt me-1"></i>Log Masuk</a></li>
    </ul>
  </div>
</div>
</nav>

<!-- HERO -->
<section id="hero" style="min-height:65vh;display:flex;align-items:center;padding:4rem 0;position:relative;overflow:hidden">
  <div style="position:absolute;top:0;left:0;right:0;bottom:0;background:radial-gradient(ellipse at 15% 50%,rgba(204,0,1,0.1),transparent 60%),radial-gradient(ellipse at 85% 30%,rgba(13,110,253,0.07),transparent 50%)"></div>
  <div class="container-fluid px-4" style="position:relative">
  <div class="row align-items-center g-5">
    <div class="col-lg-6">
      <div style="font-size:.8rem;color:#cc0001;text-transform:uppercase;letter-spacing:3px;font-weight:600;margin-bottom:1rem;display:flex;align-items:center;gap:.5rem"><span style="width:30px;height:2px;background:#cc0001;display:inline-block"></span>Portal Rasmi</div>
      <?php if(!empty($sektorData['logo_2']) && file_exists(UPLOAD_PATH.'logo/'.$sektorData['logo_2'])): ?>
        <img src="<?=UPLOAD_URL.'logo/'.$sektorData['logo_2']?>" style="max-height:150px;max-width:100%;object-fit:contain;margin-bottom:1.5rem;filter:drop-shadow(0 0 20px rgba(204,0,1,0.2))" alt="Sektor Pembangunan Murid">
      <?php else: ?>
        <h1 style="font-size:clamp(2rem,4.5vw,3.2rem);font-weight:900;line-height:1.1;letter-spacing:-1px;color:#fff;margin-bottom:1rem">Sektor <span style="color:#cc0001;text-shadow:0 0 30px rgba(204,0,1,0.4)">Pembangunan</span><br>Murid</h1>
      <?php endif; ?>
      <p style="font-size:1.1rem;color:#666;line-height:1.7;margin-bottom:2rem">Platform pengurusan pegawai, aktiviti dan maklumat Sektor Pembangunan Murid secara profesional dan telus.</p>
      <div style="display:flex;gap:1rem;flex-wrap:wrap">
        <a href="#pegawai" class="btn-hero btn"><i class="fas fa-users me-2"></i>Senarai Pegawai</a>
        <a href="#takwim" class="btn btn-outline-light" style="border-radius:50px;padding:.85rem 2rem"><i class="fas fa-calendar me-2"></i>Takwim Awam</a>
      </div>
    </div>
    <div class="col-lg-6">
      <div class="row g-3">
        <div class="col-6"><div class="stat-card"><div class="stat-icon" style="color:#cc0001"><i class="fas fa-users"></i></div><div class="stat-number" data-count="<?=$stats['total_pegawai']?>"><?=$stats['total_pegawai']?></div><div class="stat-label">Jumlah Pegawai</div></div></div>
        <div class="col-6"><div class="stat-card"><div class="stat-icon" style="color:#0d6efd"><i class="fas fa-calendar-check"></i></div><div class="stat-number" data-count="<?=$stats['total_aktiviti']?>"><?=$stats['total_aktiviti']?></div><div class="stat-label">Jumlah Aktiviti</div></div></div>
        <?php foreach($units as $u): $col=$unitColors[$u['id']]??'#888'; ?>
        <div class="col-12"><div class="glass-card" style="padding:1rem 1.25rem;display:flex;align-items:center;gap:1rem;border-left:3px solid <?=$col?>">
          <div style="width:42px;height:42px;background:<?=$col?>22;border-radius:12px;display:flex;align-items:center;justify-content:center;flex-shrink:0"><i class="<?=$unitIcons[$u['id']]??'fas fa-building'?>" style="color:<?=$col?>"></i></div>
          <div><div style="font-weight:700;color:#fff;font-size:.9rem"><?=htmlspecialchars($u['nama_unit'])?></div><div style="font-size:.75rem;color:#555"><?=$u['jml_pegawai']?> Pegawai Aktif</div></div>
          <div style="margin-left:auto;font-size:1.5rem;font-weight:800;color:<?=$col?>"><?=$u['jml_pegawai']?></div>
        </div></div>
        <?php endforeach; ?>
      </div>
    </div>
  </div>
  </div>
</section>

<!-- SENARAI PEGAWAI PER UNIT -->
<section id="pegawai" style="padding:4rem 0;background:rgba(0,0,0,0.2)">
<div class="container-fluid px-4">
  <div style="text-align:center;margin-bottom:3rem">
    <div style="font-size:.75rem;color:#cc0001;text-transform:uppercase;letter-spacing:3px;font-weight:600;margin-bottom:.75rem">Warga Sektor</div>
    <h2 class="section-title text-center" style="font-size:2rem;display:inline-block">Senarai Pegawai</h2>
  </div>

  <!-- Filter Tabs -->
  <div style="display:flex;justify-content:center;gap:.75rem;flex-wrap:wrap;margin-bottom:2.5rem">
    <button class="btn unit-tab active" data-unit="all" style="border-radius:50px;padding:.5rem 1.5rem;font-size:.85rem;background:rgba(204,0,1,0.15);border:1px solid rgba(204,0,1,0.4);color:#fff">Semua</button>
    <button class="btn unit-tab" data-unit="timbalan" style="border-radius:50px;padding:.5rem 1.5rem;font-size:.85rem;background:rgba(204,0,1,0.07);border:1px solid rgba(204,0,1,0.2);color:#888">Ketua Sektor</button>
    <?php foreach($units as $u): $col=$unitColors[$u['id']]??'#888'; ?>
    <button class="btn unit-tab" data-unit="<?=$u['id']?>" style="border-radius:50px;padding:.5rem 1.5rem;font-size:.85rem;background:<?=$col?>11;border:1px solid <?=$col?>44;color:#888"><?=htmlspecialchars($u['nama_unit'])?></button>
    <?php endforeach; ?>
  </div>

  <style>
    .staff-flex-grid {
      display: flex;
      flex-wrap: wrap;
      margin: 0 -0.5rem;
    }
    .subunit-wrapper {
      flex: 0 0 100%;
      padding: 0 0.5rem;
      margin-bottom: 2.5rem;
      min-width: 0;
    }
    .subunit-cards {
      display: grid;
      gap: 1.5rem;
    }

    @media (min-width: 768px) {
      .subunit-wrapper[data-count="1"] { flex: 0 0 50%; }
      .subunit-wrapper[data-count="2"] { flex: 0 0 100%; }
      .subunit-cards { grid-template-columns: repeat(2, 1fr); }
      .subunit-wrapper[data-count="1"] .subunit-cards { grid-template-columns: 1fr; }
    }

    @media (min-width: 992px) {
      .subunit-wrapper[data-count="1"] { flex: 0 0 33.333%; }
      .subunit-wrapper[data-count="2"] { flex: 0 0 66.666%; }
      .subunit-wrapper[data-count="3"] { flex: 0 0 100%; }
      .subunit-cards { grid-template-columns: repeat(3, 1fr); }
      .subunit-wrapper[data-count="1"] .subunit-cards { grid-template-columns: 1fr; }
      .subunit-wrapper[data-count="2"] .subunit-cards { grid-template-columns: repeat(2, 1fr); }
    }

    @media (min-width: 1200px) {
      .subunit-wrapper[data-count="1"] { flex: 0 0 20%; }
      .subunit-wrapper[data-count="2"] { flex: 0 0 40%; }
      .subunit-wrapper[data-count="3"] { flex: 0 0 60%; }
      .subunit-wrapper[data-count="4"] { flex: 0 0 80%; }
      .subunit-wrapper[data-count="5"] { flex: 0 0 100%; }
      .subunit-cards { grid-template-columns: repeat(5, 1fr); }
      .subunit-wrapper[data-count="1"] .subunit-cards { grid-template-columns: 1fr; }
      .subunit-wrapper[data-count="2"] .subunit-cards { grid-template-columns: repeat(2, 1fr); }
      .subunit-wrapper[data-count="3"] .subunit-cards { grid-template-columns: repeat(3, 1fr); }
      .subunit-wrapper[data-count="4"] .subunit-cards { grid-template-columns: repeat(4, 1fr); }
    }

    .subunit-header {
      display: flex;
      align-items: center;
      gap: 0.75rem;
      margin-top: 1rem;
      margin-bottom: 0.5rem;
    }
    .subunit-header::after {
      content: '';
      flex: 1;
      height: 1px;
      background: linear-gradient(90deg, rgba(255,255,255,0.1), transparent);
    }
    .subunit-title {
      font-size: 0.7rem;
      font-weight: 700;
      color: #888;
      text-transform: uppercase;
      letter-spacing: 2px;
    }
    .subunit-dot {
      width: 6px;
      height: 6px;
      border-radius: 50%;
    }

    .staff-card-futuristic {
      background: rgba(255, 255, 255, 0.03);
      border: 1px solid rgba(255, 255, 255, 0.05);
      border-radius: 20px;
      padding: 1.5rem;
      text-align: center;
      transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
      position: relative;
      overflow: hidden;
      height: 100%;
      display: flex;
      flex-direction: column;
      backdrop-filter: blur(10px);
    }
    .staff-card-futuristic:hover {
      transform: translateY(-10px);
      background: rgba(255, 255, 255, 0.05);
      border-color: var(--unit-color-op);
      box-shadow: 0 15px 30px rgba(0, 0, 0, 0.4), 0 0 20px var(--unit-color-glow);
    }
    .staff-avatar-wrapper {
      position: relative;
      display: inline-block;
      margin-bottom: 1.25rem;
      width: 100px;
      height: 100px;
      margin-left: auto;
      margin-right: auto;
    }
    .staff-avatar-futuristic {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      object-fit: cover;
      border: 3px solid rgba(255, 255, 255, 0.1);
      transition: all 0.4s ease;
    }
    .staff-card-futuristic:hover .staff-avatar-futuristic {
      border-color: var(--unit-color);
      transform: scale(1.05);
    }
    .staff-name-futuristic {
      font-size: 0.95rem;
      font-weight: 800;
      color: #fff;
      margin-bottom: 0.25rem;
      line-height: 1.3;
      min-height: 2.6rem;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .staff-pos-futuristic {
      font-size: 0.75rem;
      color: #777;
      margin-bottom: 1rem;
      font-weight: 500;
    }
    .staff-contact-futuristic {
      margin-top: auto;
      padding-top: 1rem;
      border-top: 1px solid rgba(255, 255, 255, 0.05);
      font-size: 0.7rem;
      color: #555;
      text-align: left;
    }
    .staff-contact-futuristic div {
      margin-bottom: 0.25rem;
      display: flex;
      align-items: center;
      gap: 0.5rem;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  </style>

  <!-- Search -->
  <div style="max-width:500px;margin:0 auto 3.5rem;position:relative">
    <i class="fas fa-search" style="position:absolute;left:1.25rem;top:50%;transform:translateY(-50%);color:#cc0001"></i>
    <input type="search" id="publicSearch" placeholder="Cari nama pegawai atau jawatan..." style="width:100%;background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.08);border-radius:50px;padding:.8rem 1.25rem .8rem 3rem;color:#fff;font-size:.95rem;outline:none;font-family:Outfit,sans-serif;box-shadow:0 10px 30px rgba(0,0,0,0.2)" oninput="filterPegawai()">
  </div>

  <!-- ===== 1. TIMBALAN PENGARAH PENDIDIKAN - KETUA SEKTOR ===== -->
  <?php if($timbalan): ?>
  <div class="timbalan-section unit-section mb-5" data-unit-id="timbalan">
    <div style="display:flex;align-items:center;gap:1.25rem;margin-bottom:2.5rem;padding:1.25rem;background:rgba(204,0,1,0.05);border-radius:24px;border:1px solid rgba(204,0,1,0.15)">
      <div style="width:54px;height:54px;background:rgba(204,0,1,0.15);border:1px solid rgba(204,0,1,0.3);border-radius:16px;display:flex;align-items:center;justify-content:center;font-size:1.4rem;box-shadow:0 0 20px rgba(204,0,1,0.1)"><i class="fas fa-crown" style="color:#cc0001"></i></div>
      <div>
        <h3 style="font-size:1.25rem;font-weight:800;color:#fff;margin:0">Ketua Sektor</h3>
        <div style="font-size:.75rem;color:#555;font-weight:500;margin-top:2px">Sektor Pembangunan Murid • Pengurusan Tertinggi</div>
      </div>
    </div>
    
    <div style="display:flex;justify-content:center;flex-wrap:wrap;gap:1.5rem">
    <?php foreach($timbalan as $t): 
      $col = '#cc0001';
      $colGlow = $col . '22';
      $colOp = $col . '44';
    ?>
    <div class="pegawai-card" style="width:280px;--unit-color:<?=$col?>; --unit-color-op:<?=$colOp?>; --unit-color-glow:<?=$colGlow?>">
      <div class="staff-card-futuristic">
        <div style="position:absolute;top:15px;right:15px;color:<?=$col?>;font-size:.8rem"><i class="fas fa-crown"></i></div>
        <div class="staff-avatar-wrapper">
          <img src="<?=getPegawaiImage($t['gambar'])?>" alt="<?=htmlspecialchars($t['nama'])?>" class="staff-avatar-futuristic">
          <div style="position:absolute;bottom:0;right:0;width:16px;height:16px;background:#198754;border-radius:50%;border:3px solid #0a0a0f"></div>
        </div>
        <div class="staff-name-futuristic"><?=htmlspecialchars($t['nama'])?></div>
        <div class="staff-pos-futuristic"><?=htmlspecialchars($t['nama_jawatan'])?></div>
        <div class="staff-contact-futuristic">
          <?php if($t['email']): ?><div><i class="fas fa-envelope" style="width:14px;color:<?=$col?>"></i><?=htmlspecialchars($t['email'])?></div><?php endif; ?>
          <?php if($t['no_telefon_pejabat']): ?><div><i class="fas fa-phone" style="width:14px;color:<?=$col?>"></i><?=htmlspecialchars($t['no_telefon_pejabat'])?></div><?php endif; ?>
        </div>
      </div>
    </div>
    <?php endforeach; ?>
    </div>
  </div>
  <?php endif; ?>

  <!-- ===== 2. PEGAWAI PER UNIT ===== -->
  <?php foreach($units as $u):
    $col=$unitColors[$u['id']]??'#888';
    $icon=$unitIcons[$u['id']]??'fas fa-building';
    $uGroups=$pegawaiByUnit[$u['id']]??[];
    if(!$uGroups) continue;
    
    // Separate KPPs (urutan=2) for this unit
    $unitKpps = [];
    foreach($uGroups as $sid => $g) {
      foreach($g['pegawai'] as $p) {
        if($p['j_urutan'] == 2) $unitKpps[] = $p;
      }
    }
    
    $totalPegawai = 0;
    foreach($uGroups as $g) $totalPegawai += count($g['pegawai']);
  ?>
  <div class="unit-section mt-5" data-unit-id="<?=$u['id']?>">
    <div style="display:flex;align-items:center;gap:1.25rem;margin-bottom:2.5rem;padding:1.25rem;background:rgba(255,255,255,0.02);border-radius:24px;border:1px solid rgba(255,255,255,0.05)">
      <div style="width:54px;height:54px;background:<?=$col?>1a;border:1px solid <?=$col?>44;border-radius:16px;display:flex;align-items:center;justify-content:center;font-size:1.4rem;box-shadow:0 0 20px <?=$col?>11"><i class="<?=$icon?>" style="color:<?=$col?>"></i></div>
      <div>
        <h3 style="font-size:1.25rem;font-weight:800;color:#fff;margin:0"><?=htmlspecialchars($u['nama_unit'])?></h3>
        <div style="font-size:.75rem;color:#555;font-weight:500;margin-top:2px">Sektor Pembangunan Murid • <?=$totalPegawai?> Pegawai</div>
      </div>
      <div style="margin-left:auto;background:<?=$col?>22;color:<?=$col?>;padding:.4rem 1.25rem;border-radius:50px;font-size:.85rem;font-weight:800;border:1px solid <?=$col?>33"><?=$totalPegawai?></div>
    </div>

    <!-- Ketua Unit (KPP) - Featured and Centered at Top -->
    <?php if($unitKpps): ?>
    <div style="display:flex;justify-content:center;flex-wrap:wrap;gap:1.5rem;margin-bottom:3rem">
      <?php foreach($unitKpps as $p): 
        $colGlow = $col . '22';
        $colOp = $col . '44';
      ?>
      <div class="pegawai-card" data-nama="<?=strtolower(htmlspecialchars($p['nama']))?>" data-unit="<?=$p['unit_id']?>" style="width:280px;--unit-color:<?=$col?>; --unit-color-op:<?=$colOp?>; --unit-color-glow:<?=$colGlow?>">
        <div class="staff-card-futuristic" style="border-width:2px;background:rgba(<?=$col?>,0.05)">
          <div style="position:absolute;top:15px;right:15px;color:<?=$col?>;font-size:.8rem"><i class="fas fa-medal"></i></div>
          <div class="staff-avatar-wrapper">
            <img src="<?=getPegawaiImage($p['gambar'])?>" alt="<?=htmlspecialchars($p['nama'])?>" class="staff-avatar-futuristic" style="border-color:<?=$col?>">
            <div style="position:absolute;bottom:0;right:0;width:16px;height:16px;background:<?=$p['status']?'#198754':'#dc3545'?>;border-radius:50%;border:3px solid #0a0a0f"></div>
          </div>
          <div class="staff-name-futuristic"><?=htmlspecialchars($p['nama'])?></div>
          <div class="staff-pos-futuristic" style="color:<?=$col?>;font-weight:700"><?=htmlspecialchars($p['nama_jawatan'])?></div>
          <div class="staff-contact-futuristic">
            <?php if($p['email']): ?><div><i class="fas fa-envelope" style="width:14px;color:<?=$col?>"></i><?=htmlspecialchars($p['email'])?></div><?php endif; ?>
            <?php if($p['no_telefon_pejabat']): ?><div><i class="fas fa-phone" style="width:14px;color:<?=$col?>"></i><?=htmlspecialchars($p['no_telefon_pejabat'])?></div><?php endif; ?>
          </div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
    <?php endif; ?>

    <div class="staff-flex-grid">
      <?php foreach($uGroups as $sid => $group): 
        $pList = array_filter($group['pegawai'], fn($p) => $p['j_urutan'] > 2);
        if(!$pList) continue;
        $count = count($pList);
        $colGlow = $col . '22';
        $colOp = $col . '44';
      ?>
        <div class="subunit-wrapper" data-count="<?=min(5, $count)?>">
          <!-- Subunit Header -->
          <div class="subunit-header">
            <div class="subunit-dot" style="background:<?=$col?>"></div>
            <div class="subunit-title"><?=htmlspecialchars($group['nama'])?></div>
          </div>

          <div class="subunit-cards">
            <?php foreach($pList as $p): ?>
            <div class="pegawai-card" data-nama="<?=strtolower(htmlspecialchars($p['nama']))?>" data-unit="<?=$p['unit_id']?>" style="--unit-color:<?=$col?>; --unit-color-op:<?=$colOp?>; --unit-color-glow:<?=$colGlow?>">
              <div class="staff-card-futuristic">
                <div class="staff-avatar-wrapper">
                  <img src="<?=getPegawaiImage($p['gambar'])?>" alt="<?=htmlspecialchars($p['nama'])?>" class="staff-avatar-futuristic">
                  <div style="position:absolute;bottom:0;right:0;width:16px;height:16px;background:<?=$p['status']?'#198754':'#dc3545'?>;border-radius:50%;border:3px solid #0a0a0f"></div>
                </div>
                
                <div class="staff-name-futuristic"><?=htmlspecialchars($p['nama'])?></div>
                <div class="staff-pos-futuristic"><?=htmlspecialchars($p['nama_jawatan'])?></div>
                
                <div class="staff-contact-futuristic">
                  <?php if($p['email']): ?><div><i class="fas fa-envelope" style="width:14px;color:<?=$col?>"></i><?=htmlspecialchars($p['email'])?></div><?php endif; ?>
                  <?php if($p['no_telefon_pejabat']): ?><div><i class="fas fa-phone" style="width:14px;color:<?=$col?>"></i><?=htmlspecialchars($p['no_telefon_pejabat'])?></div><?php endif; ?>
                </div>
              </div>
            </div>
            <?php endforeach; ?>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
  </div>
  <?php endforeach; ?>
  <div id="noResult" style="display:none;text-align:center;padding:3rem;color:#555"><i class="fas fa-search fa-2x mb-2"></i><p>Tiada pegawai dijumpai</p></div>
</div>
</section>

<!-- TAKWIM AWAM -->
<section id="takwim" style="padding:4rem 0">
<div class="container-fluid px-4">
  <div style="text-align:center;margin-bottom:3rem">
    <div style="font-size:.75rem;color:#cc0001;text-transform:uppercase;letter-spacing:3px;font-weight:600;margin-bottom:.75rem">Jadual Program</div>
    <h2 class="section-title text-center" style="font-size:2rem;display:inline-block">Takwim Aktiviti</h2>
  </div>
  <div class="row g-4">
    <div class="col-lg-7">
      <div class="content-card" style="padding:1.5rem;background:rgba(255,255,255,0.02)">
        <div id="publicCalendar" style="min-height:500px"></div>
      </div>
    </div>
    <div class="col-lg-5">
      <div style="background:rgba(255,255,255,0.02);border:1px solid rgba(255,255,255,0.05);border-radius:24px;padding:1.5rem;height:100%;display:flex;flex-direction:column">
        <div style="display:flex;align-items:center;justify-content:between;margin-bottom:1.5rem">
          <h3 style="font-size:1.1rem;font-weight:800;color:#fff;margin:0" id="listMonthTitle">Senarai Aktiviti</h3>
          <div style="margin-left:auto;background:rgba(204,0,1,0.1);color:#cc0001;padding:.2rem .8rem;border-radius:50px;font-size:.7rem;font-weight:700;letter-spacing:1px" id="listEventCount">0 AKTIVITI</div>
        </div>
        <div id="publicEventList" style="flex:1;overflow-y:auto;max-height:600px;padding-right:.5rem">
          <div style="text-align:center;padding:3rem;color:#555"><div class="spinner-border text-primary spinner-border-sm me-2"></div>Memuatkan...</div>
        </div>
      </div>
    </div>
  </div>
</div>
</section>

<!-- DASHBOARD LINKS PER UNIT -->
<?php if($linksByUnit): ?>
<section id="links" style="padding:4rem 0;background:rgba(0,0,0,0.2)">
<div class="container-fluid px-4">
  <div style="text-align:center;margin-bottom:3rem">
    <div style="font-size:.75rem;color:#cc0001;text-transform:uppercase;letter-spacing:3px;font-weight:600;margin-bottom:.75rem">Akses Cepat</div>
    <h2 class="section-title text-center" style="font-size:2rem;display:inline-block">Dashboard Unit</h2>
  </div>
  <?php foreach($units as $u): 
    $col=$unitColors[$u['id']]??'#888';
    $icon=$unitIcons[$u['id']]??'fas fa-building';
    $uGroups=$linksByUnit[$u['id']]??[];
    if(!$uGroups) continue; 
  ?>
  <div class="mb-5">
    <div style="display:flex;align-items:center;gap:.75rem;margin-bottom:1.5rem">
      <div style="width:38px;height:38px;background:<?=$col?>22;border:1px solid <?=$col?>44;border-radius:12px;display:flex;align-items:center;justify-content:center"><i class="<?=$icon?>" style="color:<?=$col?>"></i></div>
      <h3 style="font-size:1.1rem;font-weight:700;color:#fff;margin:0"><?=htmlspecialchars($u['nama_unit'])?></h3>
    </div>
    
    <div class="staff-flex-grid">
    <?php foreach($uGroups as $sid => $group): 
      $count = count($group['links']);
    ?>
    <div class="subunit-wrapper" data-count="<?=min(5, $count)?>">
      <div class="subunit-header">
        <div class="subunit-dot" style="background:<?=$col?>"></div>
        <div class="subunit-title"><?=htmlspecialchars($group['nama'])?></div>
      </div>
      <div class="subunit-cards">
        <?php foreach($group['links'] as $lnk): ?>
        <a href="<?=htmlspecialchars($lnk['url'])?>" target="_blank" class="link-dashboard-btn" style="--link-color:<?=$lnk['warna']??$col?>">
          <?php if($lnk['logo']): ?>
          <div class="link-icon" style="background:transparent;padding:0;overflow:hidden">
            <img src="<?=UPLOAD_URL?>links/<?=$lnk['logo']?>" style="width:100%;height:100%;object-fit:cover" alt="Logo">
          </div>
          <?php else: ?>
          <div class="link-icon" style="background:<?=$lnk['warna']??$col?>22;color:<?=$lnk['warna']??$col?>"><i class="<?=$lnk['ikon']??'fas fa-link'?>"></i></div>
          <?php endif; ?>
          <div style="min-width:0;flex:1">
            <div style="font-size:.85rem;font-weight:600;color:#fff;white-space:nowrap;overflow:hidden;text-overflow:ellipsis"><?=htmlspecialchars($lnk['nama'])?></div>
            <?php if($lnk['deskripsi']): ?><div style="font-size:.7rem;color:#555;white-space:nowrap;overflow:hidden;text-overflow:ellipsis"><?=htmlspecialchars($lnk['deskripsi'])?></div><?php endif; ?>
          </div>
          <i class="fas fa-external-link-alt" style="margin-left:auto;color:#444;font-size:.75rem;flex-shrink:0"></i>
        </a>
        <?php endforeach; ?>
      </div>
    </div>
    <?php endforeach; ?>
    </div>
  </div>
  <?php endforeach; ?>
</div>
</section>
<?php endif; ?>


<!-- SUCCESS STORIES -->
<section id="stories" style="padding:4rem 0;background:rgba(0,0,0,0.2)">
<div class="container-fluid px-4">
  <div style="text-align:center;margin-bottom:3rem">
    <div style="font-size:.75rem;color:#cc0001;text-transform:uppercase;letter-spacing:3px;font-weight:600;margin-bottom:.75rem">Pencapaian Kami</div>
    <h2 class="section-title text-center" style="font-size:2rem;display:inline-block">Success Stories</h2>
  </div>

  <ul class="nav nav-pills justify-content-center mb-4" style="gap:.5rem">
    <li class="nav-item"><a class="nav-link active" href="#story_pub_all" data-bs-toggle="tab" style="border-radius:50px;padding:.5rem 1.5rem;font-size:.85rem;color:#fff;background:rgba(204,0,1,0.15);border:1px solid rgba(204,0,1,0.4)"><i class="fas fa-th-large me-2"></i>Semua</a></li>
    <?php foreach($units as $u): ?>
    <li class="nav-item"><a class="nav-link" href="#story_pub_<?=$u['id']?>" data-bs-toggle="tab" style="border-radius:50px;padding:.5rem 1.5rem;font-size:.85rem;color:#888;background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.06)"><i class="<?=htmlspecialchars($u['ikon'])?> me-2" style="color:<?=$u['warna']?>"></i><?=htmlspecialchars($u['nama_unit'])?></a></li>
    <?php endforeach; ?>
  </ul>

  <div class="tab-content">
    <div class="tab-pane fade show active" id="story_pub_all">
      <div class="row g-4 justify-content-center">
        <?php foreach($stories as $s): $col=$s['warna']??'#cc0001'; ?>
        <div class="col-md-6 col-lg-4">
        <div class="content-card h-100" style="border-top:3px solid <?=$col?>">
          <?php if($s['gambar']&&file_exists(UPLOAD_PATH.'gallery/'.$s['gambar'])): ?>
          <img src="<?=UPLOAD_URL.'gallery/'.$s['gambar']?>" style="width:100%;height:180px;object-fit:cover;border-radius:12px;margin-bottom:1rem">
          <?php endif; ?>
          <?php if($s['tarikh']): ?><div style="font-size:.75rem;color:#555;margin-bottom:.4rem"><i class="fas fa-calendar me-1"></i><?=formatDate($s['tarikh'])?></div><?php endif; ?>
          <h3 style="font-size:1rem;font-weight:700;color:#fff;margin-bottom:.5rem"><?=htmlspecialchars($s['tajuk'])?></h3>
          <p style="font-size:.85rem;color:#666;line-height:1.6;margin-bottom:.75rem"><?=nl2br(htmlspecialchars(substr($s['kandungan']??'',0,180)))?></p>
        </div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
    <?php foreach($units as $u): ?>
    <div class="tab-pane fade" id="story_pub_<?=$u['id']?>">
      <div class="row g-4 justify-content-center">
      <?php if(empty($storiesByUnit[$u['id']])): ?>
        <div class="col-12 text-center py-4" style="color:#555"><p>Tiada success stories</p></div>
      <?php else: ?>
        <?php foreach($storiesByUnit[$u['id']] as $s): $col=$s['warna']??'#cc0001'; ?>
        <div class="col-md-6 col-lg-4">
        <div class="content-card h-100" style="border-top:3px solid <?=$col?>">
          <?php if($s['gambar']&&file_exists(UPLOAD_PATH.'gallery/'.$s['gambar'])): ?>
          <img src="<?=UPLOAD_URL.'gallery/'.$s['gambar']?>" style="width:100%;height:180px;object-fit:cover;border-radius:12px;margin-bottom:1rem">
          <?php endif; ?>
          <?php if($s['tarikh']): ?><div style="font-size:.75rem;color:#555;margin-bottom:.4rem"><i class="fas fa-calendar me-1"></i><?=formatDate($s['tarikh'])?></div><?php endif; ?>
          <h3 style="font-size:1rem;font-weight:700;color:#fff;margin-bottom:.5rem"><?=htmlspecialchars($s['tajuk'])?></h3>
          <p style="font-size:.85rem;color:#666;line-height:1.6;margin-bottom:.75rem"><?=nl2br(htmlspecialchars(substr($s['kandungan']??'',0,180)))?></p>
        </div>
        </div>
        <?php endforeach; ?>
      <?php endif; ?>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
</div>
</section>

<!-- INFORMASI -->
<?php if($infosPublic): ?>
<section id="informasi" style="padding:4rem 0">
<div class="container-fluid px-4">
  <div style="text-align:center;margin-bottom:3rem">
    <div style="font-size:.75rem;color:#cc0001;text-transform:uppercase;letter-spacing:3px;font-weight:600;margin-bottom:.75rem">Terkini</div>
    <h2 class="section-title text-center" style="font-size:2rem;display:inline-block">Informasi Sektor</h2>
  </div>
  
  <ul class="nav nav-pills justify-content-center mb-4" style="gap:.5rem">
    <li class="nav-item"><a class="nav-link active" href="#info_pub_all" data-bs-toggle="tab" style="border-radius:50px;padding:.5rem 1.5rem;font-size:.85rem;color:#fff;background:rgba(204,0,1,0.15);border:1px solid rgba(204,0,1,0.4)"><i class="fas fa-th-large me-2"></i>Semua</a></li>
    <?php foreach($units as $u): ?>
    <li class="nav-item"><a class="nav-link" href="#info_pub_<?=$u['id']?>" data-bs-toggle="tab" style="border-radius:50px;padding:.5rem 1.5rem;font-size:.85rem;color:#888;background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.06)"><i class="<?=htmlspecialchars($u['ikon'])?> me-2" style="color:<?=$u['warna']?>"></i><?=htmlspecialchars($u['nama_unit'])?></a></li>
    <?php endforeach; ?>
  </ul>

  <div class="tab-content">
    <div class="tab-pane fade show active" id="info_pub_all">
      <div class="row g-4 justify-content-center">
        <?php foreach($infosPublic as $i): 
          $jCol=['umum'=>'#888','pengumuman'=>'#0d6efd','pencapaian'=>'#198754','aktiviti'=>'#ffc107','dokumen'=>'#6f42c1'][$i['jenis']]??'#888';
        ?>
        <div class="col-md-6 col-lg-4">
        <div class="content-card h-100" style="border-top:2px solid <?=$jCol?>">
          <div style="display:flex;align-items:center;gap:.75rem;margin-bottom:1rem">
            <img src="<?=getPegawaiImage($i['gambar'])?>" style="width:40px;height:40px;border-radius:50%;object-fit:cover;border:2px solid <?=$i['warna']??'#888'?>44">
            <div>
              <div style="font-size:.85rem;font-weight:600;color:#fff"><?=htmlspecialchars($i['nama_pegawai'])?></div>
              <div style="font-size:.7rem;color:#555">
                <?php if($i['tarikh']): ?>
                  <i class="far fa-calendar-alt me-1"></i><?=date('d/m/Y', strtotime($i['tarikh']))?> • 
                <?php endif; ?>
                <?=timeAgo($i['created_at'])?>
              </div>
            </div>
            <span style="margin-left:auto;background:<?=$jCol?>22;color:<?=$jCol?>;border-radius:6px;padding:.2rem .5rem;font-size:.7rem;font-weight:600"><?=ucfirst($i['jenis'])?></span>
          </div>
          <h3 style="font-size:.95rem;font-weight:700;color:#fff;margin-bottom:.5rem"><?=htmlspecialchars($i['tajuk'])?></h3>
          <p style="font-size:.82rem;color:#666;line-height:1.6;margin:0"><?=nl2br(htmlspecialchars(substr($i['kandungan']??'',0,150)))?></p>
          <?php if($i['lampiran']): 
            $ext = strtolower(pathinfo($i['lampiran'], PATHINFO_EXTENSION));
            if(in_array($ext, ['jpg','jpeg','png','gif','webp'])): ?>
              <div style="margin-top:1rem"><a href="<?=UPLOAD_URL.'documents/'.$i['lampiran']?>" target="_blank"><img src="<?=UPLOAD_URL.'documents/'.$i['lampiran']?>" style="width:100%;max-height:200px;object-fit:contain;border-radius:8px;background:rgba(0,0,0,0.2)"></a></div>
            <?php else: ?>
              <div style="margin-top:.75rem"><a href="<?=UPLOAD_URL.'documents/'.$i['lampiran']?>" target="_blank" class="btn btn-sm" style="background:rgba(255,255,255,0.05);border:1px solid rgba(255,255,255,0.08);color:#ccc;border-radius:8px;font-size:.75rem"><i class="fas fa-paperclip me-1"></i>Lampiran (<?=$ext?>)</a></div>
            <?php endif; 
          endif; ?>
        </div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
    <?php foreach($units as $u): ?>
    <div class="tab-pane fade" id="info_pub_<?=$u['id']?>">
      <div class="row g-4 justify-content-center">
      <?php if(empty($infosByUnit[$u['id']])): ?>
        <div class="col-12 text-center py-4" style="color:#555"><p>Tiada informasi terkini</p></div>
      <?php else: ?>
        <?php foreach($infosByUnit[$u['id']] as $i): 
          $jCol=['umum'=>'#888','pengumuman'=>'#0d6efd','pencapaian'=>'#198754','aktiviti'=>'#ffc107','dokumen'=>'#6f42c1'][$i['jenis']]??'#888';
        ?>
        <div class="col-md-6 col-lg-4">
        <div class="content-card h-100" style="border-top:2px solid <?=$jCol?>">
          <div style="display:flex;align-items:center;gap:.75rem;margin-bottom:1rem">
            <img src="<?=getPegawaiImage($i['gambar'])?>" style="width:40px;height:40px;border-radius:50%;object-fit:cover;border:2px solid <?=$i['warna']??'#888'?>44">
            <div>
              <div style="font-size:.85rem;font-weight:600;color:#fff"><?=htmlspecialchars($i['nama_pegawai'])?></div>
              <div style="font-size:.7rem;color:#555">
                <?php if($i['tarikh']): ?>
                  <i class="far fa-calendar-alt me-1"></i><?=date('d/m/Y', strtotime($i['tarikh']))?> • 
                <?php endif; ?>
                <?=timeAgo($i['created_at'])?>
              </div>
            </div>
            <span style="margin-left:auto;background:<?=$jCol?>22;color:<?=$jCol?>;border-radius:6px;padding:.2rem .5rem;font-size:.7rem;font-weight:600"><?=ucfirst($i['jenis'])?></span>
          </div>
          <h3 style="font-size:.95rem;font-weight:700;color:#fff;margin-bottom:.5rem"><?=htmlspecialchars($i['tajuk'])?></h3>
          <p style="font-size:.82rem;color:#666;line-height:1.6;margin:0"><?=nl2br(htmlspecialchars(substr($i['kandungan']??'',0,150)))?></p>
          <?php if($i['lampiran']): 
            $ext = strtolower(pathinfo($i['lampiran'], PATHINFO_EXTENSION));
            if(in_array($ext, ['jpg','jpeg','png','gif','webp'])): ?>
              <div style="margin-top:1rem"><a href="<?=UPLOAD_URL.'documents/'.$i['lampiran']?>" target="_blank"><img src="<?=UPLOAD_URL.'documents/'.$i['lampiran']?>" style="width:100%;max-height:200px;object-fit:contain;border-radius:8px;background:rgba(0,0,0,0.2)"></a></div>
            <?php else: ?>
              <div style="margin-top:.75rem"><a href="<?=UPLOAD_URL.'documents/'.$i['lampiran']?>" target="_blank" class="btn btn-sm" style="background:rgba(255,255,255,0.05);border:1px solid rgba(255,255,255,0.08);color:#ccc;border-radius:8px;font-size:.75rem"><i class="fas fa-paperclip me-1"></i>Lampiran (<?=$ext?>)</a></div>
            <?php endif; 
          endif; ?>
        </div>
        </div>
        <?php endforeach; ?>
      <?php endif; ?>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
</div>
</section>
<?php endif; ?>



<!-- FOOTER -->
<footer style="background:rgba(0,0,0,0.4);border-top:1px solid rgba(255,255,255,0.04);padding:2rem 0;margin-top:2rem">
<div class="container-fluid px-4 text-center">
  <div style="display:flex;align-items:center;justify-content:center;margin-bottom:.5rem">
    <?=getSektorLogo('normal')?>
  </div>
  <div style="font-size:.8rem;color:#444;margin-bottom:.5rem"><?=htmlspecialchars(getSektorData()['nama_sektor']??'Sektor Pembangunan Murid')?></div>
  <div style="font-size:.75rem;color:#333">© <?=date('Y')?> Hak Cipta Terpelihara</div>
</div>
</footer>

<script>
// FullCalendar Public
let publicCalendar;
document.addEventListener('DOMContentLoaded', function() {
  const calEl = document.getElementById('publicCalendar');
  if (calEl) {
    publicCalendar = new FullCalendar.Calendar(calEl, {
      initialView: 'dayGridMonth',
      locale: 'ms',
      headerToolbar: { left: 'prev,next today', center: 'title', right: '' },
      buttonText: { today: 'Hari Ini' },
      events: function(info, success, fail) {
        fetch('modules/takwim/ajax_events.php?start=' + info.startStr + '&end=' + info.endStr)
          .then(r => r.json())
          .then(data => success(data))
          .catch(() => fail());
      },
      datesSet: function(info) {
        updatePublicEventList(info.start, info.end);
        const title = info.view.title;
        document.getElementById('listMonthTitle').textContent = 'Aktiviti: ' + title;
      },
      eventClick: function(info) {
        showPublicEventDetails(info.event);
      }
    });
    publicCalendar.render();
  }
});

function showPublicEventDetails(e) {
  const dateOptions = { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' };
  const dateStr = e.start.toLocaleDateString('ms-MY', dateOptions);
  const timeStr = e.allDay ? 'Sepanjang Hari' : e.start.toLocaleTimeString('ms-MY', {hour:'2-digit', minute:'2-digit'});
  
  Swal.fire({
    title: `<div style="font-weight:700;color:#fff;margin-bottom:10px">${e.title}</div>`,
    html: `<div style="text-align:left;font-size:.85rem;background:rgba(255,255,255,0.03);padding:1.25rem;border-radius:12px;border:1px solid rgba(255,255,255,0.05)">
      <div class="row g-3">
        <div class="col-6"><b style="color:#cc0001;display:block;font-size:.65rem;text-transform:uppercase;margin-bottom:3px">Tarikh</b><span style="color:#e0e0e0">${dateStr}</span></div>
        <div class="col-6"><b style="color:#cc0001;display:block;font-size:.65rem;text-transform:uppercase;margin-bottom:3px">Masa</b><span style="color:#e0e0e0">${timeStr}</span></div>
        <div class="col-12"><b style="color:#cc0001;display:block;font-size:.65rem;text-transform:uppercase;margin-bottom:3px">Unit</b><span style="color:#e0e0e0">${e.extendedProps.nama_unit||'-'}</span></div>
        <div class="col-12"><b style="color:#cc0001;display:block;font-size:.65rem;text-transform:uppercase;margin-bottom:3px">Tempat</b><span style="color:#e0e0e0">${e.extendedProps.tempat||'-'}</span></div>
        <div class="col-12"><b style="color:#cc0001;display:block;font-size:.65rem;text-transform:uppercase;margin-bottom:3px">Catatan</b><span style="color:#e0e0e0">${e.extendedProps.deskripsi||'-'}</span></div>
      </div>
    </div>`,
    confirmButtonText: 'Tutup',
    confirmButtonColor: '#333',
    background: '#0f0f1a', color: '#e0e0e0'
  });
}

function updatePublicEventList(start, end) {
  const listEl = document.getElementById('publicEventList');
  const countEl = document.getElementById('listEventCount');
  if (!listEl) return;
  
  listEl.innerHTML = '<div style="text-align:center;padding:3rem;color:#555"><div class="spinner-border text-primary spinner-border-sm me-2"></div>Memuatkan...</div>';
  
  const formatDateLocal = (d) => {
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };

  fetch('modules/takwim/ajax_events.php?start=' + formatDateLocal(start) + '&end=' + formatDateLocal(end))
    .then(r => r.json())
    .then(events => {
      if (events.length === 0) {
        listEl.innerHTML = '<div style="text-align:center;padding:3.5rem 1rem;color:#555"><i class="fas fa-calendar-times fa-3x mb-3" style="opacity:0.2"></i><p style="font-size:.9rem">Tiada aktiviti untuk bulan ini.</p></div>';
        countEl.textContent = '0 AKTIVITI';
        return;
      }
      
      countEl.textContent = events.length + ' AKTIVITI';
      let html = '';
      events.sort((a,b) => new Date(a.start) - new Date(b.start));
      
      events.forEach(e => {
        const d = new Date(e.start);
        const day = d.getDate();
        const month = d.toLocaleDateString('ms-MY', { month: 'short' }).toUpperCase();
        const col = e.backgroundColor || '#cc0001';
        
        html += `
          <div class="public-event-item" onclick="viewEventDetails('${e.id}')" style="display:flex;gap:1rem;padding:1rem;background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.05);border-radius:16px;margin-bottom:1rem;cursor:pointer;transition:all .3s;border-left:3px solid ${col}">
            <div style="min-width:48px;height:48px;background:${col}22;border:1px solid ${col}44;border-radius:12px;display:flex;flex-direction:column;align-items:center;justify-content:center;flex-shrink:0">
              <span style="font-size:1.1rem;font-weight:800;color:${col};line-height:1">${day}</span>
              <span style="font-size:.55rem;color:#555;font-weight:700">${month}</span>
            </div>
            <div style="min-width:0;flex:1">
              <div style="font-size:.9rem;font-weight:700;color:#fff;margin-bottom:.2rem;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">${e.title}</div>
              <div style="font-size:.75rem;color:#555"><i class="fas fa-map-marker-alt me-1" style="width:12px"></i>${e.extendedProps.tempat || 'N/A'}</div>
              <div style="display:flex;align-items:center;gap:1rem;margin-top:.4rem">
                <span style="font-size:.7rem;color:#444"><i class="fas fa-clock me-1"></i>${e.allDay ? 'Sepanjang Hari' : new Date(e.start).toLocaleTimeString('ms-MY', {hour:'2-digit', minute:'2-digit'})}</span>
                <span style="font-size:.7rem;color:${col};font-weight:600"><i class="fas fa-tag me-1"></i>${e.extendedProps.nama_unit || 'Umum'}</span>
              </div>
            </div>
          </div>
        `;
      });
      listEl.innerHTML = html;
      
      // Add hover effect via CSS
      const style = document.createElement('style');
      style.textContent = '.public-event-item:hover { background: rgba(255,255,255,0.06) !important; transform: translateX(5px); border-color: rgba(255,255,255,0.1) !important; }';
      document.head.appendChild(style);
    });
}

function viewEventDetails(id) {
  const e = publicCalendar.getEventById(id);
  if (e) {
    showPublicEventDetails(e);
  }
}

function filterPegawai(){
  const q=document.getElementById('publicSearch').value.toLowerCase();
  const activeUnit=document.querySelector('.unit-tab.active')?.dataset.unit||'all';
  let visibleCount=0;
  document.querySelectorAll('.pegawai-card').forEach(card=>{
    const nm=card.dataset.nama||'';
    const un=card.dataset.unit||'';
    const matchQ=!q||nm.includes(q);
    const matchU=activeUnit==='all'||un===activeUnit;
    card.style.display=(matchQ&&matchU)?'':'none';
    if(matchQ&&matchU)visibleCount++;
  });
  document.querySelectorAll('.unit-section').forEach(sec=>{
    const un=sec.dataset.unitId;
    const visible=activeUnit==='all'||un===activeUnit;
    const hasVisible=[...sec.querySelectorAll('.pegawai-card')].some(c=>c.style.display!=='none');
    sec.style.display=(visible&&hasVisible)?'':'none';
  });
  document.getElementById('noResult').style.display=visibleCount===0?'block':'none';
}
document.querySelectorAll('.unit-tab').forEach(btn=>{
  btn.addEventListener('click',function(){
    document.querySelectorAll('.unit-tab').forEach(b=>{b.classList.remove('active');b.style.background=b.dataset.unit==='all'?'rgba(255,255,255,0.05)':b.style.background.replace('0.15','0.07');b.style.color='#888';});
    this.classList.add('active');this.style.color='#fff';
    filterPegawai();
  });
});
// Smooth scroll for nav
document.querySelectorAll('a[href^="#"]').forEach(a=>{a.addEventListener('click',function(e){e.preventDefault();const t=document.querySelector(this.getAttribute('href'));if(t)t.scrollIntoView({behavior:'smooth',block:'start'});});});
</script>
<?php
}
require_once __DIR__.'/templates/footer.php';
