<?php
// Topbar spécifique gestion_compagnies
// Récupération utilisateur courant si disponible
if(function_exists('gc_current_user') && isset($gc_pdo)){
  try { $gc_user = gc_current_user($gc_pdo); } catch(Throwable $e){ $gc_user=null; }
} else { $gc_user=null; }

// Comptage justificatifs de paiement en attente (dossiers avec fichiers)
$pendingPayments = [];
try {
  $uploadsBase = __DIR__.DIRECTORY_SEPARATOR.'files'.DIRECTORY_SEPARATOR.'uploads';
  if(is_dir($uploadsBase)){
    foreach(scandir($uploadsBase) as $d){
      if($d==='.'||$d==='..') continue;
      $full = $uploadsBase.DIRECTORY_SEPARATOR.$d;
      if(is_dir($full)){
        $hasFile=false;
        foreach(scandir($full) as $f){ if($f==='.'||$f==='..') continue; if(is_file($full.DIRECTORY_SEPARATOR.$f)){ $hasFile=true; break; } }
        if($hasFile) $pendingPayments[]=$d; // $d supposé être compagnie_ref
      }
    }
  }
} catch(Throwable $e){ /* silent */ }
$pendingCount = count($pendingPayments);

// Compagnies en attente de validation (validation=0)
$pendingValidationCount = 0;
try {
  if(isset($gc_pdo)){
    $pendingValidationCount = (int)$gc_pdo->query("SELECT COUNT(*) FROM compagnies_table WHERE validation=0")->fetchColumn();
  }
} catch(Throwable $e){ /* silent */ }

// Récupérer les noms d'agence pour les refs trouvées
$pendingAgencies = [];
if($pendingCount && isset($gc_pdo)){
  // Filtrer valeurs sûres (alphanum, underscore, tiret)
  $safeRefs = array_filter($pendingPayments,function($r){ return preg_match('~^[A-Za-z0-9_-]+$~',$r); });
  if($safeRefs){
    $placeholders = implode(',', array_fill(0,count($safeRefs),'?'));
    try {
      $stN = $gc_pdo->prepare("SELECT compagnie_ref, compagnie_name FROM compagnies_table WHERE compagnie_ref IN ($placeholders)");
      $stN->execute($safeRefs);
      while($row=$stN->fetch(PDO::FETCH_ASSOC)){
        $pendingAgencies[$row['compagnie_ref']] = $row['compagnie_name'];
      }
    } catch(Throwable $e){ /* silent */ }
  }
}
// Calcul compteur notifications (style includes/topbar.php)
$notif_count = 0;
if($pendingValidationCount>0) $notif_count++; // une notification catégorie validation
if($pendingCount>0) $notif_count++;            // une notification catégorie justificatifs paiement
?>
<nav class="navbar navbar-expand navbar-light bg-navbar topbar mb-4 static-top shadow">
  <button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3">
    <i class="fa fa-bars"></i>
  </button>
  <ul class="navbar-nav ml-auto">
    <!-- Notifications -->
    <li class="nav-item dropdown no-arrow mx-1">
      <a class="nav-link dropdown-toggle" href="#" id="gcAlerts" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        <i class="fas fa-bell fa-fw"></i>
        <?php if($notif_count>0): ?>
          <span class="badge badge-danger badge-counter"><?php echo $notif_count; ?></span>
        <?php endif; ?>
      </a>
      <div class="dropdown-list dropdown-menu dropdown-menu-right shadow animated--grow-in" aria-labelledby="gcAlerts">
        <h6 class="dropdown-header">Notifications</h6>
        <?php if($pendingValidationCount>0): ?>
          <a class="dropdown-item d-flex align-items-center" href="valider_compagnies.php">
            <div class="mr-3"><div class="icon-circle bg-info"><i class="fas fa-building text-white"></i></div></div>
            <div>
              <div class="small text-gray-500"><?php echo date('d/m/Y'); ?></div>
              <span class="font-weight-bold"><?php echo $pendingValidationCount; ?> compagnie(s) à valider</span>
            </div>
          </a>
        <?php endif; ?>
        <?php if($pendingCount>0): ?>
          <?php $maxList=5; $shown=0; foreach($pendingPayments as $ref){ if($shown>=$maxList) break; $shown++; $nm=$pendingAgencies[$ref]??$ref; ?>
            <a class="dropdown-item d-flex align-items-center" href="review_justifs.php?ref=<?php echo urlencode($ref); ?>">
              <div class="mr-3"><div class="icon-circle bg-warning"><i class="fas fa-hourglass-half text-white"></i></div></div>
              <div>
                <div class="small text-gray-500"><?php echo date('d/m/Y'); ?></div>
                <span class="font-weight-bold">Justificatif: <?php echo htmlspecialchars(mb_strimwidth($nm,0,28,'…','UTF-8')); ?></span>
              </div>
            </a>
          <?php } if($pendingCount>$maxList){ ?>
            <a class="dropdown-item text-center small text-primary" href="review_justifs.php">+ <?php echo ($pendingCount-$maxList); ?> autres...</a>
          <?php } ?>
        <?php endif; ?>
        <?php if($notif_count===0): ?>
          <span class="dropdown-item small text-muted">Aucune notification.</span>
        <?php endif; ?>
      </div>
    </li>
    <div class="topbar-divider d-none d-sm-block"></div>
    <li class="nav-item dropdown no-arrow">
      <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        <img class="img-profile rounded-circle" src="../img/boy.png" style="max-width:40px">
        <span class="ml-2 d-none d-lg-inline text-white small">
          <?php
            if(!empty($gc_user)){
              $name = trim(($gc_user['first_name']??'').' '.($gc_user['last_name']??''));
              if($name==='') $name = $gc_user['user_email'] ?? 'Utilisateur';
              echo htmlspecialchars($name);
            } else {
              echo 'Utilisateur';
            }
          ?>
        </span>
      </a>
      <div class="dropdown-menu dropdown-menu-right shadow animated--grow-in" aria-labelledby="userDropdown">
  <a class="dropdown-item" href="logout.php"><i class="fas fa-sign-out-alt fa-sm fa-fw mr-2 text-gray-400"></i> Déconnexion</a>
      </div>
    </li>
  </ul>
</nav>
