<?php
require __DIR__ . '/../Login/config.php';

$search = $_GET['search'] ?? '';
$kategori = $_GET['kategori'] ?? 'semua';

$where = [];
$params = [];

if ($kategori !== 'semua' && $kategori !== '') {
  $where[] = "kategori = :kategori";
  $params[':kategori'] = $kategori;
}
if ($search !== '') {
  $where[] = "judul LIKE :search";
  $params[':search'] = "%$search%";
}

$whereSQL = $where ? 'WHERE ' . implode(' AND ', $where) : '';
$sql = "SELECT * FROM books $whereSQL ORDER BY created_at DESC LIMIT 30";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$books = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (count($books) === 0) {
  echo "<p style='text-align:center;color:#777;'>Tidak ada buku ditemukan.</p>";
  exit;
}

foreach ($books as $b):
  $img = !empty($b['gambar']) ? '../' . $b['gambar'] : '../Uploads/default.png';
  $title = htmlspecialchars($b['judul']);
  $link = 'detail.php?id=' . intval($b['id']);
  echo "
  <a href='$link' class='trend-card'>
    <img src='$img' alt='$title'>
    <p>$title</p>
  </a>";
endforeach;
?>
