index_wp_content( $bot_id, $post_type ); case 'woo_product': return $this->index_woo_products( $bot_id ); default: return array( 'indexed' => 0, 'skipped' => 0, 'errors' => array( __( 'Unknown content type.', 'ai-marketing-expert' ) ) ); } } /* ══════════════════════════════════════════════════════ * WordPress Content (posts + pages) * ══════════════════════════════════════════════════════ */ private function index_wp_content( int $bot_id, string $post_type = '' ): array { global $wpdb; $p = $wpdb->prefix; $batch_limit = 200; // Get published posts/pages not yet indexed. $knowledge_table = $p . 'aime_chatbot_knowledge'; $already_indexed = $wpdb->get_col( $wpdb->prepare( "SELECT source_id FROM %i WHERE bot_id = %d AND type = 'wp_content' AND source_id IS NOT NULL", $knowledge_table, $bot_id ) ); $exclude_ids = array_values( array_filter( array_map( 'absint', (array) $already_indexed ) ) ); $exclude_ids = ! empty( $exclude_ids ) ? $exclude_ids : array( 0 ); $ex_holders = implode( ', ', array_fill( 0, count( $exclude_ids ), '%d' ) ); $type_list = $post_type ? array( sanitize_key( $post_type ) ) : array( 'post', 'page' ); $type_holders = implode( ', ', array_fill( 0, count( $type_list ), '%s' ) ); $args = array_merge( array( $wpdb->posts ), $type_list, $exclude_ids, array( $batch_limit ) ); $posts = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_title, post_content, post_excerpt, post_type FROM %i WHERE post_status = 'publish' AND post_type IN ({$type_holders}) AND ID NOT IN ({$ex_holders}) ORDER BY post_date DESC LIMIT %d", ...$args ) ); $indexed = 0; $errors = array(); $now = current_time( 'mysql', true ); foreach ( $posts as $post ) { $text = $this->extract_text( $post ); if ( empty( $text ) ) { continue; } $result = $wpdb->insert( "{$p}aime_chatbot_knowledge", array( 'bot_id' => $bot_id, 'type' => 'wp_content', 'source_id' => $post->ID, 'content' => $text, 'status' => 'active', 'last_indexed_at' => $now, 'metadata' => wp_json_encode( array( 'post_type' => $post->post_type, 'title' => $post->post_title, 'url' => get_permalink( $post->ID ), ) ), 'created_at' => $now, 'updated_at' => $now, ) ); if ( false !== $result ) { $indexed++; } else { $errors[] = sprintf( /* translators: %d: post ID */ __( 'Failed to index post #%d', 'ai-marketing-expert' ), $post->ID ); } } return array( 'indexed' => $indexed, 'skipped' => count( $already_indexed ), 'errors' => $errors, ); } /* ══════════════════════════════════════════════════════ * WooCommerce Products * ══════════════════════════════════════════════════════ */ private function index_woo_products( int $bot_id ): array { if ( ! class_exists( 'WooCommerce' ) ) { return array( 'indexed' => 0, 'skipped' => 0, 'errors' => array( __( 'WooCommerce is not active.', 'ai-marketing-expert' ) ), ); } global $wpdb; $p = $wpdb->prefix; $knowledge_table = $p . 'aime_chatbot_knowledge'; $already_indexed = $wpdb->get_col( $wpdb->prepare( "SELECT source_id FROM %i WHERE bot_id = %d AND type = 'woo_product' AND source_id IS NOT NULL", $knowledge_table, $bot_id ) ); $exclude_ids = array_values( array_filter( array_map( 'absint', (array) $already_indexed ) ) ); $exclude_ids = ! empty( $exclude_ids ) ? $exclude_ids : array( 0 ); $ex_holders = implode( ', ', array_fill( 0, count( $exclude_ids ), '%d' ) ); $args = array_merge( array( $wpdb->posts ), $exclude_ids ); $products = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_title, post_content, post_excerpt FROM %i WHERE post_status = 'publish' AND post_type = 'product' AND ID NOT IN ({$ex_holders}) ORDER BY post_date DESC LIMIT 500", ...$args ) ); $indexed = 0; $errors = array(); $now = current_time( 'mysql', true ); foreach ( $products as $product ) { $text = $this->extract_product_text( $product ); if ( empty( $text ) ) { continue; } $result = $wpdb->insert( "{$p}aime_chatbot_knowledge", array( 'bot_id' => $bot_id, 'type' => 'woo_product', 'source_id' => $product->ID, 'content' => $text, 'status' => 'active', 'last_indexed_at' => $now, 'metadata' => wp_json_encode( array( 'title' => $product->post_title, 'url' => get_permalink( $product->ID ), 'price' => get_post_meta( $product->ID, '_price', true ), 'sku' => get_post_meta( $product->ID, '_sku', true ), ) ), 'created_at' => $now, 'updated_at' => $now, ) ); if ( false !== $result ) { $indexed++; } else { $errors[] = sprintf( /* translators: %d: product ID */ __( 'Failed to index product #%d', 'ai-marketing-expert' ), $product->ID ); } } return array( 'indexed' => $indexed, 'skipped' => count( $already_indexed ), 'errors' => $errors, ); } /* ══════════════════════════════════════════════════════ * Single Post Re-index (called via cron on post save) * ══════════════════════════════════════════════════════ */ /** * Re-index a single post across all bots that have wp_content or woo_product knowledge. * * @param int $post_id WordPress post ID. */ public static function index_single_post( int $post_id ): void { global $wpdb; $p = $wpdb->prefix; $post = get_post( $post_id ); if ( ! $post || 'publish' !== $post->post_status ) { return; } $indexer = new self(); $is_product = ( 'product' === $post->post_type ); $type = $is_product ? 'woo_product' : 'wp_content'; $text = $is_product ? $indexer->extract_product_text( $post ) : $indexer->extract_text( $post ); $now = current_time( 'mysql', true ); // 1. Find all bots that already have this post indexed. $knowledge_table = $p . 'aime_chatbot_knowledge'; $existing = $wpdb->get_results( $wpdb->prepare( 'SELECT id, bot_id FROM %i WHERE source_id = %d AND type = %s', $knowledge_table, $post_id, $type ) ); if ( ! empty( $existing ) ) { foreach ( $existing as $entry ) { if ( $text ) { $wpdb->update( $knowledge_table, array( 'content' => $text, 'status' => 'active', 'last_indexed_at' => $now, 'updated_at' => $now, 'metadata' => wp_json_encode( array( 'post_type' => $post->post_type, 'title' => $post->post_title, 'url' => get_permalink( $post_id ), ) ), ), array( 'id' => $entry->id ) ); } else { // Content empty — deactivate. $wpdb->update( $knowledge_table, array( 'status' => 'inactive', 'updated_at' => $now ), array( 'id' => $entry->id ) ); } } return; } // 2. Newly published post: auto-insert into knowledge base for all active bots. if ( empty( $text ) ) { return; } $bots_table = $p . 'aime_chatbot_bots'; $active_bot_ids = $wpdb->get_col( $wpdb->prepare( 'SELECT id FROM %i WHERE status = %s', $bots_table, 'active' ) ); if ( empty( $active_bot_ids ) ) { return; } foreach ( $active_bot_ids as $bot_id ) { $already = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT id FROM %i WHERE bot_id = %d AND source_id = %d AND type = %s LIMIT 1', $knowledge_table, $bot_id, $post_id, $type ) ); if ( ! $already ) { $wpdb->insert( "{$p}aime_chatbot_knowledge", array( 'bot_id' => (int) $bot_id, 'type' => $type, 'source_id' => $post_id, 'content' => $text, 'status' => 'active', 'last_indexed_at' => $now, 'metadata' => wp_json_encode( array( 'post_type' => $post->post_type, 'title' => $post->post_title, 'url' => get_permalink( $post_id ), ) ), 'created_at' => $now, 'updated_at' => $now, ) ); } } } /** * Remove knowledge base entries when a post or product is deleted. * * @param int $post_id WordPress post ID. */ public static function remove_post_knowledge( int $post_id ): void { global $wpdb; $p = $wpdb->prefix; $wpdb->delete( "{$p}aime_chatbot_knowledge", array( 'source_id' => $post_id ), array( '%d' ) ); } /* ── Text extraction helpers ─────────────────────── */ private function extract_text( $post ): string { $parts = array(); if ( ! empty( $post->post_title ) ) { $parts[] = $post->post_title; } $content = wp_strip_all_tags( $post->post_content ); $content = preg_replace( '/\s+/', ' ', $content ); $content = trim( $content ); if ( ! empty( $content ) ) { // Limit to ~2000 words for knowledge entry. $words = explode( ' ', $content ); if ( count( $words ) > 2000 ) { $content = implode( ' ', array_slice( $words, 0, 2000 ) ); } $parts[] = $content; } if ( ! empty( $post->post_excerpt ) ) { $parts[] = 'Summary: ' . wp_strip_all_tags( $post->post_excerpt ); } return implode( "\n\n", $parts ); } private function extract_product_text( $product ): string { $parts = array(); $parts[] = 'Product: ' . $product->post_title; $price = get_post_meta( $product->ID, '_price', true ); if ( $price ) { $parts[] = 'Price: ' . $price; } $sku = get_post_meta( $product->ID, '_sku', true ); if ( $sku ) { $parts[] = 'SKU: ' . $sku; } $short = wp_strip_all_tags( $product->post_excerpt ); if ( $short ) { $parts[] = $short; } $long = wp_strip_all_tags( $product->post_content ); $long = preg_replace( '/\s+/', ' ', trim( $long ) ); if ( $long ) { $words = explode( ' ', $long ); if ( count( $words ) > 500 ) { $long = implode( ' ', array_slice( $words, 0, 500 ) ); } $parts[] = $long; } // Product categories. $terms = wp_get_post_terms( $product->ID, 'product_cat', array( 'fields' => 'names' ) ); if ( ! is_wp_error( $terms ) && $terms ) { $parts[] = 'Categories: ' . implode( ', ', $terms ); } return implode( "\n", $parts ); } }