<?php 
session_start();
include '../koneksi.php';

// 1. Ambil Semester dan TP Aktif agar bisa disimpan ke database
$q_sem = mysqli_query($koneksi, "SELECT id_semester FROM semester WHERE status = 'Aktif' LIMIT 1");
$sem = mysqli_fetch_array($q_sem);
$id_sem_aktif = $sem['id_semester'] ?? 1;

$q_tp = mysqli_query($koneksi, "SELECT id_tp_tahun FROM tahun_pelajaran WHERE status = 'Aktif' LIMIT 1");
$tp = mysqli_fetch_array($q_tp);
$id_tp_aktif = $tp['id_tp_tahun'] ?? 1;

include 'layout_header.php';

$id = $_GET['id'] ?? '';
// Inisialisasi variabel dengan default kosong agar tidak error jika data baru
$d = ['nama_mapel' => '', 'kode_mapel' => '', 'kelompok' => 'Wajib', 'urutan' => 1];

if($id != '') {
    $d = mysqli_fetch_array(mysqli_query($koneksi, "SELECT * FROM master_mapel WHERE id_mapel='$id'"));
}
?>

<div class="container-fluid">
    <h3><?= $id ? 'Edit' : 'Tambah' ?> Mapel</h3>
    <form action="mapel_aksi.php" method="POST" class="card p-4">
        <input type="hidden" name="id" value="<?= $id ?>">
        
        <input type="hidden" name="id_semester" value="<?= $id_sem_aktif ?>">
        <input type="hidden" name="id_tp_tahun" value="<?= $id_tp_aktif ?>">
        
        <label>Nama Mapel</label>
        <input type="text" name="nama" value="<?= htmlspecialchars($d['nama_mapel']) ?>" class="form-control mb-2" required>
        
        <label>Kode Mapel</label>
        <input type="text" name="kode_mapel" value="<?= htmlspecialchars($d['kode_mapel'] ?? '') ?>" class="form-control mb-2" placeholder="Contoh: MAT, IPA" required>
        
        <label>Kelompok</label>
        <select name="kelompok" class="form-select mb-2" required>
            <option value="Wajib" <?= ($d['kelompok']=='Wajib') ? 'selected' : '' ?>>WAJIB</option>
            <option value="Mulok" <?= ($d['kelompok']=='Mulok') ? 'selected' : '' ?>>MULOK</option>
        </select>
        
        <label>Urutan (Nomor)</label>
        <input type="number" name="urutan" value="<?= $d['urutan'] ?>" class="form-control mb-3" required>
        
        <button type="submit" name="simpan" class="btn btn-primary">Simpan</button>
    </form>
</div>

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