<?php
// daftarbuku.php (versi diperbaiki — tidak mengubah config.php)
require_once __DIR__ . '/../Login/config.php'; // pastikan config.php mendefinisikan $pdo, $whatsapp_community_link, $whatsapp_community_name

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

// Ambil link komunitas dari variabel yang didefinisikan di config.php
$community_invite_link = isset($whatsapp_community_link) ? $whatsapp_community_link : '';
$community_name = isset($whatsapp_community_name) ? $whatsapp_community_name : 'Komunitas';

// Pagination & Search
$limit = 20; // 20 buku per halaman
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

// Hitung total buku (dengan search)
if ($search) {
    $stmtTotal = $pdo->prepare("SELECT COUNT(*) FROM books WHERE judul LIKE :search OR penulis LIKE :search OR isbn LIKE :search");
    $stmtTotal->execute([':search' => "%$search%"]);
} else {
    $stmtTotal = $pdo->query("SELECT COUNT(*) FROM books");
}
$totalBooks = $stmtTotal->fetchColumn();
$totalPages = $totalBooks ? ceil($totalBooks / $limit) : 1;

// Ambil data buku
if ($search) {
    $stmt = $pdo->prepare("
        SELECT b.id, b.judul, b.penulis, b.halaman, b.penerbit, b.tahun_terbit, 
               b.berat, b.panjang, b.lebar, b.bahasa, b.isbn, b.created_at,
               COUNT(bi.id) AS stok,
               COALESCE(MAX(bi.rak), '-') AS rak
        FROM books b
        LEFT JOIN book_items bi ON bi.book_id = b.id
        WHERE b.judul LIKE :search OR b.penulis LIKE :search OR b.isbn LIKE :search
        GROUP BY b.id
        ORDER BY b.created_at DESC 
        LIMIT :limit OFFSET :offset");
    $stmt->bindValue(':search', "%$search%", PDO::PARAM_STR);
} else {
    $stmt = $pdo->prepare("
        SELECT b.id, b.judul, b.penulis, b.halaman, b.penerbit, b.tahun_terbit, 
               b.berat, b.panjang, b.lebar, b.bahasa, b.isbn, b.created_at,
               COUNT(bi.id) AS stok,
               COALESCE(MAX(bi.rak), '-') AS rak
        FROM books b
        LEFT JOIN book_items bi ON bi.book_id = b.id
        GROUP BY b.id
        ORDER BY b.created_at DESC 
        LIMIT :limit OFFSET :offset");
}
$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$books = $stmt->fetchAll(PDO::FETCH_ASSOC);

// (Masih ambil daftar user WA jika nanti dibutuhkan, tapi UI tidak memakainya sekarang)
$users = $pdo->query("SELECT id, username, phone FROM users WHERE wa_opt_in = 1 AND phone IS NOT NULL AND phone != '' ORDER BY username ASC")->fetchAll(PDO::FETCH_ASSOC);

// Helper: normalisasi nomor untuk WhatsApp (server-side)
function normalize_phone_for_whatsapp($phone) {
    $p = trim($phone);
    if ($p === '') return '';
    $p = preg_replace('/[\s\-\(\)]+/', '', $p); // hapus spasi/-,()
    if (preg_match('/^0/', $p)) {
        $p = preg_replace('/^0+/', '', $p);
        $p = '+62' . $p;
    } elseif (preg_match('/^62/', $p)) {
        $p = '+' . $p;
    } elseif (!preg_match('/^\+/', $p)) {
        $p = '+' . $p;
    }
    return $p;
}
$users_normalized = array_map(function($u) {
    $phone = isset($u['phone']) ? trim($u['phone']) : '';
    $phone = preg_replace('/[\s\-\(\)]+/', '', $phone); // hapus spasi/dash/()
    if ($phone !== '') {
        if (preg_match('/^0/', $phone)) {
            $phone = preg_replace('/^0+/', '', $phone);
            $phone = '+62' . $phone;
        } elseif (preg_match('/^62/', $phone)) {
            $phone = '+' . $phone;
        } elseif (!preg_match('/^\+/', $phone)) {
            $phone = '+' . $phone;
        }
    }
    return [
        'id' => $u['id'],
        'username' => $u['username'],
        'phone' => $phone
    ];
}, $users);
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>Daftar Buku - Pustakaia</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        /* (CSS sama seperti versi kamu — dipertahankan) */
        body {
            margin: 0;
            font-family: "Poppins", Arial, sans-serif;
            line-height: 1.6;
            background: #f4f7f9;
            color: #222;
            display: flex;
            min-height: 100vh;
            flex-direction: column;
        }
        a { text-decoration: none; }
        .container { display: flex; flex: 1; }
        main { flex: 1; padding: 20px; margin-left: 250px; }

        /* Sidebar */
        .sidebar {
            width: 250px;
            height: 100vh;
            background: #fff;
            border-right: 1px solid #ddd;
            padding: 10px 0;
            position: fixed;
            top: 0;
            left: 0;
            overflow-y: auto;
        }
        .sidebar-header {
            padding: 15px 20px;
            border-bottom: 1px solid #ddd;
        }
        .sidebar-header h2 {
            margin: 0;
            font-size: 18px;
            color: #069797;
        }
        .sidebar-header p {
            margin: 0;
            font-size: 12px;
            color: #777;
        }
        .sidebar-menu {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        .sidebar-menu li {
            font-size: 14px;
            position: relative;
        }
        .sidebar-menu li > a {
            display: flex;
            align-items: center;
            padding: 12px 20px;
            color: #444;
            width: 100%;
            transition: background 0.2s;
        }
        .sidebar-menu li > a i {
            margin-right: 10px;
            font-size: 16px;
            color: #666;
        }
        .sidebar-menu li > a:hover {
            background: #f5f5f5;
            border-radius: 6px;
        }
        .sidebar-menu li > a.active {
            background: #e0ebff;
            color: #069797;
            font-weight: 600;
            border-radius: 6px;
        }
        .sidebar-menu li > a.active i { color: #069797; }

        /* Tombol Aksi */
        .aksi { text-align: center; white-space: nowrap; }
        .btn-edit, .btn-delete {
            display: inline-flex;
            align-items: center;
            gap: 5px;
            padding: 6px 10px;
            font-size: 13px;
            font-weight: 500;
            border-radius: 5px;
            text-decoration: none;
            transition: 0.2s ease;
        }
        .btn-edit {
            background: #e0f7f7;
            color: #069797;
            border: 1px solid #06a0a0;
        }
        .btn-edit:hover { background: #06a0a0; color: #fff; }
        .btn-delete {
            background: #ffe6e6;
            color: #c00;
            border: 1px solid #e55;
        }
        .btn-delete:hover { background: #c00; color: #fff; }

        /* Submenu */
        .submenu {
            list-style: none;
            padding-left: 0;
            margin: 0;
            display: none;
        }
        .submenu li a {
            display: flex;
            align-items: center;
            padding: 8px 40px;
            font-size: 13px;
            color: #444;
        }
        .submenu li a:hover {
            background: #f5f5f5;
            border-radius: 6px;
        }

        /* Table */
        table {
            width: 100%;
            border-collapse: collapse;
            background: #fff;
            box-shadow: 0 2px 6px rgba(0,0,0,0.1);
        }
        table th, table td {
            border: 1px solid #ddd;
            padding: 10px;
            text-align: left;
            font-size: 14px;
        }
        table th { background: #069797; color: #fff; }
        table tr:hover { background: #f9f9f9; }

        /* Footer */
        footer {
            background: #fff;
            border-top: 1px solid #ddd;
            padding: 15px 30px;
            font-size: 14px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: auto;
            margin-left: 250px;
            color: #555;
        }
        .footer-right a {
            margin-left: 15px;
            color: #555;
            font-weight: 500;
        }
        .footer-right a:hover { text-decoration: underline; }

        /* Pagination */
        .pagination {
            margin: 15px 0;
            display: flex;
            justify-content: center;
            gap: 5px;
            flex-wrap: wrap;
        }
        .pagination a {
            padding: 6px 12px;
            background: #fff;
            border: 1px solid #ddd;
            color: #069797;
            text-decoration: none;
            border-radius: 4px;
        }
        .pagination a.active {
            background: #069797;
            color: #fff;
        }
        .pagination a:hover { background: #e0ebff; }

        /* Search */
        .search-box {
            margin-bottom: 15px;
            display: flex;
            gap: 5px;
        }
        .search-box input {
            flex: 1;
            padding: 6px 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .search-box button {
            padding: 6px 12px;
            border: none;
            background: #069797;
            color: #fff;
            border-radius: 4px;
            cursor: pointer;
        }
        .search-box button:hover { background: #056666; }
        .alert {
         padding: 10px 15px;
  border-radius: 5px;
  margin-bottom: 15px;
  font-weight: 500;
}
.alert.success { background: #e0f7f7; color: #069797; border: 1px solid #06a0a0; }
.alert.error { background: #ffe6e6; color: #c00; border: 1px solid #e55; }
.alert.warning { background: #fff7e0; color: #b58900; border: 1px solid #e0c85f; }
/* Tombol Kirim WA & modal kecil */
.btn-wa { display:inline-flex; align-items:center; gap:6px; padding:6px 10px; background:#25D366; color:#fff; border-radius:6px; font-weight:600; border:0; cursor:pointer; }
.modal-backdrop { display:none; position:fixed; inset:0; background:rgba(0,0,0,0.45); z-index:9999; }
.modal { max-width:900px; margin:40px auto; background:#fff; padding:18px; border-radius:8px; box-shadow:0 6px 30px rgba(0,0,0,0.2); }
.users-list { max-height:320px; overflow:auto; border:1px solid #eee; padding:8px; margin-top:8px; }
.btn { padding:8px 12px; border-radius:6px; border:0; cursor:pointer; }
.btn-primary { background:#069797; color:#fff; }
.btn-ghost { background:#f5f5f5; color:#333; }
    </style>
</head>
<body>
    <div class="container">
        <!-- Sidebar -->
        <aside class="sidebar">
            <div class="sidebar-header">
                <h2>📚 Pustakaia</h2>
                <p>Admin Panel</p>
            </div>
            <ul class="sidebar-menu">
                <li><a href="dsadmin.php"><i class="fa fa-tachometer-alt"></i> Dashboard</a></li>
                <li class="has-submenu">
                    <a href="#"><i class="fa fa-book"></i> Kelola Buku</a>
                    <ul class="submenu" style="display:block;">
                        <li><a href="daftarbuku.php" class="active" style="color:#069797;"><i class="fa fa-list"></i> Daftar Buku</a></li>
                        <li><a href="add_book.php"><i class="fa fa-plus"></i> Tambahkan Buku</a></li>
                    </ul>
                </li>

                <li class="has-submenu">
                    <a href="#"><i class="fa fa-users"></i> Kelola Anggota</a>
                    <ul class="submenu">
                        <li><a href="daftaranggota.php" ><i class="fa fa-list"></i> Daftar Anggota</a></li>
                        <li><a href="add_anggota.php"><i class="fa fa-user-plus"></i> Tambahkan Anggota</a></li>
                    </ul>
                </li>

                <li><a href="borrow_requests.php"><i class="fa fa-exchange-alt"></i> Kelola Peminjaman</a></li>
            </ul>
            <hr>
            <ul class="sidebar-menu">
                <li><a href="#"><i class="fa fa-cog"></i> Pengaturan</a></li>
                <li><a href="../index2.php"><i class="fa fa-sign-out-alt"></i> Keluar</a></li>
            </ul>
        </aside>

        <!-- Main Content -->
        <main>
            <h1>Daftar Buku</h1>
            <?php if (isset($_GET['deleted'])): ?>
                <div class="alert success">Buku berhasil dihapus!</div>
            <?php elseif (isset($_GET['error'])): ?>
                <div class="alert error">Gagal menghapus buku.</div>
            <?php elseif (isset($_GET['notfound'])): ?>
                <div class="alert warning">Data buku tidak ditemukan.</div>
            <?php endif; ?>

            <!-- Search -->
            <form method="get" class="search-box">
                <input type="text" name="search" placeholder="Cari judul, penulis, ISBN..." value="<?= htmlspecialchars($search) ?>">
                <button type="submit"><i class="fa fa-search"></i> Cari</button>
            </form>

            <table>
                <thead>
                    <tr>
                        <th>No</th>
                        <th>Judul</th>
                        <th>Penulis</th>
                        <th>Halaman</th>
                        <th>Penerbit</th>
                        <th>Tahun Terbit</th>
                        <th>Berat</th>
                        <th>Panjang</th>
                        <th>Lebar</th>
                        <th>Bahasa</th>
                        <th>ISBN</th>
                        <th>Stok</th>
                        <th>Rak</th>
                        <th>Ditambahkan</th>
                        <th>Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($books) > 0): ?>
                        <?php $no = $offset + 1; foreach ($books as $book): ?>
                            <tr>
                                <td><?= $no++ ?></td>
                                <td><?= htmlspecialchars($book['judul']) ?></td>
                                <td><?= htmlspecialchars($book['penulis']) ?></td>
                                <td><?= htmlspecialchars($book['halaman']) ?></td>
                                <td><?= htmlspecialchars($book['penerbit']) ?></td>
                                <td><?= htmlspecialchars($book['tahun_terbit']) ?></td>
                                <td><?= htmlspecialchars($book['berat']) ?></td>
                                <td><?= htmlspecialchars($book['panjang']) ?></td>
                                <td><?= htmlspecialchars($book['lebar']) ?></td>
                                <td><?= htmlspecialchars($book['bahasa']) ?></td>
                                <td><?= htmlspecialchars($book['isbn']) ?></td>
                                <td><?= htmlspecialchars($book['stok']) ?></td>
                                <td><?= htmlspecialchars($book['rak']) ?></td>
                                <td><?= date('d-m-Y', strtotime($book['created_at'])) ?></td>
                                <td class="aksi">
                                    <a href="edit_book.php?isbn=<?= urlencode($book['isbn']) ?>" class="btn-edit">
                                        <i class="fa fa-pen"></i> Edit
                                    </a>
                                    <a href="delete_book.php?isbn=<?= urlencode($book['isbn']) ?>" class="btn-delete" onclick="return confirm('Yakin ingin menghapus buku ini?');">
                                        <i class="fa fa-trash"></i> Hapus
                                    </a>
                                    <button type="button" class="btn-wa notify-btn"
                                        data-book-id="<?= (int)$book['id'] ?>"
                                        data-book-judul="<?= htmlspecialchars($book['judul'], ENT_QUOTES) ?>">
                                        <i class="fa fa-paper-plane"></i> Kirim Notif WA
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="15" style="text-align:center;">Belum ada buku.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>

            <!-- Pagination -->
            <div class="pagination">
                <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                    <a href="?page=<?= $i ?>&search=<?= urlencode($search) ?>" class="<?= $i == $page ? 'active' : '' ?>"><?= $i ?></a>
                <?php endfor; ?>
            </div>
        </main>
    </div>

    <footer>
        <div>© <?= date('Y') ?>, Pustakaia | Website developed by Grup 3</div>
        <div class="footer-right">
            <a href="#">Terms of Use</a>
            <a href="#">Privacy Policy</a>
        </div>
    </footer>

    <!-- Modal Kirim WA (Komunitas) -->
    <div id="notifyBackdrop" class="modal-backdrop" aria-hidden="true">
      <div class="modal" role="dialog" aria-modal="true">
        <h3>Umumkan ke Komunitas <?= htmlspecialchars($community_name) ?></h3>
        <div style="display:flex;justify-content:space-between;align-items:center;">
          <div><strong>Judul buku:</strong> <span id="modalJudul"></span></div>
          <div></div>
        </div>

        <label style="display:block;margin-top:10px;font-weight:600;">Pesan (bisa diedit) — gunakan {name} jika ingin menandai user secara manual:</label>
        <textarea id="waMessage" rows="4" style="width:100%; box-sizing:border-box; margin-top:6px;"></textarea>

        <p style="margin-top:10px;color:#555;">
          Link komunitas: <a id="communityLink" href="<?= htmlspecialchars($community_invite_link) ?>" target="_blank" rel="noopener noreferrer"><?= htmlspecialchars($community_invite_link) ?></a>
        </p>

        <div style="margin-top:12px;display:flex;gap:8px;">
          <button id="copyBtn" class="btn btn-primary"><i class="fa fa-copy"></i> Salin Pengumuman</button>
          <button id="openCommunityBtn" class="btn btn-ghost"><i class="fa fa-share-square"></i> Buka Komunitas</button>
          <button id="copyAndOpenBtn" class="btn btn-primary"><i class="fa fa-clone"></i> Salin & Buka Komunitas</button>
          <button id="closeBtn" class="btn btn-ghost">Tutup</button>
        </div>

        <p style="margin-top:10px;font-size:13px;color:#666;">
          Catatan: Klik "Salin Pengumuman" lalu paste di chat komunitas. Jika ingin menempelkan format tebal/italic, paste di WhatsApp Desktop atau Mobile sesuai kebutuhan.
        </p>
      </div>
    </div>

    <script>
    /* Helper escape */
    function escapeHtml(s){ if(!s) return ''; return s.replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c])); }

    /* Modal elements */
    const modalJudul = document.getElementById('modalJudul');
    const waMessage = document.getElementById('waMessage');
    const backdrop = document.getElementById('notifyBackdrop');
    const communityLink = document.getElementById('communityLink');

    // Pastikan inviteLink berasal dari server (JSON encoded) untuk keamanan
    const inviteLink = <?= json_encode($community_invite_link) ?> || '';

    // Open modal yang kini diarahkan ke komunitas
    function openNotifyModal(bookId, bookTitle) {
      modalJudul.textContent = bookTitle;
      waMessage.value = `Halo semua 👋\nBuku baru tersedia: "${bookTitle}".\nSilakan cek di Pustakaia: [link buku]\nTerima kasih.\n\n-- PustakaIA`;
      communityLink.href = inviteLink || '#';
      backdrop.style.display = 'block';
      backdrop.scrollTop = 0;
    }

    document.getElementById('closeBtn').addEventListener('click', () => {
      backdrop.style.display = 'none';
    });

    /* Salin pesan ke clipboard */
    document.getElementById('copyBtn').addEventListener('click', async () => {
      try {
        await navigator.clipboard.writeText(waMessage.value);
        alert('Pengumuman tersalin ke clipboard. Buka komunitas lalu paste pesan dan kirim.');
      } catch (err) {
        alert('Gagal salin clipboard: ' + err);
      }
    });

    /* Buka komunitas (WA Web / app) */
    document.getElementById('openCommunityBtn').addEventListener('click', () => {
      if (!inviteLink) {
        alert('Link komunitas belum diset.');
        return;
      }
      try {
        window.open(inviteLink, '_blank', 'noopener');
      } catch (e) {
        location.href = inviteLink;
      }
    });

    /* Salin + buka komunitas — buka tab kosong dulu untuk mencegah popup blocker */
    document.getElementById('copyAndOpenBtn').addEventListener('click', async (ev) => {
      if (!inviteLink) {
        alert('Link komunitas belum diset. Silakan cek konfigurasi.');
        return;
      }

      // Buka tab kosong terlebih dahulu (dalam konteks user gesture)
      const newWin = window.open('', '_blank', 'noopener');

      try {
        // Salin ke clipboard (async)
        await navigator.clipboard.writeText(waMessage.value);

        // Setelah clipboard selesai, arahkan tab yang sudah dibuka ke link komunitas
        if (newWin) {
          try {
            newWin.location.href = inviteLink;
          } catch (e) {
            // fallback
            try { window.open(inviteLink, '_blank', 'noopener'); } catch(e2) { location.href = inviteLink; }
            newWin.close();
          }
        } else {
          window.open(inviteLink, '_blank', 'noopener');
        }

        alert('Pengumuman tersalin. Buka tab komunitas dan paste pesan lalu kirim.');
      } catch (err) {
        if (newWin && !newWin.closed) newWin.close();
        alert('Gagal salin clipboard: ' + err);
      }
    });

    /* Toggle submenu Kelola Buku */
    document.querySelectorAll('.has-submenu > a').forEach(menu => {
        menu.addEventListener('click', e => {
            e.preventDefault();
            const submenu = menu.nextElementSibling;
            submenu.style.display = submenu.style.display === 'block' ? 'none' : 'block';
        });
    });

    /* Pasang event handler untuk tombol per buku */
    document.addEventListener('DOMContentLoaded', function(){
      document.querySelectorAll('.notify-btn').forEach(btn => {
        btn.addEventListener('click', () => {
          const id = btn.dataset.bookId;
          const judul = btn.dataset.bookJudul;
          openNotifyModal(id, judul);
        });
      });
    });
    </script>
</body>
</html>
