<?php session_start(); if(!isset($_SESSION['user_id'])) die('Akses ditolak');?>
<h1 class="h3 mb-4 text-gray-800">Peta Lokasi Gereja DPW Keerom</h1>
<div class="alert alert-info" id="infoPeta">Memuat data peta...</div>
<div class="card shadow mb-4">
    <div class="card-body"><div id="mapGereja" style="height:600px; z-index:1;"></div></div>
</div>

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"/>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script>
let map = L.map('mapGereja').setView([-3.165, 140.715], 9);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; OpenStreetMap',
    maxZoom: 19
}).addTo(map);

$.get('api/get_all_gereja.php', function(res){
    let totalPin = 0;
    
    res.data.forEach(d => {
        let lat = parseFloat(d.latitude);
        let lng = parseFloat(d.longitude);
        
        // VALIDASI LENGKAP: Skip kalo kosong, 0, atau bukan angka
        if(!isNaN(lat) && !isNaN(lng) && lat != 0 && lng != 0 && d.latitude != '' && d.longitude != ''){
            totalPin++;
            L.marker([lat, lng]).addTo(map)
            .bindPopup(`
                <b>${d.nama_gereja}</b><br>
                <i class="fa fa-map-marker"></i> ${d.alamat}<br>
                <i class="fa fa-location-arrow"></i> Distrik: ${d.distrik}<br>
                <i class="fa fa-user"></i> Gembala: ${d.nama_gembala || '-'}<br>
                <hr style="margin:8px 0">
                <a href="https://www.google.com/maps?q=${lat},${lng}" target="_blank" class="btn btn-sm btn-danger btn-block">
                    <i class="fa fa-google"></i> Buka di Google Maps
                </a>
            `);
        }
    });
    
    // INFO JUMLAH PIN
    if(totalPin == 0){
        $('#infoPeta').removeClass('alert-info').addClass('alert-warning')
        .html('Belum ada gereja yang punya koordinat. Silakan input di menu Data Gereja.');
    } else {
        $('#infoPeta').html(`Menampilkan ${totalPin} lokasi gereja di peta.`);
    }
});
</script>