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

if (!isset($_GET['id'])) {
    header("Location: index.php");
    exit;
}

$post_id  = intval($_GET['id']);
$user_id  = $_SESSION['user_id'] ?? null;
$username = $_SESSION['username'] ?? null;
$isAdmin  = ($username === "admin");
$isOver18 = $_SESSION['is_over_18'] ?? 0;

/* ---------------------------------------------------------
   FETCH POST
--------------------------------------------------------- */
$stmt = $pdo->prepare("
    SELECT p.*, u.username
    FROM posts p
    JOIN users u ON p.user_id = u.id
    WHERE p.id = ?
");
$stmt->execute([$post_id]);
$post = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$post) {
    die("Post not found.");
}

if ($post['nsfw'] == 1 && !$isOver18) {
    die("This content is restricted to 18+ users.");
}

/* ---------------------------------------------------------
   TAGS
--------------------------------------------------------- */
$tagStmt = $pdo->prepare("
    SELECT t.name
    FROM post_tags pt
    JOIN tags t ON pt.tag_id = t.id
    WHERE pt.post_id = ?
");
$tagStmt->execute([$post_id]);
$tags = $tagStmt->fetchAll(PDO::FETCH_COLUMN);

/* ---------------------------------------------------------
   COMMENTS
--------------------------------------------------------- */
$commentStmt = $pdo->prepare("
    SELECT c.*, u.username
    FROM comments c
    JOIN users u ON c.user_id = u.id
    WHERE c.post_id = ?
    ORDER BY c.id DESC
");
$commentStmt->execute([$post_id]);
$comments = $commentStmt->fetchAll(PDO::FETCH_ASSOC);

/* ---------------------------------------------------------
   RATING
--------------------------------------------------------- */
$ratingStmt = $pdo->prepare("SELECT COUNT(*) FROM ratings WHERE post_id = ?");
$ratingStmt->execute([$post_id]);
$rating_count = $ratingStmt->fetchColumn();

$hasVoted = false;
if ($user_id) {
    $voteCheck = $pdo->prepare("SELECT id FROM ratings WHERE post_id = ? AND user_id = ?");
    $voteCheck->execute([$post_id, $user_id]);
    $hasVoted = $voteCheck->fetchColumn() ? true : false;
}

/* ---------------------------------------------------------
   NEXT / PREVIOUS POSTS
--------------------------------------------------------- */
$prevStmt = $pdo->prepare("SELECT id FROM posts WHERE id < ? ORDER BY id DESC LIMIT 1");
$prevStmt->execute([$post_id]);
$prev_id = $prevStmt->fetchColumn();

$nextStmt = $pdo->prepare("SELECT id FROM posts WHERE id > ? ORDER BY id ASC LIMIT 1");
$nextStmt->execute([$post_id]);
$next_id = $nextStmt->fetchColumn();

/* ---------------------------------------------------------
   EXIF JSON (admin only)
--------------------------------------------------------- */
$exif_data = null;
if ($isAdmin && !empty($post['exif_json'])) {
    $exif_data = json_decode($post['exif_json'], true);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title><?= htmlspecialchars($post['title'] ?: 'Artwork') ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

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

  <style>
    .filter-blur { filter: blur(18px); }
  </style>
</head>

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

<header class="border-b border-slate-200 bg-white/80 backdrop-blur sticky top-0 z-20">
  <div class="max-w-4xl mx-auto px-4 py-3 flex items-center justify-between">
    <h1 class="text-lg font-semibold">Artwork</h1>
    <a href="index.php" class="text-sm text-teal-600 hover:text-teal-800">Back</a>
  </div>
</header>

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

  <!-- Navigation -->
  <div class="flex justify-between text-sm mb-2">
    <div>
      <?php if ($prev_id): ?>
        <a href="post.php?id=<?= $prev_id ?>" class="text-teal-600 hover:text-teal-800">← Previous</a>
      <?php else: ?>
        <span class="text-slate-400">← Previous</span>
      <?php endif; ?>
    </div>

    <div>
      <?php if ($next_id): ?>
        <a href="post.php?id=<?= $next_id ?>" class="text-teal-600 hover:text-teal-800">Next →</a>
      <?php else: ?>
        <span class="text-slate-400">Next →</span>
      <?php endif; ?>
    </div>
  </div>

  <!-- Media + Basic Info -->
  <section class="bg-white rounded-xl shadow-sm border border-slate-200 p-4">
    <div class="flex items-center justify-between mb-3">
      <div>
        <h2 class="text-xl font-semibold"><?= htmlspecialchars($post['title']) ?></h2>
        <p class="text-sm text-slate-500">by <?= htmlspecialchars($post['username']) ?></p>
      </div>
      <?php if ($post['nsfw']): ?>
        <span class="px-2 py-1 rounded-full bg-red-600 text-white text-xs uppercase">
          NSFW / 18+
        </span>
      <?php endif; ?>
    </div>

    <div class="bg-black rounded-lg overflow-hidden mb-4">
      <?php if ($post['type'] === 'image'): ?>
        <img src="<?= htmlspecialchars($post['file_path']) ?>"
             class="w-full max-h-[80vh] object-contain bg-black">
      <?php else: ?>
        <video src="<?= htmlspecialchars($post['file_path']) ?>"
               controls
               class="w-full max-h-[80vh] bg-black"></video>
      <?php endif; ?>
    </div>

    <p class="text-xs text-slate-500 mb-4">
      Uploaded: <?= date("M j, Y", strtotime($post['created_at'])) ?>
    </p>

    <?php if (!empty($post['description'])): ?>
      <p class="mt-2 text-sm text-slate-700 whitespace-pre-line">
        <?= nl2br(htmlspecialchars($post['description'])) ?>
      </p>
    <?php endif; ?>

    <!-- Tags -->
    <?php if (!empty($tags)): ?>
      <div class="flex flex-wrap gap-2 mt-4">
        <?php foreach ($tags as $t): ?>
          <span class="px-2 py-1 bg-teal-100 text-teal-700 rounded-full text-xs">
            #<?= htmlspecialchars($t) ?>
          </span>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>

    <!-- Rating -->
    <div class="mt-6 flex items-center gap-4">
      <div class="text-sm text-slate-600"><?= $rating_count ?> votes</div>

      <?php if ($user_id): ?>
        <?php if ($hasVoted): ?>
          <button disabled
                  class="px-3 py-1 bg-slate-300 text-slate-600 rounded-lg text-sm cursor-not-allowed">
            You voted
          </button>
        <?php else: ?>
          <form action="api/rate.php" method="POST">
            <input type="hidden" name="post_id" value="<?= $post_id ?>">
            <button class="px-3 py-1 bg-teal-600 text-white rounded-lg text-sm hover:bg-teal-700">
              Vote
            </button>
          </form>
        <?php endif; ?>
      <?php else: ?>
        <div class="text-xs text-slate-500">Login to vote</div>
      <?php endif; ?>
    </div>
  </section>

  <!-- Admin Metadata (EXIF / GPS / Region) -->
  <?php if ($isAdmin): ?>
    <section class="bg-white rounded-xl shadow-sm border border-slate-200 p-4">
      <h3 class="text-lg font-semibold mb-3">Admin Metadata</h3>

      <div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm text-slate-700">
        <div>
          <?php if (!empty($post['camera_model'])): ?>
            <div><strong>Camera:</strong> <?= htmlspecialchars($post['camera_model']) ?></div>
          <?php endif; ?>

          <?php if (!empty($post['location_region'])): ?>
            <div class="mt-2"><strong>Region:</strong> <?= htmlspecialchars($post['location_region']) ?></div>
          <?php endif; ?>
        </div>

        <div>
          <?php if (!empty($post['gps_lat']) && !empty($post['gps_lng'])): ?>
            <div><strong>GPS:</strong> <?= $post['gps_lat'] ?>, <?= $post['gps_lng'] ?></div>
            <a href="https://www.google.com/maps?q=<?= $post['gps_lat'] ?>,<?= $post['gps_lng'] ?>"
               target="_blank"
               class="text-blue-600 underline text-sm">
              View on Google Maps
            </a>
          <?php else: ?>
            <div class="text-slate-400 text-sm">No GPS data available.</div>
          <?php endif; ?>
        </div>
      </div>

      <?php if ($exif_data): ?>
        <details class="mt-4 text-xs text-slate-600">
          <summary class="cursor-pointer text-sm font-semibold text-slate-800">
            Show raw EXIF data
          </summary>
          <pre class="mt-2 bg-slate-100 p-2 rounded overflow-auto max-h-64">
<?= htmlspecialchars(json_encode($exif_data, JSON_PRETTY_PRINT)) ?>
          </pre>
        </details>
      <?php endif; ?>
    </section>
  <?php endif; ?>

  <!-- Comments -->
  <section class="bg-white rounded-xl shadow-sm border border-slate-200 p-4">
    <h3 class="text-lg font-semibold mb-4">Comments</h3>

    <?php if ($user_id): ?>
      <form action="api/comment.php" method="POST" class="mb-6">
        <input type="hidden" name="post_id" value="<?= $post_id ?>">
        <textarea name="comment" rows="3" required
                  class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-teal-400"></textarea>
        <button class="mt-2 px-3 py-1 bg-teal-600 text-white rounded-lg text-sm hover:bg-teal-700">
          Post Comment
        </button>
      </form>
    <?php else: ?>
      <p class="text-sm text-slate-500 mb-4">Login to comment</p>
    <?php endif; ?>

    <div class="space-y-4">
      <?php foreach ($comments as $c): ?>
        <div class="border-b border-slate-200 pb-3">
          <div class="text-sm font-semibold"><?= htmlspecialchars($c['username']) ?></div>
          <div class="text-sm text-slate-700 whitespace-pre-line">
            <?= nl2br(htmlspecialchars($c['comment'])) ?>
          </div>
        </div>
      <?php endforeach; ?>

      <?php if (empty($comments)): ?>
        <p class="text-sm text-slate-400">No comments yet.</p>
      <?php endif; ?>
    </div>
  </section>

</main>

</body>
</html>s