<?php use App\Core\Auth; $title = 'Incident ' . htmlspecialchars($incident['ticket_id']); ?>
<?php
  $cu = Auth::user();
  $role = $cu['role_key'] ?? '';
  $showAdminQuickReportUI = false;
  $isAssigned = false;
  if (!empty($assignedUsers)) { foreach ($assignedUsers as $a) { if (($cu['name'] ?? '') === ($a['name'] ?? '')) { $isAssigned = true; break; } } }
  $canTreat = in_array($role, ['admin','agent'], true) || ($role==='technicien' && $isAssigned && in_array($treatmentState ?? 'none',['none','draft'],true));
  $canViewTreatment = in_array($role, ['admin','manager','superviseur','supervisor','agent','technicien'], true);
  // Permettre rapport final (modal) pour technicien assigné quand traitement validé et rapport final non complété
  $canFinalReport = ($role==='technicien' && $isAssigned && ($treatmentState==='validated') && ($finalReportState!=='completed'));
?>

<div class="incident-detail px-2 px-md-3">

<div class="card shadow-sm mb-4">
  <div class="card-body py-3">
    <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-3">
      <div>
        <div class="d-flex align-items-center gap-2 mb-1">
          <a href="<?= htmlspecialchars(route_url('/incidents')) ?>" class="btn btn-sm btn-outline-secondary" title="Retour"><i class="fas fa-arrow-left"></i></a>
          <h4 class="mb-0"><i class="fas fa-ticket-alt text-muted me-2"></i><?= htmlspecialchars($incident['ticket_id']) ?> — <?= htmlspecialchars($incident['title']) ?></h4>
        </div>
        <?php if (!empty($incident['incident_number'])): ?><div class="text-muted small">Référence: <?= htmlspecialchars($incident['incident_number']) ?></div><?php endif; ?>
      </div>
      <div class="text-md-end">
        <span class="badge rounded-pill" style="background:<?= htmlspecialchars($incident['status_color']) ?>;"><?= htmlspecialchars($incident['status_label']) ?></span>
        <div class="mt-2 d-flex flex-wrap gap-2 justify-content-start justify-content-md-end">
          <?php if ($canTreat): ?><a href="<?= htmlspecialchars(route_url('/incidents/treatment',['id'=>$incident['id']])) ?>" class="btn btn-sm btn-outline-success"><i class="fas fa-wrench"></i> Traiter</a><?php endif; ?>
          <?php if ($canViewTreatment): ?><a href="<?= htmlspecialchars(route_url('/incidents/treatment',['id'=>$incident['id'],'view'=>1])) ?>" class="btn btn-sm btn-outline-info"><i class="fas fa-eye"></i> Voir traitement</a><?php endif; ?>
          <?php if ($canFinalReport): ?><a href="#" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#finalReportModal"><i class="fas fa-file-signature"></i> Clôturer</a><?php endif; ?>
          <?php if (!empty($finalReport) && !empty($finalReport['restoration_at'])): ?>
            <a href="<?= htmlspecialchars(route_url('/incidents/final-report/print',['id'=>$incident['id']])) ?>" target="_blank" class="btn btn-sm btn-outline-secondary"><i class="fas fa-print"></i> Imprimer</a>
            <a href="<?= htmlspecialchars(route_url('/incidents/final-report/pdf',['id'=>$incident['id']])) ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-file-pdf"></i> PDF</a>
          <?php endif; ?>
          <?php
            // Bouton de suppression uniquement si statut = "open" et rôle admin/agent
            $canDelete = in_array($role, ['admin','agent'], true) && strtolower($incident['status_key'] ?? '') === 'open';
            if ($canDelete):
          ?>
            <button type="button" class="btn btn-sm btn-outline-danger" onclick="confirmDeleteIncident(<?= (int)$incident['id'] ?>)">
              <i class="fas fa-trash"></i> Supprimer
            </button>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </div>
  <div class="border-top px-3 py-2 bg-light small text-muted d-flex flex-wrap gap-3">
    <div><i class="fas fa-user me-1"></i><?= htmlspecialchars($incident['client_name']) ?></div>
    <div><i class="fas fa-location-dot me-1"></i><?= htmlspecialchars($incident['location_name']) ?></div>
    <div><i class="fas fa-calendar-plus me-1"></i>Déclaré le <?= date('d/m/Y H:i', strtotime($incident['declared_at'])) ?> par <?= htmlspecialchars($incident['declared_by_name']) ?></div>
    <?php if ($incident['expected_resolution_at']): ?><div><i class="fas fa-stopwatch me-1"></i>SLA Résolution: <?= date('d/m/Y H:i', strtotime($incident['expected_resolution_at'])) ?></div><?php endif; ?>
  </div>
</div>

<?php
  $priorityClass = match($incident['priority']) {
    'Urgent' => 'text-bg-danger',
    'Haute' => 'text-bg-warning',
    'Moyenne' => 'text-bg-info',
    'Basse' => 'text-bg-secondary',
    default => 'text-bg-secondary'
  };
  // Harmonisation état Intervention avec incident clôturé / rapport final
  $incidentStatusKey = strtolower($incident['status_key'] ?? '');
  $incidentStatusLabelLow = strtolower($incident['status_label'] ?? '');
  $isIncidentClosed = in_array($incidentStatusKey, ['closed','resolu','resolved','cloture','clôturé'], true)
    || str_contains($incidentStatusLabelLow, 'clôtur')
    || str_contains($incidentStatusLabelLow, 'clos');
  // Statut traité pour bloquer l'assignation
  $isIncidentTreated = in_array($incidentStatusKey, ['treated','traite','processed'], true)
    || str_contains($incidentStatusLabelLow, 'trait');
  $canAssignTechnician = in_array($role, ['admin','agent'], true) && !$isIncidentClosed && !$isIncidentTreated;
  $hasRestoration = !empty($finalReport['restoration_at']);
  $forceCompleted = $isIncidentClosed || ($hasRestoration && ($finalReportState === 'completed'));
  $kpiIntervState = $interventionState ?? 'none';
  if ($forceCompleted && $kpiIntervState !== 'completed') { $kpiIntervState = 'completed'; }
  $kpiIntervBadge = match($kpiIntervState) {
    'active' => 'success',
    'paused' => 'secondary',
    'completed' => 'primary',
    default => 'secondary'
  };
  $kpiIntervLabel = match($kpiIntervState) {
    'active' => 'En cours',
    'paused' => 'En pause',
    'completed' => 'Terminée',
    default => '—'
  };
  $kpiFrState = $finalReportState ?? 'none';
  $kpiFrBadge = match($kpiFrState) {
    'completed' => 'success',
    'pending' => 'warning',
    default => 'secondary'
  };
  $kpiFrLabel = match($kpiFrState) {
    'completed' => 'Clôturé',
    'pending' => 'À compléter',
    default => 'Aucun'
  };
?>
<?php // Fallback: charger les commentaires si non fournis au template ?>
<?php if (!isset($comments) || !is_array($comments)) {
  try {
    $pdoC = \App\Core\Database::pdo();
    $stC = $pdoC->prepare('SELECT id, author_name, content, created_at FROM incident_comments WHERE incident_id = ? ORDER BY created_at DESC');
    $stC->execute([(int)$incident['id']]);
    $comments = $stC->fetchAll();
  } catch (\Throwable $e) { $comments = []; }
} ?>
<div class="row g-3 mb-4">
  <div class="col-6 col-md-3 col-xl-2"><div class="card kpi-card h-100 shadow-sm border-0 bg-light"><div class="card-body py-2 px-3 d-flex flex-column justify-content-between"><div><div class="small text-muted">Priorité</div><div class="fw-semibold mt-1"><span class="badge <?= $priorityClass ?> w-100"><?= htmlspecialchars($incident['priority'] ?? '—') ?></span></div></div></div></div></div>
  <div class="col-6 col-md-3 col-xl-2"><div class="card kpi-card h-100 shadow-sm border-0 bg-light"><div class="card-body py-2 px-3 d-flex flex-column justify-content-between"><div><div class="small text-muted">Statut</div><div class="fw-semibold mt-1"><span class="badge w-100" style="background:<?= htmlspecialchars($incident['status_color']) ?>;"><?= htmlspecialchars($incident['status_label']) ?></span></div></div></div></div></div>
  <div class="col-6 col-md-3 col-xl-2"><div class="card kpi-card h-100 shadow-sm border-0 bg-light"><div class="card-body py-2 px-3 d-flex flex-column justify-content-between"><div><div class="small text-muted">SLA Résolution</div><div class="fw-semibold mt-1 text-truncate" title="<?= $incident['expected_resolution_at'] ? date('d/m/Y H:i', strtotime($incident['expected_resolution_at'])) : '—' ?>"><?= $incident['expected_resolution_at'] ? date('d/m/Y H:i', strtotime($incident['expected_resolution_at'])) : '—' ?></div></div></div></div></div>
  <div class="col-6 col-md-3 col-xl-2"><div class="card kpi-card h-100 shadow-sm border-0 bg-light"><div class="card-body py-2 px-3 d-flex flex-column justify-content-between"><div><div class="small text-muted">Intervention</div><div class="fw-semibold mt-1"><span class="badge text-bg-<?= $kpiIntervBadge ?> w-100"><?= $kpiIntervLabel ?></span></div><div class="small text-muted mt-1">Durée: <?= htmlspecialchars($interventionDurationHuman ?? '0m') ?></div></div></div></div></div>
  <div class="col-6 col-md-3 col-xl-2"><div class="card kpi-card h-100 shadow-sm border-0 bg-light"><div class="card-body py-2 px-3 d-flex flex-column justify-content-between"><div><div class="small text-muted">Rapport final</div><div class="fw-semibold mt-1"><span class="badge text-bg-<?= $kpiFrBadge ?> w-100"><?= $kpiFrLabel ?></span></div><?php if (!empty($finalReport['restoration_at'])): ?><div class="small text-muted mt-1" title="<?= date('d/m/Y H:i', strtotime($finalReport['restoration_at'])) ?>">Rétabli: <?= date('d/m H:i', strtotime($finalReport['restoration_at'])) ?></div><?php endif; ?></div></div></div></div>
  <div class="col-6 col-md-3 col-xl-2"><div class="card kpi-card h-100 shadow-sm border-0 bg-light"><div class="card-body py-2 px-3 d-flex flex-column justify-content-between"><div><div class="small text-muted">Pauses</div><div class="fw-semibold mt-1"><span class="badge text-bg-secondary w-100"><i class="fas fa-pause me-1"></i><?= (int)($pauseCount ?? 0) ?></span></div></div></div></div></div>
</div>

<style>
  /* Hauteur uniforme des cartes KPI */
  .kpi-card .card-body { min-height: 110px; }
  @media (min-width: 1200px) { .kpi-card .card-body { min-height: 120px; } }
  /* Sidebar sticky */
  .incident-sidebar-sticky { position: sticky; top: 1rem; align-self: flex-start; }
  /* Historique scroll */
  .history-scroll { max-height: 320px; overflow: auto; }
    /* Actions rapides responsive */
    .quick-actions { display:flex; flex-wrap:wrap; gap:.5rem; }
    .quick-actions .btn { flex:1 1 100%; }
    @media (min-width:576px){ .quick-actions .btn { flex:1 1 auto; } }
</style>

<style>
  /* Équilibrage largeur: empêcher tout rétrécissement et utiliser toute la largeur disponible dans le body */
  .incident-detail { width: 100%; }
  .incident-detail .card { max-width: 100%; }
  .incident-detail .tab-content { max-width: 100%; }
  /* Réduction de condensation à droite en normalisant le gutter horizontal */
  .incident-detail .row { --bs-gutter-x: 1rem; }
  @media (min-width: 1400px) {
    .incident-detail .row { --bs-gutter-x: 1.25rem; }
  }
</style>

<ul class="nav nav-tabs mb-3" id="incidentTabs" role="tablist">
  <li class="nav-item" role="presentation"><button class="nav-link active" id="tab-overview" data-bs-toggle="tab" data-bs-target="#pane-overview" type="button" role="tab" aria-selected="true"><i class="fas fa-circle-info me-1"></i>Aperçu</button></li>
  <li class="nav-item" role="presentation"><button class="nav-link" id="tab-comments" data-bs-toggle="tab" data-bs-target="#pane-comments" type="button" role="tab" aria-selected="false"><i class="fas fa-comments me-1"></i>Commentaires</button></li>
  <li class="nav-item" role="presentation"><button class="nav-link" id="tab-history" data-bs-toggle="tab" data-bs-target="#pane-history" type="button" role="tab" aria-selected="false"><i class="fas fa-clock-rotate-left me-1"></i>Historique</button></li>
</ul>

<div class="tab-content" id="incidentTabsContent">
  <!-- Aperçu -->
  <div class="tab-pane fade show active" id="pane-overview" role="tabpanel" aria-labelledby="tab-overview">
    <div class="row g-4">
      <!-- Colonne principale -->
      <div class="col-12 col-xl-8">
        <?php
          $nowTs = time();
          $expRes = !empty($incident['expected_resolution_at']) ? strtotime($incident['expected_resolution_at']) : null;
          $resAt  = !empty($incident['resolved_at']) ? strtotime($incident['resolved_at']) : null;
          $isLateUnresolved = ($expRes && !$resAt && $expRes < $nowTs);
          $isLateResolved   = ($expRes && $resAt && $resAt > $expRes);
          if ($isLateUnresolved || $isLateResolved):
            $deltaSec = $isLateUnresolved ? ($nowTs - $expRes) : ($resAt - $expRes);
            $hours = floor($deltaSec / 3600); $mins = floor(($deltaSec % 3600) / 60);
            $msg = $isLateUnresolved
              ? "SLA de résolution échue depuis {$hours}h{$mins} — intervention toujours en cours."
              : "SLA de résolution dépassé de {$hours}h{$mins} (résolu après l'échéance).";
        ?>
          <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-triangle-exclamation me-1"></i><?= htmlspecialchars($msg) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Fermer"></button>
          </div>
        <?php else: ?>
          <?php if (!empty($me) && (($me['role_key'] ?? '') === 'technicien')): ?>
            <div class="alert alert-info py-2 px-3">Vous devez être assigné à cet incident pour ajouter un commentaire.</div>
          <?php endif; ?>
        <?php endif; ?>
        <div class="card shadow-sm mb-4">
          <div class="card-header"><h5 class="mb-0"><i class="fas fa-circle-info text-muted me-2"></i>Détails</h5></div>
          <div class="card-body">
            <div class="row g-3">
              <div class="col-12 col-md-6"><strong>Client :</strong><br><?= htmlspecialchars($incident['client_name']) ?></div>
              <div class="col-12 col-md-6"><strong>Localisation :</strong><br><?= htmlspecialchars($incident['location_name']) ?><?php if ($incident['location_address']): ?><br><small class="text-muted"><?= htmlspecialchars($incident['location_address']) ?></small><?php endif; ?></div>
              <div class="col-12 col-md-6"><strong>Priorité :</strong><br><span class="badge <?= $priorityClass ?>"><?= htmlspecialchars($incident['priority']) ?></span></div>
              <div class="col-12 col-md-6"><strong>Cause :</strong><br><?= $incident['cause_name'] ? htmlspecialchars($incident['cause_name']) : '<em>Non identifiée</em>' ?></div>
              <div class="col-12 col-md-6"><strong>Déclaré le :</strong><br><?= date('d/m/Y à H:i', strtotime($incident['declared_at'])) ?><br><small class="text-muted">par <?= htmlspecialchars($incident['declared_by_name']) ?></small></div>
              <div class="col-12 col-md-6"><strong>SLA :</strong><br><?php if ($incident['expected_response_at']): ?>Réponse : <?= date('d/m/Y H:i', strtotime($incident['expected_response_at'])) ?><br><?php endif; ?><?php if ($incident['expected_resolution_at']): ?>Résolution : <?= date('d/m/Y H:i', strtotime($incident['expected_resolution_at'])) ?><?php endif; ?></div>
              <?php if ($incident['description']): ?><div class="col-12"><strong>Description :</strong><div class="mt-2 p-3 bg-light rounded"><?= nl2br(htmlspecialchars($incident['description'])) ?></div></div><?php endif; ?>
            </div>
          </div>
        </div>
      </div>
      <!-- Sidebar -->
      <div class="col-12 col-xl-4 incident-sidebar-sticky">
        <div class="d-flex flex-column gap-3">
          <?php // Intervention ?>
          <?php if (in_array($role, ['technicien','admin','agent'])) {
              $origInterventionState = $interventionState ?? 'none';
              $state = $origInterventionState;
              if ($forceCompleted && $state !== 'completed') { $state = 'completed'; }
            $durHuman = htmlspecialchars($interventionDurationHuman ?? '0m');
            $pauseCountInt = (int)($pauseCount ?? 0);
            $lastPauseReason = $lastPauseReason ?? null;
            $lastPauseAt = $lastPauseAt ?? null;
          ?>
          <div class="card shadow-sm">
            <div class="card-header"><h6 class="mb-0"><i class="fas fa-toolbox me-2"></i>Intervention</h6></div>
            <div class="card-body" id="interventionCardBody">
              <?php if ($state === 'active'): ?>
                <p class="mb-2 d-flex flex-wrap align-items-center gap-2">
                  <span class="badge text-bg-success"><i class="fas fa-person-digging me-1"></i> En cours</span>
                  <span class="badge text-bg-primary"><i class="fas fa-hourglass-half me-1"></i><?= $durHuman ?></span>
                  <?php if ($pauseCountInt > 0): ?><span class="badge text-bg-secondary"><i class="fas fa-pause me-1"></i><?= $pauseCountInt ?> pause<?= $pauseCountInt>1?'s':'' ?></span><?php endif; ?>
                </p>
                <button type="button" id="btnInterventionPause" class="btn btn-sm btn-outline-warning"><i class="fas fa-pause"></i> Mettre en pause</button>
              <?php elseif ($state === 'paused'): ?>
                <p class="mb-2 d-flex flex-wrap align-items-center gap-2">
                  <span class="badge text-bg-secondary"><i class="fas fa-pause me-1"></i> En pause</span>
                  <span class="badge text-bg-primary"><i class="fas fa-hourglass-half me-1"></i><?= $durHuman ?></span>
                  <?php if ($pauseCountInt > 0): ?><span class="badge text-bg-secondary"><i class="fas fa-pause me-1"></i><?= $pauseCountInt ?> pause<?= $pauseCountInt>1?'s':'' ?></span><?php endif; ?>
                </p>
                <?php if ($lastPauseReason): ?>
                  <div class="alert alert-secondary py-2 px-3 mb-2"><i class="fas fa-comment-dots me-1"></i><strong>Motif:</strong> <?= nl2br(htmlspecialchars($lastPauseReason)) ?><?php if ($lastPauseAt): ?><span class="text-muted"> (<?= date('d/m H:i', strtotime($lastPauseAt)) ?>)</span><?php endif; ?></div>
                <?php endif; ?>
                <button type="button" id="btnInterventionResume" class="btn btn-sm btn-outline-success"><i class="fas fa-play"></i> Reprendre</button>
              <?php elseif ($state === 'completed'): ?>
                <p class="mb-2 d-flex flex-wrap align-items-center gap-2">
                  <span class="badge text-bg-success"><i class="fas fa-flag-checkered me-1"></i> Terminée</span>
                  <span class="badge text-bg-primary"><i class="fas fa-hourglass-half me-1"></i><?= $durHuman ?></span>
                  <?php if ($pauseCountInt > 0): ?><span class="badge text-bg-secondary"><i class="fas fa-pause me-1"></i><?= $pauseCountInt ?> pause<?= $pauseCountInt>1?'s':'' ?></span><?php endif; ?>
                </p>
                <div class="alert alert-success py-2 px-3 mb-2"><i class="fas fa-check-circle me-1"></i>Clôturée via rapport final.</div>
                <div class="d-flex gap-2 flex-wrap"><button class="btn btn-sm btn-outline-secondary" disabled><i class="fas fa-play"></i> Démarrer</button><button class="btn btn-sm btn-outline-secondary" disabled><i class="fas fa-pause"></i> Pause</button><button class="btn btn-sm btn-outline-secondary" disabled><i class="fas fa-play"></i> Reprendre</button></div>
              <?php else: ?>
                <div class="alert alert-secondary py-2 small mb-2">
                  <i class="fas fa-info-circle me-1"></i>Aucune intervention en cours. Temps cumulé: <?= $durHuman ?>
                </div>
                <button type="button" id="btnInterventionStart" class="btn btn-sm btn-warning"><i class="fas fa-play"></i> Démarrer</button>
              <?php endif; ?>
              <div class="mt-3 d-flex gap-2 flex-wrap">
                <a class="btn btn-sm btn-outline-secondary" href="<?= htmlspecialchars(route_url('/incidents/intervention/export-csv',['id'=>$incident['id']])) ?>"><i class="fas fa-file-csv"></i> CSV</a>
                <a class="btn btn-sm btn-outline-secondary" href="<?= htmlspecialchars(route_url('/incidents/intervention/export-pdf',['id'=>$incident['id']])) ?>"><i class="fas fa-file-pdf"></i> PDF</a>
                <a class="btn btn-sm btn-outline-info" href="<?= htmlspecialchars(route_url('/incidents/intervention/metrics-pdf',['id'=>$incident['id']])) ?>"><i class="fas fa-chart-line"></i> Métriques</a>
              </div>
              <p class="small text-muted mt-3 mb-0">Toutes les actions sont historisées.</p>
              <?php if ($forceCompleted && $origInterventionState !== 'completed'): ?>
                <p class="text-muted mt-2 mb-0 small"><i class="fas fa-info-circle me-1"></i>Clôture forcée car incident marqué clôturé.</p>
              <?php endif; ?>
            </div>
          </div>
          <?php if ($role === 'admin' && $showAdminQuickReportUI): ?>
          <div class="mt-2">
            <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#adminReportModal">
              <i class="fas fa-file-medical me-1"></i> Ajouter un rapport (Admin)
            </button>
          </div>
          <?php endif; ?>
          <?php } ?>

          <?php // Workflow traitement ?>
          <?php $ts = $treatmentState ?? 'none'; $rep = $treatmentReport ?? null; $workflowStates = [ 'none'=>['label'=>'Aucun','color'=>'secondary'], 'draft'=>['label'=>'Brouillon','color'=>'info'], 'submitted'=>['label'=>'Soumis','color'=>'warning'], 'validated'=>['label'=>'Validé','color'=>'success'], 'rejected'=>['label'=>'Refusé','color'=>'danger'] ]; ?>
          <div class="card shadow-sm">
            <div class="card-header"><h6 class="mb-0"><i class="fas fa-diagram-project me-2"></i>Workflow traitement</h6></div>
            <div class="card-body">
              <div class="d-flex flex-wrap gap-2 mb-3">
                <?php foreach ($workflowStates as $state=>$cfg): ?>
                  <span class="badge text-bg-<?= $cfg['color'] ?><?= $ts===$state?' border border-2 border-dark':'' ?>" style="min-width:90px"><?= htmlspecialchars($cfg['label']) ?></span>
                <?php endforeach; ?>
              </div>
              <?php if ($rep): ?>
                <ul class="list-unstyled small mb-0">
                  <?php if (!empty($rep['submitted_at'])): ?><li><i class="fas fa-paper-plane me-1 text-warning"></i> Soumis le <?= date('d/m/Y H:i', strtotime($rep['submitted_at'])) ?></li><?php elseif ($ts==='draft'): ?><li><i class="fas fa-pencil-alt me-1 text-info"></i> Brouillon (non soumis)</li><?php endif; ?>
                  <?php if (!empty($rep['validated_at'])): ?><li><i class="fas fa-check-circle me-1 text-success"></i> Validé le <?= date('d/m/Y H:i', strtotime($rep['validated_at'])) ?></li><?php elseif (!empty($rep['rejected_at'])): ?><li><i class="fas fa-times-circle me-1 text-danger"></i> Refusé le <?= date('d/m/Y H:i', strtotime($rep['rejected_at'])) ?></li><?php if (!empty($rep['rejection_reason'])): ?><li class="mt-1"><strong>Motif :</strong> <?= nl2br(htmlspecialchars($rep['rejection_reason'])) ?></li><?php endif; ?><?php endif; ?>
                </ul>
              <?php else: ?><p class="text-muted small mb-0">Aucun rapport.</p><?php endif; ?>
              <?php if ($rep && isset($rep['gps_lat'],$rep['gps_lng']) && $rep['gps_lat']!=='' && $rep['gps_lng']!==''): ?>
                <div class="mt-3"><a href="<?= htmlspecialchars(route_url('/interventions/live',['incident_id'=>$incident['id']])) ?>" class="btn btn-sm btn-outline-primary"><i class="fas fa-map-location-dot"></i> Voir sur la carte</a></div>
              <?php endif; ?>
            </div>
          </div>

          <?php // Rapport final ?>
          <?php $frState = $finalReportState ?? 'none'; $fr = $finalReport ?? null; $badgeColor = match($frState){'completed'=>'success','pending'=>'warning',default=>'secondary'}; $badgeLabel = match($frState){'completed'=>'Complété','pending'=>'En attente',default=>'Aucun'}; ?>
          <div class="card shadow-sm">
            <div class="card-header"><h6 class="mb-0"><i class="fas fa-file-signature me-2"></i>Rapport final</h6></div>
            <div class="card-body">
              <p class="mb-2"><span class="badge text-bg-<?= $badgeColor ?>"><?= htmlspecialchars($badgeLabel) ?></span></p>
              <?php if ($fr && !empty($fr['restoration_at'])): ?>
                <p class="small mb-1"><i class="fas fa-clock me-1"></i> Rétabli le <?= date('d/m/Y H:i', strtotime($fr['restoration_at'])) ?></p>
                <div class="d-flex gap-2 flex-wrap"><a class="btn btn-sm btn-outline-secondary" target="_blank" href="<?= htmlspecialchars(route_url('/incidents/final-report/print',['id'=>$incident['id']])) ?>"><i class="fas fa-print"></i> Imprimer</a><a class="btn btn-sm btn-outline-secondary" href="<?= htmlspecialchars(route_url('/incidents/final-report/pdf',['id'=>$incident['id']])) ?>"><i class="fas fa-file-pdf"></i> PDF</a></div>
              <?php elseif ($frState==='pending'): ?><p class="small text-muted mb-1">À compléter.</p><?php else: ?><p class="small text-muted mb-1">Aucune donnée.</p><?php endif; ?>
              <?php if ($canFinalReport): ?><div class="d-grid"><a href="#" data-final-report-modal="1" class="btn btn-sm btn-outline-primary"><i class="fas fa-file-signature"></i> Clôturer (rapport final)</a></div><?php endif; ?>
            </div>
          </div>

          <?php // Prise en charge (masquée si incident clôturé) ?>
          <?php if (!$isIncidentClosed && in_array($role,['technicien','admin'])) {
            try { $pdoTK=\App\Core\Database::pdo(); $stTK=$pdoTK->prepare('SELECT takeover_at FROM users WHERE id=?'); $stTK->execute([(int)($cu['id']??0)]); $takeoverAtCurrent=$stTK->fetchColumn(); } catch (\Throwable $e){ $takeoverAtCurrent=null; }
          ?>
          <div class="card shadow-sm">
            <div class="card-header"><h6 class="mb-0"><i class="fas fa-play me-2"></i>Prise en charge</h6></div>
            <div class="card-body" id="takeoverCardBody">
              <?php if ($takeoverAtCurrent): ?>
                <p class="mb-2"><span class="badge text-bg-warning"><i class="fas fa-clock me-1"></i><?= date('d/m/Y H:i', strtotime($takeoverAtCurrent)) ?></span></p>
                <p class="text-muted small mb-2">Horodatage enregistré.</p>
              <?php else: ?>
                <p class="text-muted small mb-2">Aucune prise en charge.</p>
                <button type="button" id="btnTakeoverCard" class="btn btn-sm btn-warning"><i class="fas fa-play"></i> Enregistrer maintenant</button>
              <?php endif; ?>
              <p class="small text-muted mt-3 mb-0">Début réel d'intervention.</p>
            </div>
          </div>
          <?php } ?>

          <?php // Techniciens assignés + formulaire d'assignation si autorisé ?>
          <?php
            if (!isset($techniciens) || !is_array($techniciens)) {
              try { $pdoU=\App\Core\Database::pdo(); $techniciens=$pdoU->query("SELECT id, name FROM users WHERE active=1 AND role_key='technicien' ORDER BY name")->fetchAll(); } catch (\Throwable $e) { $techniciens=[]; }
            }
          ?>
          <?php if ((!empty($assignedUsers) && is_array($assignedUsers)) || $canAssignTechnician): ?>
          <div class="card shadow-sm">
            <div class="card-header"><h6 class="mb-0"><i class="fas fa-users me-2"></i>Techniciens</h6></div>
            <div class="card-body">
              <?php if (!empty($assignedUsers) && is_array($assignedUsers)): ?>
              <ul class="list-group list-group-flush mb-3">
                <?php foreach ($assignedUsers as $u): ?>
                  <li class="list-group-item small d-flex justify-content-between align-items-center">
                    <span><i class="fas fa-user me-1 text-muted"></i><?= htmlspecialchars($u['name'] ?? 'Technicien') ?></span>
                    <?php if (!empty($u['phone'])): ?><span class="text-muted"><i class="fas fa-phone me-1"></i><?= htmlspecialchars($u['phone']) ?></span><?php endif; ?>
                  </li>
                <?php endforeach; ?>
              </ul>
              <?php else: ?>
                <div class="alert alert-secondary py-2 small mb-3">
                  <i class="fas fa-user-slash me-1"></i>Aucun technicien assigné.
                </div>
              <?php endif; ?>

              <?php if ($canAssignTechnician): ?>
              <form method="post" action="<?= htmlspecialchars(route_url('/incidents/assign')) ?>" class="row g-3 align-items-end">
                <input type="hidden" name="incident_id" value="<?= (int)$incident['id'] ?>">
                <div class="col-12">
                  <?php $assignedIds = array_map(fn($u) => (int)($u['user_id'] ?? 0), is_array($assignedUsers)?$assignedUsers:[]); ?>
                  <div class="form-floating">
                    <select class="form-select" name="user_id" id="assignTechSelect" required>
                      <option value="" selected disabled>— Sélectionner —</option>
                      <?php foreach ($techniciens as $t): $tid=(int)$t['id']; if (in_array($tid,$assignedIds,true)) { continue; } ?>
                        <option value="<?= $tid ?>"><?= htmlspecialchars($t['name'] ?? 'Technicien') ?></option>
                      <?php endforeach; ?>
                    </select>
                    <label for="assignTechSelect">Assigner un technicien</label>
                  </div>
                </div>
                <div class="col-12 d-grid">
                  <button type="submit" class="btn btn-sm btn-primary"><i class="fas fa-user-plus me-1"></i> Assigner</button>
                </div>
              </form>
              <?php else: ?>
                <p class="small text-muted mb-0"><i class="fas fa-lock me-1"></i> Assignation indisponible (statut traité/clôturé).</p>
              <?php endif; ?>
            </div>
          </div>
          <?php endif; ?>

          <?php // Statut incident ?>
          <div class="card shadow-sm">
            <div class="card-header"><h6 class="mb-0"><i class="fas fa-info-circle me-2"></i>Statut</h6></div>
            <div class="card-body">
              <p class="mb-2"><span class="badge" style="background:<?= htmlspecialchars($incident['status_color']) ?>;">
                <?= htmlspecialchars($incident['status_label']) ?></span>
                <span class="badge <?= $priorityClass ?> ms-1">Priorité: <?= htmlspecialchars($incident['priority'] ?? '—') ?></span>
              </p>
              <?php if ($isIncidentClosed): ?><p class="small text-success mb-0"><i class="fas fa-lock me-1"></i>Incident clôturé.</p><?php else: ?><p class="small text-muted mb-0">En cours de traitement.</p><?php endif; ?>
            </div>
          </div>

          <?php // Traitement (accessible même clôturé) ?>
          <div class="card shadow-sm">
            <div class="card-header"><h6 class="mb-0"><i class="fas fa-wrench me-2"></i>Traitement</h6></div>
            <div class="card-body">
              <p class="small mb-2 text-muted">Consultation et export du rapport de traitement.</p>
              <div class="d-flex flex-wrap gap-2">
                <a href="<?= htmlspecialchars(route_url('/incidents/treatment',['id'=>$incident['id'],'view'=>1])) ?>" class="btn btn-sm btn-outline-info"><i class="fas fa-eye"></i> Voir</a>
                <?php if (!empty($treatmentReport) && !empty($treatmentReport['id'])): ?>
                  <a href="<?= htmlspecialchars(route_url('/incidents/treatment/pdf',['id'=>$incident['id']])) ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-file-pdf"></i> PDF</a>
                  <a href="<?= htmlspecialchars(route_url('/incidents/treatment/print',['id'=>$incident['id']])) ?>" target="_blank" class="btn btn-sm btn-outline-secondary"><i class="fas fa-print"></i> Imprimer</a>
                <?php endif; ?>
                <a href="<?= htmlspecialchars(route_url('/incidents/intervention/export-pdf',['id'=>$incident['id']])) ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-chart-line"></i> Intervention PDF</a>
              </div>
            </div>
          </div>

          <?php // Actions rapides (masquées si incident clôturé) ?>
          <?php if (!$isIncidentClosed): ?>
          <div class="card shadow-sm">
            <div class="card-header"><h6 class="mb-0"><i class="fas fa-bolt me-2"></i>Actions rapides</h6></div>
            <div class="card-body">
              <div class="quick-actions">
                <?php if (!empty($canTreat)): ?><a href="<?= htmlspecialchars(route_url('/incidents/treatment',['id'=>$incident['id']])) ?>" class="btn btn-sm btn-outline-success"><i class="fas fa-wrench"></i> Traiter</a><?php endif; ?>
                <?php if (!empty($canViewTreatment)): ?><a href="<?= htmlspecialchars(route_url('/incidents/treatment',['id'=>$incident['id'],'view'=>1])) ?>" class="btn btn-sm btn-outline-info"><i class="fas fa-eye"></i> Voir traitement</a><?php endif; ?>
                <?php if (!empty($canFinalReport)): ?><a href="#" data-bs-toggle="modal" data-bs-target="#finalReportModal" class="btn btn-sm btn-outline-primary"><i class="fas fa-file-signature"></i> Clôturer</a><?php endif; ?>
                <?php if (!empty($finalReport) && !empty($finalReport['restoration_at'])): ?>
                  <a href="<?= htmlspecialchars(route_url('/incidents/final-report/print',['id'=>$incident['id']])) ?>" target="_blank" class="btn btn-sm btn-outline-secondary"><i class="fas fa-print"></i> Imprimer</a>
                  <a href="<?= htmlspecialchars(route_url('/incidents/final-report/pdf',['id'=>$incident['id']])) ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-file-pdf"></i> PDF</a>
                <?php endif; ?>
              </div>
            </div>
          </div>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </div>

  <!-- Commentaires -->
  <div class="tab-pane fade" id="pane-comments" role="tabpanel" aria-labelledby="tab-comments">
    <div class="card shadow-sm mb-4">
      <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0"><i class="fas fa-comments text-muted me-2"></i>Commentaires</h5>
      </div>
      <div class="card-body">
        <?php // Compatibilité: le contrôleur fournit 'commentsTree'; anciens templates utilisaient 'commentTree' ?>
        <?php $tree = isset($commentsTree) && is_array($commentsTree) ? $commentsTree : (isset($commentTree) && is_array($commentTree) ? $commentTree : []); ?>
        <?php
          // Autorisation d'ajout de commentaire: admin/agent toujours; technicien seulement s'il est assigné
          $canAdd = false;
          try {
            $me = \App\Core\Auth::user();
            $roleX = $me['role_key'] ?? '';
            if (in_array($roleX, ['admin','agent'], true)) { $canAdd = true; }
            elseif ($roleX === 'technicien') {
              $pdoX = \App\Core\Database::pdo();
              $chkX = $pdoX->prepare('SELECT COUNT(*) FROM incident_assignments WHERE incident_id=? AND user_id=? AND active=1');
              $chkX->execute([(int)$incident['id'], (int)$me['id']]);
              $canAdd = ((int)$chkX->fetchColumn() > 0);
            }
          } catch (\Throwable $e) { /* ignore */ }
        ?>
        <?php if ($canAdd): ?>
          <form class="mb-3" method="post" action="<?= htmlspecialchars(route_url('/incidents/comment')) ?>" enctype="multipart/form-data">
            <input type="hidden" name="incident_id" value="<?= (int)$incident['id'] ?>">
            <div class="form-floating mb-3">
              <textarea id="commentInput" name="comment" class="form-control" placeholder="Votre commentaire" style="height: 120px" required></textarea>
              <label for="commentInput">Votre commentaire</label>
            </div>
            <div class="d-flex align-items-center gap-3 mb-3 flex-wrap">
              <div class="form-check">
                <input class="form-check-input" type="checkbox" value="1" id="isInternalCheck" name="is_internal">
                <label class="form-check-label" for="isInternalCheck">Interne (non visible côté client)</label>
              </div>
              <div class="flex-grow-1" style="min-width:260px;">
                <label class="form-label mb-1" for="attachmentsInput">Pièces jointes</label>
                <div class="input-group">
                  <span class="input-group-text"><i class="fas fa-paperclip"></i></span>
                  <input type="file" id="attachmentsInput" name="attachments[]" class="form-control" multiple>
                </div>
              </div>
            </div>
            <button type="submit" class="btn btn-sm btn-primary"><i class="fas fa-paper-plane me-1"></i> Publier</button>
          </form>
          <hr>
        <?php endif; ?>
        <?php if (!empty($tree)): ?>
          <ul class="list-unstyled mb-0" id="commentsList">
            <?php foreach ($tree as $c): ?>
              <li class="mb-3 pb-3 border-bottom">
                <div class="d-flex justify-content-between small mb-1">
                  <strong><?= htmlspecialchars($c['user_name'] ?? $c['author_name'] ?? 'Utilisateur') ?></strong>
                  <span class="text-muted" title="<?= !empty($c['created_at']) ? date('d/m/Y H:i', strtotime($c['created_at'])) : '' ?>">
                    <?= !empty($c['created_at']) ? date('d/m H:i', strtotime($c['created_at'])) : '' ?>
                  </span>
                </div>
                <div><?= !empty($c['comment'] ?? $c['content'] ?? '') ? nl2br(htmlspecialchars($c['comment'] ?? $c['content'])) : '<em class="text-muted">(Vide)</em>' ?></div>
                <?php if (!empty($c['attachments']) && is_array($c['attachments'])): ?>
                  <div class="mt-2 small d-flex flex-wrap gap-2">
                    <?php foreach ($c['attachments'] as $att):
                      $raw = is_array($att) ? ($att['path'] ?? '') : $att;
                      $clean = ltrim((string)$raw, '/');
                      if (str_starts_with($clean, 'storage/uploads/')) { $clean = substr($clean, strlen('storage/uploads/')); }
                      $url = upload_url($clean);
                      $ext = strtolower(pathinfo($clean, PATHINFO_EXTENSION));
                      $isImg = in_array($ext, ['jpg','jpeg','png','gif','webp'], true);
                    ?>
                      <?php if ($isImg): ?>
                        <a href="<?= htmlspecialchars($url) ?>" data-file-url="<?= htmlspecialchars($url) ?>" class="d-inline-block js-open-file">
                          <img src="<?= htmlspecialchars($url) ?>" class="img-thumbnail" style="max-height:100px" alt="pièce jointe">
                        </a>
                      <?php else: ?>
                        <a href="<?= htmlspecialchars($url) ?>" data-file-url="<?= htmlspecialchars($url) ?>" class="btn btn-sm btn-outline-secondary js-open-file"><i class="fas fa-paperclip me-1"></i> PJ</a>
                      <?php endif; ?>
                    <?php endforeach; ?>
                  </div>
                <?php endif; ?>
              </li>
            <?php endforeach; ?>
          </ul>
        <?php elseif (!empty($comments) && is_array($comments)): ?>
          <ul class="list-unstyled mb-0" id="commentsList">
            <?php foreach ($comments as $c): ?>
              <li class="mb-3 pb-3 border-bottom">
                <div class="d-flex justify-content-between small mb-1">
                  <strong><?= htmlspecialchars($c['user_name'] ?? $c['author_name'] ?? 'Utilisateur') ?></strong>
                  <span class="text-muted" title="<?= !empty($c['created_at']) ? date('d/m/Y H:i', strtotime($c['created_at'])) : '' ?>">
                    <?= !empty($c['created_at']) ? date('d/m H:i', strtotime($c['created_at'])) : '' ?>
                  </span>
                </div>
                <div><?= !empty($c['comment'] ?? $c['content'] ?? '') ? nl2br(htmlspecialchars($c['comment'] ?? $c['content'])) : '<em class="text-muted">(Vide)</em>' ?></div>
                <?php if (!empty($c['attachments']) && is_array($c['attachments'])): ?>
                  <div class="mt-2 small d-flex flex-wrap gap-2">
                    <?php foreach ($c['attachments'] as $att):
                      $raw = is_array($att) ? ($att['path'] ?? '') : $att;
                      $clean = ltrim((string)$raw, '/');
                      if (str_starts_with($clean, 'storage/uploads/')) { $clean = substr($clean, strlen('storage/uploads/')); }
                      $url = upload_url($clean);
                      $ext = strtolower(pathinfo($clean, PATHINFO_EXTENSION));
                      $isImg = in_array($ext, ['jpg','jpeg','png','gif','webp'], true);
                    ?>
                      <?php if ($isImg): ?>
                        <a href="<?= htmlspecialchars($url) ?>" data-file-url="<?= htmlspecialchars($url) ?>" class="d-inline-block js-open-file">
                          <img src="<?= htmlspecialchars($url) ?>" class="img-thumbnail" style="max-height:100px" alt="pièce jointe">
                        </a>
                      <?php else: ?>
                        <a href="<?= htmlspecialchars($url) ?>" data-file-url="<?= htmlspecialchars($url) ?>" class="btn btn-sm btn-outline-secondary js-open-file"><i class="fas fa-paperclip me-1"></i> PJ</a>
                      <?php endif; ?>
                    <?php endforeach; ?>
                  </div>
                <?php endif; ?>
              </li>
            <?php endforeach; ?>
          </ul>
        <?php else: ?>
          <p class="text-muted mb-0" id="noCommentsMsg">Aucun commentaire.</p>
        <?php endif; ?>
      </div>
    </div>
  </div>

  <!-- Historique -->
  <div class="tab-pane fade" id="pane-history" role="tabpanel" aria-labelledby="tab-history">
    <div class="card shadow-sm mb-4">
      <div class="card-header"><h5 class="mb-0"><i class="fas fa-clock-rotate-left text-muted me-2"></i>Historique</h5></div>
      <div class="card-body history-scroll">
        <?php if (!empty($history) && is_array($history)): ?>
          <ul class="list-unstyled mb-0">
            <?php foreach ($history as $h): ?>
              <?php
                // Normaliser les champs selon incident_history (field_name, old_value, new_value, changed_at, changed_by_name)
                $field = trim($h['field_name'] ?? ($h['event_label'] ?? ''));
                $newVal = trim($h['new_value'] ?? ($h['details'] ?? ''));
                $oldVal = trim($h['old_value'] ?? '');
                $when = $h['changed_at'] ?? ($h['created_at'] ?? null);
                $by = trim($h['changed_by_name'] ?? '');
                // Construire label lisible
                $label = $field !== '' ? $field : 'Événement';
                // Construire détails lisibles: préférer new_value; si old_value présent, afficher la transition
                $details = '';
                if ($newVal !== '' && $oldVal !== '') {
                  $details = 'Ancien: ' . $oldVal . "\nNouveau: " . $newVal;
                } elseif ($newVal !== '') { $details = $newVal; }
                elseif ($oldVal !== '') { $details = 'Ancien: ' . $oldVal; }
                // Enrichir avec auteur si disponible
                if ($by !== '') { $details = ($details !== '' ? $details . "\n" : '') . '(par ' . $by . ')'; }
                // Filtrer entrées totalement vides
                if ($label === '' && $details === '') { continue; }
              ?>
              <li class="mb-3 pb-3 border-bottom">
                <div class="d-flex justify-content-between small mb-1">
                  <?php
                    $badgeColor = 'secondary';
                    $fname = mb_strtolower($field);
                    if (str_contains($fname, 'intervention')) { $badgeColor = 'info'; }
                    elseif (str_contains($fname, 'status') || str_contains($fname, 'statut')) { $badgeColor = 'primary'; }
                    elseif (str_contains($fname, 'finalreport') || str_contains($fname, 'rapport')) { $badgeColor = 'success'; }
                    elseif (str_contains($fname, 'action')) { $badgeColor = 'warning'; }
                  ?>
                  <span class="badge text-bg-<?= $badgeColor ?>" style="min-width: 110px;"><?= htmlspecialchars($label) ?></span>
                  <span class="text-muted" title="<?= $when ? date('d/m/Y H:i', strtotime($when)) : '' ?>">
                    <?= $when ? date('d/m H:i', strtotime($when)) : '' ?>
                  </span>
                </div>
                <?php if ($details !== ''): ?>
                  <div class="small">><?= nl2br(htmlspecialchars($details)) ?></div>
                <?php endif; ?>
              </li>
            <?php endforeach; ?>
          </ul>
        <?php else: ?>
          <p class="text-muted mb-0">Aucun événement historisé.</p>
        <?php endif; ?>
      </div>
    </div>
  </div>

<!-- Modal aperçu fichier -->
<div class="modal fade" id="filePreviewModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><i class="fas fa-file me-2"></i> Aperçu</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fermer"></button>
      </div>
      <div class="modal-body p-0" id="filePreviewBody">
        <iframe id="filePreviewFrame" src="" class="w-100 border-0" style="height:70vh; background:#fff"></iframe>
      </div>
      <div class="modal-footer">
        <a id="fileDownloadLink" href="#" class="btn btn-primary" target="_blank"><i class="fas fa-download me-1"></i> Ouvrir</a>
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Fermer</button>
      </div>
    </div>
  </div>
</div>

<?php if ($canFinalReport): ?>
<style>.modal-backdrop.show{backdrop-filter:blur(3px);background-color:rgba(0,0,0,0.25);} .modal-lg{max-width:720px;} .form-text{font-size:.85rem;} .form-floating>textarea.form-control{height:120px;}</style>
<div class="modal fade" id="finalReportModal" tabindex="-1" aria-hidden="true"><div class="modal-dialog modal-lg modal-dialog-centered"><div class="modal-content"><div class="modal-header"><h5 class="modal-title"><i class="fas fa-file-signature me-2"></i> Rapport final</h5><button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fermer"></button></div><div class="modal-body"><form id="finalReportForm" method="post" action="<?= htmlspecialchars(route_url('/incidents/final-report/save')) ?>" enctype="multipart/form-data"><input type="hidden" name="incident_id" value="<?= (int)$incident['id'] ?>"><div class="row g-3">
  <div class="col-12 col-md-6">
    <label class="form-label">Date et heure de remontée</label>
    <div class="input-group">
      <span class="input-group-text"><i class="far fa-calendar"></i></span>
      <?php $valFR = (!empty($finalReport['restoration_at']) ? date('Y-m-d\TH:i', strtotime($finalReport['restoration_at'])) : ''); ?>
      <input type="datetime-local" name="restoration_at" class="form-control" value="<?= htmlspecialchars($valFR) ?>" required>
    </div>
    <div class="form-text">Horodatage de rétablissement.</div>
  </div>
  <div class="col-12 col-md-6">
    <div class="form-floating">
      <input id="fr_tech" type="text" class="form-control" value="<?= htmlspecialchars($cu['name'] ?? 'Technicien') ?>" disabled placeholder=" ">
      <label for="fr_tech">Technicien</label>
    </div>
  </div>
  <div class="col-12 col-md-6">
    <div class="form-floating">
      <input id="fr_client_supervisor" type="text" name="client_supervisor" class="form-control" value="<?= htmlspecialchars($finalReport['client_supervisor'] ?? '') ?>" placeholder="Nom superviseur côté client">
      <label for="fr_client_supervisor">Superviseur Client</label>
    </div>
    <div class="form-text">Saisi manuellement.</div>
  </div>
  <div class="col-12">
    <div class="form-floating">
      <textarea id="fr_comments" name="comments" class="form-control" placeholder="Observations finales..."><?= htmlspecialchars($finalReport['comments'] ?? '') ?></textarea>
      <label for="fr_comments">Commentaire</label>
    </div>
  </div>
  <div class="col-12">
    <label class="form-label mb-1">Pièces jointes</label>
    <div class="input-group">
      <span class="input-group-text"><i class="fas fa-paperclip"></i></span>
      <input type="file" name="final_attachments[]" class="form-control" multiple>
    </div>
    <div class="form-text">Images, PDF...</div>
  </div>
</div></form><?php
  try { $pdoFR = \App\Core\Database::pdo(); $stFR = $pdoFR->prepare('SELECT a.path FROM incident_final_report_attachments a JOIN incident_final_reports fr ON fr.id=a.final_report_id WHERE fr.incident_id=? ORDER BY a.id ASC'); $stFR->execute([(int)$incident['id']]); $rowsFR=$stFR->fetchAll(); } catch (\Throwable $e) { $rowsFR=[]; }
  if (!empty($rowsFR)) { echo '<div class="mt-3"><label class="form-label">Pièces jointes existantes</label><div class="d-flex flex-wrap gap-2">'; foreach ($rowsFR as $r){ $p=$r['path']; $clean=ltrim($p,'/'); if(str_starts_with($clean,'storage/uploads/')) $clean=substr($clean,strlen('storage/uploads/')); if(!str_starts_with($clean,'incidents/')) $clean='incidents/'.$incident['id'].'/final/'.basename($clean); $url=upload_url($clean); echo '<a class="btn btn-sm btn-outline-secondary js-open-file" data-file-url="'.htmlspecialchars($url).'" href="'.htmlspecialchars($url).'"><i class="fas fa-paperclip me-1"></i> PJ</a>'; } echo '</div></div>'; }
?></div><div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button><button type="submit" form="finalReportForm" class="btn btn-primary"><i class="fas fa-check me-1"></i> Enregistrer et clôturer</button></div></div></div></div>
<?php endif; ?>

<?php if ($role === 'admin' && $showAdminQuickReportUI): ?>
<!-- Modale: Création rapide d'un rapport (Admin) -->
<style>.modal-lg{max-width:900px}</style>
<?php
  // Pré-remplir avec les données du rapport existant
  $rTeamName = !empty($treatmentReport['team_name']) ? $treatmentReport['team_name'] : ($cu['name'] ?? 'Admin');
  $rTeamContact = !empty($treatmentReport['team_contact']) ? $treatmentReport['team_contact'] : ($cu['phone'] ?? ($cu['email'] ?? ''));
  $rType = $treatmentReport['type_of_incident'] ?? '';
  $rDetection = $treatmentReport['detection_mode'] ?? '';
  $rCutKm = $treatmentReport['cut_distance_km'] ?? '';
  $rGpsLat = $treatmentReport['gps_lat'] ?? '';
  $rGpsLng = $treatmentReport['gps_lng'] ?? '';
  $rFault = $treatmentReport['fault_nature'] ?? '';
  $rRepairType = $treatmentReport['repair_type'] ?? '';
  $rWorkComments = $treatmentReport['work_comments'] ?? '';
  
  // Dates au format datetime-local (Y-m-d\TH:i)
  $rTakeover = '';
  if (!empty($treatmentReport['takeover_at'])) {
    $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $treatmentReport['takeover_at']);
    if ($dt) $rTakeover = $dt->format('Y-m-d\TH:i');
  }
  $rStart = '';
  if (!empty($treatmentReport['intervention_start'])) {
    $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $treatmentReport['intervention_start']);
    if ($dt) $rStart = $dt->format('Y-m-d\TH:i');
  }
  $rEnd = '';
  if (!empty($treatmentReport['intervention_end'])) {
    $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $treatmentReport['intervention_end']);
    if ($dt) $rEnd = $dt->format('Y-m-d\TH:i');
  }
  
  // Équipements impactés: JSON → string séparée par virgules
  $rImpacted = '';
  if (!empty($treatmentReport['impacted_equipment'])) {
    $arr = @json_decode($treatmentReport['impacted_equipment'], true);
    if (is_array($arr)) {
      $rImpacted = implode(', ', array_filter($arr));
    }
  }
?>
<div class="modal fade" id="adminReportModal" tabindex="-1" aria-labelledby="adminReportLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title" id="adminReportLabel"><i class="fas fa-file-medical me-2"></i> Rapport de traitement — <?= htmlspecialchars($incident['ticket_id']) ?></h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Fermer"></button>
      </div>
      <form id="adminReportForm" method="post" action="<?= htmlspecialchars(route_url('/incidents/treatment/save')) ?>" enctype="multipart/form-data">
        <input type="hidden" name="incident_id" value="<?= (int)$incident['id'] ?>">
        <div class="modal-body">
          <?php if (!empty($treatmentReport)): ?>
            <div class="alert alert-info mb-3">
              <i class="fas fa-info-circle me-2"></i>
              Les champs sont pré-remplis avec les données validées du traitement. 
              <strong>Seul l'ajout d'un rapport final (fichier) permet de clôturer l'incident.</strong>
            </div>
          <?php endif; ?>
          
          <div class="row g-3">
            <div class="col-12 col-md-6">
              <div class="form-floating">
                <input type="text" class="form-control" id="ar_team_name" name="team_name" value="<?= htmlspecialchars($rTeamName) ?>" placeholder=" " readonly>
                <label for="ar_team_name">Équipe / Auteur</label>
              </div>
            </div>
            <div class="col-12 col-md-6">
              <div class="form-floating">
                <input type="text" class="form-control" id="ar_team_contact" name="team_contact" value="<?= htmlspecialchars($rTeamContact) ?>" placeholder=" " readonly>
                <label for="ar_team_contact">Contact</label>
              </div>
            </div>

            <div class="col-12 col-md-4">
              <div class="form-floating">
                <input type="text" class="form-control" id="ar_type" name="type_of_incident" value="<?= htmlspecialchars($rType) ?>" placeholder=" " readonly>
                <label for="ar_type">Type d'incident</label>
              </div>
            </div>
            <div class="col-12 col-md-4">
              <div class="form-floating">
                <input type="text" class="form-control" id="ar_detection" name="detection_mode" value="<?= htmlspecialchars($rDetection) ?>" placeholder=" " readonly>
                <label for="ar_detection">Mode de détection</label>
              </div>
            </div>
            <div class="col-12 col-md-4">
              <div class="form-floating">
                <input type="number" step="0.01" class="form-control" id="ar_cut_km" name="cut_distance_km" value="<?= htmlspecialchars($rCutKm) ?>" placeholder=" " readonly>
                <label for="ar_cut_km">Distance de coupure (km)</label>
              </div>
            </div>

            <div class="col-12 col-md-6">
              <div class="form-floating">
                <input type="number" step="0.000001" class="form-control" id="ar_gps_lat" name="gps_lat" value="<?= htmlspecialchars($rGpsLat) ?>" placeholder=" " readonly>
                <label for="ar_gps_lat">GPS Latitude</label>
              </div>
            </div>
            <div class="col-12 col-md-6">
              <div class="form-floating">
                <input type="number" step="0.000001" class="form-control" id="ar_gps_lng" name="gps_lng" value="<?= htmlspecialchars($rGpsLng) ?>" placeholder=" " readonly>
                <label for="ar_gps_lng">GPS Longitude</label>
              </div>
            </div>

            <div class="col-12 col-md-4">
              <label class="form-label">Prise en charge</label>
              <div class="input-group">
                <span class="input-group-text"><i class="far fa-calendar"></i></span>
                <input type="datetime-local" class="form-control" name="takeover_at" value="<?= htmlspecialchars($rTakeover) ?>" readonly>
              </div>
            </div>
            <div class="col-12 col-md-4">
              <label class="form-label">Début intervention</label>
              <div class="input-group">
                <span class="input-group-text"><i class="far fa-calendar"></i></span>
                <input type="datetime-local" class="form-control" name="intervention_start" value="<?= htmlspecialchars($rStart) ?>" readonly>
              </div>
            </div>
            <div class="col-12 col-md-4">
              <label class="form-label">Fin intervention</label>
              <div class="input-group">
                <span class="input-group-text"><i class="far fa-calendar"></i></span>
                <input type="datetime-local" class="form-control" name="intervention_end" value="<?= htmlspecialchars($rEnd) ?>" readonly>
              </div>
            </div>

            <div class="col-12 col-md-6">
              <div class="form-floating">
                <input type="text" class="form-control" id="ar_repair_type" name="repair_type" value="<?= htmlspecialchars($rRepairType) ?>" placeholder=" " readonly>
                <label for="ar_repair_type">Type de réparation</label>
              </div>
            </div>
            <div class="col-12 col-md-6">
              <div class="form-floating">
                <input type="text" class="form-control" id="ar_fault" name="fault_nature" value="<?= htmlspecialchars($rFault) ?>" placeholder=" " readonly>
                <label for="ar_fault">Nature de la panne</label>
              </div>
            </div>

            <div class="col-12">
              <div class="form-floating">
                <input type="text" class="form-control" id="ar_impacted" value="<?= htmlspecialchars($rImpacted) ?>" placeholder="Routeur, PTO, Boîtier" readonly />
                <label for="ar_impacted">Équipements impactés</label>
              </div>
            </div>

            <div class="col-12">
              <div class="form-floating">
                <textarea class="form-control" id="ar_work_comments" name="work_comments" placeholder=" " style="height: 110px" readonly><?= htmlspecialchars($rWorkComments) ?></textarea>
                <label for="ar_work_comments">Observations / Travaux effectués</label>
              </div>
            </div>

            <hr class="my-4">
            
            <div class="col-12">
              <h6 class="text-primary mb-3"><i class="fas fa-file-upload me-2"></i>Clôture de l'incident</h6>
              <div class="alert alert-warning">
                <i class="fas fa-exclamation-triangle me-2"></i>
                <strong>Important :</strong> L'upload d'un rapport final (PDF, Word, etc.) permettra de clôturer définitivement cet incident.
              </div>
            </div>

            <div class="col-12">
              <label class="form-label fw-bold">Rapport final de clôture <span class="text-danger">*</span></label>
              <div class="input-group">
                <span class="input-group-text"><i class="fas fa-file-pdf"></i></span>
                <input type="file" class="form-control" name="closure_report" id="ar_closure_report" accept=".pdf,.doc,.docx" required>
              </div>
              <div class="form-text">Formats acceptés : PDF, Word. Requis pour clôturer l'incident.</div>
            </div>

            <div class="col-12">
              <div class="form-floating">
                <textarea class="form-control" id="ar_closure_notes" name="closure_notes" placeholder=" " rows="3"></textarea>
                <label for="ar_closure_notes">Notes de clôture (optionnel)</label>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button>
          <button type="submit" class="btn btn-success" id="ar_submit_btn">
            <i class="fas fa-check-circle me-1"></i> Clôturer l'incident
          </button>
        </div>
      </form>
    </div>
  </div>
  <script>
    // Transformer la liste d'équipements en inputs [] avant l'envoi
    (function(){
      const form = document.getElementById('adminReportForm');
      form && form.addEventListener('submit', function(ev){
        const txt = document.getElementById('ar_impacted');
        if (!txt) return;
        const raw = (txt.value || '').split(',');
        raw.map(s => s.trim()).filter(Boolean).forEach(val => {
          const inp = document.createElement('input');
          inp.type = 'hidden';
          inp.name = 'impacted_equipment[]';
          inp.value = val;
          form.appendChild(inp);
        });
      });
    })();
  </script>
</div>
<?php endif; ?>

<!-- Modal motif de pause -->
<div class="modal fade" id="pauseReasonModal" tabindex="-1" aria-labelledby="pauseReasonLabel" aria-hidden="true"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h5 class="modal-title" id="pauseReasonLabel"><i class="fas fa-pause me-2"></i> Motif de mise en pause</h5><button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fermer"></button></div><div class="modal-body"><div class="mb-2"><label for="pauseReasonInput" class="form-label">Motif (obligatoire)</label><textarea id="pauseReasonInput" class="form-control" rows="3" placeholder="Ex: Attente matériel..."></textarea></div><div id="pauseReasonError" class="text-danger small d-none">Le motif est requis.</div></div><div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button><button type="button" id="pauseReasonSubmit" class="btn btn-warning"><i class="fas fa-check me-1"></i> Valider la pause</button></div></div></div></div>

<!-- Modal confirmation suppression incident -->
<div class="modal fade" id="deleteIncidentModal" tabindex="-1" aria-labelledby="deleteIncidentLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content border-0 shadow">
      <div class="modal-header bg-danger text-white border-0">
        <h5 class="modal-title" id="deleteIncidentLabel">
          <i class="fas fa-exclamation-triangle me-2"></i>
          Confirmer la suppression
        </h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Fermer"></button>
      </div>
      <div class="modal-body p-4">
        <div class="alert alert-warning border-0 mb-3">
          <i class="fas fa-info-circle me-2"></i>
          <strong>Attention !</strong> Cette action est irréversible.
        </div>
        <p class="mb-2">Êtes-vous sûr de vouloir supprimer cet incident ?</p>
        <p class="text-muted small mb-0">
          <i class="fas fa-trash-alt me-1"></i>
          Toutes les données associées seront définitivement supprimées :
        </p>
        <ul class="text-muted small mt-2 mb-0">
          <li>Commentaires et réponses</li>
          <li>Pièces jointes</li>
          <li>Historique des modifications</li>
          <li>Assignations de techniciens</li>
        </ul>
      </div>
      <div class="modal-footer border-0 bg-light">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
          <i class="fas fa-times me-1"></i> Annuler
        </button>
        <button type="button" class="btn btn-danger" id="confirmDeleteIncidentBtn">
          <i class="fas fa-trash-alt me-1"></i> Supprimer définitivement
        </button>
      </div>
    </div>
  </div>
</div>

<!-- (Supprimé) doublon du modal motif de pause -->

<script>
// Modal et fonction de confirmation de suppression d'incident
let deleteIncidentModal = null;
let incidentIdToDelete = null;

function confirmDeleteIncident(incidentId) {
  incidentIdToDelete = incidentId;
  if (!deleteIncidentModal) {
    deleteIncidentModal = new bootstrap.Modal(document.getElementById('deleteIncidentModal'));
  }
  deleteIncidentModal.show();
}

// Gérer la confirmation de suppression
document.addEventListener('DOMContentLoaded', function() {
  // Active le bon onglet Bootstrap si un hash est présent (ex: #pane-comments)
  (function(){
    const hash = window.location.hash;
    if (hash) {
      const tabTriggerEl = document.querySelector(`button[data-bs-target="${hash}"]`);
      if (tabTriggerEl) {
        try { new bootstrap.Tab(tabTriggerEl).show(); } catch(e) { /* ignore */ }
      }
    }
    // Conserver le hash à chaque changement d'onglet
    document.querySelectorAll('button[data-bs-toggle="tab"]').forEach(btn=>{
      btn.addEventListener('shown.bs.tab', e => {
        const target = e.target?.getAttribute('data-bs-target');
        if (target && history.replaceState) { history.replaceState(null, '', target); }
      });
    });
  })();
  const confirmBtn = document.getElementById('confirmDeleteIncidentBtn');
  if (confirmBtn) {
    confirmBtn.addEventListener('click', function() {
      if (incidentIdToDelete) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = '<?= htmlspecialchars(route_url('/incidents/delete')) ?>';
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'incident_id';
        input.value = incidentIdToDelete;
        form.appendChild(input);
        document.body.appendChild(form);
        form.submit();
      }
    });
  }

  // Gestion des actions d'intervention (start/pause/resume)
  const btnStart = document.getElementById('btnInterventionStart');
  const btnPause = document.getElementById('btnInterventionPause');
  const btnResume = document.getElementById('btnInterventionResume');
  const incidentId = <?= (int)$incident['id'] ?>;
  const cardBody = document.getElementById('interventionCardBody');
  const pauseReasonModalEl = document.getElementById('pauseReasonModal');
  const pauseReasonInput = document.getElementById('pauseReasonInput');
  const confirmPauseBtn = document.getElementById('confirmPauseBtn');
  const pauseReasonSubmitBtn = document.getElementById('pauseReasonSubmit'); // compat bouton alternatif
  let pauseModal = null;
  if (pauseReasonModalEl) { pauseModal = new bootstrap.Modal(pauseReasonModalEl); }

  async function postIntervention(action, extraParams) {
    const urlMap = {
      start: '<?= htmlspecialchars(route_url('/incidents/intervention/start')) ?>',
      pause: '<?= htmlspecialchars(route_url('/incidents/intervention/pause')) ?>',
      resume: '<?= htmlspecialchars(route_url('/incidents/intervention/resume')) ?>'
    };
    const params = new URLSearchParams({ incident_id: String(incidentId), ajax: '1' });
    if (extraParams) {
      Object.entries(extraParams).forEach(([k, v]) => { if (v !== undefined && v !== null) params.append(k, v); });
    }
    try {
      const resp = await fetch(urlMap[action], {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'X-Requested-With': 'XMLHttpRequest' },
        body: params.toString(),
        credentials: 'same-origin'
      });
      const data = await resp.json().catch(() => ({}));
      if (resp.ok && data && data.status === 'ok') {
        // Mise à jour rapide de l'UI sans rechargement
        updateInterventionUI(action, data);
      } else {
        const msg = (data && data.message) ? data.message : 'Action intervention échouée.';
        alert(msg);
      }
    } catch (e) {
      alert('Impossible d\'effectuer l\'action d\'intervention.');
    }
  }

  function updateInterventionUI(action, data) {
    if (!cardBody) { location.reload(); return; }
    // Reconstruire les badges d'état + boutons
    const duration = (data && data.duration_human) ? data.duration_human : '';
    const pauseCountTxt = ''; // pour simplifier côté client; valeurs exactes seront recalculées côté serveur
    let html = '';
    if (action === 'start' || action === 'resume') {
      html += '<p class="mb-2 d-flex flex-wrap align-items-center gap-2">'
           + '<span class="badge text-bg-success"><i class="fas fa-person-digging me-1"></i> En cours</span>'
           + '<span class="badge text-bg-primary"><i class="fas fa-hourglass-half me-1"></i>' + (duration || '') + '</span>'
           + (pauseCountTxt || '')
           + '</p>'
           + '<button type="button" id="btnInterventionPause" class="btn btn-sm btn-outline-warning"><i class="fas fa-pause"></i> Mettre en pause</button>';
    } else if (action === 'pause') {
      const reason = (data && data.label && data.label.includes('Motif:')) ? data.label.split('Motif:').slice(1).join('Motif:').trim() : '';
      html += '<p class="mb-2 d-flex flex-wrap align-items-center gap-2">'
           + '<span class="badge text-bg-secondary"><i class="fas fa-pause me-1"></i> En pause</span>'
           + '<span class="badge text-bg-primary"><i class="fas fa-hourglass-half me-1"></i>' + (duration || '') + '</span>'
           + (pauseCountTxt || '')
           + '</p>'
           + (reason ? '<div class="alert alert-secondary py-2 px-3 mb-2"><i class="fas fa-comment-dots me-1"></i><strong>Motif:</strong> ' + reason.replace(/</g,'&lt;') + '</div>' : '')
           + '<button type="button" id="btnInterventionResume" class="btn btn-sm btn-outline-success"><i class="fas fa-play"></i> Reprendre</button>';
    }
    // Conserver la zone d'actions/exports et les mentions
    const extras = cardBody.querySelector('.mt-3.d-flex.gap-2.flex-wrap')?.outerHTML || '';
    const note = Array.from(cardBody.querySelectorAll('p.small.text-muted')).map(n=>n.outerHTML).join('');
    cardBody.innerHTML = html + extras + note;
    // Réattacher les listeners
    const newPause = document.getElementById('btnInterventionPause');
    const newResume = document.getElementById('btnInterventionResume');
    if (newPause) {
      newPause.addEventListener('click', () => {
        pauseReasonInput && (pauseReasonInput.value = '');
        pauseModal && pauseModal.show();
      });
    }
    if (newResume) {
      newResume.addEventListener('click', () => { postIntervention('resume'); });
    }
  }

  if (btnStart) {
    btnStart.addEventListener('click', () => {
      postIntervention('start');
    });
  }
  if (btnPause) {
    btnPause.addEventListener('click', () => {
      if (!pauseModal) { alert('Modal non disponible'); return; }
      pauseReasonInput && (pauseReasonInput.value = '');
      pauseModal.show();
    });
  }
  if (btnResume) {
    btnResume.addEventListener('click', () => {
      postIntervention('resume');
    });
  }

  function onPauseConfirm() {
    const val = (pauseReasonInput ? String(pauseReasonInput.value).trim() : '');
    if (!val) { alert('Merci de renseigner un motif.'); return; }
    postIntervention('pause', { reason: val }).then(() => { pauseModal && pauseModal.hide(); });
  }
  if (confirmPauseBtn) { confirmPauseBtn.addEventListener('click', onPauseConfirm); }
  if (pauseReasonSubmitBtn) { pauseReasonSubmitBtn.addEventListener('click', onPauseConfirm); }

  // Soumission AJAX des commentaires (rester dans l'onglet)
  const commentForm = document.querySelector('#pane-comments form[action*="/incidents/comment"]');
  if (commentForm) {
    const commentsList = document.getElementById('commentsList');
    const noCommentsMsg = document.getElementById('noCommentsMsg');
    const submitBtn = commentForm.querySelector('button[type="submit"]');
    const uploadBase = '<?= htmlspecialchars(rtrim(upload_url(""), "/")) ?>';

    commentForm.addEventListener('submit', async function (e) {
      e.preventDefault();
      const fd = new FormData(commentForm);
      fd.append('ajax', '1');
      if (submitBtn) { submitBtn.disabled = true; submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> Publication...'; }
      try {
        const resp = await fetch(commentForm.action, {
          method: 'POST',
          body: fd,
          headers: { 'X-Requested-With': 'XMLHttpRequest' },
          credentials: 'same-origin'
        });
        const data = await resp.json().catch(() => ({}));
        if (resp.ok && data && data.status === 'ok' && data.comment) {
          // Nettoyer le formulaire
          commentForm.reset();
          // Construire l'élément de commentaire
          const c = data.comment;
          const userName = (c.user_name ? String(c.user_name) : 'Vous').replace(/</g, '&lt;');
          const when = c.created_at ? String(c.created_at) : '';
          const content = (c.comment ? String(c.comment) : '').replace(/</g, '&lt;').replace(/\n/g, '<br>');

          let attHtml = '';
          if (Array.isArray(c.attachments) && c.attachments.length > 0) {
            const links = c.attachments.map(function(p) {
              let path = String(p || '').replace(/^\/+/, '');
              path = path.replace(/^storage\/uploads\//, '');
              const href = uploadBase + '/' + encodeURI(path);
              const ext = (path.split('.').pop() || '').toLowerCase();
              const isImg = ['jpg','jpeg','png','gif','webp'].includes(ext);
              if (isImg) {
                return '<a href="' + href + '" data-file-url="' + href + '" class="d-inline-block js-open-file"><img src="' + href + '" class="img-thumbnail" style="max-height:100px" alt="pièce jointe"></a>';
              }
              return '<a href="' + href + '" data-file-url="' + href + '" class="btn btn-sm btn-outline-secondary js-open-file"><i class="fas fa-paperclip me-1"></i> PJ</a>';
            }).join('');
            attHtml = '<div class="mt-2 small d-flex flex-wrap gap-2">' + links + '</div>';
          }

          const li = document.createElement('li');
          li.className = 'mb-3 pb-3 border-bottom';
          li.innerHTML =
            '<div class="d-flex justify-content-between small mb-1">' +
              '<strong>' + userName + '</strong>' +
              '<span class="text-muted">' + when + '</span>' +
            '</div>' +
            '<div>' + (content || '<em class="text-muted">(Vide)</em>') + '</div>' +
            attHtml;

          if (commentsList) {
            commentsList.insertBefore(li, commentsList.firstChild);
          } else {
            const ul = document.createElement('ul');
            ul.id = 'commentsList';
            ul.className = 'list-unstyled mb-0';
            ul.appendChild(li);
            commentForm.insertAdjacentElement('afterend', ul);
          }
          if (noCommentsMsg) { noCommentsMsg.remove(); }
        } else {
          const msg = (data && data.message) ? data.message : 'Publication du commentaire échouée.';
          alert(msg);
        }
      } catch (err) {
        alert('Impossible de publier le commentaire.');
      } finally {
        if (submitBtn) { submitBtn.disabled = false; submitBtn.innerHTML = '<i class="fas fa-paper-plane me-1"></i> Publier'; }
      }
    });
  }
  // Délégation : ouverture des fichiers en modal
  (function(){
    const modalEl = document.getElementById('filePreviewModal');
    const frame = document.getElementById('filePreviewFrame');
    const dl = document.getElementById('fileDownloadLink');
    let modal;
    if (modalEl) { modal = new bootstrap.Modal(modalEl); }
    document.addEventListener('click', function(e){
      const a = e.target.closest && e.target.closest('a.js-open-file');
      if (!a) return;
      e.preventDefault();
      const url = a.getAttribute('data-file-url') || a.getAttribute('href');
      if (!url || !frame) return;
      frame.src = url;
      if (dl) dl.href = url;
      modal && modal.show();
    });
  })();
});
</script>

</div>
