<?php
session_start();

// ── Notification actions run BEFORE any HTML output ─────────────────────────
// This keeps AJAX responses clean JSON, and lets the "all" actions redirect
// without hitting "headers already sent" (which was showing a blank page).
require_once __DIR__ . '/config/db.php';
$uid = (int)($_SESSION['user_id'] ?? 0);

if ($uid && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    // Mark one / delete one (AJAX)
    if ($action === 'mark_read' || $action === 'delete') {
        header('Content-Type: application/json');
        $nid = (int)($_POST['id'] ?? 0);
        $sql = $action === 'delete'
            ? "DELETE FROM customer_notifications WHERE id=? AND user_id=?"
            : "UPDATE customer_notifications SET is_read=1 WHERE id=? AND user_id=?";
        $st = $conn->prepare($sql);
        $st->bind_param("ii", $nid, $uid);
        echo json_encode(['ok' => $st->execute()]);
        exit;
    }

    // Mark all as read
    if ($action === 'mark_all_read') {
        $st = $conn->prepare("UPDATE customer_notifications SET is_read=1 WHERE user_id=?");
        $st->bind_param("i", $uid);
        $st->execute();
        header("Location: notifications.php");
        exit;
    }

    // Clear all
    if ($action === 'clear_all') {
        $st = $conn->prepare("DELETE FROM customer_notifications WHERE user_id=?");
        $st->bind_param("i", $uid);
        $st->execute();
        header("Location: notifications.php");
        exit;
    }
}

$page_title = 'Notifications';
$active_nav = 'notifications';
include("includes/header.php");
$uid = (int)$_SESSION['user_id'];

// ── Filter/pagination params ──────────────────────────────────────────────
$filter  = in_array($_GET['filter'] ?? '', ['orders','payments']) ? $_GET['filter'] : 'all';
$page    = max(1, (int)($_GET['page'] ?? 1));
$perpage = 20;
$offset  = ($page - 1) * $perpage;

$type_filter = '';
if ($filter === 'orders')   $type_filter = " AND cn.type IN ('order_update','broadcast')";
if ($filter === 'payments') $type_filter = " AND cn.type IN ('wallet_funded')";

// ── Total count ───────────────────────────────────────────────────────────
$count_stmt = $conn->prepare(
    "SELECT COUNT(*) FROM customer_notifications cn WHERE cn.user_id = ? $type_filter"
);
$count_stmt->bind_param("i", $uid);
$count_stmt->execute();
$total_count = (int)$count_stmt->get_result()->fetch_row()[0];
$total_pages = max(1, ceil($total_count / $perpage));

// ── Fetch notifications ───────────────────────────────────────────────────
$ns = $conn->prepare(
    "SELECT cn.*, r.name as restaurant_name, r.logo as restaurant_logo
     FROM customer_notifications cn
     LEFT JOIN restaurants r ON cn.restaurant_id = r.id
     WHERE cn.user_id = ? $type_filter
     ORDER BY cn.created_at DESC
     LIMIT ? OFFSET ?"
);
$ns->bind_param("iii", $uid, $perpage, $offset);
$ns->execute();
$notifications = $ns->get_result()->fetch_all(MYSQLI_ASSOC);

// ── Unread count (always all types) ───────────────────────────────────────
$unread_stmt = $conn->prepare(
    "SELECT COUNT(*) FROM customer_notifications WHERE user_id=? AND is_read=0"
);
$unread_stmt->bind_param("i", $uid);
$unread_stmt->execute();
$unread_count = (int)$unread_stmt->get_result()->fetch_row()[0];

// ── Date group label helper ────────────────────────────────────────────────
function date_group_label(string $datetime): string {
    $today     = date('Y-m-d');
    $yesterday = date('Y-m-d', strtotime('-1 day'));
    $date      = date('Y-m-d', strtotime($datetime));
    if ($date === $today)     return 'TODAY';
    if ($date === $yesterday) return 'YESTERDAY';
    $diff_days = (int)floor((strtotime($today) - strtotime($date)) / 86400);
    if ($diff_days < 7)       return strtoupper(date('l', strtotime($datetime)));
    return strtoupper(date('l, F j', strtotime($datetime)));
}

// ── Notification type → icon ───────────────────────────────────────────────
function notif_icon(string $type): array {
    $map = [
        'order_update'     => ['bg'=>'#EEF3FF', 'stroke'=>'#225AE3',
            'path'=>'<path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2"/><rect x="9" y="3" width="6" height="4" rx="1"/><path d="M9 12h6M9 16h4"/>'],
        'wallet_funded'    => ['bg'=>'#ECFDF5', 'stroke'=>'#10B981',
            'path'=>'<path d="M12 2v20M17 5H9.5a3.5 3.5 0 000 7h5a3.5 3.5 0 010 7H6"/>'],
        'broadcast'        => ['bg'=>'#FFF7ED', 'stroke'=>'#F59E0B',
            'path'=>'<path d="M18 8A6 6 0 006 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 01-3.46 0"/>'],
        'org_announcement' => ['bg'=>'#F5F3FF', 'stroke'=>'#8B5CF6',
            'path'=>'<circle cx="12" cy="12" r="10"/><path d="M12 8v4M12 16h.01"/>'],
        'promo'            => ['bg'=>'#FEF2F2', 'stroke'=>'#EF4444',
            'path'=>'<path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/>'],
    ];
    return $map[$type] ?? ['bg'=>'#F1F5F9', 'stroke'=>'#64748B',
        'path'=>'<circle cx="12" cy="12" r="10"/><path d="M12 8v4M12 16h.01"/>'];
}

// ── Time-ago helper ────────────────────────────────────────────────────────
function time_ago(string $datetime): string {
    $diff = time() - strtotime($datetime);
    if ($diff < 60)     return 'just now';
    if ($diff < 3600)   return floor($diff / 60) . 'm ago';
    if ($diff < 86400)  return floor($diff / 3600) . 'h ago';
    if ($diff < 604800) return floor($diff / 86400) . 'd ago';
    return date('M j', strtotime($datetime));
}

// ── Group notifications by date ────────────────────────────────────────────
$grouped = [];
foreach ($notifications as $n) {
    $grp = date_group_label($n['created_at']);
    $grouped[$grp][] = $n;
}
?>

<style>
/* ═══════════════════════════════════════════════════════════════════════
   NOTIFICATIONS — FULLY RESPONSIVE
   ═══════════════════════════════════════════════════════════════════════ */

* { -webkit-tap-highlight-color: transparent; }

.notif-page {
  max-width: 680px;
  margin: 0 auto;
}

/* ── Header ───────────────────────────────────────────────────────── */
.notif-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 12px;
  margin-bottom: clamp(18px, 5vw, 26px);
  flex-wrap: wrap;
}
.notif-header-left { flex: 1; min-width: 0; }
.notif-header-left h1 {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
  font-size: clamp(1.25rem, 5.5vw, 1.5rem);
  font-weight: 800;
  letter-spacing: -.04em;
  line-height: 1.1;
  margin-bottom: 4px;
}
.notif-header-left h1 .bell-icon { color: var(--primary); flex-shrink: 0; }
.notif-header-left h1 .badge-new {
  font-size: clamp(.62rem, 2vw, .72rem);
  font-weight: 700;
  background: var(--error);
  color: #fff;
  padding: 3px 9px;
  border-radius: 20px;
  white-space: nowrap;
  letter-spacing: 0;
}
.notif-header-left p {
  font-size: clamp(.74rem, 2.3vw, .84rem);
  color: var(--text-muted);
  margin: 0;
}
.notif-header-right { display: flex; align-items: center; gap: 8px; flex-shrink: 0; }
.mark-all-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  background: none;
  border: 1.5px solid var(--border);
  border-radius: 20px;
  padding: clamp(7px, 2.5vw, 9px) clamp(12px, 3.5vw, 16px);
  font-size: clamp(.73rem, 2.2vw, .8rem);
  font-weight: 700;
  color: var(--text-muted);
  cursor: pointer;
  transition: all .18s;
  white-space: nowrap;
  min-height: 38px;
  touch-action: manipulation;
  font-family: var(--font);
}
.mark-all-btn:hover { border-color: var(--primary); color: var(--primary); }
@media (hover: none) { .mark-all-btn:hover { border-color: var(--border); color: var(--text-muted); } }
.mark-all-btn:active { border-color: var(--primary); color: var(--primary); background: var(--primary-bg); }

/* ── Manage bar ───────────────────────────────────────────────────── */
.notif-manage-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  margin-bottom: clamp(14px, 4vw, 20px);
  flex-wrap: wrap;
}
.notif-manage-bar p {
  font-size: clamp(.74rem, 2.3vw, .82rem);
  color: var(--text-muted);
  margin: 0;
}

/* ── Filter tabs ──────────────────────────────────────────────────── */
.notif-filter-tabs {
  display: flex;
  gap: clamp(2px, 1vw, 6px);
  margin-bottom: clamp(16px, 4.5vw, 22px);
  border-bottom: 1.5px solid var(--border);
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
  scrollbar-width: none;
}
.notif-filter-tabs::-webkit-scrollbar { display: none; }
.nft-tab {
  padding: clamp(8px, 2.5vw, 10px) clamp(14px, 4vw, 20px);
  font-size: clamp(.76rem, 2.3vw, .84rem);
  font-weight: 700;
  color: var(--text-muted);
  text-decoration: none;
  border-bottom: 2.5px solid transparent;
  margin-bottom: -1.5px;
  white-space: nowrap;
  display: flex;
  align-items: center;
  gap: 5px;
  transition: all .18s;
  touch-action: manipulation;
  flex-shrink: 0;
  min-height: 40px;
}
.nft-tab:hover { color: var(--primary); }
.nft-tab.active { color: var(--primary); border-bottom-color: var(--primary); }
.nft-tab .tab-badge {
  font-size: .65rem;
  font-weight: 700;
  background: var(--error);
  color: #fff;
  padding: 2px 6px;
  border-radius: 10px;
  line-height: 1.3;
}
.nft-tab.active .tab-badge { background: var(--primary); }

/* ── Group label ──────────────────────────────────────────────────── */
.notif-group-label {
  font-size: clamp(.65rem, 2vw, .72rem);
  font-weight: 800;
  letter-spacing: .1em;
  color: var(--text-muted);
  padding: clamp(12px, 3.5vw, 16px) 0 clamp(8px, 2.5vw, 12px);
  text-transform: uppercase;
}

/* ── Notification card ────────────────────────────────────────────── */
.notif-card {
  display: flex;
  gap: clamp(10px, 3vw, 16px);
  padding: clamp(14px, 4vw, 18px);
  background: #fff;
  border: 1.5px solid var(--border);
  border-radius: clamp(14px, 3.5vw, 18px);
  margin-bottom: clamp(8px, 2.5vw, 12px);
  cursor: pointer;
  transition: border-color .18s, box-shadow .18s, transform .12s;
  touch-action: manipulation;
  min-height: 72px;
}
.notif-card.unread {
  background: #F5F8FF;
  border-color: rgba(34,90,227,.22);
}
.notif-card:hover {
  border-color: rgba(34,90,227,.3);
  box-shadow: 0 4px 16px rgba(34,90,227,.08);
}
@media (hover: none) {
  .notif-card:hover { border-color: var(--border); box-shadow: none; }
  .notif-card.unread:hover { border-color: rgba(34,90,227,.22); }
  .notif-card:active { transform: scale(0.98); }
}
.notif-del-x { flex-shrink: 0; align-self: center; width: 42px; height: 42px; border: none; background: transparent; color: var(--text-light); border-radius: 10px; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: background .15s, color .15s; touch-action: manipulation; }
.notif-del-x:hover { background: var(--error-bg); color: var(--error); }
.notif-card.removing { transition: transform .28s ease, opacity .28s ease; }
.clear-all-btn { display: inline-flex; align-items: center; gap: 5px; border: none; background: var(--error-bg); color: var(--error); font-weight: 700; font-size: .8rem; cursor: pointer; font-family: var(--font); padding: 7px 12px; border-radius: 10px; white-space: nowrap; }
.clear-all-btn:active { opacity: .85; }

/* ── Icon ─────────────────────────────────────────────────────────── */
.notif-icon {
  width: clamp(40px, 12vw, 46px);
  height: clamp(40px, 12vw, 46px);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

/* ── Content ──────────────────────────────────────────────────────── */
.notif-content { flex: 1; min-width: 0; }
.notif-meta {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 6px;
  margin-bottom: 4px;
}
.notif-source {
  font-size: clamp(.7rem, 2vw, .76rem);
  font-weight: 700;
  color: var(--primary);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.notif-meta-right { display: flex; align-items: center; gap: 6px; flex-shrink: 0; }
.unread-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--primary); flex-shrink: 0; }
.notif-time {
  font-size: clamp(.66rem, 2vw, .72rem);
  color: var(--text-muted);
  white-space: nowrap;
}
.notif-title {
  font-size: clamp(.82rem, 2.5vw, .9rem);
  font-weight: 700;
  margin-bottom: 4px;
  line-height: 1.3;
}
.notif-card:not(.unread) .notif-title { font-weight: 600; }
.notif-body {
  font-size: clamp(.74rem, 2.2vw, .8rem);
  color: var(--text-muted);
  line-height: 1.55;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
.notif-view-menu {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  margin-top: 9px;
  padding: clamp(6px, 2vw, 7px) clamp(12px, 3.5vw, 14px);
  border: 1.5px solid var(--primary);
  color: var(--primary);
  border-radius: 20px;
  font-size: clamp(.72rem, 2vw, .78rem);
  font-weight: 700;
  text-decoration: none;
  transition: all .18s;
  touch-action: manipulation;
  min-height: 34px;
}
.notif-view-menu:hover { background: var(--primary); color: #fff; }
@media (hover: none) { .notif-view-menu:hover { background: none; color: var(--primary); } }
.notif-view-menu:active { background: var(--primary); color: #fff; }

/* ── Empty state ──────────────────────────────────────────────────── */
.notif-empty {
  padding: clamp(40px, 12vw, 60px) 24px;
  text-align: center;
  color: var(--text-muted);
}
.notif-empty p.title { font-weight: 700; margin-bottom: 6px; font-size: clamp(.88rem, 2.8vw, 1rem); }
.notif-empty p.sub   { font-size: clamp(.78rem, 2.3vw, .86rem); line-height: 1.5; }

/* ── Pagination ───────────────────────────────────────────────────── */
.notif-pagination {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  gap: 6px;
  margin-top: clamp(16px, 4vw, 24px);
  padding-bottom: clamp(12px, 3vw, 20px);
}
.notif-pg-btn {
  min-width: clamp(34px, 10vw, 38px);
  height: clamp(34px, 10vw, 38px);
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 9px;
  font-size: clamp(.78rem, 2.3vw, .84rem);
  font-weight: 700;
  border: 1.5px solid var(--border);
  background: #fff;
  color: var(--text);
  text-decoration: none;
  padding: 0 8px;
  transition: all .15s;
  white-space: nowrap;
  touch-action: manipulation;
}
.notif-pg-btn.active { background: var(--primary); color: #fff; border-color: var(--primary); }
.notif-pg-btn:hover:not(.active) { border-color: var(--primary); color: var(--primary); }
@media (hover: none) { .notif-pg-btn:hover:not(.active) { border-color: var(--border); color: var(--text); } }

/* ── Fine-grain breakpoints ────────────────────────────────────────── */
@media (max-width: 480px) {
  .notif-card { padding: 13px; gap: 10px; border-radius: 14px; }
  .notif-icon { width: 40px; height: 40px; }
  .mark-all-btn { padding: 7px 11px; font-size: .73rem; }
}
@media (max-width: 375px) {
  .notif-header { gap: 8px; margin-bottom: 16px; }
  .notif-header-left h1 { font-size: 1.2rem; }
  .nft-tab { padding: 8px 12px; font-size: .75rem; }
  .notif-card { padding: 12px; gap: 9px; }
  .notif-icon { width: 38px; height: 38px; }
  .notif-body { -webkit-line-clamp: 2; }
}
@media (max-width: 320px) {
  .notif-card { padding: 11px 10px; gap: 8px; border-radius: 12px; }
  .notif-icon { width: 34px; height: 34px; }
  .mark-all-btn .btn-text { display: none; }
  .nft-tab { padding: 7px 10px; font-size: .72rem; }
}

/* Landscape small phones */
@media (max-height: 480px) and (orientation: landscape) {
  .notif-card { padding: 11px 14px; }
  .notif-empty { padding: 28px 24px; }
}

/* Safe area insets */
@supports (padding: max(0px)) {
  @media (max-width: 1024px) {
    .notif-page { padding-bottom: max(0px, env(safe-area-inset-bottom)); }
  }
}
</style>

<div class="notif-page">

  <!-- ── Header ──────────────────────────────────────────────────────────── -->
  <div class="notif-header">
    <div class="notif-header-left">
      <h1>
        <span class="bell-icon">
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round">
            <path d="M18 8A6 6 0 006 8c0 7-3 9-3 9h18s-3-2-3-9"/>
            <path d="M13.73 21a2 2 0 01-3.46 0"/>
          </svg>
        </span>
        Notifications
        <?php if ($unread_count > 0): ?>
          <span class="badge-new"><?php echo $unread_count; ?> new</span>
        <?php endif; ?>
      </h1>
      <p>Manage your alerts</p>
    </div>
    <?php if ($unread_count > 0): ?>
    <div class="notif-header-right">
      <form method="POST">
        <input type="hidden" name="action" value="mark_all_read">
        <button type="submit" class="mark-all-btn">
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
            <polyline points="20 6 9 17 4 12"/>
          </svg>
          <span class="btn-text">Mark all as read</span>
        </button>
      </form>
    </div>
    <?php endif; ?>
  </div>

  <!-- ── Filter tabs ──────────────────────────────────────────────────────── -->
  <div class="notif-filter-tabs">
    <a href="notifications.php?filter=all"
       class="nft-tab <?php echo $filter==='all'?'active':''; ?>">
      All
      <?php if ($unread_count > 0 && $filter==='all'): ?>
        <span class="tab-badge"><?php echo $unread_count; ?></span>
      <?php endif; ?>
    </a>
    <a href="notifications.php?filter=orders"
       class="nft-tab <?php echo $filter==='orders'?'active':''; ?>">
      Orders
    </a>
    <a href="notifications.php?filter=payments"
       class="nft-tab <?php echo $filter==='payments'?'active':''; ?>">
      Payments
    </a>
  </div>

  <!-- ── Manage bar ─────────────────────────────────────────────────────── -->
  <div class="notif-manage-bar" style="display:flex;align-items:center;justify-content:space-between;gap:12px">
    <p style="margin:0"><?php echo $total_count; ?> notification<?php echo $total_count != 1 ? 's' : ''; ?> · <span style="color:var(--text-light)">swipe to remove</span></p>
    <?php if ($total_count > 0): ?>
    <form method="POST" onsubmit="return confirm('Clear all notifications? This cannot be undone.')">
      <input type="hidden" name="action" value="clear_all">
      <button type="submit" class="clear-all-btn">
        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18M8 6V4a2 2 0 012-2h4a2 2 0 012 2v2m3 0v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6"/></svg>
        Clear all
      </button>
    </form>
    <?php endif; ?>
  </div>

  <!-- ── Notification list ─────────────────────────────────────────────── -->
  <?php if (empty($grouped)): ?>
  <div class="notif-empty">
    <svg width="46" height="46" viewBox="0 0 24 24" fill="none" stroke="var(--border)" stroke-width="1.5" stroke-linecap="round" style="margin:0 auto 14px;display:block">
      <path d="M18 8A6 6 0 006 8c0 7-3 9-3 9h18s-3-2-3-9"/>
      <path d="M13.73 21a2 2 0 01-3.46 0"/>
    </svg>
    <p class="title">
      <?php echo $filter !== 'all' ? 'No ' . $filter . ' notifications' : 'No notifications yet'; ?>
    </p>
    <p class="sub">
      <?php if ($filter !== 'all'): ?>
        <a href="notifications.php" style="color:var(--primary);font-weight:700">View all notifications →</a>
      <?php else: ?>
        You'll receive updates about your orders and wallet here
      <?php endif; ?>
    </p>
  </div>
  <?php else:
    foreach ($grouped as $group_label => $items): ?>

    <div class="notif-group-label"><?php echo htmlspecialchars($group_label); ?></div>

    <?php foreach ($items as $n):
      $is_unread = !$n['is_read'];
      $ago       = time_ago($n['created_at']);
      $full_date = date('l, F j, Y \a\t g:i A', strtotime($n['created_at']));
      $icon      = notif_icon($n['type'] ?? '');
      $is_promo  = ($n['type'] === 'promo');
      $source    = $n['restaurant_name'] ?? 'Dabil';
    ?>
    <div id="notif-<?php echo $n['id']; ?>"
         class="notif-card <?php echo $is_unread ? 'unread' : ''; ?>"
         style="cursor:pointer"
         onclick="location.href='notification_detail.php?id=<?php echo (int)$n['id']; ?>'">

      <!-- Icon -->
      <div class="notif-icon" style="background:<?php echo $icon['bg']; ?>">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none"
             stroke="<?php echo $icon['stroke']; ?>"
             stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <?php echo $icon['path']; ?>
        </svg>
      </div>

      <!-- Content -->
      <div class="notif-content">
        <div class="notif-meta">
          <div class="notif-source"><?php echo htmlspecialchars($source); ?></div>
          <div class="notif-meta-right">
            <?php if ($is_unread): ?><div class="unread-dot"></div><?php endif; ?>
            <span class="notif-time" title="<?php echo htmlspecialchars($full_date); ?>">
              <?php echo $ago; ?>
            </span>
          </div>
        </div>
        <div class="notif-title"><?php echo htmlspecialchars($n['title']); ?></div>
        <div class="notif-body"><?php echo htmlspecialchars($n['message']); ?></div>
        <?php
        if (in_array($n['type'], ['promo','broadcast'], true) && !empty($n['restaurant_id'])):
            $deep = 'scan.php?rid=' . (int)$n['restaurant_id'];
            if (!empty($n['menu_item_id'])) $deep .= '&item=' . (int)$n['menu_item_id'];
        ?>
        <a href="<?php echo $deep; ?>"
           class="notif-view-menu"
           onclick="event.stopPropagation()">
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
            <path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2"/>
            <rect x="9" y="3" width="6" height="4" rx="1"/>
          </svg>
          <?php echo !empty($n['menu_item_id']) ? 'View Dish' : 'View Menu'; ?>
        </a>
        <?php endif; ?>
      </div>

      <!-- Delete (button fallback for swipe) -->
      <button type="button" class="notif-del-x" aria-label="Remove notification"
              onclick="event.stopPropagation(); deleteNotif(<?php echo (int)$n['id']; ?>, this)">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
      </button>

    </div>
    <?php endforeach; ?>
  <?php endforeach; endif; ?>

  <!-- ── Pagination ──────────────────────────────────────────────────────── -->
  <?php if ($total_pages > 1): ?>
  <div class="notif-pagination">
    <?php if ($page > 1): ?>
    <a href="notifications.php?filter=<?php echo $filter; ?>&page=<?php echo $page-1; ?>" class="notif-pg-btn">‹ Prev</a>
    <?php endif; ?>

    <?php
    $pg_start = max(1, $page - 2);
    $pg_end   = min($total_pages, $page + 2);
    for ($p = $pg_start; $p <= $pg_end; $p++): ?>
    <a href="notifications.php?filter=<?php echo $filter; ?>&page=<?php echo $p; ?>"
       class="notif-pg-btn <?php echo $p===$page?'active':''; ?>">
      <?php echo $p; ?>
    </a>
    <?php endfor; ?>

    <?php if ($page < $total_pages): ?>
    <a href="notifications.php?filter=<?php echo $filter; ?>&page=<?php echo $page+1; ?>" class="notif-pg-btn">Next ›</a>
    <?php endif; ?>
  </div>
  <?php endif; ?>

</div>

<script>
function markRead(id, el) {
  if (!el.classList.contains('unread')) return;
  el.classList.remove('unread');
  const dot = el.querySelector('.unread-dot');
  if (dot) dot.remove();
  const title = el.querySelector('.notif-title');
  if (title) title.style.fontWeight = '600';
  fetch('notifications.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: 'action=mark_read&id=' + id
  });
}

// Delete a single notification (used by the × button and by swipe).
function deleteNotif(id, el) {
  const card = (el && el.closest) ? el.closest('.notif-card') : (el || null);
  if (!card) return;
  fetch('notifications.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: 'action=delete&id=' + id
  }).then(r => r.json()).then(d => {
    if (!d || !d.ok) { card.style.transform = ''; card.style.opacity = ''; return; }
    card.classList.add('removing');
    card.style.transform = 'translateX(-110%)';
    card.style.opacity = '0';
    setTimeout(() => {
      card.remove();
      if (!document.querySelector('.notif-card')) location.reload();
    }, 300);
  }).catch(() => { card.style.transform = ''; card.style.opacity = ''; });
}

// Finger-swipe left to remove a notification.
(function () {
  let startX = 0, startY = 0, cur = null, dx = 0, swiping = false;
  document.querySelectorAll('.notif-card').forEach(card => {
    card.addEventListener('touchstart', e => {
      const t = e.touches[0]; startX = t.clientX; startY = t.clientY; cur = card; dx = 0; swiping = false;
      card.style.transition = 'none';
    }, { passive: true });
    card.addEventListener('touchmove', e => {
      if (cur !== card) return;
      const t = e.touches[0], mx = t.clientX - startX, my = t.clientY - startY;
      if (!swiping && Math.abs(mx) > Math.abs(my) + 8) swiping = true;
      if (swiping && mx < 0) {
        dx = mx;
        card.style.transform = 'translateX(' + mx + 'px)';
        card.style.opacity = String(Math.max(0.35, 1 + mx / 220));
      }
    }, { passive: true });
    card.addEventListener('touchend', () => {
      if (cur !== card) return;
      card.style.transition = 'transform .2s ease, opacity .2s ease';
      if (dx < -90) {
        card.dataset.swiped = '1';
        deleteNotif(card.id.replace('notif-', ''), card);
      } else {
        card.style.transform = ''; card.style.opacity = '';
      }
      cur = null; dx = 0; swiping = false;
    });
    // Don't open the detail page if the tap was actually a swipe.
    card.addEventListener('click', e => {
      if (card.dataset.swiped === '1') { e.stopPropagation(); e.preventDefault(); card.dataset.swiped = ''; }
    }, true);
  });
})();
</script>

<?php include("includes/footer.php"); ?>
