<?php
require_once "db.php";
session_start();

// Fetch latest posts
$stmt = $pdo->query("
    SELECT id, title, thumbnail_path, type, nsfw 
    FROM posts 
    ORDER BY id DESC
");
$posts = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Gallery</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<script src="https://cdn.tailwindcss.com"></script>

<style>
  .nsfw-blur {
    filter: blur(12px);
    transition: 0.2s;
  }
  .nsfw-blur:hover {
    filter: blur(0);
  }
</style>
</head>

<body class="bg-slate-100 text-slate-900">

<header class="bg-white border-b border-slate-200 sticky top-0 z-20">
  <div class="max-w-5xl mx-auto px-4 py-4 flex justify-between items-center">
    <h1 class="text-xl font-semibold">Gallery</h1>
    <a href="upload.php" class="px-4 py-2 bg-teal-600 text-white rounded-lg text-sm hover:bg-teal-700">
      Upload
    </a>
  </div>
</header>

<main class="max-w-5xl mx-auto px-4 py-6">

  <!-- GRID -->
  <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">

    <?php foreach ($posts as $p): ?>
      <div 
        class="relative cursor-pointer group"
        onclick="openModal(<?= $p['id'] ?>)"
      >

        <!-- Thumbnail -->
        <img 
          src="<?= htmlspecialchars($p['thumbnail_path']) ?>" 
          class="w-full h-auto rounded-lg shadow <?php if ($p['nsfw']) echo 'nsfw-blur'; ?>"
        >

        <!-- Video badge -->
        <?php if ($p['type'] === 'video'): ?>
          <span class="absolute bottom-2 right-2 bg-black/70 text-white text-xs px-2 py-1 rounded">
            VIDEO
          </span>
        <?php endif; ?>

      </div>
    <?php endforeach; ?>

  </div>

</main>

<!-- MODAL (empty for now — FILE 4 will fill this) -->
<div id="modal" class="hidden fixed inset-0 bg-black/80 backdrop-blur flex items-center justify-center p-4 z-50">
  <div id="modalContent" class="bg-white rounded-lg max-w-3xl w-full p-4 relative">
    <button onclick="closeModal()" class="absolute top-2 right-2 text-black text-xl">&times;</button>
    <div id="modalBody">Loading...</div>
  </div>
</div>

<script>
function openModal(id) {
  const modal = document.getElementById("modal");
  const body  = document.getElementById("modalBody");

  modal.classList.remove("hidden");
  body.innerHTML = "Loading...";

  fetch("api/get_post.php?id=" + id)
    .then(res => res.text())
    .then(html => body.innerHTML = html);
}

function closeModal() {
  document.getElementById("modal").classList.add("hidden");
}
</script>

</body>
</html>