<?php
/**
 * API endpoint to get user notifications
 */

require_once '../includes/db_connect.php';
session_start();

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

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

try {
    // Get notifications for the current user
    $stmt = $pdo->prepare("
        SELECT id, title, message, is_read, created_at,
               CASE 
                   WHEN created_at >= NOW() - INTERVAL 1 HOUR THEN CONCAT(TIMESTAMPDIFF(MINUTE, created_at, NOW()), ' min ago')
                   WHEN created_at >= NOW() - INTERVAL 1 DAY THEN CONCAT(TIMESTAMPDIFF(HOUR, created_at, NOW()), ' hr ago')
                   ELSE DATE_FORMAT(created_at, '%M %d')
               END as time_ago
        FROM notifications 
        WHERE user_id = ? 
        ORDER BY created_at DESC 
        LIMIT 20
    ");
    $stmt->execute([$_SESSION['user_id']]);
    $notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Count unread notifications
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM notifications WHERE user_id = ? AND is_read = 0");
    $stmt->execute([$_SESSION['user_id']]);
    $unread_count = $stmt->fetch()['count'];
    
    // Format notifications
    $formatted_notifications = array_map(function($notification) {
        return [
            'id' => $notification['id'],
            'title' => $notification['title'],
            'message' => $notification['message'],
            'unread' => !$notification['is_read'],
            'time_ago' => $notification['time_ago']
        ];
    }, $notifications);
    
    echo json_encode([
        'success' => true,
        'notifications' => $formatted_notifications,
        'unread_count' => (int)$unread_count
    ]);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
}
?>
