<?php 
session_start();
include '../koneksi.php';
include 'layout_header.php'; 

// 1. Pengaturan Filter, Pencarian, & Limit
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 25;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;
$status_filter = isset($_GET['status']) ? $_GET['status'] : 'Aktif';
$search = isset($_GET['search']) ? mysqli_real_escape_string($koneksi, $_GET['search']) : '';

// 2. Query untuk Menghitung Total
$where = "WHERE status = '$status_filter'";
if (!empty($search)) {
    $where .= " AND (nama LIKE '%$search%' OR nis LIKE '%$search%')";
}

$sql_count = mysqli_query($koneksi, "SELECT COUNT(*) FROM master_siswa $where");
$total_data = mysqli_fetch_array($sql_count)[0];
$total_pages = ceil($total_data / $limit);
?>

<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h3>Data Siswa (Total: <?= $total_data ?>)</h3>
        <div>
            <a href="siswa_form.php" class="btn btn-primary"><i class="fa fa-plus"></i> Tambah</a>
            <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#modalImport"><i class="fa fa-upload"></i> CSV</button>
        </div>
    </div>

    <div class="card shadow-sm mb-3">
        <div class="card-body d-flex flex-wrap gap-2 align-items-center">
            <div class="btn-group">
                <a href="?status=Aktif&limit=<?= $limit ?>" class="btn btn-sm btn-outline-primary <?= ($status_filter=='Aktif')?'active':'' ?>">Aktif</a>
                <a href="?status=Lulus&limit=<?= $limit ?>" class="btn btn-sm btn-outline-success <?= ($status_filter=='Lulus')?'active':'' ?>">Lulus</a>
                <a href="?status=Pindah&limit=<?= $limit ?>" class="btn btn-sm btn-outline-warning <?= ($status_filter=='Pindah')?'active':'' ?>">Pindah</a>
            </div>

            <select class="form-select form-select-sm w-auto" onchange="window.location.href='?status=<?= $status_filter ?>&limit='+this.value">
                <option value="25" <?= $limit == 25 ? 'selected' : '' ?>>25 / Hal</option>
                <option value="50" <?= $limit == 50 ? 'selected' : '' ?>>50 / Hal</option>
                <option value="100" <?= $limit == 100 ? 'selected' : '' ?>>100 / Hal</option>
            </select>

            <form class="d-flex ms-auto" method="GET">
                <input type="hidden" name="status" value="<?= $status_filter ?>">
                <input type="hidden" name="limit" value="<?= $limit ?>">
                <input type="text" name="search" class="form-control form-control-sm me-2" placeholder="Cari nama/NIS..." value="<?= $search ?>">
                <button type="submit" class="btn btn-sm btn-secondary">Cari</button>
            </form>
        </div>
    </div>

    <form action="aksi_status_massal.php" method="POST" id="formMassal">
        <div class="card shadow-sm border-0">
            <div class="card-body p-0">
                <table class="table table-hover align-middle mb-0">
                    <thead class="table-light">
                        <tr>
                            <th width="30"><input type="checkbox" id="checkAll"></th>
                            <th>No</th>
                            <th>Foto</th>
                            <th>Nama & Kelas</th>
                            <th>NIS/NISN</th>
                            <th>Status</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $no = $offset + 1;
                        $sql = mysqli_query($koneksi, "SELECT * FROM master_siswa $where ORDER BY nama ASC LIMIT $limit OFFSET $offset");
                        while($d = mysqli_fetch_array($sql)) {
                            $foto = (!empty($d['foto']) && file_exists('../assets/img/siswa/'.$d['foto'])) ? '../assets/img/siswa/'.$d['foto'] : '../assets/img/default.png';
                        ?>
                        <tr>
                            <td><input type="checkbox" name="id_siswa[]" value="<?= $d['id_siswa']; ?>"></td>
                            <td><?= $no++; ?></td>
                            <td><img src="<?= $foto ?>" width="40" height="40" class="rounded-circle" style="object-fit: cover;"></td>
                            <td><b><?= htmlspecialchars($d['nama']); ?></b><br><small><?= htmlspecialchars($d['kelas_awal'] ?? '-') ?></small></td>
                            <td><?= $d['nis'] ?><br><small><?= $d['nisn'] ?></small></td>
                            <td><span class="badge bg-<?= ($d['status']=='Aktif'?'info':($d['status']=='Lulus'?'success':'warning')) ?>"><?= $d['status'] ?></span></td>
                            <td>
    <a href="siswa_form.php?id=<?= $d['id_siswa']; ?>" class="btn btn-sm btn-warning"><i class="fa fa-edit"></i></a>
    <a href="aksi_hapus_siswa.php?id=<?= $d['id_siswa']; ?>" 
       class="btn btn-sm btn-danger" 
       onclick="return confirm('Apakah Anda yakin ingin menghapus data siswa ini?')">
       <i class="fa fa-trash"></i>
    </a>
</td>
                        </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>
            <div class="card-footer bg-light">
                <select name="status_baru" class="form-select form-select-sm w-25 d-inline-block" required>
                    <option value="">-- Aksi Massal --</option>
                    <option value="Aktif">Set Aktif</option>
                    <option value="Lulus">Set Lulus</option>
                    <option value="Pindah">Set Pindah</option>
                </select>
                <button type="submit" name="proses_massal" class="btn btn-sm btn-danger" onclick="return confirm('Update status siswa terpilih?')">Proses</button>
            </div>
        </div>
    </form>

    <nav class="mt-3">
        <ul class="pagination">
            <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                <li class="page-item <?= ($page == $i) ? 'active' : ''; ?>">
                    <a class="page-link" href="?status=<?= $status_filter ?>&limit=<?= $limit ?>&search=<?= $search ?>&page=<?= $i ?>"><?= $i ?></a>
                </li>
            <?php endfor; ?>
        </ul>
    </nav>
</div>

<div class="modal fade" id="modalImport" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form action="aksi_import_csv.php" method="POST" enctype="multipart/form-data">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Import Data Siswa (CSV)</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="file" name="file_csv" class="form-control" accept=".csv" required>
                </div>
                <div class="modal-footer">
                    <button type="submit" name="import" class="btn btn-success">Upload</button>
                </div>
            </div>
        </form>
    </div>
</div>

<script>
    document.getElementById('checkAll').onclick = function() {
        var checkboxes = document.querySelectorAll('input[name="id_siswa[]"]');
        for (var cb of checkboxes) cb.checked = this.checked;
    }
</script>

<?php include 'layout_footer.php'; ?>