maybe_create_tables(); // Dashboard stats filter. add_filter( 'aime_chatbot_dashboard_stats', array( $this, 'get_stats' ) ); // Frontend widget rendering. add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_widget_assets' ) ); add_action( 'wp_footer', array( $this, 'render_widget' ) ); // Cron jobs. if ( ! wp_next_scheduled( 'aime_chatbot_daily_cleanup' ) ) { wp_schedule_event( time(), 'daily', 'aime_chatbot_daily_cleanup' ); } add_action( 'aime_chatbot_daily_cleanup', array( $this, 'daily_cleanup' ) ); // Auto-index on post save (Knowledge Base real-time sync). add_action( 'save_post', array( $this, 'on_post_save' ), 20, 2 ); add_action( 'aime_chatbot_index_post', array( Services\KnowledgeIndexer::class, 'index_single_post' ) ); add_action( 'before_delete_post', array( Services\KnowledgeIndexer::class, 'remove_post_knowledge' ) ); // Public discussions shortcode. add_shortcode( 'aime_discussions', array( $this, 'render_discussions_shortcode' ) ); add_action( 'wp_enqueue_scripts', array( $this, 'maybe_enqueue_discussions_css' ) ); } /* ── REST routes ─────────────────────────────────────── */ public function register_routes(): void { $controller = new ChatbotRestController(); $controller->register_routes(); } /* ── Database tables ─────────────────────────────────── */ private function maybe_create_tables(): void { $installed = get_option( 'aime_chatbot_db_version', '' ); if ( version_compare( $installed, AIME_CHATBOT_DB_VERSION, '>=' ) ) { return; } global $wpdb; $charset = $wpdb->get_charset_collate(); $this->create_tables( $charset ); update_option( 'aime_chatbot_db_version', AIME_CHATBOT_DB_VERSION ); } public function create_tables( string $charset_collate ): void { global $wpdb; $p = $wpdb->prefix; if ( ! function_exists( 'dbDelta' ) ) { require_once ABSPATH . 'wp-admin/includes/upgrade.php'; } // Chatbot instances. dbDelta( "CREATE TABLE {$p}aime_chatbot_bots ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, name varchar(255) NOT NULL, status varchar(20) NOT NULL DEFAULT 'inactive', system_prompt longtext, welcome_message text, theme_id varchar(50) NOT NULL DEFAULT 'default', theme_config longtext, lead_capture_config longtext, knowledge_config longtext, offline_message text, business_hours longtext, banned_words text, page_rules longtext, created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id), KEY idx_status (status) ) $charset_collate;" ); // Conversations. dbDelta( "CREATE TABLE {$p}aime_chatbot_conversations ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, bot_id bigint(20) unsigned NOT NULL, visitor_id varchar(64) NOT NULL, visitor_name varchar(100) DEFAULT NULL, visitor_email varchar(255) DEFAULT NULL, visitor_ip varchar(45) DEFAULT NULL, status varchar(20) NOT NULL DEFAULT 'active', agent_id bigint(20) unsigned DEFAULT NULL, lead_captured tinyint(1) NOT NULL DEFAULT 0, is_public tinyint(1) NOT NULL DEFAULT 0, satisfaction_rating tinyint(3) unsigned DEFAULT NULL, source varchar(20) NOT NULL DEFAULT 'widget', page_url text, user_agent text, metadata longtext, started_at datetime DEFAULT NULL, ended_at datetime DEFAULT NULL, created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id), KEY idx_bot (bot_id), KEY idx_visitor (visitor_id), KEY idx_status (status), KEY idx_created (created_at), KEY idx_public (is_public) ) $charset_collate;" ); // Messages. dbDelta( "CREATE TABLE {$p}aime_chatbot_messages ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, conversation_id bigint(20) unsigned NOT NULL, sender_type varchar(20) NOT NULL, sender_id varchar(100) DEFAULT NULL, content text NOT NULL, content_type varchar(20) NOT NULL DEFAULT 'text', metadata longtext, is_read tinyint(1) NOT NULL DEFAULT 0, created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id), KEY idx_conversation (conversation_id), KEY idx_sender_type (sender_type), KEY idx_created (created_at) ) $charset_collate;" ); // Knowledge base. dbDelta( "CREATE TABLE {$p}aime_chatbot_knowledge ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, bot_id bigint(20) unsigned NOT NULL, type varchar(30) NOT NULL, source_id bigint(20) unsigned DEFAULT NULL, question text, answer text, content longtext, status varchar(20) NOT NULL DEFAULT 'active', last_indexed_at datetime DEFAULT NULL, metadata longtext, created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id), KEY idx_bot (bot_id), KEY idx_type (type), KEY idx_status (status), KEY idx_source (source_id) ) $charset_collate;" ); // Analytics (aggregated daily). dbDelta( "CREATE TABLE {$p}aime_chatbot_analytics ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, bot_id bigint(20) unsigned NOT NULL, date date NOT NULL, total_conversations int(11) NOT NULL DEFAULT 0, total_messages int(11) NOT NULL DEFAULT 0, ai_messages int(11) NOT NULL DEFAULT 0, human_messages int(11) NOT NULL DEFAULT 0, visitor_messages int(11) NOT NULL DEFAULT 0, leads_captured int(11) NOT NULL DEFAULT 0, human_takeovers int(11) NOT NULL DEFAULT 0, avg_satisfaction decimal(3,2) DEFAULT NULL, avg_response_time_ms int(11) DEFAULT NULL, total_tokens_used int(11) NOT NULL DEFAULT 0, unique_visitors int(11) NOT NULL DEFAULT 0, top_topics longtext, created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id), UNIQUE KEY idx_bot_date (bot_id, date), KEY idx_date (date) ) $charset_collate;" ); // Conversations must never be public unless an admin explicitly publishes // them. dbDelta does not reliably change an existing column's DEFAULT, so // enforce it directly for installs upgrading from the old DEFAULT 1 schema. // Existing rows are left untouched to preserve any admin-published state. $conversations_table = $p . 'aime_chatbot_conversations'; $wpdb->query( $wpdb->prepare( 'ALTER TABLE %i MODIFY is_public tinyint(1) NOT NULL DEFAULT 0', $conversations_table ) ); } /* ── Public Discussions Shortcode ────────────────────── */ public function maybe_enqueue_discussions_css(): void { global $post; if ( ! $post || ! has_shortcode( $post->post_content, 'aime_discussions' ) ) { return; } wp_enqueue_style( 'aime-discussions', AIME_PLUGIN_URL . 'assets/css/discussions.css', array(), aime_asset_version() ); } public function render_discussions_shortcode( $atts ): string { $atts = shortcode_atts( array( 'per_page' => 10, 'bot_id' => 0, ), $atts, 'aime_discussions' ); global $wpdb; $p = $wpdb->prefix; $per_page = max( 1, min( 50, absint( $atts['per_page'] ) ) ); $bot_id = absint( $atts['bot_id'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Public shortcode pagination parameter for front-end discussion browsing; no state change occurs. $paged = max( 1, absint( $_GET['aime_page'] ?? 1 ) ); $offset = ( $paged - 1 ) * $per_page; // Check if viewing a single conversation. // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Public shortcode conversation selector for read-only discussion display. $conv_id = absint( $_GET['aime_conv'] ?? 0 ); if ( $conv_id ) { return $this->render_single_discussion( $conv_id ); } $cache_key = self::build_cache_key( 'public_discussions', array( 'per_page' => $per_page, 'bot_id' => $bot_id, 'paged' => $paged, ) ); $cached = wp_cache_get( $cache_key, self::CACHE_GROUP ); if ( false !== $cached ) { return (string) $cached; } $conv_table = $p . 'aime_chatbot_conversations'; $msg_table = $p . 'aime_chatbot_messages'; $bot_table = $p . 'aime_chatbot_bots'; if ( $bot_id ) { $total = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i c WHERE c.is_public = 1 AND EXISTS (SELECT 1 FROM %i vm WHERE vm.conversation_id = c.id AND vm.sender_type = %s) AND c.bot_id = %d', $conv_table, $msg_table, 'visitor', $bot_id ) ); $items = $wpdb->get_results( $wpdb->prepare( 'SELECT c.id, c.visitor_name, c.status, c.created_at, b.name AS bot_name, (SELECT COUNT(*) FROM %i m WHERE m.conversation_id = c.id AND m.sender_type IN (\'visitor\',\'ai\',\'agent\')) AS message_count, (SELECT m2.content FROM %i m2 WHERE m2.conversation_id = c.id AND m2.sender_type = %s ORDER BY m2.id ASC LIMIT 1) AS first_message FROM %i c LEFT JOIN %i b ON b.id = c.bot_id WHERE c.is_public = 1 AND EXISTS (SELECT 1 FROM %i vm WHERE vm.conversation_id = c.id AND vm.sender_type = %s) AND c.bot_id = %d ORDER BY c.created_at DESC LIMIT %d OFFSET %d', $msg_table, $msg_table, 'visitor', $conv_table, $bot_table, $msg_table, 'visitor', $bot_id, $per_page, $offset ) ); } else { $total = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i c WHERE c.is_public = 1 AND EXISTS (SELECT 1 FROM %i vm WHERE vm.conversation_id = c.id AND vm.sender_type = %s)', $conv_table, $msg_table, 'visitor' ) ); $items = $wpdb->get_results( $wpdb->prepare( 'SELECT c.id, c.visitor_name, c.status, c.created_at, b.name AS bot_name, (SELECT COUNT(*) FROM %i m WHERE m.conversation_id = c.id AND m.sender_type IN (\'visitor\',\'ai\',\'agent\')) AS message_count, (SELECT m2.content FROM %i m2 WHERE m2.conversation_id = c.id AND m2.sender_type = %s ORDER BY m2.id ASC LIMIT 1) AS first_message FROM %i c LEFT JOIN %i b ON b.id = c.bot_id WHERE c.is_public = 1 AND EXISTS (SELECT 1 FROM %i vm WHERE vm.conversation_id = c.id AND vm.sender_type = %s) ORDER BY c.created_at DESC LIMIT %d OFFSET %d', $msg_table, $msg_table, 'visitor', $conv_table, $bot_table, $msg_table, 'visitor', $per_page, $offset ) ); } $total_pages = max( 1, (int) ceil( $total / $per_page ) ); $current_url = remove_query_arg( array( 'aime_page', 'aime_conv' ) ); ob_start(); ?>

visitor_name ? esc_html( $item->visitor_name ) : esc_html__( 'Anonymous', 'ai-marketing-expert' ); $date = date_i18n( get_option( 'date_format' ), strtotime( $item->created_at ) ); $preview = $item->first_message ? esc_html( wp_trim_words( $item->first_message, 25, '…' ) ) : '—'; $link = esc_url( add_query_arg( 'aime_conv', $item->id, $current_url ) ); $msg_count = absint( $item->message_count ); $status_label = 'closed' === $item->status ? esc_html__( 'Resolved', 'ai-marketing-expert' ) : esc_html__( 'Open', 'ai-marketing-expert' ); $status_class = 'closed' === $item->status ? 'resolved' : 'open'; ?>
1 ) : ?>
prefix; $cache_key = self::build_cache_key( 'single_discussion', array( 'conv_id' => $conv_id ) ); $cached = wp_cache_get( $cache_key, self::CACHE_GROUP ); if ( false !== $cached ) { return (string) $cached; } $conv_table = $p . 'aime_chatbot_conversations'; $bot_table = $p . 'aime_chatbot_bots'; $msg_table = $p . 'aime_chatbot_messages'; $conversation = $wpdb->get_row( $wpdb->prepare( 'SELECT c.id, c.visitor_name, c.status, c.created_at, b.name AS bot_name FROM %i c LEFT JOIN %i b ON b.id = c.bot_id WHERE c.id = %d AND c.is_public = 1', $conv_table, $bot_table, $conv_id ) ); if ( ! $conversation ) { return '

' . esc_html__( 'Discussion not found.', 'ai-marketing-expert' ) . '

'; } $messages = $wpdb->get_results( $wpdb->prepare( 'SELECT sender_type, content, created_at FROM %i WHERE conversation_id = %d AND sender_type IN (\'visitor\',\'ai\',\'agent\') ORDER BY created_at ASC', $msg_table, $conv_id ) ); // Remove the first AI welcome message so thread starts with the visitor. if ( ! empty( $messages ) && 'ai' === $messages[0]->sender_type ) { array_shift( $messages ); } $visitor = $conversation->visitor_name ? esc_html( $conversation->visitor_name ) : esc_html__( 'Anonymous', 'ai-marketing-expert' ); $date = date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $conversation->created_at ) ); $back_url = esc_url( remove_query_arg( 'aime_conv' ) ); $sender_labels = array( 'visitor' => $visitor, 'ai' => $conversation->bot_name ? esc_html( $conversation->bot_name ) : esc_html__( 'AI Assistant', 'ai-marketing-expert' ), 'agent' => esc_html__( 'Support Agent', 'ai-marketing-expert' ), ); ob_start(); ?>
«

sender_type ); $sender_name = $sender_labels[ $msg->sender_type ] ?? esc_html__( 'Unknown', 'ai-marketing-expert' ); $msg_date = date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $msg->created_at ) ); ?>
content ) ); ?>
prefix; $cache_key = self::build_cache_key( 'stats' ); $cached = wp_cache_get( $cache_key, self::CACHE_GROUP ); if ( false !== $cached ) { return $cached; } $table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', "{$p}aime_chatbot_conversations" ) ); if ( ! $table_exists ) { $empty = array( 'total_conversations' => 0, 'active_conversations' => 0, 'total_messages' => 0, 'leads_captured' => 0, 'total_bots' => 0, ); wp_cache_set( $cache_key, $empty, self::CACHE_GROUP, self::CACHE_TTL ); return $empty; } $conv_table = $p . 'aime_chatbot_conversations'; $msg_table = $p . 'aime_chatbot_messages'; $bot_table = $p . 'aime_chatbot_bots'; $stats = array( 'total_conversations' => (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i c WHERE EXISTS (SELECT 1 FROM %i mv WHERE mv.conversation_id = c.id AND mv.sender_type = %s)', $conv_table, $msg_table, 'visitor' ) ), 'active_conversations' => (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i c WHERE c.status = %s AND EXISTS (SELECT 1 FROM %i mv WHERE mv.conversation_id = c.id AND mv.sender_type = %s)', $conv_table, 'active', $msg_table, 'visitor' ) ), 'total_messages' => (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i WHERE sender_type != %s', $msg_table, 'system' ) ), 'leads_captured' => (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i c WHERE c.lead_captured = %d AND EXISTS (SELECT 1 FROM %i mv WHERE mv.conversation_id = c.id AND mv.sender_type = %s)', $conv_table, 1, $msg_table, 'visitor' ) ), 'total_bots' => (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i', $bot_table ) ), ); wp_cache_set( $cache_key, $stats, self::CACHE_GROUP, self::CACHE_TTL ); return $stats; } /* ── Monthly conversation count (for free limit check) ─ */ public static function get_monthly_conversation_count(): int { global $wpdb; $p = $wpdb->prefix; $cache_key = self::build_cache_key( 'monthly_conversation_count', array( 'month' => gmdate( 'Y-m' ) ) ); $cached = wp_cache_get( $cache_key, self::CACHE_GROUP ); if ( false !== $cached ) { return (int) $cached; } $table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', "{$p}aime_chatbot_conversations" ) ); if ( ! $table_exists ) { return 0; } $count = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i WHERE created_at >= %s', $p . 'aime_chatbot_conversations', gmdate( 'Y-m-01 00:00:00' ) ) ); wp_cache_set( $cache_key, $count, self::CACHE_GROUP, self::CACHE_TTL ); return $count; } /* ── Frontend widget ─────────────────────────────────── */ public function enqueue_widget_assets(): void { // Don't load on admin pages. if ( is_admin() ) { return; } // Check if there's an active bot. $bot = $this->get_active_frontend_bot(); if ( ! $bot ) { return; } // Check page rules. if ( ! $this->should_show_on_page( $bot ) ) { return; } $asset_file = AIME_PLUGIN_DIR . 'build/chatbot-widget.asset.php'; $asset = file_exists( $asset_file ) ? include $asset_file : array( 'dependencies' => array(), 'version' => AIME_VERSION, ); $version = aime_asset_version( $asset['version'] ?? AIME_VERSION ); wp_enqueue_script( 'aime-chatbot-widget', AIME_PLUGIN_URL . 'build/chatbot-widget.js', $asset['dependencies'], $version, true ); if ( file_exists( AIME_PLUGIN_DIR . 'build/chatbot-widget.css' ) ) { wp_enqueue_style( 'aime-chatbot-widget', AIME_PLUGIN_URL . 'build/chatbot-widget.css', array(), $version ); } // Generate or retrieve visitor UUID. $visitor_id = ''; if ( isset( $_COOKIE['aime_visitor_id'] ) ) { $visitor_id = sanitize_text_field( wp_unslash( $_COOKIE['aime_visitor_id'] ) ); } $theme_config = json_decode( $bot->theme_config ?: '{}', true ) ?: array(); $lead_config = json_decode( $bot->lead_capture_config ?: '{}', true ) ?: array(); // Merge global chatbot settings (needed for theme fallback and widget settings). $global_settings = get_option( 'aime_chatbot_settings', array() ); // Resolve effective theme: per-bot theme_id takes priority, otherwise fall back // to the global default_theme setting from Chatbot → Settings. $effective_theme = $bot->theme_id ?: 'default'; if ( 'default' === $effective_theme && ! empty( $global_settings['default_theme'] ) ) { $effective_theme = $global_settings['default_theme']; } // Resolve theme preset colours and merge with any custom overrides. $theme_preset = Services\WidgetService::get_theme( $effective_theme ); $theme_config = array_merge( $theme_preset, $theme_config ); $global_defaults = array( 'enable_sound_notification' => true, 'poll_interval_seconds' => 5, 'max_message_length' => 500, 'consent_message' => __( 'We use cookies and chat data to provide you with the best support experience. By starting this chat, you consent to our collection and use of this data in accordance with our Privacy Policy. You can end the chat at any time.', 'ai-marketing-expert' ), 'gdpr_enabled' => true, 'enable_typing_indicator' => true, 'enable_read_receipts' => true, ); $gs = array_merge( $global_defaults, $global_settings ); // Inject global settings into theme_config (widget reads them from themeConfig). $theme_config['sound_enabled'] = ! empty( $gs['enable_sound_notification'] ); $theme_config['poll_interval'] = (int) ( $gs['poll_interval_seconds'] ?? 5 ); $theme_config['max_message_length'] = (int) ( $gs['max_message_length'] ?? 500 ); $theme_config['gdpr_enabled'] = ! isset( $gs['gdpr_enabled'] ) || ! empty( $gs['gdpr_enabled'] ); $theme_config['consent_message'] = $gs['consent_message'] ?? ''; $theme_config['enable_typing_indicator'] = ! empty( $gs['enable_typing_indicator'] ); $theme_config['enable_read_receipts'] = ! empty( $gs['enable_read_receipts'] ); wp_localize_script( 'aime-chatbot-widget', 'aimeChatbot', array( 'restUrl' => rest_url( aime_rest_namespace() . '/chatbot/public' ), 'nonce' => wp_create_nonce( 'wp_rest' ), 'botId' => (int) $bot->id, 'botName' => $bot->name, 'welcomeMsg' => $bot->welcome_message ?: __( 'Hi! How can I help you today?', 'ai-marketing-expert' ), 'offlineMsg' => $bot->offline_message ?: '', 'themeId' => $effective_theme, 'themeConfig' => $theme_config, 'leadConfig' => $lead_config, 'visitorId' => $visitor_id, 'businessHours' => json_decode( $bot->business_hours ?: '{}', true ) ?: array(), 'siteUrl' => home_url(), 'siteName' => get_bloginfo( 'name' ), ) ); } public function render_widget(): void { if ( is_admin() ) { return; } $bot = $this->get_active_frontend_bot(); if ( ! $bot ) { return; } if ( ! $this->should_show_on_page( $bot ) ) { return; } echo '
'; } /* ── Helper: get active bot for frontend ─────────── */ private function get_active_frontend_bot(): ?object { global $wpdb; $p = $wpdb->prefix; $cache_key = self::build_cache_key( 'active_frontend_bot' ); $cached = wp_cache_get( $cache_key, self::CACHE_GROUP ); if ( false !== $cached ) { return $cached ?: null; } $table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', "{$p}aime_chatbot_bots" ) ); if ( ! $table_exists ) { return null; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery $bot = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM %i WHERE status = %s ORDER BY id ASC LIMIT 1", $wpdb->prefix . 'aime_chatbot_bots', 'active' ) ); wp_cache_set( $cache_key, $bot ?: null, self::CACHE_GROUP, self::CACHE_TTL ); return $bot ?: null; } /* ── Helper: check page rules ────────────────────── */ private function should_show_on_page( object $bot ): bool { $rules = json_decode( $bot->page_rules ?: '[]', true ); if ( empty( $rules ) ) { return true; // No rules = show everywhere. } $current_path = wp_parse_url( home_url( add_query_arg( null, null ) ), PHP_URL_PATH ) ?: '/'; $is_list = array_keys( $rules ) === range( 0, count( $rules ) - 1 ); if ( $is_list ) { $has_include = false; $included = false; foreach ( $rules as $rule ) { $type = $rule['type'] ?? 'include'; $pattern = $rule['pattern'] ?? ''; if ( '' === $pattern ) { continue; } $matches = fnmatch( $pattern, $current_path ) || fnmatch( $pattern, '/' . ltrim( $current_path, '/' ) ); if ( 'exclude' === $type && $matches ) { return false; } if ( 'include' === $type ) { $has_include = true; if ( $matches ) { $included = true; } } } return $has_include ? $included : true; } if ( empty( $rules['mode'] ) ) { return true; } $current_url = home_url( add_query_arg( null, null ) ); $pages = $rules['pages'] ?? array(); if ( 'show_on' === $rules['mode'] ) { if ( empty( $pages ) ) { return true; } foreach ( $pages as $page_pattern ) { if ( fnmatch( $page_pattern, $current_url ) ) { return true; } } return false; } if ( 'hide_on' === $rules['mode'] ) { foreach ( $pages as $page_pattern ) { if ( fnmatch( $page_pattern, $current_url ) ) { return false; } } return true; } return true; } /* ── Post save hook (auto-index content) ─────────── */ public function on_post_save( int $post_id, \WP_Post $post ): void { if ( wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ) ) { return; } if ( 'publish' !== $post->post_status ) { return; } $settings = get_option( 'aime_chatbot_settings', array() ); $auto_sync = ! isset( $settings['auto_sync_knowledge'] ) || ! empty( $settings['auto_sync_knowledge'] ); if ( ! $auto_sync ) { return; } $allowed_types = array( 'post', 'page' ); if ( class_exists( 'WooCommerce' ) ) { $allowed_types[] = 'product'; } if ( ! in_array( $post->post_type, $allowed_types, true ) ) { return; } // Schedule background re-index or trigger so it doesn't slow down the save. if ( ! wp_next_scheduled( 'aime_chatbot_index_post', array( $post_id ) ) ) { wp_schedule_single_event( time() + 5, 'aime_chatbot_index_post', array( $post_id ) ); } } /* ── Daily cleanup cron ──────────────────────────── */ public function daily_cleanup(): void { global $wpdb; $p = $wpdb->prefix; $conv_table = $p . 'aime_chatbot_conversations'; $msg_table = $p . 'aime_chatbot_messages'; // Auto-close conversations inactive for >24 hours. $wpdb->query( $wpdb->prepare( 'UPDATE %i SET status = %s, ended_at = %s, updated_at = %s WHERE status = %s AND updated_at < %s', $conv_table, 'closed', current_time( 'mysql', true ), current_time( 'mysql', true ), 'active', gmdate( 'Y-m-d H:i:s', strtotime( '-24 hours' ) ) ) ); // Purge old conversations based on data retention setting (0 = keep forever). $settings = get_option( 'aime_chatbot_settings', array() ); $retention_days = absint( $settings['data_retention_days'] ?? 90 ); if ( $retention_days > 0 ) { $cutoff = gmdate( 'Y-m-d H:i:s', strtotime( "-{$retention_days} days" ) ); // Get conversation IDs to delete. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery $old_ids = $wpdb->get_col( $wpdb->prepare( 'SELECT id FROM %i WHERE created_at < %s', $conv_table, $cutoff ) ); if ( $old_ids ) { $placeholders = implode( ',', array_fill( 0, count( $old_ids ), '%d' ) ); // Delete messages first. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery $wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE conversation_id IN ({$placeholders})", $msg_table, ...$old_ids ) ); // Delete conversations. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery $wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE id IN ({$placeholders})", $conv_table, ...$old_ids ) ); } } self::bump_cache_version(); // Aggregate analytics for yesterday. Services\AnalyticsService::aggregate_daily( gmdate( 'Y-m-d', strtotime( '-1 day' ) ) ); } } /* ── Register with Module Manager ──────────────────────── */ add_action( 'aime_load_module_chatbot', function ( $manager ) { $manager->register( new ChatbotModule() ); } );