<?php
/**
 * API Manager class for handling AI API interactions.
 *
 * This class manages the communication with different AI providers (OpenAI and DeepSeek),
 * handles API responses, and manages plugin settings.
 *
 * @package Askany
 * @since 1.0.0
 */
namespace Askany;

use ask\askany\wpnts_nts_fs;
use Askany\Providers\ProviderFactory;

/**
 * API Manager class for handling AI API interactions.
 *
 * @package Askany
 * @since 1.0.0
 */
class ApiManager {
	/**
	 * Database instance for content indexing and retrieval.
	 *
	 * @var Database
	 */
	private $database;
	/**
	 * Selected API provider (openai or deepseek).
	 *
	 * @var string
	 */
	private $api_provider;
	/**
	 * DeepSeek API key.
	 *
	 * @var string
	 */
	private $api_key_deepseek;
	/**
	 * OpenAI API key.
	 *
	 * @var string
	 */
	private $api_key_openai;
	/**
	 * Gemini API key.
	 *
	 * @var string
	 */
	private $api_key_gemini;
	/**
	 * Claude API key.
	 *
	 * @var string
	 */
	private $api_key_claude;
	/**
	 * Grok API key.
	 *
	 * @var string
	 */
	private $api_key_grok;
	/**
	 * OpenRouter API key.
	 *
	 * @var string
	 */
	private $api_key_openrouter;
	/**
	 * DeepSeek API URL.
	 *
	 * @var string
	 */
	private $api_url_deepseek;
	/**
	 * OpenAI API URL.
	 *
	 * @var string
	 */
	private $api_url_openai;
	/**
	 * Gemini API URL.
	 *
	 * @var string
	 */
	private $api_url_gemini;
	/**
	 * Claude API URL.
	 *
	 * @var string
	 */
	private $api_url_claude;
	/**
	 * Grok API URL.
	 *
	 * @var string
	 */
	private $api_url_grok;
	/**
	 * OpenRouter API URL.
	 *
	 * @var string
	 */
	private $api_url_openrouter;
	/**
	 * Selected AI model.
	 *
	 * @var string
	 */
	private $api_model;
	/**
	 * Whether the API is enabled.
	 *
	 * @var bool
	 */
	private $api_enabled;
	/**
	 * Whether fallback mode is enabled.
	 *
	 * @var bool
	 */
	private $fallback_enabled;
	/**
	 * Whether floating widget is enabled.
	 *
	 * @var bool
	 */
	private $floating_widget_enabled;
	/**
	 * Widget position setting.
	 *
	 * @var string
	 */
	private $widget_position;
	/**
	 * Chat header text.
	 *
	 * @var string
	 */
	private $chat_header_text;
	/**
	 * Assistant avatar URL.
	 *
	 * @var string
	 */
	private $assistant_avatar;

	/**
	 * Whether contact form is enabled.
	 *
	 * @var bool
	 */
	private $contact_form_enabled;

	/**
	 * Contact form shortcode.
	 *
	 * @var string
	 */
	private $contact_form_shortcode;

	/**
	 * Response language setting.
	 *
	 * @var string
	 */
	private $response_language;

	/**
	 * Constructor for ApiManager.
	 *
	 * Initializes the database connection and loads settings.
	 */
	public function __construct() {
		$this->database = new Database();
		$this->load_settings();
	}

	/**
	 * Initialize the API Manager.
	 *
	 * @return void
	 */
	public function init() {
		// No initialization needed as settings are loaded in constructor.
		return;
	}

	/**
	 * Load settings from the database.
	 *
	 * This method retrieves the API provider, keys, URLs, and other settings
	 * from the WordPress options table.
	 *
	 * @return void
	 */
	private function load_settings() {
		$this->api_provider = get_option('askany_api_provider', 'deepseek');
		$this->api_key_deepseek = get_option('askany_api_key_deepseek', '');
		$this->api_key_openai = get_option('askany_api_key_openai', '');
		$this->api_key_gemini = get_option('askany_api_key_gemini', '');
		$this->api_key_claude = get_option('askany_api_key_claude', '');
		$this->api_key_grok = get_option('askany_api_key_grok', '');
		$this->api_key_openrouter = get_option('askany_api_key_openrouter', '');
		$this->api_url_deepseek = get_option('askany_api_url_deepseek', 'https://api.deepseek.com/v1/chat/completions');
		$this->api_url_openai = get_option('askany_api_url_openai', 'https://api.openai.com/v1/chat/completions');
		$this->api_url_gemini = get_option('askany_api_url_gemini', 'https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent');
		$this->api_url_claude = get_option('askany_api_url_claude', 'https://api.anthropic.com/v1/messages');
		$this->api_url_grok = get_option('askany_api_url_grok', 'https://api.x.ai/v1/chat/completions');
		$this->api_url_openrouter = get_option('askany_api_url_openrouter', 'https://openrouter.ai/api/v1/chat/completions');
		$this->api_model = get_option('askany_api_model', '');
		$this->api_enabled = get_option('askany_api_enabled', false);
		$this->fallback_enabled = get_option('askany_fallback_enabled', true);
		$this->floating_widget_enabled = get_option('askany_floating_widget_enabled', false);
		$this->widget_position = get_option('askany_widget_position', 'bottom-right');
		$this->chat_header_text = get_option('askany_chat_header_text', 'Ask Me Anything');
		$this->assistant_avatar = get_option('askany_assistant_avatar', '');

		$this->contact_form_enabled = get_option('askany_contact_form_enabled', false);
		$this->contact_form_shortcode = get_option('askany_contact_form_shortcode', '');
		$this->response_language = get_option('askany_response_language', 'auto');
	}

	/**
	 * Get the response from the API or fallback.
	 *
	 * @param string $query The user query.
	 * @param string $session_id Optional session ID for tracking.
	 * @return array|false The response data or false on failure.
	 */
	public function get_fallback_response_public( $query ) {
		return $this->get_fallback_response( $query );
	}

	public function get_response( $query, $session_id = '' ) {
		$start_time = microtime(true);
		$user_id = get_current_user_id();

		// Check for WooCommerce order tracking first
		$plugin = \Askany\Plugin::get_instance();
		$woocommerce_handler = $plugin->get_woocommerce_handler();
		
		if ( $woocommerce_handler && $woocommerce_handler->is_order_tracking_enabled() ) {
			$order_response = $woocommerce_handler->handle_order_query( $query, $session_id );
			
			if ( $order_response && ! empty( $order_response['is_order_request'] ) ) {
				// Log order tracking request
				$response_time = microtime(true) - $start_time;
				$this->database->log_api_stats(
					'chat',
					'woocommerce',
					'success',
					$response_time,
					'Order tracking request handled',
					$query,
					$session_id,
					$user_id ?: null
				);
				
				return array(
					'message' => $order_response['message'],
					'related_products' => array(),
					'session_id' => $session_id,
				);
			}
		}

		// If API is disabled, use fallback but log as API disabled (not failure)
		if ( ! $this->api_enabled ) {
			$response = $this->get_fallback_response($query);
			$response_time = microtime(true) - $start_time;
			
			// Log as API disabled (separate from API failure)
			$this->database->log_api_stats(
				'chat',
				'fallback',
				'api_disabled',
				$response_time,
				'API is disabled in settings',
				$query,
				$session_id,
				$user_id ?: null
			);
			
			return $response;
		}

		// Try to get AI response
		$web_settings       = $this->get_settings();
		$web_search_enabled = ! empty( $web_settings['web_search_enabled'] );
		$web_search_mode    = $web_search_enabled ? ( $web_settings['web_search_mode'] ?? 'fallback' ) : '';

		$response = $this->get_ai_response( $query, $session_id, $web_search_mode );
		if ( $response ) {
			return array(
				'message'          => $response['text'],
				'related_products' => $response['related_products'],
				'session_id'       => $session_id,
			);
		}

		// AI API failed - log the actual API failure first
		$response_time = microtime(true) - $start_time;
		$this->database->log_api_stats(
			'chat',
			$this->api_provider,
			'api_failed',
			$response_time,
			'API request failed, attempting fallback',
			$query,
			$session_id,
			$user_id ?: null
		);

		// If fallback is enabled, use it but log as fallback usage due to API failure
		if ( $this->fallback_enabled ) {
			$fallback_start_time = microtime(true);
			$fallback = $this->get_fallback_response($query);
			$fallback_response_time = microtime(true) - $fallback_start_time;
			
			// Log fallback usage as a separate entry (not as success)
			$this->database->log_api_stats(
				'chat',
				'fallback',
				'fallback_used',
				$fallback_response_time,
				'Fallback used due to API failure',
				$query,
				$session_id,
				$user_id ?: null
			);
			
			return array(
				'message' => $fallback['text'],
				'related_products' => $fallback['related_products'],
				'session_id' => $session_id,
			);
		}

		// Complete failure - API failed and fallback disabled
		$this->database->log_api_stats(
			'chat',
			$this->api_provider,
			'complete_failure',
			$response_time,
			'API failed and fallback is disabled',
			$query,
			$session_id,
			$user_id ?: null
		);

		return false;
	}

	/**
	 * Get the current AI provider instance.
	 *
	 * @return \Askany\Providers\AIProviderInterface|null Provider instance or null if not configured.
	 */
	private function get_provider() {
		$api_key = '';

		switch ( $this->api_provider ) {
			case 'openai':
				$api_key = $this->api_key_openai;
				break;
			case 'deepseek':
				$api_key = $this->api_key_deepseek;
				break;
			case 'gemini':
				$api_key = $this->api_key_gemini;
				break;
			case 'claude':
				$api_key = $this->api_key_claude;
				break;
			case 'grok':
				$api_key = $this->api_key_grok;
				break;
			case 'openrouter':
				$api_key = $this->api_key_openrouter;
				break;
		}

		if ( empty( $api_key ) ) {
			return null;
		}

		// Always pass empty URL - providers will use their defaults
		return ProviderFactory::create( $this->api_provider, $api_key, '' );
	}

	/**
	 * Get the AI response based on the selected provider.
	 *
	 * @param string $query The user query.
	 * @param string $session_id Optional session ID for tracking.
	 * @return array|false The response data or false on failure.
	 */
	private function get_ai_response( $query, $session_id = '', $web_search_mode = '' ) {
		// First check for custom Q&A pairs.
		$qa_pair = $this->database->find_qa_match($query);

		// If we have a direct match, return it immediately.
		if ( $qa_pair ) {
			return array(
				'text' => $qa_pair->answer,
				'related_products' => $this->is_product_query($query) ? $this->get_enhanced_product_context($query) : array(),
				'session_id' => $session_id,
				'source' => 'qa_pair',
			);
		}

		// Get conversation history for context
		$conversation_history = $this->get_conversation_history($session_id);

		// When web search is enabled, strip any previous AI responses that contain
		// limitation phrases — the AI anchors to its own history and ignores the
		// new system prompt instructions if it sees itself saying "I can only help
		// with our products" in a prior turn.
		if ( ! empty( $web_search_mode ) && ! empty( $conversation_history ) ) {
			$limitation_phrases = array(
				"i can only help",
				"i'm only able to",
				"i cannot browse",
				"i can't browse",
				"my purpose is to provide information based on",
				"i don't have access to",
				"i couldn't find any specific information",
				"my current knowledge base is focused",
				"i've reviewed the website content",
				"i still couldn't find",
			);
			$conversation_history = array_filter( $conversation_history, function( $msg ) use ( $limitation_phrases ) {
				if ( $msg['role'] !== 'assistant' ) {
					return true; // always keep user messages
				}
				$lower = strtolower( $msg['content'] );
				foreach ( $limitation_phrases as $phrase ) {
					if ( strpos( $lower, $phrase ) !== false ) {
						return false; // drop this AI response from history
					}
				}
				return true;
			} );
			$conversation_history = array_values( $conversation_history );
		}
		
		// Get relevant content using RAG if enabled, otherwise use keyword search
		$rag_enabled = get_option( 'askany_rag_enabled', false );
		$hybrid_enabled = get_option( 'askany_hybrid_search_enabled', false );
		
		if ( $rag_enabled && $hybrid_enabled ) {
			// Hybrid mode: Combine semantic + keyword search for best results
			$semantic_results = $this->database->get_relevant_content_rag( $query, $this, array(
				'top_k' => 3,
				'threshold' => 0.7,
			) );
			
			$keyword_results = $this->database->get_relevant_content( $query );
			
			// Merge results (semantic results take priority)
			$relevant_content = $this->merge_search_results( $semantic_results, $keyword_results );
			
		} elseif ( $rag_enabled ) {
			// Semantic only: Use RAG (embeddings)
			$relevant_content = $this->database->get_relevant_content_rag( $query, $this, array(
				'top_k' => 5,
				'threshold' => 0.7,
			) );
		} else {
			// Keyword only: Use traditional keyword search
			$relevant_content = $this->database->get_relevant_content( $query );
		}
		
		$product_context = $this->is_product_query($query) ? $this->get_enhanced_product_context($query) : array();

		// Build comprehensive system message with context
		$system_message = $this->build_enhanced_system_message($relevant_content, $product_context, $conversation_history, $web_search_mode);

		// Use new provider architecture
		$provider = $this->get_provider();
		if ( ! $provider ) {
			return false;
		}

		return $this->get_provider_response( $provider, $query, $system_message, $session_id, $conversation_history, $product_context );
	}

	/**
	 * Merge semantic and keyword search results for hybrid search
	 * 
	 * @param array $semantic_results Results from vector/semantic search
	 * @param string $keyword_results Results from keyword search (formatted string)
	 * @return string Merged and formatted results
	 */
	private function merge_search_results( $semantic_results, $keyword_results ) {
		$merged_content = '';
		
		// Add semantic results first (higher priority)
		if ( ! empty( $semantic_results ) && is_array( $semantic_results ) ) {
			$merged_content .= "=== Semantic Search Results (Conceptually Related) ===\n\n";
			
			foreach ( $semantic_results as $result ) {
				$similarity_score = isset( $result['similarity'] ) ? round( $result['similarity'] * 100 ) : 0;
				$merged_content .= sprintf(
					"From %s '%s' (Relevance: %d%%):\n%s\n\n",
					ucfirst( $result['type'] ?? 'content' ),
					$result['title'] ?? 'Untitled',
					$similarity_score,
					substr( $result['content'] ?? '', 0, 500 )
				);
			}
		}
		
		// Add keyword results (exact matches)
		if ( ! empty( $keyword_results ) && is_string( $keyword_results ) ) {
			$merged_content .= "\n=== Keyword Search Results (Exact Matches) ===\n\n";
			$merged_content .= $keyword_results;
		}
		
		// If both are empty, return empty string
		if ( empty( $merged_content ) ) {
			return '';
		}
		
		return $merged_content;
	}

	/**
	 * Get response from the AI provider.
	 *
	 * @param \Askany\Providers\AIProviderInterface $provider The provider instance.
	 * @param string $query The user query.
	 * @param string $system_message The system message for context.
	 * @param string $session_id Optional session ID for tracking.
	 * @param array $conversation_history Optional conversation history.
	 * @param array $product_context Product context if this is a product query.
	 * @return array|false The response data or false on failure.
	 */
	private function get_provider_response( $provider, $query, $system_message, $session_id = '', $conversation_history = array(), $product_context = array() ) {
		$start_time = microtime(true);
		$user_id = get_current_user_id();

		// Build messages array with conversation history
		$messages = array(
			array(
				'role' => 'system',
				'content' => $system_message,
			)
		);

		// Add ALL conversation history (no limit) so AI can learn from complete context
		// This allows AI to understand mistakes and provide better responses
		if ( ! empty($conversation_history) ) {
			foreach ( $conversation_history as $msg ) {
				$messages[] = array(
					'role' => $msg['role'],
					'content' => $msg['content']
				);
			}
		}

		// Add current user query
		$messages[] = array(
			'role' => 'user',
			'content' => $query,
		);

		// Use selected model or default
		$options = array();
		if ( ! empty( $this->api_model ) ) {
			$options['model'] = $this->api_model;
		}

		$response = $provider->send_chat_request( $messages, $options );

		if ( ! $response ) {
			$response_time = microtime(true) - $start_time;
			$this->database->log_api_stats(
				'chat',
				$provider->get_provider_name(),
				'error',
				$response_time,
				'Provider request failed',
				$query,
				$session_id,
				$user_id ?: null
			);
			return false;
		}

		$response_time = microtime(true) - $start_time;
		
		// Log successful response
		$this->database->log_api_stats(
			'chat',
			$provider->get_provider_name(),
			'success',
			$response_time,
			null,
			$query,
			$session_id,
			$user_id ?: null
		);

		return array(
			'text' => $response['text'],
			'related_products' => $product_context,
		);
	}
	
	/**
	 * Get the OpenAI response.
	 *
	 * @param string $query The user query.
	 * @param string $system_message The system message for context.
	 * @param string $session_id Optional session ID for tracking.
	 * @param array $conversation_history Optional conversation history.
	 * @param array $product_context Product context if this is a product query.
	 * @return array|false The response data or false on failure.
	 */
	private function get_openai_response( $query, $system_message, $session_id = '', $conversation_history = array(), $product_context = array() ) {
		$start_time = microtime(true);
		$user_id = get_current_user_id();

		if ( empty($this->api_key_openai) ) {
			$this->database->log_api_stats(
				'chat',
				'openai',
				'error',
				null,
				'No API key configured',
				$query,
				$session_id,
				$user_id ?: null
			);
			return false;
		}

		$api_url = $this->api_url_openai ?: 'https://api.openai.com/v1/chat/completions';

		// Build messages array with conversation history
		$messages = array(
			array(
				'role' => 'system',
				'content' => $system_message,
			)
		);

		// Add ALL conversation history (no limit) so AI can learn from complete context
		if ( ! empty($conversation_history) ) {
			foreach ( $conversation_history as $msg ) {
				$messages[] = array(
					'role' => $msg['role'],
					'content' => $msg['content']
				);
			}
		}

		// Add current user query
		$messages[] = array(
			'role' => 'user',
			'content' => $query,
		);

		$request_data = array(
			'model' => 'gpt-4o-mini',
			'messages' => $messages,
			'temperature' => 0.3,
			'max_tokens' => 800,
			'frequency_penalty' => 0.3,
		);

		// Ensure JSON encoding succeeds
		$json_body = json_encode($request_data);
		if ($json_body === false) {
			$response_time = microtime(true) - $start_time;
			$this->database->log_api_stats(
				'chat',
				'openai',
				'error',
				$response_time,
				'JSON encoding failed for request data',
				$query,
				$session_id,
				$user_id ?: null
			);
			return false;
		}

		$args = array(
			'method' => 'POST',
			'timeout' => 30,
			'headers' => array(
				'Content-Type' => 'application/json',
				'Authorization' => 'Bearer ' . $this->api_key_openai,
			),
			'body' => $json_body,
		);

		$response = wp_remote_post($api_url, $args);

		if ( is_wp_error($response) ) {
			$error_message = 'OpenAI API Error: ' . $response->get_error_message();
			$response_time = microtime(true) - $start_time;
			
			$this->database->log_api_stats(
				'chat',
				'openai',
				'error',
				$response_time,
				$error_message,
				$query,
				$session_id,
				$user_id ?: null
			);
			
			return false;
		}

		$response_code = wp_remote_retrieve_response_code($response);
		$response_body = wp_remote_retrieve_body($response);
		$data = json_decode($response_body, true);

		// Handle specific HTTP status codes.
		switch ( $response_code ) {
			case 200:
				break; // Success - continue processing.
			case 401:
				// error_log('OpenAI API Error: Invalid API key (HTTP 401)');
				return false;
			case 429:
				// error_log('OpenAI API Error: Rate limit exceeded (HTTP 429)');
				return false;
			case 402:
				// error_log('OpenAI API Error: Payment required (HTTP 402)');
				return false;
			default:
				// error_log("OpenAI API Error: HTTP $response_code - " . $response_body);
				return false;
		}

		if ( empty($data) || ! isset($data['choices'][0]['message']['content']) ) {
			$response_time = microtime(true) - $start_time;
			$this->database->log_api_stats(
				'chat',
				'openai',
				'error',
				$response_time,
				'Invalid response format',
				$query,
				$session_id,
				$user_id ?: null
			);
			return false;
		}

		$response_text = $data['choices'][0]['message']['content'];
		$response_time = microtime(true) - $start_time;
		
		// Log successful response
		$this->database->log_api_stats(
			'chat',
			'openai',
			'success',
			$response_time,
			null,
			$query,
			$session_id,
			$user_id ?: null
		);

		return array(
			'text' => $response_text,
			'related_products' => $product_context,
		);
	}

	/**
	 * Get the DeepSeek response.
	 *
	 * @param string $query The user query.
	 * @param string $system_message The system message for context.
	 * @param string $session_id Optional session ID for tracking.
	 * @param array $conversation_history Optional conversation history.
	 * @param array $product_context Product context if this is a product query.
	 * @return array|false The response data or false on failure.
	 */
	private function get_deepseek_response( $query, $system_message, $session_id = '', $conversation_history = array(), $product_context = array() ) {
		if ( empty($this->api_key_deepseek) ) {
			// error_log('DeepSeek API Error: No API key configured');
			return false;
		}

		$api_url = $this->api_url_deepseek ?: 'https://api.deepseek.com/v1/chat/completions';

		// Build messages array with conversation history
		$messages = array(
			array(
				'role' => 'system',
				'content' => $system_message,
			)
		);

		// Add ALL conversation history (no limit) so AI can learn from complete context
		if ( ! empty($conversation_history) ) {
			foreach ( $conversation_history as $msg ) {
				$messages[] = array(
					'role' => $msg['role'],
					'content' => $msg['content']
				);
			}
		}

		// Add current user query
		$messages[] = array(
			'role' => 'user',
			'content' => $query,
		);

		$request_data = array(
			'model' => 'deepseek-chat',
			'messages' => $messages,
			'temperature' => 0.3,
			'max_tokens' => 800,
			'frequency_penalty' => 0.3,
		);

		// Ensure JSON encoding succeeds
		$json_body = json_encode($request_data);
		if ($json_body === false) {
			error_log('DeepSeek API Error: JSON encoding failed for request data');
			return false;
		}

		$args = array(
			'method' => 'POST',
			'timeout' => 30,
			'headers' => array(
				'Content-Type' => 'application/json',
				'Authorization' => 'Bearer ' . $this->api_key_deepseek,
			),
			'body' => $json_body,
		);

		$response = wp_remote_post($api_url, $args);

		if ( is_wp_error($response) ) {
			$error_message = 'DeepSeek API Error: ' . $response->get_error_message();
			// error_log($error_message);
			return false;
		}

		$response_code = wp_remote_retrieve_response_code($response);
		$response_body = wp_remote_retrieve_body($response);
		$data = json_decode($response_body, true);

		// Handle specific HTTP status codes.
		switch ( $response_code ) {
			case 200:
				break; // Success - continue processing.
			case 401:
				// error_log('DeepSeek API Error: Invalid API key (HTTP 401) - ' . $response_body);
				return false;
			case 402:
				// error_log('DeepSeek API Error: Payment required (HTTP 402) - ' . $response_body);
				return false;
			case 403:
				// error_log('DeepSeek API Error: Forbidden (HTTP 403) - ' . $response_body);
				return false;
			case 429:
				// error_log('DeepSeek API Error: Rate limit exceeded (HTTP 429) - ' . $response_body);
				return false;
			case 500:
				// error_log('DeepSeek API Error: Internal server error (HTTP 500) - ' . $response_body);
				return false;
			case 503:
				// error_log('DeepSeek API Error: Service unavailable (HTTP 503) - ' . $response_body);
				return false;
			default:
				// error_log("DeepSeek API Error: HTTP $response_code - " . $response_body);
				return false;
		}

		if ( empty($data) || ! isset($data['choices'][0]['message']['content']) ) {
			// error_log('DeepSeek API Error: Invalid response format - ' . $response_body);
			return false;
		}

		$response_text = $data['choices'][0]['message']['content'];

		return array(
			'text' => $response_text,
			'related_products' => $product_context,
		);
	}

	/**
	 * Get intelligent fallback response if API is not available.
	 *
	 * @param string $query The user query.
	 * @return array The fallback response data.
	 */
	private function get_fallback_response( $query ) {
		// error_log( 'AskAny Debug: get_fallback_response called for: ' . $query );
		
		// First check for common responses (greetings, small talk, etc.)
		$common_response = $this->get_common_response($query);
		if ( $common_response !== false ) {
			// error_log( 'AskAny Debug: Using common response for: ' . $query );
			return array(
				'text' => $common_response,
				'related_products' => array(),
			);
		}

		// Determine query type and get appropriate response
		$query_type = $this->analyze_query_type($query);
		$related_products = $this->is_product_query($query) ? $this->get_enhanced_product_context($query) : array();
		
		// error_log( 'AskAny Debug: Query type determined as: ' . $query_type . ' for query: ' . $query );
		
		switch ( $query_type ) {
			case 'product_specific':
				// error_log( 'AskAny Debug: Using product_specific_response for: ' . $query );
				return $this->get_product_specific_response($query, $related_products);
			case 'product_general':
				// error_log( 'AskAny Debug: Using product_general_response for: ' . $query );
				return $this->get_product_general_response($query, $related_products);
			case 'product_comparison':
				// error_log( 'AskAny Debug: Using product_comparison_response for: ' . $query );
				return $this->get_product_comparison_response($query, $related_products);
			case 'general_info':
				// error_log( 'AskAny Debug: Using general_info_response for: ' . $query );
				return $this->get_general_info_response($query);
			case 'greeting':
				// error_log( 'AskAny Debug: Using greeting_response for: ' . $query );
				return $this->get_greeting_response($query);
			default:
				// error_log( 'AskAny Debug: Using default_helpful_response for: ' . $query );
				return $this->get_default_helpful_response($query, $related_products);
		}
	}

	/**
	 * Analyze the type of user query to provide appropriate response.
	 *
	 * @param string $query The user query.
	 * @return string The query type.
	 */
	private function analyze_query_type( $query ) {
		$query_lower = strtolower($query);
		
		// Greeting patterns - use word boundaries for precise matching
		$greeting_patterns = array('hello', 'hi', 'hey', 'good morning', 'good afternoon', 'good evening');
		foreach ( $greeting_patterns as $pattern ) {
			if ( preg_match('/\b' . preg_quote($pattern, '/') . '\b/', $query_lower) ) {
				return 'greeting';
			}
		}
		
		// Special case for "how are you" - exact phrase match
		if ( strpos($query_lower, 'how are you') !== false ) {
			return 'greeting';
		}
		
		// Information seeking queries - these should trigger search
		$info_seeking_patterns = array(
			'who is', 'who are', 'what is', 'what are', 'tell me about', 
			'do you know', 'have you heard', 'explain', 'describe',
			'who was', 'what was', 'when was', 'where is', 'how does'
		);
		foreach ( $info_seeking_patterns as $pattern ) {
			if ( strpos($query_lower, $pattern) !== false ) {
				// Check if it's not a product query
				if ( ! $this->is_product_query($query) ) {
					return 'general_info';
				}
			}
		}
		
		// Product-specific queries (asking about specific product details)
		$specific_patterns = array(
			'price of', 'cost of', 'how much', 'stock of', 'availability of', 
			'color of', 'size of', 'specification', 'details of'
		);
		foreach ( $specific_patterns as $pattern ) {
			if ( strpos($query_lower, $pattern) !== false && $this->is_product_query($query) ) {
				return 'product_specific';
			}
		}
		
		// Product comparison queries
		$comparison_patterns = array('compare', 'difference between', 'vs', 'versus', 'better', 'best', 'recommend');
		foreach ( $comparison_patterns as $pattern ) {
			if ( strpos($query_lower, $pattern) !== false && $this->is_product_query($query) ) {
				return 'product_comparison';
			}
		}
		
		// General product queries
		if ( $this->is_product_query($query) ) {
			return 'product_general';
		}
		
		// General information queries - broader patterns
		$general_info_patterns = array('what', 'how', 'why', 'when', 'where');
		foreach ( $general_info_patterns as $pattern ) {
			if ( preg_match('/\b' . preg_quote($pattern, '/') . '\b/', $query_lower) ) {
				return 'general_info';
			}
		}
		
		return 'general';
	}

	/**
	 * Get response for product-specific queries.
	 *
	 * @param string $query The user query.
	 * @param array $products Related products.
	 * @return array The response data.
	 */
	private function get_product_specific_response( $query, $products ) {
		if ( empty($products) ) {
			return array(
				'text' => "I'd love to help you with product information! However, I couldn't find the specific product you're asking about. Could you try rephrasing your question or browse our available products?",
				'related_products' => array(),
			);
		}

		// If only one product found, provide detailed information
		if ( count($products) === 1 ) {
			$product = $products[0];
			$response = "Here's what I found about " . $product['name'] . ":\n\n";
			
			if ( ! empty($product['price_html']) ) {
				$response .= "💰 Price: " . strip_tags($product['price_html']) . "\n";
			}
			
			if ( ! empty($product['stock_status']) ) {
				$stock_text = $product['stock_status'] === 'instock' ? '✅ In Stock' : '❌ Out of Stock';
				if ( ! empty($product['stock_quantity']) && $product['stock_quantity'] > 0 ) {
					$stock_text .= " (" . $product['stock_quantity'] . " available)";
				}
				$response .= $stock_text . "\n";
			}
			
			if ( ! empty($product['short_description']) ) {
				$response .= "\n" . wp_strip_all_tags($product['short_description']) . "\n";
			}
			
			$response .= "\nWould you like to know anything else about this product?";
			
			return array(
				'text' => $response,
				'related_products' => $products,
			);
		}

		// Multiple products found
		$response = "I found several products that match your query. Here are the details:\n\n";
		foreach ( array_slice($products, 0, 3) as $index => $product ) {
			$response .= ($index + 1) . ". " . $product['name'];
			if ( ! empty($product['price_html']) ) {
				$response .= " - " . strip_tags($product['price_html']);
			}
			if ( $product['stock_status'] === 'outofstock' ) {
				$response .= " (Out of Stock)";
			}
			$response .= "\n";
		}
		
		$response .= "\nWhich one would you like to know more about?";
		
		return array(
			'text' => $response,
			'related_products' => $products,
		);
	}

	/**
	 * Get response for general product queries.
	 *
	 * @param string $query The user query.
	 * @param array $products Related products.
	 * @return array The response data.
	 */
	private function get_product_general_response( $query, $products ) {
		if ( empty($products) ) {
			return array(
				'text' => "I'd be happy to help you find products! Could you be more specific about what you're looking for? For example, you could ask about categories, price ranges, or specific features you need.",
				'related_products' => $this->get_popular_products(),
			);
		}

		$response_starters = array(
			"Great! I found some products that might interest you.",
			"Perfect! Here are some options I think you'll like.",
			"Excellent choice! I have some great recommendations for you.",
			"I found some fantastic products that match what you're looking for!"
		);
		
		$response = $response_starters[array_rand($response_starters)] . "\n\n";
		$response .= "Take a look at the product cards below - they include all the details like prices, availability, and descriptions. ";
		$response .= "If you need specific information about any of these products, just ask!";
		
		return array(
			'text' => $response,
			'related_products' => $products,
		);
	}

	/**
	 * Get response for product comparison queries.
	 *
	 * @param string $query The user query.
	 * @param array $products Related products.
	 * @return array The response data.
	 */
	private function get_product_comparison_response( $query, $products ) {
		if ( empty($products) ) {
			return array(
				'text' => "I'd love to help you compare products! Could you tell me which specific products you'd like to compare? I can help you look at prices, features, availability, and more.",
				'related_products' => array(),
			);
		}

		if ( count($products) < 2 ) {
			return array(
				'text' => "I found one product that matches your query, but I'd need at least two products to make a comparison. Could you specify another product you'd like to compare it with?",
				'related_products' => $products,
			);
		}

		$response = "Here's a comparison of the products I found:\n\n";
		
		foreach ( array_slice($products, 0, 3) as $index => $product ) {
			$response .= "**" . $product['name'] . "**\n";
			$response .= "• Price: " . strip_tags($product['price_html']) . "\n";
			$response .= "• Status: " . ($product['stock_status'] === 'instock' ? 'In Stock' : 'Out of Stock') . "\n";
			if ( ! empty($product['average_rating']) && $product['average_rating'] > 0 ) {
				$response .= "• Rating: " . $product['average_rating'] . "/5 stars\n";
			}
			$response .= "\n";
		}
		
		$response .= "Check out the detailed product cards below for more information. Which one catches your interest?";
		
		return array(
			'text' => $response,
			'related_products' => $products,
		);
	}

	/**
	 * Get response for general information queries.
	 * Enhanced with search integration when local content is insufficient.
	 *
	 * @param string $query The user query.
	 * @return array The response data.
	 */
	private function get_general_info_response( $query ) {
		// First check local content (including external sources)
		$relevant_content = $this->database->get_relevant_content($query);
		
		if ( ! empty($relevant_content) ) {
			// Format the response with proper structure
			$response = $this->format_external_content_response($relevant_content, $query);
			
			if ( ! empty($response) ) {
				return array(
					'text' => $response,
					'related_products' => array(),
				);
			}
		}
		
		// No local content found, try internet search for informational queries
		$search_response = $this->get_search_enhanced_response( $query );
		
		if ( $search_response !== false ) {
			return array(
				'text' => $search_response,
				'related_products' => array(),
			);
		}
		
		// If search also fails, provide a helpful response suggesting search
		$query_lower = strtolower($query);
		if ( strpos($query_lower, 'who is') !== false || strpos($query_lower, 'what is') !== false || 
			 strpos($query_lower, 'tell me about') !== false || strpos($query_lower, 'do you know') !== false ) {
			
			return array(
				'text' => "I don't have specific information about that in my current knowledge base. However, I can try to search the internet for you if you'd like. You could also try asking me about topics related to our website content, products, or services that I might be able to help with.",
				'related_products' => array(),
			);
		}
		
		return array(
			'text' => "I'd be happy to help answer your question! However, I don't have specific information about that topic in my knowledge base. Is there something else I can help you with, or would you like to browse our products?",
			'related_products' => array(),
		);
	}

	/**
	 * Format external content response with proper structure and links.
	 *
	 * @param string $content The raw content from external sources.
	 * @param string $query The user query.
	 * @return string The formatted response.
	 */
	private function format_external_content_response( $content, $query ) {
		// Extract external source references
		$sources = array();
		$content_parts = explode('From External_url', $content);
		
		if ( count($content_parts) > 1 ) {
			$response = "Based on the information I found:\n\n";
			
			for ( $i = 1; $i < count($content_parts); $i++ ) {
				$part = $content_parts[$i];
				
				// Extract title and URL
				if ( preg_match("/^\\s*'([^']+)'\\s*\\(([^)]+)\\):\\s*(.+?)(?=From External_url|$)/s", $part, $matches) ) {
					$title = trim($matches[1]);
					$url = trim($matches[2]);
					$excerpt = trim($matches[3]);
					
					// Clean up the excerpt
					$excerpt = preg_replace('/\s+/', ' ', $excerpt);
					$excerpt = substr($excerpt, 0, 300);
					if ( strlen($matches[3]) > 300 ) {
						$excerpt .= '...';
					}
					
					$response .= "**From: [{$title}]({$url})**\n";
					$response .= "{$excerpt}\n\n";
					
					$sources[] = array('title' => $title, 'url' => $url);
				}
			}
			
			if ( ! empty($sources) ) {
				$response .= "Would you like to know more about any of these topics?";
				return $response;
			}
		}
		
		// Fallback to simple content extraction
		$sentences = preg_split('/(?<=[.!?])\s+/', $content, -1, PREG_SPLIT_NO_EMPTY);
		$keywords = array_filter(explode(' ', strtolower($query)), function($word) {
			return strlen($word) > 3;
		});
		
		$best_sentences = array();
		foreach ( $sentences as $sentence ) {
			$score = 0;
			$sentence_lower = strtolower($sentence);
			foreach ( $keywords as $keyword ) {
				if ( strpos($sentence_lower, $keyword) !== false ) {
					$score++;
				}
			}
			if ( $score > 0 ) {
				$best_sentences[] = array('sentence' => $sentence, 'score' => $score);
			}
		}
		
		if ( ! empty($best_sentences) ) {
			// Sort by score and take the best ones
			usort($best_sentences, function($a, $b) {
				return $b['score'] - $a['score'];
			});
			
			$response = "Based on the information I have:\n\n";
			$response .= $best_sentences[0]['sentence'];
			
			if ( count($best_sentences) > 1 ) {
				$response .= " " . $best_sentences[1]['sentence'];
			}
			
			$response .= "\n\nIs there anything specific you'd like to know more about?";
			
			return $response;
		}
		
		return '';
	}

	/**
	 * Get greeting response.
	 *
	 * @param string $query The user query.
	 * @return array The response data.
	 */
	private function get_greeting_response( $query ) {
		$greetings = array(
			"Hello! Welcome! I'm here to help you find what you're looking for. How can I assist you today?",
			"Hi there! Great to see you! I'm ready to help with any questions about our products or services. What can I do for you?",
			"Hey! Welcome to our store! I'm your shopping assistant and I'm here to make your experience amazing. How can I help?",
			"Hello and welcome! I'm excited to help you today. Whether you're looking for products, have questions, or need recommendations, I'm here for you!"
		);
		
		return array(
			'text' => $greetings[array_rand($greetings)],
			'related_products' => array(),
		);
	}

	/**
	 * Get default helpful response when no specific pattern matches.
	 * Enhanced with DuckDuckGo search integration for better responses.
	 *
	 * @param string $query The user query.
	 * @param array $products Related products.
	 * @return array The response data.
	 */
	private function get_default_helpful_response( $query, $products ) {
		// Try to get search-enhanced response first
		$search_response = $this->get_search_enhanced_response( $query );
		
		if ( $search_response !== false ) {
			// Combine search results with local context
			$response = $search_response;
			
			if ( ! empty($products) ) {
				$response .= "\n\nI also found some related products that might interest you - check them out below!";
			}
			
			return array(
				'text' => $response,
				'related_products' => $products,
			);
		}
		
		// Fallback to generic responses if search fails
		$responses = array(
			"I'm here to help! Could you tell me a bit more about what you're looking for?",
			"I'd love to assist you! Can you provide more details about your question?",
			"I'm ready to help you find what you need! Could you be more specific about what you're interested in?",
			"Great question! To give you the best answer, could you tell me more about what you have in mind?"
		);
		
		$response = $responses[array_rand($responses)];
		
		if ( ! empty($products) ) {
			$response .= " In the meantime, I found some products that might interest you - check them out below!";
		}
		
		return array(
			'text' => $response,
			'related_products' => $products,
		);
	}

	/**
	 * Get search-enhanced response using DuckDuckGo Instant Answer API.
	 *
	 * @param string $query The user query.
	 * @return string|false The enhanced response or false if search fails.
	 */
	private function get_search_enhanced_response( $query ) {
		// Skip search for very short queries or greetings
		if ( strlen(trim($query)) < 3 ) {
			// error_log( 'AskAny Debug: Skipping search for short query: ' . $query );
			return false;
		}
		
		// Skip search for obvious product queries (let product handlers deal with them)
		$product_indicators = array('buy', 'purchase', 'price', 'cost', 'order', 'cart', 'checkout');
		$query_lower = strtolower($query);
		
		// But allow queries about "author", "creator", "developer" even if they mention "plugin"
		$author_indicators = array('author', 'creator', 'developer', 'made by', 'created by', 'who made', 'who created', 'who developed', 'author of');
		$is_author_query = false;
		foreach ( $author_indicators as $indicator ) {
			if ( strpos($query_lower, $indicator) !== false ) {
				$is_author_query = true;
				break;
			}
		}
		
		// Also allow general information queries that might need internet search
		$info_indicators = array('what is', 'tell me about', 'explain', 'how does', 'who is', 'where is', 'when was', 'why is');
		$is_info_query = false;
		foreach ( $info_indicators as $indicator ) {
			if ( strpos($query_lower, $indicator) !== false ) {
				$is_info_query = true;
				break;
			}
		}
		
		if ( !$is_author_query && !$is_info_query ) {
			foreach ( $product_indicators as $indicator ) {
				if ( strpos($query_lower, $indicator) !== false ) {
					// error_log( 'AskAny Debug: Skipping search for product query: ' . $query );
					return false;
				}
			}
		} else {
			if ( $is_author_query ) {
				// error_log( 'AskAny Debug: Detected author/creator query, allowing search: ' . $query );
			}
			if ( $is_info_query ) {
				// error_log( 'AskAny Debug: Detected information query, allowing search: ' . $query );
			}
		}
		
		// error_log( 'AskAny Debug: Attempting DuckDuckGo search for: ' . $query );
		
		try {
			// Use DuckDuckGo Instant Answer API
			$search_url = 'https://api.duckduckgo.com/?q=' . urlencode($query) . '&format=json&no_html=1&skip_disambig=1';
			
			$response = wp_remote_get( $search_url, array(
				'timeout' => 5,
				'user-agent' => 'AskAny WordPress Plugin/1.0'
			) );
			
			if ( is_wp_error( $response ) ) {
				// error_log( 'AskAny Debug: DuckDuckGo API error: ' . $response->get_error_message() );
				return false;
			}
			
			$body = wp_remote_retrieve_body( $response );
			$data = json_decode( $body, true );
			
			if ( ! $data ) {
				// error_log( 'AskAny Debug: Failed to decode DuckDuckGo response' );
				return false;
			}
			
			// error_log( 'AskAny Debug: DuckDuckGo raw response: ' . substr($body, 0, 500) . '...' );
			
			// Try to extract useful information from the response
			$answer = $this->extract_search_answer( $data, $query );
			
			if ( $answer ) {
				// error_log( 'AskAny Debug: Successfully extracted search answer: ' . substr($answer, 0, 100) . '...' );
				return $answer;
			} else {
				// error_log( 'AskAny Debug: No useful answer found in DuckDuckGo response' );
			}
			
		} catch ( Exception $e ) {
			// error_log( 'AskAny Search Error: ' . $e->getMessage() );
		}
		
		return false;
	}

	/**
	 * Extract useful answer from DuckDuckGo search results.
	 *
	 * @param array $data The search API response data.
	 * @param string $query The original query.
	 * @return string|false The extracted answer or false.
	 */
	private function extract_search_answer( $data, $query ) {
		// Check for instant answer
		if ( ! empty( $data['Answer'] ) ) {
			return "Based on my search: " . $data['Answer'];
		}
		
		// Check for abstract (Wikipedia-style summary)
		if ( ! empty( $data['Abstract'] ) ) {
			$abstract = $data['Abstract'];
			// Limit length to keep response manageable
			if ( strlen( $abstract ) > 300 ) {
				$abstract = substr( $abstract, 0, 300 ) . '...';
			}
			
			$response = "Here's what I found: " . $abstract;
			
			// Add source if available
			if ( ! empty( $data['AbstractSource'] ) ) {
				$response .= "\n\n*Source: " . $data['AbstractSource'] . "*";
			}
			
			return $response;
		}
		
		// Check for definition
		if ( ! empty( $data['Definition'] ) ) {
			$response = "Definition: " . $data['Definition'];
			
			if ( ! empty( $data['DefinitionSource'] ) ) {
				$response .= "\n\n*Source: " . $data['DefinitionSource'] . "*";
			}
			
			return $response;
		}
		
		// Check for related topics that might be useful
		if ( ! empty( $data['RelatedTopics'] ) && is_array( $data['RelatedTopics'] ) ) {
			foreach ( $data['RelatedTopics'] as $topic ) {
				if ( ! empty( $topic['Text'] ) ) {
					$text = $topic['Text'];
					// Use first relevant topic
					if ( strlen( $text ) > 50 && strlen( $text ) < 400 ) {
						return "I found this information: " . $text;
					}
				}
			}
		}
		
		// Check for infobox data (structured information)
		if ( ! empty( $data['Infobox'] ) && ! empty( $data['Infobox']['content'] ) ) {
			$infobox = $data['Infobox']['content'];
			$info_parts = array();
			
			foreach ( $infobox as $item ) {
				if ( ! empty( $item['label'] ) && ! empty( $item['value'] ) ) {
					$info_parts[] = $item['label'] . ': ' . $item['value'];
				}
				
				// Limit to first 3 items to keep response concise
				if ( count( $info_parts ) >= 3 ) {
					break;
				}
			}
			
			if ( ! empty( $info_parts ) ) {
				return "Here's what I found:\n\n" . implode( "\n", $info_parts );
			}
		}
		
		return false;
	}

	
	/**
	 * Get popular products for suggestions.
	 *
	 * @return array Popular products.
	 */
	private function get_popular_products() {
		if ( ! class_exists('WooCommerce') ) {
			return array();
		}

		// Get products ordered by popularity (sales)
		$args = array(
			'post_type' => 'product',
			'post_status' => 'publish',
			'posts_per_page' => 4,
			'meta_key' => 'total_sales',
			'orderby' => 'meta_value_num',
			'order' => 'DESC',
		);

		$products = get_posts($args);
		$product_data = array();

		foreach ( $products as $post ) {
			$product = wc_get_product($post->ID);
			if ( $product ) {
				$product_data[] = array(
					'id' => $post->ID,
					'name' => $product->get_name(),
					'title' => $product->get_name(),
					'price_html' => $product->get_price_html(),
					'stock_status' => $product->get_stock_status(),
					'url' => get_permalink($post->ID),
					'image' => wp_get_attachment_image_url($product->get_image_id(), 'medium'),
					'short_description' => wp_strip_all_tags($product->get_short_description()),
				);
			}
		}

		return $product_data;
	}

	/**
	 * Get common responses for small talk and greetings.
	 *
	 * @param string $query The user query.
	 * @return string|false The common response or false if not found.
	 */
	private function get_common_response( $query ) {
		$query = strtolower(trim($query));

		// Enhanced greeting responses
		$greeting_patterns = array(
			'hello' => array(
				"Hello! Welcome to our store! I'm here to help you find exactly what you're looking for. What can I assist you with today?",
				"Hi there! Great to see you! I'm your personal shopping assistant. How can I make your day better?",
				"Hello and welcome! I'm excited to help you discover amazing products. What brings you here today?"
			),
			'hi' => array(
				"Hi! Welcome! I'm here to help you with anything you need. What can I do for you?",
				"Hey there! I'm your friendly shopping assistant. Ready to help you find something great!",
				"Hi! So glad you're here! I'm ready to assist with products, questions, or recommendations."
			),
			'hey' => array(
				"Hey! Welcome to our store! I'm here to make your shopping experience awesome. What's up?",
				"Hey there! I'm your shopping buddy, ready to help you find what you need. How can I assist?",
				"Hey! Great to see you! I'm here to help with products, questions, or just to chat. What's on your mind?"
			),
			'good morning' => array(
				"Good morning! What a great way to start the day - shopping with us! How can I help you this morning?",
				"Good morning! I hope you're having a wonderful start to your day. I'm here to help you find what you need!",
				"Good morning! Ready to make today amazing? I'm here to assist with any questions or product recommendations!"
			),
			'good afternoon' => array(
				"Good afternoon! Perfect time for some shopping! I'm here to help you find exactly what you're looking for.",
				"Good afternoon! Hope your day is going well! I'm ready to assist with products, questions, or recommendations.",
				"Good afternoon! Great to see you! I'm your shopping assistant, ready to make your afternoon even better!"
			),
			'good evening' => array(
				"Good evening! Perfect time to browse and discover something new! How can I help you tonight?",
				"Good evening! Hope you've had a great day! I'm here to help you find what you need.",
				"Good evening! Welcome! I'm ready to assist with any questions or help you discover great products!"
			),
			'how are you' => array(
				"I'm doing great, thank you for asking! I'm excited to help you today. How are you doing?",
				"I'm fantastic and ready to help! Thanks for asking. I'm here to make your shopping experience amazing!",
				"I'm wonderful, thanks! I love helping customers find exactly what they need. How can I assist you today?"
			),
			'thanks' => array(
				"You're very welcome! I'm always happy to help. Is there anything else you need?",
				"My pleasure! That's what I'm here for. Feel free to ask if you need anything else!",
				"You're so welcome! I love helping out. Let me know if there's anything else I can do for you!"
			),
			'thank you' => array(
				"You're absolutely welcome! I'm here whenever you need help. Anything else I can assist with?",
				"It's my pleasure to help! That's what I'm here for. Is there anything else you'd like to know?",
				"You're very welcome! I'm always happy to help. Feel free to ask about anything else!"
			)
		);

		// Check for greeting patterns (use word boundaries to avoid false matches)
		foreach ( $greeting_patterns as $pattern => $responses ) {
			// Use word boundaries to ensure exact word matches
			if ( preg_match('/\b' . preg_quote($pattern, '/') . '\b/', $query) ) {
				return $responses[array_rand($responses)];
			}
		}

		// Time and date queries (these might trigger internet search in full AI mode)
		$time_date_responses = array(
			'time' => "I'd love to help with the current time! For the most accurate time, you might want to check your device's clock or ask me to search the internet for you.",
			'date' => "For today's date, I'd recommend checking your device or asking me to search for current date information online!",
			'day' => "To get the current day of the week, you can check your device or I can search the internet for you!",
		);

		foreach ( $time_date_responses as $pattern => $response ) {
			// Use word boundaries for more precise matching
			if ( preg_match('/\b' . preg_quote($pattern, '/') . '\b/', $query) ) {
				return $response;
			}
		}

		// Help and support queries
		$help_patterns = array(
			'help' => "I'm here to help! I can assist you with finding products, answering questions about our store, providing recommendations, and much more. What would you like help with?",
			'support' => "I'm your support assistant! I can help with product information, recommendations, store policies, and answer any questions you have. How can I support you today?",
			'assist' => "Absolutely! I'm here to assist you with anything you need. Whether it's finding products, getting information, or just browsing - I'm ready to help!"
		);

		foreach ( $help_patterns as $pattern => $response ) {
			// Use word boundaries for more precise matching
			if ( preg_match('/\b' . preg_quote($pattern, '/') . '\b/', $query) ) {
				return $response;
			}
		}

		return false;
	}

	/**
	 * Extract product information based on the query.
	 *
	 * @param string $query The user query.
	 * @return array The extracted product information.
	 */
	private function extract_product_information( $query ) {
		// Product extraction logic remains unchanged.
		if ( ! class_exists('WooCommerce') ) {
			return array();
		}

		global $wpdb;
		$tables = $this->database->get_tables();
		$content_index_table = $tables['content_index'];

		$search_terms = explode(' ', $query);
		$valid_terms = array_filter($search_terms, function ( $term ) {
			return strlen($term) > 3;
		});

		if ( empty($valid_terms) ) {
			return array();
		}

		$placeholders = array();
		$sql_parts = array();

		foreach ( $valid_terms as $term ) {
			$sql_parts[] = 'content LIKE %s';
			$placeholders[] = '%' . $wpdb->esc_like($term) . '%';
		}

		$search_condition = '(' . implode(' OR ', $sql_parts) . ')';
		array_unshift($placeholders, 'product');

		$product_ids = $wpdb->get_col(
			$wpdb->prepare(
				"SELECT object_id FROM $content_index_table 
                 WHERE object_type = %s AND $search_condition 
                 LIMIT 3",
				$placeholders
			)
		);

		if ( empty($product_ids) ) {
			return array();
		}

		$products = array();

		foreach ( $product_ids as $product_id ) {
			$product = wc_get_product($product_id);

			if ( ! $product ) {
				continue;
			}

			$product_data = array(
				'id' => $product_id,
				'title' => $product->get_name(),
				'price' => $product->get_price_html(),
				'url' => get_permalink($product_id),
				'add_to_cart_url' => $product->add_to_cart_url(),
				'image' => wp_get_attachment_image_url($product->get_image_id(), 'thumbnail'),
				'short_description' => $product->get_short_description(),
			);

			$products[] = $product_data;
		}

		return $products;
	}

	/**
	 * Update settings in the database. Save in backend we need to add here the settings update_settings
	 *
	 * @param array $settings The settings to update.
	 * @return bool True on success, false on failure.
	 */
	public function update_settings( $settings ) {
		if ( ! is_array($settings) ) {
			return false;
		}

		// Get current provider to determine which key/url to update.
		$current_provider = isset($settings['api_provider']) ? $settings['api_provider'] : $this->api_provider;

		// Update provider first if it's being changed.
		if ( isset($settings['api_provider']) ) {
			update_option('askany_api_provider', $settings['api_provider']);
		}

		// Update API key based on provider.
		if ( isset($settings['api_key']) ) {
			if ( $current_provider === 'openai' ) {
				update_option('askany_api_key_openai', $settings['api_key']);
			} elseif ( $current_provider === 'claude' ) {
				update_option('askany_api_key_claude', $settings['api_key']);
			} elseif ( $current_provider === 'gemini' ) {
				update_option('askany_api_key_gemini', $settings['api_key']);
			} elseif ( $current_provider === 'grok' ) {
				update_option('askany_api_key_grok', $settings['api_key']);
			} elseif ( $current_provider === 'openrouter' ) {
				update_option('askany_api_key_openrouter', $settings['api_key']);
			} else {
				update_option('askany_api_key_deepseek', $settings['api_key']);
			}
		}

		// Update API URL based on provider.
		if ( isset($settings['api_url']) ) {
			if ( $current_provider === 'openai' ) {
				update_option('askany_api_url_openai', $settings['api_url']);
			} elseif ( $current_provider === 'claude' ) {
				update_option('askany_api_url_claude', $settings['api_url']);
			} elseif ( $current_provider === 'gemini' ) {
				update_option('askany_api_url_gemini', $settings['api_url']);
			} elseif ( $current_provider === 'grok' ) {
				update_option('askany_api_url_grok', $settings['api_url']);
			} elseif ( $current_provider === 'openrouter' ) {
				update_option('askany_api_url_openrouter', $settings['api_url']);
			} else {
				update_option('askany_api_url_deepseek', $settings['api_url']);
			}
		}

		// Update model setting.
		if ( isset($settings['api_model']) ) {
			update_option('askany_api_model', sanitize_text_field($settings['api_model']));
		}

		// Update other settings.
		if ( isset($settings['api_enabled']) ) {
			update_option('askany_api_enabled', (bool) $settings['api_enabled']);
		}

		if ( isset($settings['fallback_enabled']) ) {
			update_option('askany_fallback_enabled', (bool) $settings['fallback_enabled']);
		}

		// Handle floating widget settings.
		if ( isset($settings['floating_widget_enabled']) ) {
			update_option('askany_floating_widget_enabled', (bool) $settings['floating_widget_enabled']);
		}

		if ( isset($settings['widget_position']) ) {
			update_option('askany_widget_position', sanitize_text_field($settings['widget_position']));
		}

		// Update chat header text and avatar.
		if ( isset($settings['chat_header_text']) ) {
			update_option('askany_chat_header_text', sanitize_text_field($settings['chat_header_text']));
		}

		if ( isset($settings['assistant_avatar']) ) {
			update_option('askany_assistant_avatar', esc_url_raw($settings['assistant_avatar']));
		}

		if ( isset($settings['contact_form_enabled']) ) {
			update_option('askany_contact_form_enabled', (bool) $settings['contact_form_enabled']);
		}

		if ( isset($settings['contact_form_shortcode']) ) {
			update_option('askany_contact_form_shortcode', sanitize_text_field($settings['contact_form_shortcode']));
		}

		// Handle home page settings
		if ( isset($settings['home_page_enabled']) ) {
			update_option('askany_home_page_enabled', (bool) $settings['home_page_enabled']);
		}

		if ( isset($settings['home_logo']) ) {
			update_option('askany_home_logo', esc_url_raw($settings['home_logo']));
		}

		if ( isset($settings['home_welcome_message']) ) {
			update_option('askany_home_welcome_message', sanitize_text_field($settings['home_welcome_message']));
		}

		if ( isset($settings['show_agents']) ) {
			update_option('askany_show_agents', (bool) $settings['show_agents']);
		}

		if ( isset($settings['show_documentation']) ) {
			update_option('askany_show_documentation', (bool) $settings['show_documentation']);
		}

		if ( isset($settings['documentation_url']) ) {
			update_option('askany_documentation_url', esc_url_raw($settings['documentation_url']));
		}

		if ( isset($settings['documentation_description']) ) {
			update_option('askany_documentation_description', sanitize_text_field($settings['documentation_description']));
		}

		if ( isset($settings['show_faq']) ) {
			update_option('askany_show_faq', (bool) $settings['show_faq']);
		}

		if ( isset($settings['show_custom_links']) ) {
			update_option('askany_show_custom_links', (bool) $settings['show_custom_links']);
		}

		// Handle get started page settings
		if ( isset($settings['get_started_enabled']) ) {
			update_option('askany_get_started_enabled', (bool) $settings['get_started_enabled']);
		}

		if ( isset($settings['get_started_title']) ) {
			update_option('askany_get_started_title', sanitize_text_field($settings['get_started_title']));
		}

		if ( isset($settings['get_started_description']) ) {
			update_option('askany_get_started_description', sanitize_textarea_field($settings['get_started_description']));
		}

		if ( isset($settings['get_started_name_label']) ) {
			update_option('askany_get_started_name_label', sanitize_text_field($settings['get_started_name_label']));
		}

		if ( isset($settings['get_started_email_label']) ) {
			update_option('askany_get_started_email_label', sanitize_text_field($settings['get_started_email_label']));
		}

		if ( isset($settings['get_started_button_text']) ) {
			update_option('askany_get_started_button_text', sanitize_text_field($settings['get_started_button_text']));
		}

		if ( isset($settings['get_started_name_required']) ) {
			update_option('askany_get_started_name_required', (bool) $settings['get_started_name_required']);
		}

		if ( isset($settings['get_started_email_required']) ) {
			update_option('askany_get_started_email_required', (bool) $settings['get_started_email_required']);
		}

		// Handle news section settings
		if ( isset($settings['news_enabled']) ) {
			update_option('askany_news_enabled', (bool) $settings['news_enabled']);
		}

		if ( isset($settings['news_label']) ) {
			update_option('askany_news_label', sanitize_text_field($settings['news_label']));
		}

		if ( isset($settings['news_mode']) ) {
			update_option('askany_news_mode', sanitize_text_field($settings['news_mode']));
		}

		if ( isset($settings['news_timeframe']) ) {
			update_option('askany_news_timeframe', intval($settings['news_timeframe']));
		}

		if ( isset($settings['news_count']) ) {
			update_option('askany_news_count', intval($settings['news_count']));
		}

		if ( isset($settings['news_excerpt_length']) ) {
			update_option('askany_news_excerpt_length', intval($settings['news_excerpt_length']));
		}

		if ( isset($settings['news_selected_posts']) ) {
			update_option('askany_news_selected_posts', $settings['news_selected_posts']);
		}

		// Handle report issue settings
		if ( isset($settings['report_issue_enabled']) ) {
			update_option('askany_report_issue_enabled', (bool) $settings['report_issue_enabled']);
		}

		if ( isset($settings['report_issue_title']) ) {
			update_option('askany_report_issue_title', sanitize_text_field($settings['report_issue_title']));
		}

		if ( isset($settings['report_issue_description']) ) {
			update_option('askany_report_issue_description', sanitize_text_field($settings['report_issue_description']));
		}

		if ( isset($settings['report_issue_message']) ) {
			update_option('askany_report_issue_message', sanitize_textarea_field($settings['report_issue_message']));
		}

		// Handle feature request settings
		if ( isset($settings['feature_request_enabled']) ) {
			update_option('askany_feature_request_enabled', (bool) $settings['feature_request_enabled']);
		}

		if ( isset($settings['feature_request_title']) ) {
			update_option('askany_feature_request_title', sanitize_text_field($settings['feature_request_title']));
		}

		if ( isset($settings['feature_request_description']) ) {
			update_option('askany_feature_request_description', sanitize_text_field($settings['feature_request_description']));
		}

		if ( isset($settings['feature_request_message']) ) {
			update_option('askany_feature_request_message', sanitize_textarea_field($settings['feature_request_message']));
		}

		// Handle response language setting
		if ( isset($settings['response_language']) ) {
			update_option('askany_response_language', sanitize_text_field($settings['response_language']));
		}

		// Handle typing animation setting (Pro only)
		if ( isset($settings['typing_animation_enabled']) ) {
			$plugin = \Askany\Plugin::get_instance();
			if ( $plugin->is_pro_active() ) {
				update_option('askany_typing_animation_enabled', (bool) $settings['typing_animation_enabled']);
			} else {
				update_option('askany_typing_animation_enabled', false);
			}
		}

		// Handle Slack integration settings
		if ( isset($settings['slack']) && is_array($settings['slack']) ) {
			$slack_settings = $settings['slack'];
			
			if ( isset($slack_settings['enabled']) ) {
				update_option('askany_slack_enabled', (bool) $slack_settings['enabled']);
			}
			
			if ( isset($slack_settings['webhook_url']) ) {
				update_option('askany_slack_webhook_url', esc_url_raw($slack_settings['webhook_url']));
			}
			
			if ( isset($slack_settings['channel']) ) {
				update_option('askany_slack_channel', sanitize_text_field($slack_settings['channel']));
			}
			
			if ( isset($slack_settings['notify_user_messages']) ) {
				update_option('askany_slack_notify_user_messages', (bool) $slack_settings['notify_user_messages']);
			}
			
			if ( isset($slack_settings['forward_agent_messages']) ) {
				update_option('askany_slack_forward_agent_messages', (bool) $slack_settings['forward_agent_messages']);
			}
			
			if ( isset($slack_settings['forward_ai_messages']) ) {
				update_option('askany_slack_forward_ai_messages', (bool) $slack_settings['forward_ai_messages']);
			}
		}

		// Handle WooCommerce integration setting
		if ( isset($settings['woocommerce_integration']) ) {
			update_option('askany_woocommerce_integration', (bool) $settings['woocommerce_integration']);
		}

		// Handle RAG (Retrieval-Augmented Generation) setting
		if ( isset($settings['rag_enabled']) ) {
			update_option('askany_rag_enabled', (bool) $settings['rag_enabled']);
		}

		// Handle Hybrid Search setting (Pro only)
		if ( isset($settings['hybrid_search_enabled']) ) {
			$plugin = \Askany\Plugin::get_instance();
			if ( $plugin->is_pro_active() ) {
				update_option('askany_hybrid_search_enabled', (bool) $settings['hybrid_search_enabled']);
			} else {
				update_option('askany_hybrid_search_enabled', false);
			}
		}

		// Handle RAG Optimization setting (Pro only)
		if ( isset($settings['rag_optimization_enabled']) ) {
			$plugin = \Askany\Plugin::get_instance();
			if ( $plugin->is_pro_active() ) {
				update_option('askany_rag_optimization_enabled', (bool) $settings['rag_optimization_enabled']);
			} else {
				update_option('askany_rag_optimization_enabled', false);
			}
		}

		// Handle Real-time Chat setting
		if ( isset($settings['realtime_enabled']) ) {
			update_option('askany_realtime_enabled', (bool) $settings['realtime_enabled']);
		}

		// Handle Mobile App Push Bridge setting (Pro only)
		if ( isset($settings['mobile_bridge_enabled']) ) {
			$plugin = \Askany\Plugin::get_instance();
			if ( $plugin->is_pro_active() ) {
				update_option('askany_mobile_bridge_enabled', (bool) $settings['mobile_bridge_enabled']);
			} else {
				update_option('askany_mobile_bridge_enabled', false);
			}
		}

		// Handle Push Modify Credentials setting (Pro only)
		if ( isset($settings['push_modify_credentials']) ) {
			$plugin = \Askany\Plugin::get_instance();
			if ( $plugin->is_pro_active() ) {
				update_option('askany_push_modify_credentials', (bool) $settings['push_modify_credentials']);
			} else {
				update_option('askany_push_modify_credentials', false);
			}
		}

		// Handle FCM V1 credentials (Pro only)
		$plugin = \Askany\Plugin::get_instance();
		if ( $plugin->is_pro_active() ) {
			if ( isset($settings['push_project_id']) ) {
				update_option('askany_push_project_id', sanitize_text_field($settings['push_project_id']));
			}
			if ( isset($settings['push_client_email']) ) {
				update_option('askany_push_client_email', sanitize_email($settings['push_client_email']));
			}
			if ( isset($settings['push_sender_id']) ) {
				update_option('askany_push_sender_id', sanitize_text_field($settings['push_sender_id']));
			}
			if ( isset($settings['push_private_key']) ) {
				// Normalize \n literals to real newlines (common when copying from JSON), then store
				$private_key = str_replace( '\\n', "\n", $settings['push_private_key'] );
				update_option('askany_push_private_key', sanitize_textarea_field( trim( $private_key ) ));
			}
		}

		// Web Search settings
		if ( isset( $settings['web_search_enabled'] ) ) {
			update_option( 'askany_web_search_enabled', (bool) $settings['web_search_enabled'] );
		}
		if ( isset( $settings['web_search_mode'] ) ) {
			$mode = sanitize_text_field( $settings['web_search_mode'] );
			if ( ! in_array( $mode, array( 'fallback', 'always' ), true ) ) {
				$mode = 'fallback';
			}
			update_option( 'askany_web_search_mode', $mode );
		}

		// Response Tone
		if ( isset( $settings['response_tone'] ) ) {
			$tone = sanitize_text_field( $settings['response_tone'] );
			if ( ! in_array( $tone, array( 'human', 'professional', 'friendly', 'robotic' ), true ) ) {
				$tone = 'human';
			}
			update_option( 'askany_response_tone', $tone );
		}

		// Typing Speed
		if ( isset( $settings['typing_speed'] ) ) {
			$speed = sanitize_text_field( $settings['typing_speed'] );
			if ( ! in_array( $speed, array( 'regular', 'fast', 'faster', 'instant' ), true ) ) {
				$speed = 'regular';
			}
			update_option( 'askany_typing_speed', $speed );
		}

		$this->load_settings();
		return true;
	}

	/**
	 * Get the current settings.
	 *
	 * @return array The current settings.
	 */
	public function get_settings() {
		// Check Pro status for feature access
		$plugin = \Askany\Plugin::get_instance();
		$is_pro = $plugin->is_pro_active();
		
		return array(
			'api_key' => get_option('askany_api_key', ''),
			'api_provider' => get_option('askany_api_provider', 'deepseek'),
			'api_model' => get_option('askany_api_model', ''),
			'api_url' => get_option('askany_api_url', ''),
			'api_enabled' => get_option('askany_api_enabled', false),
			'fallback_enabled' => get_option('askany_fallback_enabled', false),
			'floating_widget_enabled' => get_option('askany_floating_widget_enabled', false),
			'widget_position' => get_option('askany_widget_position', 'bottom-right'),
			'chat_header_text' => get_option('askany_chat_header_text', 'Ask Me Anything'),
			'assistant_avatar' => get_option('askany_assistant_avatar', ''),
			'contact_form_enabled' => get_option('askany_contact_form_enabled', ''),
			'contact_form_shortcode' => get_option('askany_contact_form_shortcode', ''),
			'response_language' => get_option('askany_response_language', 'auto'),
			'typing_animation_enabled' => $is_pro ? get_option('askany_typing_animation_enabled', false) : false,
			'rag_enabled' => get_option('askany_rag_enabled', false),
			'hybrid_search_enabled' => $is_pro ? get_option('askany_hybrid_search_enabled', false) : false,
			'rag_optimization_enabled' => $is_pro ? get_option('askany_rag_optimization_enabled', false) : false,
			'realtime_enabled' => get_option('askany_realtime_enabled', true),
			'mobile_bridge_enabled' => $is_pro ? (bool) get_option('askany_mobile_bridge_enabled', false) : false,
			'push_modify_credentials' => $is_pro ? (bool) get_option('askany_push_modify_credentials', false) : false,
			'push_project_id'       => $is_pro ? get_option('askany_push_project_id', '') : '',
			'push_client_email'     => $is_pro ? get_option('askany_push_client_email', '') : '',
			'push_sender_id'        => $is_pro ? get_option('askany_push_sender_id', '') : '',
			'push_private_key'      => $is_pro ? get_option('askany_push_private_key', '') : '',
			// Home page settings
			'home_page_enabled' => get_option('askany_home_page_enabled', false),
			'home_logo' => get_option('askany_home_logo', ''),
			'home_welcome_message' => get_option('askany_home_welcome_message', 'How may we help you today?'),
			'show_agents' => get_option('askany_show_agents', false),
			'show_documentation' => get_option('askany_show_documentation', false),
			'documentation_url' => get_option('askany_documentation_url', ''),
			'documentation_description' => get_option('askany_documentation_description', 'Find detailed guides and tutorials'),
			'show_faq' => get_option('askany_show_faq', false),
			'show_custom_links' => get_option('askany_show_custom_links', false),
			// Get started page settings
			'get_started_enabled' => get_option('askany_get_started_enabled', false),
			'get_started_title' => get_option('askany_get_started_title', 'Welcome! Let\'s Get Started'),
			'get_started_description' => get_option('askany_get_started_description', 'Please provide your name and email to start chatting with us.'),
			'get_started_name_label' => get_option('askany_get_started_name_label', 'Your Name'),
			'get_started_email_label' => get_option('askany_get_started_email_label', 'Your Email'),
			'get_started_button_text' => get_option('askany_get_started_button_text', 'Start Chat'),
			'get_started_name_required' => get_option('askany_get_started_name_required', false),
			'get_started_email_required' => get_option('askany_get_started_email_required', false),
			// News section settings
			'news_enabled' => get_option('askany_news_enabled', false),
			'news_label' => get_option('askany_news_label', __('News', 'askany')),
			'news_mode' => get_option('askany_news_mode', 'latest'),
			'news_timeframe' => get_option('askany_news_timeframe', 7),
			'news_count' => get_option('askany_news_count', 5),
			'news_excerpt_length' => get_option('askany_news_excerpt_length', 150),
			'news_selected_posts' => get_option('askany_news_selected_posts', array()),
			// Report issue settings
			'report_issue_enabled' => get_option('askany_report_issue_enabled', true),
			'report_issue_title' => get_option('askany_report_issue_title', __('Report an issue?', 'askany')),
			'report_issue_description' => get_option('askany_report_issue_description', __('Found a bug? Let us know.', 'askany')),
			'report_issue_message' => get_option('askany_report_issue_message', __('Hey 👋 Found a bug? Please describe the issue below. Also, please share your name and email so we can follow up with you.', 'askany')),
			// Feature request settings
			'feature_request_enabled' => get_option('askany_feature_request_enabled', true),
			'feature_request_title' => get_option('askany_feature_request_title', __('Request a feature', 'askany')),
			'feature_request_description' => get_option('askany_feature_request_description', __('What would you like to see next?', 'askany')),
			'feature_request_message' => get_option('askany_feature_request_message', __('What feature would you like to see next? Share your name, email and feature details so we can consider it for future updates.', 'askany')),
			// Integration settings
			'woocommerce_integration' => get_option('askany_woocommerce_integration', true),
			// Web Search settings
			'web_search_enabled' => (bool) get_option( 'askany_web_search_enabled', false ),
			'web_search_mode'    => get_option( 'askany_web_search_mode', 'fallback' ),
			// Response Tone
			'response_tone'      => get_option( 'askany_response_tone', 'human' ),
			// Typing Speed
			'typing_speed'       => get_option( 'askany_typing_speed', 'regular' ),
			'slack' => array(
				'enabled' => get_option('askany_slack_enabled', false),
				'webhook_url' => get_option('askany_slack_webhook_url', ''),
				'channel' => get_option('askany_slack_channel', '#general'),
				'notify_user_messages' => get_option('askany_slack_notify_user_messages', true),
				'forward_agent_messages' => get_option('askany_slack_forward_agent_messages', false),
				'forward_ai_messages' => get_option('askany_slack_forward_ai_messages', false),
			),
		);
	}

	/**
	 * Get OpenAI API key for RAG embeddings
	 */
	public function get_openai_api_key() {
		return $this->api_key_openai;
	}
	
	/**
	 * Get Gemini API key for RAG embeddings
	 */
	public function get_gemini_api_key() {
		return $this->api_key_gemini;
	}

	/**
	 * Test the current provider connection.
	 *
	 * @return array The connection test results.
	 */
	public function test_connection() {
		$provider = $this->get_provider();
		
		if ( ! $provider ) {
			return array(
				'status' => 'error',
				'message' => 'API provider not configured',
				'details' => 'Please configure your API key for the selected provider',
				'error_code' => 'missing_provider',
			);
		}

		return $provider->test_connection();
	}

	/**
	 * Test OpenAI connection (legacy method for backward compatibility).
	 *
	 * @return array The connection test results.
	 */
	public function test_openai_connection() {
		if ( empty($this->api_key_openai) ) {
			return array(
				'status' => 'error',
				'message' => 'OpenAI API key is not configured',
				'details' => 'Please set your OpenAI API key in the plugin settings',
				'error_code' => 'missing_key',
			);
		}

		$provider = ProviderFactory::create( 'openai', $this->api_key_openai, $this->api_url_openai );
		return $provider->test_connection();
	}

	/**
	 * Test DeepSeek connection (legacy method for backward compatibility).
	 *
	 * @return array The connection test results.
	 */
	public function test_deepseek_connection() {
		if ( empty($this->api_key_deepseek) ) {
			return array(
				'status' => 'error',
				'message' => 'DeepSeek API key is not configured',
				'details' => 'Please set your DeepSeek API key in the plugin settings',
			);
		}

		$provider = ProviderFactory::create( 'deepseek', $this->api_key_deepseek, $this->api_url_deepseek );
		return $provider->test_connection();
	}

	/**
	 * Test Gemini connection.
	 *
	 * @return array The connection test results.
	 */
	public function test_gemini_connection() {
		if ( empty($this->api_key_gemini) ) {
			return array(
				'status' => 'error',
				'message' => 'Google Gemini API key is not configured',
				'details' => 'Please set your Gemini API key in the plugin settings',
			);
		}

		$provider = ProviderFactory::create( 'gemini', $this->api_key_gemini, $this->api_url_gemini );
		if ( ! $provider ) {
			return array(
				'status' => 'error',
				'message' => 'Failed to create Gemini provider',
				'details' => 'Provider initialization failed',
			);
		}

		return $provider->test_connection();
	}

	/**
	 * Test API connections and return results.
	 *
	 * @return array The connection test results.
	 */
	public function test_api_connections() {
		return [
			'openai' => $this->test_openai_connection(),
			'deepseek' => $this->test_deepseek_connection(),
			'current_provider' => $this->api_provider,
			'api_enabled' => $this->api_enabled,
		];
	}

	/**
	 * Get conversation history for context.
	 *
	 * @param string $session_id The session ID.
	 * @return array The conversation history.
	 */
	private function get_conversation_history( $session_id ) {
		if ( empty($session_id) ) {
			return array();
		}

		global $wpdb;
		$messages_table = $wpdb->prefix . 'askany_chat_messages';

		// Get last 20 messages from this session for full context
		// This allows AI to learn from its mistakes and understand the full conversation flow
		$messages = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT sender_type, message, created_at 
				 FROM {$messages_table} 
				 WHERE session_id = %s 
				 ORDER BY created_at DESC 
				 LIMIT 20",
				$session_id
			)
		);

		if ( empty($messages) ) {
			return array();
		}

		// Reverse to get chronological order
		$messages = array_reverse($messages);
		
		$history = array();
		foreach ( $messages as $message ) {
			$role = ($message->sender_type === 'user') ? 'user' : 'assistant';
			$history[] = array(
				'role' => $role,
				'content' => $message->message,
				'timestamp' => $message->created_at
			);
		}

		return $history;
	}

	/**
	 * Check if the user query is asking about products.
	 *
	 * @param string $query The user query.
	 * @return bool True if the query is product-related, false otherwise.
	 */
	private function is_product_query( $query ) {
		$query_lower = strtolower($query);
		
		// Product-related keywords that indicate user is asking about products
		$product_keywords = array(
			// Direct product requests
			'product', 'products', 'item', 'items', 'buy', 'purchase', 'shop', 'shopping',
			'store', 'catalog', 'catalogue', 'merchandise', 'goods',
			
			// Product attributes
			'price', 'cost', 'expensive', 'cheap', 'affordable', 'budget',
			'stock', 'inventory', 'available', 'availability', 'in stock', 'out of stock',
			'sale', 'discount', 'offer', 'deal', 'promotion',
			
			// Product actions
			'add to cart', 'cart', 'checkout', 'order', 'shipping', 'delivery',
			'compare', 'review', 'rating', 'specification', 'specs',
			
			// Product categories (common ones)
			'clothing', 'electronics', 'books', 'accessories', 'shoes',
			'laptop', 'phone', 'computer', 'tablet', 'camera',
			
			// Question patterns
			'how much', 'what is the price', 'where can i buy', 'do you have',
			'show me', 'find me', 'looking for', 'need to buy', 'want to purchase'
		);
		
		// Check if any product keywords are present in the query
		foreach ( $product_keywords as $keyword ) {
			if ( strpos($query_lower, $keyword) !== false ) {
				return true;
			}
		}
		
		// Additional pattern matching for product-related questions
		if ( preg_match('/\b(what|where|how|can|do|show|find|get|buy|purchase)\b.*\b(product|item|price|cost|stock|available)\b/i', $query) ) {
			return true;
		}
		
		return false;
	}

	/**
	 * Get enhanced product context with detailed information.
	 *
	 * @param string $query The user query.
	 * @return array Enhanced product information.
	 */
	private function get_enhanced_product_context( $query ) {
		if ( ! class_exists('WooCommerce') ) {
			return array();
		}

		global $wpdb;
		$tables = $this->database->get_tables();
		$content_index_table = $tables['content_index'];

		// Search for products more intelligently
		$search_terms = explode(' ', strtolower($query));
		$valid_terms = array_filter($search_terms, function ( $term ) {
			return strlen($term) > 2; // Lower threshold for better matching
		});

		if ( empty($valid_terms) ) {
			return array();
		}

		$placeholders = array();
		$sql_parts = array();

		foreach ( $valid_terms as $term ) {
			$sql_parts[] = '(title LIKE %s OR content LIKE %s)';
			$placeholders[] = '%' . $wpdb->esc_like($term) . '%';
			$placeholders[] = '%' . $wpdb->esc_like($term) . '%';
		}

		$search_condition = '(' . implode(' OR ', $sql_parts) . ')';
		array_unshift($placeholders, 'product');

		$product_ids = $wpdb->get_col(
			$wpdb->prepare(
				"SELECT DISTINCT object_id FROM $content_index_table 
				 WHERE object_type = %s AND $search_condition 
				 ORDER BY updated_at DESC
				 LIMIT 5",
				$placeholders
			)
		);

		if ( empty($product_ids) ) {
			return array();
		}

		$products = array();
		foreach ( $product_ids as $product_id ) {
			$product = wc_get_product($product_id);
			if ( ! $product ) {
				continue;
			}

			// Get comprehensive product data with consistent naming
			$product_data = array(
				'id' => $product_id,
				'name' => $product->get_name(),
				'title' => $product->get_name(), // For backward compatibility
				'price' => $product->get_price(),
				'price_html' => $product->get_price_html(),
				'regular_price' => $product->get_regular_price(),
				'sale_price' => $product->get_sale_price(),
				'on_sale' => $product->is_on_sale(),
				'stock_status' => $product->get_stock_status(),
				'stock_quantity' => $product->get_stock_quantity(),
				'sku' => $product->get_sku(),
				'short_description' => wp_strip_all_tags($product->get_short_description()),
				'description' => wp_strip_all_tags($product->get_description()),
				'url' => get_permalink($product_id),
				'add_to_cart_url' => $product->add_to_cart_url(),
				'image_url' => wp_get_attachment_image_url($product->get_image_id(), 'medium'),
				'image' => wp_get_attachment_image_url($product->get_image_id(), 'medium'), // For backward compatibility
				'gallery_images' => array(),
				'categories' => array(),
				'tags' => array(),
				'attributes' => array(),
				'reviews_count' => $product->get_review_count(),
				'average_rating' => $product->get_average_rating(),
			);

			// Get product categories
			$categories = wp_get_post_terms($product_id, 'product_cat');
			foreach ( $categories as $category ) {
				$product_data['categories'][] = $category->name;
			}

			// Get product tags
			$tags = wp_get_post_terms($product_id, 'product_tag');
			foreach ( $tags as $tag ) {
				$product_data['tags'][] = $tag->name;
			}

			// Get product attributes
			$attributes = $product->get_attributes();
			foreach ( $attributes as $attribute ) {
				if ( $attribute->is_taxonomy() ) {
					$terms = wp_get_post_terms($product_id, $attribute->get_name());
					$values = array();
					foreach ( $terms as $term ) {
						$values[] = $term->name;
					}
					$product_data['attributes'][$attribute->get_name()] = implode(', ', $values);
				} else {
					$product_data['attributes'][$attribute->get_name()] = $attribute->get_options();
				}
			}

			// Get gallery images
			$gallery_ids = $product->get_gallery_image_ids();
			foreach ( $gallery_ids as $gallery_id ) {
				$product_data['gallery_images'][] = wp_get_attachment_image_url($gallery_id, 'medium');
			}

			$products[] = $product_data;
		}

		return $products;
	}

	/**
	 * Build enhanced system message with comprehensive context.
	 *
	 * @param string $relevant_content Website content.
	 * @param array $product_context Enhanced product information.
	 * @param array $conversation_history Previous conversation.
	 * @return string The enhanced system message.
	 */
	private function build_enhanced_system_message( $relevant_content, $product_context, $conversation_history, $web_search_mode = '' ) {
		$system_message = "";

		// ── 0. RESPONSE TONE — injected first so it governs the entire response ──
		$tone_settings = $this->get_settings();
		$response_tone = $tone_settings['response_tone'] ?? 'human';

		switch ( $response_tone ) {
			case 'human':
				$system_message .= "TONE INSTRUCTION: Respond like a real, helpful human being.\n";
				$system_message .= "- Write naturally and conversationally, as if texting a friend\n";
				$system_message .= "- NEVER start with phrases like \"Based on the website content\", \"I've reviewed\", \"According to the data\", or any AI-sounding opener\n";
				$system_message .= "- Just answer directly, warmly, and naturally\n";
				$system_message .= "- Use contractions (I'm, you'll, it's) and casual phrasing\n";
				$system_message .= "- Example: Instead of \"Based on the website content, the product costs $20\" → say \"It's $20!\"\n\n";
				break;
			case 'professional':
				$system_message .= "TONE INSTRUCTION: Respond in a professional, business-appropriate tone.\n";
				$system_message .= "- Be clear, precise, and formal without being stiff\n";
				$system_message .= "- NEVER start with \"Based on the website content\" or similar AI phrases\n";
				$system_message .= "- Get straight to the point with well-structured answers\n\n";
				break;
			case 'friendly':
				$system_message .= "TONE INSTRUCTION: Respond in a warm, enthusiastic, and friendly tone.\n";
				$system_message .= "- Be upbeat, encouraging, and positive\n";
				$system_message .= "- NEVER start with \"Based on the website content\" or similar AI phrases\n";
				$system_message .= "- Use emojis occasionally where appropriate\n";
				$system_message .= "- Make the user feel welcome and supported\n\n";
				break;
			case 'robotic':
				$system_message .= "TONE INSTRUCTION: Respond in a precise, factual, structured tone.\n";
				$system_message .= "- Be direct and data-focused\n";
				$system_message .= "- Use structured formatting with clear labels\n\n";
				break;
		}

		// ── 0. WEB SEARCH OVERRIDE — MUST BE FIRST ───────────────────────────────
		// This goes BEFORE everything else so the AI reads it first and follows it.
		// Website content comes after, but this instruction overrides the AI's default
		// "I can only help with this website" behaviour.
		if ( ! empty( $web_search_mode ) ) {
			$system_message .= "🚨 CRITICAL OVERRIDE — READ THIS FIRST BEFORE ANYTHING ELSE 🚨\n";
			$system_message .= "========================================================\n";
			$system_message .= "You are an AI assistant with FULL access to your own training knowledge.\n";
			$system_message .= "Web search mode is ACTIVE. You MUST follow these rules for EVERY response:\n\n";

			$system_message .= "✅ YOU MUST ALWAYS answer the user's question completely.\n";
			$system_message .= "✅ Use website content below when it is relevant.\n";
			$system_message .= "✅ For ANYTHING not in the website content, use YOUR OWN KNOWLEDGE to answer.\n\n";

			$system_message .= "🚫 YOU ARE FORBIDDEN from saying:\n";
			$system_message .= "   - \"I can only help with this website\"\n";
			$system_message .= "   - \"I don't have access to that\"\n";
			$system_message .= "   - \"I cannot browse the internet\"\n";
			$system_message .= "   - \"My knowledge base is focused on...\"\n";
			$system_message .= "   - \"I couldn't find information about X\"\n";
			$system_message .= "   - ANY phrase that suggests you are limited\n\n";

			if ( $web_search_mode === 'always' ) {
				$system_message .= "🔵 MODE = ALWAYS: For EVERY query, combine website content WITH your own knowledge.\n";
				$system_message .= "   Even if the website has an answer, ADD real-world context from your training.\n\n";
			} else {
				$system_message .= "🟢 MODE = FALLBACK: Try website content first. If not found there, answer from YOUR OWN KNOWLEDGE.\n";
				$system_message .= "   Never refuse. Never say you don't know. Just answer.\n\n";
			}

			$system_message .= "EXAMPLES OF CORRECT BEHAVIOUR:\n";
			$system_message .= "   User: \"tell me about wedevs\" → You know wedevs is a WordPress company. Answer from your knowledge.\n";
			$system_message .= "   User: \"what time is it in Tokyo\" → Answer from your knowledge about Tokyo timezone.\n";
			$system_message .= "   User: \"who is the CEO of Google\" → Answer from your training knowledge.\n";
			$system_message .= "========================================================\n\n";
		}

		// ── 1. LANGUAGE INSTRUCTION (highest priority — placed first) ─────────────
		if ( ! empty( $this->response_language ) && $this->response_language !== 'auto' ) {
			$language_names = array(
				'en' => 'English',
				'es' => 'Spanish (Español)',
				'fr' => 'French (Français)',
				'de' => 'German (Deutsch)',
				'it' => 'Italian (Italiano)',
				'pt' => 'Portuguese (Português)',
				'ru' => 'Russian (Русский)',
				'zh' => 'Chinese (中文)',
				'ja' => 'Japanese (日本語)',
				'ko' => 'Korean (한국어)',
				'ar' => 'Arabic (العربية)',
				'hi' => 'Hindi (हिन्दी)',
				'bn' => 'Bengali (বাংলা)',
				'tr' => 'Turkish (Türkçe)',
				'nl' => 'Dutch (Nederlands)',
				'pl' => 'Polish (Polski)',
				'sv' => 'Swedish (Svenska)',
				'vi' => 'Vietnamese (Tiếng Việt)',
				'th' => 'Thai (ไทย)',
				'id' => 'Indonesian (Bahasa Indonesia)',
			);

			$language_name = isset( $language_names[ $this->response_language ] )
				? $language_names[ $this->response_language ]
				: $this->response_language;

			$system_message .= "⚠️ CRITICAL LANGUAGE REQUIREMENT ⚠️\n";
			$system_message .= "YOU MUST RESPOND EXCLUSIVELY IN: {$language_name}\n";
			$system_message .= "This is a MANDATORY requirement. No matter what language the user writes in, your ENTIRE response must be in {$language_name}.\n";
			$system_message .= "Do NOT respond in English or any other language. ONLY {$language_name}.\n\n";
		}

		// ── 2. BASE IDENTITY ──────────────────────────────────────────────────────
		$system_message .= "You are an intelligent AI assistant embedded in a WordPress website. ";
		$system_message .= "You have access to comprehensive website content, indexed data, and your own extensive general knowledge. ";
		$system_message .= "Always provide helpful, accurate, and contextual responses.\n\n";

		// ── 3. CONVERSATION HISTORY ───────────────────────────────────────────────
		if ( ! empty( $conversation_history ) ) {
			$system_message .= "FULL CONVERSATION HISTORY (review previous responses and learn from any mistakes):\n";
			$system_message .= "IMPORTANT: If the user corrects you or asks for clarification, it means your previous response was not accurate.\n";
			$system_message .= "Always check the WEBSITE CONTENT section below to provide the most accurate answer.\n\n";

			foreach ( $conversation_history as $msg ) {
				$role = ucfirst( $msg['role'] );
				$system_message .= "{$role}: {$msg['content']}\n\n";
			}
		}

		// ── 4. WEBSITE CONTENT ────────────────────────────────────────────────────
		if ( ! empty( $relevant_content ) ) {
			$system_message .= "WEBSITE CONTENT:\n" . $relevant_content . "\n\n";
		}

		// ── 5. PRODUCT CONTEXT ────────────────────────────────────────────────────
		if ( ! empty( $product_context ) ) {
			$system_message .= "AVAILABLE PRODUCTS (detailed product cards will be shown separately):\n";
			foreach ( $product_context as $product ) {
				$system_message .= "- {$product['name']} ({$product['price_html']})";
				if ( $product['on_sale'] ) {
					$system_message .= " - ON SALE";
				}
				$system_message .= " - " . ucfirst( $product['stock_status'] );
				if ( ! empty( $product['short_description'] ) ) {
					$system_message .= " - " . substr( $product['short_description'], 0, 50 ) . "...";
				}
				$system_message .= "\n";
			}
			$system_message .= "\n";
		}

		// ── 6. CORE BEHAVIOURAL INSTRUCTIONS ─────────────────────────────────────
		$system_message .= "INSTRUCTIONS:\n";

		// Language reminder (repeat for emphasis when set)
		if ( ! empty( $this->response_language ) && $this->response_language !== 'auto' ) {
			$language_names_short = array(
				'en' => 'English', 'es' => 'Spanish', 'fr' => 'French', 'de' => 'German',
				'it' => 'Italian', 'pt' => 'Portuguese', 'ru' => 'Russian', 'zh' => 'Chinese',
				'ja' => 'Japanese', 'ko' => 'Korean', 'ar' => 'Arabic', 'hi' => 'Hindi',
				'bn' => 'Bengali', 'tr' => 'Turkish', 'nl' => 'Dutch', 'pl' => 'Polish',
				'sv' => 'Swedish', 'vi' => 'Vietnamese', 'th' => 'Thai', 'id' => 'Indonesian',
			);
			$lang_short = isset( $language_names_short[ $this->response_language ] )
				? $language_names_short[ $this->response_language ]
				: $this->response_language;
			$system_message .= "- ⚠️ REMEMBER: Respond ONLY in {$lang_short} — this is mandatory!\n";
		}

		$system_message .= "- 🎯 **LEARN FROM MISTAKES**: Review the full conversation history above\n";
		$system_message .= "- If user asks for clarification or says 'no that's not right', your previous response was incorrect\n";
		$system_message .= "- When corrected, acknowledge the mistake and provide the correct answer using WEBSITE CONTENT\n";
		$system_message .= "- Always cross-reference your responses with the WEBSITE CONTENT and AVAILABLE PRODUCTS sections\n";
		$system_message .= "- If you previously gave wrong information, apologize and correct it immediately\n";
		$system_message .= "- **IMPORTANT: Always format your responses using Markdown for better readability**\n";
		$system_message .= "- Use **bold** for emphasis, *italic* for subtle emphasis\n";
		$system_message .= "- Use bullet points (- or *) for lists\n";
		$system_message .= "- Use numbered lists (1. 2. 3.) for steps or ordered information\n";
		$system_message .= "- Use headings (## or ###) for sections when appropriate\n";
		$system_message .= "- When discussing products, be conversational and helpful\n";
		$system_message .= "- If products are available, mention them naturally and the system will display product cards automatically\n";
		$system_message .= "- If asking about product prices or details, provide the information from the AVAILABLE PRODUCTS list above\n";

		// ── 7. BEHAVIOUR INSTRUCTIONS ────────────────────────────────────────────
		if ( empty( $web_search_mode ) ) {
			// Web search DISABLED — standard behaviour
			$system_message .= "- Use the website content provided above to answer questions accurately\n";
			$system_message .= "- Be conversational and helpful, remembering previous parts of the conversation\n";
			$system_message .= "- If you don't have specific information in the site content, clearly state that and offer alternatives\n";
		} else {
			$system_message .= "- Use the website content above when relevant, and your own knowledge for everything else\n";
			$system_message .= "- Be conversational, confident, and helpful at all times\n";
			$system_message .= "- Do NOT mention RAG, indexed data, system context, or web search mode\n";
		}

		// ── 8. FORMATTING REMINDER ────────────────────────────────────────────────
		$system_message .= "\n- Keep responses well-formatted and easy to read using Markdown\n";
		$system_message .= "- Example good response: 'I found **3 great options** for you:\\n\\n1. **Product A** - Perfect for beginners\\n2. **Product B** - Best value\\n3. **Product C** - Premium choice'\n";

		return $system_message;
	}

	private function needs_internet_search( $ai_response, $query ) {
		$ai_response_lower = strtolower($ai_response);
		$query_lower = strtolower($query);
		
		// Phrases that indicate AI doesn't have the information
		$no_info_phrases = array(
			"i don't have",
			"i can't provide",
			"i'm sorry, but i can't",
			"i don't know",
			"i'm not sure",
			"i don't have access to",
			"i cannot provide",
			"i'm unable to",
			"i don't have information about",
			"i'm not able to",
			"i don't have current",
			"i don't have real-time",
			"i don't have up-to-date"
		);
		
		// Check if AI response contains any "no info" phrases
		foreach ( $no_info_phrases as $phrase ) {
			if ( strpos($ai_response_lower, $phrase) !== false ) {
				// Additional check: make sure it's not about products (we handle those separately)
				if ( ! $this->is_product_query($query) ) {
					return true;
				}
			}
		}
		
		// Specific queries that often need internet search
		$search_worthy_patterns = array(
			'current time', 'what time', 'time now',
			'current date', 'what date', 'today date',
			'weather', 'temperature',
			'news', 'latest news',
			'stock price', 'cryptocurrency',
			'exchange rate', 'currency',
			'current events',
			'what happened',
			'recent',
			'latest',
			'today',
			'now'
		);
		
		foreach ( $search_worthy_patterns as $pattern ) {
			if ( strpos($query_lower, $pattern) !== false ) {
				return true;
			}
		}
		
		return false;
	}
	
	/**
	 * Get internet search response using DuckDuckGo.
	 *
	 * @param string $query The user query.
	 * @param string $session_id Optional session ID for tracking.
	 * @return array|false The search response or false on failure.
	 */
	public function get_internet_search_response( $query, $session_id = '' ) {
		// First try to get search results
		$search_results = $this->search_duckduckgo($query);
		
		if ( empty($search_results) ) {
			return false;
		}
		
		// Use AI to synthesize the search results into a helpful response
		$search_context = $this->format_search_results_for_ai($search_results);
		$ai_response = $this->get_ai_response_with_search_context($query, $search_context, $session_id);
		
		if ( $ai_response ) {
			return array(
				'text' => $ai_response,
				'search_results' => $search_results,
				'source' => 'internet_search'
			);
		}
		
		// Fallback: format search results directly
		return array(
			'text' => $this->format_search_results_as_text($search_results, $query),
			'search_results' => $search_results,
			'source' => 'internet_search'
		);
	}
	
	/**
	 * Search DuckDuckGo for information.
	 *
	 * @param string $query The search query.
	 * @return array Search results or empty array on failure.
	 */
	private function search_duckduckgo( $query ) {
		// DuckDuckGo Instant Answer API
		$api_url = 'https://api.duckduckgo.com/';
		$params = array(
			'q' => $query,
			'format' => 'json',
			'no_html' => '1',
			'skip_disambig' => '1'
		);
		
		$url = $api_url . '?' . http_build_query($params);
		
		$args = array(
			'timeout' => 10,
			'headers' => array(
				'User-Agent' => 'AskAny WordPress Plugin/1.0'
			)
		);
		
		$response = wp_remote_get($url, $args);
		
		if ( is_wp_error($response) ) {
			return array();
		}
		
		$body = wp_remote_retrieve_body($response);
		$data = json_decode($body, true);
		
		if ( empty($data) ) {
			return array();
		}
		
		$results = array();
		
		// Check for instant answer
		if ( ! empty($data['Answer']) ) {
			$results[] = array(
				'type' => 'answer',
				'text' => $data['Answer'],
				'source' => $data['AnswerType'] ?? 'DuckDuckGo'
			);
		}
		
		// Check for abstract
		if ( ! empty($data['Abstract']) ) {
			$results[] = array(
				'type' => 'abstract',
				'text' => $data['Abstract'],
				'source' => $data['AbstractSource'] ?? 'Wikipedia',
				'url' => $data['AbstractURL'] ?? ''
			);
		}
		
		// Check for definition
		if ( ! empty($data['Definition']) ) {
			$results[] = array(
				'type' => 'definition',
				'text' => $data['Definition'],
				'source' => $data['DefinitionSource'] ?? 'Dictionary',
				'url' => $data['DefinitionURL'] ?? ''
			);
		}
		
		// Check for related topics
		if ( ! empty($data['RelatedTopics']) && is_array($data['RelatedTopics']) ) {
			foreach ( array_slice($data['RelatedTopics'], 0, 3) as $topic ) {
				if ( ! empty($topic['Text']) ) {
					$results[] = array(
						'type' => 'related',
						'text' => $topic['Text'],
						'url' => $topic['FirstURL'] ?? ''
					);
				}
			}
		}
		
		return $results;
	}
	
	/**
	 * Format search results for AI processing.
	 *
	 * @param array $search_results The search results.
	 * @return string Formatted search context.
	 */
	private function format_search_results_for_ai( $search_results ) {
		if ( empty($search_results) ) {
			return '';
		}
		
		$context = "INTERNET SEARCH RESULTS:\n\n";
		
		foreach ( $search_results as $result ) {
			$context .= "Source: " . ($result['source'] ?? 'Unknown') . "\n";
			$context .= "Content: " . $result['text'] . "\n";
			if ( ! empty($result['url']) ) {
				$context .= "URL: " . $result['url'] . "\n";
			}
			$context .= "\n";
		}
		
		return $context;
	}
	
	/**
	 * Get AI response with search context.
	 *
	 * @param string $query The original query.
	 * @param string $search_context The search results context.
	 * @param string $session_id Optional session ID.
	 * @return string|false The AI response or false on failure.
	 */
	private function get_ai_response_with_search_context( $query, $search_context, $session_id = '' ) {
		$system_message = "You are a helpful assistant. Use the provided internet search results to answer the user's question accurately and helpfully. ";
		$system_message .= "Cite sources when appropriate and provide a natural, conversational response.\n\n";
		$system_message .= $search_context;
		$system_message .= "\nINSTRUCTIONS:\n";
		$system_message .= "- Use the search results to provide an accurate answer\n";
		$system_message .= "- Be conversational and helpful\n";
		$system_message .= "- Mention the source when relevant\n";
		$system_message .= "- If the search results don't fully answer the question, say so\n";
		
		$conversation_history = $this->get_conversation_history($session_id);
		
		switch ( $this->api_provider ) {
			case 'openai':
				$response = $this->get_openai_response($query, $system_message, $session_id, $conversation_history, array());
				break;
			case 'deepseek':
			default:
				$response = $this->get_deepseek_response($query, $system_message, $session_id, $conversation_history, array());
				break;
		}
		
		return $response ? $response['text'] : false;
	}
	
	/**
	 * Format search results as plain text response.
	 *
	 * @param array $search_results The search results.
	 * @param string $query The original query.
	 * @return string Formatted text response.
	 */
	private function format_search_results_as_text( $search_results, $query ) {
		if ( empty($search_results) ) {
			return "I searched the internet but couldn't find specific information about your question. Could you try rephrasing it or asking something else?";
		}
		
		$response = "I found some information for you:\n\n";
		
		foreach ( $search_results as $index => $result ) {
			if ( $index > 0 ) {
				$response .= "\n";
			}
			
			$response .= $result['text'];
			
			if ( ! empty($result['source']) && $result['source'] !== 'DuckDuckGo' ) {
				$response .= " (Source: " . $result['source'] . ")";
			}
		}
		
		$response .= "\n\nIs there anything else you'd like to know?";
		
		return $response;
	}

	/**
	 * Test function for DuckDuckGo search - REMOVE AFTER TESTING
	 */
	public function test_duckduckgo_search( $query ) {
		$result = $this->get_search_enhanced_response( $query );
		return $result;
	}

	/**
	 * Test function to debug query classification - REMOVE AFTER TESTING
	 */
	public function test_query_classification( $query ) {
		
		// Test common response
		$common_response = $this->get_common_response($query);
		
		// Test query type
		$query_type = $this->analyze_query_type($query);
		
		// Test product query
		$is_product = $this->is_product_query($query);
		
		// Test search enhancement directly
		$search_result = $this->get_search_enhanced_response( $query );
		
		return array(
			'query' => $query,
			'common_response' => $common_response !== false,
			'query_type' => $query_type,
			'is_product_query' => $is_product,
			'search_result' => $search_result !== false ? substr($search_result, 0, 200) : false
		);
	}
}