<?php
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 data user
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

// Foto profil
$photoURL = "../uploads/default.jpg";
if (!empty($user['photo']) && file_exists("../uploads/" . $user['photo'])) {
  $photoURL = "../uploads/" . $user['photo'];
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Kartu Pustakaia | 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;
      display: flex;
      flex-direction: column;
      min-height: 100vh;
    }
    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;
    }
    .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;
    }
    .notif-wrapper.open #notif-list { display: block; }

    /* === 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: 900px; margin: 100px auto;
      background: #fff; padding: 30px 50px;
      border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.05);
      flex: 1;
    }
    .container h2 {
      color: #069797; font-size: 24px;
      margin-bottom: 20px; font-weight: 600;
    }

    /* ====== KARTU ====== */
    .library-card {
      background: #fff;
      width: 580px;
      height: 340px;
      border-radius: 18px;
      box-shadow: 0 8px 20px rgba(0,0,0,0.15);
      margin: 40px auto;
      overflow: hidden;
      position: relative;
      display: flex;
      flex-direction: column;
      color: #333;
      transition: transform 0.2s ease;
    }

    .library-card:hover {
      transform: translateY(-4px);
    }

    .card-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      background: #069797;
      color: #fff;
      padding: 12px 20px;
      font-weight: 600;
      font-size: 18px;
      letter-spacing: 0.5px;
    }

    .card-body {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      padding: 25px;
      flex: 1;
      position: relative;
    }

    /* KIRI */
    .left {
      text-align: center;
      width: 40%;
    }

    .photo {
      width: 120px;
      height: 140px;
      border-radius: 10px;
      object-fit: cover;
      border: 3px solid #069797;
      background: #f4fdfd;
      margin-bottom: 15px;
      box-shadow: 0 3px 10px rgba(0,0,0,0.1);
    }

    /* KANAN */
    .right {
      width: 55%;
      background: #f6fbfb;
      border-radius: 10px;
      padding: 15px 20px;
      border: 1px solid #d8efef;
    }

    .fullname {
      font-weight: 700;
      font-size: 20px;
      margin-bottom: 8px;
      text-transform: uppercase;
      color: #069797;
    }

    .role {
      font-size: 13px;
      color: #666;
      margin-bottom: 15px;
    }

    .right p {
      margin: 5px 0;
      font-size: 15px;
      display: flex;
      justify-content: space-between;
      border-bottom: 1px dashed rgba(0,0,0,0.1);
      padding-bottom: 3px;
    }

    footer{background:#fff;padding:20px 30px 40px;font-size:14px;color:#222;margin-top:auto;text-align:left;}
    .footer-bottom{display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;font-size:13px;width:100%;}
    body { position: relative; min-height: 100vh; }

    footer {
      position: absolute; bottom: 0; left: 0; width: 100%;
    }

    /* Supaya konten tidak ketutup footer */
    .content { padding-bottom: 120px; }
  </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 onclick="window.location.href='saved.php'"><i class="fa fa-bookmark"></i> Simpanan Saya</li>
      <li onclick="window.location.href='borrowed_list.php'"><i class="fa fa-book-reader"></i> Pinjaman Saya</li>
      <li class="active"><i class="fa fa-id-card"></i> Kartu Perpustakaan</li>
    </ul>
    <hr>
    <ul class="sidebar-menu">
      <li onclick="window.location.href='profile.php'"><i class="fa fa-cog"></i> Pengaturan</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"><div style="text-align:center; color:#777;">Memuat notifikasi...</div></div>
      </div>
      <a href="../Login/Logout.php">Keluar</a>
    </nav>
  </header>

  <!-- KONTEN -->
  <div class="content">
    <main class="content">
      <div class="library-card">
        <div class="card-header">
          <span><i class="fa fa-id-card"></i> Pustakaia Digital</span>
        </div>

        <div class="card-body">
          <div class="left">
            <img src="<?php echo $user['photo'] ? '../uploads/'.$user['photo'] : '../images/default_user.png'; ?>" alt="Foto Profil" class="photo">
          </div>

          <div class="right">
            <p class="fullname"><?php echo htmlspecialchars($user['fullname']); ?></p>
            <p class="role">Anggota Perpustakaan Digital</p>
            <p><span>NIS</span><span><?php echo htmlspecialchars($user['nis']); ?></span></p>
            <p><span>Kelas</span><span><?php echo htmlspecialchars($user['class']); ?></span></p>
            <p><span>No HP</span><span><?php echo htmlspecialchars($user['phone']); ?></span></p>
          </div>
        </div>
      </div>
    </main>
  </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>

  <!-- Library JS (cukup sekali masing-masing) -->
  <script src="https://unpkg.com/html2canvas@1.4.1/dist/html2canvas.min.js"></script>
  <script src="https://unpkg.com/jspdf@2.5.1/dist/jspdf.umd.min.js"></script>

  <script>
  document.addEventListener("DOMContentLoaded", function() {
    const card = document.querySelector(".library-card");

    // === Tambahkan tombol download/print ===
    const btnContainer = document.createElement("div");
    btnContainer.style.textAlign = "center";
    btnContainer.style.marginTop = "20px";
    btnContainer.innerHTML = `
      <button id="downloadPNG" style="padding:8px 14px;background:#069797;color:#fff;border:none;border-radius:6px;cursor:pointer;margin-right:10px;">Download PNG</button>
      <button id="downloadPDF" style="padding:8px 14px;background:#069797;color:#fff;border:none;border-radius:6px;cursor:pointer;margin-right:10px;">Download PDF</button>
      <button id="printCard" style="padding:8px 14px;background:#444;color:#fff;border:none;border-radius:6px;cursor:pointer;">Print</button>
    `;
    card.insertAdjacentElement("afterend", btnContainer);

    // === Fungsi umum untuk ambil gambar kartu ===
    async function generateImage() {
      return await html2canvas(card, {
        scale: 2,
        useCORS: true,
        allowTaint: false,
      });
    }

    // === Download PNG ===
    document.getElementById("downloadPNG").addEventListener("click", async () => {
      const canvas = await generateImage();
      const link = document.createElement("a");
      link.download = "kartu_pustakaia.png";
      link.href = canvas.toDataURL("image/png");
      link.click();
    });

    // === Download PDF ===
    document.getElementById("downloadPDF").addEventListener("click", async () => {
      const canvas = await generateImage();
      const imgData = canvas.toDataURL("image/png");
      const { jsPDF } = window.jspdf;
      const pdf = new jsPDF({
        orientation: "landscape",
        unit: "px",
        format: [canvas.width, canvas.height]
      });
      pdf.addImage(imgData, "PNG", 0, 0, canvas.width, canvas.height);
      pdf.save("kartu_pustakaia.pdf");
    });

    // === Print Card ===
    document.getElementById("printCard").addEventListener("click", async () => {
      const canvas = await generateImage();
      const imgData = canvas.toDataURL("image/png");
      const win = window.open("");
      win.document.write("<title>Print Kartu</title>");
      win.document.write("<img src='" + imgData + "' style='width:100%;max-width:600px;'>");
      win.document.close();
      win.focus();
      win.print();
      win.close();
    });
  });

  // ==== SISA SCRIPT KAMU (notif & sidebar) ====
  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;">📕</div>
                      <div><div style="font-size:13px;color:#222;">${escapeHtml(n.message)}</div>
                      <small>${escapeHtml(n.created_at)}</small></div>
                    </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){return str?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>
