<?= $this->extend('v_template/layout') ?>

<?= $this->section('content') ?>

<div class="row mb-4 align-items-center">
    <div class="col-12">
        <h4 class="fw-bold text-success"><i class="fa-solid fa-person-hiking me-2"></i> Form Patroli Lapangan</h4>
        <p class="text-muted mb-0">Laporan temuan di lapangan. <span id="statusSinyal" class="badge bg-success ms-2">Online</span></p>
    </div>
</div>

<div class="row">
    <div class="col-md-7">
        <div class="card shadow-sm border-0 mb-4">
            <div class="card-body p-4">

                <form id="formPatroli">
                    <div class="mb-3">
                        <label class="form-label fw-bold">Nama Petugas</label>
                        <input type="text" id="nama_petugas" class="form-control bg-light" value="<?= session()->get('nama_lengkap') ?>" readonly>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-bold">Lokasi / Blok Hutan</label>
                        <select id="lokasi_blok" class="form-select" required>
                            <option value="">-- Pilih Area Patroli --</option>
                            <option value="Blok Kisaran Timur">Blok Kisaran Timur</option>
                            <option value="Blok Hutan Lindung A">Blok Hutan Lindung A</option>
                            <option value="Area Perhutanan Sosial">Area Perhutanan Sosial</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-bold">Keterangan / Temuan</label>
                        <textarea id="temuan" class="form-control" rows="3" placeholder="Tuliskan kondisi tegakan, temuan patok batas, atau indikasi karhutla..." required></textarea>
                    </div>

                    <!-- Input Foto Baru -->
                    <div class="mb-4">
                        <label class="form-label fw-bold">Foto Bukti Lapangan <span class="text-muted fw-normal">(Opsional)</span></label>
                        <!-- atribut 'capture="environment"' akan langsung membuka kamera belakang saat di HP -->
                        <input type="file" id="inputFoto" class="form-control" accept="image/*" capture="environment">
                        <div class="form-text text-muted"><i class="fa-solid fa-compress me-1"></i> Foto akan otomatis dikompres agar ringan di-upload.</div>
                        <img id="previewFoto" src="" class="img-thumbnail mt-2 d-none" style="max-height: 200px; width: auto;">
                    </div>

                    <div class="text-end">
                        <button type="submit" class="btn btn-success px-4 rounded-pill shadow-sm">
                            <i class="fa-solid fa-paper-plane me-2"></i> Kirim Laporan
                        </button>
                    </div>
                </form>

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

    <div class="col-md-5">
        <div class="card border-warning bg-warning bg-opacity-10 shadow-sm">
            <div class="card-header bg-warning text-dark fw-bold">
                <i class="fa-solid fa-rotate me-2"></i> Antrean Sinkronisasi (Offline)
            </div>
            <div class="card-body">
                <ul id="daftarAntrean" class="list-group list-group-flush bg-transparent">
                </ul>
                <p id="pesanKosong" class="text-muted small mt-2 mb-0">Semua laporan & foto telah tersinkronisasi ke server pusat.</p>
            </div>
        </div>
    </div>
</div>

<script>
    const form = document.getElementById('formPatroli');
    const statusSinyal = document.getElementById('statusSinyal');
    const daftarAntrean = document.getElementById('daftarAntrean');
    const pesanKosong = document.getElementById('pesanKosong');

    // Variabel untuk menyimpan kode foto
    let kodeFotoBase64 = "";

    // Fitur Mengompres Gambar (Mengecilkan Ukuran Foto)
    document.getElementById('inputFoto').addEventListener('change', function(event) {
        let file = event.target.files[0];
        if (!file) return;

        let reader = new FileReader();
        reader.onload = function(e) {
            let img = new Image();
            img.onload = function() {
                // Proses melukis ulang gambar dengan ukuran lebih kecil
                let canvas = document.createElement('canvas');
                let MAX_WIDTH = 800; // Lebar maksimal
                let scaleSize = MAX_WIDTH / img.width;
                canvas.width = MAX_WIDTH;
                canvas.height = img.height * scaleSize;

                let ctx = canvas.getContext('2d');
                ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

                // Mengubah gambar menjadi kode Base64 (kualitas 70%)
                kodeFotoBase64 = canvas.toDataURL("image/jpeg", 0.7);

                // Menampilkan preview foto ke layar
                let preview = document.getElementById('previewFoto');
                preview.src = kodeFotoBase64;
                preview.classList.remove('d-none');
            }
            img.src = e.target.result;
        }
        reader.readAsDataURL(file);
    });

    window.addEventListener('online', updateIndikatorSinyal);
    window.addEventListener('offline', updateIndikatorSinyal);

    function updateIndikatorSinyal() {
        if (navigator.onLine) {
            statusSinyal.className = 'badge bg-success ms-2';
            statusSinyal.innerText = 'Online';
            sinkronisasiData();
        } else {
            statusSinyal.className = 'badge bg-danger ms-2';
            statusSinyal.innerText = 'Offline (Blank Spot)';
        }
    }

    form.addEventListener('submit', function(e) {
        e.preventDefault();

        let dataLaporan = {
            nama_petugas: document.getElementById('nama_petugas').value,
            lokasi_blok: document.getElementById('lokasi_blok').value,
            temuan: document.getElementById('temuan').value,
            foto_bukti: kodeFotoBase64, // Memasukkan kode foto
            id_unik: Date.now()
        };

        if (navigator.onLine) {
            kirimKeServer(dataLaporan);
        } else {
            simpanKeOffline(dataLaporan);
            alert("Sinyal tidak terdeteksi. Laporan & Foto disimpan di memori HP dan akan dikirim saat sinyal kembali!");
            resetForm();
        }
    });

    function kirimKeServer(data) {
        let formData = new FormData();
        formData.append('nama_petugas', data.nama_petugas);
        formData.append('lokasi_blok', data.lokasi_blok);
        formData.append('temuan', data.temuan);
        formData.append('foto_bukti', data.foto_bukti);

        fetch('<?= base_url('patroli/simpan_ajax') ?>', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(res => {
                alert(res.pesan);
                resetForm();
                hapusDariOffline(data.id_unik);
            })
            .catch(error => {
                simpanKeOffline(data);
            });
    }

    function simpanKeOffline(data) {
        let antrean = JSON.parse(localStorage.getItem('antreanPatroli')) || [];
        let cekAda = antrean.find(item => item.id_unik === data.id_unik);
        if (!cekAda) {
            antrean.push(data);
            localStorage.setItem('antreanPatroli', JSON.stringify(antrean));
        }
        tampilkanAntrean();
    }

    function hapusDariOffline(id_unik) {
        let antrean = JSON.parse(localStorage.getItem('antreanPatroli')) || [];
        antrean = antrean.filter(item => item.id_unik !== id_unik);
        localStorage.setItem('antreanPatroli', JSON.stringify(antrean));
        tampilkanAntrean();
    }

    function sinkronisasiData() {
        let antrean = JSON.parse(localStorage.getItem('antreanPatroli')) || [];
        if (antrean.length > 0) {
            antrean.forEach(data => {
                kirimKeServer(data);
            });
        }
    }

    function tampilkanAntrean() {
        let antrean = JSON.parse(localStorage.getItem('antreanPatroli')) || [];
        daftarAntrean.innerHTML = '';
        if (antrean.length > 0) {
            pesanKosong.style.display = 'none';
            antrean.forEach(data => {
                let infoFoto = data.foto_bukti !== "" ? '<span class="badge bg-info mt-1"><i class="fa-solid fa-camera"></i> Dengan Foto</span>' : '';
                daftarAntrean.innerHTML += `
                    <li class="list-group-item bg-transparent px-0 text-dark">
                        <i class="fa-solid fa-clock text-danger me-2"></i> 
                        <strong>${data.lokasi_blok}</strong><br>
                        ${infoFoto}
                        <br><small class="text-muted">Tertunda pengiriman...</small>
                    </li>`;
            });
        } else {
            pesanKosong.style.display = 'block';
        }
    }

    // Fungsi untuk mereset form dan foto
    function resetForm() {
        form.reset();
        kodeFotoBase64 = "";
        document.getElementById('previewFoto').classList.add('d-none');
        document.getElementById('previewFoto').src = "";
    }

    updateIndikatorSinyal();
    tampilkanAntrean();
</script>

<?= $this->endSection() ?>