70 lines
2.4 KiB
PHP
70 lines
2.4 KiB
PHP
<?php
|
|
/**
|
|
* API - Obtener conversaciones recientes
|
|
* Fecha: 4 de enero de 2026
|
|
*/
|
|
|
|
require_once '../config/config.php';
|
|
|
|
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 {
|
|
$db = Database::getInstance();
|
|
|
|
// Obtener conversaciones agregadas por usuario: último mensaje + conteo de no leídos + avatar
|
|
$conversations = $db->fetchAll(
|
|
"SELECT
|
|
u.id AS user_id,
|
|
COALESCE(u.name, u.phone_number) AS name,
|
|
u.phone_number,
|
|
u.avatar_url,
|
|
lm.message_id AS last_message_id,
|
|
lm.content AS last_message,
|
|
lm.direction AS direction,
|
|
lm.message_type AS message_type,
|
|
lm.created_at AS last_time,
|
|
IFNULL(SUM(CASE WHEN c.direction = 'incoming' AND (c.is_read IS NULL OR c.is_read = 0) THEN 1 ELSE 0 END), 0) AS unread_count
|
|
FROM users u
|
|
LEFT JOIN conversations c ON c.user_id = u.id
|
|
LEFT JOIN (
|
|
SELECT t1.* FROM conversations t1
|
|
JOIN (
|
|
SELECT user_id, MAX(created_at) AS last_time FROM conversations GROUP BY user_id
|
|
) t2 ON t1.user_id = t2.user_id AND t1.created_at = t2.last_time
|
|
) lm ON lm.user_id = u.id
|
|
GROUP BY u.id
|
|
ORDER BY lm.created_at DESC
|
|
LIMIT 500"
|
|
);
|
|
|
|
// Si no hay datos, retornar array vacío
|
|
if (empty($conversations)) {
|
|
$conversations = [];
|
|
}
|
|
|
|
// Formatear datos para el frontend
|
|
$conversations = array_map(function($conv) {
|
|
return [
|
|
'id' => intval($conv['id']),
|
|
'user_id' => intval($conv['user_id']),
|
|
'content' => $conv['content'] ?? '',
|
|
'direction' => $conv['direction'] ?? 'incoming',
|
|
'message_type' => $conv['message_type'] ?? 'text',
|
|
'status' => $conv['status'] ?? 'sent',
|
|
'created_at' => $conv['created_at'],
|
|
'phone_number' => $conv['phone_number'],
|
|
'name' => $conv['name'] ?? $conv['phone_number']
|
|
];
|
|
}, $conversations);
|
|
|
|
echo json_encode($conversations);
|
|
|
|
} catch (Exception $e) {
|
|
error_log("Error in get_conversations.php: " . $e->getMessage());
|
|
http_response_code(500);
|
|
echo json_encode(['error' => 'Error interno del servidor: ' . $e->getMessage()]);
|
|
}
|
|
?>
|