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

    if(!isset($_COOKIE['COOKIES_MEMBER']) && !isset($_COOKIE['COOKIES_COOKIES'])){
        setcookie('COOKIES_MEMBER', '', 0, '/');
        setcookie('COOKIES_COOKIES', '', 0, '/');
        setcookie("COOKIES_MEMBER", "", time()-$expired_cookie);
        setcookie("COOKIES_COOKIES", "", time()-$expired_cookie);
        session_destroy();
        header("location:./index");
    }else{
        // nama pelapor dari user login (sesuaikan field)
        $pelapor = ucfirst($row_user['employees_name']);

        // proses simpan laporan asrama
        if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['kirim_laporan'])) {
            $tanggal_laporan  = date('Y-m-d');
            // gunakan position.position_name sebagai sumber divisi
            $divisi_tujuan    = $_POST['divisi_tujuan'];
            $penanggung_jawab = $_POST['penanggung_jawab'];
            $lokasi           = $_POST['lokasi'];
            $asrama           = $_POST['asrama'];
            $kategori         = $_POST['kategori'];
            $sub_kategori     = $_POST['sub_kategori'];
            $detail_laporan   = $_POST['detail_laporan'];
            $status           = "Belum Proses";

            // Upload foto (maks 2MB) - simpan single foto, jika Anda mau multiple nanti saya ubah
            $fotoName = null;
            if(isset($_FILES['foto']) && $_FILES['foto']['error'] == 0){
                $targetDir = "uploads/laporan/";
                if(!file_exists($targetDir)) mkdir($targetDir, 0777, true);
                $ext = pathinfo($_FILES['foto']['name'], PATHINFO_EXTENSION);
                $fotoName = time().'-'.preg_replace('/[^a-zA-Z0-9_\-\.]/','_', $_FILES['foto']['name']);
                $targetFile = $targetDir.$fotoName;

                if($_FILES['foto']['size'] <= 2097152){
                    if(!move_uploaded_file($_FILES['foto']['tmp_name'], $targetFile)){
                        $fotoName = null;
                        $msg = "<div class='alert alert-warning m-3'>⚠️ Gagal memindahkan file foto.</div>";
                    }
                } else {
                    $msg = "<div class='alert alert-danger m-3'>❌ Ukuran foto maksimal 2MB.</div>";
                }
            }

            // Insert ke tabel laporan_asrama
            $sql = "INSERT INTO laporan_asrama
                    (nama_pelapor, tanggal_laporan, divisi_tujuan, penanggung_jawab, lokasi, asrama, kategori, sub_kategori, detail_laporan, foto, status_pekerjaan, created_at)
                    VALUES (?,?,?,?,?,?,?,?,?,?,?,NOW())";
            $stmt = $connection->prepare($sql);
            if(!$stmt){
                $msg = "<div class='alert alert-danger m-3'>❌ Query prepare error: ".$connection->error."</div>";
            } else {
                $stmt->bind_param("sssssssssss",
                    $pelapor,
                    $tanggal_laporan,
                    $divisi_tujuan,
                    $penanggung_jawab,
                    $lokasi,
                    $asrama,
                    $kategori,
                    $sub_kategori,
                    $detail_laporan,
                    $fotoName,
                    $status
                );
                if($stmt->execute()){
                    // buat notifikasi ke divisi (menggunakan nama divisi seperti position_name)
                    $connection->query("INSERT INTO notifikasi (pesan, kepada_divisi, dibuat_pada)
                                        VALUES ('Laporan asrama baru dari $pelapor', '".$connection->real_escape_string($divisi_tujuan)."', NOW())");

                    $msg = "<div class='alert alert-success m-3'>✅ Laporan asrama berhasil dikirim!</div>";
                    echo '<meta http-equiv="refresh" content="1;url=?mod=supervisi">';
                } else {
                    $msg = "<div class='alert alert-danger m-3'>❌ Gagal menyimpan: ".$stmt->error."</div>";
                }
                $stmt->close();
            }
        }

        // ambil data master untuk dropdown: posisi (divisi), lokasi_asrama, asrama, kategori & subkategori
        $positions = [];
        $qpos = $connection->query("SELECT position_name FROM position ORDER BY position_name ASC");
        while($rp = $qpos->fetch_assoc()){
            $positions[] = $rp['position_name'];
        }

        // lokasi_asrama
        $lokasis = [];
        $ql = $connection->query("SELECT id, nama_lokasi FROM lokasi_asrama ORDER BY id ASC");
        while($rl = $ql->fetch_assoc()){
            $lokasis[] = ['id'=>$rl['id'],'nama'=>$rl['nama_lokasi']];
        }

        // asrama per lokasi -> build JS object
        $asrama_by_lokasi = [];
        $qas = $connection->query("SELECT a.nama_asrama, l.nama_lokasi FROM asrama a JOIN lokasi_asrama l ON a.lokasi_id = l.id ORDER BY l.id, a.nama_asrama");
        while($ras = $qas->fetch_assoc()){
            $asrama_by_lokasi[$ras['nama_lokasi']][] = $ras['nama_asrama'];
        }

        // kategori & subkategori
        $kategori_list = [];
        $sub_by_kat = [];
        $qk = $connection->query("SELECT id, nama_kategori FROM kategori_masalah ORDER BY id");
        while($rk = $qk->fetch_assoc()){
            $kategori_list[] = $rk;
            $qid = $rk['id'];
            $qsub = $connection->query("SELECT nama_sub_kategori FROM sub_kategori_masalah WHERE kategori_id = ".intval($qid)." ORDER BY id");
            while($rsb = $qsub->fetch_assoc()){
                $sub_by_kat[$rk['nama_kategori']][] = $rsb['nama_sub_kategori'];
            }
        }

        // Tampilkan form
        echo '
        <div id="appCapsule">
            <div class="section mt-3 text-center">
                <h3>📄 Laporan Asrama</h3>
                <p>'.tgl_ind(date("Y-m-d")).' - <span class="clock"></span></p>
                '.(isset($msg)?$msg:"").'
            </div>

            <div class="section mt-2 mb-2">
                <div class="card">
                    <div class="card-body">
                        <button id="btnOpenForm" class="btn btn-primary">+ Buat Laporan Asrama</button>
                    </div>
                </div>

                <div id="formLaporan" style="display:none">
                    <div class="card mt-3">
                        <div class="card-body">
                            <form action="" method="POST" enctype="multipart/form-data">

                                <!-- Nama Pelapor (otomatis) -->
                                <div class="form-group boxed">
                                    <div class="input-wrapper">
                                        <label class="label">Nama Pelapor</label>
                                        <input type="text" class="form-control" value="'.htmlspecialchars($pelapor).'" readonly>
                                    </div>
                                </div>

                                <!-- Divisi Tujuan (dari tabel position) -->
                                <div class="form-group boxed">
                                    <div class="input-wrapper">
                                        <label class="label">Divisi Tujuan</label>
                                        <select name="divisi_tujuan" class="form-control custom-select" required>
                                            <option value="">Pilih Divisi</option>';
                                            foreach($positions as $p){
                                                echo "<option value=\"".htmlspecialchars($p)."\">".htmlspecialchars($p)."</option>";
                                            }
        echo '                          </select>
                                    </div>
                                </div>

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

                                <!-- Lokasi -->
                                <div class="form-group boxed">
                                    <div class="input-wrapper">
                                        <label class="label">Lokasi</label>
                                        <select name="lokasi" id="lokasiSelect" class="form-control custom-select" required>
                                            <option value="">Pilih Lokasi</option>';
                                            foreach($lokasis as $lk){
                                                echo "<option value=\"".htmlspecialchars($lk['nama'])."\">".htmlspecialchars($lk['nama'])."</option>";
                                            }
        echo '                              </select>
                                    </div>
                                </div>

                                <!-- Asrama -->
                                <div class="form-group boxed">
                                    <div class="input-wrapper">
                                        <label class="label">Asrama</label>
                                        <select name="asrama" id="asramaSelect" class="form-control custom-select" required>
                                            <option value="">Pilih Asrama</option>
                                        </select>
                                    </div>
                                </div>

                                <!-- Kategori -->
                                <div class="form-group boxed">
                                    <div class="input-wrapper">
                                        <label class="label">Kategori</label>
                                        <select name="kategori" id="kategoriSelect" class="form-control custom-select" required>
                                            <option value="">Pilih Kategori</option>';
                                            foreach($kategori_list as $kat){
                                                echo "<option value=\"".htmlspecialchars($kat['nama_kategori'])."\">".htmlspecialchars($kat['nama_kategori'])."</option>";
                                            }
        echo '                              </select>
                                    </div>
                                </div>

                                <!-- Sub Kategori -->
                                <div class="form-group boxed">
                                    <div class="input-wrapper">
                                        <label class="label">Sub Kategori</label>
                                        <select name="sub_kategori" id="subKategoriSelect" class="form-control custom-select" required>
                                            <option value="">Pilih Sub Kategori</option>
                                        </select>
                                    </div>
                                </div>

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

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

                                <button type="submit" name="kirim_laporan" class="btn btn-success btn-block mt-2">📩 Kirim Laporan</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        ';

        // buat object JS untuk asrama per lokasi dan subkategori
        $js_asrama = json_encode($asrama_by_lokasi);
        $js_sub = json_encode($sub_by_kat);

        echo "
        <script>
            document.getElementById('btnOpenForm').addEventListener('click', function(){
                document.getElementById('formLaporan').style.display = 'block';
                this.style.display = 'none';
            });

            const asramaData = $js_asrama;
            const subKategori = $js_sub;

            document.getElementById('lokasiSelect').addEventListener('change', function(){
                let lokasi = this.value;
                let asramaSel = document.getElementById('asramaSelect');
                asramaSel.innerHTML = '<option value=\"\">Pilih Asrama</option>';
                if (asramaData[lokasi]) {
                    asramaData[lokasi].forEach(a => {
                        asramaSel.innerHTML += `<option value=\"${a}\">${a}</option>`;
                    });
                }
            });

            document.getElementById('kategoriSelect').addEventListener('change', function(){
                let kategori = this.value;
                let subSel = document.getElementById('subKategoriSelect');
                subSel.innerHTML = '<option value=\"\">Pilih Sub Kategori</option>';
                if (subKategori[kategori]) {
                    subKategori[kategori].forEach(s => {
                        subSel.innerHTML += `<option value=\"${s}\">${s}</option>`;
                    });
                }
            });
        </script>
        ";

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