<?php
$safeTicket = htmlspecialchars((string)($incident['ticket_id'] ?? ('INC-' . (int)($incident['id'] ?? 0))));
$title = 'Carte des photos — ' . $safeTicket;
?>
<!doctype html>
<html lang="fr">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title><?= htmlspecialchars($title) ?></title>
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin=""/>
  <style>
    html, body { height:100%; margin:0; }
    #map { height: 100vh; }
    .leaflet-popup-content img { max-width: 280px; height:auto; display:block; margin-bottom: .5rem; border:1px solid #dee2e6; }
  </style>
</head>
<body>
<div id="map"></div>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
<script>
  const photos = <?= json_encode(array_map(function($p){
    return [
      'lat' => isset($p['lat']) ? (float)$p['lat'] : null,
      'lng' => isset($p['lng']) ? (float)$p['lng'] : null,
      'observation' => (string)($p['observation'] ?? ''),
      'taken_by' => (string)($p['taken_by'] ?? ''),
      'uploaded_at' => (string)($p['uploaded_at'] ?? ''),
      'taken_at' => (string)($p['taken_at'] ?? ''),
      'url' => upload_url($p['path'])
    ];
  }, $photos ?? []), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
  const map = L.map('map');
  const osm = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 19,
    attribution: '&copy; OpenStreetMap'
  }).addTo(map);
  const group = L.featureGroup();
  photos.forEach(p => {
    if (p.lat === null || p.lng === null) return;
    const popup = `
      <div>
        <img src="${p.url}" alt="Photo"/>
        ${p.observation ? ('<div><strong>Observation:</strong> '+p.observation.replace(/</g,'&lt;').replace(/>/g,'&gt;')+'</div>') : ''}
        <div>${p.taken_by ? ('<strong>Technicien:</strong> '+p.taken_by+' — ') : ''}GPS: ${p.lat}, ${p.lng}</div>
        <div>${p.taken_at ? ('Pris le: '+p.taken_at) : (p.uploaded_at ? ('Ajouté le: '+p.uploaded_at) : '')}</div>
      </div>`;
    const m = L.marker([p.lat, p.lng]).bindPopup(popup);
    m.addTo(group);
  });
  group.addTo(map);
  try {
    map.fitBounds(group.getBounds(), { padding:[30,30] });
  } catch(e) {
    map.setView([5.3600, -4.0083], 11); // fallback: Abidjan
  }
</script>
</body>
</html>
