<?php
/**
 * admin/kelola_siswa.php - Manajemen Data Siswa Enhanced
 * Fitur: Filter Limit & Hapus User (Disesuaikan tanpa kolom 'nama')
 * Dikembangkan oleh: Sikawarsito, S.Kom
 */
session_start();
include '../config/database.php';

// 1. Proteksi Admin
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../auth/login_page.php");
    exit;
}

// 2. Logika Hapus User
$msg = "";
if (isset($_GET['hapus'])) {
    $id_hapus = mysqli_real_escape_string($conn, $_GET['hapus']);
    // Pastikan tidak menghapus diri sendiri
    if ($id_hapus == $_SESSION['user_id']) {
        $msg = "<div class='alert alert-danger'>Anda tidak bisa menghapus akun sendiri!</div>";
    } else {
        $del = mysqli_query($conn, "DELETE FROM users WHERE id = '$id_hapus' AND role != 'admin'");
        if ($del) {
            $msg = "<div class='alert alert-success'>Data siswa berhasil dihapus secara permanen.</div>";
        }
    }
}

// 3. Logika Pencarian & Filter
$search = isset($_GET['search']) ? mysqli_real_escape_string($conn, $_GET['search']) : '';
$limit = isset($_GET['limit']) ? $_GET['limit'] : '50';

$where_clause = "WHERE role != 'admin'"; 
if (!empty($search)) {
    // UBAH: Pencarian menggunakan email_guru atau username
    $where_clause .= " AND (email_guru LIKE '%$search%' OR username LIKE '%$search%')";
}

$sql_limit = ($limit == 'all') ? "" : "LIMIT $limit";

// 4. Ambil Data Siswa
$query_users = mysqli_query($conn, "SELECT * FROM users $where_clause ORDER BY id DESC $sql_limit");
$total_tampil = mysqli_num_rows($query_users);
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kelola Siswa | Admin Panel</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <style>
        body { background: #f8fafc; font-family: 'Inter', sans-serif; }
        .card-custom { border: none; border-radius: 24px; box-shadow: 0 10px 30px rgba(0,0,0,0.05); }
        .badge-pro { background: #dcfce7; color: #166534; }
        .badge-free { background: #f1f5f9; color: #475569; }
        .table thead { background: #f1f5f9; }
    </style>
</head>
<body>

<div class="container py-5">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h3 class="fw-bold mb-0">Manajemen Siswa</h3>
            <p class="text-muted">Total ditampilkan: <b><?= $total_tampil ?></b> Siswa</p>
        </div>
        <a href="index.php" class="btn btn-outline-dark rounded-pill px-4">Kembali</a>
    </div>

    <?= $msg ?>

    <div class="card card-custom bg-white p-4 mb-4">
        <form method="GET" class="row g-3">
            <div class="col-md-5">
                <div class="input-group">
                    <span class="input-group-text bg-transparent border-end-0"><i class="bi bi-search"></i></span>
                    <input type="text" name="search" class="form-control border-start-0" placeholder="Cari email atau username..." value="<?= htmlspecialchars($search) ?>">
                </div>
            </div>
            <div class="col-md-3">
                <select name="limit" class="form-select">
                    <option value="50" <?= $limit == '50' ? 'selected' : '' ?>>Tampilkan 50</option>
                    <option value="100" <?= $limit == '100' ? 'selected' : '' ?>>Tampilkan 100</option>
                    <option value="200" <?= $limit == '200' ? 'selected' : '' ?>>Tampilkan 200</option>
                    <option value="all" <?= $limit == 'all' ? 'selected' : '' ?>>Semua Data</option>
                </select>
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-primary w-100 rounded-3 fw-bold">Filter</button>
            </div>
            <div class="col-md-2 text-end">
                 <a href="tambah_siswa.php" class="btn btn-success w-100 rounded-3 fw-bold"><i class="bi bi-person-plus"></i> Baru</a>
            </div>
        </form>
    </div>

    <div class="card card-custom bg-white overflow-hidden p-2">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="small text-uppercase">
                    <tr>
                        <th class="ps-4">Siswa (Username / Email)</th>
                        <th>Layanan</th>
                        <th>Sisa Kuota</th>
                        <th class="text-center">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if($total_tampil > 0): ?>
                        <?php while($row = mysqli_fetch_assoc($query_users)): ?>
                        <tr>
                            <td class="ps-4">
                                <div class="fw-bold text-dark">@<?= htmlspecialchars($row['username']) ?></div>
                                <div class="text-muted small">
                                    <i class="bi bi-envelope"></i> <?= htmlspecialchars($row['email_guru'] ?? 'Belum ada email') ?>
                                </div>
                            </td>
                            <td>
                                <span class="badge rounded-pill <?= $row['status_akun'] == 'pro' ? 'badge-pro' : 'badge-free' ?>">
                                    <?= strtoupper($row['status_akun']) ?>
                                </span>
                            </td>
                            <td>
                                <div class="d-flex align-items-center">
                                    <i class="bi bi-chat-dots-fill text-muted me-2"></i>
                                    <b><?= $row['kuota_harian'] ?></b> <span class="ms-1 text-muted small">Chat</span>
                                </div>
                            </td>
                            <td class="text-center">
                                <div class="btn-group">
                                    <a href="edit_user.php?id=<?= $row['id'] ?>" class="btn btn-sm btn-outline-primary px-3 rounded-pill me-2">
                                        <i class="bi bi-pencil-square"></i> Edit
                                    </a>
                                    <button class="btn btn-sm btn-outline-danger px-3 rounded-pill" onclick="confirmDelete(<?= $row['id'] ?>, '<?= htmlspecialchars($row['username']) ?>')">
                                        <i class="bi bi-trash"></i> Hapus
                                    </button>
                                </div>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr><td colspan="4" class="text-center py-5 text-muted">Data tidak ditemukan.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
    function confirmDelete(id, username) {
        if (confirm("Apakah Bapak yakin ingin menghapus akun '" + username + "'? Semua data riwayat chat akun ini mungkin tidak akan teridentifikasi lagi.")) {
            window.location.href = "kelola_siswa.php?hapus=" + id;
        }
    }
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>