<?php 
// ================= VALIDASI INPUT =================
$error = [];
$latitude = $longitude = $nama_lokasi = null;

// Validasi latitude
if (!isset($_GET['latitude']) || !is_numeric($_GET['latitude'])) {
  $error[] = 'Latitude tidak valid.';
} else {
  $latitude = (float) $_GET['latitude'];
}

// Validasi longitude
if (!isset($_GET['longitude']) || !is_numeric($_GET['longitude'])) {
  $error[] = 'Longitude tidak valid.';
} else {
  $longitude = (float) $_GET['longitude'];
}

// Validasi nama lokasi / jamaah
if (empty($_GET['nama'])) {
  $error[] = 'Nama lokasi ibadah tidak boleh kosong.';
} else {
  $nama_lokasi = htmlspecialchars(trim($_GET['nama']), ENT_QUOTES, 'UTF-8');
}
?>

<?php if (empty($error)) : ?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Peta Lokasi Ibadah</title>

  <!-- Leaflet -->
  <link rel="stylesheet" href="../../assets/plugins/leaflet/leaflet.css">
  <script src="../../assets/plugins/leaflet/leaflet.js"></script>

  <style>
    html, body {
      height: 100%;
      margin: 0;
      font-family: "Segoe UI", Tahoma, sans-serif;
      background-color: #f4f4f4;
    }
    #peta {
      height: 100vh;
      width: 100%;
    }
    .leaflet-popup-content {
      font-size: 14px;
    }
    .info-box {
      position: absolute;
      top: 10px;
      left: 10px;
      z-index: 1000;
      background: rgba(255, 255, 255, 0.9);
      padding: 10px 15px;
      border-radius: 8px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.2);
    }
  </style>
</head>
<body>
  <div class="info-box">
    <strong>📍 Lokasi Ibadah:</strong><br>
    <?php echo $nama_lokasi; ?><br>
    <small>Lat: <?php echo $latitude; ?>, Lng: <?php echo $longitude; ?></small>
  </div>

  <div id="peta"></div>

  <script type="text/javascript">
    // Inisialisasi peta
    var map = L.map('peta').setView([<?= $latitude ?>, <?= $longitude ?>], 15);

    // Layer dasar (OpenStreetMap)
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      maxZoom: 19,
      attribution: '© OpenStreetMap contributors'
    }).addTo(map);

    // Tambahkan marker lokasi ibadah
    var marker = L.marker([<?= $latitude ?>, <?= $longitude ?>]).addTo(map);
    marker.bindPopup("<b>Lokasi Ibadah:</b><br><?= $nama_lokasi ?><br><small>(<?= $latitude ?>, <?= $longitude ?>)</small>").openPopup();

    // Tambahkan lingkaran radius 300m
    L.circle([<?= $latitude ?>, <?= $longitude ?>], {
      radius: 300,
      color: 'blue',
      fillColor: '#3f8efc',
      fillOpacity: 0.3
    }).addTo(map);

    // Klik peta → tampilkan koordinat
    var popup = L.popup();
    function onMapClick(e) {
      popup
        .setLatLng(e.latlng)
        .setContent("Koordinat: " + e.latlng.lat.toFixed(5) + ", " + e.latlng.lng.toFixed(5))
        .openOn(map);
    }
    map.on('click', onMapClick);

    // Tombol lokasi saya
    if ("geolocation" in navigator) {
      var locateBtn = L.control({ position: 'topleft' });
      locateBtn.onAdd = function (map) {
        var btn = L.DomUtil.create('button', 'leaflet-bar leaflet-control leaflet-control-custom');
        btn.innerHTML = '📍';
        btn.style.background = '#fff';
        btn.style.border = 'none';
        btn.style.cursor = 'pointer';
        btn.title = 'Tampilkan Lokasi Saya';
        btn.onclick = function () {
          navigator.geolocation.getCurrentPosition(function (pos) {
            var lat = pos.coords.latitude;
            var lng = pos.coords.longitude;
            L.marker([lat, lng], { title: 'Lokasi Anda' })
              .addTo(map)
              .bindPopup("<b>Lokasi Anda</b><br>(" + lat.toFixed(5) + ", " + lng.toFixed(5) + ")")
              .openPopup();
            map.setView([lat, lng], 15);
          });
        };
        return btn;
      };
      locateBtn.addTo(map);
    }
  </script>
</body>
</html>

<?php else: ?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Data Tidak Valid</title>
  <style>
    body {
      background: #f7f7f7;
      font-family: "Segoe UI", sans-serif;
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100vh;
      color: #333;
    }
    .error-box {
      background: white;
      border-radius: 8px;
      padding: 25px 30px;
      box-shadow: 0 2px 8px rgba(0,0,0,0.1);
      text-align: center;
    }
    ul { text-align: left; display: inline-block; margin: 10px 0; }
  </style>
</head>
<body>
  <div class="error-box">
    <h2>⚠️ Data Lokasi Ibadah Tidak Valid</h2>
    <p>Kesalahan ditemukan:</p>
    <ul>
      <?php foreach ($error as $err): ?>
        <li><?= htmlspecialchars($err) ?></li>
      <?php endforeach; ?>
    </ul>
    <a href="javascript:history.back()" style="color:#007bff;text-decoration:none;">← Kembali</a>
  </div>
</body>
</html>
<?php endif; ?>
