<?php 
use App\Core\Auth;
$safeTicket = htmlspecialchars((string)($incident['ticket_id'] ?? ($incident['reference'] ?? ('INC-' . (int)($incident['id'] ?? 0)))));
$title = 'Rapport de traitement - ' . $safeTicket;
// Données utiles
$equipSel = [];
if (!empty($report['impacted_equipment'])) {
  $dec = json_decode($report['impacted_equipment'], true);
  if (is_array($dec)) { $equipSel = array_map('strval', $dec); }
}
$rootPath = dirname(__DIR__, 3); // Racine du projet
$logoRelative = '/public/assets/img/novalink-logo.png';
$logoFs = $rootPath . str_replace('/', DIRECTORY_SEPARATOR, $logoRelative);
$logoUrl = is_file($logoFs) ? route_url('/assets/img/novalink-logo.png') : null; // affiche seulement si présent
$today = date('d/m/Y');
?>
<style>
  @media print {
    .no-print { display:none !important; }
    .page-break { page-break-before: always; }
    header.print-header, footer.print-footer { position: fixed; left: 0; right: 0; color: #888; }
    header.print-header { top: 0; height: 60px; }
    footer.print-footer { bottom: 0; height: 40px; }
    body { margin-top: 80px; margin-bottom: 60px; }
    .pagenum:before { content: counter(page); }
  }
  /* Couverture */
  .cover { display:flex; align-items:center; justify-content:center; height:70vh; flex-direction:column; text-align:center; background: #f8f9fa; border: 1px solid #e9ecef; }
  .cover-logo { max-height: 80px; margin-bottom: 1rem; }
  .subtitle { color:#6c757d; }
  .meta { color:#495057; }
  .hr-title { border-top: 2px solid #0d6efd; width: 120px; margin: 1rem auto 0; }
  /* Sommaire */
  .toc li { margin-bottom: .25rem; }
  /* Tableaux propres */
  table.table { width:100%; border-collapse:collapse; }
  .table th, .table td { padding:.5rem .75rem; border:1px solid #dee2e6; vertical-align: top; }
  .table th { background:#f1f3f5; width:260px; }
  .section-title { margin: 2rem 0 0.75rem; border-left: 4px solid #0d6efd; padding-left: .5rem; }
  .muted { color:#6c757d; }
  .watermark { position: fixed; top: 40%; left: 20%; font-size: 6rem; color: rgba(13,110,253,.06); transform: rotate(-20deg); pointer-events:none; }
  /* Grille photos intervention */
  .photo-grid { width:100%; border-collapse:collapse; }
  .photo-grid th, .photo-grid td { padding:.5rem .75rem; border:1px solid #dee2e6; vertical-align: top; }
  .photo-grid th { background:#f1f3f5; }
  .cell-image { width:300px; }
  .photo-box { width:280px; height:180px; border:1px solid #ced4da; background:#fff; display:flex; align-items:center; justify-content:center; }
  .photo-box img { max-width:100%; max-height:100%; object-fit:contain; }
</style>
<header class="print-header">
  <div style="display:flex; align-items:center; justify-content:space-between; padding: .5rem 0; border-bottom:1px solid #dee2e6;">
    <div style="display:flex; align-items:center; gap:.5rem;">
  <?php if ($logoUrl): ?><img src="<?= htmlspecialchars($logoUrl) ?>" alt="Logo" style="height:28px;"><?php endif; ?>
      <strong>Rapport de traitement</strong>
    </div>
    <div class="muted">Ticket: <?= $safeTicket ?> • Généré le <?= $today ?></div>
  </div>
</header>
<footer class="print-footer">
  <div style="display:flex; align-items:center; justify-content:space-between; padding: .25rem 0; border-top:1px solid #dee2e6; font-size:.9rem;">
  <span class="muted">Confidentiel — Client: <?= htmlspecialchars($incident['client_name'] ?? '') ?></span>
    <span class="muted">Page <span class="pagenum"></span></span>
  </div>
</footer>
<div class="no-print mb-3">
  <a href="<?= htmlspecialchars(route_url('/incidents/detail', ['id'=>$incident['id']])) ?>" class="btn btn-outline-secondary">Retour</a>
  <button onclick="window.print()" class="btn btn-primary"><i class="fas fa-file-pdf"></i> Imprimer / PDF</button>
</div>

<!-- Page de garde -->
<div class="cover">
  <?php if ($logoUrl): ?><img src="<?= htmlspecialchars($logoUrl) ?>" alt="Logo" class="cover-logo"><?php endif; ?>
  <h1>Rapport de traitement</h1>
  <div class="subtitle">Incident <?= $safeTicket ?></div>
  <div class="hr-title"></div>
  <p class="meta mt-3">"<?= htmlspecialchars((string)($incident['title'] ?? '')) ?>"</p>
  <p class="meta"><strong>Client:</strong> <?= htmlspecialchars($incident['client_name'] ?? '') ?> — <strong>Site:</strong> <?= htmlspecialchars($incident['location_name'] ?? '') ?></p>
  <?php if (!empty($incident['incident_number'])): ?><p class="meta"><strong>Référence:</strong> <?= htmlspecialchars((string)$incident['incident_number']) ?></p><?php endif; ?>
  <p class="meta"><strong>Déclaré le:</strong> <?= !empty($incident['declared_at']) ? date('d/m/Y H:i', strtotime($incident['declared_at'])) : '' ?></p>
</div>
<div class="page-break"></div>

<!-- Sommaire -->
<h3>Sommaire</h3>
<ol class="toc">
  <li><a href="#sec1">Informations générales</a></li>
  <li><a href="#sec2">Diagnostic</a></li>
  <li><a href="#sec3">Intervention & Actions</a></li>
  <li><a href="#sec4">Suivi & Décisions</a></li>
</ol>
<div class="page-break"></div>

<!-- Contenu -->
<h3 id="sec1" class="section-title">1. Informations générales</h3>
<table class="table table-sm">
  <tr><th style="width:260px">N° Ticket</th><td><?= $safeTicket ?></td></tr>
  <?php if (!empty($incident['incident_number'])): ?>
    <tr><th>Numéro Incident</th><td><?= htmlspecialchars((string)$incident['incident_number']) ?></td></tr>
  <?php endif; ?>
  <tr><th>Technicien</th><td><?= htmlspecialchars($report['team_name'] ?? '') ?></td></tr>
  <tr><th>Chef d'équipe (coord.)</th><td><?= htmlspecialchars($report['team_contact'] ?? '') ?></td></tr>
  <tr><th>Type d'incident</th><td><?= htmlspecialchars($report['type_of_incident'] ?? '') ?></td></tr>
  <tr><th>Prise en charge</th><td><?= !empty($report['takeover_at'])?date('d/m/Y H:i', strtotime($report['takeover_at'])):'' ?></td></tr>
</table>

<h3 id="sec2" class="section-title">2. Diagnostic</h3>
<table class="table table-sm">
  <tr><th style="width:260px">Mode de détection</th><td><?= htmlspecialchars($report['detection_mode'] ?? '') ?></td></tr>
  <tr><th>Distance de coupure (km)</th><td><?= htmlspecialchars($report['cut_distance_km'] ?? '') ?></td></tr>
  <tr><th>GPS (lat,lng)</th><td><?= htmlspecialchars(($report['gps_lat'] ?? '').',' . ($report['gps_lng'] ?? '')) ?></td></tr>
  <tr><th>Nature de la panne</th><td><?= nl2br(htmlspecialchars($report['fault_nature'] ?? '')) ?></td></tr>
  <tr><th>Équipements impactés</th><td><?= htmlspecialchars(implode(', ', $equipSel)) ?></td></tr>
</table>

<h3 id="sec3" class="section-title">3. Intervention & Actions</h3>
<table class="table table-sm">
  <tr><th style="width:260px">Début d'intervention</th><td><?= !empty($report['intervention_start'])?date('d/m/Y H:i', strtotime($report['intervention_start'])):'' ?></td></tr>
  <tr><th>Fin d'intervention</th><td><?= !empty($report['intervention_end'])?date('d/m/Y H:i', strtotime($report['intervention_end'])):'' ?></td></tr>
  <tr><th>Durée (h)</th><td><?= htmlspecialchars($report['duration_hours'] ?? '') ?></td></tr>
  <tr><th>Type de réparation</th><td><?= htmlspecialchars($report['repair_type'] ?? '') ?></td></tr>
  <tr><th>Commentaires travaux</th><td><?= nl2br(htmlspecialchars($report['work_comments'] ?? '')) ?></td></tr>
</table>

<h5 class="section-title" style="border-left-color:#198754">Photos d'intervention</h5>
<table class="photo-grid">
  <thead>
    <tr>
      <th class="cell-image">Photo</th>
      <th>Observation & Métadonnées</th>
    </tr>
  </thead>
  <tbody>
    <?php if (!empty($interventionPhotos) && is_array($interventionPhotos)): ?>
      <?php foreach ($interventionPhotos as $ph): ?>
        <tr>
          <td class="cell-image">
            <div class="photo-box">
              <?php $phUrl = upload_url($ph['path']); ?>
              <img src="<?= htmlspecialchars($phUrl) ?>" alt="Photo">
            </div>
          </td>
          <td>
            <div class="muted small"><?= !empty($ph['taken_by']) ? ('Technicien: ' . htmlspecialchars($ph['taken_by']) . ' • ') : '' ?><?php if (isset($ph['lat'],$ph['lng']) && $ph['lat'] !== null && $ph['lng'] !== null): ?>GPS: <?= htmlspecialchars($ph['lat']) ?>, <?= htmlspecialchars($ph['lng']) ?> • <?php endif; ?><?= !empty($ph['uploaded_at']) ? ('Ajouté le ' . date('d/m/Y H:i', strtotime($ph['uploaded_at']))) : '' ?><?php if (!empty($ph['taken_at'])): ?> • Pris le <?= date('d/m/Y H:i', strtotime($ph['taken_at'])) ?><?php endif; ?></div>
            <?php if (!empty($ph['observation'])): ?>
              <div class="mt-2" style="white-space:pre-wrap;"><?= nl2br(htmlspecialchars($ph['observation'])) ?></div>
            <?php else: ?>
              <div class="mt-2 text-muted">Aucune observation fournie.</div>
            <?php endif; ?>
          </td>
        </tr>
      <?php endforeach; ?>
    <?php else: ?>
      <tr>
        <td colspan="2" class="text-center text-muted">Aucune photo d'intervention ajoutée</td>
      </tr>
    <?php endif; ?>
  </tbody>
</table>

<?php if (!empty($report['otdr_before_path']) || !empty($report['otdr_after_path'])): ?>
  <h5 class="section-title" style="border-left-color:#6610f2">Tests de réflectométrie (OTDR)</h5>
  <table class="table table-sm">
    <?php if (!empty($report['otdr_before_path'])): ?>
      <tr>
        <th style="width:260px">OTDR avant réparation</th>
        <td>
          <div style="max-width:420px">
            <?php $beforeUrl = upload_url('incidents/'.$incident['id'].'/'.basename($report['otdr_before_path'])); ?>
            <img src="<?= htmlspecialchars($beforeUrl) ?>" alt="OTDR avant" style="max-width:100%;height:auto;border:1px solid #dee2e6;padding:4px;background:#fff;">
            <div class="muted small mt-1">Fichier: <?= htmlspecialchars(basename($report['otdr_before_path'])) ?></div>
          </div>
        </td>
      </tr>
    <?php endif; ?>
    <?php if (!empty($report['otdr_after_path'])): ?>
      <tr>
        <th style="width:260px">OTDR après réparation</th>
        <td>
          <div style="max-width:420px">
            <?php $afterUrl = upload_url('incidents/'.$incident['id'].'/'.basename($report['otdr_after_path'])); ?>
            <img src="<?= htmlspecialchars($afterUrl) ?>" alt="OTDR après" style="max-width:100%;height:auto;border:1px solid #dee2e6;padding:4px;background:#fff;">
            <div class="muted small mt-1">Fichier: <?= htmlspecialchars(basename($report['otdr_after_path'])) ?></div>
          </div>
        </td>
      </tr>
    <?php endif; ?>
  </table>
<?php endif; ?>

<?php 
$total = 0; 
foreach (($materials ?? []) as $m) { $total += (float)$m['qty'] * (float)$m['unit_cost']; }
?>
<h5 class="section-title" style="border-left-color:#20c997">Matériels utilisés</h5>
<table class="table table-sm" style="border-collapse:collapse;">
  <thead>
    <tr>
      <th style="padding:.5rem .75rem;border:1px solid #dee2e6;background:#f1f3f5;">Désignation</th>
      <th style="padding:.5rem .75rem;border:1px solid #dee2e6;background:#f1f3f5;">Qté</th>
      <th style="padding:.5rem .75rem;border:1px solid #dee2e6;background:#f1f3f5;">Référence</th>
      <th style="padding:.5rem .75rem;border:1px solid #dee2e6;background:#f1f3f5;">PU</th>
      <th style="padding:.5rem .75rem;border:1px solid #dee2e6;background:#f1f3f5;">Total</th>
    </tr>
  </thead>
  <tbody>
    <?php if (!empty($materials) && is_array($materials)): ?>
      <?php foreach ($materials as $m): ?>
        <tr>
          <td style="padding:.5rem .75rem;border:1px solid #dee2e6;vertical-align:top;"><?= htmlspecialchars($m['designation']) ?></td>
          <td style="padding:.5rem .75rem;border:1px solid #dee2e6;vertical-align:top;"><?= htmlspecialchars($m['qty']) ?></td>
          <td style="padding:.5rem .75rem;border:1px solid #dee2e6;vertical-align:top;"><?= htmlspecialchars($m['reference']) ?></td>
          <td style="padding:.5rem .75rem;border:1px solid #dee2e6;vertical-align:top;"><?= htmlspecialchars($m['unit_cost']) ?></td>
          <td style="padding:.5rem .75rem;border:1px solid #dee2e6;vertical-align:top;"><?= number_format((float)$m['qty']*(float)$m['unit_cost'], 2, ',', ' ') ?></td>
        </tr>
      <?php endforeach; ?>
    <?php else: ?>
      <tr>
        <td colspan="5" style="padding:.5rem .75rem;border:1px solid #dee2e6;text-align:center;" class="text-muted">Aucun matériel utilisé</td>
      </tr>
    <?php endif; ?>
  </tbody>
  <tfoot>
    <tr>
      <th colspan="4" style="padding:.5rem .75rem;border:1px solid #dee2e6;background:#f1f3f5;text-align:right;">Total estimé</th>
      <th style="padding:.5rem .75rem;border:1px solid #dee2e6;background:#f1f3f5;"><?= number_format($total, 2, ',', ' ') ?> FCFA</th>
    </tr>
  </tfoot>
</table>

<h3 id="sec4" class="section-title">4. Suivi & Décisions</h3>
<table class="table table-sm">
  <tr><th style="width:260px">Résultat OTDR</th><td><?= htmlspecialchars($report['otdr_result'] ?? '') ?></td></tr>
  <tr><th>Conformité</th><td><?= htmlspecialchars($report['conformity_status'] ?? '') ?></td></tr>
  <tr><th>Statut de la résolution</th><td><?= htmlspecialchars($report['resolution_status'] ?? '') ?></td></tr>
  <tr><th>Besoin d'intervention complémentaire</th><td><?= (isset($report['need_additional']) && (int)$report['need_additional']===1)?'Oui':'Non' ?></td></tr>
  <tr><th>Soumis le</th><td><?= !empty($report['submitted_at'])?date('d/m/Y H:i', strtotime($report['submitted_at'])):'' ?></td></tr>
  <tr><th>Validé le</th><td><?= !empty($report['validated_at'])?date('d/m/Y H:i', strtotime($report['validated_at'])):'' ?></td></tr>
  <tr><th>Commentaire superviseur</th><td><?= nl2br(htmlspecialchars($report['supervisor_comments'] ?? '')) ?></td></tr>
  <tr><th>Motif de refus</th><td><?= nl2br(htmlspecialchars($report['rejection_reason'] ?? '')) ?></td></tr>
</table>

<div class="watermark">NOVALINK</div>
