API_URL = $ai_botkit_url . '/api/saas/'; // Initialize post sync hooks $this->init_post_sync_hooks(); } /** * Get the access token from options. * * @return string|false The access token or false if not found. */ private function get_access_token() { return get_option('ai_botkit_saas_connect_token'); } /** * Send get request to the API */ public function send_get_request(string $endpoint, array $options = []): array { $access_token = $this->get_access_token(); if (empty($access_token)) { return ['error' => 'Access token is not set.']; } $url = $this->API_URL . $endpoint; $params['headers'] = [ 'Content-Type' => 'application/json', ]; $params['timeout'] = 100; $options['access_token'] = $access_token; $url = add_query_arg($options, $url); $response = wp_remote_get($url, $params); if (is_wp_error($response)) { return ['error' => $response->get_error_message()]; } $body = wp_remote_retrieve_body($response); $data = json_decode($body, true); return is_array($data) ? $data : ['error' => 'Invalid API response.', 'response_body' => $body]; } /** * Send post request to the API */ public function send_post_request(string $endpoint, array $options = []): array { $access_token = $this->get_access_token(); if (empty($access_token)) { return ['error' => 'Access token is not set.']; } $url = $this->API_URL . $endpoint; $params['headers'] = [ 'Content-Type' => 'application/json', ]; $options['access_token'] = $access_token; $params['body'] = json_encode($options); $response = wp_remote_post($url, $params); if (is_wp_error($response)) { return ['error' => $response->get_error_message()]; } $body = wp_remote_retrieve_body($response); $data = json_decode($body, true); return is_array($data) ? $data : ['error' => 'Invalid API response.', 'response_body' => $body]; } /** * Seconds to wait for AI BotKit on a request the owner is watching. The * switch shows a spinner until this returns (R15), so it stays short. */ const SYNC_TIMEOUT = 15; /** * The agents this site may see, each reduced to what the plugin uses. * * GET /api/saas/chatbots, token as Bearer (KTD15). The chat widget switch * is read from `widget_enabled`; an AI BotKit from before Release A only * sends `active`, which then stands in for it. * * @return array{ok: true, agents: array[]}|array{ok: false, error: string} */ public function get_agents(): array { $result = $this->send_site_request('GET', 'chatbots'); if (!$result['ok']) { return $result; } if (!isset($result['data']['data']) || !is_array($result['data']['data'])) { return ['ok' => false, 'error' => self::message('unexpected')]; } $agents = []; foreach ($result['data']['data'] as $row) { if (is_array($row)) { $agent = self::agent_status($row); if ($agent['id'] > 0) { $agents[] = $agent; } } } return ['ok' => true, 'agents' => $agents]; } /** * Sets the chat widget switch to an absolute value and returns what AI * BotKit stored (KTD6). Nothing is written on this site: the switch has * one home, in AI BotKit. * * @return array{ok: true, agent: array}|array{ok: false, error: string} */ public function set_widget_enabled(int $chatbot_id, bool $enabled): array { $result = $this->send_site_request('PATCH', 'chatbots', [ 'chatbotId' => $chatbot_id, 'widget_enabled' => $enabled, ]); if (!$result['ok']) { return $result; } if (!isset($result['data']['data']) || !is_array($result['data']['data'])) { return ['ok' => false, 'error' => self::message('unexpected')]; } return ['ok' => true, 'agent' => self::agent_status($result['data']['data'])]; } /** * One agent row from AI BotKit, reduced to what the plugin uses. * * `widget_enabled` is the only source of the card's status: an agent can * be `live` on its agent page or a channel while its chat widget is off. * `live` is null when AI BotKit did not say. */ public static function agent_status(array $row): array { if (array_key_exists('widget_enabled', $row)) { $widget_enabled = true === $row['widget_enabled'] || 1 === $row['widget_enabled'] || '1' === $row['widget_enabled']; } else { $widget_enabled = isset($row['active']) && (true === $row['active'] || 1 === $row['active'] || '1' === $row['active']); } $namespace = ''; if (isset($row['messagesTemplate']['namespace']) && is_scalar($row['messagesTemplate']['namespace'])) { $namespace = (string) $row['messagesTemplate']['namespace']; } elseif (isset($row['namespace']) && is_scalar($row['namespace'])) { $namespace = (string) $row['namespace']; } return [ 'id' => isset($row['id']) && is_numeric($row['id']) ? (int) $row['id'] : 0, 'namespace' => $namespace, 'name' => isset($row['name']) && is_scalar($row['name']) ? (string) $row['name'] : '', 'widget_enabled' => $widget_enabled, 'live' => array_key_exists('live', $row) && null !== $row['live'] ? (bool) $row['live'] : null, ]; } /** * A site-token request to /api/saas/{endpoint} that the owner is waiting * on. The token goes in the Authorization header, never the URL or body, * because it does not expire (KTD15). Anything but a 2xx JSON answer with * `success: true` is a failure with a plain message. * * @return array{ok: true, status: int, data: array}|array{ok: false, error: string, status?: int} */ private function send_site_request(string $method, string $endpoint, ?array $body = null): array { $access_token = $this->get_access_token(); if (empty($access_token) || !is_string($access_token)) { return ['ok' => false, 'error' => self::message('not_connected')]; } $args = [ 'method' => $method, 'timeout' => self::SYNC_TIMEOUT, 'headers' => [ 'Authorization' => 'Bearer ' . $access_token, 'Accept' => 'application/json', ], ]; if (null !== $body) { $args['headers']['Content-Type'] = 'application/json'; $args['body'] = wp_json_encode($body); } $response = wp_remote_request($this->API_URL . $endpoint, $args); if (is_wp_error($response)) { return ['ok' => false, 'error' => self::message('unreachable')]; } $status = (int) wp_remote_retrieve_response_code($response); if ($status < 200 || $status >= 300) { if (401 === $status || 403 === $status) { $key = 'unauthorized'; } elseif (404 === $status) { $key = 'not_found'; } else { $key = 'failed'; } return ['ok' => false, 'status' => $status, 'error' => self::message($key)]; } $data = json_decode((string) wp_remote_retrieve_body($response), true); if (!is_array($data) || empty($data['success'])) { return ['ok' => false, 'status' => $status, 'error' => self::message('unexpected')]; } return ['ok' => true, 'status' => $status, 'data' => $data]; } private static function message(string $key): string { switch ($key) { case 'not_connected': return __('This site is not connected to AI BotKit. Connect it and try again.', 'ai-botkit-for-lead-generation'); case 'unreachable': return __('AI BotKit could not be reached, so nothing changed. Check your connection and try again.', 'ai-botkit-for-lead-generation'); case 'unauthorized': return __('AI BotKit did not accept this site\'s connection, so nothing changed. Reconnect the site and try again.', 'ai-botkit-for-lead-generation'); case 'not_found': return __('AI BotKit could not find this agent for this site, so nothing changed.', 'ai-botkit-for-lead-generation'); case 'unexpected': return __('AI BotKit sent an unexpected answer, so nothing changed. Please try again in a moment.', 'ai-botkit-for-lead-generation'); default: return __('AI BotKit had a problem, so nothing changed. Please try again in a moment.', 'ai-botkit-for-lead-generation'); } } /** * Initialize post sync hooks */ private function init_post_sync_hooks(): void { // Hook into post update events add_action('save_post', [$this, 'handle_post_sync'], 10, 3); add_action('delete_post', [$this, 'handle_post_delete_sync'], 10, 2); } /** * Handle post sync when posts are updated */ public function handle_post_sync(int $post_id, \WP_Post $post, bool $update): void { // Skip autosaves and revisions if (wp_is_post_autosave($post_id) || wp_is_post_revision($post_id)) { return; } // Check if post sync is enabled for this post type $sync_settings = get_option('ai_botkit_post_sync_settings', []); if (empty($sync_settings['enabled_post_types']) || !in_array($post->post_type, $sync_settings['enabled_post_types'])) { return; } // Only sync published posts if ($post->post_status !== 'publish') { return; } // Sync the post content $this->sync_post_content($post_id, $post); } /** * Handle post delete sync */ public function handle_post_delete_sync(int $post_id, \WP_Post $post): void { // Check if post sync is enabled for this post type $sync_settings = get_option('ai_botkit_post_sync_settings', []); if (empty($sync_settings['enabled_post_types']) || !in_array($post->post_type, $sync_settings['enabled_post_types'])) { return; } // Notify SaaS about post deletion $this->sync_post_content($post_id, $post, 'delete'); } /** * Sync post content to SaaS platform */ private function sync_post_content(int $post_id, \WP_Post $post, string $action = 'sync'): void { global $ai_botkit_url; $access_token = $this->get_access_token(); if (empty($access_token)) { return; } // Prepare post data $post_data = [ 'postId' => $post_id, 'postTitle' => $post->post_title, 'postContent' => $post->post_content, 'postExcerpt' => $post->post_excerpt, 'action' => $action, 'authToken' => $access_token ]; // Additive, optional field: the post's public URL so the SaaS can cite it. // Skipped on delete (a trashed post's permalink carries a "__trashed" slug) and // when get_permalink() fails and returns false. if ($action !== 'delete') { $post_link = get_permalink($post); if (is_string($post_link) && $post_link !== '') { $post_data['postLink'] = esc_url_raw($post_link); } } // Enrich post content via filter (allows third-party plugins to append metadata) $enriched_content = apply_filters( 'ai_botkit_enrich_post_content', $post->post_content, $post_id, $post->post_type ); $post_data['postContent'] = $enriched_content; // For backward compatibility: if a plugin previously sent structured metadata, // remove those legacy keys so the SaaS receives clean enriched text only. unset( $post_data['postType'], $post_data['productPrice'], $post_data['productCategories'], $post_data['productTags'] ); // Send to SaaS sync endpoint $url = $ai_botkit_url . '/api/wordpress/sync-content/'; $response = wp_remote_post($url, [ 'headers' => [ 'Content-Type' => 'application/json', ], 'body' => json_encode($post_data), 'timeout' => 30 ]); // Log errors if any if (is_wp_error($response)) { error_log('AI BotKit Post Sync Error: ' . $response->get_error_message()); } else { $response_code = wp_remote_retrieve_response_code($response); if ($response_code !== 200) { error_log('AI BotKit Post Sync Error: HTTP ' . $response_code); } } } /** * Get enabled post types for sync */ public static function get_enabled_post_types(): array { $sync_settings = get_option('ai_botkit_post_sync_settings', []); return $sync_settings['enabled_post_types'] ?? []; } /** * Save post sync settings */ public static function save_sync_settings(array $settings): bool { return update_option('ai_botkit_post_sync_settings', $settings); } /** * Get all available post types */ public static function get_available_post_types(): array { $post_types = get_post_types(['public' => true], 'objects'); $formatted_types = []; foreach ($post_types as $post_type) { $formatted_types[] = [ 'name' => $post_type->name, 'label' => $post_type->label, 'description' => $post_type->description ?? '' ]; } return $formatted_types; } }