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

header('Content-Type: application/json');

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

$stmt = $pdo->prepare("SELECT id, message, link, is_read, created_at FROM notifications WHERE user_id = ? ORDER BY created_at DESC LIMIT 8");
$stmt->execute([$u['id']]);
$recent = $stmt->fetchAll();
foreach ($recent as &$n) {
    $n['link'] = BASE_URL . 'notify_go.php?id=' . $n['id'];
    $n['time_ago'] = time_ago($n['created_at']);
}
unset($n);

echo json_encode([
    'unread' => unread_notification_count($pdo, $u['id']),
    'recent' => $recent,
]);
