<?php
/****************************************************
 * 📁 FILE: index.php
 * 💡 Bahasa Pemrograman: PHP + HTML + CSS + JavaScript
 * 🎯 Fungsi: Halaman utama website Pustakaia
 * - Menampilkan hero slider
 * - Menampilkan daftar buku terbaru (section "Terbaru")
 * - Menampilkan semua buku (dengan pagination & search)
 * - Menyediakan sidebar, header, notifikasi (AJAX), footer
 *
 * Catatan: saya hanya menambahkan komentar & penjelasan
 *        di seluruh file. Isi logika / query / path asli
 *        TIDAK SAYA UBAH.
 ****************************************************/
require __DIR__ . '/../Login/config.php';
 // koneksi database menggunakan $pdo

// ✅ Mulai session jika belum dimulai
if (session_status() === PHP_SESSION_NONE) {
  session_start();
}

/* ==========================================================
   🔹 BAGIAN 1: DATA USER UNTUK SIDEBAR
   - Mengambil fullname, role, dan photo dari session
   - Menentukan fallback photo jika file/URL tidak ditemukan
   Bahasa: PHP
   ========================================================== */
$fullname = $_SESSION['fullname'] ?? $_SESSION['username'] ?? 'Pengguna';
$role     = $_SESSION['role'] ?? 'User';
$sessionPhoto = $_SESSION['photo'] ?? '';

$user_id = $_SESSION['user_id'];

// === FOTO PROFIL USER ===
$photoURL = "../uploads/default.jpg";
$stmtUser = $pdo->prepare("SELECT photo FROM users WHERE id = ?");
$stmtUser->execute([$user_id]);
$photo = $stmtUser->fetchColumn();
if (!empty($photo) && file_exists("../uploads/" . $photo)) {
  $photoURL = "../uploads/" . $photo;
}

/* ==========================================================
   🔹 BAGIAN 2: AMBIL DATA BUKU DARI DATABASE
   - Query semua buku urut berdasarkan created_at DESC
   - Digunakan untuk menampilkan bagian "Terbaru" (6 item)
   Bahasa: PHP (PDO)
   ========================================================== */
// Ambil semua buku (untuk bagian "Terbaru")
$stmt = $pdo->query("SELECT * FROM books ORDER BY created_at DESC");
$all = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Terbaru: 6 pertama
$latest = array_slice($all, 0, 5);

/* ==========================================================
   🔹 BAGIAN 3: PAGINATION & SEARCH untuk Semua Buku
   - Mendukung parameter GET: search dan page
   - Limit per halaman = 30
   - Menghitung total_pages untuk pagination
   Bahasa: PHP (PDO prepared statements untuk search)
   ========================================================== */
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$page   = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$limit  = 30;
$offset = ($page - 1) * $limit;

// Hitung total buku
if ($search !== '') {
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM books WHERE judul LIKE ?");
    $stmt->execute(["%$search%"]);
} else {
    $stmt = $pdo->query("SELECT COUNT(*) FROM books");
}
$total_books = $stmt->fetchColumn();
$total_pages = ceil($total_books / $limit);

// Ambil data sesuai page + search
if ($search !== '') {
    $stmt = $pdo->prepare("SELECT * FROM books WHERE judul LIKE ? ORDER BY created_at DESC LIMIT $limit OFFSET $offset");
    $stmt->execute(["%$search%"]);
} else {
    $stmt = $pdo->query("SELECT * FROM books ORDER BY created_at DESC LIMIT $limit OFFSET $offset");
}
$tren = $stmt->fetchAll(PDO::FETCH_ASSOC);
$rating_data = [];

$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;
}
$rating_avg_data = [];
$stmt = $pdo->query("SELECT book_id, AVG(rating) AS avg_rating, COUNT(*) AS total_ulasan 
                     FROM reviews GROUP BY book_id");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $rating_avg_data[$row['book_id']] = [
        'avg' => round($row['avg_rating'], 1),
        'count' => $row['total_ulasan']
    ];
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Pustakaia</title>

  <!-- 🔗 Font Awesome (ikon) -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

  <style>
    /****************************************************
     * 💅 BAGIAN CSS — Bahasa: CSS
     * Mengatur tampilan seluruh halaman (header, sidebar,
     * hero, promo, grid buku, footer, dsb.)
     *
     * Catatan: saya menambahkan komentar CSS untuk setiap
     * blok agar lebih mudah dipahami.
     ****************************************************/

    /* ---------- Global ---------- */
    body {
      margin: 0;
      font-family: "Poppins", Arial, sans-serif;
      line-height: 1.6;
      background: linear-gradient(135deg, #f9f9f9, #e9f5ec);
      color: #222;
      overflow-x: hidden;
    }
    a { text-decoration: none; color: inherit; }

    /* ---------- 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 */
}

    /* ---------- Notifikasi (ikon + badge + dropdown) ---------- */
    .notif-icon {
      position: relative;
      font-size: 22px;
      cursor: pointer;
      color: #069797;
    }
    .notif-badge {
      position: absolute;
      top: -8px; right: -10px;
      background: red;
      color: #fff;
      border-radius: 50%;
      font-size: 12px;
      padding: 2px 6px;
      display: none;
    }

    /* dropdown notifikasi */
    #notif-list {
      display:none;
      position:absolute;
      right:20px; top:60px;
      background:#fff;
      border:1px solid #ccc;
      padding:10px;
      width:280px;
      z-index:1200;
      box-shadow:0 4px 12px rgba(0,0,0,0.15);
      border-radius:6px;
    }
    #notif-list div {
      border-bottom:1px solid #eee;
      padding:5px 0;
      font-size:14px;
    }
    #notif-list small {
      color:#777;
      font-size:12px;
    }

    /* ---------- Hamburger (mobile) ---------- */
    .hamburger { font-size: 24px; cursor: pointer; color: #069797; }

    /* ---------- Sidebar ---------- */
    .sidebar {
      width: 250px;
      height: 100vh;
      background: #fff;
      border-right: 1px solid #ddd;
      padding: 10px 0;
      position: fixed;
      top: 0;
      left: -100%;
      overflow-y: auto;
      transition: left 0.3s ease;
      z-index: 1100;
    }
    .sidebar.active { left: 0; }

    .sidebar-header { padding: 15px 20px; border-bottom: 1px solid #ddd; }
    .sidebar-header h2 { margin: 0; font-size: 18px; color: #333; }
    .sidebar-header p { margin: 0; font-size: 12px; color: #777; }

    .sidebar-menu { list-style: none; padding: 0; margin: 0; }
    .sidebar-menu li {
      padding: 12px 20px; font-size: 14px; color: #444;
      display: flex; align-items: center; cursor: pointer;
      transition: background 0.2s;
    }
    .sidebar-menu li i { margin-right: 10px; font-size: 16px; color: #666; }
    .sidebar-menu li:hover { background: #f5f5f5; }
    .sidebar-menu li.active { background: #e0ebff; color: #069797; }
    .sidebar-menu li.active i { color: #069797; }

    hr { border: none; border-top: 1px solid #ddd; margin: 10px 0; }

    .overlay {
      position: fixed; top: 0; left: 0; width: 100%; height: 100%;
      background: rgba(0,0,0,0.5);
      display: none;
      z-index: 1050;
    }
    .overlay.active { display: block; }

    /* ---------- Promo Book (section) ---------- */
    .promo-book {
      padding: 80px 40px;
      background: linear-gradient(135deg, #f9f9f9, #e9f5ec);
    }
    .promo-content {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      justify-content: center;
      gap: 40px;
      max-width: 1050px;
      margin: auto;
    }
    .promo-text {
      flex: 1;
      min-width: 280px;
    }
    .promo-text h2 {
      font-size: 36px;
      font-weight: 700;
      line-height: 1.3;
      margin-bottom: 15px;
      color: #222;
    }
    .promo-text .highlight { color: #069797; }
    .promo-text p { color: #444; margin-bottom: 20px; max-width: 400px; }
    .promo-buttons { display: flex; gap: 15px; }
    .btn-primary {
      background: #069797; color: #fff; padding: 10px 20px;
      border-radius: 6px; font-weight: 600; transition: background 0.3s;
    }
    .btn-primary:hover { background: #047676; }
    .btn-outline {
      border: 2px solid #069797; color: #069797;
      padding: 8px 18px; border-radius: 6px;
      font-weight: 600; transition: all 0.3s;
    }
    .btn-outline:hover { background: #069797; color: #fff; }

    .promo-image img { max-width: 280px; border-radius: 8px; }

    /* ---------- Hero (slide) ---------- */
.hero {
  position: relative;
  height: 500px;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  text-align: center;
  color: #fff;
}

.hero-bg {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  background-size: cover;
  background-position: center;
  transition: transform 1s ease-in-out;
  z-index: 0;
}

.hero-content {
  position: relative;
  z-index: 2;
}

.hero::after {
  content: "";
  position: absolute;
  inset: 0;
  background: rgba(0, 0, 0, 0.6);
  z-index: 1;
}

.hero h1 {
  font-size: 42px;
  font-weight: 700;
}

.hero span {
  color: #069797;
}

/* === Tambahan untuk animasi 2 layer hero === */
#heroBg1,
#heroBg2 {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-size: cover;
  background-position: center;
  will-change: transform, opacity;
  transition: transform 1.2s ease-in-out, opacity 0.3s ease-in-out;
  z-index: 0;
}

    /* ---------- Sections / Grid Buku ---------- */
    .section { padding: 40px; max-width: 1200px; margin: auto; }
    .section-title { font-size: 28px; font-weight: bold; margin-bottom: 25px; text-align: left; color: #069797; }

    .trending-row {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 25px;
  justify-items: center;
  padding: 20px 0;
}

.trend-card {
  background: #fff;
  border-radius: 3px;
 
  text-align: center;
  padding: 15px;
  width: 180px;
  transition: transform 0.2s ease;
}

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

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

.trend-card p {
  margin: 10px 0 4px;
  font-weight: 600;
  color: #222;
  font-size: 14px;
}

.trend-card .rating-detail {
  font-size: 13px;
  color: #666;
}


    /* ---------- Footer ---------- */
    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; }
    
/* Pastikan parent search bar punya posisi relatif */
.search-container {
  position: relative;
  display: inline-block;
}

/* Style untuk kotak hasil pencarian */
#suggestions {
  position: absolute;
  top: 100%; /* muncul tepat di bawah input */
  left: 0;
  width: 100%;
  max-height: 250px;
  overflow-y: auto;
  background: #fff;
  border: 1px solid #ddd;
  border-radius: 6px;
  box-shadow: 0 4px 10px rgba(0,0,0,0.1);
  display: none;
  z-index: 9999;
}

#suggestions.active {
  display: block;
}
.book-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 25px;
  justify-items: center;
  overflow: visible;
}

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

.cover-wrapper {
  position: relative;
  width: 100%;
  height: 260px;
  overflow: hidden;
}
.cover-wrapper img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
  transition: transform .3s ease;
}
.cover-wrapper:hover img {
  transform: scale(1.05);
}

.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;
  margin: 0;
  width: 100%;
  box-sizing: border-box;
  border-top: 1px solid #eee;
  border-radius: 0 0 8px 8px;
}
.book-title a {
  color: inherit;
  text-decoration: none;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
.book-title a:hover { text-decoration: underline; }

.rating-popover {
  position: absolute;
  top: calc(100% + 8px);
  left: 50%;
  transform: translateX(-50%) translateY(-6px);
  width: 220px;
  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;
}
.rating-popover div {
  font-size: 13px;
  margin: 4px 0;
}
.book-card.popover-open { z-index: 1000; }
/* Center grid cards, fixed width columns */
.book-section { max-width: 1200px; margin: 40px auto; }

.book-grid{
  display: grid !important;
  grid-template-columns: repeat(auto-fit, 190px) !important; /* kolom fix */
  justify-content: center !important;  /* seluruh grid ke tengah */
  gap: 25px !important;
}

.book-card{
  width: 190px !important;   /* pastikan kartu konsisten */
  margin: 0 !important;
  justify-self: center;       /* jaga-jaga */
}


  </style>
</head>
<body>
  <!-- ==========================================================
       🔹 SIDEBAR (HTML)
       - Menampilkan foto profil, nama, role, menu navigasi.
       - Sidebar dikendalikan via JS (tambah/kurangi kelas .active)
       ========================================================== -->
 <!-- SIDEBAR (ganti blok ini dengan yang lama) -->
<!-- SIDEBAR: perbaikan alignment kiri untuk Pengaturan, Profil, Akun -->
<aside class="sidebar" id="sidebar">
  <div class="sidebar-header" style="padding:15px 16px;">
    <div class="logo" style="font-size:20px; font-weight:bold; color:#069797; margin-bottom:8px;">
      📚 Pustakaia
    </div>

    <div style="text-align:center; margin-bottom:8px;">
      <img src="<?= htmlspecialchars($photoURL) ?>"
           alt="Foto Profil"
           style="width:80px; height:80px; border-radius:50%; object-fit:cover; border:2px solid #069797;">
    </div>

    <!-- Teks nama & role dibuat left-aligned -->
    <div style="text-align:left; padding-left:4px;">
      <h2 style="margin:0; font-size:17px; color:#333;"><?= htmlspecialchars($_SESSION['fullname'] ?? 'Pengguna') ?></h2>
      <p style="margin:0; font-size:13px; color:#777;"><?= htmlspecialchars(ucfirst($_SESSION['role'] ?? 'User')) ?></p>
    </div>
  </div>

  <ul class="sidebar-menu" id="sidebar-menu">
    <li class="menu-item">
      <a href="books.php" class="menu-link">
        <i class="fa fa-book menu-icon"></i>
        <span class="menu-text">Semua Buku</span>
      </a>
    </li>

    <li class="menu-item">
      <a href="notifications_page.php" class="menu-link">
        <i class="fa fa-bell menu-icon"></i>
        <span class="menu-text">Notifikasi</span>
      </a>
    </li>

    <li class="menu-item"><a href="favorites.php" class="menu-link"><i class="fa fa-heart menu-icon"></i> <span class="menu-text">Favorit</span></a></li>
    <li class="menu-item"><a href="saved.php" class="menu-link"><i class="fa fa-bookmark menu-icon"></i> <span class="menu-text">Simpanan Saya</span></a></li>
    <li class="menu-item"><a href="borrowed_list.php" class="menu-link"><i class="fa fa-book-reader menu-icon"></i> <span class="menu-text">Pinjaman Saya</span></a></li>
    <li class="menu-item"><a href="library_card.php" class="menu-link"><i class="fa fa-id-card menu-icon"></i> <span class="menu-text">Kartu Perpustakaan</span></a></li>
  </ul>

  <hr style="margin:10px 0; border:none; border-top:1px solid #eee;">

  <ul class="sidebar-menu">
    <!-- Pengaturan sebagai tombol toggle (bukan link) -->
    <li class="menu-item has-submenu" id="setting-item" style="cursor:pointer;">
      <div class="menu-link" style="justify-content:space-between;">
        <div style="display:flex; align-items:center; gap:10px;">
          <i class="fa fa-cog menu-icon"></i>
          <span class="menu-text">Pengaturan</span>
        </div>
        <i class="fa fa-chevron-down" id="setting-caret" style="color:#999; font-size:12px;"></i>
      </div>
    </li>

    <!-- Submenu kiri rapi -->
    <ul class="submenu" id="setting-submenu" style="display:none; margin:0; padding:0;">
      <li style="list-style:none;">
        <a href="profile.php" class="menu-link submenu-link">
          <i class="fa fa-user menu-icon"></i>
          <span class="menu-text">Profil</span>
        </a>
      </li>
      <li style="list-style:none;">
        <a href="akun.php" class="menu-link submenu-link">
          <i class="fa fa-envelope menu-icon"></i>
          <span class="menu-text">Akun / Email</span>
        </a>
      </li>
    </ul>

    <li style="margin-top:8px;"><a href="../index2.php" class="menu-link"><i class="fa fa-sign-out-alt menu-icon"></i> <span class="menu-text">Keluar</span></a></li>
  </ul>
</aside>


  <!-- overlay (untuk menutup sidebar saat diklik diluar) -->
  <div class="overlay" id="overlay"></div>

  <!-- ==========================================================
       🔹 HEADER UTAMA (HTML)
       - Berisi hamburger (buka sidebar), logo, notifikasi, logout
       ========================================================== -->
       <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">☰</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;">
    <div class="notif-icon" id="notif-btn">
      🔔
      <span class="notif-badge" id="notif-count"></span>
    </div>

    <a href="../Login/Logout.php">Keluar</a>
  </nav>
</header>

<!-- Popup Notifikasi (kontainer untuk notifikasi yang dimuat via AJAX) -->
<div id="notif-list">
  <div id="notif-items"></div>

  <!-- Lihat Selengkapnya -->
  <div style="text-align:center; margin-top:8px; border-top:1px solid #eee; padding-top:6px;">
    <a href="notifications_page.php" 
       style="color:#555; font-size:13px; font-weight:400; text-decoration:none;">
      Lihat selengkapnya →
    </a>
  </div>
</div>

  <!-- NOTE: elemen ID 'notif-list' didefinisikan dua kali di versi awal.
       Saya biarkan sesuai aslinya (tidak dihapus) agar tidak mengubah struktur. -->
  <div id="notif-list"></div>

 <!-- ==========================================================
      🔹 HERO SECTION (HTML + CSS)
      - Dua lapis background untuk transisi slide
      ========================================================== -->
<section class="hero">
  <div class="hero-bg" id="heroBg1" style="background-image: url('../images/bghome.jpg');"></div>
  <div class="hero-bg" id="heroBg2" style="background-image: url('../images/bf.jpg'); transform: translateX(100%);"></div>

  <div class="hero-content">
    <h1>Membaca <span>adalah </span>Jendela <span>Dunia</span></h1>
    <p>Temukan buku favoritmu dan tren terbaru di Pustakaia</p>
  </div>
</section>

  <!-- ==========================================================
       🔹 PROMO BUKU (HTML)
       - Section promosi sederhana dengan tombol aksi
       ========================================================== -->
  <section class="promo-book">
    <div class="promo-content">
      <div class="promo-text">
        <h2>
          A <span class="highlight">Book</span><br>
          Can Change<br>
          Your Life
        </h2>
        <p>
          Temukan inspirasi baru dan ubah cara pandangmu melalui buku pilihan terbaik.
        </p>
        <div class="promo-buttons">
          <a href="#" class="btn-primary">Pinjam</a>
          <a href="detail.php?id=21" class="btn-outline">See Details</a>
        </div>
      </div>
      <div class="promo-image">
        <img src="../images/aa.png" alt="Buku Inspirasi">
      </div>
    </div>
  </section>

  <!-- ==========================================================
       🔹 TERBARU (menampilkan 6 buku terbaru dari query)
       - Looping PHP untuk menampilkan cover + judul
       ========================================================== -->
      <!-- 🆕 TERBARU -->
<section class="book-section">
  <h2 class="section-title">Terbaru</h2>
  <div class="book-grid">
    <?php foreach ($latest as $b): ?>
      <?php 
        $img = !empty($b['gambar']) ? '../' . $b['gambar'] : '../Uploads/default.png';
        $title = htmlspecialchars($b['judul']);
        $link = 'detail.php?id=' . intval($b['id']);
        $bookId = $b['id'];
      ?>
      <div class="book-card" data-book-id="<?= $bookId ?>">
        <div class="cover-wrapper">
          <a href="<?= $link ?>">
            <img src="<?= $img ?>" alt="<?= $title ?>">
          </a>
          <button class="star-toggle" type="button" aria-expanded="false" title="Lihat rating">⭐</button>
        </div>

        <div class="book-title">
          <a href="<?= $link ?>"><?= $title ?></a>
        </div>

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


<!-- 📚 SEMUA BUKU -->
<section class="book-section">
  <h2 class="section-title">Semua Buku</h2>
  <div class="book-grid">
    <?php foreach ($tren as $b): ?>
      <?php 
        $img = !empty($b['gambar']) ? '../' . $b['gambar'] : '../Uploads/default.png';
        $title = htmlspecialchars($b['judul']);
        $link = 'detail.php?id=' . intval($b['id']);
        $bookId = $b['id'];
      ?>
      <div class="book-card" data-book-id="<?= $bookId ?>">
        <div class="cover-wrapper">
          <a href="<?= $link ?>">
            <img src="<?= $img ?>" alt="<?= $title ?>">
          </a>
          <button class="star-toggle" type="button" aria-expanded="false" title="Lihat rating">⭐</button>
        </div>

        <div class="book-title">
          <a href="<?= $link ?>"><?= $title ?></a>
        </div>

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

    <!-- Pagination (link sederhana dengan query string) -->
    <div id="pagination" style="margin-top:20px; text-align:center;">
      <?php if ($total_pages > 1): ?>
        <?php for ($i = 1; $i <= $total_pages; $i++): ?>
          <?php 
            $active = $i == $page ? "font-weight:bold;color:#069797;" : "color:#333;"; 
            $q = "?page=$i";
            if ($search !== '') $q .= "&search=" . urlencode($search);
          ?>
          <a href="<?= $q ?>" style="margin:0 5px; <?= $active ?>"><?= $i ?></a>
        <?php endfor; ?>
      <?php endif; ?>
    </div>
  </div>

  <!-- ==========================================================
       🔹 FOOTER
       ========================================================== -->
  <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>

  <!-- ==========================================================
       🔹 JAVASCRIPT (Bahasa: JavaScript)
       - Mengatur interaksi: sidebar toggle, notifikasi AJAX,
         search AJAX, hero slide animation
       ========================================================== -->
  <script>
  // Ambil elemen penting dari DOM
  const sidebar = document.getElementById("sidebar");
  const hamburger = document.getElementById("hamburger");
  const overlay = document.getElementById("overlay");
  const notifBtn = document.getElementById("notif-btn");
  const notifList = document.getElementById("notif-list");

  // ---------- Sidebar Toggle ----------
  // Menambahkan / menghapus kelas .active untuk menampilkan sidebar
  hamburger.addEventListener("click", () => {
    sidebar.classList.add("active");
    overlay.classList.add("active");
  });

  overlay.addEventListener("click", () => {
    sidebar.classList.remove("active");
    overlay.classList.remove("active");
  });

  // ---------- Notifikasi: buka/tutup + mark read ----------
  notifBtn.addEventListener("click", () => {
    notifList.style.display = notifList.style.display === "none" || notifList.style.display === "" ? "block" : "none";

    // Panggil endpoint untuk menandai notifikasi sebagai "dibaca"
    // (read_notifications.php harus ada di server untuk menangani ini)
    fetch('read_notifications.php')
  .then(() => {
    const badge = document.getElementById("notif-count");
    if (badge) badge.style.display = "none";
  })
  .catch(err => console.error("Gagal menandai notifikasi:", err));
  });

  // 🔔 Load Notifikasi (AJAX polling tiap 10 detik)
  // - notifications.php harus mengembalikan JSON: { count: N, notifications: [...] }
  function loadNotifications() {
    fetch('notifications.php')
      .then(res => res.json())
      .then(data => {
        let count = data.count;
        let badge = document.getElementById('notif-count');
        if (count > 0) {
          badge.style.display = 'inline-block';
          badge.textContent = count;
        } else {
          badge.style.display = 'none';
        }

        // Buat list HTML sederhana dari data.notifications
        let list = "";
        data.notifications.forEach(n => {
          // n.message dan n.created_at diasumsikan tersedia dari server
          list += `<div>📕 ${n.message}<br><small>${n.created_at}</small></div>`;
        });
        notifList.innerHTML = (list || "<div>Tidak ada notifikasi</div>") + `
  <div style="text-align:center; margin-top:10px; border-top:1px solid #eee; padding-top:8px;">
    <a href="notifications_page.php" 
       style="color:#333; font-weight:500; text-decoration:none;">
      Lihat Selengkapnya →
    </a>
  </div>
`;
      })
      .catch(err => console.error("Error load notifikasi:", err));
  }
  // Mulai polling notifikasi
  setInterval(loadNotifications, 10000);
  loadNotifications();

  // ---------- Search AJAX untuk daftar buku ----------
  // Form #searchForm akan mencegah submit default dan memanggil search_books.php
  // Endpoint search_books.php harus mengembalikan potongan HTML (kartu buku)
  document.getElementById("searchForm").addEventListener("submit", function(e) {
    e.preventDefault();

    let query = document.getElementById("searchInput").value;

    fetch("search_books.php?search=" + encodeURIComponent(query))
      .then(res => res.text())
      .then(html => {
        // Ganti konten grid buku dengan hasil dari server (potongan HTML)
        document.getElementById("bookResults").innerHTML = html;
        // Sembunyikan pagination jika sedang menampilkan hasil pencarian
        document.getElementById("pagination").style.display = query ? "none" : "block";
      })
      .catch(err => console.error("Error search:", err));
  });

 
 // === Hero Slide Background ===
 // - Mengatur array heroImages, preload gambar, lalu lakukan transisi
const heroImages = [
  '../images/bghome.jpg',
  '../images/bf.jpg'
];

// ✅ Preload semua gambar biar nggak muncul abu-abu saat ganti
heroImages.forEach(src => {
  const img = new Image();
  img.src = src;
});

let current = 0;
let showingBg1 = true;

// Ambil elemen hero bg yang sudah ada di HTML
const heroBg1 = document.getElementById('heroBg1');
const heroBg2 = document.getElementById('heroBg2');

// Set gambar awal ke dua layer
heroBg1.style.backgroundImage = `url(${heroImages[0]})`;
heroBg2.style.backgroundImage = `url(${heroImages[1]})`;
heroBg2.style.transform = "translateX(100%)"; // siap masuk dari kanan

function slideNextHero() {
  current = (current + 1) % heroImages.length;
  const nextImage = heroImages[current];

  if (showingBg1) {
    // siapkan heroBg2 untuk masuk dari kanan
    heroBg2.style.backgroundImage = `url(${nextImage})`;
    heroBg2.style.transition = "none";
    heroBg2.style.transform = "translateX(100%)";
    heroBg2.style.opacity = 1;

    // Reflow kecil biar animasi kebaca browser
    void heroBg2.offsetWidth;

    // jalankan transisi
    heroBg1.style.transition = "transform 1.2s ease-in-out, opacity 0.3s ease-in-out";
    heroBg2.style.transition = "transform 1.2s ease-in-out, opacity 0.3s ease-in-out";
    heroBg2.style.transform = "translateX(0)";
    heroBg1.style.transform = "translateX(-100%)";

  } else {
    // siapkan heroBg1 untuk masuk dari kanan
    heroBg1.style.backgroundImage = `url(${nextImage})`;
    heroBg1.style.transition = "none";
    heroBg1.style.transform = "translateX(100%)";
    heroBg1.style.opacity = 1;

    void heroBg1.offsetWidth;

    heroBg1.style.transition = "transform 1.2s ease-in-out, opacity 0.3s ease-in-out";
    heroBg2.style.transition = "transform 1.2s ease-in-out, opacity 0.3s ease-in-out";
    heroBg1.style.transform = "translateX(0)";
    heroBg2.style.transform = "translateX(-100%)";
  }

  showingBg1 = !showingBg1;
}


// Jalankan setiap 5 detik
setInterval(slideNextHero, 5000);

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.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');
      const card = p.closest('.book-card');
      card?.classList.remove('popover-open');
      const star = card?.querySelector('.star-toggle');
      star?.setAttribute('aria-expanded','false');
    }
  });
}

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);
    starBtn.setAttribute('aria-expanded', !isOpen);
    return;
  }
  if (!e.target.closest('.rating-popover')){
    closeAllPopovers();
  }
});
window.addEventListener('scroll', () => closeAllPopovers(), true);
window.addEventListener('resize', () => closeAllPopovers());
// Toggle submenu Pengaturan
(function(){
    const settingItem = document.getElementById('setting-item');
    const submenu = document.getElementById('setting-submenu');
    const caret = document.getElementById('setting-caret');

    if (!settingItem || !submenu) return;

    // toggle saat klik wrapper Pengaturan
    settingItem.addEventListener('click', () => {
      const isOpen = submenu.style.display === 'block';
      submenu.style.display = isOpen ? 'none' : 'block';
      // rotate caret
      caret.style.transform = isOpen ? 'rotate(0deg)' : 'rotate(180deg)';
    });

    // tutup submenu saat klik di luar sidebar (untuk mobile/overlay)
    document.addEventListener('click', (e) => {
      const insideSidebar = e.target.closest('.sidebar');
      if (!insideSidebar) {
        submenu.style.display = 'none';
        caret.style.transform = 'rotate(0deg)';
      }
    });

    // OPTIONAL: highlight menu aktif berdasarkan URL (jalankan sekali)
    (function highlightActive() {
      const links = document.querySelectorAll('#setting-submenu a');
      const current = window.location.pathname.split('/').pop();
      links.forEach(a => {
        const href = a.getAttribute('href').split('/').pop();
        if (href === current) {
          a.style.background = '#eef8ff';
          a.style.color = '#069797';
          a.style.fontWeight = '600';
          // buka submenu bila aktif
          submenu.style.display = 'block';
          caret.style.transform = 'rotate(180deg)';
        }
      });
    })();
  })();
</script>

</body>
</html>
