<?php
use App\Core\Auth;
$cu = Auth::user();
$isAdmin = in_array($cu['role_key'] ?? '', ['admin','agent','manager','superviseur','supervisor']);
$canDelete = in_array($cu['role_key'] ?? '', ['admin','manager'], true);
$isRaccordementClients = isset($isRaccordementClients) ? (bool)$isRaccordementClients : str_contains((string)($_SERVER['REQUEST_URI'] ?? ''), '/raccordement-clients');
$moduleBasePath = isset($moduleBasePath) && is_string($moduleBasePath) && $moduleBasePath !== ''
  ? $moduleBasePath
  : ($isRaccordementClients ? '/raccordement-clients' : '/maintenance-ftth');
$moduleTitle = $isRaccordementClients ? 'Raccordement Clients' : 'Maintenance FTTH B2B';
$moduleKicker = $isRaccordementClients ? 'Raccordement Clients' : 'Supervision FTTH B2B';
$moduleHeroTitle = $isRaccordementClients
  ? 'Pilotage des imports, dispatchs terrain et clôtures de raccordement.'
  : 'Pilotage des coupures, affectations et traitements FTTH.';
$moduleHeroCopy = $isRaccordementClients
  ? 'Importez le template INSTANCES, dispatchiez automatiquement par zone, suivez la fiche terrain mobile et supervisez la validation N+1 depuis une seule vue.'
  : 'Retrouvez les incidents client et transport, filtrez rapidement par topologie réseau et déclenchez les actions terrain depuis une seule vue.';
$moduleCreateLabel = $isRaccordementClients ? 'Créer un raccordement' : 'Déclarer un incident';
$boardTitle = $isRaccordementClients ? 'Portefeuille des raccordements clients' : 'Portefeuille des tickets FTTH';
$boardSubtitle = $isRaccordementClients
  ? 'Vue consolidée des abonnements, repères RACCORDES et affectations terrain avec accès direct au détail et au suivi mobile.'
  : 'Vue consolidée des interventions client et transport avec accès direct au détail, à l’assignation et au suivi des rapports.';
$normalizeImportKey = static function ($value): string {
  $normalized = @iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', (string)$value);
  if ($normalized === false) {
    $normalized = (string)$value;
  }
  $normalized = strtolower($normalized);
  $normalized = preg_replace('/[^a-z0-9]+/', ' ', $normalized) ?? '';
  return trim($normalized);
};
$decodeExtraFields = static function ($raw): array {
  if (is_array($raw)) {
    return $raw;
  }
  if (!is_string($raw) || trim($raw) === '') {
    return [];
  }
  $decoded = json_decode($raw, true);
  return is_array($decoded) ? $decoded : [];
};
$findImportedField = static function (array $extraFields, array $candidates) use ($normalizeImportKey): string {
  foreach ($candidates as $candidate) {
    $normalizedCandidate = $normalizeImportKey($candidate);
    foreach ($extraFields as $label => $value) {
      $normalizedLabel = $normalizeImportKey((string)$label);
      if ($normalizedLabel === '' || $value === null || trim((string)$value) === '') {
        continue;
      }
      if ($normalizedLabel === $normalizedCandidate || str_contains($normalizedLabel, $normalizedCandidate)) {
        return trim((string)$value);
      }
    }
  }
  return '';
};
$normalizeDateInputValue = static function ($rawValue): string {
  $rawValue = trim((string)$rawValue);
  if ($rawValue === '') {
    return '';
  }

  if (preg_match('/^\d+(?:[\.,]\d+)?$/', $rawValue)) {
    $normalizedNumber = (float) str_replace(',', '.', $rawValue);
    if ($normalizedNumber >= 20000 && $normalizedNumber <= 70000) {
      $days = (int) floor($normalizedNumber);
      $seconds = (int) round(($normalizedNumber - $days) * 86400);
      $baseDate = new \DateTimeImmutable('1899-12-30 00:00:00');
      $formattedDate = $baseDate->modify('+' . $days . ' days');
      if ($formattedDate !== false) {
        if ($seconds > 0) {
          $formattedDate = $formattedDate->modify('+' . $seconds . ' seconds');
        }
        return $formattedDate->format('Y-m-d');
      }
    }
  }

  foreach (['Y-m-d', 'd/m/Y', 'd-m-Y', 'd.m.Y'] as $format) {
    $date = \DateTimeImmutable::createFromFormat($format, $rawValue);
    if ($date instanceof \DateTimeImmutable) {
      return $date->format('Y-m-d');
    }
  }

  $timestamp = strtotime($rawValue);
  return $timestamp !== false ? date('Y-m-d', $timestamp) : '';
};
$buildRaccordementEditPayload = static function (array $ticket) use ($decodeExtraFields, $findImportedField, $normalizeDateInputValue): array {
  $extraFields = $decodeExtraFields($ticket['extra_fields'] ?? null);
  $selectedBoxPlaque = trim((string)($ticket['selected_box_plaque'] ?? ''));
  $selectedBoxJdv = trim((string)($ticket['selected_box_hub'] ?? ''));
  $selectedBoxPco = trim((string)(($ticket['selected_box_code'] ?? '') ?: ($ticket['selected_otb_label'] ?? '')));
  $ticketId = (int)($ticket['ticket_id'] ?? $ticket['id'] ?? 0);
  return [
    'id' => $ticketId,
    'ref_code' => (string)($ticket['ref_code'] ?? ''),
    'client_code' => (string)(($ticket['client_code'] ?? '') ?: $findImportedField($extraFields, ['NumeroAbonnement', 'Numéro Abonnement'])),
    'client_name' => (string)(($ticket['client_name'] ?? '') ?: $findImportedField($extraFields, ['NomClient'])),
    'client_phone' => (string)(($ticket['client_phone'] ?? '') ?: $findImportedField($extraFields, ['Contact1'])),
    'client_phone2' => (string)(($ticket['client_phone2'] ?? '') ?: $findImportedField($extraFields, ['Contact2'])),
    'client_address' => (string)(($ticket['client_address'] ?? '') ?: $findImportedField($extraFields, ['Localisation'])),
    'raccordement_city' => $findImportedField($extraFields, ['Ville']),
    'raccordement_commune' => $findImportedField($extraFields, ['Commune']),
    'raccordement_latitude' => (string)(($ticket['client_lat'] ?? '') ?: $findImportedField($extraFields, ['Latitude_Terrai'])),
    'raccordement_longitude' => (string)(($ticket['client_lng'] ?? '') ?: $findImportedField($extraFields, ['Longitude_Terrain'])),
    'sro_client' => (string)($selectedBoxPlaque !== '' ? $selectedBoxPlaque : (($ticket['sro_client'] ?? '') ?: $findImportedField($extraFields, ['PLAQUE']))),
    'jdv_client' => (string)($selectedBoxJdv !== '' ? $selectedBoxJdv : (($ticket['jdv_client'] ?? '') ?: $findImportedField($extraFields, ['JDV']))),
    'pco_client' => (string)($selectedBoxPco !== '' ? $selectedBoxPco : (($ticket['pco_client'] ?? '') ?: $findImportedField($extraFields, ['PCO']))),
    'company_name' => (string)(($ticket['company_name'] ?? '') ?: $findImportedField($extraFields, ['EntrepriseFTTH', 'Entreprise'])),
    'raccordement_snont' => $findImportedField($extraFields, ['SNONT']),
    'raccordement_nd' => $findImportedField($extraFields, ['ND']),
    'raccordement_date_enregistrement' => $normalizeDateInputValue($findImportedField($extraFields, ['Date_Enregistrement_Instances'])),
    'raccordement_date_envoi_prestataires' => $normalizeDateInputValue($findImportedField($extraFields, ['Date_Envoi_Instances_Prestataires'])),
    'raccordement_duree_attente' => $findImportedField($extraFields, ['Duree_attente_j']),
    'raccordement_team' => $findImportedField($extraFields, ['Equipe_raccordement']),
    'raccordement_etude_technique' => $findImportedField($extraFields, ['Etude_Technique']),
    'avancement' => (string)(($ticket['avancement'] ?? '') ?: $findImportedField($extraFields, ['Avancement'])),
    'priority' => (string)($ticket['priority'] ?? 'Moyenne'),
    'status' => (string)($ticket['status'] ?? 'nouveau'),
    'description' => (string)(($ticket['description'] ?? '') ?: $findImportedField($extraFields, ['Commentaires'])),
    'cause_comment' => (string)(($ticket['cause_comment'] ?? '') ?: $findImportedField($extraFields, ['Problèmes', 'Problemes'])),
  ];
};
$queryBase = array_filter([
  'q' => $search ?? '',
  'status' => $status ?? '',
  'sro' => $sro ?? '',
  'company' => $company ?? '',
  'progress' => $progress ?? '',
  'source' => $source ?? '',
], static fn($value) => $value !== null && $value !== '');
$queryString = !empty($queryBase) ? '?' . http_build_query($queryBase) : '';
$exportUrl = route_url($moduleBasePath . '/export' . $queryString);
$exportPdfUrl = route_url($moduleBasePath . '/export-pdf' . $queryString);
$activeFilterCount = count($queryBase);
$openTicketCount = (int)(($stats['nouveau'] ?? 0) + ($stats['assigné'] ?? 0) + ($stats['en_cours'] ?? 0));
$activeAssignedCity = trim((string)($cu['assigned_city'] ?? ''));
?>

<style>
.ftth-page-shell{display:grid;gap:1.25rem}
.ftth-hero-panel{position:relative;overflow:hidden;border-radius:1.5rem;padding:1.5rem 1.5rem 1.35rem;background:linear-gradient(135deg,#12344d 0%,#1f7a8c 58%,#76c893 100%);color:#fff;box-shadow:0 1.2rem 2.8rem rgba(18,52,77,.18)}
.ftth-hero-panel::after{content:'';position:absolute;right:-70px;top:-70px;width:220px;height:220px;border-radius:50%;background:rgba(255,255,255,.07)}
.ftth-hero-grid{position:relative;z-index:1;display:grid;grid-template-columns:minmax(0,1.25fr) minmax(280px,.75fr);gap:1rem;align-items:start}
.ftth-hero-kicker{display:inline-flex;align-items:center;gap:.55rem;padding:.4rem .75rem;border-radius:999px;background:rgba(255,255,255,.14);font-size:.75rem;font-weight:700;letter-spacing:.05em;text-transform:uppercase}
.ftth-hero-title{font-size:clamp(1.7rem,3vw,2.35rem);font-weight:800;line-height:1.05;margin:1rem 0 .55rem}
.ftth-hero-copy{max-width:60rem;color:rgba(255,255,255,.85);font-size:.96rem;margin:0}
.ftth-hero-actions{display:flex;gap:.75rem;flex-wrap:wrap;justify-content:flex-end}
.ftth-hero-actions .btn{border-radius:999px;padding:.7rem 1rem;font-weight:600}
.ftth-hero-metrics{display:grid;grid-template-columns:repeat(auto-fit,minmax(155px,1fr));gap:.85rem;margin-top:1.15rem;position:relative;z-index:1}
.ftth-hero-metric{padding:1rem 1.05rem;border-radius:1rem;background:rgba(255,255,255,.12);border:1px solid rgba(255,255,255,.12);backdrop-filter:blur(12px)}
.ftth-hero-metric strong{display:block;font-size:1.35rem;line-height:1;margin-bottom:.35rem}
.ftth-hero-metric span{display:block;font-size:.83rem;color:rgba(255,255,255,.8)}
.ftth-status-overview{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:.85rem}
.ftth-stat-card{display:flex;align-items:center;gap:.9rem;padding:1rem 1.05rem;border:1px solid #dbe7ef;border-radius:1.15rem;background:#fff;box-shadow:0 .7rem 1.5rem rgba(18,52,77,.06);text-decoration:none;transition:transform .18s ease, box-shadow .18s ease, border-color .18s ease}
.ftth-stat-card:hover{transform:translateY(-2px);box-shadow:0 1rem 2rem rgba(18,52,77,.09);border-color:#bfd5df}
.ftth-stat-icon{width:48px;height:48px;border-radius:14px;display:flex;align-items:center;justify-content:center;color:#fff;font-size:1rem;flex:0 0 48px}
.ftth-stat-label{display:block;font-size:.78rem;text-transform:uppercase;letter-spacing:.05em;color:#6b7f8c;margin-bottom:.15rem}
.ftth-stat-value{display:block;font-size:1.25rem;font-weight:800;color:#12344d;line-height:1.1}
.ftth-filter-shell{border:1px solid #dbe7ef;border-radius:1.25rem;background:linear-gradient(180deg,#ffffff 0%,#f8fbfd 100%);box-shadow:0 .7rem 1.5rem rgba(18,52,77,.05)}
.ftth-filter-header{display:flex;align-items:flex-start;justify-content:space-between;gap:1rem;padding:1rem 1.15rem .3rem}
.ftth-filter-title{font-size:.82rem;font-weight:800;letter-spacing:.05em;text-transform:uppercase;color:#12344d;margin-bottom:.2rem}
.ftth-filter-copy{font-size:.84rem;color:#6b7f8c;margin:0}
.ftth-filter-badge{display:inline-flex;align-items:center;gap:.45rem;padding:.45rem .75rem;border-radius:999px;background:#edf5f8;color:#1f7a8c;font-size:.78rem;font-weight:700}
.ftth-filter-shell .card-body{padding:1rem 1.15rem 1.15rem}
.ftth-filter-shell .form-label{font-size:.74rem;font-weight:700;letter-spacing:.04em;text-transform:uppercase;color:#5d7281}
.ftth-filter-shell .form-control,.ftth-filter-shell .form-select{min-height:42px;border-radius:.85rem;border:1px solid #dbe7ef}
.ftth-filter-shell .form-control:focus,.ftth-filter-shell .form-select:focus{border-color:#5aa7b4;box-shadow:0 0 0 .2rem rgba(31,122,140,.1)}
.ftth-board{border:1px solid #dbe7ef;border-radius:1.3rem;background:#fff;box-shadow:0 .85rem 1.8rem rgba(18,52,77,.06);overflow:hidden}
.ftth-board-header{display:flex;align-items:center;justify-content:space-between;gap:1rem;padding:1rem 1.15rem;border-bottom:1px solid #edf3f6;background:linear-gradient(180deg,#ffffff 0%,#f7fbfd 100%)}
.ftth-board-title{display:flex;align-items:center;gap:.75rem;font-weight:800;color:#12344d}
.ftth-board-title i{width:42px;height:42px;border-radius:14px;display:flex;align-items:center;justify-content:center;background:#e9f5f6;color:#1f7a8c}
.ftth-board-subtitle{font-size:.84rem;color:#6b7f8c;margin:0}
.ftth-bulk-toolbar{display:flex;align-items:center;justify-content:space-between;gap:1rem;flex-wrap:wrap;padding:1rem 1.15rem;border-bottom:1px solid #edf3f6;background:linear-gradient(180deg,#fbfdfe 0%,#f4f9fb 100%)}
.ftth-bulk-copy{display:flex;align-items:center;gap:.85rem;flex-wrap:wrap}
.ftth-bulk-badge{display:inline-flex;align-items:center;gap:.45rem;padding:.48rem .85rem;border-radius:999px;background:#12344d;color:#fff;font-size:.78rem;font-weight:700}
.ftth-bulk-summary{font-size:.84rem;color:#5d7281}
.ftth-bulk-actions{display:flex;gap:.55rem;flex-wrap:wrap}
.ftth-bulk-actions .btn{border-radius:999px;padding-inline:1rem}
.ftth-bulk-actions .btn:disabled{opacity:.55;cursor:not-allowed}
.ftth-confirm-modal .modal-content{border:0;border-radius:1.25rem;overflow:hidden;box-shadow:0 1.25rem 3rem rgba(18,52,77,.18)}
.ftth-confirm-modal .modal-header{border-bottom:0;padding:1rem 1.15rem .5rem}
.ftth-confirm-modal .modal-body{padding:.25rem 1.15rem 1rem}
.ftth-confirm-modal .modal-footer{border-top:1px solid #edf3f6;padding:.9rem 1.15rem 1.1rem}
.ftth-confirm-hero{display:flex;align-items:flex-start;gap:.9rem}
.ftth-confirm-icon{width:52px;height:52px;border-radius:16px;display:flex;align-items:center;justify-content:center;background:rgba(220,53,69,.12);color:#dc3545;font-size:1.15rem;flex:0 0 52px}
.ftth-confirm-copy strong{display:block;color:#12344d;font-size:1rem;margin-bottom:.25rem}
.ftth-confirm-copy p{margin:0;color:#5d7281;font-size:.9rem}
.ftth-confirm-meta{margin-top:.95rem;display:flex;flex-wrap:wrap;gap:.5rem}
.ftth-confirm-pill{display:inline-flex;align-items:center;gap:.4rem;padding:.42rem .7rem;border-radius:999px;background:#f7fafc;border:1px solid #dbe7ef;color:#58707f;font-size:.78rem;font-weight:700}
.ftth-table-shell{padding:1rem 1.15rem 1.15rem}
.ftth-table-wrap{border:1px solid #dbe7ef;border-radius:1.15rem;overflow:auto;box-shadow:inset 0 1px 0 rgba(255,255,255,.6)}
.ftth-table{width:100%;min-width:1360px;border-collapse:separate;border-spacing:0;background:#fff}
.ftth-table thead th{position:sticky;top:0;z-index:1;background:#f6fafc;color:#58707f;font-size:.75rem;font-weight:800;letter-spacing:.05em;text-transform:uppercase;padding:.9rem .85rem;border-bottom:1px solid #dbe7ef;white-space:nowrap}
.ftth-table tbody td{padding:1rem .85rem;border-bottom:1px solid #edf3f6;vertical-align:top;color:#425866;font-size:.88rem}
.ftth-table tbody tr{transition:background .18s ease, box-shadow .18s ease}
.ftth-table tbody tr:hover{background:#fbfdfe}
.ftth-table tbody tr.is-selected{background:#edf7f8;box-shadow:inset 3px 0 0 #1f7a8c}
.ftth-table tbody tr:last-child td{border-bottom:0}
.ftth-table-check{width:48px;text-align:center}
.ftth-table .form-check-input{width:1.1rem;height:1.1rem;cursor:pointer}
.ftth-ticket-main{display:grid;gap:.38rem;min-width:240px}
.ftth-ticket-main-top{display:flex;align-items:center;gap:.5rem;flex-wrap:wrap}
.ftth-ticket-ref{display:inline-flex;align-items:center;gap:.4rem;padding:.35rem .65rem;border-radius:999px;background:#edf5f8;color:#1f7a8c;font-size:.74rem;font-weight:800}
.ftth-ticket-title{font-size:.98rem;font-weight:800;color:#12344d;line-height:1.2}
.ftth-ticket-subline{display:flex;flex-wrap:wrap;gap:.35rem .7rem;color:#6b7f8c;font-size:.8rem}
.ftth-ticket-network{display:block;padding:.7rem .85rem;border:1px solid #dbe7ef;border-radius:.95rem;background:linear-gradient(180deg,#ffffff 0%,#f7fbfd 100%);color:#12344d;font-size:.82rem;font-weight:700;line-height:1.55}
.ftth-ticket-stack{display:grid;gap:.35rem}
.ftth-ticket-stack strong{font-size:.82rem;color:#12344d}
.ftth-ticket-stack span,.ftth-ticket-stack small{color:#5d7281}
.ftth-state-cluster{display:flex;flex-direction:column;align-items:flex-start;gap:.45rem}
.ftth-state-cluster .badge{padding:.42rem .7rem;border-radius:999px}
.ftth-status-note{font-size:.76rem;color:#6b7f8c}
.ftth-inline-meta{display:flex;flex-wrap:wrap;gap:.35rem .55rem}
.ftth-inline-meta span{display:inline-flex;align-items:center;gap:.35rem;padding:.32rem .55rem;border-radius:999px;background:#f5f8fa;color:#56707f;font-size:.75rem}
.ftth-row-actions{display:flex;gap:.45rem;flex-wrap:wrap;justify-content:flex-end;min-width:210px}
.ftth-row-actions .btn{border-radius:999px;padding-inline:.85rem;white-space:nowrap}
.ftth-mobile-list{display:grid;gap:.9rem}
.ftth-mobile-card{border:1px solid #dbe7ef;border-radius:1rem;background:#fff;box-shadow:0 .45rem 1rem rgba(18,52,77,.06);padding:1rem}
.ftth-mobile-card-header{display:flex;align-items:flex-start;justify-content:space-between;gap:.75rem;margin-bottom:.75rem}
.ftth-mobile-meta{display:grid;gap:.5rem}
.ftth-mobile-line{display:flex;gap:.55rem;align-items:flex-start;color:#5d7281;font-size:.84rem}
.ftth-mobile-line i{width:16px;color:#1f7a8c;margin-top:.15rem}
.ftth-mobile-tags{display:flex;flex-wrap:wrap;gap:.35rem;margin-top:.55rem}
.ftth-mobile-actions{display:flex;gap:.5rem;margin-top:.85rem}
.ftth-mobile-actions .btn{flex:1}
.ftth-create-modal .modal-content{border:0;border-radius:1.25rem;overflow:hidden;box-shadow:0 1.2rem 3rem rgba(18,52,77,.18)}
.ftth-create-modal .modal-header{padding:0;border-bottom:0;background:linear-gradient(135deg,#12344d 0%,#1f7a8c 60%,#76c893 100%);color:#fff}
.ftth-create-modal .modal-header-inner{display:flex;align-items:flex-start;justify-content:space-between;gap:1rem;padding:1.35rem 1.5rem;width:100%}
.ftth-create-modal .modal-kicker{display:inline-flex;align-items:center;gap:.5rem;padding:.35rem .7rem;border-radius:999px;background:rgba(255,255,255,.16);font-size:.72rem;font-weight:700;letter-spacing:.05em;text-transform:uppercase}
.ftth-create-modal .modal-subtitle{max-width:54rem;color:rgba(255,255,255,.86);font-size:.92rem;margin-top:.55rem}
.ftth-create-modal .btn-close{filter:invert(1) grayscale(1) brightness(200%);opacity:.9;margin:0}
.ftth-create-modal .modal-body{padding:1.35rem 1.5rem 1rem;background:linear-gradient(180deg,#f7fbfd 0%,#ffffff 38%)}
.ftth-create-modal .modal-footer{padding:1rem 1.5rem 1.25rem;border-top:1px solid #e7eef3;background:#fff}
.ftth-create-modal .section-card{height:100%;border:1px solid #dbe7ef;border-radius:1rem;background:#fff;box-shadow:0 .45rem 1rem rgba(18,52,77,.05)}
.ftth-create-modal .section-card .card-body{padding:1rem 1rem 1.1rem}
.ftth-create-modal .cut-type-switch{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:.9rem;margin-bottom:1rem}
.ftth-create-modal .cut-type-option{position:relative}
.ftth-create-modal .cut-type-option input{position:absolute;opacity:0;pointer-events:none}
.ftth-create-modal .cut-type-card{height:100%;display:block;padding:1rem 1.05rem;border:1px solid #dbe7ef;border-radius:1rem;background:#fff;cursor:pointer;transition:.18s ease;box-shadow:0 .35rem .85rem rgba(18,52,77,.04)}
.ftth-create-modal .cut-type-card strong{display:block;color:#12344d;font-size:.98rem;margin-bottom:.25rem}
.ftth-create-modal .cut-type-card span{display:block;color:#6b7f8c;font-size:.84rem}
.ftth-create-modal .cut-type-option input:checked + .cut-type-card{border-color:#1f7a8c;background:linear-gradient(180deg,#ffffff 0%,#eef7f8 100%);box-shadow:0 .55rem 1.2rem rgba(31,122,140,.14)}
.ftth-create-modal .cut-type-option input:focus-visible + .cut-type-card{outline:2px solid rgba(31,122,140,.35);outline-offset:3px}
.ftth-create-modal [data-cuture-panel][hidden]{display:none!important}
.ftth-create-modal .section-title{display:flex;align-items:center;gap:.6rem;margin-bottom:.9rem;font-size:.82rem;font-weight:800;letter-spacing:.05em;text-transform:uppercase;color:#12344d}
.ftth-create-modal .section-title i{width:2rem;height:2rem;border-radius:.75rem;display:flex;align-items:center;justify-content:center;background:#e9f5f6;color:#1f7a8c}
.ftth-create-modal .form-label{font-size:.76rem;font-weight:700;letter-spacing:.04em;text-transform:uppercase;color:#5d7281;margin-bottom:.4rem}
.ftth-create-modal .form-control,.ftth-create-modal .form-select{min-height:46px;border-radius:.85rem;border:1px solid #dbe7ef;box-shadow:none}
.ftth-create-modal textarea.form-control{min-height:auto}
.ftth-create-modal .form-control:focus,.ftth-create-modal .form-select:focus{border-color:#5aa7b4;box-shadow:0 0 0 .2rem rgba(31,122,140,.12)}
.ftth-create-modal .input-group-text{border-radius:.85rem 0 0 .85rem;border-color:#dbe7ef;background:#f4f8fb;color:#1f7a8c}
.ftth-create-modal .input-group .form-control{border-radius:0 .85rem .85rem 0}
.ftth-create-modal .hint-panel{display:flex;align-items:flex-start;gap:.75rem;padding:.9rem 1rem;border:1px solid rgba(31,122,140,.14);border-radius:1rem;background:rgba(31,122,140,.06);margin-bottom:1rem}
.ftth-create-modal .hint-panel i{width:2rem;height:2rem;border-radius:.7rem;display:flex;align-items:center;justify-content:center;background:#fff;color:#1f7a8c;flex:0 0 2rem}
.ftth-create-modal .helper-text{font-size:.8rem;color:#6b7f8c;margin-top:.35rem}
.ftth-create-modal .footer-note{font-size:.82rem;color:#6b7f8c}
@media (max-width: 767.98px){
  .ftth-desktop-table{display:none}
  .ftth-create-modal .modal-header-inner,
  .ftth-create-modal .modal-body,
  .ftth-create-modal .modal-footer{padding-left:1rem;padding-right:1rem}
  .ftth-hero-panel{padding:1.15rem 1rem}
  .ftth-hero-grid{grid-template-columns:1fr}
  .ftth-hero-actions{justify-content:flex-start}
  .ftth-filter-header,.ftth-filter-shell .card-body,.ftth-board-header{padding-left:1rem;padding-right:1rem}
}
@media (min-width: 768px){
  .ftth-mobile-list{display:none}
}
@media (max-width: 1199.98px){
  .ftth-bulk-toolbar{align-items:flex-start}
}
</style>

<section class="content">
  <div class="container-fluid">
    <div class="ftth-page-shell">
      <section class="ftth-hero-panel">
        <div class="ftth-hero-grid">
          <div>
            <div class="ftth-hero-kicker"><i class="fas fa-network-wired"></i><?= htmlspecialchars($moduleKicker) ?></div>
            <h1 class="ftth-hero-title"><?= htmlspecialchars($moduleHeroTitle) ?></h1>
            <p class="ftth-hero-copy"><?= htmlspecialchars($moduleHeroCopy) ?></p>
          </div>
          <?php if ($isAdmin): ?>
          <div class="ftth-hero-actions">
            <a class="btn btn-outline-light" href="<?= htmlspecialchars($exportUrl) ?>">
              <i class="fas fa-download me-1"></i>Exporter la liste
            </a>
            <a class="btn btn-outline-light" href="<?= htmlspecialchars($exportPdfUrl) ?>" target="_blank" rel="noopener">
              <i class="fas fa-file-pdf me-1"></i>Exporter PDF
            </a>
            <button class="btn btn-light" data-bs-toggle="modal" data-bs-target="#modalCreateTicket">
              <i class="fas fa-plus-circle me-1"></i><?= htmlspecialchars($moduleCreateLabel) ?>
            </button>
            <button class="btn btn-outline-light" data-bs-toggle="modal" data-bs-target="#modalImport">
              <i class="fas fa-file-excel me-1"></i>Importer Excel
            </button>
          </div>
          <?php endif; ?>
        </div>
        <div class="ftth-hero-metrics">
          <div class="ftth-hero-metric">
            <strong><?= number_format((int)$total) ?></strong>
            <span>tickets dans le portefeuille</span>
          </div>
          <div class="ftth-hero-metric">
            <strong><?= number_format($openTicketCount) ?></strong>
            <span>tickets encore ouverts</span>
          </div>
          <div class="ftth-hero-metric">
            <strong><?= number_format((int)($stats['validé'] ?? 0)) ?></strong>
            <span>rapports validés</span>
          </div>
          <div class="ftth-hero-metric">
            <strong><?= $activeFilterCount ?></strong>
            <span>filtre<?= $activeFilterCount > 1 ? 's' : '' ?> actif<?= $activeFilterCount > 1 ? 's' : '' ?></span>
          </div>
        </div>
      </section>

      <!-- Alertes flash -->
      <?php if (isset($_GET['imported'])): ?>
      <div class="alert alert-success alert-dismissible fade show">
        <i class="fas fa-check-circle me-1"></i>
        <strong><?= (int)$_GET['imported'] ?> ticket(s)</strong> importé(s)<?= isset($_GET['skipped']) && (int)$_GET['skipped'] > 0 ? ', <strong>' . (int)$_GET['skipped'] . '</strong> ignoré(s)' : '' ?><?= isset($_GET['resolved_skipped']) && (int)$_GET['resolved_skipped'] > 0 ? ' dont <strong>' . (int)$_GET['resolved_skipped'] . '</strong> ligne(s) au statut RESOLU' : '' ?>.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
      </div>
      <?php endif; ?>
      <?php if (isset($_GET['duplicate_import'])): ?>
      <?php
        $duplicateFile = trim((string)($_GET['duplicate_file'] ?? 'ce fichier'));
        $duplicateAtRaw = trim((string)($_GET['duplicate_at'] ?? ''));
        $duplicateAt = $duplicateAtRaw !== '' ? strtotime($duplicateAtRaw) : false;
        $duplicateCount = max(1, (int)($_GET['duplicate_count'] ?? 1));
      ?>
      <div class="alert alert-warning alert-dismissible fade show">
        <i class="fas fa-history me-1"></i>
        Ce contenu correspond a un fichier deja importe<?= $duplicateAt ? ' le <strong>' . htmlspecialchars(date('d/m/Y H:i', $duplicateAt)) . '</strong>' : '' ?>
        sous le nom <strong><?= htmlspecialchars($duplicateFile) ?></strong><?= $duplicateCount > 1 ? ' (' . $duplicateCount . ' import(s) anterieurs)' : '' ?>.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
      </div>
      <?php endif; ?>
      <?php if (isset($_GET['deleted'])): ?>
      <div class="alert alert-success alert-dismissible fade show">
        <i class="fas fa-trash me-1"></i> Ticket supprimé.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
      </div>
      <?php endif; ?>
      <?php if (isset($_GET['bulk_deleted'])): ?>
      <div class="alert alert-success alert-dismissible fade show">
        <i class="fas fa-trash-arrow-up me-1"></i> <?= (int)$_GET['bulk_deleted'] ?> ticket(s) supprimé(s) depuis la sélection.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
      </div>
      <?php endif; ?>
      <?php if (isset($_GET['created'])): ?>
      <div class="alert alert-success alert-dismissible fade show">
        <i class="fas fa-plus-circle me-1"></i> Déclaration créée avec succès.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
      </div>
      <?php endif; ?>
      <?php if (isset($_GET['updated'])): ?>
      <div class="alert alert-success alert-dismissible fade show">
        <i class="fas fa-pen-to-square me-1"></i> Raccordement mis à jour avec succès.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
      </div>
      <?php endif; ?>
      <?php if (isset($_GET['priority_updated'])): ?>
      <div class="alert alert-success alert-dismissible fade show">
        <i class="fas fa-triangle-exclamation me-1"></i> Criticité requalifiée avec succès.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
      </div>
      <?php endif; ?>
      <?php if (isset($_GET['assigned'])): ?>
      <div class="alert alert-success alert-dismissible fade show">
        <i class="fas fa-user-check me-1"></i> Ticket assigné et notifications envoyées.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
      </div>
      <?php endif; ?>
      <?php if (isset($_GET['unassigned'])): ?>
      <div class="alert alert-success alert-dismissible fade show">
        <i class="fas fa-user-minus me-1"></i> Assignation retirée avec succès.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
      </div>
      <?php endif; ?>
      <?php if (isset($_GET['bulk_assigned'])): ?>
      <div class="alert alert-success alert-dismissible fade show">
        <i class="fas fa-people-arrows me-1"></i> Assignation rapide exécutée sur <strong><?= (int)$_GET['bulk_assigned'] ?></strong> ticket(s)<?= isset($_GET['selection']) ? ' sélectionné(s) sur ' . (int)$_GET['selection'] : '' ?>.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
      </div>
      <?php endif; ?>
      <?php if (isset($_GET['err'])): ?>
      <div class="alert alert-danger alert-dismissible fade show">
        <i class="fas fa-exclamation-circle me-1"></i> <?= htmlspecialchars($_GET['err']) ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
      </div>
      <?php endif; ?>

      <?php if ($activeAssignedCity !== ''): ?>
      <div class="alert alert-info border-0 shadow-sm d-flex flex-wrap align-items-center justify-content-between gap-2 mb-0">
        <div>
          <strong><i class="fas fa-location-dot me-1"></i>Ville de rattachement active:</strong>
          <?= htmlspecialchars($activeAssignedCity) ?>
          <span class="text-muted">Seuls les tickets correspondant à cette ville sont affichés dans la liste, les exports et les actions associées.</span>
        </div>
        <span class="badge rounded-pill text-bg-light border px-3 py-2"><?= htmlspecialchars($activeAssignedCity) ?></span>
      </div>
      <?php endif; ?>

      <!-- Statistiques -->
      <div class="ftth-status-overview">
      <?php
      $statConf = [
        'nouveau'  => ['label'=>'Nouveaux',  'icon'=>'fas fa-inbox',        'color'=>'primary'],
        'assigné'  => ['label'=>'Assignés',  'icon'=>'fas fa-user-check',   'color'=>'warning'],
        'en_cours' => ['label'=>'En cours',  'icon'=>'fas fa-spinner',      'color'=>'info'],
        'traité'   => ['label'=>'Traités',   'icon'=>'fas fa-tools',        'color'=>'success'],
        'validé'   => ['label'=>'Validés',   'icon'=>'fas fa-check-double', 'color'=>'success'],
        'clôturé'  => ['label'=>'Clôturés',  'icon'=>'fas fa-archive',      'color'=>'secondary'],
      ];
      foreach ($statConf as $key => $conf): $cnt = $stats[$key] ?? 0; ?>
      <a href="<?= htmlspecialchars(route_url($moduleBasePath . '?status=' . urlencode($key))) ?>" class="ftth-stat-card">
        <span class="ftth-stat-icon bg-<?= $conf['color'] ?>"><i class="<?= $conf['icon'] ?>"></i></span>
        <span>
          <span class="ftth-stat-label"><?= $conf['label'] ?></span>
          <span class="ftth-stat-value"><?= $cnt ?></span>
        </span>
      </a>
      <?php endforeach; ?>
      </div>

      <!-- Filtres -->
      <div class="card ftth-filter-shell mb-0">
        <div class="ftth-filter-header">
          <div>
            <div class="ftth-filter-title">Filtres opérationnels</div>
            <p class="ftth-filter-copy">Isolez rapidement les tickets par état, zone réseau, entreprise ou avancement terrain.</p>
          </div>
          <div class="ftth-filter-badge"><i class="fas fa-sliders"></i><?= $activeFilterCount ?> filtre<?= $activeFilterCount > 1 ? 's' : '' ?> actif<?= $activeFilterCount > 1 ? 's' : '' ?></div>
        </div>
        <div class="card-body">
        <form method="GET" action="<?= htmlspecialchars(route_url($moduleBasePath)) ?>" class="row g-2 align-items-end">
          <div class="col-12 col-xl-3">
            <label class="form-label small mb-1">Recherche</label>
            <input type="text" name="q" class="form-control form-control-sm" placeholder="Client, réf, nature…" value="<?= htmlspecialchars($search) ?>">
          </div>
          <div class="col-6 col-md-3 col-xl-2">
            <label class="form-label small mb-1">Statut</label>
            <select name="status" class="form-select form-select-sm">
              <option value="">Tous les statuts</option>
              <?php foreach (['nouveau','assigné','en_cours','traité','validé','clôturé'] as $s): ?>
              <option value="<?= $s ?>" <?= $status === $s ? 'selected' : '' ?>><?= ucfirst($s) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-6 col-md-3 col-xl-2">
            <label class="form-label small mb-1">SRO</label>
            <select name="sro" class="form-select form-select-sm">
              <option value="">Tous les SRO</option>
              <?php foreach (($sroOptions ?? []) as $option): ?>
              <option value="<?= htmlspecialchars($option) ?>" <?= ($sro ?? '') === $option ? 'selected' : '' ?>><?= htmlspecialchars($option) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-6 col-md-3 col-xl-2">
            <label class="form-label small mb-1">Entreprise</label>
            <select name="company" class="form-select form-select-sm">
              <option value="">Toutes</option>
              <?php foreach (($companyOptions ?? []) as $option): ?>
              <option value="<?= htmlspecialchars($option) ?>" <?= ($company ?? '') === $option ? 'selected' : '' ?>><?= htmlspecialchars($option) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-6 col-md-3 col-xl-2">
            <label class="form-label small mb-1">Avancement</label>
            <select name="progress" class="form-select form-select-sm">
              <option value="">Tous</option>
              <?php foreach (($progressOptions ?? []) as $option): ?>
              <option value="<?= htmlspecialchars($option) ?>" <?= ($progress ?? '') === $option ? 'selected' : '' ?>><?= htmlspecialchars($option) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-6 col-md-3 col-xl-2">
            <label class="form-label small mb-1">Origine</label>
            <select name="source" class="form-select form-select-sm">
              <option value="">Toutes</option>
              <?php foreach (($sourceOptions ?? []) as $sourceValue => $sourceLabel): ?>
              <option value="<?= htmlspecialchars($sourceValue) ?>" <?= ($source ?? '') === $sourceValue ? 'selected' : '' ?>><?= htmlspecialchars($sourceLabel) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-12 col-xl-1 d-flex gap-1">
            <button type="submit" class="btn btn-secondary btn-sm flex-fill"><i class="fas fa-filter me-1"></i>Filtrer</button>
            <a href="<?= htmlspecialchars(route_url($moduleBasePath)) ?>" class="btn btn-outline-secondary btn-sm" title="Réinitialiser"><i class="fas fa-times"></i></a>
          </div>
          <div class="col-12 col-xl-auto d-flex gap-1 justify-content-xl-end">
            <a href="<?= htmlspecialchars($exportUrl) ?>" class="btn btn-outline-primary btn-sm">
              <i class="fas fa-download me-1"></i>Exporter CSV
            </a>
            <a href="<?= htmlspecialchars($exportPdfUrl) ?>" class="btn btn-outline-danger btn-sm" target="_blank" rel="noopener">
              <i class="fas fa-file-pdf me-1"></i>Exporter PDF
            </a>
          </div>
        </form>
        </div>
      </div>

      <!-- Tableau -->
      <div class="ftth-board">
        <div class="ftth-board-header">
          <div>
            <div class="ftth-board-title"><i class="fas fa-list"></i><span><?= htmlspecialchars($boardTitle) ?></span></div>
            <p class="ftth-board-subtitle"><?= htmlspecialchars($boardSubtitle) ?></p>
          </div>
          <span class="badge rounded-pill text-bg-light border px-3 py-2"><?= number_format($total) ?> ticket<?= (int)$total > 1 ? 's' : '' ?></span>
        </div>
        <div class="card-body p-0">
        <?php if (empty($tickets)): ?>
        <div class="text-center py-5 text-muted">
          <i class="fas fa-network-wired fa-3x mb-3 opacity-25"></i>
          <p class="mb-2">Aucun ticket trouvé.</p>
          <?php if ($isAdmin): ?>
          <div class="d-flex gap-2 justify-content-center">
          <button class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#modalCreateTicket">
            <i class="fas fa-plus-circle me-1"></i>Créer une déclaration
          </button>
          <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#modalImport">
            <i class="fas fa-file-excel me-1"></i>Importer un fichier Excel
          </button>
          </div>
          <?php endif; ?>
        </div>
        <?php else: ?>
        <div class="ftth-mobile-list p-3">
          <?php foreach ($tickets as $tk):
            $ticketId = (int)($tk['ticket_id'] ?? $tk['id'] ?? 0);
            $editPayload = $buildRaccordementEditPayload($tk);
            $priColor = ['Urgent'=>'danger','Haute'=>'warning','Moyenne'=>'primary','Basse'=>'secondary'][$tk['priority']] ?? 'secondary';
            $stColor  = ['nouveau'=>'primary','assigné'=>'warning','en_cours'=>'info','traité'=>'success','validé'=>'success','clôturé'=>'secondary'][$tk['status']] ?? 'secondary';
            $assignmentLocked = in_array((string)($tk['status'] ?? ''), ['validé', 'clôturé'], true);
            $sourceLabel = (($tk['source_channel'] ?? '') === 'e-intervention') ? 'e-Intervention' : 'Opérateur direct';
            $sourceIcon = (($tk['source_channel'] ?? '') === 'e-intervention') ? 'fa-mobile-screen-button' : 'fa-headset';
            $extraFields = $decodeExtraFields($tk['extra_fields'] ?? null);
            $raccordementName = $tk['client_name'] ?: $findImportedField($extraFields, ['NomClient']);
            $raccordementSubscription = $tk['client_code'] ?: $findImportedField($extraFields, ['NumeroAbonnement', 'Numéro Abonnement']);
            $raccordementAddress = $tk['client_address'] ?: $findImportedField($extraFields, ['Localisation']);
            $raccordementContact1 = $tk['client_phone'] ?: $findImportedField($extraFields, ['Contact1']);
            $raccordementContact2 = $tk['client_phone2'] ?: $findImportedField($extraFields, ['Contact2']);
            $raccordementCity = $findImportedField($extraFields, ['Ville']);
            $raccordementCommune = $findImportedField($extraFields, ['Commune']);
            $raccordementPlaque = $findImportedField($extraFields, ['PLAQUE']);
            $selectedBoxPlaque = trim((string)($tk['selected_box_plaque'] ?? ''));
            $selectedBoxJdv = trim((string)($tk['selected_box_hub'] ?? ''));
            $selectedBoxPco = trim((string)(($tk['selected_box_code'] ?? '') ?: ($tk['selected_otb_label'] ?? '')));
            $displayPlaque = $selectedBoxPlaque !== '' ? $selectedBoxPlaque : ($raccordementPlaque ?: (string)($tk['sro_client'] ?? ''));
            $displayJdv = $selectedBoxJdv !== '' ? $selectedBoxJdv : trim((string)($tk['jdv_client'] ?? ''));
            $displayPco = $selectedBoxPco !== '' ? $selectedBoxPco : trim((string)($tk['pco_client'] ?? ''));
            $raccordementSnont = $findImportedField($extraFields, ['SNONT']);
            $raccordementNd = $findImportedField($extraFields, ['ND']);
            $raccordementCompany = $tk['company_name'] ?: $findImportedField($extraFields, ['EntrepriseFTTH', 'Entreprise']);
            $raccordementProgress = $tk['avancement'] ?: $findImportedField($extraFields, ['Avancement']);
            $networkRefs = array_values(array_filter([
              !empty($isRaccordementClients ? $displayPlaque : $tk['sro_client']) ? ($isRaccordementClients ? 'PLAQUE ' . $displayPlaque : 'SRO ' . $tk['sro_client']) : null,
              !empty($isRaccordementClients ? $displayJdv : $tk['jdv_client']) ? 'JDV ' . ($isRaccordementClients ? $displayJdv : $tk['jdv_client']) : null,
              !empty($isRaccordementClients ? $displayPco : $tk['pco_client']) ? 'PCO ' . ($isRaccordementClients ? $displayPco : $tk['pco_client']) : null,
            ]));
            $networkPath = implode(' => ', $networkRefs);
            $lastReportSavedAt = !empty($tk['report_updated_at']) ? date('d/m/Y à H:i', strtotime((string)$tk['report_updated_at'])) : '';
          ?>
          <article class="ftth-mobile-card">
            <div class="ftth-mobile-card-header">
              <div>
                <div class="fw-semibold"><?= htmlspecialchars($isRaccordementClients ? ($raccordementName ?: 'Client raccordement') : $tk['client_name']) ?></div>
                <div class="small text-muted mt-1"><?= htmlspecialchars($isRaccordementClients ? ($raccordementSubscription ?: ($tk['ref_code'] ?: '#'.$ticketId)) : ($tk['ref_code'] ?: '#'.$ticketId)) ?></div>
              </div>
              <div class="d-flex flex-column align-items-end gap-1">
                <span class="badge bg-<?= $priColor ?>"><?= htmlspecialchars($tk['priority']) ?></span>
                <span class="badge bg-<?= $stColor ?>"><?= htmlspecialchars(ucfirst($tk['status'])) ?></span>
              </div>
            </div>
            <div class="ftth-mobile-meta">
              <?php if (!empty($isRaccordementClients ? $raccordementSubscription : $tk['client_code'])): ?><div class="ftth-mobile-line"><i class="fas fa-id-badge"></i><span>Abonnement <?= htmlspecialchars($isRaccordementClients ? $raccordementSubscription : $tk['client_code']) ?></span></div><?php endif; ?>
              <?php if (!empty($tk['fixed_line'])): ?><div class="ftth-mobile-line"><i class="fas fa-phone"></i><span>Ligne fixe <?= htmlspecialchars($tk['fixed_line']) ?></span></div><?php endif; ?>
              <?php if (!empty($isRaccordementClients ? $raccordementContact1 : $tk['client_phone']) || !empty($isRaccordementClients ? $raccordementContact2 : $tk['client_phone2'])): ?><div class="ftth-mobile-line"><i class="fas fa-mobile-alt"></i><span><?= htmlspecialchars(($isRaccordementClients ? $raccordementContact1 : $tk['client_phone']) ?: '—') ?><?php if (!empty($isRaccordementClients ? $raccordementContact2 : $tk['client_phone2'])): ?>, <?= htmlspecialchars($isRaccordementClients ? $raccordementContact2 : $tk['client_phone2']) ?><?php endif; ?></span></div><?php endif; ?>
              <?php if (!empty($isRaccordementClients ? $raccordementAddress : $tk['client_address'])): ?><div class="ftth-mobile-line"><i class="fas fa-map-marker-alt"></i><span><?= htmlspecialchars($isRaccordementClients ? $raccordementAddress : $tk['client_address']) ?></span></div><?php endif; ?>
              <?php if ($isRaccordementClients && (!empty($raccordementCity) || !empty($raccordementCommune))): ?><div class="ftth-mobile-line"><i class="fas fa-map"></i><span><?= htmlspecialchars(trim($raccordementCity . (!empty($raccordementCity) && !empty($raccordementCommune) ? ' / ' : '') . $raccordementCommune)) ?></span></div><?php endif; ?>
              <?php if (!empty($tk['nature_intervention']) || $isRaccordementClients): ?><div class="ftth-mobile-line"><i class="fas fa-bolt"></i><span><strong><?= $isRaccordementClients ? 'Mission' : 'Intervention' ?></strong> <?= htmlspecialchars($isRaccordementClients ? 'Raccordement client' : $tk['nature_intervention']) ?></span></div><?php endif; ?>
              <div class="ftth-mobile-line"><i class="fas <?= htmlspecialchars($sourceIcon) ?>"></i><span><strong>Origine</strong> <?= htmlspecialchars($sourceLabel) ?></span></div>
              <?php if (!empty($isRaccordementClients ? $raccordementProgress : $tk['avancement'])): ?><div class="ftth-mobile-line"><i class="fas fa-route"></i><span><strong>Avancement</strong> <?= htmlspecialchars($isRaccordementClients ? $raccordementProgress : $tk['avancement']) ?></span></div><?php endif; ?>
              <?php if (!empty($tk['cause_comment'])): ?><div class="ftth-mobile-line"><i class="fas fa-triangle-exclamation"></i><span><strong>Cause</strong> Renseignée</span></div><?php endif; ?>
              <?php if (!empty($isRaccordementClients ? $raccordementCompany : $tk['company_name'])): ?><div class="ftth-mobile-line"><i class="fas fa-building"></i><span><?= htmlspecialchars($isRaccordementClients ? $raccordementCompany : $tk['company_name']) ?></span></div><?php endif; ?>
              <?php if ($isRaccordementClients && (!empty($raccordementSnont) || !empty($raccordementNd))): ?><div class="ftth-mobile-line"><i class="fas fa-ethernet"></i><span><?= htmlspecialchars(trim((!empty($raccordementSnont) ? 'SNONT ' . $raccordementSnont : '') . (!empty($raccordementSnont) && !empty($raccordementNd) ? ' · ' : '') . (!empty($raccordementNd) ? 'ND ' . $raccordementNd : ''))) ?></span></div><?php endif; ?>
              <?php if (!empty($tk['assigned_to'])): ?><div class="ftth-mobile-line"><i class="fas fa-user-check"></i><span><strong>Affecté à</strong> <?= htmlspecialchars($tk['assigned_to']) ?></span></div><?php endif; ?>
              <?php if (empty($tk['assigned_to'])): ?><div class="ftth-mobile-line"><i class="fas fa-clock"></i><span><strong>Affectation</strong> Non affecté</span></div><?php endif; ?>
            </div>
            <?php if (!empty($networkRefs)): ?>
            <div class="ftth-ticket-network mt-2"><?= htmlspecialchars($networkPath) ?></div>
            <?php else: ?>
            <div class="small text-muted mt-2">Aucun repère réseau renseigné.</div>
            <?php endif; ?>
            <?php if ($lastReportSavedAt !== ''): ?>
            <div class="small text-muted mt-2"><i class="fas fa-clock me-1"></i>Dernier enregistrement du formulaire : <?= htmlspecialchars($lastReportSavedAt) ?></div>
            <?php endif; ?>
            <div class="ftth-mobile-actions">
              <a href="<?= htmlspecialchars(route_url($moduleBasePath . '/detail?id='.$ticketId)) ?>" class="btn btn-sm btn-outline-primary"><i class="fas fa-eye me-1"></i>Détail</a>
              <?php if ($isAdmin && $isRaccordementClients): ?>
              <button type="button" class="btn btn-sm btn-outline-secondary btn-edit-raccordement" data-ticket='<?= htmlspecialchars(json_encode($editPayload, JSON_UNESCAPED_UNICODE), ENT_QUOTES) ?>'><i class="fas fa-pen me-1"></i>Modifier</button>
              <button type="button" class="btn btn-sm btn-outline-danger btn-priority-raccordement" data-ticket-id="<?= $ticketId ?>" data-ticket-name="<?= htmlspecialchars(($raccordementName ?: $tk['client_name']), ENT_QUOTES) ?>" data-ticket-priority="<?= htmlspecialchars((string)$tk['priority'], ENT_QUOTES) ?>"><i class="fas fa-bolt me-1"></i>Criticité</button>
              <?php endif; ?>
              <?php if ($isAdmin && !$assignmentLocked && !empty($tk['assigned_to'])): ?>
              <form method="POST" action="<?= htmlspecialchars(route_url($moduleBasePath . '/unassign')) ?>" onsubmit="return confirm('Retirer l\'assignation de ce ticket ?')">
                <input type="hidden" name="ticket_id" value="<?= $ticketId ?>">
                <button class="btn btn-sm btn-outline-danger" type="submit"><i class="fas fa-user-minus me-1"></i>Désassigner</button>
              </form>
              <?php elseif ($isAdmin && in_array($tk['status'], ['nouveau', 'assigné'], true)): ?>
              <button class="btn btn-sm btn-outline-warning btn-assign" data-id="<?= $ticketId ?>" data-client="<?= htmlspecialchars($tk['client_name'], ENT_QUOTES) ?>"><i class="fas fa-user-plus me-1"></i>Assigner</button>
              <?php endif; ?>
            </div>
          </article>
          <?php endforeach; ?>
        </div>

        <div class="ftth-desktop-table">
          <div class="ftth-bulk-toolbar">
            <div class="ftth-bulk-copy">
              <span class="ftth-bulk-badge"><i class="fas fa-check-double"></i><span id="selectedTicketCount">0</span> sélectionné(s)</span>
              <span class="ftth-bulk-summary">Sélectionnez plusieurs tickets pour lancer rapidement une assignation, une suppression ou une édition de rapport imprimable.</span>
            </div>
            <div class="ftth-bulk-actions">
              <button type="button" class="btn btn-outline-secondary btn-sm" id="btnSingleReport" disabled><i class="fas fa-file-lines me-1"></i>Rapport individuel</button>
              <button type="button" class="btn btn-outline-primary btn-sm" id="btnGroupedReport" disabled><i class="fas fa-layer-group me-1"></i>Rapport groupé</button>
              <?php if ($isAdmin): ?>
              <button type="button" class="btn btn-warning btn-sm" id="btnBulkAssign" disabled><i class="fas fa-user-plus me-1"></i>Assigner</button>
              <?php endif; ?>
              <?php if ($canDelete): ?>
              <button type="button" class="btn btn-outline-danger btn-sm" id="btnBulkDelete" disabled><i class="fas fa-trash me-1"></i>Supprimer</button>
              <?php endif; ?>
            </div>
          </div>

          <div class="ftth-table-shell">
            <div class="ftth-table-wrap">
              <table class="ftth-table">
                <thead>
                  <tr>
                    <th class="ftth-table-check"><input type="checkbox" class="form-check-input" id="selectAllTickets" aria-label="Tout sélectionner"></th>
                    <th><?= $isRaccordementClients ? 'Abonné / référence' : 'Ticket' ?></th>
                    <th><?= $isRaccordementClients ? 'Contacts & localisation' : 'Contact & site' ?></th>
                    <th><?= $isRaccordementClients ? 'Repères raccordement' : 'Réseau' ?></th>
                    <th><?= $isRaccordementClients ? 'Suivi raccordement' : 'Intervention' ?></th>
                    <th>État</th>
                    <th>Affectation</th>
                    <th class="text-end">Actions</th>
                  </tr>
                </thead>
                <tbody>
                  <?php foreach ($tickets as $tk):
                    $ticketId = (int)($tk['ticket_id'] ?? $tk['id'] ?? 0);
                    $editPayload = $buildRaccordementEditPayload($tk);
                    $priColor = ['Urgent'=>'danger','Haute'=>'warning','Moyenne'=>'primary','Basse'=>'secondary'][$tk['priority']] ?? 'secondary';
                    $stColor  = ['nouveau'=>'primary','assigné'=>'warning','en_cours'=>'info','attente_planification'=>'dark','traité'=>'success','validé'=>'success','clôturé'=>'secondary'][$tk['status']] ?? 'secondary';
                    $assignmentLocked = in_array((string)($tk['status'] ?? ''), ['validé', 'clôturé'], true);
                    $sourceLabel = (($tk['source_channel'] ?? '') === 'e-intervention') ? 'e-Intervention' : 'Opérateur direct';
                    $sourceIcon = (($tk['source_channel'] ?? '') === 'e-intervention') ? 'fa-mobile-screen-button' : 'fa-headset';
                    $extraFields = $decodeExtraFields($tk['extra_fields'] ?? null);
                    $raccordementName = $tk['client_name'] ?: $findImportedField($extraFields, ['NomClient']);
                    $raccordementSubscription = $tk['client_code'] ?: $findImportedField($extraFields, ['NumeroAbonnement', 'Numéro Abonnement']);
                    $raccordementAddress = $tk['client_address'] ?: $findImportedField($extraFields, ['Localisation']);
                    $raccordementContact1 = $tk['client_phone'] ?: $findImportedField($extraFields, ['Contact1']);
                    $raccordementContact2 = $tk['client_phone2'] ?: $findImportedField($extraFields, ['Contact2']);
                    $raccordementCity = $findImportedField($extraFields, ['Ville']);
                    $raccordementCommune = $findImportedField($extraFields, ['Commune']);
                    $raccordementPlaque = $findImportedField($extraFields, ['PLAQUE']);
                    $selectedBoxPlaque = trim((string)($tk['selected_box_plaque'] ?? ''));
                    $selectedBoxJdv = trim((string)($tk['selected_box_hub'] ?? ''));
                    $selectedBoxPco = trim((string)(($tk['selected_box_code'] ?? '') ?: ($tk['selected_otb_label'] ?? '')));
                    $displayPlaque = $selectedBoxPlaque !== '' ? $selectedBoxPlaque : ($raccordementPlaque ?: (string)($tk['sro_client'] ?? ''));
                    $displayJdv = $selectedBoxJdv !== '' ? $selectedBoxJdv : trim((string)($tk['jdv_client'] ?? ''));
                    $displayPco = $selectedBoxPco !== '' ? $selectedBoxPco : trim((string)($tk['pco_client'] ?? ''));
                    $raccordementSnont = $findImportedField($extraFields, ['SNONT']);
                    $raccordementNd = $findImportedField($extraFields, ['ND']);
                    $raccordementCompany = $tk['company_name'] ?: $findImportedField($extraFields, ['EntrepriseFTTH', 'Entreprise']);
                    $raccordementProgress = $tk['avancement'] ?: $findImportedField($extraFields, ['Avancement']);
                    $networkRefs = array_values(array_filter([
                      !empty($isRaccordementClients ? $displayPlaque : $tk['sro_client']) ? ($isRaccordementClients ? 'PLAQUE ' . $displayPlaque : 'SRO ' . $tk['sro_client']) : null,
                      !empty($isRaccordementClients ? $displayJdv : $tk['jdv_client']) ? 'JDV ' . ($isRaccordementClients ? $displayJdv : $tk['jdv_client']) : null,
                      !empty($isRaccordementClients ? $displayPco : $tk['pco_client']) ? 'PCO ' . ($isRaccordementClients ? $displayPco : $tk['pco_client']) : null,
                    ]));
                    $networkPath = implode(' => ', $networkRefs);
                    $rpSt = $tk['report_status'] ?? null;
                    $visitStatus = $tk['client_visit_status'] ?? null;
                    $visitMap = ['intervention_effectuee'=>['success','Intervention réalisée'],'client_indisponible'=>['warning','Client indisponible'],'reprogrammation_demandee'=>['info','Reprogrammation demandée']];
                    $plannedSlot = '';
                    if (!empty($tk['planned_intervention_date'])) {
                      $plannedSlot = date('d/m/Y', strtotime((string)$tk['planned_intervention_date']));
                      if (!empty($tk['planned_intervention_time'])) {
                        $plannedSlot .= ' à ' . substr((string)$tk['planned_intervention_time'], 0, 5);
                      }
                    }
                    $lastReportSavedAt = !empty($tk['report_updated_at']) ? date('d/m/Y à H:i', strtotime((string)$tk['report_updated_at'])) : '';
                    $rpMap = ['brouillon'=>['secondary','Brouillon'],'soumis'=>['warning','En attente'],'validé'=>['success','Validé'],'rejeté'=>['danger','Rejeté']];
                  ?>
                  <tr data-ticket-row data-ticket-id="<?= $ticketId ?>">
                    <td class="ftth-table-check">
                      <input type="checkbox" class="form-check-input ftth-ticket-checkbox" value="<?= $ticketId ?>" data-client="<?= htmlspecialchars($tk['client_name'], ENT_QUOTES) ?>" aria-label="Sélectionner <?= htmlspecialchars($tk['client_name']) ?>">
                    </td>
                    <td>
                      <div class="ftth-ticket-main">
                        <div class="ftth-ticket-main-top">
                          <span class="ftth-ticket-ref"><i class="fas fa-hashtag"></i><?= htmlspecialchars($isRaccordementClients ? ($raccordementSubscription ?: ($tk['ref_code'] ?: '#'.$ticketId)) : ($tk['ref_code'] ?: '#'.$ticketId)) ?></span>
                          <span class="badge bg-<?= $priColor ?>"><?= htmlspecialchars($tk['priority']) ?></span>
                        </div>
                        <div class="ftth-ticket-title"><?= htmlspecialchars($isRaccordementClients ? ($raccordementName ?: 'Client raccordement') : $tk['client_name']) ?></div>
                        <div class="ftth-ticket-subline">
                          <?php if (!empty($isRaccordementClients ? $raccordementSubscription : $tk['client_code'])): ?><span>Abonnement <?= htmlspecialchars($isRaccordementClients ? $raccordementSubscription : $tk['client_code']) ?></span><?php endif; ?>
                          <?php if (!empty($tk['fixed_line'])): ?><span>Ligne fixe <?= htmlspecialchars($tk['fixed_line']) ?></span><?php endif; ?>
                          <?php if ($isRaccordementClients && (!empty($raccordementCity) || !empty($raccordementCommune))): ?><span><?= htmlspecialchars(trim($raccordementCity . (!empty($raccordementCity) && !empty($raccordementCommune) ? ' / ' : '') . $raccordementCommune)) ?></span><?php elseif (!empty($tk['site_name'])): ?><span><?= htmlspecialchars($tk['site_name']) ?></span><?php endif; ?>
                        </div>
                      </div>
                    </td>
                    <td>
                      <div class="ftth-ticket-stack">
                        <?php if (!empty($isRaccordementClients ? $raccordementContact1 : $tk['client_phone']) || !empty($isRaccordementClients ? $raccordementContact2 : $tk['client_phone2'])): ?><span><strong>Téléphones</strong> <?= htmlspecialchars(($isRaccordementClients ? $raccordementContact1 : $tk['client_phone']) ?: '—') ?><?php if (!empty($isRaccordementClients ? $raccordementContact2 : $tk['client_phone2'])): ?>, <?= htmlspecialchars($isRaccordementClients ? $raccordementContact2 : $tk['client_phone2']) ?><?php endif; ?></span><?php endif; ?>
                        <?php if (!empty($isRaccordementClients ? $raccordementAddress : $tk['client_address'])): ?><span><strong><?= $isRaccordementClients ? 'Localisation' : 'Adresse' ?></strong> <?= htmlspecialchars($isRaccordementClients ? $raccordementAddress : $tk['client_address']) ?></span><?php endif; ?>
                        <small><strong>Origine</strong> <?= htmlspecialchars($sourceLabel) ?></small>
                        <?php if (!empty($isRaccordementClients ? $raccordementCompany : $tk['company_name'])): ?><small><strong>Entreprise</strong> <?= htmlspecialchars($isRaccordementClients ? $raccordementCompany : $tk['company_name']) ?></small><?php endif; ?>
                      </div>
                    </td>
                    <td>
                      <div class="ftth-ticket-stack">
                        <?php if (!empty($networkRefs)): ?>
                        <div class="ftth-ticket-network"><?= htmlspecialchars($networkPath) ?></div>
                        <?php else: ?>
                        <small>Aucun repère réseau renseigné</small>
                        <?php endif; ?>
                        <?php if ($isRaccordementClients && (!empty($raccordementSnont) || !empty($raccordementNd))): ?><small><?= htmlspecialchars(trim((!empty($raccordementSnont) ? 'SNONT ' . $raccordementSnont : '') . (!empty($raccordementSnont) && !empty($raccordementNd) ? ' · ' : '') . (!empty($raccordementNd) ? 'ND ' . $raccordementNd : ''))) ?></small><?php endif; ?>
                      </div>
                    </td>
                    <td>
                      <div class="ftth-ticket-stack">
                        <?php if (!empty($tk['nature_intervention']) || $isRaccordementClients): ?><span><strong><?= $isRaccordementClients ? 'Mission' : 'Nature' ?></strong> <?= htmlspecialchars($isRaccordementClients ? 'Raccordement client' : $tk['nature_intervention']) ?></span><?php endif; ?>
                        <?php if (!empty($isRaccordementClients ? $raccordementProgress : $tk['avancement'])): ?><span><strong>Avancement</strong> <?= htmlspecialchars($isRaccordementClients ? $raccordementProgress : $tk['avancement']) ?></span><?php endif; ?>
                        <?php if (!empty($tk['cause_comment'])): ?><small><strong>Cause</strong> Renseignée</small><?php endif; ?>
                        <?php if (empty($tk['nature_intervention']) && empty($isRaccordementClients ? $raccordementProgress : $tk['avancement']) && empty($tk['cause_comment'])): ?><small><?= $isRaccordementClients ? 'Suivi non détaillé' : 'Intervention non détaillée' ?></small><?php endif; ?>
                      </div>
                    </td>
                    <td>
                      <div class="ftth-state-cluster">
                        <span class="badge bg-<?= $stColor ?>"><?= htmlspecialchars($tk['status'] === 'attente_planification' ? 'En attente de planification' : ucfirst((string)$tk['status'])) ?></span>
                        <span class="badge text-bg-light border"><?php if ($rpSt && isset($rpMap[$rpSt])): ?>Rapport <?= $rpMap[$rpSt][1] ?><?php else: ?>Rapport non démarré<?php endif; ?></span>
                        <span class="badge text-bg-light border"><i class="fas <?= htmlspecialchars($sourceIcon) ?> me-1"></i><?= htmlspecialchars($sourceLabel) ?></span>
                        <?php if ($visitStatus && isset($visitMap[$visitStatus])): ?><span class="badge bg-<?= $visitMap[$visitStatus][0] ?><?= in_array($visitMap[$visitStatus][0], ['warning','info'], true) ? ' text-dark' : '' ?>"><?= htmlspecialchars($visitMap[$visitStatus][1]) ?></span><?php endif; ?>
                        <?php if ($plannedSlot !== ''): ?><span class="badge text-bg-light border"><i class="fas fa-calendar-days me-1"></i><?= htmlspecialchars($plannedSlot) ?></span><?php endif; ?>
                        <?php if ($lastReportSavedAt !== ''): ?><span class="badge text-bg-light border"><i class="fas fa-clock me-1"></i><?= htmlspecialchars($lastReportSavedAt) ?></span><?php endif; ?>
                        <div class="ftth-status-note">Importé <?= !empty($tk['imported_at']) ? htmlspecialchars(date('d/m/Y H:i', strtotime($tk['imported_at']))) : 'manuellement' ?></div>
                      </div>
                    </td>
                    <td>
                      <div class="ftth-inline-meta">
                        <?php if (!empty($tk['assigned_to'])): ?><span><i class="fas fa-user-check text-warning"></i><?= htmlspecialchars($tk['assigned_to']) ?></span><?php endif; ?>
                        <?php if (empty($tk['assigned_to'])): ?><span><i class="fas fa-clock text-secondary"></i>Non affecté</span><?php endif; ?>
                      </div>
                    </td>
                    <td>
                      <div class="ftth-row-actions">
                        <a href="<?= htmlspecialchars(route_url($moduleBasePath . '/detail?id='.$ticketId)) ?>" class="btn btn-sm btn-outline-primary"><i class="fas fa-eye me-1"></i>Détail</a>
                        <?php if ($isAdmin && $isRaccordementClients): ?>
                        <button type="button" class="btn btn-sm btn-outline-secondary btn-edit-raccordement" data-ticket='<?= htmlspecialchars(json_encode($editPayload, JSON_UNESCAPED_UNICODE), ENT_QUOTES) ?>'><i class="fas fa-pen me-1"></i>Modifier</button>
                        <button type="button" class="btn btn-sm btn-outline-danger btn-priority-raccordement" data-ticket-id="<?= $ticketId ?>" data-ticket-name="<?= htmlspecialchars(($raccordementName ?: $tk['client_name']), ENT_QUOTES) ?>" data-ticket-priority="<?= htmlspecialchars((string)$tk['priority'], ENT_QUOTES) ?>"><i class="fas fa-bolt me-1"></i>Criticité</button>
                        <?php endif; ?>
                        <button type="button" class="btn btn-sm btn-outline-secondary btn-report-single" data-id="<?= $ticketId ?>"><i class="fas fa-print me-1"></i>Rapport</button>
                        <?php if ($isAdmin && !$assignmentLocked && !empty($tk['assigned_to'])): ?>
                        <form method="POST" action="<?= htmlspecialchars(route_url($moduleBasePath . '/unassign')) ?>" onsubmit="return confirm('Retirer l\'assignation de ce ticket ?')">
                          <input type="hidden" name="ticket_id" value="<?= $ticketId ?>">
                          <button class="btn btn-sm btn-outline-danger" type="submit"><i class="fas fa-user-minus me-1"></i>Désassigner</button>
                        </form>
                        <?php elseif ($isAdmin && in_array($tk['status'], ['nouveau', 'assigné'], true)): ?>
                        <button class="btn btn-sm btn-outline-warning btn-assign" type="button" data-id="<?= $ticketId ?>" data-client="<?= htmlspecialchars($tk['client_name'], ENT_QUOTES) ?>"><i class="fas fa-user-plus me-1"></i>Assigner</button>
                        <?php endif; ?>
                      </div>
                    </td>
                  </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
          </div>
        </div>

        <!-- Pagination -->
        <?php if ($pages > 1): ?>
        <div class="card-footer d-flex justify-content-center py-3 bg-white border-top-0">
          <ul class="pagination pagination-sm mb-0">
            <?php for ($p = 1; $p <= $pages; $p++): ?>
            <li class="page-item <?= $p === $page ? 'active' : '' ?>">
              <a class="page-link" href="<?= htmlspecialchars(route_url($moduleBasePath) . '?' . http_build_query(array_merge($queryBase, ['page' => $p]))) ?>"><?= $p ?></a>
            </li>
            <?php endfor; ?>
          </ul>
        </div>
        <?php endif; ?>
        <?php endif; ?>
        </div>
      </div>
    </div>

  </div>
</section>

<!-- Modal Import -->
<?php if ($isAdmin): ?>
<div class="modal fade" id="modalImport" tabindex="-1">
  <div class="modal-dialog">
    <form method="POST" action="<?= htmlspecialchars(route_url($moduleBasePath . '/import')) ?>" enctype="multipart/form-data">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title"><i class="fas fa-file-excel text-success me-2"></i>Importer depuis Excel</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <p class="text-muted small mb-3">
            Importez le fichier <strong><?= htmlspecialchars($expectedImportFileLabel ?? 'LE STATUS DES DIFFERENTS CAS DES CLIENTS.xlsx') ?></strong> ou tout fichier Excel
            avec les colonnes : <em><?= htmlspecialchars(implode(', ', $expectedHeaders ?? [])) ?></em>
          </p>
          <div class="mb-0">
            <label class="form-label fw-semibold">Fichier Excel (.xlsx)</label>
            <input type="file" name="excel_file" class="form-control" accept=".xlsx,.xls" required>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Annuler</button>
          <button type="submit" class="btn btn-success btn-sm"><i class="fas fa-upload me-1"></i>Importer</button>
        </div>
      </div>
    </form>
  </div>
</div>

<!-- Modal Déclaration manuelle -->
<div class="modal fade ftth-create-modal" id="modalCreateTicket" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-xl modal-dialog-scrollable">
    <form method="POST" action="<?= htmlspecialchars(route_url($moduleBasePath . '/create')) ?>">
      <div class="modal-content">
        <div class="modal-header">
          <div class="modal-header-inner">
            <div>
              <div class="modal-kicker"><i class="fas fa-bolt"></i>Déclaration manuelle</div>
              <h5 class="modal-title mt-3 mb-0"><?= $isRaccordementClients ? 'Créer un raccordement client' : 'Déclarer un incident FTTH' ?></h5>
              <div class="modal-subtitle"><?= $isRaccordementClients ? 'Saisissez les principaux en-têtes RACCORDES pour créer un dossier raccordement cohérent avec le fichier d’import.' : 'Créez rapidement un ticket terrain complet, avec coordonnées réseau, informations client et assignation immédiate des techniciens si nécessaire.' ?></div>
            </div>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fermer"></button>
          </div>
        </div>
        <div class="modal-body">
          <div class="hint-panel">
            <i class="fas fa-circle-info"></i>
            <div>
              <div class="fw-semibold text-dark"><?= $isRaccordementClients ? 'Saisie alignée sur l’onglet RACCORDES' : 'Saisie alignée sur le flux terrain' ?></div>
              <div class="small text-muted mb-0"><?= $isRaccordementClients ? 'Le formulaire reprend les champs clés du fichier RACCORDES. L’assignation technicien reste optionnelle.' : 'Choisissez d\'abord le type de coupure. Le formulaire adapte ensuite les champs à renseigner. L\'assignation technicien reste optionnelle.' ?></div>
            </div>
          </div>

          <?php if ($isRaccordementClients): ?>
          <input type="hidden" name="cut_type" value="client">
          <?php else: ?>
          <div class="cut-type-switch" role="radiogroup" aria-label="Type de coupure FTTH">
            <label class="cut-type-option">
              <input type="radio" name="cut_type" value="client" checked>
              <span class="cut-type-card">
                <strong><i class="fas fa-house-signal me-2 text-primary"></i>Coupure client</strong>
                <span>Utilise le formulaire FTTH actuel avec identité client, accès, GPS et contexte terrain.</span>
              </span>
            </label>
            <label class="cut-type-option">
              <input type="radio" name="cut_type" value="transport">
              <span class="cut-type-card">
                <strong><i class="fas fa-tower-broadcast me-2 text-warning"></i>Coupure transport</strong>
                <span>Déclaration orientée réseau de transport avec zone, OLT de rattachement et détail de signalisation.</span>
              </span>
            </label>
          </div>
          <?php endif; ?>

          <div class="row g-3">
            <div class="col-12 col-lg-6">
              <div class="section-card" data-cuture-panel="client">
                <div class="card-body">
                  <div class="section-title"><i class="fas fa-id-card"></i><span><?= $isRaccordementClients ? 'Entête RACCORDES' : 'Référence et client' ?></span></div>
                  <div class="row g-3">
                    <div class="col-12 col-md-6">
                      <label class="form-label"><?= $isRaccordementClients ? 'Référence dossier' : 'Numéro de requête' ?></label>
                      <div class="input-group">
                        <span class="input-group-text"><i class="fas fa-hashtag"></i></span>
                        <input type="text" name="ref_code" class="form-control" placeholder="<?= $isRaccordementClients ? 'Ex. RACC-20260415-001' : 'Ex. RQ-20260329-001' ?>">
                      </div>
                    </div>
                    <div class="col-12 col-md-6">
                      <label class="form-label">Numéro abonnement</label>
                      <input type="text" name="client_code" class="form-control" placeholder="Référence client ou contrat">
                    </div>
                    <div class="col-12">
                      <label class="form-label">Nom du client <span class="text-danger">*</span></label>
                      <input type="text" name="client_name" class="form-control" placeholder="Nom du client ou de l'entreprise" required>
                    </div>
                    <?php if ($isRaccordementClients): ?>
                    <div class="col-12 col-md-6">
                      <label class="form-label">Ville</label>
                      <input type="text" name="raccordement_city" class="form-control" placeholder="Ville du client">
                    </div>
                    <div class="col-12 col-md-6">
                      <label class="form-label">Commune</label>
                      <input type="text" name="raccordement_commune" class="form-control" placeholder="Commune ou secteur">
                    </div>
                    <?php endif; ?>
                    <div class="col-12 col-md-6">
                      <label class="form-label">Contact client 1</label>
                      <input type="text" name="client_phone" class="form-control" placeholder="Téléphone principal">
                    </div>
                    <div class="col-12 col-md-6">
                      <label class="form-label">Contact client 2</label>
                      <input type="text" name="client_phone2" class="form-control" placeholder="Téléphone secondaire">
                    </div>
                    <div class="col-12">
                      <label class="form-label">Localisation</label>
                      <textarea name="client_address" class="form-control" rows="3" placeholder="Adresse, repères d'accès, bâtiment, niveau..."></textarea>
                    </div>
                    <div class="col-12 col-md-6"<?= $isRaccordementClients ? ' hidden' : '' ?>>
                      <label class="form-label">Ligne fixe</label>
                      <input type="text" name="fixed_line" class="form-control" placeholder="Numéro FTTH fixe">
                    </div>
                    <?php if ($isRaccordementClients): ?>
                    <div class="col-12 col-md-6">
                      <label class="form-label">Latitude_Terrain</label>
                      <input type="text" name="raccordement_latitude" class="form-control" placeholder="Ex. 6.767202">
                    </div>
                    <div class="col-12 col-md-6">
                      <label class="form-label">Longitude_Terrain</label>
                      <input type="text" name="raccordement_longitude" class="form-control" placeholder="Ex. -5.279581">
                    </div>
                    <?php else: ?>
                    <div class="col-12 col-md-6">
                      <label class="form-label">Coordonnées GPS</label>
                      <input type="text" name="gps" class="form-control" placeholder="6.767202, -5.279581">
                      <div class="helper-text">Format attendu: latitude, longitude.</div>
                    </div>
                    <?php endif; ?>
                  </div>
                </div>
              </div>
            </div>

            <div class="col-12 col-lg-6">
              <div class="section-card" data-cuture-panel="common client">
                <div class="card-body">
                  <div class="section-title"><i class="fas fa-network-wired"></i><span><?= $isRaccordementClients ? 'Repères et pilotage raccordement' : 'Topologie et pilotage' ?></span></div>
                  <div class="row g-3">
                    <div class="col-12 col-md-4">
                      <label class="form-label"><?= $isRaccordementClients ? 'PLAQUE' : 'SRO client' ?></label>
                      <input type="text" name="sro_client" class="form-control" placeholder="<?= $isRaccordementClients ? 'Repère plaque' : 'Code SRO' ?>" <?= $isRaccordementClients ? 'disabled readonly' : '' ?>>
                    </div>
                    <div class="col-12 col-md-4">
                      <label class="form-label"><?= $isRaccordementClients ? 'JDV' : 'JDV client' ?></label>
                      <input type="text" name="jdv_client" class="form-control" placeholder="Repère JDV" <?= $isRaccordementClients ? 'disabled readonly' : '' ?>>
                    </div>
                    <div class="col-12 col-md-4">
                      <label class="form-label"><?= $isRaccordementClients ? 'PCO' : 'PCO client' ?></label>
                      <input type="text" name="pco_client" class="form-control" placeholder="Repère PCO" <?= $isRaccordementClients ? 'disabled readonly' : '' ?>>
                    </div>
                    <div class="col-12">
                      <label class="form-label"><?= $isRaccordementClients ? 'EntrepriseFTTH' : 'Entreprise / porteur d\'action' ?></label>
                      <input type="text" name="company_name" class="form-control" placeholder="<?= $isRaccordementClients ? 'Entreprise FTTH concernée' : 'Prestataire, porteur ou entité concernée' ?>">
                    </div>
                    <?php if ($isRaccordementClients): ?>
                    <div class="col-12 col-md-6">
                      <label class="form-label">SNONT</label>
                      <input type="text" name="raccordement_snont" class="form-control" placeholder="Identifiant SNONT">
                    </div>
                    <div class="col-12 col-md-6">
                      <label class="form-label">ND</label>
                      <input type="text" name="raccordement_nd" class="form-control" placeholder="Numéro ND">
                    </div>
                    <div class="col-12 col-md-6">
                      <label class="form-label">Date_Enregistrement_Instances</label>
                      <input type="date" name="raccordement_date_enregistrement" class="form-control">
                    </div>
                    <div class="col-12 col-md-6">
                      <label class="form-label">Date_Envoi_Instances_Prestataires</label>
                      <input type="date" name="raccordement_date_envoi_prestataires" class="form-control">
                    </div>
                    <div class="col-12 col-md-6">
                      <label class="form-label">Duree_attente_j</label>
                      <input type="text" name="raccordement_duree_attente" class="form-control" placeholder="Nombre de jours">
                    </div>
                    <div class="col-12 col-md-6">
                      <label class="form-label">Equipe_raccordement</label>
                      <input type="text" name="raccordement_team" class="form-control" placeholder="Équipe ou prestataire terrain">
                    </div>
                    <?php endif; ?>
                    <div class="col-12 col-md-4">
                      <label class="form-label">Avancement</label>
                      <input type="text" name="avancement" class="form-control" placeholder="<?= $isRaccordementClients ? 'Ex. En attente planification' : 'Ex. En attente client' ?>">
                    </div>
                    <div class="col-12 col-md-4">
                      <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 class="col-12 col-md-4">
                      <label class="form-label">Statut initial</label>
                      <select name="status" class="form-select">
                        <?php foreach (['nouveau','assigné','en_cours'] as $statusOption): ?>
                        <option value="<?= htmlspecialchars($statusOption) ?>"><?= htmlspecialchars(ucfirst($statusOption)) ?></option>
                        <?php endforeach; ?>
                      </select>
                    </div>
                    <div class="col-12"<?= $isRaccordementClients ? ' hidden' : '' ?>>
                      <label class="form-label">Date de clôture</label>
                      <input type="text" name="date_cloture" class="form-control" placeholder="Optionnel, ex. 29/03/2026">
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div class="col-12 col-lg-6">
              <div class="section-card" data-cuture-panel="transport" hidden>
                <div class="card-body">
                  <div class="section-title"><i class="fas fa-tower-cell"></i><span>Référence transport</span></div>
                  <div class="row g-3">
                    <div class="col-12">
                      <label class="form-label">Numéro de requête</label>
                      <div class="input-group">
                        <span class="input-group-text"><i class="fas fa-hashtag"></i></span>
                        <input type="text" name="transport_ref_code" class="form-control" placeholder="Ex. TR-20260329-001">
                      </div>
                    </div>
                    <div class="col-12">
                      <label class="form-label">Zone</label>
                      <input type="text" name="transport_zone" class="form-control" placeholder="Zone impactée ou périmètre concerné">
                    </div>
                    <div class="col-12">
                      <label class="form-label">OLT de rattachement</label>
                      <input type="text" name="transport_olt" class="form-control" placeholder="OLT de rattachement">
                    </div>
                    <div class="col-12 col-md-4">
                      <label class="form-label">SRO</label>
                      <input type="text" name="transport_sro" class="form-control" placeholder="Code SRO">
                    </div>
                    <div class="col-12 col-md-4">
                      <label class="form-label">JDV</label>
                      <input type="text" name="transport_jdv" class="form-control" placeholder="Repère JDV">
                    </div>
                    <div class="col-12 col-md-4">
                      <label class="form-label">PCO</label>
                      <input type="text" name="transport_pco" class="form-control" placeholder="Repère PCO">
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div class="col-12 col-lg-6">
              <div class="section-card" data-cuture-panel="common transport" hidden>
                <div class="card-body">
                  <div class="section-title"><i class="fas fa-sliders"></i><span>Pilotage transport</span></div>
                  <div class="row g-3">
                    <div class="col-12 col-md-6">
                      <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 class="col-12 col-md-6">
                      <label class="form-label">Statut initial</label>
                      <select name="status" class="form-select">
                        <?php foreach (['nouveau','assigné','en_cours'] as $statusOption): ?>
                        <option value="<?= htmlspecialchars($statusOption) ?>"><?= htmlspecialchars(ucfirst($statusOption)) ?></option>
                        <?php endforeach; ?>
                      </select>
                    </div>
                    <div class="col-12">
                      <label class="form-label">Date de clôture</label>
                      <input type="text" name="date_cloture" class="form-control" placeholder="Optionnel, ex. 29/03/2026">
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div class="col-12 col-lg-7">
              <div class="section-card" data-cuture-panel="common client">
                <div class="card-body">
                  <div class="section-title"><i class="fas fa-file-lines"></i><span><?= $isRaccordementClients ? 'Commentaires et étude technique' : 'Contexte de l\'incident' ?></span></div>
                  <div class="row g-3">
                    <?php if ($isRaccordementClients): ?>
                    <div class="col-12">
                      <label class="form-label">Etude_Technique</label>
                      <textarea name="raccordement_etude_technique" class="form-control" rows="3" placeholder="Précisez l'étude technique, les contraintes identifiées et la préparation du raccordement..."></textarea>
                    </div>
                    <?php endif; ?>
                    <div class="col-12">
                      <label class="form-label"><?= $isRaccordementClients ? 'Commentaires' : 'Commentaire' ?></label>
                      <textarea name="description" class="form-control" rows="4" placeholder="<?= $isRaccordementClients ? 'Commentaires opérationnels, contexte terrain, repères d\'accès ou précisions client...' : 'Décrivez le symptôme, l\'impact métier, les informations collectées auprès du client...' ?>"></textarea>
                    </div>
                    <div class="col-12">
                      <label class="form-label"><?= $isRaccordementClients ? 'Problèmes' : 'Commentaire_cause' ?></label>
                      <textarea name="cause_comment" class="form-control" rows="4" placeholder="<?= $isRaccordementClients ? 'Blocages, anomalies réseau, refus d\'accès, besoin matériel ou incident observé...' : 'Cause probable, contexte technique, antécédents ou hypothèses terrain...' ?>"></textarea>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div class="col-12 col-lg-7">
              <div class="section-card" data-cuture-panel="transport" hidden>
                <div class="card-body">
                  <div class="section-title"><i class="fas fa-wave-square"></i><span>Signalisation transport</span></div>
                  <div class="row g-3">
                    <div class="col-12">
                      <label class="form-label">Détail de la signalisation</label>
                      <textarea name="transport_signal_details" class="form-control" rows="5" placeholder="Décrivez les alarmes, pertes de signal, symptômes OLT, remontées NMS ou observations réseau..."></textarea>
                    </div>
                    <div class="col-12">
                      <label class="form-label">Commentaire_cause</label>
                      <textarea name="cause_comment" class="form-control" rows="4" placeholder="Cause probable, contexte technique, incident upstream, coupure fibre ou défaut d'équipement..."></textarea>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div class="col-12 col-lg-5">
              <div class="section-card" data-cuture-panel="common client transport">
                <div class="card-body">
                  <div class="section-title"><i class="fas fa-user-plus"></i><span>Assignation terrain</span></div>
                  <div class="mb-3">
                    <label class="form-label">Technicien(s) terrain à assigner</label>
                    <select name="technician_ids[]" class="form-select" multiple size="<?= min(7, max(4, count($technicians))) ?>">
                      <?php foreach ($technicians as $tech): ?>
                      <option value="<?= (int)$tech['id'] ?>"><?= htmlspecialchars($tech['name']) ?></option>
                      <?php endforeach; ?>
                    </select>
                    <div class="helper-text">Laissez vide pour créer la déclaration sans assignation immédiate. Utilisez Ctrl+clic pour une sélection multiple.</div>
                  </div>
                  <div>
                    <label class="form-label">Notes d'assignation</label>
                    <textarea name="assignment_notes" class="form-control" rows="6" placeholder="Consignes terrain, matériel à prévoir, contraintes d'accès, personne à contacter..."></textarea>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <div class="footer-note me-auto"><?= $isRaccordementClients ? 'Le dossier raccordement est créé immédiatement avec les champs RACCORDES saisis. Si des techniciens sont sélectionnés, ils seront assignés et notifiés dans la foulée.' : 'Le ticket est créé immédiatement. Si des techniciens sont sélectionnés, ils seront assignés et notifiés dans la foulée.' ?></div>
          <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><?= $isRaccordementClients ? 'Créer le raccordement' : 'Créer la déclaration' ?></button>
        </div>
      </div>
    </form>
  </div>
</div>

<!-- Modal Assignation rapide -->
<div class="modal fade" id="modalAssign" tabindex="-1">
  <div class="modal-dialog modal-sm">
    <form method="POST" action="<?= htmlspecialchars(route_url($moduleBasePath . '/assign')) ?>">
      <input type="hidden" name="ticket_id" id="assignTicketId">
      <div class="modal-content">
        <div class="modal-header py-2">
          <h6 class="modal-title"><i class="fas fa-user-plus me-2 text-warning"></i>Assigner</h6>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <p class="small text-muted mb-2">Client : <strong id="assignClientName"></strong></p>
          <div class="mb-2">
            <label class="form-label small fw-semibold">Technicien(s)</label>
            <select name="technician_ids[]" class="form-select form-select-sm" multiple size="<?= min(6, max(3, count($technicians))) ?>" required>
              <?php foreach ($technicians as $tech): ?>
              <option value="<?= (int)$tech['id'] ?>"><?= htmlspecialchars($tech['name']) ?></option>
              <?php endforeach; ?>
            </select>
            <small class="text-muted">Ctrl+clic pour sélection multiple</small>
          </div>
          <div>
            <label class="form-label small">Notes</label>
            <textarea name="notes" class="form-control form-control-sm" rows="2"></textarea>
          </div>
        </div>
        <div class="modal-footer py-2">
          <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Annuler</button>
          <button type="submit" class="btn btn-warning btn-sm"><i class="fas fa-paper-plane me-1"></i>Assigner & Notifier</button>
        </div>
      </div>
    </form>
  </div>
</div>

<?php if ($isAdmin && $isRaccordementClients): ?>
<div class="modal fade ftth-create-modal" id="modalEditRaccordement" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-xl modal-dialog-scrollable">
    <form method="POST" action="<?= htmlspecialchars(route_url($moduleBasePath . '/update')) ?>">
      <input type="hidden" name="ticket_id" id="editRaccordementTicketId">
      <div class="modal-content">
        <div class="modal-header">
          <div class="modal-header-inner">
            <div>
              <div class="modal-kicker"><i class="fas fa-pen"></i>Modification</div>
              <h5 class="modal-title mt-3 mb-0">Modifier un raccordement</h5>
              <div class="modal-subtitle">Mettez à jour les principaux champs RACCORDES du dossier sans repasser par l'import Excel.</div>
            </div>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fermer"></button>
          </div>
        </div>
        <div class="modal-body">
          <div class="row g-3">
            <div class="col-12 col-lg-6">
              <div class="section-card">
                <div class="card-body">
                  <div class="section-title"><i class="fas fa-id-card"></i><span>Entête RACCORDES</span></div>
                  <div class="row g-3">
                    <div class="col-12 col-md-6">
                      <label class="form-label">Référence dossier</label>
                      <input type="text" name="ref_code" id="edit_ref_code" class="form-control">
                    </div>
                    <div class="col-12 col-md-6">
                      <label class="form-label">Numéro abonnement</label>
                      <input type="text" name="client_code" id="edit_client_code" class="form-control">
                    </div>
                    <div class="col-12">
                      <label class="form-label">Nom du client</label>
                      <input type="text" name="client_name" id="edit_client_name" class="form-control" required>
                    </div>
                    <div class="col-12 col-md-6">
                      <label class="form-label">Ville</label>
                      <input type="text" name="raccordement_city" id="edit_raccordement_city" class="form-control">
                    </div>
                    <div class="col-12 col-md-6">
                      <label class="form-label">Commune</label>
                      <input type="text" name="raccordement_commune" id="edit_raccordement_commune" class="form-control">
                    </div>
                    <div class="col-12 col-md-6">
                      <label class="form-label">Contact client 1</label>
                      <input type="text" name="client_phone" id="edit_client_phone" class="form-control">
                    </div>
                    <div class="col-12 col-md-6">
                      <label class="form-label">Contact client 2</label>
                      <input type="text" name="client_phone2" id="edit_client_phone2" class="form-control">
                    </div>
                    <div class="col-12">
                      <label class="form-label">Localisation</label>
                      <textarea name="client_address" id="edit_client_address" class="form-control" rows="3"></textarea>
                    </div>
                    <div class="col-12 col-md-6">
                      <label class="form-label">Latitude_Terrain</label>
                      <input type="text" name="raccordement_latitude" id="edit_raccordement_latitude" class="form-control">
                    </div>
                    <div class="col-12 col-md-6">
                      <label class="form-label">Longitude_Terrain</label>
                      <input type="text" name="raccordement_longitude" id="edit_raccordement_longitude" class="form-control">
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-12 col-lg-6">
              <div class="section-card">
                <div class="card-body">
                  <div class="section-title"><i class="fas fa-network-wired"></i><span>Repères et pilotage</span></div>
                  <div class="row g-3">
                    <div class="col-12 col-md-4">
                      <label class="form-label">PLAQUE</label>
                      <input type="text" name="sro_client" id="edit_sro_client" class="form-control">
                    </div>
                    <div class="col-12 col-md-4">
                      <label class="form-label">JDV</label>
                      <input type="text" name="jdv_client" id="edit_jdv_client" class="form-control">
                    </div>
                    <div class="col-12 col-md-4">
                      <label class="form-label">PCO</label>
                      <input type="text" name="pco_client" id="edit_pco_client" class="form-control">
                    </div>
                    <div class="col-12">
                      <label class="form-label">EntrepriseFTTH</label>
                      <input type="text" name="company_name" id="edit_company_name" class="form-control">
                    </div>
                    <div class="col-12 col-md-6">
                      <label class="form-label">SNONT</label>
                      <input type="text" name="raccordement_snont" id="edit_raccordement_snont" class="form-control">
                    </div>
                    <div class="col-12 col-md-6">
                      <label class="form-label">ND</label>
                      <input type="text" name="raccordement_nd" id="edit_raccordement_nd" class="form-control">
                    </div>
                    <div class="col-12 col-md-6">
                      <label class="form-label">Date_Enregistrement_Instances</label>
                      <input type="date" name="raccordement_date_enregistrement" id="edit_raccordement_date_enregistrement" class="form-control">
                    </div>
                    <div class="col-12 col-md-6">
                      <label class="form-label">Date_Envoi_Instances_Prestataires</label>
                      <input type="date" name="raccordement_date_envoi_prestataires" id="edit_raccordement_date_envoi_prestataires" class="form-control">
                    </div>
                    <div class="col-12 col-md-6">
                      <label class="form-label">Duree_attente_j</label>
                      <input type="text" name="raccordement_duree_attente" id="edit_raccordement_duree_attente" class="form-control">
                    </div>
                    <div class="col-12 col-md-6">
                      <label class="form-label">Equipe_raccordement</label>
                      <input type="text" name="raccordement_team" id="edit_raccordement_team" class="form-control">
                    </div>
                    <div class="col-12 col-md-4">
                      <label class="form-label">Avancement</label>
                      <input type="text" name="avancement" id="edit_avancement" class="form-control">
                    </div>
                    <div class="col-12 col-md-4">
                      <label class="form-label">Priorité</label>
                      <select name="priority" id="edit_priority" class="form-select">
                        <?php foreach (['Moyenne','Haute','Urgent','Basse'] as $priority): ?>
                        <option value="<?= htmlspecialchars($priority) ?>"><?= htmlspecialchars($priority) ?></option>
                        <?php endforeach; ?>
                      </select>
                    </div>
                    <div class="col-12 col-md-4">
                      <label class="form-label">Statut</label>
                      <select name="status" id="edit_status" class="form-select">
                        <?php foreach (['nouveau','assigné','en_cours','attente_planification','traité','validé','clôturé'] as $statusOption): ?>
                        <option value="<?= htmlspecialchars($statusOption) ?>"><?= htmlspecialchars($statusOption === 'attente_planification' ? 'En attente de planification' : ucfirst($statusOption)) ?></option>
                        <?php endforeach; ?>
                      </select>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-12">
              <div class="section-card">
                <div class="card-body">
                  <div class="section-title"><i class="fas fa-file-lines"></i><span>Commentaires et étude technique</span></div>
                  <div class="row g-3">
                    <div class="col-12">
                      <label class="form-label">Etude_Technique</label>
                      <textarea name="raccordement_etude_technique" id="edit_raccordement_etude_technique" class="form-control" rows="3"></textarea>
                    </div>
                    <div class="col-12 col-lg-6">
                      <label class="form-label">Commentaires</label>
                      <textarea name="description" id="edit_description" class="form-control" rows="4"></textarea>
                    </div>
                    <div class="col-12 col-lg-6">
                      <label class="form-label">Problèmes</label>
                      <textarea name="cause_comment" id="edit_cause_comment" class="form-control" rows="4"></textarea>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <div class="footer-note me-auto">Les changements sont appliqués immédiatement au dossier et aux champs RACCORDES associés.</div>
          <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 les modifications</button>
        </div>
      </div>
    </form>
  </div>
</div>

<div class="modal fade" id="modalPriorityRaccordement" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-sm modal-dialog-centered">
    <form method="POST" action="<?= htmlspecialchars(route_url($moduleBasePath . '/requalify-priority')) ?>">
      <input type="hidden" name="ticket_id" id="priorityTicketId">
      <div class="modal-content">
        <div class="modal-header py-2">
          <h6 class="modal-title"><i class="fas fa-bolt me-2 text-danger"></i>Requalifier la criticité</h6>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <p class="small text-muted mb-3">Dossier : <strong id="priorityTicketName"></strong></p>
          <label class="form-label small fw-semibold">Nouvelle criticité</label>
          <select name="priority" id="priorityTicketValue" class="form-select" required>
            <?php foreach (['Basse','Moyenne','Haute','Urgent'] as $priority): ?>
            <option value="<?= htmlspecialchars($priority) ?>"><?= htmlspecialchars($priority) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="modal-footer py-2">
          <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Annuler</button>
          <button type="submit" class="btn btn-danger btn-sm"><i class="fas fa-bolt me-1"></i>Mettre à jour</button>
        </div>
      </div>
    </form>
  </div>
</div>
<?php endif; ?>

<div class="modal fade" id="modalBulkAssign" tabindex="-1">
  <div class="modal-dialog modal-sm">
    <form method="POST" action="<?= htmlspecialchars(route_url($moduleBasePath . '/bulk-assign')) ?>" id="bulkAssignForm">
      <div id="bulkAssignSelectionFields"></div>
      <div class="modal-content">
        <div class="modal-header py-2">
          <h6 class="modal-title"><i class="fas fa-people-arrows me-2 text-warning"></i>Assignation rapide</h6>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <p class="small text-muted mb-2"><strong id="bulkAssignCountLabel">0 ticket</strong> seront affectés.</p>
          <div class="mb-2">
            <label class="form-label small fw-semibold">Technicien(s)</label>
            <select name="technician_ids[]" class="form-select form-select-sm" multiple size="<?= min(6, max(3, count($technicians))) ?>" required>
              <?php foreach ($technicians as $tech): ?>
              <option value="<?= (int)$tech['id'] ?>"><?= htmlspecialchars($tech['name']) ?></option>
              <?php endforeach; ?>
            </select>
            <small class="text-muted">Les techniciens sélectionnés seront notifiés sur tous les tickets cochés.</small>
          </div>
          <div>
            <label class="form-label small">Notes</label>
            <textarea name="notes" class="form-control form-control-sm" rows="3" placeholder="Consignes communes pour la tournée, contraintes d’accès, pièces à prévoir..."></textarea>
          </div>
        </div>
        <div class="modal-footer py-2">
          <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Annuler</button>
          <button type="submit" class="btn btn-warning btn-sm"><i class="fas fa-paper-plane me-1"></i>Assigner la sélection</button>
        </div>
      </div>
    </form>
  </div>
</div>

<form method="POST" action="<?= htmlspecialchars(route_url($moduleBasePath . '/bulk-delete')) ?>" id="bulkDeleteForm" class="d-none">
  <div id="bulkDeleteSelectionFields"></div>
</form>

<div class="modal fade ftth-confirm-modal" id="modalBulkDelete" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered modal-sm">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="btn-close ms-auto" data-bs-dismiss="modal" aria-label="Fermer"></button>
      </div>
      <div class="modal-body">
        <div class="ftth-confirm-hero">
          <div class="ftth-confirm-icon"><i class="fas fa-trash"></i></div>
          <div class="ftth-confirm-copy">
            <strong>Supprimer la sélection</strong>
            <p>Cette action retirera les tickets sélectionnés ainsi que leurs assignations, rapports et pièces associées.</p>
          </div>
        </div>
        <div class="ftth-confirm-meta">
          <span class="ftth-confirm-pill"><i class="fas fa-check-double"></i><span id="bulkDeleteCountLabel">0 ticket</span></span>
          <span class="ftth-confirm-pill"><i class="fas fa-database"></i>Données liées incluses</span>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Annuler</button>
        <button type="button" class="btn btn-danger" id="confirmBulkDeleteBtn"><i class="fas fa-trash me-1"></i>Supprimer</button>
      </div>
    </div>
  </div>
</div>
<?php endif; ?>

<script>
const selectionReportBaseUrl = '<?= htmlspecialchars(route_url($moduleBasePath . '/report/selection')) ?>';

function syncCutTypePanels(type) {
  document.querySelectorAll('[data-cuture-panel]').forEach((panel) => {
    const allowedTypes = String(panel.getAttribute('data-cuture-panel') || '').split(/\s+/).filter(Boolean);
    const isVisible = allowedTypes.includes(type);
    panel.hidden = !isVisible;
    panel.querySelectorAll('input, select, textarea, button').forEach((field) => {
      if (field.type === 'radio' && field.name === 'cut_type') return;
      field.disabled = !isVisible;
    });
  });
}

document.querySelectorAll('input[name="cut_type"]').forEach((input) => {
  input.addEventListener('change', () => syncCutTypePanels(input.value));
});

syncCutTypePanels(document.querySelector('input[name="cut_type"]:checked')?.value || 'client');

document.querySelectorAll('.btn-assign').forEach(btn => {
  btn.addEventListener('click', () => {
    document.getElementById('assignTicketId').value  = btn.dataset.id;
    document.getElementById('assignClientName').textContent = btn.dataset.client;
    new bootstrap.Modal(document.getElementById('modalAssign')).show();
  });
});

document.querySelectorAll('.btn-edit-raccordement').forEach((button) => {
  button.addEventListener('click', () => {
    const payload = JSON.parse(button.getAttribute('data-ticket') || '{}');
    const fieldMap = {
      editRaccordementTicketId: 'id',
      edit_ref_code: 'ref_code',
      edit_client_code: 'client_code',
      edit_client_name: 'client_name',
      edit_client_phone: 'client_phone',
      edit_client_phone2: 'client_phone2',
      edit_client_address: 'client_address',
      edit_raccordement_city: 'raccordement_city',
      edit_raccordement_commune: 'raccordement_commune',
      edit_raccordement_latitude: 'raccordement_latitude',
      edit_raccordement_longitude: 'raccordement_longitude',
      edit_sro_client: 'sro_client',
      edit_jdv_client: 'jdv_client',
      edit_pco_client: 'pco_client',
      edit_company_name: 'company_name',
      edit_raccordement_snont: 'raccordement_snont',
      edit_raccordement_nd: 'raccordement_nd',
      edit_raccordement_date_enregistrement: 'raccordement_date_enregistrement',
      edit_raccordement_date_envoi_prestataires: 'raccordement_date_envoi_prestataires',
      edit_raccordement_duree_attente: 'raccordement_duree_attente',
      edit_raccordement_team: 'raccordement_team',
      edit_raccordement_etude_technique: 'raccordement_etude_technique',
      edit_avancement: 'avancement',
      edit_priority: 'priority',
      edit_status: 'status',
      edit_description: 'description',
      edit_cause_comment: 'cause_comment'
    };

    Object.entries(fieldMap).forEach(([fieldId, payloadKey]) => {
      const field = document.getElementById(fieldId);
      if (!field) return;
      field.value = payload[payloadKey] ?? '';
    });

    new bootstrap.Modal(document.getElementById('modalEditRaccordement')).show();
  });
});

document.querySelectorAll('.btn-priority-raccordement').forEach((button) => {
  button.addEventListener('click', () => {
    const ticketIdField = document.getElementById('priorityTicketId');
    const ticketNameField = document.getElementById('priorityTicketName');
    const ticketPriorityField = document.getElementById('priorityTicketValue');
    if (ticketIdField) ticketIdField.value = button.getAttribute('data-ticket-id') || '';
    if (ticketNameField) ticketNameField.textContent = button.getAttribute('data-ticket-name') || '';
    if (ticketPriorityField) ticketPriorityField.value = button.getAttribute('data-ticket-priority') || 'Moyenne';
    new bootstrap.Modal(document.getElementById('modalPriorityRaccordement')).show();
  });
});

const ticketCheckboxes = Array.from(document.querySelectorAll('.ftth-ticket-checkbox'));
const selectAllTickets = document.getElementById('selectAllTickets');
const selectedTicketCount = document.getElementById('selectedTicketCount');
const btnSingleReport = document.getElementById('btnSingleReport');
const btnGroupedReport = document.getElementById('btnGroupedReport');
const btnBulkAssign = document.getElementById('btnBulkAssign');
const btnBulkDelete = document.getElementById('btnBulkDelete');
const confirmBulkDeleteBtn = document.getElementById('confirmBulkDeleteBtn');

function getSelectedTicketIds() {
  return ticketCheckboxes.filter((checkbox) => checkbox.checked).map((checkbox) => checkbox.value);
}

function fillSelectionFields(containerId, selectedIds) {
  const container = document.getElementById(containerId);
  if (!container) return;
  container.innerHTML = selectedIds.map((id) => `<input type="hidden" name="selected_ticket_ids[]" value="${id}">`).join('');
}

function refreshTicketSelectionUi() {
  const selectedIds = getSelectedTicketIds();
  if (selectedTicketCount) {
    selectedTicketCount.textContent = String(selectedIds.length);
  }

  ticketCheckboxes.forEach((checkbox) => {
    checkbox.closest('[data-ticket-row]')?.classList.toggle('is-selected', checkbox.checked);
  });

  if (selectAllTickets) {
    const allSelected = ticketCheckboxes.length > 0 && selectedIds.length === ticketCheckboxes.length;
    selectAllTickets.checked = allSelected;
    selectAllTickets.indeterminate = selectedIds.length > 0 && !allSelected;
  }

  if (btnSingleReport) btnSingleReport.disabled = selectedIds.length !== 1;
  if (btnGroupedReport) btnGroupedReport.disabled = selectedIds.length === 0;
  if (btnBulkAssign) btnBulkAssign.disabled = selectedIds.length === 0;
  if (btnBulkDelete) btnBulkDelete.disabled = selectedIds.length === 0;

  fillSelectionFields('bulkAssignSelectionFields', selectedIds);
  fillSelectionFields('bulkDeleteSelectionFields', selectedIds);
}

selectAllTickets?.addEventListener('change', () => {
  ticketCheckboxes.forEach((checkbox) => {
    checkbox.checked = selectAllTickets.checked;
  });
  refreshTicketSelectionUi();
});

ticketCheckboxes.forEach((checkbox) => {
  checkbox.addEventListener('change', refreshTicketSelectionUi);
});

document.querySelectorAll('.btn-report-single').forEach((button) => {
  button.addEventListener('click', () => {
    window.open(`${selectionReportBaseUrl}?mode=single&ids=${encodeURIComponent(button.dataset.id)}`, '_blank', 'noopener');
  });
});

btnSingleReport?.addEventListener('click', () => {
  const selectedIds = getSelectedTicketIds();
  if (selectedIds.length !== 1) return;
  window.open(`${selectionReportBaseUrl}?mode=single&ids=${encodeURIComponent(selectedIds[0])}`, '_blank', 'noopener');
});

btnGroupedReport?.addEventListener('click', () => {
  const selectedIds = getSelectedTicketIds();
  if (!selectedIds.length) return;
  window.open(`${selectionReportBaseUrl}?mode=group&ids=${encodeURIComponent(selectedIds.join(','))}`, '_blank', 'noopener');
});

btnBulkAssign?.addEventListener('click', () => {
  const selectedIds = getSelectedTicketIds();
  if (!selectedIds.length) return;
  const countLabel = document.getElementById('bulkAssignCountLabel');
  if (countLabel) {
    countLabel.textContent = `${selectedIds.length} ticket${selectedIds.length > 1 ? 's' : ''}`;
  }
  new bootstrap.Modal(document.getElementById('modalBulkAssign')).show();
});

btnBulkDelete?.addEventListener('click', () => {
  const selectedIds = getSelectedTicketIds();
  if (!selectedIds.length) return;
  const countLabel = document.getElementById('bulkDeleteCountLabel');
  if (countLabel) {
    countLabel.textContent = `${selectedIds.length} ticket${selectedIds.length > 1 ? 's' : ''}`;
  }
  new bootstrap.Modal(document.getElementById('modalBulkDelete')).show();
});

confirmBulkDeleteBtn?.addEventListener('click', () => {
  document.getElementById('bulkDeleteForm')?.submit();
});

refreshTicketSelectionUi();
</script>
