<?php
/**
 * Widget: Listen-Übersicht
 * ---------------------------------------------------------------
 * Tabelle       lists              (id, name …)
 * Zwischentabelle recipient_lists  (list_id, recipient_id …)
 *
 * Ergebnis:
 *   • Top-10 der größten Listen mit Empfänger­anzahl
 *   • Summenzeile „übrige Listen“, falls >10
 */

try {
    /* ============================================================
     * 1) Alle Listen & Counts ermitteln
     * ========================================================== */
    $sql = "
        SELECT l.id, l.name, COUNT(rl.recipient_id) AS cnt
        FROM lists AS l
        LEFT JOIN recipient_lists AS rl ON l.id = rl.list_id
        GROUP BY l.id
        ORDER BY cnt DESC, l.name
    ";
    $stmt = $db->query($sql);
    $lists = $stmt->fetchAll(PDO::FETCH_ASSOC);

    ErrorLogger::logSqlSuccess(__FILE__ . ' | LISTS with counts');

    /* Top-10 + Rest zusammenstellen */
    $top    = array_slice($lists, 0, 10);
    $others = array_slice($lists, 10);

    $otherTotal = 0;
    foreach ($others as $row) {
        $otherTotal += $row['cnt'];
    }

} catch (Throwable $e) {
    ErrorLogger::logSqlError(__FILE__ . ' | ' . $e->getMessage());

    echo "<div class='alert alert-danger auto-dismiss' role='alert'>
            <i class='ti ti-bug me-1'></i>
            Die Listen-Statistiken konnten nicht geladen werden.
          </div>";
    return;
}
?>

<div class="card shadow-sm h-100">
  <div class="card-body">

    <div class="d-flex align-items-center mb-3">
      <i class="ti ti-list-check fs-3 me-2"></i>
      <h5 class="card-title mb-0">Empfänger&nbsp;pro&nbsp;Liste</h5>
    </div>

    <ul class="list-group list-group-flush small">
      <?php foreach ($top as $row): ?>
        <li class="list-group-item d-flex justify-content-between align-items-center px-0">
          <span>
            <i class="ti ti-tag me-1"></i><?= htmlspecialchars($row['name']) ?>
          </span>
          <span class="badge bg-primary-subtle text-primary fw-semibold">
            <?= number_format($row['cnt'],0,',','.') ?>
          </span>
        </li>
      <?php endforeach; ?>

      <?php if ($otherTotal > 0): ?>
        <li class="list-group-item d-flex justify-content-between align-items-center px-0">
          <span><i class="ti ti-dots me-1"></i>übrige&nbsp;Listen</span>
          <span class="badge bg-secondary-subtle text-secondary fw-semibold">
            <?= number_format($otherTotal,0,',','.') ?>
          </span>
        </li>
      <?php endif; ?>
    </ul>

  </div>
</div>
