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

$id = intval($_GET['id'] ?? 0);
if ($id <= 0) {
    header('Location: index2.php');
    exit;
}


// Ambil data buku (sama logic-mu)
$stmt = $pdo->prepare("
  SELECT 
      b.*, 
      MAX(bi.rak) AS rak, 
      COUNT(CASE WHEN bi.status = 'tersedia' THEN 1 END) AS total_stok
  FROM books b
  LEFT JOIN book_items bi ON b.id = bi.book_id
  WHERE b.id = ?
  GROUP BY b.id
  LIMIT 1
");
$stmt->execute([$id]);
$book = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$book) {
    echo "Buku tidak ditemukan.";
    exit;
}

// Gambar
$default_img = 'Uploads/default.png';
if (!empty($book['gambar'])) {
    $relative_path = $book['gambar']; // langsung ambil path dari database
    $absolute_path = __DIR__ . '/' . $book['gambar']; // path sejajar
    $img = file_exists($absolute_path) ? $relative_path : $default_img;
} else {
    $img = $default_img;
}






// Format tampilan data
$berat_display   = $book['berat']   ? (number_format($book['berat'] / 1000, 2) . ' kg') : '-';
$panjang_display = $book['panjang'] ? ($book['panjang'] . ' cm') : '-';
$lebar_display   = $book['lebar']   ? ($book['lebar'] . ' cm') : '-';
$stok_display = intval($book['total_stok'] ?? 0);
$kategori        = $book['kategori'] ?? '-';
$lokasi_rak   = $book['rak'] ? $book['rak'] : '-';

// jumlah peminjam (distinct user_id)
$stmt_borrow = $pdo->prepare("
    SELECT COUNT(DISTINCT br.user_id) AS total_peminjam
    FROM borrowings br
    JOIN book_items bi ON br.book_item_id = bi.id
    WHERE bi.book_id = :book_id
      AND br.status = 'dikembalikan'
");
$stmt_borrow->execute([':book_id' => $id]);
$total_peminjam = (int)$stmt_borrow->fetchColumn();

// reviews (read-only here)
$stmt_reviews = $pdo->prepare("SELECT r.*, u.username FROM reviews r JOIN users u ON r.user_id = u.id WHERE book_id = ? ORDER BY tanggal DESC LIMIT 6");
$stmt_reviews->execute([$id]);
$reviews = $stmt_reviews->fetchAll(PDO::FETCH_ASSOC);

// avg rating
$stmt_avg = $pdo->prepare("SELECT AVG(rating) AS avg_rating, COUNT(*) AS count_rating FROM reviews WHERE book_id = ?");
$stmt_avg->execute([$id]);
// detail distribusi rating
$stmt_rating_dist = $pdo->prepare("
  SELECT rating, COUNT(*) AS jumlah 
  FROM reviews 
  WHERE book_id = ? 
  GROUP BY rating
");
$stmt_rating_dist->execute([$id]);
$rating_dist_rows = $stmt_rating_dist->fetchAll(PDO::FETCH_ASSOC);

// susun jadi array dengan default 0 untuk semua bintang
$rating_dist = [1=>0,2=>0,3=>0,4=>0,5=>0];
foreach ($rating_dist_rows as $r) {
  $rating = intval($r['rating']);
  $rating_dist[$rating] = intval($r['jumlah']);
}
$avgrow = $stmt_avg->fetch(PDO::FETCH_ASSOC);
$avg_rating = $avgrow && $avgrow['avg_rating'] ? floatval($avgrow['avg_rating']) : null;
$count_rating = intval($avgrow['count_rating'] ?? 0);

// related books
$stmt_related = $pdo->prepare("SELECT id, judul, penulis, gambar FROM books WHERE kategori = ? AND id != ? LIMIT 4");
$stmt_related->execute([$kategori, $book['id']]);
$related = $stmt_related->fetchAll(PDO::FETCH_ASSOC);

// helper: render star html (filled color toska)
function render_stars($avg) {
    $html = '';
    if ($avg === null) return '<span style="color:#999">Belum ada rating</span>';
    $rounded = round($avg * 2) / 2; // nearest 0.5
    for ($i=1; $i<=5; $i++) {
        if ($rounded >= $i) {
            $html .= '<span style="color:#f5a623;font-size:16px">★</span>'; // filled
        } elseif ($rounded + 0.5 == $i) {
            // half star: use a half-star unicode fallback (use ★ with opacity)
            $html .= '<span style="color:#f5a623;font-size:16px;position:relative;display:inline-block;">★</span>';
        } else {
            $html .= '<span style="color:#ddd;font-size:16px">★</span>'; // empty (gray)
        }
    }
    $html .= ' <small style="color:#666;margin-left:6px">(' . number_format($avg,2) . ' / 5 — ' . $GLOBALS['count_rating'] . ')</small>';
    return $html;
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <title><?= htmlspecialchars($book['judul'] ?? 'Detail Buku') ?> - Pustakaia</title>
  <style>
    :root{--accent:#069797;}
    body{
      margin:0;font-family:"Poppins", Arial, sans-serif;background:#f9f9f9;color:#222;
      min-height:100vh;display:flex;flex-direction:column;
    }
    a{text-decoration:none;color:inherit;}
    header{display:flex;justify-content:space-between;align-items:center;padding:15px 30px;background:#fff;border-bottom:1px solid #ddd;position:sticky;top:0;z-index:100;}
    .logo{font-size:20px;font-weight:bold;color:var(--accent);display:flex;align-items:center;gap:10px;}
    .back-btn{font-size:18px;color:var(--accent);margin-right:8px;}
    main{flex:1;max-width:1000px;margin:28px auto;padding:0 16px;}
    .book-container {
  max-width: 1200px;       /* dari 1000px → 1200px */
  margin: 30px auto;       /* sedikit rapetin jarak atas bawah */
  padding: 30px 40px;      /* kasih ruang dalam biar lega tapi proporsional */
  background: #fff;
  box-shadow: 0 6px 18px rgba(0,0,0,0.08);
  border-radius: 10px;
}
.book-header {
  display: flex;
  gap: 40px;
  flex-wrap: wrap;
  margin-bottom: 25px;
}

.book-header img {
  width: 260px;                  /* dari 220px → 260px */
  height: auto;
  border-radius: 8px;
  object-fit: cover;
  box-shadow: 0 3px 10px rgba(0,0,0,0.12);
  flex-shrink: 0;                /* biar gak ketarik saat layar lebar */
}
.book-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 8px;
}
    .book-info{flex:1;}
    .book-info h1{margin:0;font-size:24px;color:var(--accent);}
    .book-info h2{margin:6px 0;color:#444;font-size:16px;font-weight:500;}
    .meta{margin-top:8px;color:#666;font-size:14px;display:flex;gap:12px;flex-wrap:wrap;align-items:center;}
    .meta .rating{display:inline-flex;align-items:center;gap:6px}
    .synopsis{margin-top:12px;color:#333;line-height:1.6;}
    .actions{margin-top:12px;display:flex;gap:10px;align-items:center;}
    .btn {padding:8px 12px;border-radius:6px;border:1px solid #e6e6e6;background:#fff;cursor:pointer;font-weight:600}
    .btn.wishlist.active{background:var(--accent);color:#fff;border:none;box-shadow:0 6px 18px rgba(6,151,151,0.08)}
    .btn.fav.active{background:#ff6b6b;color:#fff;border:none;box-shadow:0 6px 18px rgba(255,107,107,0.08)}
    .detail-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  gap: 24px;
  margin-top: 28px;
  padding: 24px 28px;
  border-radius: 12px;
  background: #fcfcfc;
  border: 1px solid #eaeaea;
  font-family: "Poppins", Arial, sans-serif;
  transition: all 0.3s ease;
}

.detail-grid div {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.detail-grid div p strong {
  color: #06a0a0;
  font-size: 14px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.4px;
}

.detail-grid div p {
  color: #555; /* abu lembut */
  font-size: 15.5px;
  font-weight: 500;
  margin: 0;
  line-height: 1.5;
}

    .related{margin-top:18px}
    .related-list{display:flex;gap:12px;flex-wrap:wrap}
    .related-card{width:150px;background:#fff;border-radius:6px;padding:8px;border:1px solid #eee;text-align:center}
    .related-card img{width:100%;height:200px;object-fit:cover;border-radius:4px}
    .reviews{margin-top:18px}
    .review-card{background:#fff;border-radius:6px;padding:10px;border:1px solid #eee;margin-bottom:8px}
    .borrow-btn{position:fixed;bottom:0;left:0;width:100%;padding:14px;background:var(--accent);color:#fff;font-size:18px;font-weight:bold;text-align:center;border:none;cursor:pointer}
    .borrow-btn.disabled{background:#ccc;cursor:not-allowed}
    footer {
  background: #fff;
  padding: 20px 30px 40px; /* kiri kanan sejajar header */
  font-size: 14px;
  color: #222;
  margin-top: auto;
  text-align: left; /* pastikan semua text rata kiri */
}
.footer-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  font-size: 13px;
  width: 100%;
}
    @media(max-width:820px){
      .book-header{flex-direction:column;align-items:center}
      .book-header img{width:160px;height:auto}
    }
    /* small toast */
    .toast{position:fixed;right:20px;bottom:20px;background:#111;color:#fff;padding:10px 14px;border-radius:8px;opacity:0;transform:translateY(10px);transition:all .25s}
    .toast.show{opacity:1;transform:translateY(0)}
    @media (min-width: 1200px) {
  .book-header {
    align-items: center;
  }
  .book-header img {
    width: 300px; /* biar tampil elegan di layar lebar */
  }
}
.action-buttons {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  gap: 12px;
  margin-top: 20px;
}

.action-buttons button {
  background-color: #069797;
  color: #fff;
  border: none;
  padding: 10px 18px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: not-allowed;
  opacity: 0.9;
  transition: background 0.3s ease;
}

.action-buttons button:hover {
  background-color: #047979;
}
/* ==== Modal Login ==== */
.modal-backdrop { position:fixed; inset:0; background:rgba(0,0,0,.55); display:none; z-index:9999; }
.modal { position:fixed; left:50%; top:50%; transform:translate(-50%,-50%); background:#fff;
  width:min(92vw,420px); border-radius:12px; padding:20px; box-shadow:0 10px 30px rgba(0,0,0,.2);
  display:none; z-index:10000; }
.modal h3 { margin:0 0 8px 0; color:#069797; }
.modal p { margin:0 0 16px 0; color:#333; }
.modal .actions { display:flex; gap:10px; justify-content:flex-end; }
.modal .btn { padding:10px 14px; border-radius:8px; border:1px solid #ddd; cursor:pointer; background:#fff; }
.modal .btn-primary { background:#069797; color:#fff; border-color:#069797; }


  </style>
</head>
<body>

<header>
  <div class="logo">
    <a href="index2.php" class="back-btn">⬅</a>
    📚 Pustakaia
  </div>
</header>
<?php if (isset($_GET['success'])): ?>
  <div style="background:#e0f7f7;color:#069797;padding:10px;margin:15px auto;width:90%;max-width:800px;
              border-radius:6px;text-align:center;font-weight:600;">
    ✅ Peminjaman berhasil diajukan.
  </div>
<?php elseif (isset($_GET['error'])): ?>
  <div style="background:#ffe6e6;color:#c00;padding:10px;margin:15px auto;width:90%;max-width:800px;
              border-radius:6px;text-align:center;font-weight:600;">
    ⚠️ <?= htmlspecialchars($_GET['error']) ?>
  </div>
<?php endif; ?>
<main>
  <div class="book-container">
  <div class="book-header">
  <button class="cover-btn" type="button" aria-label="Buka login"
          style="border:none;background:transparent;padding:0;cursor:pointer;flex-shrink:0;">
    <img src="<?= htmlspecialchars($img) ?>" alt="<?= htmlspecialchars($book['judul']) ?>">
  </button>
  <div class="book-info">
        <h1><?= htmlspecialchars($book['judul']) ?></h1>
        <h2><?= htmlspecialchars($book['penulis'] ?: '-') ?></h2>

        <div class="meta">
          <div class="rating"><?= render_stars($avg_rating) ?></div>
          <div>•</div>
          <div>📚 <?= $stok_display > 0 ? $stok_display . " tersedia" : "Habis" ?></div>
          <div>•</div>
          <div>📍 Rak: <?= htmlspecialchars($lokasi_rak) ?></div>
          <div>•</div>
          <div>👥 <?= $total_peminjam ?> orang</div>
        </div>

        <div class="synopsis">
          <p><strong>Sinopsis</strong></p>
          <p><?= nl2br(htmlspecialchars($book['sinopsis'] ?: '-')) ?></p>
        </div>
        <div class="action-buttons">
        <button class="btn-wishlist" disabled>⭐ Tambahkan ke Wishlist</button>
  <button class="btn-fav" disabled>❤️ Tambahkan ke Favorite</button>
 
</div>
        <a href="login/login.php" class="borrow-btn">Login Untuk Meminjam</a>
        </div>

      </div>
    </div>

    <div class="detail-grid" aria-hidden="false">
      <div><p><strong>Kategori</strong></p><p><?= htmlspecialchars($kategori) ?></p></div>
      <div><p><strong>Halaman</strong></p><p><?= $book['halaman'] ? htmlspecialchars($book['halaman']) . " Halaman" : "-" ?></p></div>
      <div><p><strong>Penerbit</strong></p><p><?= htmlspecialchars($book['penerbit'] ?: '-') ?></p></div>
      <div><p><strong>Tahun Terbit</strong></p><p><?= htmlspecialchars($book['tahun_terbit'] ?: '-') ?></p></div>
      <div><p><strong>Berat</strong></p><p><?= $berat_display ?></p></div>
      <div><p><strong>Ukuran</strong></p><p><?= $panjang_display . " × " . $lebar_display ?></p></div>
      <div><p><strong>Bahasa</strong></p><p><?= htmlspecialchars($book['bahasa'] ?: '-') ?></p></div>
      <div><p><strong>ISBN</strong></p><p><?= htmlspecialchars($book['isbn'] ?: '-') ?></p></div>
    </div>

<!-- Distribusi Rating -->
<?php if ($count_rating > 0): ?>
  <div class="rating-distribution" style="margin-top:24px;padding:10px 12px;background:#fff;border-radius:6px;border:1px solid #eee;">
    <h3 style="color:var(--accent);margin:0 0 8px 0;">📊 Distribusi Rating</h3>
    <?php for ($i = 5; $i >= 1; $i--): ?>
      <div style="font-size:15px;color:#333;margin:3px 0;">
        ⭐<?= $i ?>: <?= $rating_dist[$i] ?> orang
      </div>
    <?php endfor; ?>
  </div>
<?php endif; ?>

<!-- Ulasan (read-only: user tidak dapat menambah di halaman detail) -->
<div class="reviews">
  <h3 style="margin-top:18px;color:var(--accent)">💬 Ulasan Pembaca</h3>

      <?php if (count($reviews) === 0): ?>
        <div class="review-card">Belum ada ulasan.</div>
      <?php else: ?>
        <?php foreach ($reviews as $rev): ?>
          <div class="review-card">
            <div style="font-weight:600;color:#333"><?= htmlspecialchars($rev['username']) ?>
              <span style="margin-left:8px;color:#f5a623;font-weight:700"><?= str_repeat('★', intval($rev['rating'])) . str_repeat('☆', 5 - intval($rev['rating'])) ?></span>
              <small style="margin-left:8px;color:#666"><?= htmlspecialchars($rev['tanggal']) ?></small>
            </div>
            <div style="margin-top:6px;color:#333"><?= nl2br(htmlspecialchars($rev['komentar'])) ?></div>
          </div>
        <?php endforeach; ?>
      <?php endif; ?>
    </div>

    <!-- Related -->
    <div class="related">
      <h3 style="margin-top:18px;color:var(--accent)">📚 Buku Serupa</h3>
      <div class="related-list">
        <?php foreach ($related as $r): 
            $img_r = !empty($r['gambar']) ? $r['gambar'] : $default_img;
        ?>
          <a class="related-card" href="detail_guest.php?id=<?= $r['id'] ?>">
            <img src="<?= htmlspecialchars($img_r) ?>" alt="<?= htmlspecialchars($r['judul']) ?>">
            <div style="font-weight:600;margin-top:8px;font-size:14px"><?= htmlspecialchars($r['judul']) ?></div>
            <div style="font-size:13px;color:#666"><?= htmlspecialchars($r['penulis']) ?></div>
          </a>
        <?php endforeach; ?>
      </div>
    </div>

  </div>
</main>

<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>


<!-- Modal Login (re-use dari homepage) -->
<div class="modal-backdrop" id="loginBackdrop"></div>
<div class="modal" id="loginModal" role="dialog" aria-modal="true" aria-labelledby="loginTitle">
  <h3 id="loginTitle">Anda belum login</h3>
  <p>Silakan login untuk meminjam buku.</p>
  <div class="actions">
    <button type="button" class="btn" id="modalClose">Tutup</button>
    <a href="Login/login.php" class="btn btn-primary" id="modalLoginBtn">Ke Halaman Login</a>
  </div>
</div>
<div id="toast" class="toast"></div>
<script>
document.addEventListener('DOMContentLoaded', () => {
  const bookId = <?= json_encode((int)$book['id']) ?>;

  // ===== Element Tombol =====
  const btnWishlist = document.querySelector('.btn-wishlist');
  const btnFav      = document.querySelector('.btn-fav');
  const toast       = document.getElementById('toast');

  // ===== Fungsi Toast =====
  function showToast(msg){
    if (!toast) return;
    toast.textContent = msg;
    toast.classList.add('show');
    setTimeout(()=> toast.classList.remove('show'), 2000);
  }

  // ===== Modal Login =====
  const modal    = document.getElementById('loginModal');
  const backdrop = document.getElementById('loginBackdrop');
  const closeBtn = document.getElementById('modalClose');

  function openModal(){
    if (!modal || !backdrop) return;
    modal.style.display = 'block';
    backdrop.style.display = 'block';
    document.getElementById('modalLoginBtn')?.focus();
  }
  function closeModal(){
    if (!modal || !backdrop) return;
    modal.style.display = 'none';
    backdrop.style.display = 'none';
  }

  closeBtn?.addEventListener('click', closeModal);
  backdrop?.addEventListener('click', closeModal);
  document.addEventListener('keydown', e => { if (e.key === 'Escape') closeModal(); });

  // ===== Klik sampul buku -> buka modal login =====
  document.querySelector('.cover-btn')?.addEventListener('click', (e) => {
    e.preventDefault();
    openModal();
  });

  // ===== Klik tombol Wishlist/Favorite -> buka modal juga =====
  btnWishlist?.addEventListener('click', (e) => {
    e.preventDefault();
    openModal();
  });
  btnFav?.addEventListener('click', (e) => {
    e.preventDefault();
    openModal();
  });

  // ===== (Jika nanti user login) Handler toggle favorit/wishlist =====
  // Ini hanya aktif kalau kamu aktifkan logic login
  async function toggleData(url, btn, key, labelTrue, labelFalse){
    try {
      const res = await fetch(url, {
        method: 'POST',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({ book_id: bookId })
      });
      const data = await res.json();
      if (data.success) {
        btn.classList.toggle('active', data[key]);
        btn.textContent = data[key] ? labelTrue : labelFalse;
        showToast(data.message);
      } else showToast(data.message || 'Gagal.');
    } catch(err){
      console.error(err);
      showToast('Terjadi kesalahan.');
    }
  }

  // Kalau nanti butuh logic login sebenarnya (hapus openModal di atas)

  btnWishlist?.addEventListener('click', (e) => {
    e.preventDefault();
    toggleData('toggle_wishlist.php', btnWishlist, 'is_wishlist', '💛 Di Wishlist', '🤍 Tambah ke Wishlist');
  });
  btnFav?.addEventListener('click', (e) => {
    e.preventDefault();
    toggleData('toggle_favorite.php', btnFav, 'is_favorite', '❤️ Favorit', '🤍 Tambah ke Favorit');
  });
});
</script>

</body>
</html>
