<?php
// public/live_map.php
require_once __DIR__ . '/../helpers/auth.php';
require_role(['admin','staff']);

$pdo = db();
$title = "Live Map - IMS";

// Load recent deliveries (for dropdown)
$stmt = $pdo->prepare("
  SELECT id, delivery_code, status
  FROM deliveries
  ORDER BY created_at DESC
  LIMIT 100
");
$stmt->execute();
$deliveries = $stmt->fetchAll(PDO::FETCH_ASSOC);

require_once __DIR__ . '/../templates/header.php';
require_once __DIR__ . '/../templates/sidebar.php';
?>

<main class="col-12 col-md-9 col-lg-10 p-3 p-md-4">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <h4 class="mb-0">Live Map Viewer</h4>
    <div class="text-muted small">Admin/Staff</div>
  </div>

  <div class="card shadow-sm mb-3">
    <div class="card-body">
      <label class="form-label">Select Delivery</label>
      <select id="delivery_id" class="form-select">
        <option value="0">-- Select delivery --</option>
        <?php foreach ($deliveries as $d): ?>
          <option value="<?= (int)$d['id'] ?>">
            <?= htmlspecialchars($d['delivery_code']) ?> (<?= htmlspecialchars($d['status']) ?>)
          </option>
        <?php endforeach; ?>
      </select>

      <div class="mt-2 small text-muted">
        Auto refresh every 5 seconds. Latest GPS comes from <code>api/location_latest.php</code>.
      </div>

      <hr class="my-3">

      <div class="row g-3">
        <div class="col-12 col-lg-7">
          <div id="map" style="height:420px;" class="border rounded"></div>
        </div>

        <div class="col-12 col-lg-5">
          <div class="border rounded p-3 bg-light">
            <div class="fw-semibold mb-2">Info</div>

            <div class="small text-muted">Delivery Code</div>
            <div id="infoCode" class="mb-2">-</div>

            <div class="small text-muted">Status</div>
            <div id="infoStatus" class="mb-2">-</div>

            <div class="small text-muted">Last GPS</div>
            <div id="infoGps" class="mb-2">-</div>

            <div class="small text-muted">Coordinates</div>
            <div id="infoCoords" class="mb-2">-</div>

            <div class="small text-muted">Accuracy</div>
            <div id="infoAcc" class="mb-2">-</div>

            <div class="small text-muted">Speed / Heading</div>
            <div id="infoSpeed" class="mb-0">-</div>
          </div>
        </div>
      </div>

    </div>
  </div>
</main>

<!-- Leaflet -->
<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>
const deliverySelect = document.getElementById('delivery_id');

const infoCode = document.getElementById('infoCode');
const infoStatus = document.getElementById('infoStatus');
const infoGps = document.getElementById('infoGps');
const infoCoords = document.getElementById('infoCoords');
const infoAcc = document.getElementById('infoAcc');
const infoSpeed = document.getElementById('infoSpeed');

let map = L.map('map').setView([13.941, 121.615], 12);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  maxZoom: 19,
  attribution: '&copy; OpenStreetMap'
}).addTo(map);

let markerDriver = null;
let markerPickup = null;
let markerDropoff = null;

let refreshTimer = null;

function setText(el, txt){ el.textContent = txt; }

function ensureMarker(existing, lat, lng, label, color) {
  if (lat === null || lng === null) return null;

  const m = existing ? existing : L.marker([lat, lng]).addTo(map);
  m.setLatLng([lat, lng]);
  m.bindPopup(label);
  return m;
}

async function refresh() {
  const id = Number(deliverySelect.value || 0);
  if (!id) return;

  try {
    const res = await fetch(`../api/location_latest.php?delivery_id=${id}`);
    const data = await res.json();

    if (!data.ok) {
      setText(infoCode, '-');
      setText(infoStatus, 'Error: ' + (data.error || 'Unknown'));
      setText(infoGps, '-');
      setText(infoCoords, '-');
      setText(infoAcc, '-');
      setText(infoSpeed, '-');
      return;
    }

    // delivery info
    setText(infoCode, data.delivery.delivery_code || '-');
    setText(infoStatus, data.delivery.status || '-');

    // pickup / dropoff markers (if coords exist)
    markerPickup = ensureMarker(markerPickup,
      data.delivery.pickup_lat, data.delivery.pickup_lng,
      'Pickup', 'blue'
    );
    markerDropoff = ensureMarker(markerDropoff,
      data.delivery.dropoff_lat, data.delivery.dropoff_lng,
      'Dropoff', 'red'
    );

    // latest driver loc
    if (data.latest) {
      setText(infoGps, data.latest.recorded_at || '-');
      setText(infoCoords, `${data.latest.lat.toFixed(6)}, ${data.latest.lng.toFixed(6)}`);
      setText(infoAcc, data.latest.accuracy_m ? `±${Math.round(data.latest.accuracy_m)}m` : '-');

      const sp = data.latest.speed_mps ? `${data.latest.speed_mps.toFixed(1)} m/s` : '-';
      const hd = (data.latest.heading_deg !== null && data.latest.heading_deg !== undefined) ? `${Math.round(data.latest.heading_deg)}°` : '-';
      setText(infoSpeed, `${sp} / ${hd}`);

      if (!markerDriver) {
        markerDriver = L.marker([data.latest.lat, data.latest.lng]).addTo(map);
        markerDriver.bindPopup('Driver (latest)');
      } else {
        markerDriver.setLatLng([data.latest.lat, data.latest.lng]);
      }

      // Fit map bounds if first time
      const pts = [];
      if (markerPickup) pts.push(markerPickup.getLatLng());
      if (markerDropoff) pts.push(markerDropoff.getLatLng());
      if (markerDriver) pts.push(markerDriver.getLatLng());

      if (pts.length > 0) {
        const bounds = L.latLngBounds(pts);
        map.fitBounds(bounds.pad(0.25));
      }

    } else {
      setText(infoGps, 'No GPS saved yet');
      setText(infoCoords, '-');
      setText(infoAcc, '-');
      setText(infoSpeed, '-');
    }

  } catch (e) {
    setText(infoStatus, 'Network error: ' + e.message);
  }
}

deliverySelect.addEventListener('change', () => {
  if (refreshTimer) clearInterval(refreshTimer);
  refreshTimer = null;

  // reset UI
  setText(infoCode, '-');
  setText(infoStatus, '-');
  setText(infoGps, '-');
  setText(infoCoords, '-');
  setText(infoAcc, '-');
  setText(infoSpeed, '-');

  // remove markers
  if (markerDriver) { map.removeLayer(markerDriver); markerDriver = null; }
  if (markerPickup) { map.removeLayer(markerPickup); markerPickup = null; }
  if (markerDropoff) { map.removeLayer(markerDropoff); markerDropoff = null; }

  if (Number(deliverySelect.value || 0)) {
    refresh();
    refreshTimer = setInterval(refresh, 5000);
  }
});
</script>

<?php require_once __DIR__ . '/../templates/footer.php'; ?>
