<?php
require_once __DIR__ . '/config/config.php';
require_login();
$u = current_user();

if (isset($_GET['read'])) {
    $pdo->prepare("UPDATE notifications SET is_read=1 WHERE id=? AND user_id=?")->execute([$_GET['read'], $u['id']]);
    redirect('notifications.php');
}
if (isset($_GET['mark_all'])) {
    $pdo->prepare("UPDATE notifications SET is_read=1 WHERE user_id=?")->execute([$u['id']]);
    redirect('notifications.php');
}

$stmt = $pdo->prepare("SELECT * FROM notifications WHERE user_id = ? ORDER BY created_at DESC LIMIT 150");
$stmt->execute([$u['id']]);
$notes = $stmt->fetchAll();

// Group by day for readability
$groups = [];
foreach ($notes as $n) {
    $day = date('Y-m-d', strtotime($n['created_at']));
    $today = date('Y-m-d');
    $yesterday = date('Y-m-d', strtotime('-1 day'));
    $label = $day === $today ? 'Today' : ($day === $yesterday ? 'Yesterday' : date('M j, Y', strtotime($n['created_at'])));
    $groups[$label][] = $n;
}

$pageTitle = 'Notifications';
include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/sidebar.php';
?>
<div class="flex items-center justify-between mb-6 flex-wrap gap-2">
  <h1 class="text-2xl font-bold">Notifications</h1>
  <a href="?mark_all=1" class="text-sm text-blue-600 hover:underline">Mark all as read</a>
</div>

<?php if (empty($notes)): ?>
  <div class="bg-white rounded-xl shadow-sm border border-slate-200 px-5 py-16 text-center">
    <p class="text-4xl mb-3">🔔</p>
    <p class="text-sm text-slate-400">No notifications yet. You'll see approval requests, status updates, and alerts here.</p>
  </div>
<?php else: ?>
  <?php foreach ($groups as $label => $group): ?>
    <p class="text-xs font-semibold uppercase tracking-wide text-slate-400 mb-2 mt-6 first:mt-0"><?= e($label) ?></p>
    <div class="bg-white rounded-xl shadow-sm border border-slate-200 divide-y divide-slate-100 overflow-hidden">
      <?php foreach ($group as $n): ?>
        <a href="<?= BASE_URL ?>notify_go.php?id=<?= $n['id'] ?>"
           class="block px-5 py-4 hover:bg-slate-50 transition <?= $n['is_read'] ? '' : 'bg-blue-50/60' ?>">
          <div class="flex items-start gap-3">
            <span class="mt-1.5 w-2 h-2 rounded-full shrink-0 <?= $n['is_read'] ? 'bg-transparent' : 'bg-blue-600' ?>"></span>
            <span class="flex-1 min-w-0">
              <span class="block text-sm <?= $n['is_read'] ? 'text-slate-600' : 'text-slate-800 font-medium' ?>"><?= e($n['message']) ?></span>
              <span class="block text-xs text-slate-400 mt-1"><?= date('M j, Y', strtotime($n['created_at'])) ?> · <?= date('h:i A', strtotime($n['created_at'])) ?></span>
            </span>
          </div>
        </a>
      <?php endforeach; ?>
    </div>
  <?php endforeach; ?>
<?php endif; ?>
<?php include __DIR__ . '/includes/footer.php'; ?>
