114 lines
4.5 KiB
PHP
114 lines
4.5 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();
|
|
|
|
// Paginación: recibir page y limit desde query string (con límites razonables)
|
|
$limit = isset($_GET['limit']) ? intval($_GET['limit']) : 50;
|
|
$limit = max(1, min(200, $limit)); // máximo 200 por página
|
|
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
|
|
$offset = ($page - 1) * $limit;
|
|
|
|
// Obtener conversaciones agregadas por usuario: último mensaje + conteo de no leídos + avatar
|
|
$filter = isset($_GET['filter']) ? strtolower(trim($_GET['filter'])) : 'all';
|
|
|
|
$sql = "SELECT
|
|
u.id AS user_id,
|
|
COALESCE(u.name, u.phone_number) AS name,
|
|
u.phone_number,
|
|
u.avatar_url,
|
|
u.bot_enabled,
|
|
u.on_hold,
|
|
u.advisor_requested,
|
|
u.in_service,
|
|
u.in_service_by,
|
|
u.in_service_at,
|
|
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";
|
|
|
|
// Aplicar filtro 'unread' si se solicita
|
|
if ($filter === 'unread') {
|
|
$sql .= " HAVING IFNULL(SUM(CASE WHEN c.direction = 'incoming' AND (c.is_read IS NULL OR c.is_read = 0) THEN 1 ELSE 0 END), 0) > 0";
|
|
}
|
|
|
|
$sql .= "\n ORDER BY lm.created_at DESC\n LIMIT %d OFFSET %d";
|
|
|
|
$conversations = $db->fetchAll(sprintf($sql, $limit, $offset));
|
|
|
|
// Conteo total de usuarios con al menos una conversación (útil para paginar)
|
|
if ($filter === 'unread') {
|
|
$totalRow = $db->fetch("SELECT COUNT(DISTINCT user_id) AS count FROM conversations c WHERE c.direction = 'incoming' AND (c.is_read IS NULL OR c.is_read = 0)");
|
|
} else {
|
|
$totalRow = $db->fetch("SELECT COUNT(DISTINCT user_id) AS count FROM conversations");
|
|
}
|
|
$total = isset($totalRow['count']) ? intval($totalRow['count']) : 0;
|
|
|
|
// Si no hay datos, retornar array vacío
|
|
if (empty($conversations)) {
|
|
$conversations = [];
|
|
}
|
|
|
|
// Formatear datos para el frontend
|
|
$conversations = array_map(function($conv) {
|
|
return [
|
|
'user_id' => intval($conv['user_id']),
|
|
'name' => $conv['name'] ?? $conv['phone_number'],
|
|
'phone_number' => $conv['phone_number'],
|
|
'avatar_url' => $conv['avatar_url'] ?? null,
|
|
'last_message' => $conv['last_message'] ?? '',
|
|
'last_time' => $conv['last_time'] ?? null,
|
|
'direction' => $conv['direction'] ?? 'incoming',
|
|
'message_type' => $conv['message_type'] ?? 'text',
|
|
'unread_count' => intval($conv['unread_count'] ?? 0),
|
|
'bot_enabled' => isset($conv['bot_enabled']) ? (bool)$conv['bot_enabled'] : true,
|
|
'on_hold' => isset($conv['on_hold']) ? (bool)$conv['on_hold'] : false,
|
|
'advisor_requested' => isset($conv['advisor_requested']) ? (bool)$conv['advisor_requested'] : false,
|
|
'in_service' => isset($conv['in_service']) ? (bool)$conv['in_service'] : false,
|
|
'in_service_by' => isset($conv['in_service_by']) ? intval($conv['in_service_by']) : null,
|
|
'in_service_at' => $conv['in_service_at'] ?? null
|
|
];
|
|
}, $conversations);
|
|
|
|
// Indicar metadatos para la paginación
|
|
$hasMore = ($page * $limit) < $total;
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $conversations,
|
|
'page' => $page,
|
|
'limit' => $limit,
|
|
'has_more' => (bool)$hasMore,
|
|
'total' => $total
|
|
]);
|
|
|
|
|
|
} 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()]);
|
|
}
|
|
?>
|