<?php
/**
 * ============================================================================
 * chat/send-message.php - Send Message API
 * ============================================================================
 */
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 POST data
$chatId = isset($_POST['chat_id']) ? (int)$_POST['chat_id'] : 0;
$content = isset($_POST['content']) ? trim($_POST['content']) : '';
$messageType = isset($_POST['message_type']) ? $_POST['message_type'] : 'text';
$mediaUrl = isset($_POST['media_url']) ? $_POST['media_url'] : null;

// Validate input
if (!$chatId || empty($content)) {
    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();
    }
    
    // Send the message
    $messageId = $messageClass->send($chatId, $userId, $content, $messageType, $mediaUrl);
    
    if ($messageId) {
        // Get the sent message details
        $query = "SELECT 
                    m.*,
                    u.full_name as sender_name,
                    u.profile_picture as sender_avatar
                FROM messages m
                INNER JOIN users u ON m.sender_id = u.id
                WHERE m.id = :message_id";
        
        $stmt = $db->prepare($query);
        $stmt->bindParam(':message_id', $messageId);
        $stmt->execute();
        
        $message = $stmt->fetch(PDO::FETCH_ASSOC);
        
        echo json_encode([
            'success' => true,
            'message' => $message
        ]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Failed to send message']);
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
?>