api_key = $api_key; add_action('wp_enqueue_scripts', [$this, 'enqueue_widget']); } /** * Check every site-level override that may hide the widget. * All options default to the original hard-coded behavior so upgrades are safe. */ private function should_hide_widget(): bool { if (is_admin()) return true; if (get_option('addtaisa_widget_disabled_global', false)) return true; if (function_exists('is_cart') && is_cart() && get_option('addtaisa_widget_disabled_on_cart', true)) { return true; } if (function_exists('is_checkout') && is_checkout() && get_option('addtaisa_widget_disabled_on_checkout', true)) { return true; } $patterns_raw = get_option('addtaisa_widget_disabled_patterns', ''); if (!empty($patterns_raw)) { $path = wp_parse_url(home_url(add_query_arg([])), PHP_URL_PATH) ?: '/'; $lines = array_filter(array_map('trim', explode("\n", (string) $patterns_raw))); foreach ($lines as $pattern) { $regex = '#^' . str_replace(['\*', '\?'], ['.*', '.'], preg_quote($pattern, '#')) . '$#i'; if (preg_match($regex, $path)) return true; } } return false; } public function enqueue_widget() { if ($this->should_hide_widget()) return; wp_enqueue_script( 'addtaisa-widget', ADDTAISA_CDN_URL . '/widget.js', [], ADDTAISA_VERSION, ['strategy' => 'async', 'in_footer' => true] ); // Build config object for the widget $config = [ 'shopId' => $this->api_key, 'apiUrl' => ADDTAISA_PUBLIC_API_URL, 'language' => substr(get_locale(), 0, 2), ]; // Inject cached remote widget config so the widget can render without a round-trip. $remote = self::get_cached_remote_config($this->api_key); if ($remote) { $config['config'] = $remote; } // Detect WooCommerce logged-in customer if (class_exists('WooCommerce') && is_user_logged_in()) { $customer_data = $this->get_customer_data(); if ($customer_data) { $config['customer'] = $customer_data; } } // Current page context $page_data = $this->get_page_context(); if ($page_data) { $config['page'] = $page_data; } // Inject as global variable (read by widget.js on load) $inline = 'window.__addtochat = ' . wp_json_encode($config) . ';'; wp_add_inline_script('addtaisa-widget', $inline, 'before'); } /** * Get current WooCommerce customer data. * Passed to the widget so the bot can greet by name + personalize. */ private function get_customer_data(): ?array { $user = wp_get_current_user(); if (!$user || !$user->ID) return null; $customer = new WC_Customer($user->ID); $data = [ 'email' => $customer->get_email(), 'first_name' => $customer->get_first_name(), 'last_name' => $customer->get_last_name(), ]; // Recent orders (last 5) $orders = wc_get_orders([ 'customer_id' => $user->ID, 'limit' => 10, 'orderby' => 'date', 'order' => 'DESC', 'status' => ['completed', 'processing', 'on-hold', 'pending', 'refunded'], ]); $recent_orders = []; foreach ($orders as $order) { $items = []; foreach ($order->get_items() as $item) { $items[] = [ 'name' => $item->get_name(), 'product_id' => $item->get_product_id(), 'quantity' => $item->get_quantity(), 'total' => (float) $item->get_total(), ]; } $recent_orders[] = [ 'id' => $order->get_id(), 'date' => $order->get_date_created()->format('Y-m-d'), 'status' => $order->get_status(), 'total' => (float) $order->get_total(), 'items' => $items, ]; } if (!empty($recent_orders)) { $data['recent_orders'] = $recent_orders; } // Recently viewed products (from WC session) $viewed = []; if (function_exists('wc_get_customer_last_viewed_products')) { $viewed = wc_get_customer_last_viewed_products(5); } else { // Fallback: read from cookie $cookie = isset($_COOKIE['woocommerce_recently_viewed']) ? sanitize_text_field(wp_unslash($_COOKIE['woocommerce_recently_viewed'])) : ''; if ($cookie) { $viewed_ids = array_filter(array_map('absint', explode('|', $cookie))); foreach (array_slice($viewed_ids, 0, 5) as $pid) { $product = wc_get_product($pid); if ($product) { $viewed[] = [ 'id' => $pid, 'name' => $product->get_name(), 'price' => (float) $product->get_price(), 'on_sale' => $product->is_on_sale(), ]; } } } } if (!empty($viewed)) { $data['recently_viewed'] = $viewed; } // Current cart contents if (WC()->cart && !WC()->cart->is_empty()) { $cart_items = []; foreach (WC()->cart->get_cart() as $item) { $product = $item['data']; $cart_items[] = [ 'product_id' => $item['product_id'], 'name' => $product->get_name(), 'quantity' => $item['quantity'], 'price' => (float) $product->get_price(), 'total' => (float) $item['line_total'], ]; } $data['cart'] = [ 'items' => $cart_items, 'total' => (float) WC()->cart->get_total('edit'), 'count' => WC()->cart->get_cart_contents_count(), ]; } return $data; } /** * Fetch and cache the remote widget config from addtochat.com. * Cache TTL: 5 minutes. On error returns null — widget falls back to built-in defaults. */ public static function get_cached_remote_config(string $api_key): ?array { if (empty($api_key)) return null; $cached = get_transient('addtaisa_widget_config'); if (is_array($cached)) return $cached; $response = wp_remote_get( ADDTAISA_API_URL . '/v1/widget/config?shop=' . rawurlencode($api_key), ['timeout' => 5, 'headers' => ['Accept' => 'application/json']] ); if (is_wp_error($response)) return null; if (wp_remote_retrieve_response_code($response) !== 200) return null; $body = json_decode(wp_remote_retrieve_body($response), true); if (!is_array($body)) return null; set_transient('addtaisa_widget_config', $body, 5 * MINUTE_IN_SECONDS); return $body; } /** * Get current page context for the widget. */ private function get_page_context(): ?array { $data = [ 'url' => home_url(add_query_arg([])), 'title' => wp_title('', false), ]; if (is_product()) { global $product; if ($product instanceof WC_Product) { $data['type'] = 'product'; $data['product_id'] = $product->get_id(); $data['product_name'] = $product->get_name(); $data['product_price'] = (float) $product->get_price(); $data['on_sale'] = $product->is_on_sale(); $data['regular_price'] = (float) $product->get_regular_price(); // Main product thumbnail — widget reads this to render the image // inside the persistent product-ask card instead of the ◉ glyph. $atc_image_id = $product->get_image_id(); if ($atc_image_id) { $atc_image_url = wp_get_attachment_image_url($atc_image_id, 'woocommerce_thumbnail'); if ($atc_image_url) { $data['product_image'] = $atc_image_url; } } } } elseif (is_product_category()) { $term = get_queried_object(); $data['type'] = 'category'; $data['category'] = $term->name ?? ''; } elseif (is_search()) { $data['type'] = 'search'; $data['search_query'] = get_search_query(); } elseif (is_shop()) { $data['type'] = 'shop'; } elseif (is_front_page()) { $data['type'] = 'homepage'; } return $data; } }