<?php
/* =========================================
   FIX AGAR HALAMAN SELALU TAMPIL
========================================= */
if (!isset($mod)) {
    $mod = 'kelas';
}

include_once 'mod/sw-header.php';

/* =========================================
   CEK LOGIN
========================================= */
if(!isset($_COOKIE['COOKIES_MEMBER']) && !isset($_COOKIE['COOKIES_COOKIES'])){
    session_destroy();
    header("location:./index");
    exit;
}

/* =========================================
   DATA USER LOGIN
========================================= */
$pelapor = ucfirst($row_user['employees_name']);
$msg = '';

/* =========================================
   PROSES SIMPAN LAPORAN
========================================= */
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $connection->set_charset("utf8mb4");

    try {
        $tanggal_input    = date('Y-m-d');
        $divisi_tujuan    = $_POST['divisi_tujuan'];
        $penanggung_jawab = $_POST['penanggung_jawab'];
        $lokasi           = $_POST['lokasi'];
        $sekolah          = $_POST['sekolah'];
        $kelas            = $_POST['kelas'];
        $kategori         = $_POST['kategori'];
        $subkategori      = $_POST['subkategori'];
        $detail_laporan   = $_POST['detail_laporan'];
        $status           = 'Belum Proses';

        /* Upload Foto */
        $foto = '';
        if (!empty($_FILES['foto']['name'])) {
            if ($_FILES['foto']['size'] > 2097152) {
                throw new Exception("Ukuran foto maksimal 2MB");
            }
            $dir = "uploads/kelas/";
            if (!is_dir($dir)) mkdir($dir, 0777, true);
            $foto = time().'-'.preg_replace("/[^a-zA-Z0-9.]/","",$_FILES['foto']['name']);
            move_uploaded_file($_FILES['foto']['tmp_name'], $dir.$foto);
        }

        /* INSERT DATABASE */
        $sql = "INSERT INTO kelas_perbaikan SET
                nama_pelapor     = ?,
                tanggal_input    = ?,
                divisi_tujuan    = ?,
                penanggung_jawab = ?,
                lokasi           = ?,
                sekolah          = ?,
                kelas            = ?,
                kategori         = ?,
                subkategori      = ?,
                detail_laporan   = ?,
                foto             = ?,
                status_pekerjaan = ?";

        $stmt = $connection->prepare($sql);
        $stmt->bind_param(
            "ssssssssssss",
            $pelapor,
            $tanggal_input,
            $divisi_tujuan,
            $penanggung_jawab,
            $lokasi,
            $sekolah,
            $kelas,
            $kategori,
            $subkategori,
            $detail_laporan,
            $foto,
            $status
        );
        $stmt->execute();

        /* NOTIFIKASI */
        $connection->query("
            INSERT INTO notifikasi (pesan, kepada_divisi, dibuat_pada)
            VALUES ('Laporan kelas baru dari $pelapor', '$divisi_tujuan', NOW())
        ");

        $msg = "<div class='alert alert-success m-3'>✅ Laporan berhasil dikirim</div>";

    } catch (Exception $e) {
        $msg = "<div class='alert alert-danger m-3'>❌ ".$e->getMessage()."</div>";
    }
}

/* =========================================
   DATA MASTER
========================================= */
$divisiQ   = $connection->query("SELECT position_name FROM position ORDER BY position_name");
$lokasiQ   = $connection->query("SELECT nama_lokasi FROM lokasi_kelas ORDER BY nama_lokasi");
$kategoriQ = $connection->query("SELECT nama_kategori FROM kelas_kategori ORDER BY nama_kategori");

/* Kelas per lokasi */
$kelasData = [];
$q = $connection->query("
    SELECT a.nama_kelas, l.nama_lokasi
    FROM kelas a
    JOIN lokasi_kelas l ON a.lokasi_id = l.id
    ORDER BY a.nama_kelas
");
while($r = $q->fetch_assoc()){
    $kelasData[$r['nama_lokasi']][] = $r['nama_kelas'];
}

/* Subkategori per kategori */
$subData = [];
$q = $connection->query("
    SELECT k.nama_kategori, s.nama_subkategori
    FROM kelas_subkategori s
    JOIN kelas_kategori k ON s.kategori_id = k.id
");
while($r = $q->fetch_assoc()){
    $subData[$r['nama_kategori']][] = $r['nama_subkategori'];
}
?>

<div id="appCapsule">
    <div class="section mt-3 text-center">
        <h3>🏫 Formulir Laporan Sekolah</h3>
        <p><?= tgl_ind($date); ?> - <span class="clock"></span></p>
        <?= $msg; ?>
    </div>

    <div class="section mt-2 mb-2">
        <div class="card">
            <div class="card-body">

                <form method="POST" enctype="multipart/form-data">

                    <div class="form-group boxed">
                        <label>Divisi Tujuan</label>
                        <select name="divisi_tujuan" class="form-control" required>
                            <option value="">Pilih</option>
                            <?php while($d=$divisiQ->fetch_assoc()){ ?>
                                <option><?= $d['position_name']; ?></option>
                            <?php } ?>
                        </select>
                    </div>

                    <div class="form-group boxed">
                        <label>Penanggung Jawab</label>
                        <input type="text" name="penanggung_jawab" class="form-control" required>
                    </div>

                    <div class="form-group boxed">
                        <label>Lokasi</label>
                        <select name="lokasi" id="lokasi" class="form-control" required>
                            <option value="">Pilih</option>
                            <?php while($l=$lokasiQ->fetch_assoc()){ ?>
                                <option><?= $l['nama_lokasi']; ?></option>
                            <?php } ?>
                        </select>
                    </div>

                    <div class="form-group boxed">
                        <label>Sekolah</label>
                        <select name="sekolah" class="form-control" required>
                            <option value="">Pilih Sekolah</option>
                            <option value="SMA IT">SMA IT</option>
                            <option value="SMP IT">SMP IT</option>
                            <option value="SMP ICEH">SMP ICEH</option>
                            <option value="SMP ICH">SMP ICH</option>
                        </select>
                    </div>

                    <div class="form-group boxed">
                        <label>Kelas</label>
                        <select name="kelas" id="kelas" class="form-control" required></select>
                    </div>

                    <div class="form-group boxed">
                        <label>Kategori Masalah</label>
                        <select name="kategori" id="kategori" class="form-control" required>
                            <option value="">Pilih</option>
                            <?php while($k=$kategoriQ->fetch_assoc()){ ?>
                                <option><?= $k['nama_kategori']; ?></option>
                            <?php } ?>
                        </select>
                    </div>

                    <div class="form-group boxed">
                        <label>Sub Kategori</label>
                        <select name="subkategori" id="subkategori" class="form-control" required></select>
                    </div>

                    <div class="form-group boxed">
                        <label>Detail Laporan</label>
                        <textarea name="detail_laporan" class="form-control" required></textarea>
                    </div>

                    <div class="form-group boxed">
                        <label>Upload Foto (maks 2MB)</label>
                        <input type="file" name="foto" class="form-control">
                    </div>

                    <button class="btn btn-success btn-block">
                        📩 Kirim Laporan
                    </button>

                </form>

            </div>
        </div>
    </div>
</div>

<script>
const kelasData = <?= json_encode($kelasData); ?>;
const subData   = <?= json_encode($subData); ?>;

document.getElementById('lokasi').addEventListener('change', function(){
    const k = document.getElementById('kelas');
    k.innerHTML = '<option value="">Pilih</option>';
    if(kelasData[this.value]){
        kelasData[this.value].forEach(v=>{
            k.innerHTML += `<option>${v}</option>`;
        });
    }
});

document.getElementById('kategori').addEventListener('change', function(){
    const s = document.getElementById('subkategori');
    s.innerHTML = '<option value="">Pilih</option>';
    if(subData[this.value]){
        subData[this.value].forEach(v=>{
            s.innerHTML += `<option>${v}</option>`;
        });
    }
});
</script>

<?php include_once 'mod/sw-footer.php'; ?>
