<?php
include 'check_code.php';
include 'includes/db.php';
include 'includes/functions.php';
// Session bereits in check_code gestartet

$sql = 'SELECT p.id, p.filename, ROUND(AVG(r.rating),1) AS avg, COUNT(r.id) AS cnt
        FROM photos p
        LEFT JOIN ratings r ON p.id = r.photo_id
        GROUP BY p.id
        ORDER BY avg DESC';
$photos = $pdo->query($sql)->fetchAll();
?>
<!DOCTYPE html>
<html lang="de">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Ranking</title>
  <link rel="stylesheet" href="css/style.css">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.3/css/lightbox.min.css" rel="stylesheet">
</head>
<body>
  <nav class="navbar">
    <a href="index.php">Home</a>
    <a href="gallery.php">Galerie</a>
    <a href="upload.php">Hochladen</a>
    <a href="ranking.php" class="active">Ranking</a>
    <a href="logout.php">Logout</a>
  </nav>
  <main class="container">
    <div class="ranking-grid">
      <?php foreach ($photos as $i => $p): ?>
        <div class="rank-item">
          <h2><?= $i+1 ?>.</h2>
          <a href="uploads/<?= escape($p['filename']) ?>" data-lightbox="ranking">
            <img src="uploads/<?= escape($p['filename']) ?>" alt="<?= escape($p['filename']) ?>" class="responsive-img">
          </a>
          <div class="rating" data-id="<?= $p['id'] ?>">
            <?php for ($j = 1; $j <= 5; $j++): ?>
              <span class="star <?= $j <= round($p['avg']) ? 'filled' : '' ?>" data-rating="<?= $j ?>">&#9733;</span>
            <?php endfor; ?>
            <span class="count">(<?= $p['avg'] ?> ★, <?= $p['cnt'] ?>)</span>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
  </main>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.3/js/lightbox.min.js"></script>
  <script src="js/rating.js"></script>
</body>
</html>