<?php
session_start();
require_once '../koneksi.php';
require_once '../auth.php';
cekAdminAtauGuru();

// 1. Ambil Periode Aktif
$q_aktif = mysqli_query($koneksi, "SELECT s.id_semester, t.id_tp_tahun, s.nama_semester, t.tahun_pelajaran 
                                   FROM semester s, tahun_pelajaran t 
                                   WHERE s.status = 'Aktif' AND t.status = 'Aktif' LIMIT 1");
$aktif = mysqli_fetch_array($q_aktif);
$id_sem_aktif = $aktif['id_semester'] ?? 0;
$id_tp_aktif  = $aktif['id_tp_tahun'] ?? 0;

$id_guru_login = $_SESSION['id_guru'] ?? 0;
$role = $_SESSION['role'] ?? 'guru';

// 2. Logika Ambil Daftar Kelas
$sql_kelas = "SELECT r.id_rombel, r.kelas 
              FROM rombel r
              JOIN anggota_rombel ar ON r.id_rombel = ar.id_rombel
              WHERE ar.id_semester = '$id_sem_aktif' 
              AND ar.id_tp_tahun = '$id_tp_aktif'";

if ($role !== 'admin') {
    $sql_kelas .= " AND r.id_rombel IN (SELECT id_rombel FROM tugas_guru WHERE id_guru = '$id_guru_login')";
}

// Tambahkan ORDER BY di sini
$sql_kelas .= " ORDER BY r.kelas ASC";

$ambil_kelas = mysqli_query($koneksi, $sql_kelas);
$data_mentah = mysqli_fetch_all($ambil_kelas, MYSQLI_ASSOC);

// --- LOGIKA FILTER UNIK BERDASARKAN NAMA KELAS ---
$array_kelas = [];
$nama_terpakai = [];

foreach ($data_mentah as $row) {
    if (!in_array($row['kelas'], $nama_terpakai)) {
        $array_kelas[] = $row;
        $nama_terpakai[] = $row['kelas'];
    }
}

// Validasi kelas_aktif agar mengambil ID pertama yang valid dari hasil filter
$kelas_aktif = $_GET['id_rombel'] ?? ($array_kelas[0]['id_rombel'] ?? '');

// 3. Query Siswa (Kunci ketat dengan ID Semester & TP Aktif)
$query_siswa = null;
if (!empty($kelas_aktif)) {
    $sql_siswa = "SELECT s.* FROM master_siswa s 
                  JOIN anggota_rombel ar ON s.id_siswa = ar.id_siswa 
                  WHERE ar.id_rombel = '$kelas_aktif' 
                  AND ar.id_semester = '$id_sem_aktif' 
                  AND ar.id_tp_tahun = '$id_tp_aktif' 
                  ORDER BY s.nama ASC";
    $query_siswa = mysqli_query($koneksi, $sql_siswa);
}

include 'layout.php';
?>

<div class="container-fluid p-4">
    <h3>Daftar Siswa Kelas</h3>
    <p class="text-muted">Periode Aktif: <strong><?= $aktif['nama_semester'] ?? '-' ?> | <?= $aktif['tahun_pelajaran'] ?? '-' ?></strong></p>
    <hr>

    <form method="GET" class="mb-4">
        <label class="form-label fw-bold">Pilih Kelas:</label>
        <select name="id_rombel" onchange="this.form.submit()" class="form-select w-25">
            <?php if(empty($array_kelas)): ?>
                <option value="">Tidak ada kelas aktif</option>
            <?php else: ?>
                <?php foreach ($array_kelas as $k) { ?>
                    <option value="<?= $k['id_rombel'] ?>" <?= ($kelas_aktif == $k['id_rombel']) ? 'selected' : '' ?>>
                        <?= htmlspecialchars($k['kelas']) ?>
                    </option>
                <?php } ?>
            <?php endif; ?>
        </select>
    </form>

    <table class="table table-bordered table-striped">
        <thead class="table-primary">
            <tr>
                <th>No</th><th>Foto</th><th>NIS</th><th>NISN</th><th>Nama</th><th>Aksi</th>
            </tr>
        </thead>
        <tbody>
            <?php 
            if ($query_siswa && mysqli_num_rows($query_siswa) > 0) {
                $no = 1;
                while($data = mysqli_fetch_array($query_siswa)) {
                    $foto = !empty($data['foto']) ? "../assets/img/siswa/".$data['foto'] : "../assets/img/default.png";
                    echo "<tr>
                            <td>{$no}</td>
                            <td><img src='{$foto}' style='width:50px; height:60px; object-fit:cover;'></td>
                            <td>".htmlspecialchars($data['nis'])."</td>
                            <td>".htmlspecialchars($data['nisn'])."</td>
                            <td>".htmlspecialchars($data['nama'])."</td>
                            <td><a href='edit_siswa.php?id={$data['id_siswa']}' class='btn btn-sm btn-warning'>Edit</a></td>
                          </tr>";
                    $no++;
                }
            } else {
                echo "<tr><td colspan='6' class='text-center'>Data siswa tidak ditemukan untuk kelas/periode ini.</td></tr>";
            }
            ?>
        </tbody>
    </table>
</div>

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