<?php
require_once '../includes/config.php';

// Fetch existing GPS points
$points = $pdo->query("SELECT title, latitude, longitude, created_at FROM gps_locations ORDER BY created_at DESC")->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
  <title>Click to Add Marker + Table</title>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <style>
    #map { height: 60vh; width: 100%; margin-bottom: 20px; }
    .container { padding: 20px; }
    table { width: 100%; border-collapse: collapse; }
    th, td { padding: 8px; border: 1px solid #ccc; text-align: center; }
    th { background-color: #f8f8f8; }
  </style>
</head>
<body>
<div class="container">
  <h4>🗺️ Click on the map to add a location (stored to MySQL)</h4>
  <div id="map"></div>

  <h5>📋 Saved GPS Locations</h5>
  <table>
    <thead>
      <tr><th>#</th><th>Title</th><th>Latitude</th><th>Longitude</th><th>Timestamp</th></tr>
    </thead>
    <tbody>
      <?php foreach ($points as $index => $row): ?>
        <tr>
          <td><?= $index + 1 ?></td>
          <td><?= htmlspecialchars($row['title']) ?></td>
          <td><?= $row['latitude'] ?></td>
          <td><?= $row['longitude'] ?></td>
          <td><?= $row['created_at'] ?></td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>

<script>
  let map;
  function initMap() {
    const sg = { lat: 1.3521, lng: 103.8198 };
    map = new google.maps.Map(document.getElementById("map"), {
      center: sg,
      zoom: 12,
    });

    const points = <?php echo json_encode($points); ?>;
    points.forEach(p => {
      new google.maps.Marker({
        position: { lat: parseFloat(p.latitude), lng: parseFloat(p.longitude) },
        map,
        title: p.title
      });
    });

    map.addListener("click", function(event) {
      const lat = event.latLng.lat();
      const lng = event.latLng.lng();
      const title = prompt("Enter title for this location:");
      if (title) {
        new google.maps.Marker({
          position: { lat, lng },
          map,
          title: title
        });

        fetch("save_gps_point.php", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ title: title, latitude: lat, longitude: lng })
        })
        .then(res => res.json())
        .then(data => {
          if (data.success) {
            alert("✅ Saved. Reloading...");
            location.reload();
          } else {
            alert("❌ Error: " + data.error);
          }
        })
        .catch(err => alert("Network error: " + err));
      }
    });
  }
</script>

<!-- Replace with your valid Google Maps API key -->
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async defer></script>
</body>
</html>
