<?php
/**
 * API - Obtener un mensaje por su message_id o id
 */
require_once '../config/config.php';
requireAuthentication();
header('Content-Type: application/json; charset=utf-8');

try {
    $mid = trim($_GET['message_id'] ?? ($_GET['id'] ?? ''));
    if (!$mid) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'message_id es requerido']);
        exit;
    }

    $db = Database::getInstance();

    $sql = "SELECT 
            c.id as id,
            c.user_id as user_id,
            c.content as content,
            c.message_id as message_id,
            c.media_url,
            c.local_file,
            c.local_thumb,
            c.filename,
            c.mime_type,
            c.direction,
            c.message_type,
            c.status,
            c.created_at,
            c.reply_to_message_id,
            c.reaction_emoji,
            c.reaction_to_message_id
         FROM conversations c
         WHERE c.message_id = :mid OR c.id = :mid
         LIMIT 1";
    $row = $db->fetch($sql, ['mid' => $mid]);
    if (!$row) {
        echo json_encode(['success' => true, 'data' => null]);
        exit;
    }

    // build external media similar to get_user_messages
    $external = (isset($row['media_url']) && $row['media_url']) ? (preg_match('#^https?://#i', $row['media_url']) ? $row['media_url'] : ("api/get_media.php?id=" . urlencode($row['media_url']))) : null;

    $msg = [
        'id' => intval($row['id']),
        'user_id' => intval($row['user_id']),
        'content' => $row['content'] ?? '',
        'message_id' => $row['message_id'] ?? null,
        'media_url' => null,
        'local_file' => $row['local_file'] ?? null,
        'local_thumb' => $row['local_thumb'] ?? null,
        'media_url_external' => $external,
        'filename' => $row['filename'] ?? null,
        'mime_type' => $row['mime_type'] ?? null,
        'direction' => $row['direction'] ?? 'incoming',
        'message_type' => $row['message_type'] ?? 'text',
        'status' => $row['status'] ?? 'sent',
        'created_at' => $row['created_at'],
        'reply_to_message_id' => $row['reply_to_message_id'] ?? null,
        'reaction_emoji' => $row['reaction_emoji'] ?? null,
        'reaction_to_message_id' => $row['reaction_to_message_id'] ?? null
    ];

    echo json_encode(['success' => true, 'data' => $msg]);
} catch (Exception $e) {
    http_response_code(500);
    error_log('get_message.php error: ' . $e->getMessage());
    echo json_encode(['success' => false, 'error' => 'Error interno']);
}
