<?php
/**
 * ============================================================================
 * chat/ajax/get-messages.php - Get New Messages Endpoint
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../../config/config.php';

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

if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit;
}

try {
    $userId = getUserId();
    $chatId = (int)($_GET['chat_id'] ?? 0);
    $afterId = (int)($_GET['after_id'] ?? 0);
    
    if (!$chatId) {
        echo json_encode([
            'success' => false,
            'message' => 'Chat ID is required'
        ]);
        exit;
    }
    
    $database = new \App\Database();
    $db = $database->getConnection();
    $chatClass = new \App\Chat($db);
    $messageClass = new \App\Message($db);
    
    // Check if user is member
    if (!$chatClass->isMember($chatId, $userId)) {
        echo json_encode([
            'success' => false,
            'message' => 'Access denied'
        ]);
        exit;
    }
    
    // Get new messages
    $messages = $messageClass->getNewMessages($chatId, $userId, $afterId);
    
    echo json_encode([
        'success' => true,
        'messages' => $messages
    ]);
    
} catch (\Exception $e) {
    error_log('Get messages error: ' . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Failed to get messages: ' . $e->getMessage()
    ]);
}