<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>GKPB-MDC Jombang</title>
  <link rel="icon" href="asecet/icon.png" type="image/x-icon">

  <!-- Font Awesome -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
  <!-- Bootstrap CSS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <!-- AOS -->
  <link href="https://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet">

<style>
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800;900&display=swap');

body{
  font-family:'Poppins',sans-serif;
  background:#05070f;
  padding:10px;
  display:flex;
  flex-direction:column;
  min-height:100vh;
  margin:0;
  overflow-x:hidden;
  color:#fff;
}

/* Overlay */
.overlay{
  position:fixed;
  inset:0;
  background:rgba(0,0,0,.35);
  opacity:0;
  visibility:hidden;
  transition:.35s;
  z-index:1000;
}
.overlay.active{opacity:1;visibility:visible}

/* Sidebar */
.sidebar{
  position:fixed;
  top:0;left:0;
  width:270px;height:100vh;
  background:rgba(255,255,255,.15);
  backdrop-filter:blur(20px);
  padding-top:70px;
  z-index:1100;
  border-top-right-radius:30px;
  border-bottom-right-radius:30px;
  box-shadow:4px 0 20px rgba(0,0,0,.25);
  transform:translateX(-100%);
  transition:.35s cubic-bezier(.25,1,.3,1);
}
.sidebar.active{transform:translateX(0)}
.sidebar ul{list-style:none;padding:0;margin:0}
.sidebar ul li a{
  display:flex;align-items:center;
  padding:14px 20px;margin:6px 12px;
  border-radius:12px;
  color:white;
  text-decoration:none;font-size:16px;
}
.sidebar ul li a:hover{background:rgba(255,255,255,.25)}
.sidebar ul li a.active{
  background:rgba(0,123,255,.35);
  box-shadow:inset 0 0 8px rgba(0,123,255,.6);
}
.sidebar ul li i{margin-right:14px;font-size:20px;width:25px}

/* Navbar */
#navbar-top{position:sticky;top:10px;z-index:999}
.menu-btn{font-size:24px;cursor:pointer;margin-right:15px}

/* Card */
.glass-card{
  backdrop-filter:blur(20px);
  background:rgba(255,255,255,.25);
  border-radius:20px;
  padding:22px;
  max-width:420px;
  margin:20px auto;
}

/* CYBER */
#particles{position:fixed;inset:0;z-index:-5}

.cyber-grid{
  position:fixed;inset:0;
  background:
    linear-gradient(transparent 95%,rgba(0,245,255,.35) 100%),
    linear-gradient(90deg,transparent 95%,rgba(0,245,255,.25) 100%);
  background-size:70px 70px;
  opacity:.22;
  z-index:-4;
  transform:perspective(900px) rotateX(60deg);
  animation:gridMove 22s linear infinite;
}
@keyframes gridMove{
  from{background-position:0 0,0 0}
  to{background-position:0 900px,900px 0}
}

.glow-bg{
  position:fixed;inset:0;
  background:
    radial-gradient(circle at 20% 15%,rgba(0,245,255,.16),transparent 45%),
    radial-gradient(circle at 80% 30%,rgba(168,85,247,.14),transparent 45%);
  z-index:-3;
}

.scanline{
  pointer-events:none;
  position:fixed;inset:0;
  background:linear-gradient(
    to bottom,
    rgba(255,255,255,.05) 1px,
    transparent 3px
  );
  background-size:100% 6px;
  opacity:.12;
  z-index:3000;
}

.wrap{
  display:flex;
  flex-direction:column;
}

.wrap iframe{
  flex:1;
  width:100%;
  border:0;
}

/* Performance boost */
canvas,
.cyber-grid,
.glow-bg,
.scanline{
  will-change: transform;
}

iframe{
  transform:translateZ(0);
}

/* jangan intercept touch */
#particles{
  pointer-events:none;
}
</style>
</head>

<body>

<canvas id="particles"></canvas>
<div class="cyber-grid"></div>
<div class="glow-bg"></div>
<div class="scanline"></div>

<div class="overlay" id="overlay"></div>

<div class="sidebar" id="sidebar">
<ul>
<li><a href="/id"><i class="fas fa-th-large"></i> Home</a></li>
<li><a href="/id/ibadah"><i class="fa-solid fa-person-praying"></i> ppt sabtu</a></li>
<li><a href="/id/warta"><i class="fa-solid fa-newspaper"></i> jadwal pelayanan</a></li>
<li><a href="/id/alkitab"><i class="fa-solid fa-book-bible"></i> Alkitab</a></li>
</ul>
</div>

<div id="navbar-top" class="d-flex align-items-center mb-3">
<span class="menu-btn" id="menu-btn"><i class="fas fa-bars"></i></span>
<h5 class="text-white m-0">Youth MDC</h5>
</div>

  <div class="glass-card">
    <?php
    // user_ppt.php — Fullscreen Google Viewer, 1 dokumen terbaru (PPT/PPTX/PDF)
    // Default sumber (bisa override via ?src=URL)
    $src = isset($_GET['src']) ? $_GET['src'] : 'https://mdcjombang.id/siap/youth/ppt/list_ppt.php';
    $timeoutSec = 2; // timeout ambil data

    // ---- Compat polyfills untuk PHP lama ----
    if (!function_exists('str_ends_with')) {
      function str_ends_with($haystack, $needle) {
        $len = strlen($needle);
        if ($len === 0) return true;
        return substr($haystack, -$len) === $needle;
      }
    }

    // ---- Helper ----
    function is_supported($u) {
      $path = parse_url($u, PHP_URL_PATH);
      $u = strtolower($path !== null ? $path : $u);
      return str_ends_with($u, '.ppt') || str_ends_with($u, '.pptx') || str_ends_with($u, '.pdf');
    }
    function first_non_empty() {
      $args = func_get_args();
      foreach ($args as $v) {
        $t = trim((string)(isset($v) ? $v : ''));
        if ($t !== '') return $t;
      }
      return '';
    }
    function to_abs_url($u) {
      if (!$u) return $u;
      $parts = @parse_url($u);
      if ($parts && !empty($parts['scheme'])) return $u; // sudah absolut
      $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
      $host   = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost';
      $base   = rtrim(dirname(isset($_SERVER['SCRIPT_NAME']) ? $_SERVER['SCRIPT_NAME'] : '/'), '/');
      return $scheme . '://' . $host . ($base ? $base : '') . '/' . ltrim($u, '/');
    }
    function normalize_list($arr) {
      if (!is_array($arr)) return array();
      $out = array();
      foreach ($arr as $it) {
        $url = first_non_empty(
          isset($it['url']) ? $it['url'] : null,
          isset($it['link']) ? $it['link'] : null,
          isset($it['file']) ? $it['file'] : null,
          isset($it['gambar']) ? $it['gambar'] : null
        );
        if (!$url || !is_supported($url)) continue;
        $out[] = array(
          'title' => first_non_empty(
            isset($it['title']) ? $it['title'] : null,
            isset($it['judul']) ? $it['judul'] : null,
            isset($it['nama']) ? $it['nama'] : null,
            'Tanpa Judul'
          ),
          'url' => $url,
          'at'  => first_non_empty(
            isset($it['uploaded_at']) ? $it['uploaded_at'] : null,
            isset($it['tanggal']) ? $it['tanggal'] : null,
            ''
          )
        );
      }
      usort($out, function($a, $b) {
        $ta = strtotime(isset($a['at']) ? $a['at'] : '0');
        $tb = strtotime(isset($b['at']) ? $b['at'] : '0');
        if ($tb == $ta) return 0;
        return ($tb < $ta) ? -1 : 1;
      });
      return $out;
    }

    // ---- Fetch JSON: cURL → fallback stream ----
    function fetch_json_text($url, $timeoutSec) {
      if (function_exists('curl_init')) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeoutSec);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeoutSec);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome Safari');
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        $body = curl_exec($ch);
        $http = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($body !== false && $http >= 200 && $http < 300) {
          return $body;
        }
      }
      // fallback stream
      $ctx = stream_context_create(array(
        'http' => array(
          'timeout' => $timeoutSec,
          'header'  => "User-Agent: Mozilla/5.0\r\nAccept: application/json\r\n"
        ),
        'ssl' => array(
          'verify_peer' => true,
          'verify_peer_name' => true,
        )
      ));
      $raw = @file_get_contents($url, false, $ctx);
      return $raw !== false ? $raw : null;
    }

    // ---- Ambil data (server-side); kalau gagal, JS akan coba fetch di klien ----
    $latest = null;
    $viewerSrc = '';
    $titleSafe = 'Dokumen Terbaru';
    $directUrl = '';
    $serverFailed = false;

    $raw = fetch_json_text($src, $timeoutSec);
    if ($raw !== null) {
      $json = @json_decode($raw, true);
      $list = normalize_list(is_array($json) ? $json : array());
      if (!empty($list)) {
        $latest = $list[0];
        $abs = to_abs_url($latest['url']);
        $buster = (strpos($abs, '?') === false ? '?t=' : '&t=') . time(); // anti-cache
        $viewerSrc = 'https://docs.google.com/gview?embedded=true&url=' . rawurlencode($abs . $buster);
        $directUrl = htmlspecialchars($abs, ENT_QUOTES, 'UTF-8');
        $titleSafe = htmlspecialchars($latest['title'], ENT_QUOTES, 'UTF-8');
      } else {
        $serverFailed = true;
      }
    } else {
      $serverFailed = true;
    }
    ?>

    <!-- Area viewer -->
    <div class="wrap" style="flex:1; min-height:75vh; margin-top:12px;">
      <?php if ($viewerSrc): ?>
        <iframe
          id="frame"
          title="Google Viewer"
          src="<?php echo htmlspecialchars($viewerSrc, ENT_QUOTES, 'UTF-8'); ?>"
          allow="fullscreen"
          referrerpolicy="no-referrer-when-downgrade">
        </iframe>
      <?php else: ?>
        <div class="empty" id="fallbackBox">
          <h2>Memuat dokumen…</h2>
          <p id="fallbackMsg">Server tidak bisa ambil data, mencoba via browser.</p>
        </div>
        <iframe id="frame" style="display:none" title="Google Viewer"></iframe>
        <script>
          (function(){
            var SRC = <?php echo json_encode($src); ?>;
            var fbBox = document.getElementById('fallbackBox');
            var fbMsg = document.getElementById('fallbackMsg');
            var frame = document.getElementById('frame');

            function isSupported(u){
              var p = (u||'').split('?')[0].toLowerCase();
              return p.endsWith('.ppt') || p.endsWith('.pptx') || p.endsWith('.pdf');
            }
            function firstNon(){
              for (var i=0;i<arguments.length;i++){
                var v = arguments[i];
                if (v !== undefined && v !== null && String(v).trim() !== '') return String(v).trim();
              }
              return '';
            }
            function normalize(arr){
              if (!Array.isArray(arr)) return [];
              var out = [];
              arr.forEach(function(it){
                var url = firstNon(it.url, it.link, it.file, it.gambar);
                if (!url || !isSupported(url)) return;
                out.push({
                  title: firstNon(it.title, it.judul, it.nama, 'Tanpa Judul'),
                  url: url,
                  at: firstNon(it.uploaded_at, it.tanggal, '')
                });
              });
              out.sort(function(a,b){
                return new Date(b.at||0) - new Date(a.at||0);
              });
              return out;
            }
            function toAbs(u){
              try { return new URL(u, location.href).href; } catch(e){ return u; }
            }
            function gview(u){
              var abs = toAbs(u);
              var bust = (abs.indexOf('?')>-1 ? '&' : '?') + 't=' + Date.now();
              return 'https://docs.google.com/gview?embedded=true&url=' + encodeURIComponent(abs + bust);
            }

            fetch(SRC, {cache:'no-store', mode:'cors'})
              .then(function(r){ return r.text().then(function(t){ return {ok:r.ok, text:t, status:r.status}; }); })
              .then(function(res){
                if (!res.ok) throw new Error('HTTP '+res.status);
                var data;
                try { data = JSON.parse(res.text); }
                catch(e){ throw new Error('JSON invalid'); }
                var list = normalize(data);
                if (!list.length) throw new Error('Tidak ada .ppt/.pptx/.pdf');
                var latest = list[0];
                frame.src = gview(latest.url);
                frame.style.display = 'block';
                if (fbBox) fbBox.style.display = 'none';
                document.title = latest.title || 'Dokumen Terbaru';
              })
              .catch(function(err){
                if (fbMsg) fbMsg.textContent = 'Gagal memuat via browser: ' + (err && err.message ? err.message : String(err));
              });
          })();
        </script>
      <?php endif; ?>
    </div>
  </div>

<footer style="text-align:center;font-size:12px;opacity:.9">
© 2025 GKPB MDC Jombang
</footer>

<script>
const menuBtn=document.getElementById("menu-btn");
const sidebar=document.getElementById("sidebar");
const overlay=document.getElementById("overlay");

menuBtn.onclick=()=>{
  sidebar.classList.toggle("active");
  overlay.classList.toggle("active");
};

overlay.onclick=()=>{
  sidebar.classList.remove("active");
  overlay.classList.remove("active");
};

/* PARTICLES */
const c=document.getElementById("particles");
const ctx=c.getContext("2d");

function resize(){
  c.width=innerWidth;
  c.height=innerHeight;
}
resize();
addEventListener("resize",resize);

let dots=[];
for(let i=0;i<45;i++){{
  dots.push({
    x:Math.random()*innerWidth,
    y:Math.random()*innerHeight,
    vx:(Math.random()-.5)*.5,
    vy:(Math.random()-.5)*.5
  });
}

(function anim(){
  ctx.clearRect(0,0,c.width,c.height);

  dots.forEach(d=>{
    d.x+=d.vx;
    d.y+=d.vy;

    if(d.x<0||d.x>c.width)d.vx*=-1;
    if(d.y<0||d.y>c.height)d.vy*=-1;

    ctx.fillStyle="rgba(0,245,255,.45)";
    ctx.beginPath();
    ctx.arc(d.x,d.y,2,0,Math.PI*2);
    ctx.fill();
  });

  requestAnimationFrame(anim);
})();

let scrolling=false;

window.addEventListener("scroll",()=>{
  scrolling=true;
  clearTimeout(window.__st);
  window.__st=setTimeout(()=>scrolling=false,120);
},{passive:true});

(function anim(){
  if(!scrolling){
    ctx.clearRect(0,0,c.width,c.height);

    dots.forEach(d=>{
      d.x+=d.vx;
      d.y+=d.vy;

      if(d.x<0||d.x>c.width)d.vx*=-1;
      if(d.y<0||d.y>c.height)d.vy*=-1;

      ctx.fillStyle="rgba(0,245,255,.45)";
      ctx.beginPath();
      ctx.arc(d.x,d.y,2,0,Math.PI*2);
      ctx.fill();
    });
  }
  requestAnimationFrame(anim);
})();
</script>

</body>
</html>