<?php
// csr_manager/notifications.php
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['csr_id'])) { header('Location: ../login.php'); exit(); }

require_once __DIR__ . '/../config/database.php';

$db = (new Database())->getConnection();
$csrId = (int)$_SESSION['csr_id'];

// Mark all as read if requested
if (isset($_POST['mark_all_read'])) {
    $db->prepare("UPDATE csr_notifications SET is_read = 1 WHERE csr_id = :id")
       ->execute([':id' => $csrId]);
    header('Location: notifications.php'); exit();
}

// Mark single as read
if (isset($_GET['read']) && is_numeric($_GET['read'])) {
    $db->prepare("UPDATE csr_notifications SET is_read = 1 WHERE id = :id AND csr_id = :cid")
       ->execute([':id' => (int)$_GET['read'], ':cid' => $csrId]);
}

$page     = max(1, (int)($_GET['page'] ?? 1));
$perPage  = 20;
$offset   = ($page - 1) * $perPage;
$filter = $_GET['filter'] ?? 'all'; // all | unread
// Whitelist — never inject user input directly
if (!in_array($filter, ['all', 'unread'], true)) $filter = 'all';
$whereExtra = $filter === 'unread' ? " AND is_read = 0" : "";
$total = (int)$db->prepare("SELECT COUNT(*) FROM csr_notifications WHERE csr_id = :id $whereExtra")
                 ->execute([':id' => $csrId]) ? $db->query("SELECT FOUND_ROWS()")->fetchColumn() : 0;

$countStmt = $db->prepare("SELECT COUNT(*) FROM csr_notifications WHERE csr_id = :id $whereExtra");
$countStmt->execute([':id' => $csrId]);
$total = (int)$countStmt->fetchColumn();
$totalPages = max(1, (int)ceil($total / $perPage));

$stmt = $db->prepare("SELECT * FROM csr_notifications WHERE csr_id = :id $whereExtra ORDER BY created_at DESC LIMIT :lim OFFSET :off");
$stmt->bindValue(':id', $csrId, PDO::PARAM_INT);
$stmt->bindValue(':lim', $perPage, PDO::PARAM_INT);
$stmt->bindValue(':off', $offset, PDO::PARAM_INT);
$stmt->execute();
$notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);

$unreadStmt = $db->prepare("SELECT COUNT(*) FROM csr_notifications WHERE csr_id=:id AND is_read=0");
$unreadStmt->execute([':id' => $csrId]);
$unreadCount = (int)$unreadStmt->fetchColumn();

$title = 'Notifications';
function h(string $s): string { return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); }

ob_start();
?>

<div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-4">
  <div>
    <h2 style="font-family:'Space Grotesk',system-ui,sans-serif;font-weight:800;margin:0;">
      <i class="fas fa-bell me-2" style="color:var(--cm-blue);"></i>Notifications
      <?php if ($unreadCount > 0): ?>
        <span class="cm-badge cm-badge--red ms-2"><?= $unreadCount ?> unread</span>
      <?php endif; ?>
    </h2>
    <small style="color:var(--cm-muted);">Your activity feed and system alerts</small>
  </div>
  <div style="display:flex;gap:8px;flex-wrap:wrap;">
    <a href="?filter=all"    class="cm-btn <?= $filter==='all'   ? 'cm-btn--active':'' ?>">All</a>
    <a href="?filter=unread" class="cm-btn <?= $filter==='unread'? 'cm-btn--active':'' ?>">Unread</a>
    <?php if ($unreadCount > 0): ?>
    <form method="POST" style="margin:0;">
      <button type="submit" name="mark_all_read" class="cm-btn cm-btn--primary">
        <i class="fas fa-check-double me-1"></i>Mark all read
      </button>
    </form>
    <?php endif; ?>
  </div>
</div>

<div class="cm-card">
  <?php if (empty($notifications)): ?>
    <div style="text-align:center;padding:40px 0;color:var(--cm-muted);">
      <i class="fas fa-bell-slash" style="font-size:2.5rem;opacity:.3;margin-bottom:12px;display:block;"></i>
      <?= $filter === 'unread' ? 'No unread notifications.' : 'No notifications yet.' ?>
    </div>
  <?php else: ?>
  <div class="cm-table-wrap">
    <table class="cm-table">
      <thead>
        <tr>
          <th style="width:32px;"></th>
          <th>Notification</th>
          <th>Type</th>
          <th>Time</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($notifications as $n):
          $isUnread = !(int)$n['is_read'];
          $typeColors = ['success'=>'cm-badge--green','warning'=>'cm-badge--yellow','danger'=>'cm-badge--red','info'=>'cm-badge--blue','primary'=>'cm-badge--blue'];
          $typeIcons  = ['success'=>'fa-check-circle','warning'=>'fa-exclamation-triangle','danger'=>'fa-times-circle','info'=>'fa-info-circle','primary'=>'fa-bell'];
          $tc   = $typeColors[$n['type'] ?? 'info'] ?? 'cm-badge--blue';
          $ti   = $typeIcons[$n['type']  ?? 'info'] ?? 'fa-bell';
          $link = h(addslashes($n['link'] ?? ''));
        ?>
        <tr
          onclick="cmNotifClick(<?= (int)$n['id'] ?>,'<?= $link ?>')"
          style="cursor:pointer;<?= $isUnread ? 'background:oklch(0.62 0.22 255 / 0.05);' : '' ?>"
        >
          <td>
            <?php if ($isUnread): ?>
              <span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:var(--cm-blue);"></span>
            <?php endif; ?>
          </td>
          <td>
            <div style="font-weight:<?= $isUnread ? '700' : '500' ?>;font-size:.88rem;"><?= h($n['title'] ?? '') ?></div>
            <div style="font-size:.78rem;color:var(--cm-muted);margin-top:2px;"><?= h(mb_strimwidth($n['message'] ?? '', 0, 120, '…')) ?></div>
          </td>
          <td>
            <span class="cm-badge <?= $tc ?>">
              <i class="fas <?= $ti ?> me-1"></i><?= h(ucfirst($n['type'] ?? 'info')) ?>
            </span>
          </td>
          <td style="font-size:.78rem;color:var(--cm-muted);white-space:nowrap;">
            <?= h(date('M d, g:i A', strtotime($n['created_at']))) ?>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>

  <!-- Pager -->
  <?php if ($totalPages > 1): ?>
  <div style="display:flex;gap:6px;flex-wrap:wrap;margin-top:14px;">
    <?php for ($p = 1; $p <= $totalPages; $p++): ?>
      <a href="?filter=<?= h($filter) ?>&page=<?= $p ?>"
         class="cm-btn <?= $p === $page ? 'cm-btn--active' : '' ?>"
         style="padding:6px 11px;"><?= $p ?></a>
    <?php endfor; ?>
    <span style="align-self:center;color:var(--cm-muted);font-size:.78rem;"><?= $total ?> total</span>
  </div>
  <?php endif; ?>
  <?php endif; ?>
</div>

<script>
function cmNotifClick(id, link) {
  $.post('../csr/ajax/mark_notification_read.php', { notification_id: id });
  if (link) { window.location.href = link; }
}
</script>

<?php
$content = ob_get_clean();
include __DIR__ . '/layout.php';
?>
