<?php
require_once __DIR__ . '/db.php';
require_login();

$notificationId = (int) ($_GET['id'] ?? 0);
$markAll = isset($_GET['all']) && $_GET['all'] === '1';
$isAjax = isset($_GET['ajax']) && $_GET['ajax'] === '1';
$redirect = trim($_GET['redirect'] ?? 'dashboard.php');

if ($markAll) {
    mark_all_notifications_as_read($conn, current_user_id());
    if ($isAjax) {
        header('Content-Type: application/json');
        echo json_encode(['success' => true]);
        exit();
    }

    if ($redirect === '') {
        $redirect = 'dashboard.php';
    }

    header('Location: ' . $redirect);
    exit();
}

if ($notificationId > 0) {
    mark_notification_as_read($conn, $notificationId, current_user_id());
}

if ($redirect === '') {
    $redirect = 'notifications.php';
}

header('Location: ' . $redirect);
exit();
