diff --git a/api/get_user_messages.php b/api/get_user_messages.php index 65bf771..66825da 100644 --- a/api/get_user_messages.php +++ b/api/get_user_messages.php @@ -99,9 +99,9 @@ try { // Queremos devolver los mensajes en orden cronológico ascendente para la UI $conversations = array_reverse($conversations); - // Indicar si hay más mensajes anteriores (si la consulta original devolvió exactamente $limit, podría haber más) - $initialCount = is_array($conversations) ? count($conversations) : 0; - $hasMore = $initialCount >= 1 && $initialCount == $limit ? true : false; + // Recalcular usando el resultado final para decidir paginación + $finalCount = is_array($conversations) ? count($conversations) : 0; + $hasMore = ($finalCount > 0 && $finalCount == $limit) ? true : false; // Si no hay mensajes en conversations, intentar con conversaciones (compatibilidad antigua) if (empty($conversations)) { @@ -164,15 +164,28 @@ try { // earliest message timestamp (para paginación hacia atrás) $earliest = $conversations[0]['created_at'] ?? null; + // Si usamos fallback y el earliest coincide o es >= al 'before' solicitado, + // decrementamos 1 segundo para evitar que la próxima petición repita el mismo bloque + $fallbackUsed = (isset($conversationsFallback) && !empty($conversationsFallback)); + if ($fallbackUsed && $earliest && $before) { + $earliest_ts = strtotime($earliest); + $before_ts = strtotime($before); + if ($earliest_ts !== false && $before_ts !== false && $earliest_ts >= $before_ts) { + // restar 1 segundo + $earliest = date('Y-m-d H:i:s', $earliest_ts - 1); + error_log('get_user_messages.php - adjusted earliest to avoid duplicate pagination: ' . $earliest); + } + } + // Añadir debug information cuando se solicita (solo con ?debug=1) $debugInfo = null; if (!empty($_GET['debug']) && $_GET['debug'] == '1') { $debugInfo = [ 'original_sql' => substr($sql, 0, 2000), 'params' => $params, - 'initial_count' => $initialCount, - 'fallback_used' => isset($conversationsFallback) && !empty($conversationsFallback), - 'fallback_count' => isset($conversationsFallback) ? count($conversationsFallback) : 0 + 'final_count' => $finalCount ?? (is_array($conversations) ? count($conversations) : 0), + 'fallback_used' => $fallbackUsed, + 'fallback_count' => $fallbackUsed ? count($conversationsFallback) : 0 ]; }