0"; } // Ordenar por relevancia si hay búsqueda, sino por fecha if (!empty($search)) { $sql .= "\n ORDER BY relevance DESC, lm.created_at DESC"; } else { $sql .= "\n ORDER BY lm.created_at DESC"; } $sql .= "\n LIMIT %d OFFSET %d"; // Preparar parámetros para la consulta $params = []; if (!empty($search)) { $searchParam = '%' . $search . '%'; // Para el campo de relevancia $params[] = $searchParam; // name LIKE $params[] = $searchParam; // phone_number LIKE // Para el WHERE $params[] = $searchParam; // name LIKE $params[] = $searchParam; // phone_number LIKE $params[] = $searchParam; // content LIKE } $finalSql = sprintf($sql, $limit, $offset); if (!empty($params)) { $conversations = $db->fetchAll($finalSql, $params); } else { $conversations = $db->fetchAll($finalSql); } // Conteo total de usuarios con al menos una conversación (útil para paginar) if (!empty($search)) { // Conteo con búsqueda $searchParam = '%' . $search . '%'; $countSql = "SELECT COUNT(DISTINCT u.id) AS count FROM users u LEFT JOIN conversations c ON c.user_id = u.id WHERE ( u.name LIKE ? OR u.phone_number LIKE ? OR EXISTS ( SELECT 1 FROM conversations c2 WHERE c2.user_id = u.id AND c2.content LIKE ? ) )"; if ($filter === 'unread') { $countSql .= " AND c.direction = 'incoming' AND (c.is_read IS NULL OR c.is_read = 0)"; } $totalRow = $db->fetch($countSql, [$searchParam, $searchParam, $searchParam]); } else { // Conteo normal sin búsqueda 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', 'last_local_file' => $conv['last_local_file'] ?? null, 'last_local_thumb' => $conv['last_local_thumb'] ?? null, '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()]); } ?>