<?php 
include 'layout_header.php'; 
require_once '../koneksi.php';

$id = isset($_GET['id']) ? (int)$_GET['id'] : '';
$data = ['id_level' => '', 'wali_kelas' => '', 'kelas' => '']; // Konsisten pakai 'kelas'

if ($id != '') {
    $q = mysqli_query($koneksi, "SELECT * FROM rombel WHERE id_rombel = '$id'");
    $data = mysqli_fetch_array($q);
}
?>

<form action="rombel_aksi.php" method="POST" class="card p-4">
    <input type="hidden" name="id_rombel" value="<?= $id ?>">
    
    <div class="mb-3">
        <label>Pilih Level</label>
        <select name="id_level" class="form-select" required>
            <?php
            $lvl = mysqli_query($koneksi, "SELECT * FROM level");
            while($l = mysqli_fetch_array($lvl)) {
                $sel = ($l['id_level'] == $data['id_level']) ? 'selected' : '';
                echo "<option value='$l[id_level]' $sel>$l[nama_level]</option>";
            }
            ?>
        </select>
    </div>
    
    <div class="mb-3">
    <label>Wali Kelas</label>
    <select name="wali_kelas" class="form-select">
        <option value="">-- Pilih Wali Kelas --</option>
        <?php
        // Mengambil data guru dari master_guru
        $g = mysqli_query($koneksi, "SELECT id_guru, nama FROM master_guru");
        while($row = mysqli_fetch_array($g)) {
            // Logika selected: bandingkan id_guru dari database dengan id yang tersimpan di rombel
            $sel = ($row['id_guru'] == $data['wali_kelas']) ? 'selected' : ''; 
            
            // Value diisi dengan id_guru, tapi label yang ditampilkan adalah nama guru
            echo "<option value='{$row['id_guru']}' $sel>{$row['nama']}</option>";
        }
        ?>
    </select>
</div>

    <div class="mb-3">
        <label>Nama Kelas</label>
        <input type="text" name="kelas" value="<?= htmlspecialchars($data['kelas'] ?? '') ?>" class="form-control" placeholder="Contoh: 6A" required>
    </div>
    
    <button type="submit" name="simpan_rombel" class="btn btn-primary">Simpan Data</button>
</form>

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