<?php
require __DIR__ . '/../Login/config.php';
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Pagination & Search
$limit = 20;
$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 anggota
if ($search) {
    $stmtTotal = $pdo->prepare("SELECT COUNT(*) FROM users 
                                WHERE fullname LIKE :search OR username LIKE :search OR email LIKE :search OR nis LIKE :search");
    $stmtTotal->execute([':search' => "%$search%"]);
} else {
    $stmtTotal = $pdo->query("SELECT COUNT(*) FROM users");
}
$totalUsers = $stmtTotal->fetchColumn();
$totalPages = ceil($totalUsers / $limit);

// Ambil data anggota
if ($search) {
    $stmt = $pdo->prepare("
        SELECT id, fullname, email, username, nis, phone, class, role, created_at
        FROM users
        WHERE fullname LIKE :search 
           OR username LIKE :search 
           OR email LIKE :search 
           OR nis LIKE :search
        ORDER BY 
            CASE WHEN role = 'admin' THEN 1 ELSE 2 END,
            created_at DESC
        LIMIT :limit OFFSET :offset
    ");
    $stmt->bindValue(':search', "%$search%", PDO::PARAM_STR);
} else {
    $stmt = $pdo->prepare("
        SELECT id, fullname, email, username, nis, phone, class, role, created_at
        FROM users
        ORDER BY 
            CASE WHEN role = 'admin' THEN 1 ELSE 2 END,
            created_at DESC
        LIMIT :limit OFFSET :offset
    ");
}

$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Daftar Anggota - Pustakaia</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
/* === Sama persis seperti daftarbuku.php === */
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; }
/* 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; }
/* 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; }

/* Alerts */
.alert {
  padding:10px 15px;
  border-radius:6px;
  margin-bottom:15px;
  font-size:14px;
  font-weight:500;
  box-shadow:0 2px 5px rgba(0,0,0,0.1);
}
.alert.success { background:#e6ffef; border:1px solid #9be7ac; color:#237a3b; }
.alert.error { background:#ffe6e6; border:1px solid #f5a3a3; color:#a01818; }
.alert.warning { background:#fff8e6; border:1px solid #ffde7a; color:#9f7700; }
</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">
                    <li><a href="daftarbuku.php"><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" style="display:block;">
                    <li><a href="daftaranggota.php" class="active" style="color:#069797;"><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 Anggota</h1>

        <!-- 🔹 ALERT DITARUH DI SINI -->
        <?php if (isset($_GET['deleted'])): ?>
          <div class="alert success">Anggota berhasil dihapus!</div>
        <?php elseif (isset($_GET['error'])): ?>
          <div class="alert error">Gagal menghapus anggota.</div>
        <?php elseif (isset($_GET['notfound'])): ?>
          <div class="alert warning">Data anggota tidak ditemukan.</div>
        <?php endif; ?>

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

        <table>
        <thead>
  <tr>
    <th>No</th>
    <th>Nama Lengkap</th>
    <th>Email</th>
    <th>Username</th>
    <th>NIS</th>
    <th>No. Telepon</th>
    <th>Kelas</th>
    <th>Role</th>
    <th>Tanggal Dibuat</th>
    <th>Aksi</th>
  </tr>
</thead>

<tbody>
<?php if (count($users) > 0): ?>
  <?php $no = $offset + 1; foreach ($users as $user): ?>
    <tr>
      <td><?= $no++ ?></td>
      <td><?= htmlspecialchars($user['fullname']) ?></td>
      <td><?= htmlspecialchars($user['email']) ?></td>
      <td><?= htmlspecialchars($user['username']) ?></td>
      <td><?= htmlspecialchars($user['nis']) ?></td>
      <td><?= htmlspecialchars($user['phone']) ?></td>
      <td><?= htmlspecialchars($user['class']) ?></td>
      <td><?= htmlspecialchars($user['role']) ?></td>
      <td><?= date('d-m-Y', strtotime($user['created_at'])) ?></td>
      <td class="aksi">
        <a href="edit_anggota.php?id=<?= $user['id'] ?>" class="btn-edit">
          <i class="fa fa-pen"></i> Edit
        </a>
        <a href="delete_anggota.php?id=<?= $user['id'] ?>" 
           class="btn-delete" 
           onclick="return confirm('Yakin ingin menghapus anggota ini?');">
          <i class="fa fa-trash"></i> Hapus
        </a>
      </td>
    </tr>
  <?php endforeach; ?>
<?php else: ?>
  <tr><td colspan="10" class="text-center">Belum ada data anggota.</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>

<script>
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';
    });
});
</script>
</body>
</html>
