<?php
include 'db.php';
include 'config.php';

$locations = [];

if (isset($_GET['tracking_id'])) {
    $track_num = $_GET['tracking_id'];
    $sql = mysqli_query($link, "SELECT * FROM tracking WHERE tracking_number = '$track_num'");

    if (mysqli_num_rows($sql) > 0) {
        $row = mysqli_fetch_assoc($sql);
        $dispatchl = $row['dispatch_location'];

        $sqlx = mysqli_query($link, "SELECT current_location FROM track_update WHERE track_num = '$track_num' ORDER BY id ASC");

        if (mysqli_num_rows($sqlx) > 0) {
            while ($rowx = mysqli_fetch_assoc($sqlx)) {
                $locations[] = $rowx['current_location'];
            }
        } else {
            $locations[] = $dispatchl;
        }
    }
}


?>

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css" />
  <style>
    #map {
      height: 600px;
      width: 100%;
    }
  </style>
</head>
<body>
  <div id="map"></div>

  <!-- Leaflet.js -->
  <script src="https://unpkg.com/leaflet@1.9.3/dist/leaflet.js"></script>
  <!-- Leaflet Polyline Decorator (for arrowheads) -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet-polylinedecorator/1.7.0/leaflet.polylineDecorator.min.js"></script>

  <script>
    const map = L.map('map').setView([0, 0], 5);

    // Add tile layer
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      maxZoom: 19
    }).addTo(map);

    // Package locations (addresses)
    const addressList = <?php echo json_encode($locations); ?>;

    let previousCoords = null;
    let index = 0;
    
    // draw route with arrow pattern similar to Google Maps
function drawArrowRoute(from, to) {
  const latlngs = [from, to];

  const polyline = L.polyline(latlngs, {
    color: "#1a73e8",   // Google blue
    weight: 5,
    opacity: 0.8,
    smoothFactor: 1
  }).addTo(map);

  // arrow pattern along the line (not just end)
  L.polylineDecorator(polyline, {
    patterns: [
      {
        offset: 12,
        repeat: 50, // distance between arrows
        symbol: L.Symbol.arrowHead({
          pixelSize: 10,
          polygon: false,
          pathOptions: { stroke: true, color: "#1a73e8" }
        })
      }
    ]
  }).addTo(map);
}


    function geocodeAndUpdate(address) {
      fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(address)}`)
        .then(response => response.json())
        .then(data => {
          if (data.length === 0) {
            console.warn(`Address not found: ${address}`);
            return;
          }

          const lat = parseFloat(data[0].lat);
          const lon = parseFloat(data[0].lon);
          const currentCoords = [lat, lon];

          // Add marker
          const marker = L.marker(currentCoords).addTo(map)
            .bindPopup(`Package reached: ${address}`).openPopup();

          // Draw arrow from previous to current
          if (previousCoords) {
              drawArrowRoute(previousCoords, currentCoords);
            // const polyline = L.polyline([previousCoords, currentCoords], { color: 'blue' }).addTo(map);
            // L.polylineDecorator(polyline, {
            //   patterns: [
            //     { offset: '100%', repeat: 0, symbol: L.Symbol.arrowHead({ pixelSize: 10, pathOptions: { color: 'blue' } }) }
            //   ]
            // }).addTo(map);
          }

          previousCoords = currentCoords;
          map.setView(currentCoords, 3);
        });
    }

    // Simulate step-by-step updates
    function simulateUpdates() {
      if (index < addressList.length) {
        geocodeAndUpdate(addressList[index]);
        index++;
        setTimeout(simulateUpdates, 5000); // 5-second delay per update
      }
    }

    simulateUpdates();
  </script>
  
  <script>
  // Disable right-click
  document.addEventListener("contextmenu", function(e) {
    e.preventDefault();
  });

  // Disable specific keyboard shortcuts
  document.addEventListener("keydown", function(e) {
    // F12
    if (e.key === "F12") {
      e.preventDefault();
    }

    // Ctrl+Shift+I / Ctrl+Shift+J / Ctrl+U
    if (
      (e.ctrlKey && e.shiftKey && (e.key === "I" || e.key === "i" || e.key === "J" || e.key === "j")) ||
      (e.ctrlKey && (e.key === "U" || e.key === "u"))
    ) {
      e.preventDefault();
    }
  });
</script>
</body>
</html>
