bool, * 'withinQuota' => bool, * 'plan' => string, * 'remaining' => int, * 'resetsAt' => string (ISO8601), * 'error' => string|null, // populated on transport/parse failure * ) * * @param bool $force Bypass the cache and re-fetch. * @return array */ public function get( $force = false ) { if ( ! Plugin::is_connected() ) { return $this->empty_status( __( 'Not connected', 'aisthetix-virtual-try-on' ) ); } if ( ! $force ) { $cached = get_transient( self::TRANSIENT ); if ( is_array( $cached ) ) { return $cached; } } $fresh = $this->fetch_from_brain(); // Cache successful responses for the full TTL; cache failures briefly so // a flaky brain does not hammer us, but recovers reasonably fast. $ttl = empty( $fresh['error'] ) ? self::CACHE_TTL : MINUTE_IN_SECONDS; set_transient( self::TRANSIENT, $fresh, $ttl ); return $fresh; } /** * Whether the try-on entry point should be shown on the storefront. * * Per DESIGN.md decision #14/#15: render only when active && withinQuota. * * @return bool */ public function should_render() { $status = $this->get(); return ! empty( $status['active'] ) && ! empty( $status['withinQuota'] ); } /** * Force-refresh the cache (used after Connect or via an admin action). * * @return array Fresh status. */ public function refresh() { delete_transient( self::TRANSIENT ); return $this->get( true ); } /** * Perform the server-to-server status call to the brain. * * @return array Normalised status (see {@see get()}). */ private function fetch_from_brain() { $url = Plugin::brain_url() . '/api/storefront/status'; $response = wp_remote_get( $url, array( 'timeout' => 10, 'headers' => array( 'X-Aisthetix-Secret' => Plugin::secret_key(), 'Accept' => 'application/json', ), ) ); if ( is_wp_error( $response ) ) { return $this->empty_status( $response->get_error_message() ); } $code = (int) wp_remote_retrieve_response_code( $response ); $body = wp_remote_retrieve_body( $response ); $data = json_decode( $body, true ); if ( 200 !== $code || ! is_array( $data ) ) { /* translators: %d: HTTP status code. */ return $this->empty_status( sprintf( __( 'Brain returned HTTP %d', 'aisthetix-virtual-try-on' ), $code ) ); } return array( 'active' => ! empty( $data['active'] ), 'withinQuota' => ! empty( $data['withinQuota'] ), 'plan' => isset( $data['plan'] ) ? sanitize_text_field( $data['plan'] ) : '', 'remaining' => isset( $data['remaining'] ) ? (int) $data['remaining'] : 0, 'resetsAt' => isset( $data['resetsAt'] ) ? sanitize_text_field( $data['resetsAt'] ) : '', 'error' => null, ); } /** * Build a "not available" status payload. * * @param string $error Human-readable reason. * @return array */ private function empty_status( $error ) { return array( 'active' => false, 'withinQuota' => false, 'plan' => '', 'remaining' => 0, 'resetsAt' => '', 'error' => $error, ); } }