<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once('../koneksi.php');
require_once('../auth.php');
cekAdminAtauGuru();

// 1. Identitas User
$id_guru_aktif = $_SESSION['id_guru'] ?? 0;
$g = mysqli_fetch_array(mysqli_query($koneksi, "SELECT nama FROM master_guru WHERE id_guru = '$id_guru_aktif'"));
$nama_guru_login = $g['nama'] ?? 'Admin/Guru';

// 2. Ambil Periode Aktif
$q_aktif = mysqli_query($koneksi, "SELECT s.id_semester, s.nama_semester, t.id_tp_tahun, 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;

// 3. Proses Update Status (Keputusan Akhir)
if (isset($_POST['simpan_status'])) {
    $id_s = (int)$_POST['id_siswa'];
    $sts = mysqli_real_escape_string($koneksi, $_POST['status']);
    $id_r = (int)$_POST['id_rombel'];
    
    mysqli_query($koneksi, "UPDATE anggota_rombel SET keputusan_akhir = '$sts' 
                           WHERE id_siswa = '$id_s' AND id_rombel = '$id_r' 
                           AND id_semester = '$id_sem_aktif' AND id_tp_tahun = '$id_tp_aktif'");
}

// 4. Penentuan Rombel
$id_rombel = 0;
if ($_SESSION['role'] == 'admin') {
    $id_rombel = (int)($_GET['id_rombel'] ?? 0);
} else {
    $wali = mysqli_fetch_array(mysqli_query($koneksi, "SELECT id_rombel FROM rombel WHERE wali_kelas = '$id_guru_aktif'"));
    $id_rombel = $wali['id_rombel'] ?? 0;
}

// Ambil data kelas untuk header
$data_kelas = mysqli_fetch_array(mysqli_query($koneksi, "SELECT kelas FROM rombel WHERE id_rombel = '$id_rombel'"));
$nama_kelas = $data_kelas['kelas'] ?? '-';

// 5. Query Mapel (Mengambil berdasarkan NAMA KELAS untuk menghindari masalah ID duplikat)
$daftar_mapel = [];
if ($id_rombel > 0) {
    $sql_mapel = "SELECT DISTINCT m.id_mapel, m.nama_mapel 
                  FROM master_mapel m 
                  JOIN tugas_guru tg ON m.id_mapel = tg.id_mapel 
                  JOIN rombel r ON tg.id_rombel = r.id_rombel
                  WHERE r.kelas = (SELECT kelas FROM rombel WHERE id_rombel = '$id_rombel')
                  AND tg.id_semester = '$id_sem_aktif' 
                  AND tg.id_tp_tahun = '$id_tp_aktif' 
                  ORDER BY m.urutan ASC";
    $daftar_mapel = mysqli_fetch_all(mysqli_query($koneksi, $sql_mapel), MYSQLI_ASSOC);
}

include 'layout.php';
?>

<div class="container-fluid">
    <h3>Leger Nilai Kelas <?= htmlspecialchars($nama_kelas) ?></h3>
    
    <div class="alert alert-secondary shadow-sm">
        <div class="row">
            <div class="col-md-4"><i class="fa fa-user"></i> Guru: <strong><?= htmlspecialchars($nama_guru_login) ?></strong></div>
            <div class="col-md-4"><i class="fa fa-calendar"></i> Tahun: <strong><?= $aktif['tahun_pelajaran'] ?? '-' ?></strong></div>
            <div class="col-md-4"><i class="fa fa-book"></i> Semester: <strong><?= $aktif['nama_semester'] ?? '-' ?></strong></div>
        </div>
    </div>

    <?php if($_SESSION['role'] == 'admin'): ?>
    <form method="GET" class="card p-3 mb-4 border-0 shadow-sm">
        <label class="fw-bold">Pilih Kelas:</label>
        <select name="id_rombel" onchange="this.form.submit()" class="form-select">
            <option value="0">- Pilih Kelas -</option>
            <?php 
            $q_r = mysqli_query($koneksi, "SELECT * FROM rombel ORDER BY kelas ASC");
            while($r = mysqli_fetch_array($q_r)) {
                echo "<option value='{$r['id_rombel']}' ".($id_rombel==$r['id_rombel']?'selected':'').">{$r['kelas']}</option>";
            }
            ?>
        </select>
    </form>
    <?php endif; ?>

    <?php if ($id_rombel > 0): ?>
    <div class="table-responsive card p-3 shadow-sm">
        <table class="table table-bordered table-hover">
            <thead class="table-dark text-center">
                <tr><th>No</th><th>Nama Siswa</th><?php foreach($daftar_mapel as $m) echo "<th>{$m['nama_mapel']}</th>"; ?><th>Status</th><th>Aksi</th></tr>
            </thead>
            <tbody>
                <?php 
                // Mengambil siswa berdasarkan nama kelas yang sama agar duplikat ID tidak menghalangi data
                $q_siswa = mysqli_query($koneksi, "
                    SELECT s.id_siswa, s.nama, ar.keputusan_akhir, ar.id_rombel 
                    FROM master_siswa s 
                    JOIN anggota_rombel ar ON s.id_siswa = ar.id_siswa 
                    JOIN rombel r ON ar.id_rombel = r.id_rombel 
                    WHERE r.kelas = (SELECT kelas FROM rombel WHERE id_rombel = '$id_rombel') 
                    AND ar.id_semester = '$id_sem_aktif' 
                    AND ar.id_tp_tahun = '$id_tp_aktif' 
                    ORDER BY s.nama ASC");
                
                if (mysqli_num_rows($q_siswa) > 0) {
                    $no = 1;
                    while($s = mysqli_fetch_array($q_siswa)) {
                        echo "<tr><td>{$no}</td><td>".htmlspecialchars($s['nama'])."</td>";
                        
                        foreach($daftar_mapel as $m) {
                            $n = mysqli_fetch_array(mysqli_query($koneksi, "
                                SELECT nilai_rapor FROM nilai_siswa 
                                WHERE id_siswa = '{$s['id_siswa']}' 
                                AND id_tugas IN (SELECT id_tugas FROM tugas_guru WHERE id_mapel = '{$m['id_mapel']}' AND id_rombel = '{$s['id_rombel']}') 
                                LIMIT 1"));
                            echo "<td class='text-center'>".($n['nilai_rapor'] ?? '-')."</td>";
                        }
                        
                        echo "<td>
                                <form method='POST'>
                                    <input type='hidden' name='id_siswa' value='{$s['id_siswa']}'>
                                    <input type='hidden' name='id_rombel' value='{$s['id_rombel']}'>
                                    <select name='status' onchange='this.form.submit()' class='form-select form-select-sm'>
                                        <option value=''>-</option>
                                        <option value='NAIK' ".($s['keputusan_akhir']=='NAIK'?'selected':'').">NAIK</option>
                                        <option value='TINGGAL' ".($s['keputusan_akhir']=='TINGGAL'?'selected':'').">TINGGAL</option>
                                        <option value='LULUS' ".($s['keputusan_akhir']=='LULUS'?'selected':'').">LULUS</option>
                                    </select>
                                    <input type='hidden' name='simpan_status'>
                                </form>
                              </td>
                              <td class='text-center'><a href='cetak_rapor.php?id_siswa={$s['id_siswa']}' class='btn btn-sm btn-success' target='_blank'>Cetak</a></td>
                              </tr>";
                        $no++;
                    }
                } else {
                    echo "<tr><td colspan='100%' class='text-center'>Data tidak ditemukan. Pastikan siswa terdaftar di kelas ini untuk tahun ajaran aktif.</td></tr>";
                }
                ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
        <div class="alert alert-warning">Silakan pilih kelas terlebih dahulu.</div>
    <?php endif; ?>
</div>
<?php include 'layout_footer.php'; ?>