<?php
$title = $title ?? 'Gestion Prospects & Clients';
$records = $records ?? [];
$summary = $summary ?? [];
$filters = $filters ?? ['search' => '', 'status' => ''];
$studyTechnicians = $studyTechnicians ?? [];
$flashSuccess = trim((string)($flashSuccess ?? ''));
$flashError = trim((string)($flashError ?? ''));

$successMessage = match ($flashSuccess) {
    'created' => 'Le prospect a été enregistré.',
    'receipt_uploaded' => 'Le reçu a été enregistré. Le prospect est maintenant client.',
    default => '',
};

$errorMessage = $flashError !== '' ? $flashError : '';
?>

<style>
  .prospect-shell{display:grid;gap:1.25rem}
  .prospect-hero{padding:1.35rem 1.4rem;border:1px solid #dbeafe;border-radius:1.2rem;background:linear-gradient(135deg,#f8fbff 0%,#eef8f1 100%);box-shadow:0 18px 40px rgba(15,23,42,.06)}
  .prospect-summary{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:1rem}
  .prospect-kpi{padding:1rem 1.1rem;border-radius:1rem;background:#fff;border:1px solid #e2e8f0;box-shadow:0 10px 24px rgba(15,23,42,.05)}
  .prospect-kpi .label{display:block;font-size:.8rem;color:#64748b;margin-bottom:.35rem}
  .prospect-kpi strong{font-size:1.65rem;line-height:1}
  .prospect-toolbar{display:flex;flex-wrap:wrap;gap:.8rem;align-items:end;justify-content:space-between}
  .prospect-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(340px,1fr));gap:1rem}
  .prospect-card{border:1px solid #e2e8f0;border-radius:1.1rem;background:#fff;padding:1.05rem;box-shadow:0 12px 28px rgba(15,23,42,.05)}
  .prospect-card__header{display:flex;justify-content:space-between;gap:.8rem;align-items:flex-start}
  .prospect-meta{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.75rem;margin-top:1rem}
  .prospect-meta div{border:1px solid #eef2f7;border-radius:.9rem;padding:.8rem;background:#fbfdff}
  .prospect-meta span{display:block;color:#64748b;font-size:.76rem;margin-bottom:.3rem}
  .prospect-actions{display:flex;flex-wrap:wrap;gap:.65rem;margin-top:1rem}
  .status-pill{display:inline-flex;align-items:center;gap:.35rem;border-radius:999px;padding:.35rem .75rem;font-size:.75rem;font-weight:700}
  .status-pill.is-prospect{background:#fef3c7;color:#92400e}
  .status-pill.is-client{background:#dcfce7;color:#166534}
  .suggestion-chip{display:inline-flex;align-items:center;gap:.35rem;padding:.32rem .72rem;border-radius:999px;background:#eff6ff;color:#1d4ed8;font-size:.74rem;font-weight:700}
  .prospect-form-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:1rem}
  .prospect-form-grid .full{grid-column:1/-1}
  .geo-helper{display:flex;gap:.6rem;flex-wrap:wrap;margin-top:.5rem}
  .recommendation-box{border:1px dashed #93c5fd;border-radius:1rem;background:#f8fbff;padding:.9rem 1rem;margin-top:.75rem}
  @media (max-width: 768px){.prospect-form-grid{grid-template-columns:1fr}.prospect-meta{grid-template-columns:1fr}}
</style>

<div class="prospect-shell">
  <section class="prospect-hero">
    <div class="d-flex flex-column flex-lg-row justify-content-between gap-3 align-items-lg-center">
      <div>
        <div class="text-uppercase text-muted small fw-semibold mb-2">Module production</div>
        <h1 class="h3 mb-2">Gestion Prospects & Clients</h1>
        <p class="text-muted mb-0">Enregistrez un prospect, proposez automatiquement un PCO et un port selon la position, basculez en client via le reçu, puis transmettez au workflow normal de raccordement.</p>
      </div>
      <div>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createProspectModal">
          <i class="fas fa-user-plus me-1"></i>Nouveau prospect
        </button>
      </div>
    </div>
  </section>

  <?php if ($successMessage !== ''): ?>
    <div class="alert alert-success mb-0"><i class="fas fa-circle-check me-1"></i><?= htmlspecialchars($successMessage) ?></div>
  <?php endif; ?>
  <?php if ($errorMessage !== ''): ?>
    <div class="alert alert-danger mb-0"><i class="fas fa-triangle-exclamation me-1"></i><?= htmlspecialchars($errorMessage) ?></div>
  <?php endif; ?>

  <section class="prospect-summary">
    <article class="prospect-kpi"><span class="label">Total dossiers</span><strong><?= (int)($summary['total_count'] ?? 0) ?></strong></article>
    <article class="prospect-kpi"><span class="label">Prospects</span><strong><?= (int)($summary['prospect_count'] ?? 0) ?></strong></article>
    <article class="prospect-kpi"><span class="label">Clients</span><strong><?= (int)($summary['client_count'] ?? 0) ?></strong></article>
    <article class="prospect-kpi"><span class="label">Transmis au raccordement</span><strong><?= (int)($summary['transmitted_count'] ?? 0) ?></strong></article>
  </section>

  <section class="card shadow-sm border-0">
    <div class="card-body">
      <form method="get" action="<?= htmlspecialchars(route_url('/prospect-clients')) ?>" class="prospect-toolbar">
        <div class="d-flex flex-wrap gap-2 align-items-end">
          <div>
            <label class="form-label small text-muted">Recherche</label>
            <input type="text" class="form-control" name="search" value="<?= htmlspecialchars((string)($filters['search'] ?? '')) ?>" placeholder="Nom, téléphone, ville, PCO...">
          </div>
          <div>
            <label class="form-label small text-muted">Statut</label>
            <select class="form-select" name="status">
              <option value="">Tous</option>
              <option value="prospect" <?= ($filters['status'] ?? '') === 'prospect' ? 'selected' : '' ?>>Prospect</option>
              <option value="client" <?= ($filters['status'] ?? '') === 'client' ? 'selected' : '' ?>>Client</option>
            </select>
          </div>
          <div><button type="submit" class="btn btn-outline-secondary"><i class="fas fa-search me-1"></i>Filtrer</button></div>
        </div>
      </form>
    </div>
  </section>

  <section class="prospect-grid">
    <?php foreach ($records as $record): ?>
      <?php
        $status = (string)($record['status'] ?? 'prospect');
        $hasReceipt = !empty($record['receipt_path']);
        $ticketId = (int)($record['raccordement_ticket_id'] ?? 0);
        $fullName = trim((string)($record['full_name'] ?? ''));
        $cityLine = trim(implode(' / ', array_filter([(string)($record['city'] ?? ''), (string)($record['commune'] ?? '')])));
        $recommendationText = trim((string)($record['recommended_otb_code'] ?? ''));
        if ($recommendationText !== '' && !empty($record['recommended_port_number'])) {
            $recommendationText .= ' · Port ' . (int)$record['recommended_port_number'];
        }
      ?>
      <article class="prospect-card">
        <div class="prospect-card__header">
          <div>
            <h2 class="h5 mb-1"><?= htmlspecialchars($fullName !== '' ? $fullName : 'Prospect sans nom') ?></h2>
            <div class="text-muted small"><?= htmlspecialchars((string)($record['phone'] ?? 'Contact non renseigné')) ?></div>
          </div>
          <span class="status-pill <?= $status === 'client' ? 'is-client' : 'is-prospect' ?>">
            <i class="fas <?= $status === 'client' ? 'fa-circle-check' : 'fa-user-clock' ?>"></i>
            <?= htmlspecialchars(ucfirst($status)) ?>
          </span>
        </div>

        <div class="prospect-meta">
          <div>
            <span>Ville / commune</span>
            <strong><?= htmlspecialchars($cityLine !== '' ? $cityLine : 'Non renseigné') ?></strong>
          </div>
          <div>
            <span>Géolocalisation</span>
            <strong><?= !empty($record['latitude']) && !empty($record['longitude']) ? htmlspecialchars((string)$record['latitude'] . ', ' . (string)$record['longitude']) : 'Non renseignée' ?></strong>
          </div>
          <div>
            <span>Recommandation PCO</span>
            <strong><?= htmlspecialchars($recommendationText !== '' ? $recommendationText : 'Aucune suggestion') ?></strong>
          </div>
          <div>
            <span>Reçu paiement</span>
            <strong>
              <?php if ($hasReceipt): ?>
                <a href="<?= htmlspecialchars(upload_url((string)$record['receipt_path'])) ?>" target="_blank" rel="noopener">Voir le reçu</a>
              <?php else: ?>
                En attente
              <?php endif; ?>
            </strong>
          </div>
        </div>

        <?php if ($recommendationText !== ''): ?>
          <div class="mt-3"><span class="suggestion-chip"><i class="fas fa-satellite-dish"></i><?= htmlspecialchars($recommendationText) ?></span></div>
        <?php endif; ?>

        <div class="prospect-actions">
          <?php if (!$hasReceipt): ?>
            <button type="button" class="btn btn-outline-success btn-sm js-open-receipt-modal"
                    data-id="<?= (int)$record['id'] ?>"
                    data-name="<?= htmlspecialchars($fullName, ENT_QUOTES) ?>"
                    data-bs-toggle="modal"
                    data-bs-target="#receiptModal">
              <i class="fas fa-receipt me-1"></i>Uploader le reçu
            </button>
          <?php endif; ?>

          <?php if ($status === 'client' && $ticketId <= 0): ?>
            <button type="button" class="btn btn-primary btn-sm js-open-raccordement-modal"
                    data-id="<?= (int)$record['id'] ?>"
                    data-name="<?= htmlspecialchars($fullName, ENT_QUOTES) ?>"
                    data-phone="<?= htmlspecialchars((string)($record['phone'] ?? ''), ENT_QUOTES) ?>"
                    data-city="<?= htmlspecialchars((string)($record['city'] ?? ''), ENT_QUOTES) ?>"
                    data-commune="<?= htmlspecialchars((string)($record['commune'] ?? ''), ENT_QUOTES) ?>"
                    data-address="<?= htmlspecialchars((string)($record['address'] ?? ''), ENT_QUOTES) ?>"
                    data-latitude="<?= htmlspecialchars((string)($record['latitude'] ?? ''), ENT_QUOTES) ?>"
                    data-longitude="<?= htmlspecialchars((string)($record['longitude'] ?? ''), ENT_QUOTES) ?>"
                    data-pco="<?= htmlspecialchars((string)($record['recommended_otb_code'] ?? ''), ENT_QUOTES) ?>"
                    data-port="<?= (int)($record['recommended_port_number'] ?? 0) ?>"
                    data-bs-toggle="modal"
                    data-bs-target="#raccordementModal">
              <i class="fas fa-plug-circle-bolt me-1"></i>Transmettre au raccordement
            </button>
          <?php endif; ?>

          <?php if ($ticketId > 0): ?>
            <a class="btn btn-outline-primary btn-sm" href="<?= htmlspecialchars(route_url('/raccordement-clients/detail?id=' . $ticketId)) ?>">
              <i class="fas fa-arrow-up-right-from-square me-1"></i>Ouvrir le dossier raccordement
            </a>
          <?php endif; ?>
        </div>
      </article>
    <?php endforeach; ?>

    <?php if ($records === []): ?>
      <article class="prospect-card">
        <div class="text-center py-4 text-muted">
          <i class="fas fa-users-viewfinder fa-2x mb-3"></i>
          <div>Aucun prospect ou client ne correspond aux filtres courants.</div>
        </div>
      </article>
    <?php endif; ?>
  </section>
</div>

<div class="modal fade" id="createProspectModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-xl modal-dialog-scrollable">
    <form method="post" action="<?= htmlspecialchars(route_url('/prospect-clients/create')) ?>" class="modal-content" id="createProspectForm">
      <div class="modal-header">
        <div>
          <h5 class="modal-title mb-1">Nouveau prospect</h5>
          <div class="text-muted small">Création en modale avec géolocalisation manuelle ou automatique et suggestion immédiate de PCO/port.</div>
        </div>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="prospect-form-grid">
          <div>
            <label class="form-label">Nom</label>
            <input type="text" name="last_name" class="form-control" required>
          </div>
          <div>
            <label class="form-label">Prénoms</label>
            <input type="text" name="first_name" class="form-control" required>
          </div>
          <div>
            <label class="form-label">Ville</label>
            <input type="text" name="city" class="form-control">
          </div>
          <div>
            <label class="form-label">Quartier / Commune</label>
            <input type="text" name="commune" class="form-control">
          </div>
          <div class="full">
            <label class="form-label">Localisation</label>
            <textarea name="address" class="form-control" rows="3"></textarea>
          </div>
          <div>
            <label class="form-label">Contact téléphonique</label>
            <input type="text" name="phone" class="form-control" required>
          </div>
          <div>
            <label class="form-label">Mode géolocalisation</label>
            <select name="geolocation_mode" id="prospectGeoMode" class="form-select">
              <option value="manual">Manuelle</option>
              <option value="auto">Ma position</option>
            </select>
          </div>
          <div>
            <label class="form-label">Latitude</label>
            <input type="text" name="latitude" id="prospectLatitude" class="form-control" placeholder="Ex. 5.359952">
          </div>
          <div>
            <label class="form-label">Longitude</label>
            <input type="text" name="longitude" id="prospectLongitude" class="form-control" placeholder="Ex. -4.008256">
          </div>
          <div class="full">
            <div class="geo-helper">
              <button type="button" class="btn btn-outline-secondary btn-sm" id="useCurrentPositionBtn"><i class="fas fa-location-crosshairs me-1"></i>Utiliser ma position</button>
              <button type="button" class="btn btn-outline-primary btn-sm" id="fetchRecommendationBtn"><i class="fas fa-satellite-dish me-1"></i>Rechercher PCO / Port</button>
            </div>
            <div class="recommendation-box" id="prospectRecommendationBox">
              <div class="fw-semibold mb-1">Suggestion réseau</div>
              <div class="text-muted small" id="prospectRecommendationText">Aucune recommandation calculée pour le moment.</div>
            </div>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Annuler</button>
        <button type="submit" class="btn btn-primary"><i class="fas fa-save me-1"></i>Enregistrer comme prospect</button>
      </div>
    </form>
  </div>
</div>

<div class="modal fade" id="receiptModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <form method="post" action="<?= htmlspecialchars(route_url('/prospect-clients/receipt/upload')) ?>" enctype="multipart/form-data" class="modal-content">
      <input type="hidden" name="prospect_id" id="receiptProspectId">
      <div class="modal-header">
        <div>
          <h5 class="modal-title mb-1">Uploader le reçu</h5>
          <div class="text-muted small" id="receiptModalSubtitle">Le reçu de paiement fait passer le prospect au statut client.</div>
        </div>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <label class="form-label">Reçu de paiement</label>
        <input type="file" name="payment_receipt" class="form-control" accept=".pdf,.jpg,.jpeg,.png,.webp" required>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Annuler</button>
        <button type="submit" class="btn btn-success"><i class="fas fa-cloud-upload-alt me-1"></i>Valider le paiement</button>
      </div>
    </form>
  </div>
</div>

<div class="modal fade" id="raccordementModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-xl modal-dialog-scrollable">
    <form method="post" action="<?= htmlspecialchars(route_url('/prospect-clients/raccordement/create')) ?>" class="modal-content">
      <input type="hidden" name="prospect_id" id="raccordementProspectId">
      <div class="modal-header">
        <div>
          <h5 class="modal-title mb-1">Transmettre au raccordement</h5>
          <div class="text-muted small" id="raccordementModalSubtitle">Complétez les champs manquants puis assignez un technicien étude si nécessaire.</div>
        </div>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="prospect-form-grid">
          <div>
            <label class="form-label">Référence dossier</label>
            <input type="text" name="ref_code" class="form-control">
          </div>
          <div>
            <label class="form-label">Numéro abonnement</label>
            <input type="text" name="client_code" class="form-control">
          </div>
          <div>
            <label class="form-label">Ville</label>
            <input type="text" name="city" id="raccordementCity" class="form-control">
          </div>
          <div>
            <label class="form-label">Commune</label>
            <input type="text" name="commune" id="raccordementCommune" class="form-control">
          </div>
          <div class="full">
            <label class="form-label">Localisation</label>
            <textarea name="address" id="raccordementAddress" class="form-control" rows="3"></textarea>
          </div>
          <div>
            <label class="form-label">Contact client</label>
            <input type="text" name="phone" id="raccordementPhone" class="form-control">
          </div>
          <div>
            <label class="form-label">Entreprise FTTH</label>
            <input type="text" name="company_name" class="form-control">
          </div>
          <div>
            <label class="form-label">Latitude</label>
            <input type="text" name="latitude" id="raccordementLatitude" class="form-control">
          </div>
          <div>
            <label class="form-label">Longitude</label>
            <input type="text" name="longitude" id="raccordementLongitude" class="form-control">
          </div>
          <div>
            <label class="form-label">PLAQUE</label>
            <input type="text" name="sro_client" class="form-control">
          </div>
          <div>
            <label class="form-label">JDV</label>
            <input type="text" name="jdv_client" class="form-control">
          </div>
          <div>
            <label class="form-label">PCO</label>
            <input type="text" name="pco_client" id="raccordementPco" class="form-control">
          </div>
          <div>
            <label class="form-label">SNONT / ND</label>
            <div class="input-group">
              <input type="text" name="snont" class="form-control" placeholder="SNONT">
              <input type="text" name="nd" class="form-control" placeholder="ND">
            </div>
          </div>
          <div>
            <label class="form-label">Priorité</label>
            <select name="priority" class="form-select">
              <?php foreach (['Moyenne', 'Haute', 'Urgent', 'Basse'] as $priority): ?>
                <option value="<?= htmlspecialchars($priority) ?>"><?= htmlspecialchars($priority) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div>
            <label class="form-label">Statut initial</label>
            <select name="status" class="form-select">
              <?php foreach (['nouveau', 'attente_planification', 'assigné'] as $statusOption): ?>
                <option value="<?= htmlspecialchars($statusOption) ?>"><?= htmlspecialchars($statusOption) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div>
            <label class="form-label">Technicien étude</label>
            <select name="technician_id" class="form-select">
              <option value="0">Aucune assignation immédiate</option>
              <?php foreach ($studyTechnicians as $technician): ?>
                <option value="<?= (int)($technician['id'] ?? 0) ?>"><?= htmlspecialchars((string)($technician['name'] ?? '')) ?><?= !empty($technician['technician_type']) ? ' • ' . htmlspecialchars((string)$technician['technician_type']) : '' ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="full">
            <label class="form-label">Notes d'assignation</label>
            <textarea name="assignment_notes" class="form-control" rows="2"></textarea>
          </div>
          <div class="full">
            <label class="form-label">Description / informations manquantes</label>
            <textarea name="description" class="form-control" rows="4" placeholder="Contexte commercial, contraintes d'accès, repères complémentaires..."></textarea>
          </div>
          <div class="full">
            <div class="recommendation-box">
              <div class="fw-semibold mb-1">Suggestion PCO détectée</div>
              <div class="text-muted small" id="raccordementSuggestionText">Aucune suggestion disponible.</div>
            </div>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Annuler</button>
        <button type="submit" class="btn btn-primary"><i class="fas fa-paper-plane me-1"></i>Créer la demande de raccordement</button>
      </div>
    </form>
  </div>
</div>

<script>
(function () {
  'use strict';

  const latitudeInput = document.getElementById('prospectLatitude');
  const longitudeInput = document.getElementById('prospectLongitude');
  const geoModeInput = document.getElementById('prospectGeoMode');
  const recommendationText = document.getElementById('prospectRecommendationText');
  const recommendationBtn = document.getElementById('fetchRecommendationBtn');
  const currentPositionBtn = document.getElementById('useCurrentPositionBtn');

  function setRecommendationMessage(message) {
    recommendationText.textContent = message;
  }

  async function fetchRecommendation() {
    const latitude = latitudeInput.value.trim();
    const longitude = longitudeInput.value.trim();
    if (!latitude || !longitude) {
      setRecommendationMessage('Renseignez d\'abord la latitude et la longitude pour calculer la suggestion PCO / port.');
      return;
    }

    setRecommendationMessage('Calcul de la suggestion en cours...');
    try {
      const url = new URL('<?= htmlspecialchars(route_url('/prospect-clients/recommendation')) ?>', window.location.origin);
      url.searchParams.set('latitude', latitude);
      url.searchParams.set('longitude', longitude);
      const response = await fetch(url.toString(), { headers: { 'X-Requested-With': 'XMLHttpRequest' } });
      const data = await response.json();
      const recommended = data && data.recommendation ? data.recommendation.recommended : null;
      if (!data.ok || !recommended) {
        setRecommendationMessage((data && data.recommendation && data.recommendation.alert) || 'Aucun PCO disponible dans le rayon configuré.');
        return;
      }

      const portNumber = data && data.snapshot ? data.snapshot.recommended_port_number : null;
      const pieces = [recommended.box_code || 'PCO recommandé'];
      if (portNumber) {
        pieces.push('Port ' + portNumber);
      }
      if (recommended.distance_label) {
        pieces.push(recommended.distance_label);
      }
      setRecommendationMessage(pieces.join(' • '));
    } catch (error) {
      setRecommendationMessage('La suggestion automatique n\'a pas pu être calculée.');
    }
  }

  if (currentPositionBtn) {
    currentPositionBtn.addEventListener('click', function () {
      if (!navigator.geolocation) {
        setRecommendationMessage('La géolocalisation n\'est pas disponible sur cet appareil.');
        return;
      }

      navigator.geolocation.getCurrentPosition(function (position) {
        geoModeInput.value = 'auto';
        latitudeInput.value = position.coords.latitude.toFixed(7);
        longitudeInput.value = position.coords.longitude.toFixed(7);
        fetchRecommendation();
      }, function () {
        setRecommendationMessage('Impossible de récupérer votre position actuelle.');
      }, { enableHighAccuracy: true, timeout: 10000, maximumAge: 0 });
    });
  }

  if (recommendationBtn) {
    recommendationBtn.addEventListener('click', fetchRecommendation);
  }

  document.querySelectorAll('.js-open-receipt-modal').forEach(function (button) {
    button.addEventListener('click', function () {
      document.getElementById('receiptProspectId').value = button.getAttribute('data-id') || '';
      document.getElementById('receiptModalSubtitle').textContent = 'Le reçu de paiement de ' + (button.getAttribute('data-name') || 'ce prospect') + ' fera passer le dossier au statut client.';
    });
  });

  document.querySelectorAll('.js-open-raccordement-modal').forEach(function (button) {
    button.addEventListener('click', function () {
      document.getElementById('raccordementProspectId').value = button.getAttribute('data-id') || '';
      document.getElementById('raccordementModalSubtitle').textContent = 'Complétez les champs manquants pour ' + (button.getAttribute('data-name') || 'ce client') + ' puis assignez un technicien étude si nécessaire.';
      document.getElementById('raccordementPhone').value = button.getAttribute('data-phone') || '';
      document.getElementById('raccordementCity').value = button.getAttribute('data-city') || '';
      document.getElementById('raccordementCommune').value = button.getAttribute('data-commune') || '';
      document.getElementById('raccordementAddress').value = button.getAttribute('data-address') || '';
      document.getElementById('raccordementLatitude').value = button.getAttribute('data-latitude') || '';
      document.getElementById('raccordementLongitude').value = button.getAttribute('data-longitude') || '';
      document.getElementById('raccordementPco').value = button.getAttribute('data-pco') || '';

      const pco = button.getAttribute('data-pco') || 'Aucune suggestion';
      const port = button.getAttribute('data-port') || '';
      document.getElementById('raccordementSuggestionText').textContent = port && Number(port) > 0 ? (pco + ' • Port ' + port) : pco;
    });
  });
})();
</script>