guard( 'manage_woocommerce' ); if ( $check ) { return $check; } if ( ! function_exists( 'wc_get_product' ) ) { return [ 'error' => 'WooCommerce is not active.' ]; } if ( $product_id <= 0 ) { return [ 'error' => 'product_id must be a positive integer.' ]; } try { $request = new \WP_REST_Request( 'GET', '/wpcafe/v2/products/' . $product_id ); $request->set_url_params( [ 'id' => $product_id ] ); $controller = new \WpCafe\Products\Controllers\Product_Controller(); $result = $this->extract_response( $controller->get_item( $request ), 'Product not found.' ); if ( isset( $result['error'] ) ) { return $result; } $categories = array_map( static fn( $term ) => is_array( $term ) ? ( $term['name'] ?? '' ) : (string) $term, $result['categories'] ?? [] ); return [ 'id' => $result['id'] ?? $product_id, 'name' => $result['name'] ?? '', 'sku' => $result['sku'] ?? '', 'permalink' => $result['permalink'] ?? '', 'status' => $result['status'] ?? '', 'price' => $result['price'] ?? '', 'regular_price' => $result['regular_price'] ?? '', 'sale_price' => $result['sale_price'] ?? '', 'on_sale' => $result['on_sale'] ?? false, 'stock_status' => $result['stock_status'] ?? '', 'stock_quantity' => $result['stock_quantity'] ?? null, 'categories' => array_values( array_filter( $categories ) ), 'image' => $result['images'][0]['src'] ?? '', 'short_description' => $this->truncate( $result['short_description'] ?? '', 300 ), 'description' => $this->truncate( $result['description'] ?? '', 600 ), ]; } catch ( \Throwable $e ) { Log::error( 'Wpcafe_Get_Product_Tool error', [ 'error' => $e->getMessage() ] ); return [ 'error' => 'Failed to retrieve product: ' . $e->getMessage() ]; } } }