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

$id_user_login = $_SESSION['id_user'];
$role = $_SESSION['role'];

// 1. Ambil Semester dan Tahun Aktif
$q_aktif = mysqli_query($koneksi, "SELECT s.nama_semester, tp.tahun_pelajaran, s.id_semester 
                                   FROM semester s, tahun_pelajaran tp 
                                   WHERE s.status = 'Aktif' AND tp.status = 'Aktif' LIMIT 1");
$aktif = mysqli_fetch_array($q_aktif);
$id_sem_aktif = $aktif['id_semester'] ?? 0;
$nama_semester = $aktif['nama_semester'] ?? '-';
$tahun_pelajaran = $aktif['tahun_pelajaran'] ?? '-';

// 2. Tentukan ID Rombel
if ($role == 'admin') {
    $id_rombel = $_GET['id_rombel'] ?? 0;
} else {
    $q_sinkron = mysqli_query($koneksi, "SELECT id_guru FROM users WHERE id_user = '$id_user_login'");
    $data_guru = mysqli_fetch_array($q_sinkron);
    $id_guru = $data_guru['id_guru'] ?? 0;
    
    $q_wali = mysqli_query($koneksi, "SELECT id_rombel FROM rombel WHERE wali_kelas = '$id_guru'");
    $wali = mysqli_fetch_array($q_wali);
    $id_rombel = $wali['id_rombel'] ?? 0;
}

// 3. Proses Simpan Catatan
if(isset($_POST['simpan_catatan'])) {
    $id_r = $_POST['id_rombel_post'];
    foreach($_POST['catatan'] as $id_siswa => $deskripsi) {
        $deskripsi = mysqli_real_escape_string($koneksi, $deskripsi);
        mysqli_query($koneksi, "INSERT INTO catatan_siswa (id_siswa, id_semester, deskripsi) 
                                VALUES ('$id_siswa', '$id_sem_aktif', '$deskripsi') 
                                ON DUPLICATE KEY UPDATE deskripsi = '$deskripsi'");
    }
    echo "<script>alert('Catatan berhasil diperbarui!'); window.location='catatan_siswa.php?id_rombel=$id_r';</script>";
}

include 'layout.php';
?>

<div class="container-fluid p-4">
    <h3>Input Catatan Wali Kelas</h3>
    
    <div class="alert alert-secondary d-flex justify-content-between">
        <span>Semester: <b><?= $nama_semester ?></b></span>
        <span>Tahun Pelajaran: <b><?= $tahun_pelajaran ?></b></span>
    </div>

    <?php if ($role == 'admin'): ?>
        <form method="GET" class="mb-4">
            <div class="row">
                <div class="col-md-4">
                    <select name="id_rombel" class="form-select" onchange="this.form.submit()">
                        <option value="">-- Pilih Kelas untuk Admin --</option>
                        <?php
                        $q_r = mysqli_query($koneksi, "SELECT id_rombel, kelas FROM rombel ORDER BY kelas ASC");
                        while($r = mysqli_fetch_array($q_r)) {
                            $sel = ($id_rombel == $r['id_rombel']) ? 'selected' : '';
                            echo "<option value='{$r['id_rombel']}' $sel>{$r['kelas']}</option>";
                        }
                        ?>
                    </select>
                </div>
            </div>
        </form>
    <?php endif; ?>

    <?php if ($id_rombel > 0): ?>
        <form method="POST" class="card p-4 shadow-sm">
            <input type="hidden" name="id_rombel_post" value="<?= $id_rombel ?>">
            <table class="table table-bordered table-hover">
                <thead class="table-dark">
                    <tr><th>No</th><th>Nama Siswa</th><th>Catatan Naratif</th></tr>
                </thead>
                <tbody>
                    <?php
                    $no = 1;
// Query yang lebih aman untuk menangani data tidak konsisten
$siswa = mysqli_query($koneksi, "
    SELECT s.id_siswa, s.nama, c.deskripsi 
    FROM master_siswa s 
    JOIN anggota_rombel ar ON s.id_siswa = ar.id_siswa 
    LEFT JOIN catatan_siswa c ON s.id_siswa = c.id_siswa AND c.id_semester = '$id_sem_aktif'
    WHERE ar.id_rombel = '$id_rombel' 
    /* BAGIAN INI DIHAPUS SEMENTARA UNTUK CEK: AND ar.id_semester = '$id_sem_aktif' */
    GROUP BY s.id_siswa 
    ORDER BY s.nama ASC
");
                    
                    if (mysqli_num_rows($siswa) > 0) {
                        while($s = mysqli_fetch_array($siswa)) {
                            echo "<tr>
                                    <td class='text-center' style='width: 5%; vertical-align: middle;'>{$no}</td>
                                    <td style='width: 30%; vertical-align: middle;'><b>{$s['nama']}</b></td>
                                    <td>
                                        <textarea name='catatan[{$s['id_siswa']}]' class='form-control' rows='2' placeholder='Tuliskan perkembangan siswa...'>{$s['deskripsi']}</textarea>
                                    </td>
                                  </tr>";
                            $no++;
                        }
                    } else {
                        echo "<tr><td colspan='3' class='text-center'>Tidak ada siswa ditemukan di kelas ini.</td></tr>";
                    }
                    ?>
                </tbody>
            </table>
            <button type="submit" name="simpan_catatan" class="btn btn-primary">Simpan Semua Catatan</button>
        </form>
    <?php else: ?>
        <div class="alert alert-info">Silakan pilih kelas untuk menampilkan daftar siswa.</div>
    <?php endif; ?>
</div>

</body>
</html>