api_url = MAGICGEO_API_URL; $this->api_key = get_option( 'magicgeo_api_key', '' ); } /** * Check if API is configured. * * @return bool */ public function is_configured() { return ! empty( $this->api_key ); } /** * Make API request. * * @param string $endpoint API endpoint. * @param array $data Request data. * @param string $method HTTP method. * @return array|WP_Error Response data or error. */ public function request( $endpoint, $data = array(), $method = 'POST' ) { if ( ! $this->is_configured() ) { return new WP_Error( 'no_api_key', __( 'API key not configured.', 'magicgeo' ) ); } $url = trailingslashit( $this->api_url ) . ltrim( $endpoint, '/' ); $args = array( 'method' => $method, 'timeout' => 60, 'headers' => array( 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $this->api_key, 'apikey' => $this->api_key, ), ); if ( ! empty( $data ) && in_array( $method, array( 'POST', 'PUT', 'PATCH' ), true ) ) { $args['body'] = wp_json_encode( $data ); } $response = wp_remote_request( $url, $args ); if ( is_wp_error( $response ) ) { return $response; } $body = wp_remote_retrieve_body( $response ); $code = wp_remote_retrieve_response_code( $response ); if ( $code >= 400 ) { return new WP_Error( 'api_error', sprintf( /* translators: %d: HTTP status code */ __( 'API request failed with status %d.', 'magicgeo' ), $code ) ); } return json_decode( $body, true ); } /** * Optimize a product. * * @param array $product_data Product data. * @return array|WP_Error Optimization result or error. */ public function optimize_product( $product_data ) { return $this->request( 'woocommerce-optimize', $product_data ); } /** * Analyze a product. * * @param array $product_data Product data. * @return array|WP_Error Analysis result or error. */ public function analyze_product( $product_data ) { return $this->request( 'woocommerce-analyze', $product_data ); } /** * Verify API connection. * * @return bool|WP_Error True on success, error on failure. */ public function verify_connection() { $result = $this->request( 'woocommerce-verify', array( 'test' => true ) ); if ( is_wp_error( $result ) ) { return $result; } return true; } }