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

if (session_status() === PHP_SESSION_NONE) {
  session_start();
}

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

$user_id = (int)$_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;
}

// --- PAGINATION (opsional, boleh dipakai atau di-skip) ---
$page  = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$limit = 20;
$offset = ($page - 1) * $limit;

// Hitung total notifikasi user ini
$stmtCount = $pdo->prepare("SELECT COUNT(*) FROM notifications WHERE user_id = :uid");
$stmtCount->execute([':uid' => $user_id]);
$total_notifs = (int)$stmtCount->fetchColumn();
$total_pages  = (int)ceil($total_notifs / $limit);

// --- AMBIL NOTIFIKASI HANYA PUNYA USER INI ---
$stmt = $pdo->prepare("
  SELECT id, type, message, is_read, created_at
  FROM notifications
  WHERE user_id = :uid
  ORDER BY created_at DESC
  LIMIT :lim OFFSET :off
");
$stmt->bindValue(':uid', $user_id, PDO::PARAM_INT);
$stmt->bindValue(':lim', $limit, PDO::PARAM_INT);
$stmt->bindValue(':off', $offset, PDO::PARAM_INT);
$stmt->execute();
$notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);

// --- TANDAI NOTIFIKASI USER INI SEBAGAI DIBACA ---
$mark = $pdo->prepare("UPDATE notifications SET is_read = 1 WHERE user_id = :uid AND is_read = 0");
$mark->execute([':uid' => $user_id]);

?>
<!DOCTYPE html>
<html lang="id">
<head>
  <!-- ===========================
       🔹 META & TITLE HTML
  ============================ -->
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Notifikasi | Pustakaia</title>

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

  <!-- ===========================
       🔹 BAGIAN CSS (TATA LETAK & DESAIN)
  ============================ -->
  <style>
    /* === Gaya umum halaman === */
    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 (Sama seperti di books.php) === */
    header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 25px;
      background: #fff;
      border-bottom: 1px solid #ddd;
      position: sticky;
      top: 0;
      z-index: 1000;
    }

     /* === Ikon notifikasi di header === */
     .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;
    }


    /* Bagian kiri header: tombol hamburger + logo */
    .left-header {
      display: flex;
      align-items: center;
      gap: 15px;
    }

    /* Tombol hamburger untuk membuka sidebar */
    .hamburger {
      font-size: 28px;
      color: #069797;
      cursor: pointer;
      font-weight: bold;
      user-select: none;
      transition: color 0.3s;
    }
    .hamburger:hover { color: #048080; }

    .logo {
      font-size: 22px;
      font-weight: 600;
      color: #069797;
    }

    /* Navigasi kanan header */
    nav {
      display: flex;
      align-items: center;
      gap: 20px;
    }
    nav a {
      color: #333;
      font-weight: 500;
      transition: color 0.3s;
    }
    nav a:hover { color: #069797; }

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

    /* Header dalam sidebar */
    .sidebar-header {
  text-align: center; /* biar foto tetap di tengah */
  padding: 20px 15px;
  border-bottom: 1px solid #ddd;
}

.sidebar-header .logo {
  text-align: left; /* logo ke kiri */
  margin-bottom: 10px;
}

.sidebar-header .user-info {
  text-align: left; /* fullname & role ke kiri */
  margin-top: 8px;
  padding-left: 10px;
}

    .sidebar-header img {
      width: 80px; height: 80px;
      border-radius: 50%;
      object-fit: cover;
      border: 2px solid #069797;
      margin-bottom: 8px;
    }
    .sidebar-header h2 { margin: 0; font-size: 17px; color: #333; }
    .sidebar-header p { margin: 0; font-size: 13px; color: #777; }

    /* Menu dalam sidebar */
    .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; }

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

    /* Overlay (background gelap ketika sidebar muncul) */
    .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; }

    /* === POPUP LIST NOTIFIKASI (di header) === */
    #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;
    }
    #notif-list div {
      font-size: 14px; color: #333;
      margin-bottom: 10px;
    }
    #notif-list small {
      color: #777; display: block;
      font-size: 12px;
    }
    #notif-list a {
      display: inline-block;
      text-align: center;
      width: 100%;
      color: #333;
      font-size: 13px;
      text-decoration: none;
      border-top: 1px solid #eee;
      padding-top: 8px;
      margin-top: 5px;
    }

    /* === KONTEN UTAMA HALAMAN (DAFTAR NOTIFIKASI) === */
    .notif-container {
  width: 95%;                /* dari 90% → 95% biar lebih lebar */
  max-width: 1400px;         /* batasi supaya di layar besar tetap enak */
  margin: 100px auto;        /* tetap tengah secara horizontal */
  background: #fff;          /* tetap ada background putih */
  padding: 30px 50px;        /* sedikit padding di dalam */
  border-radius: 10px;       /* biar nggak terlalu kotak */
  box-shadow: 0 2px 10px rgba(0,0,0,0.05); /* halus banget */
}
.notif-container h2 {
  color: #069797; /* warna utama khas Pustakaia */
  font-size: 24px;
  margin-bottom: 20px;
  font-weight: 600;
}

    .notif-item {
      border-bottom: 1px solid #eee;
      padding: 12px 0;
    }
    .notif-item:last-child { border-bottom: none; }
    .notif-message { font-size: 15px; color: #333; margin-bottom: 4px; }
    .notif-time { font-size: 12px; color: #777; }

    /* === 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;
    }
  </style>
</head>

<body>
  <!-- ===========================
       🔹 SIDEBAR NAVIGASI
  ============================ -->
  <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>

    <!-- Menu navigasi utama -->
    <ul class="sidebar-menu">
      <li onclick="window.location.href='books.php'"><i class="fa fa-book"></i> Semua Buku</li>
      <li class="active"><i class="fa fa-bell"></i> Notifikasi</li>
      <li onclick="window.location.href='favorites.php'"><i class="fa fa-heart"></i> Favorit</li>
      <li onclick="window.location.href='saved.php'"><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>

    <!-- Menu pengaturan dan logout -->
    <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>

  <!-- Overlay hitam ketika sidebar terbuka -->
  <div class="overlay" id="overlay"></div>

  <!-- ===========================
       🔹 HEADER UTAMA HALAMAN
  ============================ -->
  <header>
    <div class="left-header">
      <span class="hamburger" id="hamburger">☰</span>
      <div class="logo">📚 Pustakaia</div>
    </div>
    <nav>
      <div class="notif-icon" id="notif-btn">🔔
        <span class="notif-badge" id="notif-count"></span>
      </div>
      <a href="../Login/Logout.php">Keluar</a>
    </nav>
    <div id="notif-list"></div>
  </header>

  <!-- ===========================
       🔹 KONTEN UTAMA: DAFTAR NOTIFIKASI
  ============================ -->
  <div class="notif-container">
    <h2> Notifikasi</h2>
    <?php if (empty($notifications)): ?>
      <p style="text-align:center; color:#777;">Tidak ada notifikasi saat ini.</p>
    <?php else: ?>
      <?php foreach ($notifications as $n): ?>
        <div class="notif-item">
          <div class="notif-message">📕 <?= htmlspecialchars($n['message']) ?></div>
          <div class="notif-time"><?= htmlspecialchars($n['created_at']) ?></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>

  <!-- ===========================
       🔹 BAGIAN JAVASCRIPT (INTERAKTIFITAS)
  ============================ -->
  <script>
    // Ambil elemen 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");

    // --- Fungsi: buka sidebar ---
    hamburger.addEventListener("click", () => {
      sidebar.classList.add("active");
      overlay.classList.add("active");
    });

    // --- Fungsi: tutup sidebar ---
    overlay.addEventListener("click", () => {
      sidebar.classList.remove("active");
      overlay.classList.remove("active");
    });

    // --- Fungsi: tampilkan popup notifikasi di header ---
    notifBtn.addEventListener("click", (e) => {
      e.stopPropagation();
      notifList.style.display = notifList.style.display === "none" || notifList.style.display === "" ? "block" : "none";

      // Tandai notifikasi sebagai dibaca
      fetch('read_notifications.php').then(() => {
        document.getElementById('notif-count').style.display = 'none';
      });
    });

    // --- Tutup popup notifikasi jika klik di luar area ---
    document.addEventListener("click", (e) => {
      if (!notifList.contains(e.target) && !notifBtn.contains(e.target)) {
        notifList.style.display = "none";
      }
    });

    // --- Fungsi: load notifikasi terbaru dari server ---
    function loadNotifications() {
      fetch('notifications.php')
        .then(res => res.json())
        .then(data => {
          let badge = document.getElementById('notif-count');

          // Tampilkan jumlah notifikasi belum dibaca
          if (data.count > 0) {
            badge.style.display = 'inline-block';
            badge.textContent = data.count;
          } else {
            badge.style.display = 'none';
          }

          // Tampilkan isi popup notifikasi
          let list = "";
          data.notifications.forEach(n => {
            list += `<div>📕 ${n.message}<small>${n.created_at}</small></div>`;
          });

          notifList.innerHTML =
            (list || "<div>Tidak ada notifikasi</div>") +
            `<a href="notifications_page.php">Lihat Selengkapnya →</a>`;
        });
    }

    // Jalankan fungsi load notifikasi saat halaman dibuka
    loadNotifications();
  </script>
</body>
</html>
