<?php
/**
 * ============================================================================
 * ajax/notifications.php
 * AJAX endpoint for fetching notifications
 * ============================================================================
 */

// Define access constant
define('AIMS_ACCESS', true);

// Include configuration
require_once __DIR__ . '/../config/config.php';

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

// Check if user is logged in
if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode([
        'success' => false,
        'message' => 'Unauthorized access',
        'unread_count' => 0,
        'notifications' => []
    ]);
    exit();
}

try {
    $userId = getUserId();
    $database = new Database();
    $db = $database->getConnection();
    
    if (!$db) {
        throw new Exception('Database connection failed');
    }
    
    // Get unread count
    $sqlCount = "SELECT COUNT(*) as count FROM notifications WHERE user_id = ? AND is_read = 0";
    $stmtCount = $db->prepare($sqlCount);
    $stmtCount->execute([$userId]);
    $resultCount = $stmtCount->fetch(PDO::FETCH_ASSOC);
    $unreadCount = (int)($resultCount['count'] ?? 0);
    
    // Get recent notifications (limit 10)
    $sqlNotifications = "SELECT * FROM notifications 
                        WHERE user_id = ? 
                        ORDER BY created_at DESC 
                        LIMIT 10";
    $stmtNotifications = $db->prepare($sqlNotifications);
    $stmtNotifications->execute([$userId]);
    $notifications = $stmtNotifications->fetchAll(PDO::FETCH_ASSOC);
    
    // Add time_ago to each notification
    foreach ($notifications as &$notif) {
        $notif['time_ago'] = timeAgo($notif['created_at']);
    }
    
    // Success response
    echo json_encode([
        'success' => true,
        'message' => 'Notifications fetched successfully',
        'unread_count' => $unreadCount,
        'notifications' => $notifications
    ]);
    
} catch (Exception $e) {
    // Log error
    error_log('Notifications AJAX Error: ' . $e->getMessage());
    
    // Error response
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Failed to fetch notifications',
        'error' => $e->getMessage(),
        'unread_count' => 0,
        'notifications' => []
    ]);
}
?>