diff --git a/services/BotService.php b/services/BotService.php index f3c60fd..4f7e5af 100644 --- a/services/BotService.php +++ b/services/BotService.php @@ -326,7 +326,19 @@ class BotService { */ private function processMenuSelection($user, $messageText) { $phoneNumber = $user['phone_number']; - $currentMenuId = $user['current_menu_id']; + // Obtener el current_menu_id más reciente desde la tabla users (evita estados desincronizados) + $cur = $this->db->fetch("SELECT current_menu_id FROM users WHERE phone_number = :phone", ['phone' => $phoneNumber]); + $currentMenuId = $cur ? $cur['current_menu_id'] : ($user['current_menu_id'] ?? null); + + // Fallback: si usamos ConversationStateService para guardar estados, respetarlo + if (empty($currentMenuId)) { + try { + $stateSvc = new ConversationStateService(); + $currentMenuId = $stateSvc->getCurrentMenuId($phoneNumber); + } catch (Exception $e) { + // ignore if service not available + } + } // DEBUG try { error_log("[BotService] processMenuSelection - user_id={$user['id']} menu_id={$currentMenuId} received='{$messageText}'"); } catch (Throwable $t) {} @@ -654,14 +666,35 @@ class BotService { */ private function goToParentMenu($phoneNumber, $currentMenuId) { try { - $menu = $this->db->fetch("SELECT parent_id FROM menus WHERE id = :id", ['id' => $currentMenuId]); - $parentId = $menu['parent_id'] ?? null; - if (!empty($parentId)) { - $this->showMenu($phoneNumber, $parentId); - } else { - // Si no hay padre, mostrar menú principal - $this->showMainMenu($phoneNumber); + $parentId = null; + $menu = null; + + // Intentar resolver por ID numérico + if (!empty($currentMenuId) && is_numeric($currentMenuId)) { + $menu = $this->db->fetch("SELECT id, parent_id FROM menus WHERE id = :id", ['id' => (int)$currentMenuId]); } + + // Si no existe, intentar resolver por nombre (caso action_value = 'main_menu') + if (!$menu && !empty($currentMenuId)) { + $menu = $this->db->fetch("SELECT id, parent_id FROM menus WHERE name = :name", ['name' => $currentMenuId]); + } + + if ($menu) { + $parentId = $menu['parent_id'] ?? null; + if (!empty($parentId)) { + $this->showMenu($phoneNumber, $parentId); + return; + } else { + // Si no hay padre, re-mostrar el menú actual (mejor UX) o fallback al menú principal + if (!empty($menu['id'])) { + $this->showMenu($phoneNumber, $menu['id']); + return; + } + } + } + + // Fallback final a menú principal + $this->showMainMenu($phoneNumber); } catch (Exception $e) { error_log('[BotService] goToParentMenu failed: ' . $e->getMessage()); $this->showMainMenu($phoneNumber);