<?php
// ===========================
// 🔹 BAGIAN PHP (BACKEND)
// ===========================
require __DIR__ . '/../Login/config.php';
if (session_status() === PHP_SESSION_NONE) {
  session_start();
}

// Cek login
if (!isset($_SESSION['user_id'])) {
  header('Location: ../Login/login.php');
  exit;
}

$user_id = $_SESSION['user_id'];

// --- AMBIL FOTO PROFIL USER ---
$photoURL = "../uploads/default.jpg";
if ($user_id) {
  $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;
  }
}

$stmt = $pdo->prepare("
  SELECT 
      b.*, 
      MAX(bi.rak) AS rak, 
      COUNT(CASE WHEN bi.status = 'tersedia' THEN 1 END) AS total_stok,
      ROUND(AVG(r.rating), 2) AS avg_rating,
      COUNT(r.id) AS count_rating,
      COUNT(DISTINCT br.user_id) AS total_peminjam
  FROM wishlists w
  JOIN books b ON w.book_id = b.id
  LEFT JOIN book_items bi ON b.id = bi.book_id
  LEFT JOIN borrowings br ON bi.id = br.book_item_id AND br.status = 'dikembalikan'
  LEFT JOIN reviews r ON r.book_id = b.id
  WHERE w.user_id = ?
  GROUP BY b.id
  ORDER BY b.judul
");
$stmt->execute([$user_id]);
$books = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Buku Favorit | Pustakaia</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <style>
    body {
      margin: 0;
      font-family: "Poppins", Arial, sans-serif;
      background: linear-gradient(135deg, #f9f9f9, #e9f5ec);
      color: #222;
      overflow-x: hidden;
    }
    a { text-decoration: none; color: inherit; }

    /* === HEADER === */
    header {
      position: relative;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 25px;
      background: #fff;
      border-bottom: 1px solid #ddd;
      top: 0;
      z-index: 1000;
    }

    .left-header {
      display: flex;
      align-items: center;
      gap: 15px;
    }
    .hamburger {
      font-size: 28px;
      color: #069797;
      cursor: pointer;
      user-select: none;
      transition: color 0.3s;
    }
    .logo {
      font-size: 22px;
      font-weight: 600;
      color: #069797;
    }

    nav {
      display: flex;
      align-items: center;
      gap: 20px;
      position: relative;
    }

    .notif-wrapper {
      position: relative;
      display: inline-block;
    }
    .notif-icon {
      font-size: 22px;
      cursor: pointer;
      color: #069797;
      display: inline-flex;
      align-items: center;
      gap: 8px;
    }
    .notif-badge {
      background: red;
      color: #fff;
      border-radius: 50%;
      font-size: 12px;
      padding: 2px 6px;
      margin-left: 6px;
      display: none;
    }

    #notif-list {
      display: none;
      position: absolute;
      top: 60px;
      right: 25px;
      background: #fff;
      border: 1px solid #ddd;
      box-shadow: 0 4px 12px rgba(0,0,0,0.1);
      width: 300px;
      border-radius: 10px;
      z-index: 1200;
      padding: 10px 15px;
      max-height: none !important;
      overflow: visible !important;
    }
    #notif-list .notif-row {
      display: flex;
      gap: 10px;
      align-items: flex-start;
      padding: 8px 6px;
      border-radius: 6px;
    }
    #notif-list .notif-row + .notif-row { margin-top: 6px; }
    #notif-list .notif-row small { display:block; color:#777; font-size:12px; margin-top:4px; }
    .notif-wrapper.open #notif-list { display: block; }

    @media (max-width: 480px) {
      #notif-list { width: 90vw; right: 5vw; left: 5vw; top: 56px; }
    }

    /* === SIDEBAR === */
    .sidebar {
      width: 250px;
      height: 100vh;
      background: #fff;
      border-right: 1px solid #ddd;
      position: fixed;
      top: 0; left: -100%;
      transition: left 0.3s ease;
      z-index: 1100;
      overflow-y: auto;
    }
    .sidebar.active { left: 0; }
    .sidebar-header {
      text-align: center;
      padding: 20px 15px;
      border-bottom: 1px solid #ddd;
    }
    .sidebar-header img {
      width: 80px; height: 80px;
      border-radius: 50%;
      object-fit: cover;
      border: 2px solid #069797;
      margin-bottom: 8px;
    }
    .sidebar-header .logo { text-align: left; margin-bottom: 10px; }
    .sidebar-header .user-info { text-align: left; margin-top: 8px; padding-left: 10px; }
    .sidebar-header h2 { margin: 0; font-size: 17px; color: #333; }
    .sidebar-header p { margin: 0; font-size: 13px; color: #777; }

    .sidebar-menu {
      list-style: none;
      padding: 0;
      margin: 10px 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; }

    .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; }

    /* === KONTEN UTAMA === */
    .container {
      width: 95%;
      max-width: 1400px;;
      margin: 100px auto;
      background: #fff;
      padding: 30px 50px;
      border-radius: 10px;
      box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    }
    .container h2 {
      color: #069797;
      font-size: 24px;
      margin-bottom: 20px;
      font-weight: 600;
    }
    .favorite-card {
      display: flex;
      gap: 20px;
      border: 1px solid #eee;
      border-radius: 8px;
      padding: 15px;
      margin-bottom: 20px;
      background: #fcfcfc;
    }
    .favorite-card img {
      width: 120px;
      height: 190px;
      object-fit: cover;
      border-radius: 6px;
      flex-shrink: 0;
    }
    .favorite-info { flex: 1; }
    .favorite-info h3 {
      margin: 0;
      font-size: 18px;
      color: #069797;
    }
    .favorite-info p {
      margin: 6px 0;
      color: #444;
      font-size: 14px;
    }
    .favorite-info small { color: #777; }
    .btn {
      display: inline-block;
      background: #069797;
      color: #fff;
      padding: 8px 14px;
      border-radius: 5px;
      font-weight: 600;
      text-decoration: none;
      transition: background 0.2s;
    }
    .btn:hover { background: #048b8b; }
    .empty {
      text-align: center;
      color: #666;
      padding: 40px 0;
    }

    /* === FOOTER === */
    html, body {
      height: 100%;
      display: flex;
      flex-direction: column;
    }
    .container { flex: 1; }
    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;
    }
    
.favorite-info .meta {
    margin-top: 8px;
    font-size: 14px;
    color: #444;
    line-height: 1.5;
}
.favorite-info .meta div {
    margin-bottom: 4px; /* spasi antar baris */
}
  </style>
</head>
<body>

  <!-- SIDEBAR -->
  <aside class="sidebar" id="sidebar">
    <div class="sidebar-header">
      <div class="logo">📚 Pustakaia</div>
      <img src="<?= htmlspecialchars($photoURL) ?>" alt="Foto Profil">
      <div class="user-info">
        <h2><?= htmlspecialchars($_SESSION['fullname'] ?? 'Pengguna') ?></h2>
        <p><?= htmlspecialchars(ucfirst($_SESSION['role'] ?? 'User')) ?></p>
      </div>
    </div>
    <ul class="sidebar-menu">
      <li onclick="window.location.href='books.php'"><i class="fa fa-book"></i> Semua Buku</li>
      <li onclick="window.location.href='notifications_page.php'"><i class="fa fa-bell"></i> Notifikasi</li>
      <li onclick="window.location.href='favorites.php'"><i class="fa fa-heart"></i> Favorit</li>
      <li class="active"><i class="fa fa-bookmark"></i> Simpanan Saya</li>
     <li><a href="borrowed_list.php"><i class="fa fa-book-reader"></i> Pinjaman Saya</li>
     <li><a href="library_card.php"><i class="fa fa-id-card"></i> Kartu Perpustakaan</li>
    </ul>
    <hr>
    <ul class="sidebar-menu">
      <li><a href="profile.php"><i class="fa fa-cog"></i> Pengaturan</a></li>
      <li onclick="window.location.href='../Login/Logout.php'"><i class="fa fa-sign-out-alt"></i> Keluar</li>
    </ul>
  </aside>

  <div class="overlay" id="overlay"></div>

  <!-- HEADER -->
  <header>
    <div class="left-header">
      <span class="hamburger" id="hamburger">☰</span>
      <div class="logo">📚 Pustakaia</div>
    </div>

    <nav>
      <div class="notif-wrapper" id="notif-wrapper">
        <div class="notif-icon" id="notif-btn">🔔 <span id="notif-count" class="notif-badge"></span></div>
        <div id="notif-list" aria-hidden="true">
          <div style="text-align:center; color:#777;">Memuat notifikasi...</div>
        </div>
      </div>
      <a href="../Login/Logout.php">Keluar</a>
    </nav>
  </header>

  <!-- KONTEN UTAMA -->
  <div class="container">
  <h2>Wishlist Saya</h2>

  <?php if (count($books) === 0): ?>
    <div class="empty">Belum ada buku yang kamu simpan.</div>
  <?php else: ?>
    <?php foreach ($books as $book): ?>
      <div class="favorite-card">
        <img 
          src="<?= htmlspecialchars('../' . ($book['gambar'] ?: 'Uploads/default.png')) ?>" 
          alt="<?= htmlspecialchars($book['judul']) ?>">
        
        <div class="favorite-info">
          <h3><?= htmlspecialchars($book['judul']) ?></h3>
          <p><strong><?= htmlspecialchars($book['penulis'] ?: '-') ?></strong></p>
          <p><?= nl2br(htmlspecialchars(substr($book['sinopsis'], 0, 150))) ?>...</p>

          <div class="meta">
          <div>⭐ <?= $book['avg_rating'] ? number_format($book['avg_rating'], 1) : '0.0' ?></div>
    <div>📦 <?= $book['total_stok'] ?> stok</div>
    <div>👥 <?= $book['total_peminjam'] ?> peminjam</div>
    <div>📍 <?= htmlspecialchars($book['rak'] ?: '-') ?></div>
</div>

          <a href="detail.php?id=<?= $book['id'] ?>" class="btn">Lihat Detail</a>
        </div>
      </div>
    <?php endforeach; ?>
  <?php endif; ?>
</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>

  <script>
  const notifWrapper = document.getElementById('notif-wrapper');
  const notifBtn = document.getElementById('notif-btn');
  const notifList = document.getElementById('notif-list');
  const notifCount = document.getElementById('notif-count');

  notifBtn.addEventListener('click', (e) => {
    e.stopPropagation();
    notifWrapper.classList.toggle('open');
    fetch('read_notifications.php').catch(()=>{});
    if (notifCount) notifCount.style.display = 'none';
  });

  document.addEventListener('click', (e) => {
    if (!notifWrapper.contains(e.target)) notifWrapper.classList.remove('open');
  });

  function loadNotifications() {
    fetch('notifications.php').then(res => res.json()).then(data => {
      if (data.count && data.count > 0) {
        notifCount.style.display = 'inline-block';
        notifCount.textContent = data.count;
      } else {
        notifCount.style.display = 'none';
      }

      let html = '';
      if (data.notifications && data.notifications.length) {
        data.notifications.forEach(n => {
          html += `<div class="notif-row">
                    <div style="font-size:18px;line-height:1;">📕</div>
                    <div>
                      <div style="font-size:13px;color:#222;">${escapeHtml(n.message)}</div>
                      <small>${escapeHtml(n.created_at)}</small>
                    </div>
                  </div>`;
        });
        html += `<div style="padding-top:8px;border-top:1px solid #eee;margin-top:8px;"><a href="notifications_page.php">Lihat Selengkapnya →</a></div>`;
      } else {
        html = '<div style="text-align:center;color:#777;">Tidak ada notifikasi</div>';
      }
      notifList.innerHTML = html;
    }).catch(() => {
      notifList.innerHTML = '<div style="text-align:center;color:#777;">Gagal memuat notifikasi</div>';
    });
  }

  function escapeHtml(str) {
    if (!str) return '';
    return String(str).replace(/[&<>"']/g, m => (
      {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'" :'&#39;'}[m]
    ));
  }

  loadNotifications();

  const sidebar = document.getElementById('sidebar');
  const overlay = document.getElementById('overlay');
  const hamburger = document.getElementById('hamburger');

  hamburger.addEventListener('click', () => {
    sidebar.classList.add('active');
    overlay.classList.add('active');
  });

  overlay.addEventListener('click', () => {
    sidebar.classList.remove('active');
    overlay.classList.remove('active');
  });
  </script>

</body>
</html>
