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', '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()]); } ?>