<?php
require_once 'includes/config.php';
requireLogin();
$uid = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    $action = $_POST['action'] ?? '';
    if ($action === 'read') {
        $id = (int)($_POST['id'] ?? 0);
        $pdo->prepare("UPDATE notifications SET is_read=1 WHERE id=? AND (user_id=? OR user_id IS NULL)")->execute([$id, $uid]);
        jsonResponse(['success'=>true]);
    }
    if ($action === 'read_all') {
        $pdo->prepare("UPDATE notifications SET is_read=1 WHERE user_id=? OR user_id IS NULL")->execute([$uid]);
        jsonResponse(['success'=>true]);
    }
    if ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        $pdo->prepare("DELETE FROM notifications WHERE id=? AND user_id=?")->execute([$id, $uid]);
        jsonResponse(['success'=>true]);
    }
    if ($action === 'clear_all') {
        $pdo->prepare("DELETE FROM notifications WHERE user_id=?")->execute([$uid]);
        jsonResponse(['success'=>true]);
    }
    jsonResponse(['success'=>false]);
}

$stmt = $pdo->prepare("SELECT * FROM notifications WHERE user_id=? OR user_id IS NULL ORDER BY is_read ASC, created_at DESC");
$stmt->execute([$uid]);
$notifications = $stmt->fetchAll();
$unreadCount   = count(array_filter($notifications, fn($n) => !$n['is_read']));
$totalCount    = count($notifications);

require_once 'includes/header.php';
renderHeader('Notifications', 'notifications');

// Type config
$typeConfig = [
    'info'        => ['icon'=>'ℹ️', 'color'=>'#818cf8', 'bg'=>'rgba(99,102,241,.1)',  'border'=>'rgba(99,102,241,.25)'],
    'success'     => ['icon'=>'✅', 'color'=>'#34d399', 'bg'=>'rgba(16,185,129,.1)',  'border'=>'rgba(16,185,129,.25)'],
    'warning'     => ['icon'=>'⚠️', 'color'=>'#fbbf24', 'bg'=>'rgba(245,158,11,.1)',  'border'=>'rgba(245,158,11,.25)'],
    'danger'      => ['icon'=>'🚨', 'color'=>'#f87171', 'bg'=>'rgba(239,68,68,.1)',   'border'=>'rgba(239,68,68,.25)'],
    'achievement' => ['icon'=>'🏆', 'color'=>'#fbbf24', 'bg'=>'rgba(245,158,11,.1)',  'border'=>'rgba(245,158,11,.25)'],
    'streak'      => ['icon'=>'🔥', 'color'=>'#fb923c', 'bg'=>'rgba(249,115,22,.1)',  'border'=>'rgba(249,115,22,.25)'],
    'reminder'    => ['icon'=>'⏰', 'color'=>'#22d3ee', 'bg'=>'rgba(6,182,212,.1)',   'border'=>'rgba(6,182,212,.25)'],
    'task'        => ['icon'=>'✅', 'color'=>'#34d399', 'bg'=>'rgba(16,185,129,.1)',  'border'=>'rgba(16,185,129,.25)'],
];

function notifAgo($ts) {
    $d = time() - strtotime($ts);
    if ($d < 60)     return 'just now';
    if ($d < 3600)   return floor($d/60).'m ago';
    if ($d < 86400)  return floor($d/3600).'h ago';
    if ($d < 604800) return floor($d/86400).'d ago';
    return date('M j', strtotime($ts));
}
?>

<style>
/* ── Page header ─────────────────────────────────────── */
.nf-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 24px;
  flex-wrap: wrap;
}
.nf-title {
  font-size: 22px;
  font-weight: 800;
  color: var(--text-primary);
  font-family: 'Sora', sans-serif;
  letter-spacing: -.3px;
  display: flex;
  align-items: center;
  gap: 10px;
}
.nf-unread-badge {
  font-size: 11px;
  font-weight: 700;
  background: var(--accent);
  color: #fff;
  border-radius: 99px;
  padding: 2px 9px;
  letter-spacing: .2px;
}
.nf-subtitle {
  font-size: 13px;
  color: var(--text-muted);
  margin-top: 4px;
}

/* ── Filter tabs ─────────────────────────────────────── */
.nf-tabs {
  display: flex;
  gap: 6px;
  margin-bottom: 18px;
  flex-wrap: wrap;
}
.nf-tab {
  padding: 6px 16px;
  border-radius: 99px;
  border: 1px solid var(--border);
  background: var(--bg-secondary);
  color: var(--text-secondary);
  font-size: 12px;
  font-weight: 600;
  cursor: pointer;
  transition: all .18s;
  user-select: none;
}
.nf-tab:hover {
  border-color: var(--accent);
  color: var(--accent);
}
.nf-tab.active {
  background: rgba(99,102,241,.12);
  border-color: rgba(99,102,241,.4);
  color: var(--accent);
}
.nf-tab-count {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 18px;
  height: 18px;
  border-radius: 99px;
  background: rgba(99,102,241,.18);
  color: var(--accent);
  font-size: 10px;
  font-weight: 800;
  padding: 0 5px;
  margin-left: 5px;
}

/* ── Notification card ───────────────────────────────── */
.nf-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.nf-item {
  display: flex;
  align-items: flex-start;
  gap: 14px;
  padding: 16px 18px;
  background: var(--bg-card);
  border: 1px solid var(--border);
  border-radius: 14px;
  transition: border-color .18s, transform .18s, opacity .3s;
  position: relative;
  overflow: hidden;
  animation: nfSlideIn .25s ease both;
}
.nf-item:hover {
  border-color: rgba(99,102,241,.3);
  transform: translateY(-1px);
}
.nf-item.is-unread {
  background: var(--bg-card);
  border-color: rgba(99,102,241,.2);
}
.nf-item.is-unread::before {
  content: '';
  position: absolute;
  left: 0; top: 0; bottom: 0;
  width: 3px;
  border-radius: 14px 0 0 14px;
  background: linear-gradient(180deg, var(--accent), var(--accent2, #8b5cf6));
}
.nf-item.is-read {
  opacity: .65;
}
.nf-item[data-link]:hover {
  border-color: rgba(99,102,241,.4);
}
.nf-item[data-link] .nf-body::after {
  content: '→';
  position: absolute;
  right: 56px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 16px;
  color: var(--accent);
  opacity: 0;
  transition: opacity .18s, right .18s;
  pointer-events: none;
}
.nf-item[data-link]:hover .nf-body::after {
  opacity: 1;
  right: 52px;
}
.nf-item.removing {
  opacity: 0;
  transform: translateX(20px) scale(.97);
  pointer-events: none;
}
@keyframes nfSlideIn {
  from { opacity: 0; transform: translateY(8px); }
  to   { opacity: 1; transform: translateY(0); }
}

/* type icon */
.nf-icon {
  width: 42px;
  height: 42px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 19px;
  flex-shrink: 0;
  border: 1px solid;
}

/* content */
.nf-body { flex: 1; min-width: 0; }
.nf-item-title {
  font-size: 14px;
  font-weight: 700;
  color: var(--text-primary);
  margin-bottom: 4px;
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}
.nf-unread-dot {
  width: 7px; height: 7px;
  border-radius: 50%;
  background: var(--accent);
  flex-shrink: 0;
  box-shadow: 0 0 6px var(--accent);
}
.nf-message {
  font-size: 13px;
  color: var(--text-secondary);
  line-height: 1.6;
  margin-bottom: 8px;
}
.nf-meta {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}
.nf-time {
  font-size: 11px;
  color: var(--text-muted);
  display: flex;
  align-items: center;
  gap: 4px;
}
.nf-type-badge {
  font-size: 10px;
  font-weight: 700;
  padding: 2px 8px;
  border-radius: 99px;
  text-transform: uppercase;
  letter-spacing: .4px;
  border: 1px solid;
}

/* actions */
.nf-actions {
  display: flex;
  gap: 6px;
  flex-shrink: 0;
  align-self: flex-start;
  margin-top: 2px;
}
.nf-btn {
  width: 30px;
  height: 30px;
  border-radius: 8px;
  border: 1px solid var(--border);
  background: var(--bg-secondary);
  color: var(--text-secondary);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all .15s;
  flex-shrink: 0;
}
.nf-btn:hover { border-color: var(--accent); color: var(--accent); background: rgba(99,102,241,.08); }
.nf-btn.danger:hover { border-color: rgba(239,68,68,.4); color: #ef4444; background: rgba(239,68,68,.08); }

/* ── Empty state ─────────────────────────────────────── */
.nf-empty {
  text-align: center;
  padding: 64px 20px;
  background: var(--bg-card);
  border: 1px dashed var(--border);
  border-radius: 16px;
}
.nf-empty-icon {
  font-size: 52px;
  margin-bottom: 16px;
  display: block;
  filter: grayscale(.3);
}
.nf-empty-title {
  font-size: 16px;
  font-weight: 700;
  color: var(--text-primary);
  margin-bottom: 6px;
  font-family: 'Sora', sans-serif;
}
.nf-empty-sub {
  font-size: 13px;
  color: var(--text-muted);
  line-height: 1.6;
}

/* ── Action bar buttons ──────────────────────────────── */
.nf-action-bar {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}
</style>

<!-- Page Header -->
<div class="nf-header">
  <div>
    <div class="nf-title">
      <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" style="color:var(--accent)"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>
      Notifications
      <?php if ($unreadCount > 0): ?>
      <span class="nf-unread-badge"><?= $unreadCount ?> new</span>
      <?php endif; ?>
    </div>
    <div class="nf-subtitle"><?= $unreadCount ?> unread · <?= $totalCount ?> total</div>
  </div>

  <div class="nf-action-bar">
    <?php if ($unreadCount > 0): ?>
    <button class="btn btn-secondary btn-sm" onclick="markAllRead()" id="markAllBtn">
      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" style="margin-right:5px"><polyline points="20 6 9 17 4 12"/></svg>
      Mark all read
    </button>
    <?php endif; ?>
    <?php if ($totalCount > 0): ?>
    <button class="btn btn-sm" style="background:rgba(239,68,68,.08);color:var(--danger,#ef4444);border:1px solid rgba(239,68,68,.2)" onclick="clearAll()">
      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" style="margin-right:5px"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14H6L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/></svg>
      Clear all
    </button>
    <?php endif; ?>
  </div>
</div>

<!-- Filter Tabs -->
<?php
$types = [];
foreach ($notifications as $n) {
    $t = $n['type'] ?? 'info';
    $types[$t] = ($types[$t] ?? 0) + 1;
}
?>
<div class="nf-tabs" id="nfTabs">
  <div class="nf-tab active" data-filter="all" onclick="filterNotifs('all', this)">
    All <span class="nf-tab-count"><?= $totalCount ?></span>
  </div>
  <?php if ($unreadCount > 0): ?>
  <div class="nf-tab" data-filter="unread" onclick="filterNotifs('unread', this)">
    Unread <span class="nf-tab-count" style="background:rgba(99,102,241,.25)"><?= $unreadCount ?></span>
  </div>
  <?php endif; ?>
  <?php foreach ($types as $type => $cnt):
    $cfg = $typeConfig[$type] ?? $typeConfig['info'];
    $typeLabel = ucfirst($type);
  ?>
  <div class="nf-tab" data-filter="<?= $type ?>" onclick="filterNotifs('<?= $type ?>', this)">
    <?= $cfg['icon'] ?> <?= $typeLabel ?>
    <span class="nf-tab-count"><?= $cnt ?></span>
  </div>
  <?php endforeach; ?>
</div>

<!-- Notifications List -->
<?php if ($notifications): ?>
<div class="nf-list" id="nfList">
  <?php foreach ($notifications as $i => $n):
    $cfg    = $typeConfig[$n['type']] ?? $typeConfig['info'];
    $ago    = notifAgo($n['created_at']);
    $isRead = (bool)$n['is_read'];
    $typeLabel = ucfirst($n['type'] ?? 'info');
  ?>
  <div class="nf-item <?= $isRead ? 'is-read' : 'is-unread' ?>"
       id="nf-<?= $n['id'] ?>"
       data-type="<?= htmlspecialchars($n['type'] ?? 'info') ?>"
       data-read="<?= $isRead ? '1' : '0' ?>"
       <?php if (!empty($n['link_url'])): ?>
       data-link="<?= htmlspecialchars($n['link_url']) ?>"
       style="animation-delay:<?= min($i * 0.04, 0.3) ?>s;cursor:pointer"
       <?php else: ?>
       style="animation-delay:<?= min($i * 0.04, 0.3) ?>s"
       <?php endif; ?>>

    <!-- Icon -->
    <div class="nf-icon" style="background:<?= $cfg['bg'] ?>;border-color:<?= $cfg['border'] ?>">
      <?= $cfg['icon'] ?>
    </div>

    <!-- Body -->
    <div class="nf-body">
      <div class="nf-item-title">
        <?php if (!$isRead): ?>
        <span class="nf-unread-dot"></span>
        <?php endif; ?>
        <?= htmlspecialchars($n['title']) ?>
      </div>
      <div class="nf-message"><?= htmlspecialchars($n['message']) ?></div>
      <div class="nf-meta">
        <span class="nf-time">
          <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
          <?= $ago ?>
        </span>
        <span class="nf-type-badge" style="color:<?= $cfg['color'] ?>;background:<?= $cfg['bg'] ?>;border-color:<?= $cfg['border'] ?>">
          <?= $typeLabel ?>
        </span>
      </div>
    </div>

    <!-- Actions -->
    <div class="nf-actions">
      <?php if (!$isRead): ?>
      <button class="nf-btn" title="Mark as read" onclick="markRead(<?= $n['id'] ?>, this)">
        <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>
      </button>
      <?php endif; ?>
      <button class="nf-btn danger" title="Delete" onclick="deleteNotif(<?= $n['id'] ?>, this)">
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14H6L5 6"/></svg>
      </button>
    </div>
  </div>
  <?php endforeach; ?>
</div>

<?php else: ?>
<div class="nf-empty">
  <span class="nf-empty-icon">🔕</span>
  <div class="nf-empty-title">No notifications yet</div>
  <div class="nf-empty-sub">Smart notifications will appear here based on your study activity.</div>
</div>
<?php endif; ?>

<?php require_once 'includes/footer.php'; renderFooter(); ?>

<script>
// ── Fetch helper ──────────────────────────────────────────────────────────
async function nfPost(data) {
  var fd = new FormData();
  for (var k in data) fd.append(k, data[k]);
  return fetch(window.location.href, {
    method: 'POST', body: fd,
    headers: { 'X-Requested-With': 'XMLHttpRequest' }
  });
}

// ── Remove item with animation ────────────────────────────────────────────
function removeItem(el) {
  el.classList.add('removing');
  setTimeout(function() { el.remove(); checkEmpty(); }, 320);
}

// ── Check if list is now empty ────────────────────────────────────────────
function checkEmpty() {
  var list = document.getElementById('nfList');
  if (!list) return;
  var visible = list.querySelectorAll('.nf-item:not(.removing)');
  if (visible.length === 0) {
    list.innerHTML =
      '<div class="nf-empty">' +
        '<span class="nf-empty-icon">🔕</span>' +
        '<div class="nf-empty-title">All clear!</div>' +
        '<div class="nf-empty-sub">No notifications to show.</div>' +
      '</div>';
  }
}

// ── Mark single as read ───────────────────────────────────────────────────
async function markRead(id, btn) {
  await nfPost({ action: 'read', id: id });
  var item = document.getElementById('nf-' + id);
  if (!item) return;
  item.classList.remove('is-unread');
  item.classList.add('is-read');
  item.dataset.read = '1';
  // remove dot
  var dot = item.querySelector('.nf-unread-dot');
  if (dot) dot.remove();
  // remove mark-read btn
  btn.remove();
  updateCounts();
}

// ── Delete single ─────────────────────────────────────────────────────────
async function deleteNotif(id, btn) {
  await nfPost({ action: 'delete', id: id });
  var item = document.getElementById('nf-' + id);
  if (item) removeItem(item);
  updateCounts();
}

// ── Mark all read ─────────────────────────────────────────────────────────
async function markAllRead() {
  var markBtn = document.getElementById('markAllBtn');
  if (markBtn) { markBtn.disabled = true; markBtn.style.opacity = '.5'; }
  await nfPost({ action: 'read_all' });
  document.querySelectorAll('.nf-item.is-unread').forEach(function(item) {
    item.classList.remove('is-unread');
    item.classList.add('is-read');
    item.dataset.read = '1';
    var dot = item.querySelector('.nf-unread-dot');
    if (dot) dot.remove();
    var readBtn = item.querySelector('.nf-btn:not(.danger)');
    if (readBtn) readBtn.remove();
  });
  if (markBtn) markBtn.remove();
  updateCounts();
}

// ── Clear all ─────────────────────────────────────────────────────────────
async function clearAll() {
  if (!(await stConfirm('Delete all notifications? This cannot be undone.'))) return;
  await nfPost({ action: 'clear_all' });
  var list = document.getElementById('nfList');
  if (list) {
    list.innerHTML =
      '<div class="nf-empty">' +
        '<span class="nf-empty-icon">🔕</span>' +
        '<div class="nf-empty-title">All clear!</div>' +
        '<div class="nf-empty-sub">No notifications to show.</div>' +
      '</div>';
  }
  updateCounts();
}

// ── Filter by tab ─────────────────────────────────────────────────────────
function filterNotifs(filter, tabEl) {
  // update tabs
  document.querySelectorAll('.nf-tab').forEach(function(t) { t.classList.remove('active'); });
  tabEl.classList.add('active');

  var items = document.querySelectorAll('.nf-item');
  items.forEach(function(item) {
    var show = false;
    if (filter === 'all')    show = true;
    else if (filter === 'unread') show = item.dataset.read === '0';
    else show = item.dataset.type === filter;
    item.style.display = show ? '' : 'none';
  });
}

// ── Update counter in header ──────────────────────────────────────────────
function updateCounts() {
  var items    = document.querySelectorAll('.nf-item');
  var unread   = document.querySelectorAll('.nf-item.is-unread').length;
  var total    = items.length;

  // update subtitle
  var sub = document.querySelector('.nf-subtitle');
  if (sub) sub.textContent = unread + ' unread · ' + total + ' total';

  // update badge in title
  var badge = document.querySelector('.nf-unread-badge');
  if (badge) {
    if (unread > 0) { badge.textContent = unread + ' new'; }
    else badge.remove();
  }

  // update tab counts
  document.querySelectorAll('.nf-tab').forEach(function(tab) {
    var filter = tab.dataset.filter;
    var cnt = tab.querySelector('.nf-tab-count');
    if (!cnt) return;
    if (filter === 'all') cnt.textContent = total;
    else if (filter === 'unread') {
      cnt.textContent = unread;
      if (unread === 0) tab.style.display = 'none';
    }
  });
}

// ── Click notification → navigate to link_url ─────────────────────────────
document.addEventListener('click', function(e) {
  var item = e.target.closest('.nf-item[data-link]');
  if (!item) return;
  // Don't navigate if user clicked an action button (mark read / delete)
  if (e.target.closest('.nf-actions')) return;
  var link = item.dataset.link;
  if (!link) return;
  // Mark as read first if unread
  if (item.dataset.read === '0') {
    nfPost({ action: 'read', id: item.id.replace('nf-', '') });
    item.classList.remove('is-unread');
    item.classList.add('is-read');
    item.dataset.read = '1';
    var dot = item.querySelector('.nf-unread-dot');
    if (dot) dot.remove();
  }
  window.location.href = link;
});
</script>