<?php use App\Core\Config; $title = $pageTitle ?? 'Vue live intervention'; $pos = $position ?? null; $uid = (int)($target_user_id ?? 0); $incId = (int)($incident_id ?? 0); $incPos = $incident_pos ?? null; $incPosAt = $incident_pos_at ?? null; ?>
<?php $incTitle = $incident_title ?? null; $incStatusKey = $incident_status_key ?? null; $incStatusColor = $incident_status_color ?? null; $interventionPhotos = $intervention_photos ?? []; ?>
<div class="card shadow-sm">
  <div class="card-header d-flex align-items-center justify-content-between">
    <h5 class="mb-0"><i class="fas fa-location-crosshairs me-2"></i>Position en direct</h5>
    <div class="small text-muted">
      <?php if (!empty($takeover_at)): ?>
        <span class="badge text-bg-warning" title="Prise en charge le <?= htmlspecialchars(date('d/m/Y H:i', strtotime($takeover_at))) ?>"><i class="fas fa-clock me-1"></i><?= htmlspecialchars(date('H:i', strtotime($takeover_at))) ?></span>
      <?php else: ?>
        <span class="text-muted">Prise en charge non enregistrée</span>
      <?php endif; ?>
    </div>
  </div>
  <div class="card-body p-0">
    <div id="map" style="height: 70vh; width: 100%; position: relative;"></div>
    <div id="liveStatus" class="position-absolute top-0 end-0 m-2">
      <?php if (!$pos && $incPos): ?>
        <div class="alert alert-info py-1 px-2 mb-0 shadow-sm" role="alert">
          <i class="fas fa-map-location-dot me-1"></i>Position incident chargée (en attente position technicien)
        </div>
      <?php elseif (!$pos && !$incPos): ?>
        <div class="alert alert-warning py-1 px-2 mb-0 shadow-sm" role="alert">
          <i class="fas fa-info-circle me-1"></i>Aucune position disponible pour le moment
        </div>
      <?php endif; ?>
    </div>
    
    <!-- Boutons d'action en bas à droite -->
    <div class="position-absolute" style="right: .75rem; bottom: .75rem; z-index: 1000; display:flex; flex-direction:column; gap:.5rem; align-items:flex-end;">
      <div class="btn-group dropup">
        <button id="btnNavigate" type="button" class="btn btn-success btn-sm"><i class="fas fa-route"></i> Itinéraire</button>
        <button type="button" class="btn btn-success btn-sm dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown" aria-expanded="false"><span class="visually-hidden">Options</span></button>
        <ul class="dropdown-menu dropdown-menu-end">
          <li><a class="dropdown-item js-nav-provider" href="#" data-provider="auto">Par défaut</a></li>
          <li><a class="dropdown-item js-nav-provider" href="#" data-provider="google">Google Maps</a></li>
          <li><a class="dropdown-item js-nav-provider" href="#" data-provider="osm">OpenStreetMap</a></li>
          <li><a class="dropdown-item js-nav-provider" href="#" data-provider="waze">Waze</a></li>
          <li><a class="dropdown-item js-nav-provider" href="#" data-provider="apple">Apple Maps (iOS)</a></li>
        </ul>
      </div>
      <button id="btnRecenter" type="button" class="btn btn-primary btn-sm">
        <i class="fas fa-crosshairs"></i> Recentrer
      </button>
    </div>
    <!-- Légende couleurs statut -->
    <div class="map-legend">
      <div class="legend-body">
        <div class="legend-item"><span class="legend-dot open"></span> Ouvert</div>
        <div class="legend-item"><span class="legend-dot in_progress"></span> En cours</div>
        <div class="legend-item"><span class="legend-dot treated"></span> Traité</div>
        <div class="legend-item"><span class="legend-dot resolved"></span> Résolu</div>
        <div class="legend-item"><span class="legend-dot closed"></span> Clôturé</div>
      </div>
    </div>
  </div>
</div>

<?php if (!empty($interventionPhotos)): ?>
<div class="card shadow-sm mt-3">
  <div class="card-header">
    <h5 class="mb-0"><i class="fas fa-images me-2"></i>Photos d'intervention (<?= count($interventionPhotos) ?>)</h5>
  </div>
  <div class="card-body">
    <div class="row g-2">
      <?php foreach ($interventionPhotos as $photo): ?>
      <div class="col-md-3 col-lg-2">
        <div class="card h-100 border-0 shadow-sm">
          <?php $photoUrl = '/Insuite_backbones/public/storage/uploads/' . $photo['path']; ?>
          <img src="<?= htmlspecialchars($photoUrl) ?>" 
               class="card-img-top" 
               style="height: 150px; object-fit: cover; cursor: pointer;"
               onclick="showPhotoModal(<?= htmlspecialchars(json_encode([
                 'src' => $photoUrl,
                 'observation' => $photo['observation'] ?? '',
                 'lat' => $photo['lat'] ?? null,
                 'lng' => $photo['lng'] ?? null,
                 'date' => date('d/m/Y H:i', strtotime($photo['taken_at'] ?? $photo['uploaded_at']))
               ])) ?>)"
               alt="Photo d'intervention">
          <?php if (!empty($photo['observation'])): ?>
          <div class="card-body p-2">
            <p class="card-text small mb-0 text-truncate" title="<?= htmlspecialchars($photo['observation']) ?>">
              <?= htmlspecialchars(mb_substr($photo['observation'], 0, 50)) ?><?= mb_strlen($photo['observation']) > 50 ? '...' : '' ?>
            </p>
          </div>
          <?php endif; ?>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
</div>
<?php endif; ?>

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin=""/>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
<style>
  .pulse-marker {
    position: relative;
    width: 16px; height: 16px; border-radius: 50%;
    background: rgba(220, 53, 69, 0.95); /* bootstrap danger */
    border: 2px solid #fff; box-shadow: 0 0 0 2px rgba(220,53,69,.3);
  }
  .pulse-marker::after { /* vague pulsante */
    content: '';
    position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%);
    width: 16px; height: 16px; border-radius: 50%;
    background: rgba(220,53,69,.25);
    animation: pulse 1.8s ease-out infinite;
  }
  @keyframes pulse {
    0% { transform: translate(-50%,-50%) scale(1); opacity: 0.7; }
    70% { transform: translate(-50%,-50%) scale(3); opacity: 0; }
    100% { opacity: 0; }
  }
  .flash {
    animation: flash 1s ease-out 1;
  }
  @keyframes flash {
    0% { box-shadow: 0 0 0 2px rgba(255,255,255,.9), 0 0 12px 6px rgba(13,110,253,.7); }
    100% { box-shadow: 0 0 0 2px rgba(255,255,255,.9), 0 0 0 0 rgba(13,110,253,0); }
  }
  /* Marqueur de la position locale (navigateur) en bleu */
  .self-marker { position: relative; width: 14px; height: 14px; border-radius: 50%; background: rgba(13,110,253,.95); border: 2px solid #fff; box-shadow: 0 0 0 2px rgba(13,110,253,.3); }
  .self-marker::after { content:''; position:absolute; left:50%; top:50%; transform:translate(-50%,-50%); width:14px; height:14px; border-radius:50%; background: rgba(13,110,253,.2); animation: pulseSelf 2s ease-out infinite; }
  @keyframes pulseSelf { 0%{ transform:translate(-50%,-50%) scale(1); opacity:.6;} 70%{ transform:translate(-50%,-50%) scale(2.8); opacity:0;} 100%{ opacity:0; } }
  /* Marqueur incident dynamique (orange par défaut, vert si clôturé) */
  .incident-marker { position: relative; width: 18px; height: 18px; border-radius: 50%; border: 2px solid #fff; box-shadow: 0 0 0 2px rgba(0,0,0,.15); }
  .incident-marker.status-closed { background: rgba(25,135,84,.95); box-shadow: 0 0 0 2px rgba(25,135,84,.35); }
  .incident-marker.status-open { background: rgba(255,159,64,.95); box-shadow: 0 0 0 2px rgba(255,159,64,.35); }
  .incident-marker.status-treated { background: rgba(13,110,253,.95); box-shadow: 0 0 0 2px rgba(13,110,253,.35); }
  .incident-marker.status-in_progress { background: rgba(255,193,7,.95); box-shadow: 0 0 0 2px rgba(255,193,7,.35); }
  .incident-marker.status-resolved { background: rgba(102,16,242,.95); box-shadow: 0 0 0 2px rgba(102,16,242,.35); }
  .incident-marker::after { content:''; position:absolute; left:50%; top:50%; transform:translate(-50%,-50%); width:18px; height:18px; border-radius:50%; background: rgba(0,0,0,.15); animation: pulseIncident 2s ease-out infinite; }
  @keyframes pulseIncident { 0%{ transform:translate(-50%,-50%) scale(1); opacity:.6;} 70%{ transform:translate(-50%,-50%) scale(2.6); opacity:0;} 100%{ opacity:0; } }
  /* Légende statut */
  .map-legend { position:absolute; left:.75rem; bottom:.75rem; z-index:1000; background: rgba(255,255,255,.92); border:1px solid rgba(0,0,0,.1); border-radius:.5rem; box-shadow:0 2px 6px rgba(0,0,0,.1); }
  .map-legend .legend-body { padding:.5rem .6rem; }
  .legend-item { display:flex; align-items:center; gap:.4rem; margin:.2rem 0; font-size:.75rem; line-height:1.1; }
  .legend-dot { width:12px; height:12px; border-radius:50%; border:2px solid #fff; box-shadow:0 0 0 2px rgba(0,0,0,.1); }
  .legend-dot.open { background: rgba(255,159,64,.95); box-shadow:0 0 0 2px rgba(255,159,64,.35); }
  .legend-dot.in_progress { background: rgba(255,193,7,.95); box-shadow:0 0 0 2px rgba(255,193,7,.35); }
  .legend-dot.treated { background: rgba(13,110,253,.95); box-shadow:0 0 0 2px rgba(13,110,253,.35); }
  .legend-dot.resolved { background: rgba(102,16,242,.95); box-shadow:0 0 0 2px rgba(102,16,242,.35); }
  .legend-dot.closed { background: rgba(25,135,84,.95); box-shadow:0 0 0 2px rgba(25,135,84,.35); }
</style>

<script>
  (function(){
    const uid = <?= json_encode($uid) ?>;
    const initial = <?= json_encode($pos ? ['lat'=>(float)$pos['lat'],'lng'=>(float)$pos['lng'],'taken_at'=>$pos['taken_at']] : null) ?>;
    const incidentId = <?= json_encode($incId) ?>;
    const incidentTitle = <?= json_encode($incTitle) ?>;
  const incidentPos = <?= json_encode($incPos ? ['lat'=>(float)$incPos['lat'],'lng'=>(float)$incPos['lng']] : null) ?>;
  const incidentPosAt = <?= json_encode($incPosAt) ?>;
  const incidentStatusKey = <?= json_encode($incStatusKey) ?>;
  const incidentStatusColor = <?= json_encode($incStatusColor) ?>;

    // Initialisation carte
    const map = L.map('map');
    const tiles = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      maxZoom: 19,
      attribution: '&copy; OpenStreetMap'
    }).addTo(map);

  let marker = null; let lastTs = initial ? initial.taken_at : null;
  let markerLL = null; // dernier lat/lng technicien
  let selfMarker = null; // position du navigateur
  let selfLL = null; let selfAcc = null;
  let incidentMarker = null;
  let techTimeBadge = null; // layer séparé pour afficher l'heure / ancienneté
  let incidentTimeBadge = null;

    function setViewTo(lat, lng, z=15) {
      const target = L.latLng(lat, lng);
      if (!map._loaded) { map.setView(target, z); } else { map.panTo(target, { animate: true, duration: 0.7 }); }
    }

    function makePulseMarker(lat, lng) {
      const el = document.createElement('div'); el.className = 'pulse-marker';
      const icon = L.divIcon({ className: '', html: el, iconSize: [16,16], iconAnchor: [8,8] });
      return L.marker([lat, lng], { icon });
    }

    function flashMarker() {
      try { const el = marker.getElement(); if (el) { el.classList.add('flash'); setTimeout(()=>el.classList.remove('flash'), 1000); } } catch(e){}
    }

    function updateMarker(lat, lng) {
      if (!marker) {
        marker = makePulseMarker(lat, lng).addTo(map);
        marker.bindTooltip('Technicien', {permanent:false});
        setViewTo(lat, lng);
      } else {
        marker.setLatLng([lat, lng]);
      }
      markerLL = {lat, lng};
      flashMarker();
      // Nettoyer éventuel bandeau d'attente dès qu'on a une position technicien
      try { const st = document.getElementById('liveStatus'); if (st) st.innerHTML = ''; } catch(e){}
      renderTechTimeBadge();
    }

    // Afficher l'incident si fourni
    if (incidentPos) {
      const elI = document.createElement('div'); 
      let cls = 'incident-marker';
      if (incidentStatusKey) { cls += ' status-'+incidentStatusKey; }
      elI.className = cls;
      // Si statut clôturé, surcharger couleur dynamique si fournie
      if (incidentStatusKey === 'closed' && incidentStatusColor) {
        elI.style.background = incidentStatusColor;
        elI.style.boxShadow = '0 0 0 2px '+incidentStatusColor+'55';
      }
      const iconI = L.divIcon({ className:'', html: elI, iconSize:[18,18], iconAnchor:[9,9] });
      incidentMarker = L.marker([incidentPos.lat, incidentPos.lng], { icon: iconI }).addTo(map);
  const label = (incidentTitle && incidentTitle.trim() !== '') ? incidentTitle : ('Incident #'+incidentId);
  const tip = label + ' — GPS rapport' + (incidentPosAt ? (' ('+new Date(incidentPosAt.replace(' ','T')).toLocaleString('fr-FR')+')') : '');
      incidentMarker.bindTooltip(tip, {permanent:false});
      renderIncidentTimeBadge();
    }

    // Ordre de centrage: incident > technicien > fallback
    if (incidentPos) {
      setViewTo(incidentPos.lat, incidentPos.lng, 14);
    } else if (initial) {
      updateMarker(initial.lat, initial.lng);
    } else {
      map.setView([5.345317, -4.024429], 11); // fallback: Abidjan centre
    }

    // Tenter d'obtenir la position locale du navigateur pour centrer provisoirement
    (function tryLocalGeo(){
      if (!('geolocation' in navigator)) return;
      navigator.geolocation.getCurrentPosition(function(p){
        const lat = p.coords.latitude, lng = p.coords.longitude;
        selfLL = {lat, lng}; selfAcc = (typeof p.coords.accuracy === 'number') ? Math.round(p.coords.accuracy) : null;
        if (!selfMarker) {
          const el = document.createElement('div'); el.className = 'self-marker';
          const icon = L.divIcon({ className:'', html: el, iconSize:[14,14], iconAnchor:[7,7] });
          const label = 'Vous' + (selfAcc ? (' (±'+selfAcc+' m)') : '');
          selfMarker = L.marker([lat, lng], { icon }).addTo(map).bindTooltip(label, {permanent:false});
        } else { selfMarker.setLatLng([lat,lng]); if (selfMarker.getTooltip()) { selfMarker.setTooltipContent('Vous' + (selfAcc ? (' (±'+selfAcc+' m)') : '')); } }
        if (!initial) { setViewTo(lat, lng); }
      }, function(){ /* ignore */ }, { enableHighAccuracy: false, timeout: 3000, maximumAge: 60000 });
    })();

    // Polling
    async function poll() {
      try {
        const url = <?= json_encode(htmlspecialchars(route_url('/interventions/location'))) ?> + '?user_id=' + encodeURIComponent(uid);
        const res = await fetch(url, { headers: { 'Accept': 'application/json' } });
        const data = await res.json();
        if (data.status === 'ok') {
          if (!lastTs || lastTs !== data.taken_at) {
            lastTs = data.taken_at;
            updateMarker(data.lat, data.lng);
          }
          // Effacer éventuel bandeau d'attente
          const ls = document.getElementById('liveStatus');
          if (ls) { ls.innerHTML = ''; }
        }
      } catch(e) { /* silent */ }
    }
  // Démarrer immédiatement un premier poll pour rafraîchir l'état, puis à intervalle régulier
  poll();
  setInterval(poll, 15000);

    // Bouton recentrer
    document.getElementById('btnRecenter').addEventListener('click', function(){
      if (incidentMarker) {
        const ll = incidentMarker.getLatLng(); setViewTo(ll.lat, ll.lng);
      } else if (marker) {
        const ll = marker.getLatLng(); setViewTo(ll.lat, ll.lng); flashMarker();
      } else if (selfMarker) {
        const ll = selfMarker.getLatLng(); setViewTo(ll.lat, ll.lng);
      }
    });

    // Panneau latéral retiré
  renderTechTimeBadge();
  renderIncidentTimeBadge();

    // Démarrer un itinéraire vers l'incident
    function isIOS(){ return /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream; }
    function openDirections(provider='auto'){
      if (!incidentPos) { alert('Coordonnées de l\'incident inconnues.'); return; }
      const dlat = incidentPos.lat, dlng = incidentPos.lng;
      const origin = markerLL || selfLL || null;
      const od = origin ? (origin.lat.toFixed(6)+','+origin.lng.toFixed(6)) : null;
      const dd = dlat.toFixed(6)+','+dlng.toFixed(6);
      if (provider === 'auto') { provider = isIOS() ? 'apple' : 'google'; }
      let url = '';
      switch(provider){
        case 'google':
          url = 'https://www.google.com/maps/dir/?api=1&destination='+encodeURIComponent(dd)+(od?('&origin='+encodeURIComponent(od)):'')+'&travelmode=driving';
          break;
        case 'apple':
          url = 'http://maps.apple.com/?daddr='+encodeURIComponent(dd)+(od?('&saddr='+encodeURIComponent(od)):'')+'&dirflg=d';
          break;
        case 'waze':
          url = 'https://www.waze.com/ul?ll='+encodeURIComponent(dd)+'&navigate=yes';
          break;
        case 'osm':
          if (od) {
            url = 'https://www.openstreetmap.org/directions?engine=fossgis_osrm_car&route='+encodeURIComponent(od)+';'+encodeURIComponent(dd);
          } else {
            url = 'https://www.openstreetmap.org/?mlat='+encodeURIComponent(dlat.toFixed(6))+'&mlon='+encodeURIComponent(dlng.toFixed(6))+'#map=16/'+encodeURIComponent(dlat.toFixed(6))+'/'+encodeURIComponent(dlng.toFixed(6));
          }
          break;
        default:
          url = 'https://www.google.com/maps/dir/?api=1&destination='+encodeURIComponent(dd)+(od?('&origin='+encodeURIComponent(od)):'')+'&travelmode=driving';
      }
      window.open(url, '_blank');
    }

    document.getElementById('btnNavigate')?.addEventListener('click', function(){ openDirections('auto'); });
    document.querySelectorAll('.js-nav-provider').forEach(a => {
      a.addEventListener('click', function(e){ e.preventDefault(); const p = this.getAttribute('data-provider') || 'auto'; openDirections(p); });
    });

    // Affichage badge heure et ancienneté de la dernière position technicien
    function renderTechTimeBadge(){
      if (!markerLL || !lastTs) { if (techTimeBadge) { map.removeLayer(techTimeBadge); techTimeBadge=null; } return; }
      let dt; try { dt = new Date(lastTs.replace(' ','T')); } catch(e){ dt = null; }
      if (!dt || isNaN(dt.getTime())) return;
      const hh = String(dt.getHours()).padStart(2,'0');
      const mm = String(dt.getMinutes()).padStart(2,'0');
      const ageMin = Math.floor((Date.now() - dt.getTime())/60000);
      let ageClass = 'success';
      if (ageMin >= 15) ageClass='danger'; else if (ageMin >= 5) ageClass='warning';
      const ageLabel = ageMin === 0 ? '<1 min' : ageMin+' min';
      const html = `<div class="badge bg-${ageClass}" style="font-size:.7rem;box-shadow:0 0 4px rgba(0,0,0,.25);">${hh}:${mm} • ${ageLabel}</div>`;
      if (!techTimeBadge) {
        techTimeBadge = L.marker([markerLL.lat, markerLL.lng], { icon: L.divIcon({ className:'', html, iconAnchor:[-4,18] }), interactive:false });
        techTimeBadge.addTo(map);
      } else {
        techTimeBadge.setLatLng([markerLL.lat, markerLL.lng]);
        techTimeBadge.setIcon(L.divIcon({ className:'', html, iconAnchor:[-4,18] }));
      }
    }
    // Rafraîchir l'ancienneté toutes les 60s
    setInterval(renderTechTimeBadge, 60000);
    setInterval(renderIncidentTimeBadge, 60000);

    // Badge incident (date / ancienneté, couleur selon âge)
    function renderIncidentTimeBadge(){
      if (!incidentPos || !incidentPosAt || !incidentMarker) { if (incidentTimeBadge) { map.removeLayer(incidentTimeBadge); incidentTimeBadge=null; } return; }
      let dt; try { dt = new Date(incidentPosAt.replace(' ','T')); } catch(e){ dt=null; }
      if (!dt || isNaN(dt.getTime())) return;
      const ageMin = Math.floor((Date.now() - dt.getTime())/60000);
      const ageDays = Math.floor(ageMin / 1440);
      let variant = 'info';
      if (ageDays >= 30) variant = 'secondary'; else if (ageDays >= 7) variant = 'warning';
      const hh = String(dt.getHours()).padStart(2,'0');
      const mm = String(dt.getMinutes()).padStart(2,'0');
      const dateStr = dt.toLocaleDateString('fr-FR');
      const ageLabel = ageDays > 0 ? (ageDays+' j') : (ageMin < 60 ? (ageMin+' min') : (Math.floor(ageMin/60)+' h'));
  const lbl = (incidentTitle && incidentTitle.trim() !== '') ? incidentTitle : 'Incident';
  const html = `<div class="badge bg-${variant}" style="font-size:.7rem;box-shadow:0 0 4px rgba(0,0,0,.25);">${lbl} ${hh}:${mm} • ${ageLabel}</div>`;
      const ll = incidentMarker.getLatLng();
      if (!incidentTimeBadge) {
        incidentTimeBadge = L.marker([ll.lat, ll.lng], { icon: L.divIcon({ className:'', html, iconAnchor:[-6,20] }), interactive:false });
        incidentTimeBadge.addTo(map);
      } else {
        incidentTimeBadge.setLatLng([ll.lat, ll.lng]);
        incidentTimeBadge.setIcon(L.divIcon({ className:'', html, iconAnchor:[-6,20] }));
      }
    }
  })();
</script>

<!-- Modal pour affichage photo d'intervention en grand -->
<div class="modal fade" id="photoModal" tabindex="-1" aria-labelledby="photoModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="photoModalLabel"><i class="fas fa-image me-2"></i>Photo d'intervention</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fermer"></button>
      </div>
      <div class="modal-body text-center">
        <img id="photoModalImage" src="" alt="Photo d'intervention" class="img-fluid mb-3" style="max-height: 60vh; width: auto;">
        <div id="photoModalDetails" class="text-start">
          <div class="card">
            <div class="card-body">
              <h6 class="card-subtitle mb-2 text-muted"><i class="fas fa-comment-dots"></i> Observation</h6>
              <p id="photoModalObservation" class="card-text mb-3"></p>
              <div class="row g-2">
                <div class="col-md-6" id="photoModalGpsContainer" style="display: none;">
                  <p class="mb-0"><strong><i class="fas fa-map-marker-alt"></i> Géolocalisation:</strong></p>
                  <p id="photoModalGps" class="text-muted mb-0"></p>
                </div>
                <div class="col-md-6">
                  <p class="mb-0"><strong><i class="far fa-clock"></i> Date:</strong></p>
                  <p id="photoModalDate" class="text-muted mb-0"></p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><i class="fas fa-times me-1"></i>Fermer</button>
        <a id="photoModalDownload" href="" download class="btn btn-primary" target="_blank"><i class="fas fa-download me-1"></i>Télécharger</a>
      </div>
    </div>
  </div>
</div>

<script>
function showPhotoModal(data) {
  const modal = new bootstrap.Modal(document.getElementById('photoModal'));
  
  // Définir l'image
  document.getElementById('photoModalImage').src = data.src;
  document.getElementById('photoModalDownload').href = data.src;
  
  // Définir l'observation
  const observation = data.observation || 'Aucune observation';
  document.getElementById('photoModalObservation').innerHTML = observation.replace(/\n/g, '<br>');
  
  // Définir les coordonnées GPS si disponibles
  const gpsContainer = document.getElementById('photoModalGpsContainer');
  if (data.lat && data.lng) {
    gpsContainer.style.display = 'block';
    document.getElementById('photoModalGps').textContent = `${parseFloat(data.lat).toFixed(6)}, ${parseFloat(data.lng).toFixed(6)}`;
  } else {
    gpsContainer.style.display = 'none';
  }
  
  // Définir la date
  document.getElementById('photoModalDate').textContent = data.date;
  
  // Afficher la modal
  modal.show();
}
</script>
