<?php
session_start();
include 'layouts/dbconn.php';

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

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    exit(json_encode(['success' => false, 'error' => 'Not authenticated']));
}

try {
    $data = json_decode(file_get_contents('php://input'), true);
    $notification_id = filter_var($data['notification_id'], FILTER_VALIDATE_INT);
    
    if (!$notification_id) {
        throw new Exception('Invalid notification ID');
    }

    $stmt = $conn->prepare("UPDATE notifications SET is_read = 1 WHERE notification_id = ?");
    $stmt->bind_param("i", $notification_id);
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to update notification');
    }

    // Update activity log
    $log_stmt = $conn->prepare("INSERT INTO activity_log (user_id, action, table_name, record_id) VALUES (?, 'UPDATE', 'notifications', ?)");
    $log_stmt->bind_param("ii", $_SESSION['user_id'], $notification_id);
    $log_stmt->execute();

    echo json_encode([
        'success' => true,
        'message' => 'Notification marked as read'
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

$conn->close();
?>