<?php 
use App\Core\Auth; 
$title = 'Notifications';
$base = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? ''), '/'); if ($base === '/') { $base = ''; }
?>
<div class="card shadow-sm">
  <div class="card-header d-flex justify-content-between align-items-center">
    <strong>Notifications</strong>
    <form method="post" action="<?= htmlspecialchars($base) ?>/notifications/read-all" class="m-0">
      <button class="btn btn-sm btn-outline-primary">Tout marquer comme lu</button>
    </form>
  </div>
  <div class="card-body p-0">
    <?php if (empty($notifications)): ?>
      <div class="p-3 text-muted">Aucune notification.</div>
    <?php else: ?>
      <?php
        $isMentionNotif = function(array $n): bool {
          $t = strtolower((string)($n['title'] ?? ''));
          $b = strtolower((string)($n['body'] ?? ''));
          if (str_contains($t, 'mention')) { return true; }
          if (str_contains($b, 'mention')) { return true; }
          return (bool)preg_match('/@\[[^\]]+\]|@[a-z0-9_\.-]+/i', (string)($n['body'] ?? ''));
        };
      ?>
      <ul class="list-group list-group-flush">
        <?php foreach ($notifications as $n): ?>
          <li class="list-group-item d-flex justify-content-between align-items-start <?= ((int)$n['is_read']===0?'bg-light':'') ?>">
            <div class="ms-2 me-auto">
              <div class="fw-semibold">
                <?= htmlspecialchars($n['title']) ?>
                <?php if ($isMentionNotif($n)): ?>
                  <span class="badge text-bg-warning ms-1">Mention</span>
                <?php endif; ?>
              </div>
              <div class="small text-muted"><?= htmlspecialchars($n['body']) ?></div>
              <?php if (!empty($n['url'])): ?>
                <a class="small" href="<?= htmlspecialchars($n['url']) ?>">Ouvrir</a>
              <?php endif; ?>
            </div>
            <div class="d-flex align-items-center gap-2 ms-3">
              <?php if ((int)($n['is_read'] ?? 0) === 0): ?>
                <form method="post" action="<?= htmlspecialchars($base) ?>/notifications/read" class="m-0">
                  <input type="hidden" name="id" value="<?= (int)($n['id'] ?? 0) ?>">
                  <button class="btn btn-sm btn-link p-0">Marquer comme lu</button>
                </form>
              <?php endif; ?>
              <span class="badge text-bg-secondary rounded-pill"><?= date('d/m H:i', strtotime($n['created_at'])) ?></span>
            </div>
          </li>
        <?php endforeach; ?>
      </ul>
    <?php endif; ?>
  </div>
</div>
