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