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

// Filter und Suche
$where = [];
$params = [];
if (!empty($_GET['photographer'])) {
    $where[] = 'photographer_name = ?';
    $params[] = $_GET['photographer'];
}
if (!empty($_GET['q'])) {
    $where[] = '(description LIKE ? OR photographer_name LIKE ?)';
    $params[] = '%'.$_GET['q'].'%';
    $params[] = '%'.$_GET['q'].'%';
}
$sql = 'SELECT * FROM photos';
if ($where) { $sql .= ' WHERE '.implode(' AND ',$where); }
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$photos = $stmt->fetchAll();

// Alle Fotografen
$phs = $pdo->query('SELECT DISTINCT photographer_name FROM photos')->fetchAll();
?>
<!DOCTYPE html>
<html lang="de">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Galerie</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" class="active">Galerie</a>
    <a href="upload.php">Hochladen</a>
    <a href="ranking.php">Ranking</a>
    <a href="logout.php">Logout</a>
  </nav>
  <main class="container">
    <form method="get">
      <select name="photographer">
        <option value="">Alle Fotografen</option>
        <?php foreach($phs as $p): ?>
          <option value="<?= escape($p['photographer_name']) ?>" <?= (isset($_GET['photographer']) && $_GET['photographer']==$p['photographer_name'] ? 'selected' : '') ?>>
            <?= escape($p['photographer_name']) ?>
          </option>
        <?php endforeach; ?>
      </select>
      <input type="text" name="q" placeholder="Suche..." value="<?= escape($_GET['q'] ?? '') ?>">
      <button type="submit">Filtern</button>
    </form>
    <div class="gallery-grid">
      <?php foreach($photos as $photo):
        $avg = $pdo->prepare('SELECT AVG(rating) FROM ratings WHERE photo_id = ?');
        $avg->execute([$photo['id']]);
        $avgRating = round($avg->fetchColumn());
      ?>
        <div class="thumb">
          <a href="uploads/<?= escape($photo['filename']) ?>" data-lightbox="gallery">
            <img src="uploads/<?= escape($photo['filename']) ?>" alt="<?= escape($photo['description']) ?>">
          </a>
          <div class="rating" data-id="<?= $photo['id'] ?>">
            <?php for ($i = 1; $i <= 5; $i++): ?>
              <span class="star <?= $i <= $avgRating ? 'filled' : '' ?>" data-rating="<?= $i ?>">&#9733;</span>
            <?php endfor; ?>
            <span class="count">(<?= $avgRating ?>)</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>