Files
whatsapp/api/get_user_messages.php
T
2026-01-21 08:28:54 -05:00

105 lines
3.0 KiB
PHP

<?php
/**
* API - Obtener mensajes de un usuario específico
* Fecha: 4 de enero de 2026
*/
require_once '../config/config.php';
// Verificar autenticación
requireAuthentication();
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
header('Access-Control-Allow-Headers: Content-Type');
try {
$userId = intval($_GET['user_id'] ?? 0);
if (!$userId) {
http_response_code(400);
echo json_encode(['error' => 'user_id es requerido']);
exit;
}
$db = Database::getInstance();
// Obtener mensajes del usuario (de ambas tablas para compatibilidad)
$conversations = $db->fetchAll(
"SELECT
id,
user_id,
COALESCE(content, message_text) as content,
message_id,
c.media_url,
u.phone_number as user_phone,
direction,
message_type,
status,
created_at,
COALESCE(c.is_read, 0) as is_read
FROM conversations c
LEFT JOIN users u ON c.user_id = u.id
WHERE user_id = :user_id
UNION ALL
SELECT
id,
user_id,
message_text as content,
NULL as message_id,
NULL as media_url,
NULL as user_phone,
direction,
message_type,
status,
created_at,
1 as is_read
FROM conversations
WHERE user_id = :user_id
ORDER BY created_at ASC",
['user_id' => $userId]
);
// Si no hay mensajes en conversations, intentar con conversations
if (empty($conversations)) {
$conversations = $db->fetchAll(
"SELECT
id,
user_id,
message_text as content,
direction,
message_type,
status,
created_at
FROM conversations
WHERE user_id = :user_id
ORDER BY created_at ASC",
['user_id' => $userId]
);
}
// Formatear fechas y limpiar datos
$conversations = array_map(function($msg) {
return [
'id' => intval($msg['id']),
'user_id' => intval($msg['user_id']),
'content' => $msg['content'] ?? '',
'message_id' => $msg['message_id'] ?? null,
'media_url' => $msg['media_url'] ?? null,
'user_phone' => $msg['user_phone'] ?? null,
'direction' => $msg['direction'] ?? 'incoming',
'message_type' => $msg['message_type'] ?? 'text',
'status' => $msg['status'] ?? 'sent',
'created_at' => $msg['created_at']
];
}, $conversations);
echo json_encode($conversations);
} catch (Exception $e) {
error_log("Error in get_user_conversations.php: " . $e->getMessage());
http_response_code(500);
echo json_encode(['error' => 'Error interno del servidor']);
}
?>