<?php
if ($mod == ''){
    header('location:../404');
    exit;
}

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 ASRAMA
================================ */
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'];
        $asrama           = $_POST['asrama'];
        $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/asrama/";
            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 asrama_perbaikan SET
                nama_pelapor      = ?,
                tanggal_input     = ?,
                divisi_tujuan     = ?,
                penanggung_jawab  = ?,
                lokasi            = ?,
                asrama            = ?,
                kategori          = ?,
                subkategori       = ?,
                detail_laporan    = ?,
                foto              = ?,
                status_pekerjaan  = ?";

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

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

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

    } catch (Exception $e) {
        $msg = "<div class='alert alert-danger m-3'>
                ❌ Error: ".$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_asrama ORDER BY nama_lokasi");
$kategoriQ = $connection->query("SELECT nama_kategori FROM asrama_kategori ORDER BY nama_kategori");

/* Asrama per lokasi */
$asramaData = [];
$q = $connection->query("
    SELECT a.nama_asrama, l.nama_lokasi
    FROM asrama a
    JOIN lokasi_asrama l ON a.lokasi_id=l.id
");
while($r = $q->fetch_assoc()){
    $asramaData[$r['nama_lokasi']][] = $r['nama_asrama'];
}

/* Subkategori per kategori */
$subData = [];
$q = $connection->query("
    SELECT k.nama_kategori, s.nama_subkategori
    FROM asrama_subkategori s
    JOIN asrama_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 Asrama</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">

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

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

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

                    <!-- Asrama -->
                    <div class="form-group boxed">
                        <label class="label">Asrama</label>
                        <select name="asrama" id="asrama" class="form-control custom-select" required></select>
                    </div>

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

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

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

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

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

                </form>

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

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

document.getElementById('lokasi')?.addEventListener('change', function(){
    const a = document.getElementById('asrama');
    a.innerHTML = '<option value="">Pilih</option>';
    if(asramaData[this.value]){
        asramaData[this.value].forEach(x=>{
            a.innerHTML += `<option>${x}</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(x=>{
            s.innerHTML += `<option>${x}</option>`;
        });
    }
});
</script>

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