<?php
require __DIR__ . '/auth.php';  // load fungsi auth
portal_require_login();         // WAJIB: cek sudah login atau belum
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width,initial-scale=1"/>
  <title>Keperawatan RS BaliMéd</title>
  <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700&display=swap" rel="stylesheet">
  <script src="https://cdn.tailwindcss.com"></script>
  <style>
    :root{--bar:64px}
    html,body{height:100%;margin:0;font-family:Poppins,system-ui,sans-serif;background:#f3f4f6}
    /* overlay */
    #overlay{position:fixed;inset:0;background:#0b1220cc;backdrop-filter:saturate(120%) blur(2px);display:none;z-index:50}
    #panel{position:absolute;inset:24px;display:flex;flex-direction:column;background:#fff;border-radius:16px;box-shadow:0 20px 60px rgba(0,0,0,.25)}
    #frame{width:100%;height:calc(100% - var(--bar));border:0}
    .btn{background:#2563eb;color:#fff}
    .btn-ghost{background:#eef2ff;color:#1e40af}
    .card{background:#fff;border-radius:16px;box-shadow:0 8px 24px rgba(2,6,23,.06);padding:18px;display:flex;gap:16px;align-items:center;transition:.15s transform,.15s box-shadow;cursor:pointer}
    .card:hover{transform:translateY(-2px);box-shadow:0 14px 30px rgba(2,6,23,.10)}
    .icon{width:56px;height:56px;border-radius:14px;display:grid;place-items:center;font-size:28px}
    .badge{font-size:11px;color:#64748b}
  </style>
</head>
<body>

  <!-- Topbar -->
  <header class="bg-white border-b">
    <div class="max-w-7xl mx-auto px-4 py-3 flex items-center justify-between">
      <div class="flex items-center gap-3">
        <img src="https://balimedhospital.co.id/wp-content/uploads/elementor/thumbs/logo-dark-o9cm6tnx14hcrnest1hge1pwnqj0yaumij7qohadlm.png" class="h-9" alt="BaliMed">
        <h1 class="text-lg md:text-xl font-semibold">Keperawatan RS BaliMéd</h1>
      </div>

      <!-- kanan: salam + tombol -->
      <div class="hidden md:flex items-center gap-2">
        <span class="text-sm text-slate-500">Hai, <?php echo htmlspecialchars($_SESSION['user'] ?? ''); ?></span>
        <a class="btn-ghost px-4 py-2 rounded-lg text-sm" href="?logout=1">Logout</a>
        <a class="btn px-4 py-2 rounded-lg text-sm" href="#" onclick="location.reload()">Refresh</a>
      </div>
    </div>
  </header>

  <!-- Hero -->
  <section class="max-w-7xl mx-auto p-4 pt-6">
    <div class="bg-white rounded-2xl shadow p-6 md:p-10 text-center">
      <h2 class="text-3xl md:text-5xl font-extrabold text-slate-800">Rumah Sakit BaliMéd Denpasar</h2>
      <p class="text-slate-500 mt-3">Akses cepat ke semua aplikasi Keperawatan.</p>

      <!-- Search -->
      <div class="mt-6 flex items-center gap-3 justify-center">
        <input id="q" type="search" placeholder="Cari aplikasi"
               class="w-full max-w-2xl px-4 py-3 rounded-xl border outline-none focus:ring-2 focus:ring-blue-500">
        <button id="btnCari" class="btn px-5 py-3 rounded-xl">Cari</button>
      </div>
    </div>
  </section>

  <!-- Grid -->
  <main class="max-w-7xl mx-auto p-4">
    <div id="grid" class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3"></div>
    <p id="empty" class="text-center text-slate-500 mt-6 hidden">Tidak ada hasil.</p>
  </main>

  <!-- Overlay (embed) -->
  <div id="overlay">
    <div id="panel">
      <div class="h-[var(--bar)] px-4 md:px-6 border-b flex items-center justify-between">
        <div class="min-w-0">
          <div class="text-xs badge" id="ovlSub">Aplikasi</div>
          <h3 class="text-lg md:text-xl font-semibold truncate" id="ovlTitle">Memuat…</h3>
        </div>
        <div class="flex items-center gap-2">
          <a id="openTab" target="_blank" class="btn-ghost rounded-lg px-3 py-2 text-sm" href="#">Buka di Tab Baru</a>
          <button id="close" class="btn rounded-lg px-3 py-2 text-sm">Tutup</button>
        </div>
      </div>
      <iframe id="frame" allow="clipboard-read; clipboard-write"></iframe>
    </div>
  </div>

  <script>
    // =========================
    // 1) DAFTAR APLIKASI
    // =========================
    const APPS = [
      /* === SPO (baru) === */
      {name:"Sosialisasi SPO – Admin", desc:"Upload & kelola SPO", icon:"🧩", color:"#e0e7ff",
        url:"https://keperawatanrsbalimeddenpasar.org/spo/admin.php", embed:true},
      {name:"Daftar SPO", desc:"Baca SPO & isi pernyataan", icon:"📚", color:"#dcfce7",
        url:"https://keperawatanrsbalimeddenpasar.org/spo/index.php", embed:true},
      {name:"Rekap Respon SPO", desc:"Tabel & grafik per unit", icon:"📊", color:"#fef9c3",
        url:"https://keperawatanrsbalimeddenpasar.org/spo/responses.php", embed:true},

      /* === Aplikasi lain (sebelumnya) === */
      {name:"Absensi Digital", desc:"Absensi", icon:"📊", color:"#eff6ff",
        url:"https://script.google.com/macros/s/AKfycbw6ynY6Ze0JAc6dkD-piTcqzL_TMKFNqeH_wzRQYwpkol-Gc-mWsaGOrAurwrcnii3r/exec", embed:true},
      {name:"Daftar Absensi Digital", desc:"Hasil Absen", icon:"📝", color:"#e0f2fe",
        url:"https://script.google.com/macros/s/AKfycbxBSiDCWBTx-cqO2Z8EVZVflqpxMzENF_dQFf5Wxaaje79w-5NgG9vTsOt2llQceNwxFA/exec", embed:true},
      {name:"Laporan Harian Keperawatan", desc:"Laporkan Semua Masalah Unit", icon:"📦", color:"#dcfce7",
        url:"https://keperawatan-86775.web.app/", embed:true},
      {name:"Form Sosialisasi SPO", desc:"Sosialisasi", icon:"👥", color:"#ffe4e6",
        url:"https://script.google.com/macros/s/AKfycbzCmX-zAghdOd18qJTkY5IKJfH_UKMCH_YIdDqyHom0d0Ak_oPLZd9xia8QTi-mjS_B/exec", embed:true},
      {name:"Data Hasil Sosialisasi SPO", desc:"Laporan", icon:"🗓️", color:"#fef9c3",
        url:"https://script.google.com/macros/s/AKfycbzEou5Hu7NU9-V9J4PeZHLhv-HCK_wnBVxFZPnGGLEvu_uhl0rnqa1LDad8hwpnwlWz/exec", embed:true},
      {name:"Laporan Rajal & Ranap", desc:"Rajal & Ranap", icon:"📈", color:"#e9d5ff",
        url:"https://script.google.com/macros/s/AKfycbwT5eIXzpO6NPyKcrAYRi_3CY6b7fjc9YT0Cb3wdFnzeH222RQVF20q-zaJQFoNQ8yX/exec", embed:true},
      {name:"Sheet P3K", desc:"Sheet", icon:"📄", color:"#f1f5f9",
        url:"https://docs.google.com/spreadsheets/d/1miJlLNdpvjtyLZZ26cEn1jOptM5hEgsTKAFxZZdRflg/edit?gid=2114936720#gid=2114936720", embed:false},
      {name:"Standar Fokus Pasien", desc:"Akreditasi", icon:"💬", color:"#e0e7ff",
        url:"https://script.google.com/macros/s/AKfycbysVK03Wr1qXRHCMsCkhScgr0apB-RXKK4rmfInN3QlkKwKjpU-Pc7F9zELNs5BSF3L5Q/exec", embed:true},
      {name:"Jadwal P3K Perawat", desc:"Penjadwalan", icon:"🗓️", color:"#e0f2fe",
        url:"https://script.google.com/macros/s/AKfycbwoHwbBcRg9SKXiiM6ZUkqq30NySquhAz6w86UfX8Uqs3F4Iw1e0537-awwO__8mmc/exec", embed:true},
      {name:"Laporan Kegiatan Harian", desc:"Semua buat apa saja dilakukan selama bekerja", icon:"📑", color:"#ffedd5",
        url:"https://script.google.com/macros/s/AKfycbwp9-4ucTcAdmmkEGunhip95sfqPOd5SFvr8RKnCSATmRakxhPgOf6ZyTsZVGE9CzRl/exec", embed:true},
      {name:"Kumpulan SPO", desc:"Daftar SPO yg ada", icon:"📅", color:"#dbeafe",
        url:"https://script.google.com/macros/s/AKfycbyxbEka5FQAY_MVA8Kie8mm6CGd2ykgPbB7-rQu3Rau0EPomXXaLlvQHJ-NQCZdBwhf4Q/exec", embed:true},
        {name:"Manajemen Risiko", desc:"Daftar Risiko Keperawatan", icon:"📅", color:"#dbeafe",
        url:"https://script.google.com/macros/s/AKfycbwZyz7arxo2H_EVPffM1b21frCXC6IVYReElDZP4Dmf96i1BhZhj3szXZWmhY_cqEq_rA/exec", embed:true},
        {name:"Penugasan Insiden Keselamatan Pasien", desc:"Penugasan Bagi Staf yang Terkait Insiden", icon:"📅", color:"#dbeafe",
        url:"https://script.google.com/macros/s/AKfycby6h41TiPgus2PxJHFsoKqtYSke_3s5e0v4nrWInyqOmT3XGTLMp2g6dRIDxpHYoda80A/exec", embed:true},
         {name:"WOKR ORDER & KERUSAKAN", desc:"Kerusakan alat dan lain lain", icon:"📅", color:"#dbeafe",
        url:"https://script.google.com/macros/s/AKfycbx-0W2HzKSZ8aS9HN3LjklmNjhbGnDDaNJJLhOQfDy4ueRBK0vkxECRIjitMhjNYZjuUg/exec", embed:true},
        {name:"LAPORAN BULANAN KEP", desc:"Laporan include semua", icon:"📅", color:"#dbeafe",
        url:"https://script.google.com/macros/s/AKfycbza9tzWhmyZowiHWMVkfQdLGAsrPJ4ZjRGKrVXaftwdbxyoM9uISN_SDuvBWQe70IYx/exec", embed:true},
        {name:"Perencanaan Kegiatan Harian", desc:"Rencana Kegiatan & Aktivitas", icon:"📅", color:"#dbeafe",
        url:"https://script.google.com/macros/s/AKfycbza9tzWhmyZowiHWMVkfQdLGAsrPJ4ZjRGKrVXaftwdbxyoM9uISN_SDuvBWQe70IYx/exec", embed:true}
    ];

    // =========================
    // 2) RENDER GRID + SEARCH
    // =========================
    const grid = document.getElementById('grid'), empty = document.getElementById('empty');
    function render(list){
      grid.innerHTML = '';
      list.forEach(app=>{
        const card = document.createElement('button');
        card.className = 'card text-left';
        card.onclick = ()=> openApp(app);
        card.innerHTML = `
          <div class="icon" style="background:${app.color || '#eef2ff'}">${app.icon||'📦'}</div>
          <div class="min-w-0">
            <div class="text-sm text-slate-500 badge">${app.desc||'Aplikasi'}</div>
            <div class="text-lg font-semibold text-slate-800 truncate">${app.name}</div>
          </div>`;
        grid.appendChild(card);
      });
      empty.classList.toggle('hidden', list.length !== 0);
    }
    render(APPS);

    const q = document.getElementById('q');
    const doFilter = ()=>{
      const v = (q.value||'').toLowerCase().trim();
      const list = APPS.filter(a=> (a.name+a.desc).toLowerCase().includes(v));
      render(list);
    };
    q.addEventListener('input', doFilter);
    document.getElementById('btnCari').addEventListener('click', doFilter);

    // =========================
    // 3) OVERLAY / IFRAME FLOW
    // =========================
    const overlay = document.getElementById('overlay');
    const frame   = document.getElementById('frame');
    const ovlTitle= document.getElementById('ovlTitle');
    const ovlSub  = document.getElementById('ovlSub');
    const openTab = document.getElementById('openTab');
    document.getElementById('close').onclick = ()=>{ frame.src='about:blank'; overlay.style.display='none'; };
    document.addEventListener('keydown', (e)=>{ if(e.key==='Escape') document.getElementById('close').click(); });

    const FALLBACK_DELAY = 4500; // ms

    function openApp(app){
      if(!app || !app.url || app.url === '#') return alert('URL aplikasi belum diset.');
      if(app.embed){
        ovlTitle.textContent = app.name;
        ovlSub.textContent   = 'Aplikasi';
        openTab.href = app.url;
        frame.src = app.url;
        overlay.style.display = 'block';

        if (window._fbTimer) clearTimeout(window._fbTimer);
        openTab.classList.remove('ring-2','ring-blue-500','ring-offset-2');

        window._fbTimer = setTimeout(()=>{
          ovlSub.textContent = 'Tidak bisa di-embed. Klik "Buka di Tab Baru".';
          openTab.classList.add('ring-2','ring-blue-500','ring-offset-2');
        }, FALLBACK_DELAY);

        frame.addEventListener('load', ()=>{
          if (window._fbTimer) clearTimeout(window._fbTimer);
          ovlSub.textContent = 'Aplikasi';
          openTab.classList.remove('ring-2','ring-blue-500','ring-offset-2');
        }, {once:true});

      } else {
        window.open(app.url, '_blank');
      }
    }
  </script>
</body>
</html>
