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

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

$sql = "SELECT id, judul, penulis, isbn, sinopsis, gambar, created_at, kategori FROM books WHERE 1";
$params = [];

if ($kategori !== '') {
  // cocokkan kategori tanpa peduli kapital
  $sql .= " AND LOWER(kategori) = LOWER(?)";
  $params[] = $kategori;
}

if ($search !== '') {
  $like = "%{$search}%";
  $sql .= " AND ( judul    LIKE ?
               OR penulis  LIKE ?
               OR isbn     LIKE ?
               OR sinopsis LIKE ? )";
  array_push($params, $like, $like, $like, $like);
}

// (opsional) urutkan yang “terasa” relevan dulu
$sql .= " ORDER BY 
            (CASE 
               WHEN isbn = ? THEN 4
               WHEN judul LIKE ? THEN 3
               WHEN penulis LIKE ? THEN 2
               WHEN sinopsis LIKE ? THEN 1
               ELSE 0
             END) DESC,
            created_at DESC";

array_push($params, $search, "%{$search}%", "%{$search}%", "%{$search}%");

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$books = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt_rating = $pdo->query("
    SELECT book_id, rating, COUNT(*) AS jumlah
    FROM reviews
    GROUP BY book_id, rating
");

while ($row = $stmt_rating->fetch(PDO::FETCH_ASSOC)) {
    $bookId = $row['book_id'];
    $rating = $row['rating'];
    $count = $row['jumlah'];
    $rating_data[$bookId][$rating] = $count;
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title>Kategori Buku</title>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700&display=swap" rel="stylesheet">
<style>
  body {
    font-family: 'Poppins', sans-serif;
    background-color: #f9f9f9;
    margin: 0;
    padding: 0;
  }
/* ---------- Header ---------- */
header {
      display: flex; justify-content: space-between; align-items: center;
      padding: 15px 25px; background: #fff; border-bottom: 1px solid #ddd;
      position: sticky; top: 0; z-index: 1000;
    }
    .left-header { display: flex; align-items: center; gap: 15px; }
    .logo { font-size: 22px; font-weight: bold; color: #069797; }
    nav { display: flex; align-items: center; gap: 20px; }
    nav a { font-weight: 500; transition: color 0.3s; color: #333; }
    nav a:hover { color: #069797; }
    /* --- Search Bar Styling --- */
.search-bar {
  display: flex;
  align-items: center;
  background: #ffffff;
  border: 2px solid #069797;
  border-radius: 10px;        /* Tidak oval, agak tumpul */
  overflow: hidden;
  width: 1000px;               /* Lebih panjang */
  height: 40px;               /* Lebih besar dan tinggi */
  position: relative;
  box-shadow: 0 2px 6px rgba(0,0,0,0.05);
}

/* Dropdown kategori */
.search-bar select {
  border: none;
  background: #e7f7f7;       /* Sedikit tosca muda biar lembut */
  padding: 0 14px;
  font-size: 15px;
  outline: none;
  color: #069797;
  cursor: pointer;
  font-weight: 500;
  height: 100%;
}

/* Input pencarian */
.search-bar input {
  flex: 1;
  border: none;
  outline: none;
  padding: 0 16px;
  font-size: 15px;
  color: #333;
  background: #ffffff;
  height: 100%;
}

.search-bar input::placeholder {
  color: #aaa;
}

/* Tombol cari */
.search-bar button {
  background: #069797;
  color: #fff;
  border: none;
  padding: 0 20px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  transition: background 0.3s ease;
}

.search-bar button:hover {
  background: #048787;
}

/* Saran (autocomplete) */


#suggestions .suggest-item {
  padding: 10px 14px;
  cursor: pointer;
  transition: background 0.2s;
}

#suggestions .suggest-item:hover {
  background: #e7f7f7;
}

.search-bar {
  position: relative;
}

#suggestions {
  background: #ffffff;
  border: 2px solid #069797;
  border-radius: 8px;
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  z-index: 9999;
  box-shadow: 0 4px 10px rgba(0,0,0,0.1);
  max-height: 250px;
  overflow-y: auto;
  display: none; /* ini nanti diubah jadi block lewat JS */
}
 

  /* 🔹 KATEGORI HEADER */
  .category-header {
    padding: 60px 60px 0 60px;
    background-color: #f9f9f9;
    position: relative;
  }

  .category-header h1 {
    font-size: 32px;
    font-weight: 700;
    color: #132c33;
    margin-bottom: 10px;
  }

  .category-header h1::before {
    content: "— ";
    color: #132c33;
  }

  .category-header p {
    font-size: 16px;
    color: #666;
    margin: 0;
    max-width: 600px;
  }

  /* 🔹 WAVE PEMBATAS */
  .wave {
    position: relative;
    width: 100%;
    height: 45px;
    overflow: hidden;
    line-height: 0;
    margin-top: 45px;
  }

  .wave svg {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100vw;
    height: 100%;
    display: block;
  }

  /* 🔹 GRID BUKU */
  .book-section {
    padding: 50px 60px;
  }

  .book-section h2 {
    font-size: 24px;
    margin-bottom: 20px;
    color: #132c33;
  }

  .book-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
    gap: 30px;
  }

  .book-card {
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.08);
    text-align: center;
    padding: 15px;
    transition: transform 0.2s ease;
  }

  .book-card:hover {
    transform: translateY(-5px);
  }

  .book-card img {
    width: 100%;
    height: 230px;
    object-fit: cover;
    border-radius: 6px;
  }

  .book-title {
    margin: 10px 0 4px;
    font-weight: 600;
    color: #222;
    font-size: 14px;
  }

  .rating-detail {
    font-size: 13px;
    color: #666;
  }
  .hamburger {
  font-size: 24px;
  cursor: pointer;
  color: #000;
  text-decoration: none;
}
.hamburger:hover {
  opacity: 0.8;
}
  footer {
      background: #fff; margin-top: 40px; padding: 20px 40px;
      font-size: 14px; color: #222;
    }
    .footer-bottom { display:flex; justify-content:space-between; align-items:center; margin-top:15px; font-size:13px; flex-wrap:wrap; }
    .footer-links a { margin-left:15px; color:#222; font-weight:500; }
    .trend-card {
  background: #222;
  color: #fff;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.book-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 25px;
  justify-content: center;
}

.book-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 3px 12px rgba(0,0,0,.1);
  transition: transform .2s, box-shadow .2s;
  position: relative;
  width: 190px;
  overflow: visible;
}
.book-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0,0,0,.15);
}

.cover-wrapper {
  position: relative;
  width: 100%;
  height: 250px;
  overflow: hidden;
}
.cover-wrapper img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px 8px 0 0;
}
.star-toggle {
  position: absolute;
  bottom: 8px;
  right: 8px;
  width: 28px;
  height: 28px;
  border: none;
  border-radius: 50%;
  background: rgba(255,255,255,.9);
  cursor: pointer;
  font-size: 16px;
  transition: background .2s;
}
.star-toggle:hover { background: #ffe89a; }

.book-title {
  background: #fff;
  color: #111;
  text-align: center;
  font-weight: 600;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 56px;
  padding: 0 10px;
  width: 100%;
  border-top: 1px solid #eee;
  border-radius: 0 0 8px 8px;
}
.book-title a {
  color: inherit;          /* ambil warna dari parent (#111) */
  text-decoration: none;   /* hilangkan garis bawah */
}
.book-title a:hover {
  text-decoration: underline;  /* opsional: tampilkan underline saat hover */
}

.rating-popover {
  position: absolute;
  top: calc(100% + 8px);
  left: 50%;
  transform: translateX(-50%) translateY(-6px);
  width: 200px;
  background: #ffffff;
  color: #111;
  border: 1px solid #ddd;
  border-radius: 10px;
  padding: 10px;
  box-shadow: 0 8px 20px rgba(0,0,0,.2);
  opacity: 0;
  visibility: hidden;
  pointer-events: none;
  transition: opacity .18s ease, transform .18s ease;
  z-index: 999;
}
.rating-popover.open {
  opacity: 1;
  visibility: visible;
  pointer-events: auto;
  transform: translateX(-50%) translateY(0);
}
.rating-popover::before {
  content: "";
  position: absolute;
  top: -8px; left: 50%; transform: translateX(-50%);
  border: 8px solid transparent;
  border-bottom-color: #ffffff;
}
.book-card.popover-open { z-index: 1000; }


</style>
</head>
<body>

<!-- 🔹 HEADER -->
<header style="display:flex; align-items:center; justify-content:space-between; padding:10px 20px; background:var(--bg); position:relative;">
  <!-- Bagian kiri: logo dan hamburger -->
  <div class="left-header" style="display:flex; align-items:center; gap:10px;">
  <span class="hamburger" id="hamburger" onclick="window.location.href='index2.php'">⬅</span>
    <div class="logo">📚 Pustaka Ilium Academy</div>
  </div>

  <!-- 🔍 Search bar (di tengah header) -->
  <form id="searchForm" method="get" action="search_results.php" class="search-bar">
  <select name="kategori" id="kategori" class="search-select">
    <option value="">Kategori</option>
    <option value="Novel">Novel</option>
    <option value="Sains">Sains</option>
    <option value="Teknologi">Teknologi</option>
    <option value="Komputer">Komputer</option>
    <option value="Matematika">Matematika</option>
    <option value="Fisika">Fisika</option>
    <option value="Kimia">Kimia</option>
    <option value="Biologi">Biologi</option>
    <option value="Psikologi">Psikologi</option>
    <option value="Ekonomi">Ekonomi</option>
    <option value="Bisnis">Bisnis</option>
    <option value="Sejarah">Sejarah</option>
    <option value="Agama">Agama</option>
    <option value="Sastra">Sastra</option>
    <option value="Politik">Politik</option>
    <option value="Pendidikan">Pendidikan</option>
    <option value="Anak-anak">Anak-anak</option>
    <option value="Remaja">Remaja</option>
    <option value="Inspiratif">Inspiratif</option>
    <option value="Hukum">Hukum</option>
    <option value="Geografi">Geografi</option>
    <option value="Kesehatan">Kesehatan</option>
    <option value="Komik">Komik</option>
    <option value="Ensiklopedia">Ensiklopedia</option>
    <option value="Filsafat">Filsafat</option>
  </select>

  <input type="text" id="searchInput" name="search" placeholder="Cari buku apa...?" autocomplete="off" />

  <button type="submit">
    <i class="fa fa-search"></i>
  </button>

  <div id="suggestions"></div>
</form>

  <!-- Bagian kanan: notifikasi dan logout -->
  <nav style="display:flex; align-items:center; gap:15px;">
  </nav>
</header>

<!-- 🔹 BAGIAN KATEGORI -->
<div class="category-header">
  <div>
    <h1><?= htmlspecialchars($kategori ?: 'Buku') ?></h1>
    <p>“Buku adalah jendela dunia dan sumber inspirasi.”</p>
  </div>
</div>

<div class="wave">
  <svg viewBox="0 0 1440 60" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none">
    <defs>
      <linearGradient id="grad" x1="0" x2="1" y1="0" y2="0">
        <stop offset="0%" stop-color="#048e8e" />
        <stop offset="100%" stop-color="#056e7b" />
      </linearGradient>
    </defs>
    <path fill="url(#grad)" d="M0,0 C360,40 1080,5 1440,35 L1440,60 L0,60 Z"></path>
  </svg>
</div>

<!-- 🔹 DAFTAR BUKU -->
<div class="book-section">
  <?php if (count($books) === 0): ?>
    <p style="text-align:center;color:#555;">Tidak ada buku ditemukan.</p>
  <?php else: ?>
    <div class="book-grid">
    <?php foreach ($books as $b): ?>
  <div class="book-card" data-book-id="<?= $b['id'] ?>">
    <div class="cover-wrapper">
      <a href="detail_guest.php?id=<?= $b['id'] ?>">
        <img src="<?= htmlspecialchars($b['gambar']) ?>"
             alt="<?= htmlspecialchars($b['judul']) ?>"
             onerror="this.src='Uploads/default.jpg'">
      </a>
      <button class="star-toggle" type="button" title="Lihat rating">⭐</button>
    </div>

    <div class="book-title">
      <a href="detail_guest.php?id=<?= $b['id'] ?>"><?= htmlspecialchars($b['judul']) ?></a>
    </div>

    <div class="rating-popover" role="dialog" aria-hidden="true">
      <?php
        $bookId = $b['id'];
        if (isset($rating_data[$bookId])) {
          for ($i = 5; $i >= 1; $i--) {
            $jumlah = $rating_data[$bookId][$i] ?? 0;
            echo "<div>⭐$i: $jumlah orang</div>";
          }
        } else {
          echo "<div>Belum ada rating</div>";
        }
      ?>
    </div>
  </div>
<?php endforeach; ?>

    </div>
  <?php endif; ?>
</div>
<footer>
    <hr style="border:none;border-top:1px solid #ddd;margin:20px 0 10px 0;width:100%;">
    <div class="footer-bottom">
      <p>© 2025, Pustakaia | Website developed by Grup 3</p>
      <div class="footer-links">
        <a href="#">Terms of Use</a>
        <a href="#">Privacy Policy</a>
      </div>
    </div>
  </footer>

  <script>
document.addEventListener("DOMContentLoaded", () => {
  const input = document.getElementById("searchInput");
  if (!input) return console.warn("searchInput not found");

  // buat container baru di body (global, di atas semua elemen)
  let floating = document.getElementById('floating-suggestions');
  if (!floating) {
    floating = document.createElement('div');
    floating.id = 'floating-suggestions';
    document.body.appendChild(floating);
    Object.assign(floating.style, {
      position: 'absolute',
      display: 'none',
      background: '#fff',
      border: '2px solid #069797',
      borderRadius: '8px',
      boxShadow: '0 6px 18px rgba(0,0,0,0.15)',
      zIndex: 999999,
      maxHeight: '300px',
      overflowY: 'auto',
      color: '#000',
      padding: '4px'
    });
  }

  // helper: position floating under input
  function positionFloating() {
    const r = input.getBoundingClientRect();
    const docEl = document.documentElement;
    const scrollTop = window.pageYOffset || docEl.scrollTop || document.body.scrollTop;
    const scrollLeft = window.pageXOffset || docEl.scrollLeft || document.body.scrollLeft;
    floating.style.width = Math.max(260, r.width) + 'px'; // min width
    floating.style.left = (r.left + scrollLeft) + 'px';
    floating.style.top = (r.bottom + scrollTop + 6) + 'px';
  }

  // hide when clicking outside
  document.addEventListener('click', (ev) => {
    if (ev.target === input || floating.contains(ev.target)) return;
    floating.style.display = 'none';
  }, true);

  // on resize/scroll reposition
  window.addEventListener('resize', positionFloating);
  window.addEventListener('scroll', positionFloating, true);

  // live search: use your existing endpoint
  let lastController = null;
  input.addEventListener('input', () => {
    const q = input.value.trim();
    if (!q) {
      floating.style.display = 'none';
      return;
    }

    // cancel previous fetch
    if (lastController) lastController.abort();
    lastController = new AbortController();

    fetch('live_search.php?search=' + encodeURIComponent(q), { signal: lastController.signal })
      .then(res => res.json())
      .then(data => {
       // build HTML
if (!Array.isArray(data) || data.length === 0) {
  floating.innerHTML = "<div style='padding:10px;color:#666'>Tidak ada hasil...</div>";
} else {
  floating.innerHTML = data.map(book => {
    const safeTitle   = String(book.judul ?? '').replace(/</g,'&lt;');
    const safeAuthor  = String(book.penulis ?? '').replace(/</g,'&lt;');
    const safeIsbn    = String(book.isbn ?? '').replace(/</g,'&lt;');
    const safeSnippet = String(book.sinopsis_snippet ?? '').replace(/</g,'&lt;');

    return `
      <div class="fs-item" data-id="${book.id}" style="padding:10px;cursor:pointer;border-bottom:1px solid #eee;">
        <div style="font-weight:600">${safeTitle}</div>
        <div style="font-size:12px;color:#555">
          ${safeAuthor}${safeAuthor && (safeIsbn) ? ' • ' : ''}${safeIsbn ? 'ISBN: ' + safeIsbn : ''}
        </div>
        ${safeSnippet ? `<div style="font-size:12px;color:#666;margin-top:4px;">${safeSnippet}</div>` : ``}
      </div>`;
  }).join('');
}
        // attach click handlers
        Array.from(floating.querySelectorAll('.fs-item')).forEach(el => {
          el.onclick = () => {
            const id = el.getAttribute('data-id');
            // pergi ke detail
            window.location.href = 'detail_guest.php?id=' + encodeURIComponent(id);
          };
        });

        positionFloating();
        floating.style.display = 'block';
      })
      .catch(err => {
        if (err.name === 'AbortError') return; // ignore cancelled
        console.error('live search error', err);
        floating.style.display = 'none';
      });
  });

  // if user presses Enter while suggestion visible, navigate to search results
  input.addEventListener('keydown', (e) => {
    if (e.key === 'Enter') {
      // if floating is visible and first item exists, follow it (otherwise fallback to search_results)
      const first = floating.querySelector('.fs-item');
      if (first && floating.style.display === 'block') {
        e.preventDefault();
        first.click();
        return;
      }
      // else allow your existing submit logic to handle navigation
    }
  });
});
document.getElementById('kategori').addEventListener('change', function() {
  const category = this.value;
  if (category !== '') {
    window.location.href = 'category.php?kategori=' + encodeURIComponent(category);
  }
});
document.getElementById('searchForm').addEventListener('submit', function(e) {
  e.preventDefault(); // stop form default
  const search = document.getElementById('searchInput').value.trim();

  if (search !== '') {
    window.location.href = 'search_results.php?search=' + encodeURIComponent(search);
  }
});
function closeAllPopovers(except){
  document.querySelectorAll('.rating-popover.open').forEach(p => {
    if (p !== except){
      p.classList.remove('open');
      p.setAttribute('aria-hidden','true');
      p.closest('.book-card')?.classList.remove('popover-open');
    }
  });
}
document.addEventListener('click', function(e){
  const starBtn = e.target.closest('.star-toggle');
  if (starBtn){
    const card = starBtn.closest('.book-card');
    const pop = card.querySelector('.rating-popover');
    const isOpen = pop.classList.contains('open');
    closeAllPopovers(isOpen ? null : pop);
    pop.classList.toggle('open', !isOpen);
    pop.setAttribute('aria-hidden', isOpen ? 'true' : 'false');
    card.classList.toggle('popover-open', !isOpen);
    return;
  }
  if (!e.target.closest('.rating-popover')) closeAllPopovers();
});
window.addEventListener('scroll', () => closeAllPopovers(), true);
window.addEventListener('resize', () => closeAllPopovers());
</script>


</body>
</html>
