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

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

// Check if user is logged in
if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'error' => 'Not authenticated']);
    exit();
}

$userId = getUserId();

// Get parameters
$chatId = isset($_GET['chat_id']) ? (int)$_GET['chat_id'] : 0;
$afterTimestamp = isset($_GET['after']) ? $_GET['after'] : null;

// Validate input
if (!$chatId || !$afterTimestamp) {
    echo json_encode(['success' => false, 'error' => 'Invalid input']);
    exit();
}

try {
    // Get database connection
    $database = new Database();
    $db = $database->getConnection();
    
    $chatClass = new \App\Chat($db);
    $messageClass = new \App\Message($db);
    
    // Verify user is a member of the chat
    if (!$chatClass->isMember($chatId, $userId)) {
        echo json_encode(['success' => false, 'error' => 'Access denied']);
        exit();
    }
    
    // Get new messages
    $messages = $messageClass->getRecentMessages($chatId, $afterTimestamp);
    
    // Update last read timestamp
    if (!empty($messages)) {
        $chatClass->updateLastRead($chatId, $userId);
    }
    
    echo json_encode([
        'success' => true,
        'messages' => $messages
    ]);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
?>