<?php
session_start();
require '../Login/config.php';

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

$user_id = $_SESSION['user_id'];
$id = intval($_GET['id'] ?? 0);

if ($id <= 0) {
    header('Location: books.php');
    exit;
}

// --- Ambil data buku ---
$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'];
    $absolute_path = __DIR__ . '/../' . $book['gambar'];
    $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();

// --- cek wishlist / favorite ---
$check_wishlist = $pdo->prepare("SELECT 1 FROM wishlists WHERE user_id = ? AND book_id = ?");
$check_wishlist->execute([$user_id, $id]);
$is_wishlist = (bool)$check_wishlist->fetchColumn();

$check_fav = $pdo->prepare("SELECT 1 FROM favorites WHERE user_id = ? AND book_id = ?");
$check_fav->execute([$user_id, $id]);
$is_favorite = (bool)$check_fav->fetchColumn();

// --- reviews (read-only) ---
$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 ---
function render_stars($avg) {
    $html = '';
    if ($avg === null) return '<span style="color:#999">Belum ada rating</span>';
    $rounded = round($avg * 2) / 2;
    for ($i = 1; $i <= 5; $i++) {
        if ($rounded >= $i) {
            $html .= '<span style="color:#f5a623;font-size:16px">★</span>';
        } elseif ($rounded + 0.5 == $i) {
            $html .= '<span style="color:#f5a623;font-size:16px;position:relative;display:inline-block;">★</span>';
        } else {
            $html .= '<span style="color:#ddd;font-size:16px">★</span>';
        }
    }
    $html .= ' <small style="color:#666;margin-left:6px">(' . number_format($avg, 2) . ' / 5 — ' . $GLOBALS['count_rating'] . ')</small>';
    return $html;
}
// --- QR generation (debug & always-regenerate) ---
// --- QR generation (simple fallback: pakai generator QR publik) ---
function get_base_url() {
  $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
  $host = $_SERVER['HTTP_HOST'];
  $base = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
  return $scheme . '://' . $host . $base;
}

$book_id = intval($book['id']);

// target url yang akan dipindai (tetap sama)
$base_url = get_base_url();
$target_url = $base_url . '/detail.php?id=' . $book_id;

// Gunakan layanan QR publik (api.qrserver.com) untuk men-generate image
// ukuran web (dipakai pada modal)
$qrcode_rel = 'https://api.qrserver.com/v1/create-qr-code/?size=220x220&data=' . urlencode($target_url);
// ukuran untuk diunduh/cetak (resolusi lebih besar)
$qrcode_print_rel = 'https://api.qrserver.com/v1/create-qr-code/?size=800x800&data=' . urlencode($target_url);

// token cache-busting — pakai timestamp agar selalu fresh di frontend
$qrcode_token = time();
$qrcode_print_token = time();

// debug singkat (HTML comment) — bisa dihapus kalau sudah yakin
$qr_error = '';
echo "<!-- QR FALLBACK: using api.qrserver.com | target=" . htmlspecialchars($target_url) . " -->\n";


?>
<!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>
/* === STYLE DIPERTAHANKAN UTUH === */
: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;margin:30px auto;padding:30px 40px;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;height:auto;border-radius:8px;object-fit:cover;box-shadow:0 3px 10px rgba(0,0,0,0.12);flex-shrink:0;}
.book-info{flex:1;display:flex;flex-direction:column;justify-content:center;gap:8px;}
.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 .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;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;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%;}
@media(max-width:820px){.book-header{flex-direction:column;align-items:center}.book-header img{width:160px;height:auto}}
.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 img{width:300px;}}
/* === MODAL POPUP === */
.modal{display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.4);z-index:3000;justify-content:center;align-items:center;}
.modal-content{background:#fff;padding:24px 28px;border-radius:10px;box-shadow:0 6px 20px rgba(0,0,0,0.2);max-width:360px;text-align:center;animation:fadeIn .3s ease;}
.modal-buttons{margin-top:18px;display:flex;justify-content:center;gap:10px;}
.yes-btn,.no-btn{padding:8px 14px;border-radius:6px;border:none;cursor:pointer;font-weight:600;}
.yes-btn{background:var(--accent);color:#fff;}
.no-btn{background:#ddd;color:#333;}
@keyframes fadeIn{from{opacity:0;transform:scale(0.9);}to{opacity:1;transform:scale(1);}}
.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)}
/* QR modal tweaks (tambahkan di akhir <style>) */
#qrModal .modal-content { padding:18px 20px; text-align:center; }
#qrModal .modal-buttons a, #qrModal .modal-buttons button { padding:8px 12px; border-radius:6px; border:none; cursor:pointer; }
#qrModal .modal-buttons a.yes-btn { background:var(--accent); color:#fff; text-decoration:none; display:inline-block; }
#qrModal .modal-buttons .no-btn { background:#f0f0f0; color:#333; border:1px solid #ddd; }

</style>
</head>

<body>
<header>
  <div class="logo">
    <a href="books.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">
      <img src="<?= htmlspecialchars($img) ?>" alt="<?= htmlspecialchars($book['judul']) ?>">
      <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="actions">
          <button id="btn-wishlist" class="btn wishlist <?= $is_wishlist ? 'active' : '' ?>" data-book="<?= $book['id'] ?>">
            <?= $is_wishlist ? '💛 Di Wishlist' : '🤍 Tambah ke Wishlist' ?>
          </button>

          <button id="btn-fav" class="btn fav <?= $is_favorite ? 'active' : '' ?>" data-book="<?= $book['id'] ?>">
            <?= $is_favorite ? '❤️ Favorit' : '🤍 Tambah ke Favorit' ?>
          </button>
          <!-- jika mau inline icon tanpa file -->
<button id="qr-icon-btn" class="btn" style="display:flex;align-items:center;gap:8px;padding:6px 8px;">
  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
    <rect x="2" y="2" width="6" height="6" stroke="#069797" stroke-width="1.6" fill="none" />
    <rect x="8" y="2" width="6" height="6" stroke="#069797" stroke-width="1.6" fill="none" />
    <rect x="2" y="8" width="6" height="6" stroke="#069797" stroke-width="1.6" fill="none" />
    <rect x="14" y="14" width="8" height="8" stroke="#069797" stroke-width="1.6" fill="none" />
  </svg>
  <span style="font-weight:700;font-size:13px;">QR</span>
</button>


          <?php if ($stok_display > 0): ?>
  <button id="borrow-btn-fixed" class="borrow-btn" data-id="<?= $book['id'] ?>">Ajukan Peminjaman</button>
<?php else: ?>
  <button class="borrow-btn disabled" disabled>Stok Habis</button>
<?php endif; ?>
        </div>
      </div>
    </div>

    <div class="detail-grid">
      <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: 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; endif; ?>
    </div>

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

<!-- Tombol pinjam di luar main biar tetap fixed -->
<?php if ($stok_display > 0): ?>
  <button id="borrow-btn" class="borrow-btn" data-id="<?= $book['id'] ?>">Ajukan Peminjaman</button>
<?php else: ?>
  <button class="borrow-btn disabled" disabled>Stok Habis</button>
<?php endif; ?>

<!-- Modal Konfirmasi + Form Upload -->
<div id="confirmModal" class="modal">
  <div class="modal-content">
    <h3>Ajukan Peminjaman</h3>
    <p>Unggah kartu peminjaman (gambar/PDF) dan pilih durasi (maks 7 hari).</p>

    <form id="borrowForm" action="Borrowed.php" method="post" enctype="multipart/form-data" style="margin-top:10px;text-align:left;">
      <input type="hidden" name="book_id" value="<?= (int)$book['id'] ?>">

      <label for="bukti" style="display:block;margin:8px 0 4px;font-weight:600;">Kartu Peminjaman (jpg/png/gif/pdf, ≤ 3 MB)</label>
      <input id="bukti" name="bukti" type="file" accept="image/*,application/pdf" required
             style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px;">

      <label for="durasi" style="display:block;margin:12px 0 4px;font-weight:600;">Durasi Pinjam (hari)</label>
      <select id="durasi" name="durasi" required style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px;">
        <?php for ($i=1; $i<=7; $i++): ?>
          <option value="<?= $i ?>" <?= $i===7 ? 'selected' : '' ?>><?= $i ?> hari</option>
        <?php endfor; ?>
      </select>

      <div id="duePreview" style="margin-top:6px;color:#444;font-size:12px;"></div>

      <div class="modal-buttons" style="margin-top:16px;">
        <button type="submit" class="yes-btn" id="submitBorrow">Kirim Permintaan</button>
        <button type="button" class="no-btn" id="confirmNo">Batal</button>
      </div>
    </form>
  </div>
</div>
<div id="toast" class="toast"></div>
<!-- QR Modal (client-side generation via qrious) -->
<div id="qrModal" class="modal" style="display:none;z-index:4000;">
  <div class="modal-content" style="max-width:420px;">
    <h3 style="margin:0 0 6px 0;color:var(--accent)">QR / Barcode Buku</h3>
    <p style="color:#444;font-size:13px;margin:0 0 12px 0;">Scan dengan kamera ponsel atau download untuk cetak.</p>

    <div style="text-align:center;">
      <!-- mulai dengan src kosong; JS akan mengisi dengan dataURL dari QRious -->
      <img id="qrLargeImg" src="" alt="QR Buku"
           style="width:220px;height:220px;object-fit:contain;border:1px solid #eee;padding:8px;background:#fff;border-radius:8px;display:none;">
      <canvas id="qrCanvas" width="220" height="220" style="display:none;"></canvas>

      <div id="qrFallback" style="display:none;padding:18px;">
        <div style="display:inline-block;border:1px dashed #ddd;padding:14px;border-radius:8px;background:#fff;">
          <svg xmlns='http://www.w3.org/2000/svg' width='220' height='220' viewBox='0 0 220 220'>
            <rect width='100%' height='100%' fill='#fff'/>
            <text x='50%' y='50%' dominant-baseline='middle' text-anchor='middle' font-size='13' fill='#666'>
              QR tidak tersedia
            </text>
          </svg>
        </div>
      </div>

      <div style="margin-top:10px;font-size:13px;color:#666;word-break:break-all;">
        <!-- gunakan $target_url yang sudah ada di PHP -->
        <a id="qrTargetLink" href="<?= htmlspecialchars($target_url) ?>" target="_blank"><?= htmlspecialchars($target_url) ?></a>
      </div>
    </div>

    <div class="modal-buttons" style="margin-top:14px;">
      <a id="downloadQR" class="yes-btn" href="#" download="book_<?= $book_id ?>_qr.png">⬇️ Download (Cetak)</a>
      <button type="button" id="printQR" class="no-btn">🖨️ Print</button>
      <button type="button" id="closeQR" class="no-btn">Tutup</button>
    </div>
  </div>
</div>

<!-- QRious CDN (atau inline jika jaringan diblokir) -->
<script src="https://cdn.jsdelivr.net/npm/qrious/dist/qrious.min.js"></script>

<script>
// Client-side QR generation using QRious
(function(){
  console.log('Client-side QR modal script loaded');
  const qrBtn = document.getElementById('qr-icon-btn');
  const qrModal = document.getElementById('qrModal');
  const qrClose = document.getElementById('closeQR');
  const qrImg = document.getElementById('qrLargeImg');
  const qrCanvas = document.getElementById('qrCanvas');
  const downloadQR = document.getElementById('downloadQR');
  const printQR = document.getElementById('printQR');
  const qrFallback = document.getElementById('qrFallback');
  const qrTargetLink = document.getElementById('qrTargetLink');

  if (!qrBtn) console.error('Tombol QR (id=qr-icon-btn) tidak ditemukan — periksa HTML.');
  if (!qrImg) console.error('Elemen img#qrLargeImg tidak ditemukan.');
  if (!window.QRious) console.warn('QRious library tidak terload — cek koneksi CDN.');

  function generateQR(data, size = 220) {
    try {
      const qr = new QRious({ value: data, size: size, level: 'H' });
      const dataUrl = qr.toDataURL(); // data:image/png;base64,...
      qrImg.src = dataUrl;
      qrImg.style.display = '';
      qrFallback.style.display = 'none';
      downloadQR.href = dataUrl;
      downloadQR.dataset.dataurl = dataUrl;
      console.log('QR generated for:', data);
      return true;
    } catch (err) {
      console.error('generateQR error', err);
      qrImg.style.display = 'none';
      qrFallback.style.display = '';
      return false;
    }
  }

  qrBtn?.addEventListener('click', (e) => {
    e.preventDefault();
    console.log('QR button clicked');
    if (!qrModal) return console.error('qrModal missing');
    qrModal.style.display = 'flex';
    const target = qrTargetLink ? qrTargetLink.href : window.location.href;
    generateQR(target, 300);
  });

  qrClose?.addEventListener('click', () => { qrModal.style.display = 'none'; });
  window.addEventListener('click', (e) => { if (e.target === qrModal) qrModal.style.display = 'none'; });

  printQR?.addEventListener('click', () => {
    const dataUrl = downloadQR.getAttribute('href');
    if (!dataUrl) { alert('QR belum tersedia. Buka modal lalu coba lagi.'); return; }
    const w = window.open('', '_blank');
    if (!w) { alert('Pop-up diblokir. Silakan unduh lalu cetak.'); return; }
    w.document.write('<html><head><title>Print QR</title></head><body style="margin:0;display:flex;align-items:center;justify-content:center;">');
    w.document.write('<img src="' + dataUrl + '" style="max-width:100%;height:auto;">');
    w.document.write('</body></html>');
    w.document.close();
    w.onload = function(){ w.focus(); w.print(); };
  });

})();
</script>


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

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

<script>
const bookId = <?= json_encode((int)$book['id']) ?>;
const btnWishlist = document.getElementById('btn-wishlist');
const btnFav = document.getElementById('btn-fav');
const toast = document.getElementById('toast');

function showToast(msg){
  toast.textContent = msg;
  toast.classList.add('show');
  setTimeout(()=> toast.classList.remove('show'), 2000);
}

btnWishlist?.addEventListener('click', async (e) => {
  e.preventDefault();
  try {
    const res = await fetch('toggle_wishlist.php', {
      method: 'POST',
      headers: {'Content-Type':'application/json'},
      body: JSON.stringify({ book_id: bookId })
    });
    const data = await res.json();
    if (data.success) {
      btnWishlist.classList.toggle('active', data.is_wishlist);
      btnWishlist.textContent = data.is_wishlist ? '💛 Di Wishlist' : '🤍 Tambah ke Wishlist';
      showToast(data.message);
    } else showToast(data.message || 'Gagal.');
  } catch(err){
    console.error(err);
    showToast('Terjadi kesalahan.');
  }
});

btnFav?.addEventListener('click', async (e) => {
  e.preventDefault();
  try {
    const res = await fetch('toggle_favorite.php', {
      method: 'POST',
      headers: {'Content-Type':'application/json'},
      body: JSON.stringify({ book_id: bookId })
    });
    const data = await res.json();
    if (data.success) {
      btnFav.classList.toggle('active', data.is_favorite);
      btnFav.textContent = data.is_favorite ? '❤️ Favorit' : '🤍 Tambah ke Favorit';
      showToast(data.message);
    } else showToast(data.message || 'Gagal.');
  } catch(err){
    console.error(err);
    showToast('Terjadi kesalahan.');
  }
});

// === Modal Upload + Durasi ===
function setupBorrowOpeners() {
  const modal = document.getElementById('confirmModal');
  const noBtn = document.getElementById('confirmNo');
  const borrowForm = document.getElementById('borrowForm');
  const submitBorrow = document.getElementById('submitBorrow');

  // Support dua tombol pembuka jika ada
  const openers = [
    document.getElementById('borrow-btn'),
    document.getElementById('borrow-btn-fixed')
  ].filter(Boolean);

  openers.forEach(btn => btn.addEventListener('click', () => { modal.style.display = 'flex'; }));

  noBtn?.addEventListener('click', () => { modal.style.display = 'none'; });
  window.addEventListener('click', (e) => { if (e.target === modal) modal.style.display = 'none'; });

  // Preview jatuh tempo berdasarkan pilihan durasi
  const durasiSel = document.getElementById('durasi');
  const duePrev = document.getElementById('duePreview');
  function fmt(d){ return d.toISOString().slice(0,10); }
  function updateDue(){
    const d = parseInt(durasiSel.value,10) || 7;
    const t = new Date(); t.setHours(0,0,0,0);
    const due = new Date(t.getTime() + d*24*60*60*1000);
    duePrev.textContent = 'Jatuh tempo: ' + fmt(due) + ' • Denda telat Rp1.000/hari';
  }
  durasiSel?.addEventListener('change', updateDue);
  updateDue();

  // Validasi file & durasi
  borrowForm?.addEventListener('submit', (e) => {
    const f = document.getElementById('bukti').files[0];
    const d = parseInt(durasiSel.value,10);
    const allowed = ['image/png','image/jpeg','image/jpg','image/gif','application/pdf'];

    if (!f) { e.preventDefault(); alert('Mohon unggah kartu.'); return; }
    if (!allowed.includes(f.type)) { e.preventDefault(); alert('File harus gambar/PDF.'); return; }
    if (f.size > 3*1024*1024) { e.preventDefault(); alert('Maksimal 3 MB.'); return; }
    if (isNaN(d) || d < 1 || d > 7) { e.preventDefault(); alert('Durasi 1–7 hari.'); return; }

    submitBorrow.disabled = true;
    submitBorrow.textContent = 'Mengirim...';
  });
}
setupBorrowOpeners();


</script>

</body>
</html>
