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

require_once __DIR__ . '/../classes/Database.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../classes/Messaging.php';

try {
    session_start();
    if (empty($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'message' => 'Login required.']);
        exit;
    }

    $userId = (int)$_SESSION['user_id'];
    $conversationId = (int)($_POST['conversation_id'] ?? 0);
    $body = trim((string)($_POST['body'] ?? ''));

    $database = new Database();
    $conn = $database->getConnection();

    $messaging = new Messaging($conn);
    if (!$conversationId || !$messaging->isParticipant($conversationId, $userId)) {
        echo json_encode(['success' => false, 'message' => 'Conversation not found.']);
        exit;
    }

    if ($body === '') {
        echo json_encode(['success' => false, 'message' => 'Message cannot be empty.']);
        exit;
    }

    $message = $messaging->sendMessage($conversationId, $userId, $body);
    echo json_encode(['success' => true, 'message_data' => $message]);
} catch (Throwable $e) {
    error_log('Sending message failed: ' . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Unable to send message.']);
}
