, 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 /