<?php
/**
 * Provides a base class for API service integrations.
 *
 * This class handles the common logic for making remote API calls using
 * the WordPress HTTP API, including error handling and response parsing.
 *
 * @link       https://trynbuy.edubrazeal.com/
 * @since      1.0.0
 *
 * @package    Ai_Try_N_Buy
 * @subpackage Ai_Try_N_Buy/services
 */

abstract class Aitnb_Api_Base {

	/**
	 * The API key for the service.
	 *
	 * @since    1.0.0
	 * @access   protected
	 * @var      string    $api_key    The API key.
	 */
	protected $api_key;

	/**
	 * The base URL for the API endpoint.
	 *
	 * @since    1.0.0
	 * @access   protected
	 * @var      string    $api_url    The API endpoint URL.
	 */
	protected $api_url;

	/**
	 * Constructor.
	 *
	 * @since    1.0.0
	 * @param    string    $api_key    The API key for the service.
	 */
	public function __construct( $api_key ) {
		$this->api_key = $api_key;
	}

	/**
	 * Builds the body of the request.
	 *
	 * This method must be implemented by each child class to conform
	 * to the specific API's requirements.
	 *
	 * @since    1.0.0
	 * @access   protected
	 * @param    array      $args    The arguments for the request.
	 * @return   array               The formatted request body.
	 */
	abstract protected function build_request_body( $args );

	/**
	 * Makes the remote request to the API.
	 *
	 * @since    1.0.0
	 * @param    array     $args    The arguments for the request.
	 * @return   mixed|WP_Error     The decoded JSON response or a WP_Error object on failure.
	 */
	public function make_request( $args ) {
		if ( empty( $this->api_key ) ) {
			return new WP_Error( 'api_key_missing', __( 'API key is not configured.', 'virtual-ai-fit-and-style-assistant' ) );
		}

		$body = $this->build_request_body( $args );
		if ( is_wp_error( $body ) ) {
			return $body;
		}

		$request_args = array(
			'method'  => 'POST',
			'timeout' => 30,
			'headers' => array(
				'Content-Type' => 'application/json; charset=utf-8',
			),
			'body'    => wp_json_encode( $body ),
		);

		$request_url = add_query_arg( 'key', $this->api_key, $this->api_url );

		$response = wp_remote_post( $request_url, $request_args );

		if ( is_wp_error( $response ) ) {
			return $response;
		}

		$response_code = wp_remote_retrieve_response_code( $response );
		if ( 200 !== $response_code ) {
			$response_message = wp_remote_retrieve_response_message( $response );
			return new WP_Error(
				'api_error_' . $response_code,
				sprintf(
					/* translators: 1: HTTP status code, 2: Response message */
					__( 'API request failed with status %1$s: %2$s', 'virtual-ai-fit-and-style-assistant' ),
					$response_code,
					$response_message
				)
			);
		}

		$response_body = wp_remote_retrieve_body( $response );
		$decoded_body  = json_decode( $response_body, true );

		return $decoded_body;
	}
}