*/ class A1AI_OpenAI { /** * The data manager instance. * * @since 1.0.0 * @access private * @var A1AI_Data_Manager $data_manager Handles database operations. */ private $data_manager; /** * The conversation manager instance. * * @since 1.4.0 * @access private * @var A1AI_Conversation_Manager $conversation_manager Handles conversation state and guidance. */ private $conversation_manager; /** * Initialize the class and set its properties. * * @since 1.0.0 * @param A1AI_Data_Manager $data_manager The data manager instance. */ public function __construct($data_manager = null) { // If data manager wasn't passed, create one if (null === $data_manager) { require_once plugin_dir_path(dirname(__FILE__)) . 'includes/class-a1ai-data-manager.php'; $this->data_manager = new A1AI_Data_Manager(); } else { $this->data_manager = $data_manager; } // Initialize conversation manager require_once plugin_dir_path(dirname(__FILE__)) . 'includes/class-a1ai-conversation-manager.php'; $this->conversation_manager = new A1AI_Conversation_Manager($this->data_manager); } /** * Process a conversation with OpenAI. * * @since 1.0.0 * @param int $conversation_id The conversation ID. * @param string $message The user message. * @param array $settings The chatbot settings. * @return array The response with success status and message or error. */ public function process_conversation($conversation_id, $message, $settings) { // Get chatbot ID from settings $chatbot_id = isset($settings['chatbot_id']) ? intval($settings['chatbot_id']) : 0; // Add conversation ID to settings for conversation manager $settings['conversation_id'] = $conversation_id; // Check for matching adjustments first (3-pass: Exact > Phrase > Broad) if ($chatbot_id > 0) { $adjustments = $this->data_manager->get_adjustments($chatbot_id); if (!empty($adjustments)) { // Normalize helper: strip apostrophes, punctuation, collapse whitespace $normalize = function($str) { $str = trim(strtolower($str)); $str = str_replace("'", '', $str); $str = preg_replace('/[^\w\s]/u', ' ', $str); $str = preg_replace('/\s+/', ' ', $str); return trim($str); }; $current_normalized = $normalize($message); $matched_adjustment = null; // Pass 1: Exact matches (highest priority) foreach ($adjustments as $adjustment) { if ($adjustment['ui_match_type'] !== 'Exact') { continue; } if ($normalize($adjustment['user_input']) === $current_normalized) { $matched_adjustment = $adjustment; break; } } // Pass 2: Phrase matches if (null === $matched_adjustment) { foreach ($adjustments as $adjustment) { if ($adjustment['ui_match_type'] !== 'Phrase') { continue; } if (strpos($current_normalized, $normalize($adjustment['user_input'])) !== false) { $matched_adjustment = $adjustment; break; } } } // Pass 3: Broad and Default matches (lowest priority, best score wins) if (null === $matched_adjustment) { $best_score = -1; foreach ($adjustments as $adjustment) { if ($adjustment['ui_match_type'] === 'Exact' || $adjustment['ui_match_type'] === 'Phrase') { continue; } $raw_input = $adjustment['user_input']; $adj_normalized = $normalize($raw_input); if ($adjustment['ui_match_type'] === 'Broad') { // Parse +word required modifiers from the raw input $required_words = array(); if (preg_match_all('/\+(\w+)/', $raw_input, $req_matches)) { $required_words = array_map('strtolower', $req_matches[1]); } // Check all required words are present in the user message $user_words = explode(' ', $current_normalized); $all_required_present = true; foreach ($required_words as $req) { if (!in_array($req, $user_words, true)) { $all_required_present = false; break; } } if (!$all_required_present) { continue; } // Strip +markers for word-overlap matching $clean_pattern = preg_replace('/\+/', '', $adj_normalized); $clean_pattern = preg_replace('/\s+/', ' ', trim($clean_pattern)); $pattern_words = explode(' ', $clean_pattern); // Word overlap: count how many pattern words appear in user message $matched_words = 0; foreach ($pattern_words as $pw) { if (in_array($pw, $user_words, true)) { $matched_words++; } } $confidence = count($pattern_words) > 0 ? $matched_words / count($pattern_words) : 0; if ($confidence >= 0.5 && $confidence > $best_score) { $best_score = $confidence; $matched_adjustment = $adjustment; } } else { // Default: contains check (either direction) + levenshtein if (strpos($current_normalized, $adj_normalized) !== false || strpos($adj_normalized, $current_normalized) !== false) { $matched_adjustment = $adjustment; break; } if (strlen($current_normalized) <= 255 && strlen($adj_normalized) <= 255) { $max_length = max(strlen($current_normalized), strlen($adj_normalized)); if ($max_length > 0) { $similarity = 1 - (levenshtein($current_normalized, $adj_normalized) / $max_length); if ($similarity > 0.7 && $similarity > $best_score) { $best_score = $similarity; $matched_adjustment = $adjustment; } } } } } } // Return matched adjustment if found if (null !== $matched_adjustment) { // Log match for observability if (defined('WP_DEBUG') && WP_DEBUG && defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging gated behind WP_DEBUG error_log(sprintf( 'A1AI Adjustment Match: type=%s, input="%s", matched="%s"', $matched_adjustment['ui_match_type'], substr($message, 0, 80), substr($matched_adjustment['user_input'], 0, 80) )); } $this->conversation_manager->update_conversation_state($conversation_id, array( 'last_response_type' => 'adjustment', 'last_updated' => current_time('mysql') )); return array( 'success' => true, 'message' => $matched_adjustment['ai_output'], 'tokens_used' => 0, 'from_adjustment' => true, ); } } } // No adjustment matched, proceed with normal OpenAI request // Get message history for this conversation (capped) $history_limit = isset($settings['message_history_limit']) ? intval($settings['message_history_limit']) : 20; $history_limit = max(4, min($history_limit, 100)); $history = $this->data_manager->get_recent_messages($conversation_id, $history_limit); // Prepare messages for OpenAI $messages = $this->prepare_messages($history, $message, $settings); // Observability: log request details if (defined('WP_DEBUG') && WP_DEBUG && defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) { $prompt_length = 0; foreach ($messages as $m) { $prompt_length += mb_strlen($m['content']); } // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging gated behind WP_DEBUG error_log(sprintf( 'A1AI Request: conversation_id=%d, chatbot_id=%d, message_count=%d, estimated_prompt_tokens=%d, model=%s', $conversation_id, $chatbot_id, count($messages), (int) ceil($prompt_length / 4), isset($settings['model']) ? $settings['model'] : 'default' )); } // Send request to OpenAI $response = $this->send_request($messages, $settings); // Process response if ($response['success']) { $ai_message = $this->extract_message($response['data']); $token_usage = $this->extract_token_usage($response['data']); // Observability: log response details if (defined('WP_DEBUG') && WP_DEBUG && defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging gated behind WP_DEBUG error_log(sprintf( 'A1AI Response: conversation_id=%d, tokens_used=%d, response_length=%d', $conversation_id, $token_usage, mb_strlen($ai_message) )); } // Validate and enhance response if needed $enhanced_response = $this->validate_and_enhance_response($ai_message, $conversation_id, $message, $settings); // Update conversation state $this->conversation_manager->update_conversation_state($conversation_id, array( 'last_response_type' => 'ai', 'last_user_message' => $message, 'last_updated' => current_time('mysql') )); return array( 'success' => true, 'message' => $enhanced_response, 'tokens_used' => $token_usage, ); } else { return array( 'success' => false, 'error' => $response['message'], ); } } /** * Prepare messages for OpenAI API request. * * @since 1.0.0 * @param array $history Previous messages in the conversation. * @param string $message The new user message. * @param array $settings The chatbot settings. * @return array Formatted messages for OpenAI API. */ private function prepare_messages($history, $message, $settings) { $messages = array(); // Get chatbot ID from settings or conversation $chatbot_id = isset($settings['chatbot_id']) ? intval($settings['chatbot_id']) : 0; $conversation_id = isset($settings['conversation_id']) ? intval($settings['conversation_id']) : 0; // Get system prompt from custom instructions table $system_prompt = ''; if ($chatbot_id > 0) { $system_instructions = $this->data_manager->get_custom_instructions($chatbot_id, 'system'); if (!empty($system_instructions) && is_array($system_instructions)) { foreach ($system_instructions as $instruction) { if ($instruction['instruction_name'] === 'System Prompt' && !empty($instruction['instruction_content'])) { $system_prompt = $instruction['instruction_content']; break; } } } } // Get general custom instructions from dedicated table $custom_instructions = ''; if ($chatbot_id > 0) { $instructions_array = $this->data_manager->get_custom_instructions($chatbot_id, 'general'); if (!empty($instructions_array) && is_array($instructions_array)) { $instructions_text = ''; foreach ($instructions_array as $instruction) { if (!empty($instruction['instruction_content'])) { $instructions_text .= $instruction['instruction_content'] . "\n\n"; } } $custom_instructions = trim($instructions_text); } } // Build structured system prompt with clear sections $system_content = ''; // When caller provides system_prompt (e.g. organic contact form), prepend it so it overrides default behavior if ( ! empty( $settings['system_prompt'] ) && is_string( $settings['system_prompt'] ) ) { $system_content .= $settings['system_prompt'] . "\n\n---\n\n"; } // === SECTION 1: ROLE === $system_content .= "## ROLE\n"; if (!empty($system_prompt)) { $system_content .= $system_prompt . "\n\n"; } else { $system_content .= "You are a professional business assistant. Your primary role is to help customers accurately and guide them toward taking action.\n\n"; } if (!empty($custom_instructions)) { $system_content .= $custom_instructions . "\n\n"; } // === SECTION 2: PRIMARY DIRECTIVE === $system_content .= "## PRIMARY DIRECTIVE\n"; $system_content .= "Only use the business information and content provided below; never invent details. Keep responses concise (2-4 sentences) unless the user asks for more detail.\n\n"; // === SECTION 3: BUSINESS INFORMATION === if ($chatbot_id > 0) { $business_info = $this->data_manager->get_business_info($chatbot_id); if (!empty($business_info)) { $system_content .= "## BUSINESS INFORMATION\n"; $system_content .= "You are an AI assistant for " . (!empty($business_info['business_name']) ? $business_info['business_name'] : 'this business') . ".\n\n"; if (!empty($business_info['tagline'])) { $system_content .= "About: " . $business_info['tagline'] . "\n\n"; } else { $system_content .= "No business description was provided. When asked what the business does, do not use placeholder text in square brackets (e.g. [brief description of the business] or [company name]). Never output square brackets with placeholder instructions inside. Say you don't have a description on file and suggest exploring the website or contacting the business directly.\n\n"; } if (!empty($business_info['business_type'])) { $system_content .= "Business Type: " . ucfirst($business_info['business_type']) . "\n\n"; } if (!empty($business_info['services'])) { $services = json_decode($business_info['services'], true); if (!empty($services) && is_array($services)) { $system_content .= "Services Offered:\n"; foreach ($services as $service) { $system_content .= "- " . $service . "\n"; } $system_content .= "\n"; } } if (!empty($business_info['products'])) { $products = json_decode($business_info['products'], true); if (!empty($products) && is_array($products)) { $system_content .= "Products Available:\n"; foreach ($products as $product) { $system_content .= "- " . $product . "\n"; } $system_content .= "\n"; } } if (!empty($business_info['hours'])) { $hours = json_decode($business_info['hours'], true); if (!empty($hours) && is_array($hours)) { $system_content .= "Business Hours:\n"; foreach ($hours as $day => $time) { if (!empty($time)) { $system_content .= ucfirst($day) . ": " . $time . "\n"; } } $system_content .= "\n"; } } $has_contact = false; if (!empty($business_info['address']) || !empty($business_info['phone']) || !empty($business_info['email'])) { $system_content .= "Contact Information:\n"; if (!empty($business_info['address'])) { $system_content .= "Address: " . str_replace("\n", ", ", $business_info['address']) . "\n"; $has_contact = true; } if (!empty($business_info['phone'])) { $system_content .= "Phone: " . $business_info['phone'] . "\n"; $has_contact = true; } if (!empty($business_info['email'])) { $system_content .= "Email: " . $business_info['email'] . "\n"; $has_contact = true; } if (!empty($business_info['website'])) { $system_content .= "Website: " . $business_info['website'] . "\n"; $has_contact = true; } if ($has_contact) { $system_content .= "\n"; } } if (!empty($business_info['policies'])) { $system_content .= "Important Policies & Information:\n"; $system_content .= $business_info['policies'] . "\n\n"; } } } // === SECTION 4: RULES === $system_content .= "## RULES\n"; if ($conversation_id > 0 && !empty($history) && count($history) > 2) { $system_content .= "- This is an ongoing conversation. Maintain context and continuity. Do not restart or repeat greetings.\n"; } $system_content .= "- Respond naturally and directly to the user's question.\n"; $system_content .= "- Only provide information based on the business information above.\n"; $system_content .= "- If asked about something not listed, politely say you don't have that specific information and suggest contacting the business directly.\n"; $system_content .= "- Do not repeat links you have already provided in this conversation.\n"; $system_content .= "- If the user is already on a specific page, do not suggest they visit that same page.\n"; $system_content .= "- Never include placeholder text in square brackets (e.g. [brief description of the business] or [company name]) in your replies. Use only real information from the context above or say you don't have that information.\n"; // CTA instruction from chatbot settings (Improvement 4a) $primary_action = isset($settings['primary_action']) ? $settings['primary_action'] : ''; if (!empty($primary_action)) { $system_content .= "- When the user seems interested, naturally guide them toward: " . $primary_action . "\n"; } $system_content .= "\n"; // === SECTION 5: WEBSITE CONTENT === $content_awareness_context = $this->get_content_awareness_context($message, $chatbot_id); if (!empty($content_awareness_context)) { $system_content .= "## WEBSITE CONTENT\n"; $system_content .= $content_awareness_context . "\n\n"; } // === SECTION 6: PAGE CONTEXT === $current_url = isset($settings['_current_url']) ? $settings['_current_url'] : ''; $page_title = isset($settings['_page_title']) ? $settings['_page_title'] : ''; if (!empty($current_url)) { $system_content .= "## PAGE CONTEXT\n"; $system_content .= "The user is currently viewing: " . esc_html($page_title) . " (" . esc_url($current_url) . ")\n"; $system_content .= "Do NOT suggest links to the page the user is already on.\n"; $system_content .= "If the user asks about content on this page, answer directly instead of sending them a link.\n\n"; } // === SECTION 7: ACCURACY === $system_content .= "## ACCURACY\n"; $system_content .= "- Only state facts you are confident are accurate.\n"; $system_content .= "- Never fabricate prices, availability, hours, or policies.\n"; $system_content .= "- When uncertain, say so and suggest contacting the business directly.\n"; $system_content .= "- Be transparent about your limitations.\n\n"; // Add system message if (!empty($system_content)) { $messages[] = array( 'role' => 'system', 'content' => sanitize_textarea_field($system_content), ); } else { // Default system message (business-focused with accuracy emphasis) $default_message = "You are a professional business assistant. Your role is to help customers by:\n\n"; $default_message .= "1. ACCURACY FIRST\n"; $default_message .= " - Only state facts you know to be true\n"; $default_message .= " - If unsure, say 'I don't have that specific information. Please contact us directly.'\n"; $default_message .= " - Never guess prices, availability, hours, or specific business details\n\n"; $default_message .= "2. HELPFUL GUIDANCE\n"; $default_message .= " - Answer general questions professionally\n"; $default_message .= " - Direct customers to contact methods for detailed inquiries\n"; $default_message .= " - Be friendly, concise, and clear\n\n"; $default_message .= "3. LEAD GENERATION\n"; $default_message .= " - When customers show interest, offer to help them connect\n"; $default_message .= " - Suggest contacting the business for quotes or appointments\n"; $default_message .= " - Be proactive but respectful\n\n"; $default_message .= "Remember: It's better to say 'I don't know' than provide incorrect information."; $messages[] = array( 'role' => 'system', 'content' => $default_message, ); } // Add initial messages if provided if (!empty($settings['initial_messages']) && is_array($settings['initial_messages'])) { foreach ($settings['initial_messages'] as $initial_message) { if (!empty($initial_message['role']) && !empty($initial_message['content'])) { $messages[] = array( 'role' => sanitize_text_field($initial_message['role']), 'content' => sanitize_textarea_field($initial_message['content']), ); } } } // Add conversation history with token budget if (!empty($history) && is_array($history)) { $token_budget = 8000; $estimated_tokens_used = 0; $budgeted_history = array(); // Walk from newest to oldest, accumulating until budget is reached $reversed = array_reverse($history); foreach ($reversed as $msg) { $msg_tokens = (int) ceil(mb_strlen($msg['content']) / 4); if ($estimated_tokens_used + $msg_tokens > $token_budget && !empty($budgeted_history)) { break; } $estimated_tokens_used += $msg_tokens; array_unshift($budgeted_history, $msg); } foreach ($budgeted_history as $msg) { $messages[] = array( 'role' => sanitize_text_field($msg['role']), 'content' => $msg['content'], ); } } // Add current user message $messages[] = array( 'role' => 'user', 'content' => $message, ); return $messages; } /** * Send request to OpenAI API. * * @since 1.0.0 * @param array $messages The formatted messages. * @param array $settings The API settings. * @return array The response with success status and data or error message. */ private function send_request($messages, $settings) { // Get API key from settings $api_key = get_option('a1ai_openai_api_key', ''); if (empty($api_key)) { return array( 'success' => false, 'message' => esc_html__('OpenAI API key is not configured.', 'a1ai-chatbot'), ); } // Default settings from global options $defaults = array( 'model' => get_option('a1ai_default_model', 'gpt-4o'), 'temperature' => (float) get_option('a1ai_default_temperature', 0.5), 'max_tokens' => (int) get_option('a1ai_default_max_tokens', 1000), ); // Merge with provided settings $api_settings = wp_parse_args( array( 'model' => isset($settings['model']) ? sanitize_text_field($settings['model']) : $defaults['model'], 'temperature' => isset($settings['temperature']) ? (float) $settings['temperature'] : $defaults['temperature'], 'max_tokens' => isset($settings['max_tokens']) ? (int) $settings['max_tokens'] : $defaults['max_tokens'], ), $defaults ); // Prepare request data $request_data = array( 'model' => $api_settings['model'], 'messages' => $messages, 'temperature' => $api_settings['temperature'], 'max_tokens' => $api_settings['max_tokens'], ); // Prepare HTTP request $args = array( 'headers' => array( 'Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json', ), 'timeout' => 60, 'body' => wp_json_encode($request_data), ); // Send request to OpenAI with single retry on 5xx/timeout $max_retries = 1; $attempt = 0; $response = null; while ($attempt <= $max_retries) { $attempt++; $response = wp_remote_post('https://api.openai.com/v1/chat/completions', $args); // Check for WP_Error (network/timeout) if (is_wp_error($response)) { if ($attempt <= $max_retries) { if (defined('WP_DEBUG') && WP_DEBUG && defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging gated behind WP_DEBUG error_log('A1AI: API request failed (attempt ' . $attempt . '): ' . $response->get_error_message() . '. Retrying...'); } usleep(500000); // 500ms delay before retry continue; } return array( 'success' => false, 'message' => esc_html__('I\'m having trouble connecting right now. Please try again in a moment.', 'a1ai-chatbot'), ); } // Check for 5xx server errors (retryable) $response_code = wp_remote_retrieve_response_code($response); if ($response_code >= 500 && $attempt <= $max_retries) { if (defined('WP_DEBUG') && WP_DEBUG && defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging gated behind WP_DEBUG error_log('A1AI: API returned ' . $response_code . ' (attempt ' . $attempt . '). Retrying...'); } usleep(500000); continue; } break; // Success or non-retryable error } // Parse response $response_code = wp_remote_retrieve_response_code($response); $body = wp_remote_retrieve_body($response); $data = json_decode($body, true); // Check if response is successful if (200 !== $response_code) { $error_message = isset($data['error']['message']) ? sanitize_text_field($data['error']['message']) : esc_html__('Unknown error occurred.', 'a1ai-chatbot'); if (defined('WP_DEBUG') && WP_DEBUG && defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging gated behind WP_DEBUG error_log('A1AI: API error after ' . $attempt . ' attempt(s): [' . $response_code . '] ' . $error_message); } return array( 'success' => false, 'message' => $error_message, 'code' => $response_code, ); } // Return success with data return array( 'success' => true, 'data' => $data, ); } /** * Extract message from OpenAI response. * * @since 1.0.0 * @param array $data The response data. * @return string The extracted message content. */ private function extract_message($data) { if (isset($data['choices'][0]['message']['content'])) { return $data['choices'][0]['message']['content']; } return esc_html__('No response generated.', 'a1ai-chatbot'); } /** * Extract token usage from OpenAI response. * * @since 1.0.0 * @param array $data The response data. * @return int The total token usage or 0 if not available. */ private function extract_token_usage($data) { if (isset($data['usage']['total_tokens'])) { return (int) $data['usage']['total_tokens']; } return 0; } /** * Remove square-bracket placeholder text (e.g. [brief description of the business]) from AI output. * * @since 1.0.0 * @param string $text The message text. * @return string The text with placeholder brackets removed and spaces normalized. */ private function strip_square_bracket_placeholders( $text ) { if ( ! is_string( $text ) || $text === '' ) { return $text; } $cleaned = preg_replace( '/\s*\[[^\]]+\]\s*/u', ' ', $text ); $cleaned = preg_replace( '/\s{2,}/u', ' ', $cleaned ); return trim( $cleaned ); } /** * Validate and enhance AI response based on conversation state. * * @since 1.4.0 * @param string $ai_message The AI response message. * @param int $conversation_id The conversation ID. * @param string $user_message The user message. * @param array $settings The chatbot settings. * @return string The enhanced response. */ private function validate_and_enhance_response($ai_message, $conversation_id, $user_message, $settings) { $ai_message = $this->strip_square_bracket_placeholders( $ai_message ); $enhanced_message = $ai_message; // Organic contact form: do not append "To move our conversation forward" or call-to-action suggestions if ( ! empty( $settings['organic_contact_form'] ) ) { return $ai_message; } // Check for repetitive content - only append suggestions when also short if ($this->conversation_manager->is_repetitive_content($conversation_id, $ai_message)) { $word_count = str_word_count($ai_message); if (defined('WP_DEBUG') && WP_DEBUG && defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging gated behind WP_DEBUG error_log(sprintf( 'A1AI Repetition Detected: conversation_id=%d, word_count=%d', $conversation_id, $word_count )); } // Only append boilerplate suggestions when the reply is repetitive AND short if ($word_count < 80) { $suggested_actions = $this->get_business_aware_suggestions($conversation_id, $settings); if (!empty($suggested_actions)) { $enhanced_message .= "\n\nTo move our conversation forward, I'd be happy to help you with:"; foreach (array_slice($suggested_actions, 0, 3) as $action) { $enhanced_message .= "\n- " . $action; } } } } // Check if response includes action guidance $state = $this->conversation_manager->get_conversation_state($conversation_id); if ($state['conversation_stage'] === 'action' && !$this->contains_action_guidance($ai_message)) { $enhanced_message = $this->add_action_guidance($enhanced_message, $settings); } return $enhanced_message; } /** * Get suggested actions tied to actual business information. * * @since 1.6.0 * @param int $conversation_id The conversation ID. * @param array $settings The chatbot settings. * @return array Array of suggested actions. */ private function get_business_aware_suggestions($conversation_id, $settings) { $chatbot_id = isset($settings['chatbot_id']) ? intval($settings['chatbot_id']) : 0; $suggestions = array(); if ($chatbot_id > 0) { $business_info = $this->data_manager->get_business_info($chatbot_id); if (!empty($business_info)) { if (!empty($business_info['services'])) { $services = json_decode($business_info['services'], true); if (!empty($services) && is_array($services)) { $suggestions[] = 'Learn more about our services: ' . implode(', ', array_slice($services, 0, 3)); } } if (!empty($business_info['phone']) || !empty($business_info['email'])) { $contact_parts = array(); if (!empty($business_info['phone'])) { $contact_parts[] = 'call ' . $business_info['phone']; } if (!empty($business_info['email'])) { $contact_parts[] = 'email ' . $business_info['email']; } $suggestions[] = 'Get in touch: ' . implode(' or ', $contact_parts); } if (!empty($business_info['website'])) { $suggestions[] = 'Visit our website for more details: ' . $business_info['website']; } } } // Fallback to generic suggestions if no business info if (empty($suggestions)) { $suggestions = $this->conversation_manager->get_suggested_actions($conversation_id, $chatbot_id); } return $suggestions; } /** * Check if user message is a pricing-related query * * @since 1.5.6 * @param string $message The user message * @return bool True if pricing-related, false otherwise */ private function is_pricing_query($message) { $pricing_keywords = array( 'price', 'pricing', 'prices', 'cost', 'costs', 'costing', 'fee', 'fees', 'rate', 'rates', 'how much', 'how much does', 'how much do', 'what does it cost', 'what do they cost', 'afford', 'affordable', 'affordability', 'charge', 'charges', 'charging', 'pay', 'payment', 'payments', 'subscription', 'subscriptions', 'plan', 'plans', 'package', 'packages', 'tier', 'tiers', 'pricing tier' ); $message_lower = strtolower($message); foreach ($pricing_keywords as $keyword) { if (strpos($message_lower, $keyword) !== false) { return true; } } return false; } /** * Get Content Awareness context for the user message * * @since 1.5.6 * @param string $message The user message * @param int $chatbot_id The chatbot ID * @return string Formatted context string or empty if not available */ private function get_content_awareness_context($message, $chatbot_id) { // Check Premium first - if available and enabled, use full Content Awareness if (class_exists('A1AI_Content_Awareness_Manager') && class_exists('A1AI_Upgrade_Settings_Manager')) { $settings_manager = new A1AI_Upgrade_Settings_Manager(); if ($settings_manager->is_feature_enabled('content_awareness')) { // Use full Content Awareness system (Premium) $content_manager = new A1AI_Content_Awareness_Manager(); // Check if this is a pricing query $is_pricing = $this->is_pricing_query($message); // Search for relevant content $search_results = array(); if ($is_pricing) { // Search specifically for pricing content (uses tier2 table when Tier 2 is enabled) $search_results = $content_manager->search_content_with_pricing($message, 5); } else { // General content search (uses appropriate tier table based on settings) $search_results = $content_manager->get_content_suggestions($message, 3); } // Ensure all results have permalinks for clickable links foreach ($search_results as &$result) { $post_id = isset($result->ID) ? $result->ID : (isset($result->post_id) ? $result->post_id : 0); if ($post_id > 0 && !isset($result->permalink)) { $result->permalink = get_permalink($post_id); } if ($post_id > 0 && !isset($result->post_title) && isset($result->title)) { $result->post_title = $result->title; } } unset($result); // Break reference if (empty($search_results)) { return ''; } // Format the context if ($is_pricing) { return $this->format_pricing_context($search_results, $content_manager); } else { return $this->format_general_content_context($search_results); } } } // Fallback to basic WordPress search (Free version) return $this->get_basic_content_context($message, $chatbot_id); } /** * Get basic content context using WordPress native search (Free version) * * @since 1.5.6 * @param string $message The user message * @param int $chatbot_id The chatbot ID * @return string Formatted context string or empty if not available */ private function get_basic_content_context($message, $chatbot_id) { // Load basic content search class if not already loaded if (!class_exists('A1AI_Content_Search')) { $search_file = plugin_dir_path(dirname(__FILE__)) . 'includes/class-a1ai-content-search.php'; if (file_exists($search_file)) { require_once $search_file; } else { return ''; } } // Initialize basic content search $content_search = new A1AI_Content_Search(); // Check if this is a pricing query $is_pricing = $content_search->is_pricing_query($message); // Search for relevant content $search_results = $content_search->get_content_suggestions($message, $is_pricing ? 5 : 3); if (empty($search_results)) { return ''; } // Format the context using basic search formatter return $content_search->format_results_for_prompt($search_results, $is_pricing); } /** * Format pricing context for AI prompt * * @since 1.5.6 * @param array $content_results Search results with pricing information * @param A1AI_Content_Awareness_Manager $content_manager Content Awareness Manager instance * @return string Formatted pricing context */ private function format_pricing_context($content_results, $content_manager = null) { $context = "PRICING INFORMATION FROM WEBSITE:\n\n"; $max_content_length = 3000; $current_length = strlen($context); foreach ($content_results as $result) { $post_id = isset($result->ID) ? $result->ID : (isset($result->post_id) ? $result->post_id : 0); $title = isset($result->post_title) ? $result->post_title : (isset($result->title) ? $result->title : ''); $permalink = $post_id > 0 ? get_permalink($post_id) : ''; if (empty($title) || empty($permalink)) { continue; } $entry = "[" . esc_html($title) . "](" . esc_url($permalink) . ")\n"; // Get pricing information $pricing_info = null; if (isset($result->pricing_info) && !empty($result->pricing_info)) { $pricing_info = json_decode($result->pricing_info, true); } elseif ($post_id > 0 && $content_manager) { $pricing_info = $content_manager->get_pricing_from_content($post_id); } if (!empty($pricing_info) && is_array($pricing_info)) { if (!empty($pricing_info['has_pricing'])) { if (!empty($pricing_info['price_ranges']['min']) && !empty($pricing_info['price_ranges']['max'])) { $min = number_format($pricing_info['price_ranges']['min'], 2); $max = number_format($pricing_info['price_ranges']['max'], 2); if ($min == $max) { $entry .= "Price: $" . $min . "\n"; } else { $entry .= "Price Range: $" . $min . " - $" . $max . "\n"; } } elseif (!empty($pricing_info['price_ranges']['min'])) { $entry .= "Starting at: $" . number_format($pricing_info['price_ranges']['min'], 2) . "\n"; } if (!empty($pricing_info['prices']) && is_array($pricing_info['prices'])) { $entry .= "Pricing Details:\n"; foreach ($pricing_info['prices'] as $price_item) { if (!empty($price_item['amount'])) { $amount = number_format($price_item['amount'], 2); $currency = !empty($price_item['currency']) ? $price_item['currency'] : 'USD'; $context_item = "- $" . $amount . " " . $currency; if (!empty($price_item['context'])) { $context_item .= " (" . $price_item['context'] . ")"; } if (!empty($price_item['pricing_model'])) { $model = ucfirst(str_replace('_', ' ', $price_item['pricing_model'])); $context_item .= " - " . $model; } $entry .= $context_item . "\n"; } } } if (!empty($pricing_info['pricing_note'])) { $entry .= "Pricing Note: " . $pricing_info['pricing_note'] . "\n"; } elseif (!empty($pricing_info['pricing_model'])) { $model = ucfirst(str_replace('_', ' ', $pricing_info['pricing_model'])); $entry .= "Pricing Model: " . $model . "\n"; } if (!empty($pricing_info['has_free_tier'])) { $entry .= "Note: Free tier available\n"; } if (!empty($pricing_info['has_discounts'])) { $entry .= "Note: Discounts may be available\n"; } } } if (!empty($result->summary)) { $summary = wp_trim_words($result->summary, 60); $entry .= "Summary: " . $summary . "\n"; } $entry .= "\n"; // Check length cap before adding this entry if ($current_length + strlen($entry) > $max_content_length) { break; } $context .= $entry; $current_length += strlen($entry); } $context .= "PRICING RESPONSE GUIDELINES:\n"; $context .= "- Always reference the specific pages listed above and include clickable links in markdown format: [Page Title](URL)\n"; $context .= "- If specific dollar amounts are shown, state them clearly (e.g., \"Starting at \$199\")\n"; $context .= "- If pricing is listed as custom or requires a quote, tell the user to contact the business and link to the relevant page\n"; $context .= "- If multiple pricing options exist, list them clearly\n"; $context .= "- NEVER say you don't have pricing information if pages about this topic are listed above — always reference them\n"; return $context; } /** * Format general content context for AI prompt * * @since 1.5.6 * @param array $content_results Search results * @return string Formatted content context */ private function format_general_content_context($content_results) { $context = "RELEVANT CONTENT FROM WEBSITE:\n\n"; $max_content_length = 2000; $current_length = strlen($context); foreach ($content_results as $result) { $post_id = isset($result->ID) ? $result->ID : (isset($result->post_id) ? $result->post_id : 0); $title = isset($result->post_title) ? $result->post_title : (isset($result->title) ? $result->title : ''); $permalink = $post_id > 0 ? get_permalink($post_id) : ''; $summary = isset($result->summary) ? $result->summary : ''; if (empty($title) || empty($permalink)) { continue; } $entry = "[" . esc_html($title) . "](" . esc_url($permalink) . ")\n"; if (!empty($summary)) { $entry .= wp_trim_words($summary, 60) . "\n"; } $entry .= "\n"; if ($current_length + strlen($entry) > $max_content_length) { break; } $context .= $entry; $current_length += strlen($entry); } return $context; } /** * Check if response contains action guidance. * * @since 1.4.0 * @param string $message The message to check. * @return bool True if contains action guidance. */ private function contains_action_guidance($message) { $action_keywords = array( // Contact-related 'contact', 'call', 'email', 'reach out', 'get in touch', 'phone', 'message us', // Purchase-related 'purchase', 'buy', 'order', 'sign up', 'subscribe', 'enroll', 'register', // Scheduling-related 'schedule', 'book', 'appointment', 'consultation', 'reserve', // Discovery-related 'learn more', 'find out', 'discover', 'explore', 'visit', // CTA indicators 'click here', 'book now', 'get started', 'try now', 'view our', 'check out', 'see our', // URL patterns 'http://', 'https://', ); $message_lower = strtolower($message); foreach ($action_keywords as $keyword) { if (strpos($message_lower, $keyword) !== false) { return true; } } return false; } /** * Add action guidance to response. * * @since 1.4.0 * @param string $message The original message. * @param array $settings The chatbot settings. * @return string The message with action guidance. */ private function add_action_guidance($message, $settings) { // First check primary_action from chatbot settings (most specific) $primary_action = isset($settings['primary_action']) ? trim($settings['primary_action']) : ''; if (!empty($primary_action)) { $message .= "\n\n" . $primary_action; return $message; } // Fallback: scan custom instructions for CTA content $chatbot_id = isset($settings['chatbot_id']) ? intval($settings['chatbot_id']) : 0; $custom_instructions = $this->data_manager->get_custom_instructions($chatbot_id, 'general'); $action_guidance = ''; foreach ($custom_instructions as $instruction) { if (strpos(strtolower($instruction['instruction_content']), 'call to action') !== false || strpos(strtolower($instruction['instruction_content']), 'next step') !== false) { $action_guidance = $instruction['instruction_content']; break; } } if (!empty($action_guidance)) { $message .= "\n\n" . $action_guidance; } else { $message .= "\n\nHow can I help you take the next step? Would you like to learn more about our services or get in touch?"; } return $message; } }