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

// 1. Ambil Tahun Pelajaran Aktif untuk ditampilkan
$q_tp = mysqli_query($koneksi, "SELECT tahun_pelajaran FROM tahun_pelajaran WHERE status = 'Aktif' LIMIT 1");
$tp = mysqli_fetch_assoc($q_tp);
$tahun_teks = $tp['tahun_pelajaran'] ?? '-';

$id_edit = $_GET['edit'] ?? null;
$data = ['id_rombel'=>'', 'id_mapel'=>'', 'id_guru'=>'', 'hari'=>'', 'jam_mulai'=>'', 'jam_selesai'=>''];

// Ambil data jika sedang mode edit
if ($id_edit) {
    $q = mysqli_query($koneksi, "SELECT * FROM jadwal_pelajaran WHERE id_jadwal = '$id_edit'");
    $data = mysqli_fetch_array($q);
}

// Proses Simpan
if (isset($_POST['simpan'])) {
    $jam_data = explode('|', $_POST['jam_waktu']);
    
    $id_rombel = mysqli_real_escape_string($koneksi, $_POST['id_rombel']);
    $id_mapel = mysqli_real_escape_string($koneksi, $_POST['id_mapel']);
    $id_guru  = mysqli_real_escape_string($koneksi, $_POST['id_guru'] ?? '');
    $hari     = mysqli_real_escape_string($koneksi, $_POST['hari']);

    // Validasi
    if(empty($id_mapel)) {
        echo "<script>alert('Gagal! Pilih Mapel atau Kegiatan.'); window.history.back();</script>";
        exit;
    }
    if(empty($id_guru)) {
        echo "<script>alert('Gagal! Pilih guru.'); window.history.back();</script>";
        exit;
    }
    
    // Simpan Data
    if ($id_edit) {
        $q = "UPDATE jadwal_pelajaran SET id_rombel='$id_rombel', id_mapel='$id_mapel', id_guru='$id_guru', hari='$hari', jam_mulai='{$jam_data[0]}', jam_selesai='{$jam_data[1]}' WHERE id_jadwal='$id_edit'";
    } else {
        $q = "INSERT INTO jadwal_pelajaran (id_rombel, id_mapel, id_guru, hari, jam_mulai, jam_selesai) VALUES ('$id_rombel', '$id_mapel', '$id_guru', '$hari', '{$jam_data[0]}', '{$jam_data[1]}')";
    }
    
    if(mysqli_query($koneksi, $q)) {
        echo "<script>alert('Data berhasil disimpan'); window.location='jadwal_pelajaran.php';</script>";
    } else {
        echo "Error: " . mysqli_error($koneksi);
    }
}

include 'layout.php';
?>

<div class="container-fluid mt-4">
    <div class="card p-4 shadow-sm">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h3><?= $id_edit ? 'Edit' : 'Tambah' ?> Jadwal</h3>
                <p>Tahun Pelajaran: <strong><?= $tahun_teks ?></strong></p>
            </div>
            <a href="atur_jam_rombel.php" class="btn btn-warning btn-sm">⚙️ Atur Jam Per Kelas</a>
        </div>

        <form method="POST" id="formJadwal">
            <div class="row">
    <div class="col-md-6 mb-3">
        <label>Kelas</label>
        <select name="id_rombel" id="id_rombel" class="form-select" required onchange="loadJam(this.value)">
            <option value="">-- Pilih Kelas --</option>
            <?php 
            $q = mysqli_query($koneksi, "SELECT * FROM rombel");
            while($r = mysqli_fetch_array($q)) {
                $sel = ($data['id_rombel'] == $r['id_rombel']) ? 'selected' : '';
                echo "<option value='{$r['id_rombel']}' $sel>{$r['kelas']}</option>";
            }
            ?>
        </select>
    </div>

    <div class="col-md-6 mb-3">
        <label>Jam Pelajaran</label>
        <select name="jam_waktu" id="jam_waktu" class="form-select" required>
            <option value="">-- Pilih Kelas Dulu --</option>
        </select>
    </div>
</div>

<div class="row">
    <div class="col-md-4 mb-3">
        <label>Guru</label>
        <select name="id_guru" class="form-select" required>
            <option value="">-- Pilih Guru --</option>
            <?php 
            $q = mysqli_query($koneksi, "SELECT id_guru, nama FROM master_guru"); 
            while($r = mysqli_fetch_array($q)) { 
                $sel = ($data['id_guru'] == $r['id_guru']) ? 'selected' : ''; 
                echo "<option value='{$r['id_guru']}' $sel>{$r['nama']}</option>"; 
            } 
            ?>
        </select>
    </div>

    <div class="col-md-4 mb-3">
    <label>Mapel / Kegiatan</label>
    <select name="id_mapel" class="form-select" required>
    <option value="">-- Pilih Mapel / Kegiatan --</option>
    <?php 
    $q = mysqli_query($koneksi, "SELECT id_mapel, kode_mapel, nama_mapel FROM master_mapel GROUP BY kode_mapel"); 
    while($r = mysqli_fetch_array($q)) { 
        $sel = ($data['id_mapel'] == $r['id_mapel']) ? 'selected' : ''; 
        echo "<option value='{$r['id_mapel']}' $sel>{$r['kode_mapel']} - {$r['nama_mapel']}</option>"; 
    } 
    ?>
</select>
</div>

    <div class="col-md-4 mb-3">
        <label>Hari</label>
        <select name="hari" class="form-select" required>
            <option value="">-- Pilih Hari --</option>
            <?php foreach(['Senin','Selasa','Rabu','Kamis','Jumat','Sabtu'] as $h) { 
                $sel = ($data['hari'] == $h) ? 'selected' : ''; 
                echo "<option value='$h' $sel>$h</option>"; 
            } ?>
        </select>
    </div>
</div>
            <button type="submit" name="simpan" class="btn btn-success">Simpan Data</button>
        </form>
    </div>
</div>

<script>
function loadJam(id_rombel, selectedJam = null) {
    if(!id_rombel) return;
    fetch('get_jam.php?id_rombel=' + id_rombel)
        .then(response => response.text())
        .then(data => {
            document.getElementById("jam_waktu").innerHTML = data;
            if(selectedJam) document.getElementById("jam_waktu").value = selectedJam;
        });
}

<?php if($id_edit): ?>
    window.onload = () => loadJam('<?= $data['id_rombel'] ?>', '<?= $data['jam_mulai'].'|'.$data['jam_selesai'] ?>');
<?php endif; ?>
</script>

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