';
});
// Add inline CSS to fix tooltip display issues in various themes
add_action('wp_head', function() {
if (!is_admin()) {
wp_add_inline_style('aipa-frontend-css', '
/* Global tooltip z-index fix */
.aipa-tooltip {
position: relative;
z-index: 9;
}
.aipa-tooltip .aipa-tooltip-text {
z-index: 999999 !important;
}');
}
});
}
/**
* Add explanation tooltip after product title
*/
public function add_explanation_tooltip() {
global $product;
if (!$product) {
return;
}
// Check if current product should display explanation
$product_id = $product->get_id();
$options = get_option('aipa_settings');
$show_explanation = isset($options['show_explanation']) ? $options['show_explanation'] : true;
$explanation_icon = isset($options['explanation_icon']) ? $options['explanation_icon'] : 'AIℹ️';
// Get explanation data from session
$explanations = WC()->session ? WC()->session->get('aipa_explanations') : array();
if ($show_explanation && is_array($explanations) && isset($explanations[$product_id])) {
echo '
';
echo '' . esc_html($explanation_icon) . ' ';
echo '' . esc_html($explanations[$product_id]) . ' ';
echo '
';
}
}
/**
* Enqueue necessary scripts and styles
*/
public function enqueue_scripts() {
if (!is_admin()) {
// Use high priority to ensure our styles are loaded last
wp_enqueue_style('aipa-frontend-css', AIPA_PLUGIN_URL . 'assets/css/frontend.css', array(), AIPA_VERSION, 'all');
// Ensure jQuery is loaded
wp_enqueue_script('jquery');
// Load other scripts
wp_enqueue_script('aipa-frontend-js', AIPA_PLUGIN_URL . 'assets/js/frontend.js', array('jquery'), AIPA_VERSION, true);
// Get options for customization
$options = get_option('aipa_settings');
// Default text values
$search_modal_title = isset($options['search_modal_title']) ? $options['search_modal_title'] : __('AI Product Search', 'ai-product-assistant');
$search_modal_description = isset($options['search_modal_description']) ? $options['search_modal_description'] : __('Describe what you\'re looking for in natural language.', 'ai-product-assistant');
$search_placeholder = isset($options['search_placeholder']) ? $options['search_placeholder'] : __('e.g., I need a waterproof jacket for hiking in rainy weather', 'ai-product-assistant');
$search_button_text = isset($options['search_button_text']) ? $options['search_button_text'] : __('Search with AI', 'ai-product-assistant');
$voice_button_text = isset($options['voice_button_text']) ? $options['voice_button_text'] : __('Voice Search', 'ai-product-assistant');
// Performance settings
$search_batch_size = isset($options['search_batch_size']) ? intval($options['search_batch_size']) : 100;
// Get max batches with dynamic default calculation
if (isset($options['max_batches'])) {
$max_batches = intval($options['max_batches']);
} else {
$product_count = (int) wp_count_posts('product')->publish;
$max_batches = $product_count > 0 ? ceil($product_count / $search_batch_size) : 1;
}
// Localize script with AJAX URL and other data
wp_localize_script('aipa-frontend-js', 'aipa_data', array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('aipa_nonce'),
'searching_text' => __('Searching...', 'ai-product-assistant'),
'search_placeholder' => $search_placeholder,
'search_button' => $search_button_text,
'search_modal_title' => $search_modal_title,
'search_modal_description' => $search_modal_description,
'error_message' => __('Something went wrong. Please try again.', 'ai-product-assistant'),
'empty_query_message' => __('Please enter a search query.', 'ai-product-assistant'),
'no_results_message' => __('No products found matching your description. Try being more specific or using different terms.', 'ai-product-assistant'),
'voice_search_not_supported' => __('Voice search is not supported in your browser.', 'ai-product-assistant'),
'voice_search_prompt' => __('Speak now...', 'ai-product-assistant'),
'voice_search_button' => $voice_button_text,
'deep_search_button' => __('Search More Products', 'ai-product-assistant'),
'login_url' => function_exists('wc_get_page_permalink') ? wc_get_page_permalink('myaccount') : wp_login_url(get_permalink()),
'login_text' => __('Log in here', 'ai-product-assistant'),
'deep_search_searching' => __('Searching More...', 'ai-product-assistant'),
'search_complete_message' => __('Search complete!', 'ai-product-assistant'),
'no_more_products_message' => __('No more products found matching your description.', 'ai-product-assistant'),
'aipa_service_error_message' => __('Sorry, AI feature is temporarily unavailable. Please try again later.', 'ai-product-assistant'),
'search_options' => array(
'batch_size' => $search_batch_size,
'max_batches' => $max_batches
)
));
// Add custom CSS for search button if set
$search_button_css = isset($options['search_button_css']) ? $options['search_button_css'] : '';
if (!empty($search_button_css)) {
// Output the complete CSS as provided by user (including selectors)
wp_add_inline_style('aipa-frontend-css', esc_html($search_button_css));
}
}
}
/**
* Add search modal to the website footer
*/
public function add_search_modal() {
// Get options
$options = get_option('aipa_settings');
// Default text values
$search_modal_title = isset($options['search_modal_title']) ? $options['search_modal_title'] : __('AI Product Search', 'ai-product-assistant');
$search_modal_description = isset($options['search_modal_description']) ? $options['search_modal_description'] : __('Describe what you\'re looking for in natural language.', 'ai-product-assistant');
$search_placeholder = isset($options['search_placeholder']) ? $options['search_placeholder'] : __('e.g., I need a waterproof jacket for hiking in rainy weather', 'ai-product-assistant');
$search_button_text = isset($options['search_button_text']) ? $options['search_button_text'] : __('Search with AI', 'ai-product-assistant');
$voice_button_text = isset($options['voice_button_text']) ? $options['voice_button_text'] : __('Voice Search', 'ai-product-assistant');
?>
';
} else {
$icon_html = esc_html($icon_text);
}
?>
__('Please log in to use AI search feature.', 'ai-product-assistant'),
'code' => 'auth_required'
));
}
$query = isset($_POST['query']) ? sanitize_text_field(wp_unslash($_POST['query'])) : '';
$batch_offset = isset($_POST['batch_offset']) ? intval($_POST['batch_offset']) : 0;
$deep_search = isset($_POST['deep_search']) ? filter_var(wp_unslash($_POST['deep_search']), FILTER_VALIDATE_BOOLEAN) : false;
$is_final_batch = isset($_POST['is_final_batch']) ? filter_var(wp_unslash($_POST['is_final_batch']), FILTER_VALIDATE_BOOLEAN) : false;
$search_session_key = isset($_POST['search_session_key']) ? sanitize_text_field(wp_unslash($_POST['search_session_key'])) : '';
AIPA_Debug::log(AIPA_Debug::LEVEL_INFO, 'Product_Search', 'AJAX search request received', array(
'query_length' => strlen($query),
'batch_offset' => $batch_offset,
'has_session_key' => !empty($search_session_key),
));
if (empty($query)) {
wp_send_json_error(array(
'message' => __('Please enter a search query.', 'ai-product-assistant')
));
}
// Get settings
$options = get_option('aipa_settings');
// Get max batches with dynamic default calculation
if (isset($options['max_batches'])) {
$max_batches = intval($options['max_batches']);
} else {
$batch_size = isset($options['search_batch_size']) ? intval($options['search_batch_size']) : 100;
$product_count = (int) wp_count_posts('product')->publish;
$max_batches = $product_count > 0 ? ceil($product_count / $batch_size) : 1;
}
// Force check batch range
if ($batch_offset >= $max_batches) {
$batch_offset = $max_batches - 1;
$is_final_batch = true;
}
// Make an internal request to the REST API
$request = new WP_REST_Request('POST', '/aipa/v1/search');
$request->set_param('query', $query);
$request->set_param('batch_offset', $batch_offset);
$request->set_param('deep_search', $deep_search);
$request->set_param('is_final_batch', $is_final_batch);
$request->set_param('search_session_key', $search_session_key);
$response = rest_do_request($request);
if (is_wp_error($response)) {
wp_send_json_error(array(
'message' => $response->get_error_message(),
'code' => $response->get_error_code()
));
}
$data = $response->get_data();
// Check if the response contains error information (from wp_send_json_error)
if (isset($data['code']) && isset($data['message'])) {
wp_send_json_error(array(
'message' => $data['message'],
'code' => $data['code']
));
return;
}
// Handle case when no products found, but don't return error
// Let frontend handle this situation appropriately
if (empty($data) || !isset($data['product_ids'])) {
// If deep search, still return success but with count=0
if ($deep_search) {
// Smart Search returns its own max_batches — use it so progress is accurate
$rest_meta = isset($data['meta']) ? $data['meta'] : array();
if (!empty($rest_meta['smart_search']) && isset($rest_meta['max_batches'])) {
$max_batches = intval($rest_meta['max_batches']);
}
$current_batch = $batch_offset + 1;
$progress_percentage = min(100, $current_batch * (100 / $max_batches));
$has_more_batches = ($current_batch < $max_batches);
// Generate deep search HTML even when no products found
$html = '';
if ($has_more_batches && !$is_final_batch) {
$html = $this->get_deep_search_html($progress_percentage, $batch_offset + 1, $max_batches);
}
wp_send_json_success(array(
'html' => $html,
'count' => 0,
'append' => $batch_offset > 0,
'meta' => array(
'current_batch' => $current_batch,
'max_batches' => $max_batches,
'progress' => $progress_percentage,
'has_more_batches' => $has_more_batches,
'next_batch_offset' => $batch_offset + 1,
'smart_search' => !empty($rest_meta['smart_search']),
)
));
} else {
// If not deep search, return error message
wp_send_json_error(array(
'message' => __('No products found matching your description.', 'ai-product-assistant')
));
}
return;
}
// Handle case when product IDs exist but are empty - same logic modification
if (empty($data['product_ids'])) {
// If deep search, still return success but with count=0
if ($deep_search) {
// Smart Search returns its own max_batches — use it so progress is accurate
$rest_meta = isset($data['meta']) ? $data['meta'] : array();
if (!empty($rest_meta['smart_search']) && isset($rest_meta['max_batches'])) {
$max_batches = intval($rest_meta['max_batches']);
}
$current_batch = $batch_offset + 1;
$progress_percentage = min(100, $current_batch * (100 / $max_batches));
$has_more_batches = ($current_batch < $max_batches);
// Generate deep search HTML even when no products found
$html = '';
if ($has_more_batches && !$is_final_batch) {
$html = $this->get_deep_search_html($progress_percentage, $batch_offset + 1, $max_batches);
}
wp_send_json_success(array(
'html' => $html,
'count' => 0,
'append' => $batch_offset > 0,
'search_session_key' => isset($rest_meta['search_session_key']) ? $rest_meta['search_session_key'] : '',
'meta' => array(
'current_batch' => $current_batch,
'max_batches' => $max_batches,
'progress' => $progress_percentage,
'has_more_batches' => $has_more_batches,
'next_batch_offset' => $batch_offset + 1,
'smart_search' => !empty($rest_meta['smart_search']),
)
));
} else {
// If not deep search, return error message
wp_send_json_error(array(
'message' => __('No products found matching your description.', 'ai-product-assistant')
));
}
return;
}
// Get options
$use_native_template = isset($options['use_native_template']) ? $options['use_native_template'] : true;
$show_explanation = isset($options['show_explanation']) ? $options['show_explanation'] : true;
// Get explanations
$explanations = isset($data['explanations']) ? $data['explanations'] : array();
// Get meta information
$meta = isset($data['meta']) ? $data['meta'] : array();
// Smart search returns its own max_batches based on candidate count — use it
if (!empty($meta['smart_search']) && isset($meta['max_batches'])) {
$max_batches = intval($meta['max_batches']);
} else {
$meta['max_batches'] = $max_batches;
}
// Determine if in append mode - first batch doesn't append, subsequent batches do
$append_results = $deep_search && $batch_offset > 0;
// Prepare the response
if ($use_native_template) {
// Use native WooCommerce template
$html = $this->get_products_html_native($data['product_ids'], $explanations, $show_explanation);
} else {
// Use custom template
$html = $this->get_products_html_custom($data['product_ids'], $explanations, $show_explanation);
}
// Add deep search UI if available and not final batch
if (!empty($meta['has_more_batches']) && !$is_final_batch) {
$progress = $meta['progress'];
$html .= $this->get_deep_search_html($progress, $meta['next_batch_offset'], $max_batches);
} else if ($is_final_batch || $batch_offset >= $max_batches - 1) {
// If this is the last batch, show completion message
$html .= '
Batch ' . $max_batches . ' of ' . $max_batches . ' completed - Search complete!
';
}
// Add debug information before returning success result (only when debug mode is enabled)
if (isset($_GET['aipa_debug']) && current_user_can('manage_options')) {
$current_batch = isset($meta['current_batch']) ? $meta['current_batch'] : ($batch_offset + 1);
$progress = isset($meta['progress']) ? $meta['progress'] : 0;
$has_more_batches = isset($meta['has_more_batches']) ? $meta['has_more_batches'] : false;
$html .= '
Debug Information
Batch Offset: ' . $batch_offset . '
Batch: ' . $current_batch . '/' . $max_batches . '
Progress: ' . $progress . '%
Has More Batches: ' . ($has_more_batches ? 'Yes' : 'No') . '
Next Batch Index: ' . (isset($meta['next_batch_offset']) ? $meta['next_batch_offset'] : 'N/A') . '
Is Final Batch: ' . ($is_final_batch ? 'Yes' : 'No') . '
Number of Product IDs: ' . count($data['product_ids']) . '
';
}
// Prepare response data
$response_data = array(
'html' => $html,
'count' => count($data['product_ids']),
'append' => $append_results,
'meta' => $meta,
'search_session_key' => isset($meta['search_session_key']) ? $meta['search_session_key'] : '',
);
wp_send_json_success($response_data);
}
/**
* Generate HTML for deep search UI
*/
private function get_deep_search_html($progress, $next_batch, $max_batches = null) {
// Use passed max_batches (Smart Search candidate-based) or fall back to settings
if ($max_batches === null) {
$options = get_option('aipa_settings');
$max_batches = isset($options['max_batches']) ? intval($options['max_batches']) : 5;
}
// Calculate current display batch from next_batch
$display_batch = $next_batch;
// Check if this is the last batch
$is_final_batch = ($display_batch >= $max_batches);
// Progress should be based on current batch number
// Progress percentage = (current batch / max batches) * 100
if (is_numeric($progress)) {
$progress_percentage = $progress;
} else {
// If progress is not a number, calculate based on batch
$progress_percentage = min(100, ($display_batch / $max_batches) * 100);
}
ob_start();
?>
' . __('No products found.', 'ai-product-assistant') . '';
return $output;
}
// Store explanation data in WooCommerce session for access in hooks
if (WC()->session && !empty($explanations)) {
WC()->session->set('aipa_explanations', $explanations);
}
// Add CSS styles using wp_add_inline_style
wp_add_inline_style('aipa-frontend-css', '
.aipa-explanation-icon {
display: inline-block;
cursor: help;
margin-left: 5px;
font-size: 16px;
color: #2196F3;
}
.aipa-tooltip {
position: relative;
display: inline-block;
}
.aipa-tooltip .aipa-tooltip-text {
visibility: hidden;
width: 250px;
background-color: #555;
color: #fff;
text-align: left;
border-radius: 6px;
padding: 10px;
position: absolute;
z-index: 1000;
bottom: 125%;
left: 50%;
transform: translateX(-50%);
opacity: 0;
transition: opacity 0.3s;
font-size: 14px;
line-height: 1.4;
box-shadow: 0 5px 15px rgba(0,0,0,0.2);
}
.aipa-tooltip .aipa-tooltip-text::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
}
.aipa-tooltip:hover .aipa-tooltip-text {
visibility: visible;
opacity: 1;
}
');
// Start products wrapper
$output .= '';
$output .= '
';
foreach ($product_ids as $product_id) {
$product = wc_get_product($product_id);
if (!$product) {
continue;
}
// Start buffering output
ob_start();
// Set the global product variable
global $post, $product;
$original_post = $post; // Save original $post value
$post = get_post($product_id);
setup_postdata($post);
// Ensure global $product variable is correctly set
$product = wc_get_product($product_id);
// Get the template part
wc_get_template_part('content', 'product');
// Get the buffered content
$output .= ob_get_clean();
// Restore original $post
$post = $original_post;
wp_reset_postdata();
}
$output .= ' ';
$output .= '
';
// Clear explanation data from session after completion
if (WC()->session) {
WC()->session->__unset('aipa_explanations');
}
return $output;
}
/**
* Get HTML for products using custom template with native tooltip implementation
*/
public function get_products_html_custom($product_ids, $explanations, $show_explanation = true, $show_add_to_cart = true) {
$output = '';
if (empty($product_ids)) {
$output .= '' . __('No products found.', 'ai-product-assistant') . '
';
return $output;
}
// Get custom icon settings
$options = get_option('aipa_settings');
$explanation_icon = isset($options['explanation_icon']) ? $options['explanation_icon'] : 'AIℹ️';
// Add CSS styles using wp_add_inline_style
wp_add_inline_style('aipa-frontend-css', '
/* Icon styles */
.aipa-explanation-icon {
display: inline-block;
cursor: help;
margin-left: 5px;
font-size: 16px;
color: #2196F3;
}
/* Global tooltip styles */
#aipa-global-tooltip {
position: absolute;
z-index: 9999999;
background-color: #555;
color: #fff;
padding: 10px;
border-radius: 6px;
font-size: 14px;
line-height: 1.4;
max-width: 300px;
box-shadow: 0 5px 15px rgba(0,0,0,0.3);
display: none;
text-align: left;
pointer-events: none;
}
/* Tooltip triangle */
#aipa-global-tooltip:after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
}
');
// Add JS to implement global tooltip
wp_enqueue_script('aipa-tooltip-js', AIPA_PLUGIN_URL . 'assets/js/tooltip.js', array('jquery'), AIPA_VERSION, true);
// Start products wrapper
$output .= '';
foreach ($product_ids as $product_id) {
$product = wc_get_product($product_id);
if (!$product) {
continue;
}
$output .= '
';
// Product image
$output .= '
';
// Product details
$output .= '
';
// Title
$output .= '
';
// Price
$output .= '
' . $product->get_price_html() . '
';
// Short description
if ($product->get_short_description()) {
$output .= '
' . wp_kses_post($product->get_short_description()) . '
';
}
// AI Explanation - displayed directly
if ($show_explanation && isset($explanations[$product_id])) {
$output .= '
';
$output .= '' . esc_html($explanation_icon) . ' ';
$output .= '' . esc_html($explanations[$product_id]) . ' ';
$output .= '
';
}
// Add to cart button
if ($show_add_to_cart) {
$output .= '
';
}
$output .= '
'; // End product details
$output .= '
'; // End product
}
$output .= '
'; // End products wrapper
return $output;
}
}