<?php
// Filename: notifications_mark_read.php
require_once 'config.php';

if (!function_exists('requireLogin')) {
    function requireLogin() {
        if (session_status() === PHP_SESSION_NONE) session_start();
        if (empty($_SESSION['user_id'])) { header('Location: index.php'); exit; }
    }
}

requireLogin();

$uid = (int)($_SESSION['user_id'] ?? 0);
$id  = (int)($_POST['id'] ?? 0);

if ($uid <= 0 || $id <= 0) { header('Location: dashboard.php'); exit; }

$st = $pdo->prepare("UPDATE notifications SET is_read = 1 WHERE id = ? AND user_id = ?");
$st->execute([$id, $uid]);

// Clear unread cache so badge updates immediately
unset($_SESSION['notif_unread_cache']);

header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? 'dashboard.php'));
exit;
