<?php
/**
 * ============================================================================
 * ajax/unread-messages.php
 * AJAX endpoint for fetching unread messages count
 * ============================================================================
 */

define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

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

if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode([
        'success' => false,
        'message' => 'Unauthorized',
        'unread_count' => 0
    ]);
    exit();
}

try {
    $userId = getUserId();
    $database = new Database();
    $db = $database->getConnection();
    
    if (!$db) {
        throw new Exception('Database connection failed');
    }
    
    // Get unread messages count from all chats the user is a member of
    $sql = "SELECT COUNT(DISTINCT m.id) as count 
            FROM messages m
            INNER JOIN chats c ON m.chat_id = c.id
            INNER JOIN chat_members cm ON c.id = cm.chat_id
            WHERE cm.user_id = ?
            AND m.sender_id != ?
            AND m.created_at > COALESCE(cm.last_read_at, '2000-01-01 00:00:00')";
    
    $stmt = $db->prepare($sql);
    $stmt->execute([$userId, $userId]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    $unreadCount = (int)($result['count'] ?? 0);
    
    echo json_encode([
        'success' => true,
        'message' => 'Unread messages count fetched',
        'unread_count' => $unreadCount
    ]);
    
} catch (Exception $e) {
    error_log('Unread Messages AJAX Error: ' . $e->getMessage());
    
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Failed to fetch unread messages',
        'error' => $e->getMessage(),
        'unread_count' => 0
    ]);
}
?>