

<?php $__env->startSection('styles'); ?>
<link rel="stylesheet" href="<?php echo e(asset('css/form.css')); ?>">
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>

<div class="page-wrapper">
<div class="form-card">

    
    <div class="form-header">
        <h2>🌾 Form Laporan Serangan Hama Padi</h2>
        <p>Silakan isi data laporan dengan lengkap dan benar</p>
    </div>

    
    <?php if($errors->any()): ?>
    <div class="error-box">
        <ul>
            <?php $__currentLoopData = $errors->all(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $error): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <li>• <?php echo e($error); ?></li>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        </ul>
    </div>
    <?php endif; ?>

    <form action="<?php echo e(route('lapor.store')); ?>" method="POST">
    <?php echo csrf_field(); ?>

    
    <div class="form-grid">

        <div class="form-group">
            <label>Nama Petani</label>
            <input type="text" name="nama_petani" placeholder="Masukkan nama petani" required>
        </div>

        <div class="form-group">
            <label>Jenis Hama</label>
            <select name="jenis_hama" required>
                <option value="">-- Pilih Hama --</option>
                <option value="Wereng">Wereng</option>
                <option value="Tikus">Tikus</option>
                <option value="Walang Sangit">Walang Sangit</option>
                <option value="Penggerek Batang">Penggerek Batang</option>
            </select>
        </div>

        <div class="form-group">
            <label>Tingkat Serangan</label>
            <select name="tingkat_serangan" required>
                <option value="">-- Pilih Tingkat --</option>
                <option value="Ringan">Ringan</option>
                <option value="Sedang">Sedang</option>
                <option value="Berat">Berat</option>
            </select>
        </div>

        <div class="form-group">
            <label>Luas Lahan</label>
            <select name="luas_lahan" required>
                <option value="">-- Pilih Luas --</option>
                <option value="luas_kecil">Kurang dari 0,5 ha</option>
                <option value="luas_sedang">0,5 – 1 ha</option>
                <option value="luas_besar">Lebih dari 1 ha</option>
            </select>
        </div>

        <div class="form-group">
            <label>Lama Kejadian</label>
            <select name="lama_kejadian" required>
                <option value="">-- Pilih Lama --</option>
                <option value="cepat">Kurang dari 3 hari</option>
                <option value="menengah">3 – 7 hari</option>
                <option value="lama">Lebih dari 7 hari</option>
            </select>
        </div>

    </div>

    
    <div class="camera-section">
        <label>📷 Ambil Foto &amp; Lokasi Otomatis</label>

        <div class="camera-wrapper">
            <video id="video" autoplay playsinline></video>
            <div class="camera-overlay"></div>
        </div>

        <button type="button" class="btn-primary" onclick="ambilFoto()">
            📸 Ambil Foto Sekarang
        </button>

        <div class="loading" id="loadingText">Mengambil lokasi...</div>

        <canvas id="canvas" hidden></canvas>
        <img id="preview" class="preview-image" alt="Pratinjau foto">

        <input type="hidden" name="foto_base64" id="foto_base64">
    </div>

    
    <div class="form-group">
        <label>Koordinat</label>
        <input type="text" id="koordinat" name="koordinat" placeholder="Diisi otomatis" readonly required>
    </div>

    <div class="form-group">
        <label>Lokasi Otomatis</label>
        <input type="text" id="lokasi" name="lokasi" placeholder="Diisi otomatis" readonly required>
    </div>

    <div class="form-group">
        <label>Kecamatan</label>
        <input type="text" id="kecamatan" name="kecamatan" placeholder="Diisi otomatis" readonly>
    </div>

    <div class="form-group">
        <label>Deskripsi</label>
        <textarea name="deskripsi" rows="4" placeholder="Jelaskan kondisi serangan hama..." required></textarea>
    </div>

    <button type="submit" class="btn-submit">💾 Simpan Laporan</button>

    </form>

</div>
</div>

<?php $__env->stopSection(); ?>

<?php $__env->startSection('scripts'); ?>
<script>
let streamRef = null;

/* ---- START CAMERA ---- */
async function startCamera() {
    try {
        if (!streamRef) {
            streamRef = await navigator.mediaDevices.getUserMedia({
                video: { facingMode: { ideal: "environment" } },
                audio: false
            });
        }
        const video = document.getElementById('video');
        video.srcObject = streamRef;
        video.setAttribute("playsinline", true);
        await video.play();
    } catch (err) {
        console.error(err);
        alert("Kamera gagal dibuka. Pastikan izin kamera diberikan.");
    }
}
startCamera();

/* ---- AMBIL FOTO + GPS + WATERMARK ---- */
async function ambilFoto() {
    const loading = document.getElementById('loadingText');
    loading.classList.add('active');

    try {
        const video   = document.getElementById('video');
        const canvas  = document.getElementById('canvas');
        const preview = document.getElementById('preview');
        const ctx     = canvas.getContext('2d');

        let lat = "-", lng = "-";

        if (navigator.geolocation) {
            const position = await new Promise((resolve, reject) =>
                navigator.geolocation.getCurrentPosition(resolve, reject, {
                    enableHighAccuracy: true,
                    timeout: 10000,
                    maximumAge: 0
                })
            );

            lat = position.coords.latitude.toFixed(6);
            lng = position.coords.longitude.toFixed(6);

            document.getElementById('koordinat').value = lat + "," + lng;

            try {
                const res  = await fetch(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${lat}&lon=${lng}`);
                const data = await res.json();

                if (data?.display_name) document.getElementById('lokasi').value = data.display_name;

                const kecamatan = data?.address?.suburb
                    || data?.address?.city_district
                    || data?.address?.county
                    || "-";
                document.getElementById('kecamatan').value = kecamatan;
            } catch (e) {
                console.warn("Gagal ambil nama lokasi", e);
            }
        }

        /* Canvas */
        canvas.width  = video.videoWidth;
        canvas.height = video.videoHeight;
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

        /* Watermark */
        const namaPetani = document.querySelector('input[name="nama_petani"]').value || '-';
        const now        = new Date();
        const tanggal    = now.toLocaleDateString('id-ID', { day:'2-digit', month:'long', year:'numeric' });
        const jam        = now.toLocaleTimeString('id-ID', { hour:'2-digit', minute:'2-digit', second:'2-digit' });
        const boxH       = 110;

        ctx.fillStyle = "rgba(0,0,0,0.45)";
        ctx.fillRect(0, canvas.height - boxH, canvas.width, boxH);

        ctx.fillStyle = "#ffffff";
        ctx.font      = "18px Arial";
        ctx.fillText("🌾 SPK Hama - Kab. Gowa",            20, canvas.height - 75);
        ctx.fillText("Petani    : " + namaPetani,           20, canvas.height - 50);
        ctx.fillText("Koordinat : " + lat + ", " + lng,    20, canvas.height - 25);
        ctx.fillText("Waktu     : " + tanggal + " | " + jam, 20, canvas.height - 5);

        /* Save */
        const dataURL = canvas.toDataURL('image/jpeg', 0.9);
        document.getElementById('foto_base64').value = dataURL;
        preview.src           = dataURL;
        preview.style.display = "block";

        if (video.paused) await video.play();

    } catch (err) {
        console.error(err);
        alert("Gagal mengambil foto / lokasi. Pastikan izin kamera & GPS aktif.");
    } finally {
        loading.classList.remove('active');
    }
}

/* ---- FIX BLACKSCREEN MOBILE ---- */
document.addEventListener("visibilitychange", async () => {
    if (document.visibilityState === "visible") {
        const video = document.getElementById('video');
        if (video.paused) {
            try { await video.play(); } catch(e) { console.warn(e); }
        }
    }
});
</script>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\Users\Maylha\pelaporanpertanian\resources\views/lapor/create.blade.php ENDPATH**/ ?>