<?php
session_start();
require_once '../config/database.php';

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

if (!isset($_SESSION['user_id'])) {
    echo json_encode([]);
    exit();
}

$user_id = $_SESSION['user_id'];
$conn = getDBConnection();

$query = "SELECT n.*, a.title as activity_title
          FROM notifications n
          LEFT JOIN activities a ON n.activity_id = a.id
          WHERE n.user_id = ?
          ORDER BY n.created_at DESC
          LIMIT 20";

$stmt = $conn->prepare($query);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

$notifications = [];
while ($row = $result->fetch_assoc()) {
    $row['created_at'] = date('M d, Y H:i', strtotime($row['created_at']));
    $notifications[] = $row;
}

$stmt->close();
$conn->close();

echo json_encode($notifications);
?>
