'POST', 'callback' => array( $this, 'handle_message' ), 'permission_callback' => array( $this, 'check_permission' ), 'args' => array( 'message' => array( 'required' => true, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => function( $val ) { return is_string( $val ) && strlen( trim( $val ) ) > 0 && strlen( $val ) <= 2000; }, ), 'session_id' => array( 'required' => false, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ), ), ) ); register_rest_route( self::REST_NAMESPACE, '/chatbot/history', array( 'methods' => 'GET', 'callback' => array( $this, 'get_history' ), 'permission_callback' => array( $this, 'check_permission' ), ) ); register_rest_route( self::REST_NAMESPACE, '/chatbot/history', array( 'methods' => 'DELETE', 'callback' => array( $this, 'clear_own_history' ), 'permission_callback' => array( $this, 'check_permission' ), ) ); } /** * Only logged-in users with customer/subscriber or higher roles can use the chatbot. */ public function check_permission() { if ( ! is_user_logged_in() && ! (bool) get_option( 'wtofe_chatbot_allow_guests', false ) ) { return new WP_Error( 'rest_forbidden', __( 'You must be logged in to use the chatbot.', 'ai-content-generator-for-woocommerce' ), array( 'status' => 401 ) ); } return true; } /** * Main message handler. Builds context, calls the AI, stores history. * Supports invisible background loops for multi-step AI reasoning. */ public function handle_message( WP_REST_Request $request ) { $body = $request->get_json_params() ?: array(); $user_message = isset( $body['message'] ) ? trim( sanitize_textarea_field( $body['message'] ) ) : trim( (string) $request->get_param( 'message' ) ); $import_context = isset( $body['import_context'] ) ? sanitize_text_field( $body['import_context'] ) : ''; $user_id = get_current_user_id(); // 0 for guests $is_admin = $user_id && ( user_can( $user_id, 'manage_woocommerce' ) || user_can( $user_id, 'manage_options' ) ); // Until an AI provider is connected, every message gets the same reply. // Nothing is saved to history: a stored "not set up" reply would end up // in the AI's context once a provider is connected. if ( ! AI_Content_Generator_For_WooCommerce_Helper::has_active_connector() ) { return new WP_REST_Response( array( 'success' => true, 'response' => $this->get_not_configured_reply( $is_admin ), ), 200 ); } $history = $user_id ? AI_Content_Generator_Chatbot_DB::get_user_history( $user_id, 5 ) : array(); $ai_messages = array(); // Inject the last 5 message-pairs as context. // bot_response is stored as HTML for display; strip it to plain text before // passing it to the AI so the context stays clean and token-efficient. foreach ( $history as $entry ) { $ai_messages[] = array( 'role' => 'user', 'content' => $entry['user_message'] ); $ai_messages[] = array( 'role' => 'assistant', 'content' => $this->strip_html_for_context( $entry['bot_response'] ) ); } // Prepend compact import context to the user message when present. // This keeps the system prompt lean while still giving the AI exact product IDs. $message_with_context = $import_context ? $import_context . "\n\n" . $user_message : $user_message; $ai_messages[] = array( 'role' => 'user', 'content' => $message_with_context ); $system_prompt = $this->build_system_prompt( $user_id, $user_message, $import_context ); array_unshift( $ai_messages, array( 'role' => 'system', 'content' => $system_prompt ) ); // Mirror the chatbot model setting into the feature option read by // get_provider_credentials(). An empty value ("Use default") must clear it, // otherwise a previously saved model keeps overriding the provider default. $chatbot_model = trim( (string) get_option( 'wtofe_chatbot_model', '' ) ); if ( get_option( 'wtofe_ai_model_chatbot', '' ) !== $chatbot_model ) { update_option( 'wtofe_ai_model_chatbot', $chatbot_model ); } $max_hops = 5; $current_hop = 0; $bot_reply = ''; while ( $current_hop < $max_hops ) { $current_hop++; $response = AI_Content_Generator_For_WooCommerce_Helper::call_chat_api( $ai_messages, 4000, // fallback if option not yet saved; option overrides this 1.0, 'chatbot' ); if ( is_wp_error( $response ) ) { // Admins get the explanation and fix links; shoppers shouldn't // see provider or API key details. $bot_reply = $is_admin ? AI_Content_Generator_For_WooCommerce_Helper::get_error_html( $response ) : esc_html__( 'Sorry, the assistant is unavailable right now. Please try again later.', 'ai-content-generator-for-woocommerce' ); break; } $bot_reply = isset( $response['choices'][0]['message']['content'] ) ? trim( $response['choices'][0]['message']['content'] ) : __( 'Sorry, I could not process your request.', 'ai-content-generator-for-woocommerce' ); $bot_reply = html_entity_decode( $bot_reply, ENT_QUOTES | ENT_HTML5, 'UTF-8' ); // Match action JSON blocks — supports both single-line and multi-line JSON. // Uses [\s\S]*? (non-greedy, matches any char including newlines) bounded by { }. // A negative lookahead ensures we don't match nested objects. if ( preg_match_all( '/(\{[\s\S]*?"_action"\s*:\s*"[^"]+"[\s\S]*?\})/m', $bot_reply, $matches ) ) { $has_actions = false; foreach ( $matches[1] as $json_string ) { $json = json_decode( $json_string, true ); if ( is_array( $json ) && ! empty( $json['_action'] ) ) { $action_name = sanitize_key( $json['_action'] ); // Print actions render as HTML buttons — do NOT run in background loop. if ( ! WTOFE_Chatbot_Module_Print::handles( $action_name ) ) { $has_actions = true; break; } } } if ( $has_actions ) { $ai_messages[] = array( 'role' => 'assistant', 'content' => $bot_reply ); $system_feedback = "SYSTEM: Action results from your previous response:\n"; foreach ( $matches[1] as $json_string ) { $json = json_decode( $json_string, true ); if ( ! is_array( $json ) || empty( $json['_action'] ) ) { continue; } $action_name = sanitize_key( $json['_action'] ); // Skip print actions — they produce HTML and run in dispatch_ability instead. if ( WTOFE_Chatbot_Module_Print::handles( $action_name ) ) { continue; } $result = $this->execute_raw_action( $json, $is_admin, $user_id ); if ( is_wp_error( $result ) ) { $system_feedback .= "- {$action_name} FAILED: " . $result->get_error_message() . "\n"; } elseif ( is_string( $result ) ) { $system_feedback .= "- {$action_name} RESULT: {$result}\n"; } else { $system_feedback .= "- {$action_name} SUCCESS: " . wp_json_encode( $result ) . "\n"; } } $system_feedback .= "\nIf you still need to execute further actions to fulfill the user's request (e.g., executing create_bogo after resolving IDs), output the NEXT required JSON block(s) now.\n"; $system_feedback .= "\nIf the user's request is FULLY complete or has failed, write your FINAL reply. Rules for final reply:\n"; $system_feedback .= "- Be concise and friendly.\n"; $system_feedback .= "- State what was done and include the key result (name, ID, status).\n"; // ----------- Strict visual formatting rules for Success/Failure states ----------- $system_feedback .= "- COLOR CODING (CRITICAL): You MUST wrap successful action outcomes in green text: ✔ [Your success message]\n"; $system_feedback .= "- COLOR CODING (CRITICAL): You MUST wrap failed action outcomes in red text: ✘ [Your error message]\n"; $system_feedback .= "- USE ONLY HTML FOR FORMATTING (e.g., , ). NEVER use Markdown (do NOT use ** or *).\n"; $system_feedback .= "- If the result contains an edit_url, render it as an HTML anchor: Edit [Item Name]\n"; $system_feedback .= "- If the result contains a view_url, render it as: View [Item Name]\n"; $system_feedback .= "- If the result contains a coupon_code, mention it using tags, NOT Markdown.\n"; $system_feedback .= "- Do NOT output any JSON or _action blocks in your final reply.\n"; $system_feedback .= "- Do NOT say 'let me search' or announce what you are doing.\n"; $system_feedback .= "- If something failed, explain clearly and suggest what the user can do.\n"; $ai_messages[] = array( 'role' => 'system', 'content' => $system_feedback ); continue; } } break; } // Process final output $bot_reply = $this->dispatch_ability( $bot_reply, $is_admin, $user_id ); // $bot_reply = $this->sanitize_bot_reply( $bot_reply ); // IMPORTANT: what gets saved to history is the PLACEHOLDER form (any // print/download links are inert #wtofe-print-... fragments, not real // nonce URLs). This is what keeps history links from ever going stale. if ( $user_id ) { AI_Content_Generator_Chatbot_DB::save_message( $user_id, $user_message, $bot_reply ); } // The live reply the user sees right now DOES get real, working links — // resolved fresh against the current request/session. $live_reply = class_exists( 'WTOFE_Chatbot_Module_Print' ) ? WTOFE_Chatbot_Module_Print::resolve_placeholders( $bot_reply, $is_admin, $user_id ) : $bot_reply; return new WP_REST_Response( array( 'success' => true, 'response' => $live_reply, ), 200 ); } /** * The reply to every message while no AI provider is connected. Admins get * a link to the setup wizard; shoppers get the same message they see when * the provider can't be reached, without setup details. * * @param bool $is_admin * @return string HTML. */ private function get_not_configured_reply( $is_admin ) { if ( ! $is_admin ) { return esc_html__( 'Sorry, the assistant is unavailable right now. Please try again later.', 'ai-content-generator-for-woocommerce' ); } return sprintf( /* translators: %s: link to the setup wizard */ esc_html__( 'I can\'t answer yet because no AI provider is connected. %s to connect one in a couple of minutes.', 'ai-content-generator-for-woocommerce' ), '' . esc_html__( 'Run the setup wizard', 'ai-content-generator-for-woocommerce' ) . '' ); } /** * Centralized function to execute the WooCommerce action and return the raw result. * Used by both the background loop and the final HTML renderer. */ private function execute_raw_action( $json, $is_admin, $user_id ) { $action = sanitize_key( $json['_action'] ); $result = null; // --- BOGO MODULE DISPATCH --- if ( WTOFE_Chatbot_Module_Bogo::handles( $action ) ) { if ( ! $is_admin ) { return new WP_Error( 'rest_forbidden', 'Unauthorized: BOGO actions require admin access.' ); } return WTOFE_Chatbot_Module_Bogo::dispatch( $action, $json ); } // --- PRINT MODULE DISPATCH --- if ( WTOFE_Chatbot_Module_Print::handles( $action ) ) { return WTOFE_Chatbot_Module_Print::dispatch( $action, $json, $is_admin ); } // --- SECURITY GATE --- // Admin-only actions: write actions AND admin read/fetch actions. $admin_only_actions = array( // Write actions 'create_product', 'update_product', 'delete_product', 'publish_product', 'search_product', 'generate_description', 'generate_short_description', 'generate_tags', 'generate_brands', 'generate_image', 'create_coupon', 'update_order_status', // On-demand admin fetch actions (lazy context) 'admin_get_orders', 'admin_get_order_details', 'admin_get_products', 'admin_get_coupons', 'admin_get_low_stock', ); if ( in_array( $action, $admin_only_actions ) && ! $is_admin ) { return new WP_Error( 'rest_forbidden', 'Unauthorized: You do not have permission to execute admin actions.' ); } switch ( $action ) { // ========================================== // ADMIN ON-DEMAND FETCH ACTIONS // The AI calls these when it needs context, // instead of receiving everything up-front. // ========================================== case 'admin_get_orders': $limit = isset( $json['limit'] ) ? min( absint( $json['limit'] ), 50 ) : 15; $status = isset( $json['status'] ) && $json['status'] ? sanitize_text_field( $json['status'] ) : array(); $args = array( 'limit' => $limit, 'orderby' => 'date', 'order' => 'DESC' ); if ( $status ) { $args['status'] = $status; } $orders = wc_get_orders( $args ); $currency = get_woocommerce_currency_symbol(); $result = array(); foreach ( $orders as $o ) { $items = array(); foreach ( $o->get_items() as $item ) { $items[] = $item->get_name() . ' x' . $item->get_quantity(); } $result[] = array( 'order_id' => $o->get_order_number(), 'status' => wc_get_order_status_name( $o->get_status() ), 'date' => $o->get_date_created()->date( 'Y-m-d H:i' ), 'total' => $currency . $o->get_total(), 'customer' => trim( $o->get_billing_first_name() . ' ' . $o->get_billing_last_name() ), 'email' => $o->get_billing_email(), 'items' => implode( ', ', $items ), ); } if ( empty( $result ) ) { $result = 'No orders found.'; } break; case 'admin_get_order_details': $order_id = isset( $json['order_id'] ) ? absint( $json['order_id'] ) : 0; $order = $order_id ? wc_get_order( $order_id ) : null; if ( ! $order ) { $result = 'Order not found.'; break; } $currency = get_woocommerce_currency_symbol(); $items = array(); foreach ( $order->get_items() as $item ) { if ( ! $item instanceof WC_Order_Item_Product ) { continue; } $items[] = array( 'name' => $item->get_name(), 'qty' => $item->get_quantity(), 'subtotal' => $currency . wc_format_decimal( $item->get_total(), 2 ), ); } $result = array( 'order_id' => $order->get_order_number(), 'status' => wc_get_order_status_name( $order->get_status() ), 'date' => $order->get_date_created()->date( 'Y-m-d H:i' ), 'total' => $currency . $order->get_total(), 'customer' => trim( $order->get_billing_first_name() . ' ' . $order->get_billing_last_name() ), 'email' => $order->get_billing_email(), 'phone' => $order->get_billing_phone(), 'payment_method' => $order->get_payment_method_title(), 'shipping' => $order->get_formatted_shipping_address(), 'items' => $items, 'notes' => $order->get_customer_note(), ); break; case 'admin_get_products': $limit = isset( $json['limit'] ) ? min( absint( $json['limit'] ), 50 ) : 20; $search_term = isset( $json['search_term'] ) ? sanitize_text_field( $json['search_term'] ) : ''; $status = isset( $json['status'] ) ? sanitize_text_field( $json['status'] ) : array( 'publish', 'draft' ); $args = array( 'status' => $status, 'limit' => $limit, 'orderby' => 'date', 'order' => 'DESC', ); if ( $search_term ) { $args['s'] = $search_term; } $products = wc_get_products( $args ); $currency = get_woocommerce_currency_symbol(); $result = array(); foreach ( $products as $p ) { $stock = $p->managing_stock() ? 'Qty: ' . $p->get_stock_quantity() : ( $p->is_in_stock() ? 'In Stock' : 'Out of Stock' ); $result[] = array( 'id' => $p->get_id(), 'name' => $p->get_name(), 'status' => $p->get_status(), 'price' => $currency . $p->get_regular_price(), 'stock' => $stock, 'sku' => $p->get_sku() ?: 'N/A', 'edit_url' => get_edit_post_link( $p->get_id(), 'raw' ), ); } if ( empty( $result ) ) { $result = 'No products found.'; } break; case 'admin_get_coupons': $limit = isset( $json['limit'] ) ? min( absint( $json['limit'] ), 50 ) : 10; $coupons = get_posts( array( 'post_type' => 'shop_coupon', 'posts_per_page' => $limit, 'post_status' => 'publish', ) ); $currency = get_woocommerce_currency_symbol(); $result = array(); foreach ( $coupons as $coupon_post ) { $c = new WC_Coupon( $coupon_post->post_title ); $discount = 'percent' === $c->get_discount_type() ? $c->get_amount() . '% off' : $currency . $c->get_amount() . ' off'; $expiry = $c->get_date_expires() ? $c->get_date_expires()->date( 'Y-m-d' ) : 'No expiry'; $result[] = array( 'code' => $c->get_code(), 'discount' => $discount, 'discount_type' => $c->get_discount_type(), 'usage_count' => $c->get_usage_count(), 'usage_limit' => $c->get_usage_limit() ?: 'Unlimited', 'expires' => $expiry, 'min_amount' => $c->get_minimum_amount() ?: 'None', ); } if ( empty( $result ) ) { $result = 'No active coupons found.'; } break; case 'admin_get_low_stock': $threshold = (int) get_option( 'woocommerce_notify_low_stock_amount', 2 ); $products = wc_get_products( array( 'status' => 'publish', 'limit' => 50, 'stock_status' => 'instock', 'low_stock_amount' => true, ) ); $result = array(); foreach ( $products as $p ) { if ( $p->managing_stock() && $p->get_stock_quantity() <= $threshold ) { $result[] = array( 'id' => $p->get_id(), 'name' => $p->get_name(), 'qty' => $p->get_stock_quantity(), 'sku' => $p->get_sku() ?: 'N/A', ); } } if ( empty( $result ) ) { $result = 'No low-stock products found.'; } break; // ========================================== // CUSTOMER READ-ONLY ACTIONS // ========================================== case 'customer_search_products': $term = isset( $json['search_term'] ) ? sanitize_text_field( $json['search_term'] ) : ''; $products = wc_get_products( array( 'status' => 'publish', 'limit' => 5, 's' => $term ) ); $result = array(); foreach ( $products as $p ) { $result[] = array( 'id' => $p->get_id(), 'name' => $p->get_name(), 'price' => wp_strip_all_tags( html_entity_decode( $p->get_price_html(), ENT_QUOTES | ENT_HTML5, 'UTF-8' ) ), 'stock' => $p->is_in_stock() ? 'In Stock' : 'Out of Stock', 'link' => get_permalink( $p->get_id() ), ); } if ( empty( $result ) ) { $result = 'No products found matching that query.'; } break; case 'customer_get_recent_orders': if ( ! $user_id ) { return 'User is a guest. Tell them they must log in to view orders.'; } $orders = wc_get_orders( array( 'customer_id' => $user_id, 'status' => array( 'pending', 'processing', 'completed', 'on-hold', 'cancelled', 'refunded', 'failed' ), 'limit' => 5, 'orderby' => 'date', 'order' => 'DESC', ) ); $result = array(); foreach ( $orders as $o ) { $result[] = array( 'order_id' => $o->get_order_number(), 'status' => wc_get_order_status_name( $o->get_status() ), 'date' => $o->get_date_created()->date( 'Y-m-d' ), 'total' => $o->get_total(), ); } if ( empty( $result ) ) { $result = 'You have no recent orders.'; } break; case 'customer_get_order_details': if ( ! $user_id ) { return 'User is a guest. Cannot view orders.'; } $order_id = isset( $json['order_id'] ) ? absint( $json['order_id'] ) : 0; $order = wc_get_order( $order_id ); if ( ! $order || $order->get_customer_id() !== $user_id ) { return 'Order not found or belongs to a different user.'; } $items = array(); foreach ( $order->get_items() as $item ) { $items[] = $item->get_name() . ' x' . $item->get_quantity(); } $result = array( 'order_id' => $order->get_order_number(), 'status' => wc_get_order_status_name( $order->get_status() ), 'total' => $order->get_total(), 'items' => $items, ); break; case 'customer_get_coupons': $coupons = get_posts( array( 'post_type' => 'shop_coupon', 'posts_per_page' => 5, 'post_status' => 'publish', ) ); $result = array(); foreach ( $coupons as $c_post ) { $c = new WC_Coupon( $c_post->post_title ); $result[] = array( 'code' => $c->get_code(), 'amount' => $c->get_amount(), 'discount_type' => $c->get_discount_type(), ); } if ( empty( $result ) ) { $result = 'No active coupons available right now.'; } break; // ========================================== // ADMIN WRITE ACTIONS // ========================================== case 'create_product': $status = isset( $json['status'] ) && 'publish' === $json['status'] ? 'publish' : 'draft'; $result = AI_Content_Generator_For_WooCommerce_Helper::create_product( $json, $status ); break; case 'update_product': if ( ! empty( $json['product_id'] ) ) { $pid = absint( $json['product_id'] ); $result = AI_Content_Generator_For_WooCommerce_Helper::update_product( $pid, $json ); } break; case 'delete_product': if ( ! empty( $json['product_id'] ) ) { $force = ! empty( $json['force_delete'] ); $result = AI_Content_Generator_For_WooCommerce_Helper::delete_product( absint( $json['product_id'] ), $force ); } break; case 'publish_product': if ( ! empty( $json['product_id'] ) ) { $result = AI_Content_Generator_For_WooCommerce_Helper::publish_product( absint( $json['product_id'] ) ); } break; case 'search_product': if ( ! empty( $json['search_term'] ) ) { $result = AI_Content_Generator_For_WooCommerce_Helper::search_product_id( $json ); } break; case 'generate_description': if ( ! empty( $json['product_id'] ) ) { $tone = isset( $json['tone'] ) ? sanitize_text_field( $json['tone'] ) : 'formal'; $result = AI_Content_Generator_For_WooCommerce_Helper::api_generate_description( absint( $json['product_id'] ), $tone ); if ( ! is_wp_error( $result ) && ! empty( $result['description'] ) ) { $product = wc_get_product( absint( $json['product_id'] ) ); if ( $product ) { $product->set_description( $result['description'] ); if ( ! empty( $result['excerpt'] ) ) { $product->set_short_description( $result['excerpt'] ); } $product->save(); } $result['success'] = true; $result['message'] = 'Description generated and saved successfully.'; } } break; case 'generate_short_description': if ( ! empty( $json['product_id'] ) ) { $tone = isset( $json['tone'] ) ? sanitize_text_field( $json['tone'] ) : 'formal'; $result = AI_Content_Generator_For_WooCommerce_Helper::api_generate_short_description( absint( $json['product_id'] ), $tone ); if ( ! is_wp_error( $result ) && is_string( $result ) ) { $product = wc_get_product( absint( $json['product_id'] ) ); if ( $product ) { $product->set_short_description( $result ); $product->save(); } $result = array( 'success' => true, 'message' => 'Short description generated and saved.', 'excerpt' => $result ); } } break; case 'generate_tags': if ( ! empty( $json['product_id'] ) ) { $pid = absint( $json['product_id'] ); $result = AI_Content_Generator_For_WooCommerce_Helper::api_generate_tags( $pid ); if ( ! is_wp_error( $result ) && ! empty( $result['tags'] ) ) { $tag_ids = array(); foreach ( $result['tags'] as $name ) { $term = get_term_by( 'name', $name, 'product_tag' ); if ( $term ) { $tag_ids[] = $term->term_id; } else { $inserted = wp_insert_term( $name, 'product_tag' ); if ( ! is_wp_error( $inserted ) ) { $tag_ids[] = $inserted['term_id']; } } } if ( $tag_ids ) { wp_set_object_terms( $pid, $tag_ids, 'product_tag' ); } $result['success'] = true; $result['message'] = 'Tags generated and saved to product.'; } } break; case 'generate_brands': if ( ! empty( $json['product_id'] ) ) { $pid = absint( $json['product_id'] ); $result = AI_Content_Generator_For_WooCommerce_Helper::api_generate_brands( $pid ); if ( ! is_wp_error( $result ) && ! empty( $result['brands'] ) ) { $brand_ids = array(); foreach ( $result['brands'] as $name ) { $term = get_term_by( 'name', $name, 'product_brand' ); if ( $term ) { $brand_ids[] = $term->term_id; } else { $inserted = wp_insert_term( $name, 'product_brand' ); if ( ! is_wp_error( $inserted ) ) { $brand_ids[] = $inserted['term_id']; } } } if ( ! empty( $brand_ids ) ) { wp_set_object_terms( $pid, $brand_ids, 'product_brand' ); } $result['success'] = true; $result['message'] = 'Brands generated and saved to product.'; } } break; case 'generate_image': if ( ! empty( $json['product_id'] ) ) { $pid = absint( $json['product_id'] ); $result = AI_Content_Generator_For_WooCommerce_Helper::api_generate_images( $pid ); if ( ! is_wp_error( $result ) && ! empty( $result['image_urls'] ) ) { $product = wc_get_product( $pid ); $has_feat = $product && (bool) $product->get_image_id(); foreach ( $result['image_urls'] as $url ) { $att_id = AI_Content_Generator_For_WooCommerce_Helper::attach_image_to_product( $pid, $url, $has_feat ); if ( ! is_wp_error( $att_id ) ) { $has_feat = true; } } $result['success'] = true; $result['message'] = count( $result['image_urls'] ) . ' image(s) generated and attached to the product.'; } } break; case 'create_coupon': if ( empty( $json['title'] ) || 'AUTO_GENERATE' === $json['title'] ) { $length = 8; if ( ! empty( $json['code_length'] ) ) { $length = absint( $json['code_length'] ); $length = max( 4, min( 20, $length ) ); } $json['title'] = strtoupper( wp_generate_password( $length, false ) ); } $result = AI_Content_Generator_For_WooCommerce_Helper::create_coupon( $json ); break; case 'update_order_status': if ( ! empty( $json['order_id'] ) && ! empty( $json['new_status'] ) ) { $result = AI_Content_Generator_For_WooCommerce_Helper::update_order_status( absint( $json['order_id'] ), sanitize_text_field( $json['new_status'] ), isset( $json['note'] ) ? sanitize_textarea_field( $json['note'] ) : '' ); } break; } return $result; } /** * Returns the user's complete chat history for display in the chat window. * * Uses get_user_history_admin() (no row limit) so the chat box shows every * past message. The AI context in handle_message() still uses only the last * 5 pairs — this endpoint is purely for UI rendering. */ public function get_history( WP_REST_Request $request ) { $user_id = get_current_user_id(); if ( ! $user_id ) { return new WP_REST_Response( array( 'success' => true, 'history' => array() ), 200 ); } $history = AI_Content_Generator_Chatbot_DB::get_user_history_admin( $user_id ); // Re-resolve any print/download link placeholders against the CURRENT // session, every time history is loaded — this is what makes old // print/download buttons keep working after re-login, password change, // or simple nonce expiry, without ever touching the stored rows. if ( class_exists( 'WTOFE_Chatbot_Module_Print' ) ) { $is_admin = user_can( $user_id, 'manage_woocommerce' ) || user_can( $user_id, 'manage_options' ); foreach ( $history as &$entry ) { if ( ! empty( $entry['bot_response'] ) ) { $entry['bot_response'] = WTOFE_Chatbot_Module_Print::resolve_placeholders( $entry['bot_response'], $is_admin, $user_id ); } } unset( $entry ); } return new WP_REST_Response( array( 'success' => true, 'history' => $history, ), 200 ); } /** * Clears the current user's own chat history. */ public function clear_own_history( WP_REST_Request $request ) { $user_id = get_current_user_id(); if ( $user_id ) { AI_Content_Generator_Chatbot_DB::clear_user_history( $user_id ); } return new WP_REST_Response( array( 'success' => true ), 200 ); } /** * Builds the system prompt. * * Admin sessions receive a lean static overview (3 lines of counts) * plus the full action catalogue. All heavy data — orders, products, * coupons — is fetched on demand by the AI via admin fetch actions. * * Customer sessions have always been on-demand and remain unchanged. * * @param int $user_id * @param string $user_message * @return string */ private function build_system_prompt( $user_id, $user_message, $import_context = '' ) { $store_name = get_bloginfo( 'name' ); $store_url = home_url(); $currency_sym = get_woocommerce_currency_symbol(); $currency = get_woocommerce_currency(); $user = $user_id ? get_userdata( $user_id ) : null; $display_name = $user ? $user->display_name : 'Guest'; $chatbot_name = get_option( 'wtofe_chatbot_name', 'Store Assistant' ); $is_admin = $user_id && ( user_can( $user_id, 'manage_woocommerce' ) || user_can( $user_id, 'manage_options' ) ); if ( $is_admin ) { $prompt = "You are {$chatbot_name}, an AI-powered store management assistant for \"{$store_name}\" ({$store_url}).\n"; $prompt .= "You are speaking with a store administrator or shop manager: {$display_name}.\n"; $prompt .= "Store currency: {$currency} ({$currency_sym}) | Base country: " . WC()->countries->get_base_country() . "\n\n"; $prompt .= "Always respond in clean HTML — use ,
    /
  • ,

    , link text tags. "; $prompt .= "Never use HTML entities like & or ₹ — use real characters instead.\n\n"; // --- Lean static store overview (counts only, no rows) --- $prompt .= $this->get_store_overview(); // --- Behaviour rules --- $prompt .= "CRITICAL ACTION RULES:\n"; $prompt .= "1. JSON MUST BE SINGLE LINE: Every action JSON block must be written on ONE single line. Never break JSON across multiple lines.\n"; $prompt .= "2. SILENT EXECUTION: When you need to perform an action, output ONLY the JSON block(s). Do NOT say 'I will now...' or 'Let me search...'. Just output the JSON.\n"; $prompt .= "3. ALL ACTIONS ARE BACKGROUND: Every action JSON you output is executed silently. You receive the result automatically. Never announce what you are about to do.\n"; $prompt .= "4. FETCH BEFORE YOU ANSWER: You have NO store data preloaded. Before answering any question about orders, products, or coupons, you MUST use the appropriate fetch action first. Never guess or invent IDs, names, or totals.\n"; $prompt .= "5. RESOLVE FULLY BEFORE REPLYING: If a request requires a search first (e.g. finding a product ID), output the fetch JSON. Once you receive the result, chain the next action. Only write a conversational reply AFTER all actions are complete.\n"; $prompt .= "6. INCLUDE LINKS IN REPLY: When an action result contains edit_url or view_url, always render it as an HTML link in your final reply.\n"; $prompt .= "7. HIDDEN RESOLUTIONS: If you perform a search solely to resolve IDs for another action (for example resolving product names for create_bogo), DO NOT include product IDs, edit links, or product URLs in the final conversational reply. Only surface product links/details if the user explicitly requested them.\n"; $prompt .= "8. ONLY ASK WHEN TRULY UNCLEAR: If the user's intent is clear enough to act, act. Only ask a clarifying question if you genuinely cannot proceed.\n\n"; $prompt .= $this->get_admin_abilities_prompt( $user_message, $import_context ); } else { $prompt = "You are {$chatbot_name}, a helpful customer support assistant for \"{$store_name}\" ({$store_url}).\n"; $prompt .= "The customer's name is: {$display_name}\n"; $prompt .= "Store currency: {$currency} ({$currency_sym})\n\n"; $prompt .= "Always respond in clean HTML — use ,

      /
    • ,

      , link text tags. "; $prompt .= "Never use HTML entities like & or ₹ — use real characters instead.\n\n"; $prompt .= "CRITICAL INSTRUCTIONS:\n"; $prompt .= "1. You DO NOT have products, orders, or coupons loaded in your memory. You MUST fetch this data using JSON actions.\n"; $prompt .= "2. DO NOT invent or guess store data. If a user asks a question, trigger the relevant action with \"_wait\": true.\n"; $prompt .= "3. SEARCHING RULE: If a user asks for multiple items (e.g., 'headsets and earbuds'), DO NOT search them one by one. Output MULTIPLE `customer_search_products` JSON blocks AT THE SAME TIME in a single response.\n"; $prompt .= "4. SILENT FETCHING: When outputting JSON with \"_wait\": true, DO NOT output any conversational text. ONLY output the JSON blocks.\n"; $prompt .= "5. Your FINAL response to the user must be normal, friendly text formatted in HTML, without any JSON code visible.\n\n"; $prompt .= $this->get_customer_abilities_prompt( $user_message, $import_context ); } return $prompt; } /** * Returns a compact 3-line store overview (counts only). * Included statically in the admin prompt — it is tiny and always useful. * All row-level data (orders, products, coupons) is fetched on demand. */ private function get_store_overview() { $total_products = wp_count_posts( 'product' ); $published = isset( $total_products->publish ) ? (int) $total_products->publish : 0; $draft_count = isset( $total_products->draft ) ? (int) $total_products->draft : 0; $total_orders = wp_count_posts( 'shop_order' ); $processing = isset( $total_orders->{'wc-processing'} ) ? (int) $total_orders->{'wc-processing'} : 0; $completed = isset( $total_orders->{'wc-completed'} ) ? (int) $total_orders->{'wc-completed'} : 0; $pending = isset( $total_orders->{'wc-pending'} ) ? (int) $total_orders->{'wc-pending'} : 0; $total_coupons = wp_count_posts( 'shop_coupon' ); $active_coupons = isset( $total_coupons->publish ) ? (int) $total_coupons->publish : 0; $overview = "=== Store Overview ===\n"; $overview .= "Products: {$published} published, {$draft_count} drafts | "; $overview .= "Orders: {$processing} processing, {$pending} pending, {$completed} completed | "; $overview .= "Active coupons: {$active_coupons}\n\n"; return $overview; } /** * Returns the admin action catalogue injected into the system prompt. * Includes the new on-demand fetch actions for lazy context loading. */ private function get_admin_abilities_prompt( $message, $import_context = '' ) { $prompt = "=== Available Store Actions ===\n"; $prompt .= "To execute an action, output a JSON block. Verbal confirmation alone does nothing.\n\n"; $prompt .= "CRITICAL RULES TO ENSURE AUTONOMY & PREVENT HALLUCINATIONS:\n"; $prompt .= "1. NEVER invent, guess, or assume Product IDs, Order IDs, or Coupon IDs.\n"; $prompt .= "2. CHAINING ACTIONS STRICTLY: If you output a `search_*` action, the system will silently return the results to you. YOUR VERY NEXT RESPONSE MUST BE THE JSON BLOCK TO EXECUTE THE USER'S REQUEST (e.g., `delete_product`). Do NOT skip straight to a verbal confirmation.\n"; $prompt .= "3. DO NOT FAKE ACTIONS: Never verbally claim you deleted, updated, or created an item unless you are SIMULTANEOUSLY outputting the JSON block to perform that action in the exact same response.\n"; $prompt .= "4. NO INTERMEDIATE CHATTER: Do not narrate your intermediate steps. Only speak to the user once the final modification JSON has been dispatched.\n"; $prompt .= "5. ONLY ASK IF AMBIGUOUS: Only pause to ask the user a question if a search returns MULTIPLE results and you need clarification on which one to modify.\n"; $prompt .= "6. IMMEDIATE EXECUTION: If you already have the required ID, output the JSON block immediately.\n"; $prompt .= "7. AUTO-GENERATED CODES: If the user doesn't specify a coupon name, set title to \"AUTO_GENERATE\".\n"; $prompt .= "8. RAW JSON FORMAT: Do NOT wrap JSON in markdown fences (```). Output raw JSON on its own line.\n\n"; $prompt .= "FORMAT:\n"; $prompt .= "{\"_action\":\"action_name\", \"param1\":\"value1\", ...}\n\n"; $prompt .= $this->get_admin_action_catalog_prompt( $message, $import_context ); $prompt .= WTOFE_Chatbot_Module_Bogo::get_abilities_prompt( $message ); $prompt .= WTOFE_Chatbot_Module_Print::get_admin_abilities_prompt(); return $prompt; } private function get_admin_action_catalog_prompt( $message, $import_context = '' ) { $message = strtolower( trim( $message ) ); // Filler messages — pure greetings/acks with no actionable intent → skip action catalogue. if ( $this->is_filler_message( $message ) && ! $import_context ) { return ''; } $has_product = $this->message_has_keywords( $message, array( 'product', 'products', 'item', 'items', 'sku', 'price', 'inventory', 'stock', 'create', 'update', 'delete', 'publish', 'description', 'tag', 'brand', 'image', 'generate', 'search', 'find' ) ); $has_order = $this->message_has_keywords( $message, array( 'order', 'orders', 'refund', 'status', 'shipping', 'shipped', 'cancel', 'cancelled', 'complete', 'pending', 'processing', 'hold', 'customer' ) ); $has_coupon = $this->message_has_keywords( $message, array( 'coupon', 'discount', 'promo', 'promotion', 'code', 'deal', 'offer', 'voucher', 'sale', 'saving' ) ); $has_stock = $this->message_has_keywords( $message, array( 'low stock', 'stock', 'inventory', 'restock', 'reorder', 'out of stock', 'backorder' ) ); $has_search = $this->message_has_keywords( $message, array( 'search', 'find', 'lookup', 'match', 'which', 'where', 'show', 'list' ) ); // Import context present → always include product actions so AI can act on imported items. if ( $import_context ) { $has_product = true; } // No specific domain matched — show the two most universally needed actions only. $no_match = ! ( $has_product || $has_order || $has_coupon || $has_stock || $has_search ); if ( $no_match ) { $has_product = true; // covers search + product fetch, used for most general queries } $prompt = "ADMIN DATA FETCH ACTIONS (always use _wait:true — result returned silently for chaining):\n"; if ( $has_order ) { $prompt .= "- {\"_action\":\"admin_get_orders\", \"limit\":15, \"status\":\"\", \"_wait\":true}\n"; $prompt .= "- {\"_action\":\"admin_get_order_details\", \"order_id\":123, \"_wait\":true}\n"; } if ( $has_product || $has_stock || $has_search ) { $prompt .= "- {\"_action\":\"admin_get_products\", \"search_term\":\"keyword\", \"limit\":20, \"status\":\"publish\", \"_wait\":true}\n"; } if ( $has_coupon ) { $prompt .= "- {\"_action\":\"admin_get_coupons\", \"limit\":10, \"_wait\":true}\n"; } if ( $has_stock ) { $prompt .= "- {\"_action\":\"admin_get_low_stock\", \"_wait\":true}\n"; } $prompt .= "\n"; if ( $has_product ) { $prompt .= "PRODUCT ACTIONS:\n"; $prompt .= "- " . $this->get_product_action_schema_prompt() . "\n"; $prompt .= "- " . $this->get_product_action_schema_prompt( true ) . "\n"; $prompt .= "- {\"_action\":\"delete_product\",\"product_id\":123,\"force_delete\":false, \"_wait\": true}\n"; $prompt .= "- {\"_action\":\"publish_product\",\"product_id\":123, \"_wait\": true}\n"; $prompt .= "- {\"_action\":\"search_product\",\"search_term\":\"keyword\", \"_wait\": true}\n"; $prompt .= "\nAI GENERATION ACTIONS:\n"; $prompt .= "- {\"_action\":\"generate_description\",\"product_id\":123,\"tone\":\"formal|casual|persuasive|technical|luxury|creative\", \"_wait\": true}\n"; $prompt .= "- {\"_action\":\"generate_short_description\",\"product_id\":123,\"tone\":\"formal\", \"_wait\": true}\n"; $prompt .= "- {\"_action\":\"generate_tags\",\"product_id\":123, \"_wait\": true}\n"; $prompt .= "- {\"_action\":\"generate_brands\",\"product_id\":123, \"_wait\": true}\n"; $prompt .= "- {\"_action\":\"generate_image\",\"product_id\":123, \"_wait\": true}\n"; } if ( $has_coupon ) { $prompt .= "\nCOUPON ACTIONS:\n"; $prompt .= "- {\"_action\":\"create_coupon\",\"title\":\"AUTO_GENERATE\",\"discount_type\":\"percent|fixed\",\"amount\":10,\"fixed_scope\":\"cart|product\",\"code_length\":8, \"_wait\": true}\n"; } if ( $has_order ) { $prompt .= "\nORDER ACTIONS:\n"; $prompt .= "- {\"_action\":\"update_order_status\",\"order_id\":123,\"new_status\":\"wc-cancelled\",\"note\":\"\", \"_wait\": true} (Accepted: wc-pending, wc-processing, wc-on-hold, wc-completed, wc-cancelled, wc-refunded, wc-failed)\n"; } return $prompt; } private function get_product_action_schema_prompt( $include_product_id = false ) { $prompt = $include_product_id ? '{"_action":"update_product","product_id":123,' : '{"_action":"create_product",'; $prompt .= '"title":"...","description":"...","short_description":"...","sku":"...","regular_price":"...","sale_price":"","stock_status":"instock|outofstock","stock":0,"manage_stock":false,"categories":"...","tags":"...","images":"","status":"draft|publish","_wait": true}'; return $prompt; } private function get_customer_abilities_prompt( $message, $import_context = '' ) { $prompt = "AVAILABLE FETCH ACTIONS:\n"; $actions = array(); if ( $this->message_has_keywords( $message, array( 'order', 'orders', 'purchase', 'purchased', 'recent', 'track', 'status', 'refund', 'cancelled', 'shipped' ) ) ) { $actions[] = "- {\"_action\":\"customer_get_recent_orders\", \"_wait\":true}\n"; $actions[] = "- {\"_action\":\"customer_get_order_details\", \"order_id\":123, \"_wait\":true}\n"; } if ( $this->message_has_keywords( $message, array( 'coupon', 'discount', 'promo', 'promotion', 'code', 'deal', 'offer', 'voucher' ) ) ) { $actions[] = "- {\"_action\":\"customer_get_coupons\", \"_wait\":true}\n"; } if ( $this->message_has_keywords( $message, array( 'product', 'products', 'item', 'items', 'search', 'find', 'available', 'stock', 'inventory', 'buy', 'shopping' ) ) ) { $actions[] = "- {\"_action\":\"customer_search_products\", \"search_term\":\"keyword\", \"_wait\":true}\n"; } // Import context present → always include product search for follow-up actions. if ( $import_context && ! $this->message_has_keywords( $message, array( 'product', 'products', 'item', 'items', 'search', 'find', 'available', 'stock', 'inventory', 'buy', 'shopping' ) ) ) { $actions[] = "- {\"_action\":\"customer_search_products\", \"search_term\":\"keyword\", \"_wait\":true}"; } if ( empty( $actions ) ) { if ( $this->is_filler_message( strtolower( trim( $message ) ) ) ) { // Pure greeting — only expose product search as minimal fallback. $actions = array( "- {\"_action\":\"customer_search_products\", \"search_term\":\"keyword\", \"_wait\":true}", ); } else { $actions = array( "- {\"_action\":\"customer_search_products\", \"search_term\":\"keyword\", \"_wait\":true}", "- {\"_action\":\"customer_get_recent_orders\", \"_wait\":true}", "- {\"_action\":\"customer_get_order_details\", \"order_id\":123, \"_wait\":true}", "- {\"_action\":\"customer_get_coupons\", \"_wait\":true}", ); } } $prompt .= implode( '', $actions ); $prompt .= "\n"; $prompt .= WTOFE_Chatbot_Module_Print::get_customer_abilities_prompt(); return $prompt; } /** * Returns true for short pure-filler messages (greetings, acks) that carry no actionable intent. * Used to skip injecting the action catalogue when not needed. * * @param string $message Already lowercased + trimmed. * @return bool */ private function is_filler_message( $message ) { if ( strlen( $message ) > 40 ) { return false; } $fillers = array( 'hello', 'hi', 'hey', 'hiya', 'howdy', 'thanks', 'thank you', 'thank you!', 'thanks!', 'ty', 'ok', 'okay', 'ok!', 'okay!', 'sure', 'alright', 'got it', 'understood', 'bye', 'goodbye', 'good morning', 'good afternoon', 'good evening', 'great', 'awesome', 'perfect', 'nice', 'cool', 'sounds good', 'great!', 'awesome!', ); foreach ( $fillers as $f ) { if ( $message === $f || rtrim( $message, '.!' ) === $f ) { return true; } } return false; } /** * Converts a stored HTML bot response to clean plain text for AI context. * * Bot responses are saved as HTML (colours, icons, links, list tags, etc.). * Feeding raw HTML back into the AI messages array wastes tokens and can * confuse the model. This method: * 1. Removes