<?php
/**
 * API Client
 *
 * Thin HTTP wrapper for all apwp-ao premium API calls. Attaches the
 * plugin's own slot-specific JWT rather than the Pro Connector's JWT,
 * so apwp-ao is never coupled to the Pro Connector for runtime requests.
 *
 * @package Agency_Pulse_Admin_Menu
 * @since   1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Agency_Pulse_Admin_Menu_Api_Client {

	/**
	 * Make an authenticated request to the Agency Pulse connect server.
	 *
	 * The apwp-ao JWT is automatically injected as an Authorization header.
	 * The $args array uses the same shape as wp_remote_request() — pass
	 * 'body', 'headers', 'timeout', etc. as needed.
	 *
	 * @since 1.0.0
	 * @param string $method   HTTP method: 'GET', 'POST', 'DELETE', etc.
	 * @param string $endpoint Path relative to /api/ — no leading slash required.
	 * @param array  $args     wp_remote_request() args to merge.
	 * @return array|WP_Error  wp_remote_request() return value.
	 */
	public static function request( string $method, string $endpoint, array $args = array() ) {
		$jwt = Agency_Pulse_Admin_Menu_License_Manager::get_valid_jwt();

		if ( $jwt ) {
			if ( ! isset( $args['headers'] ) || ! is_array( $args['headers'] ) ) {
				$args['headers'] = array();
			}
			$args['headers']['Authorization'] = 'Bearer ' . $jwt;
		}

		$base           = rtrim( defined( 'APWP_CONNECT_URL' ) ? APWP_CONNECT_URL : '', '/' );
		$url            = $base . '/api/' . ltrim( $endpoint, '/' );
		$args['method'] = strtoupper( $method );

		$response = wp_remote_request( $url, $args );

		if ( is_wp_error( $response ) ) {
			Agency_Pulse_Admin_Menu_License_Manager::record_api_error( $response->get_error_message() );
			return $response;
		}

		$code = (int) wp_remote_retrieve_response_code( $response );

		if ( 401 === $code || 403 === $code ) {
			$body  = json_decode( wp_remote_retrieve_body( $response ), true );
			$error = ( is_array( $body ) && ! empty( $body['message'] ) )
				? $body['message']
				: sprintf( 'Server returned status %d', $code );
			Agency_Pulse_Admin_Menu_License_Manager::record_api_error( $error );
		} elseif ( $code >= 200 && $code < 300 ) {
			Agency_Pulse_Admin_Menu_License_Manager::clear_api_error();
		}

		return $response;
	}
}
