<?php
session_start();
require_once("../php/db_connect.php");

if (!isset($_SESSION["user_id"])) {
    header("Location: index.php");
    exit();
}

$userId = (int)$_SESSION["user_id"];
$notificationId = (int)($_GET["id"] ?? 0);

if ($notificationId <= 0) {
    header("Location: admin.php");
    exit();
}

$stmt = $conn->prepare("
    SELECT link 
    FROM notifications
    WHERE id = ?
    AND user_id = ?
    LIMIT 1
");

$stmt->bind_param("ii", $notificationId, $userId);
$stmt->execute();
$notification = $stmt->get_result()->fetch_assoc();

if ($notification) {
    $update = $conn->prepare("
        UPDATE notifications
        SET is_read = 1
        WHERE id = ?
        AND user_id = ?
    ");

    $update->bind_param("ii", $notificationId, $userId);
    $update->execute();

    if (!empty($notification["link"])) {
        header("Location: " . $notification["link"]);
        exit();
    }
}

header("Location: admin.php");
exit();