<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
/**
 * Handles communication with the Google Cloud Vision API.
 *
 * @link       https://trynbuy.edubrazeal.com/
 * @since      1.0.0
 *
 * @package    Ai_Try_N_Buy
 * @subpackage Ai_Try_N_Buy/services
 */

require_once plugin_dir_path( __FILE__ ) . 'class-api-base.php';

class Aitnb_Google_Vision_Service extends Aitnb_Api_Base {

	/**
	 * Constructor. Sets the specific API URL for the Google Vision service.
	 *
	 * @since    1.0.0
	 * @param    string    $api_key    The API key for the service.
	 */
	public function __construct( $api_key ) {
		parent::__construct( $api_key );
		$this->api_url = 'https://vision.googleapis.com/v1/images:annotate';
	}

	/**
	 * A public method to simplify calling the face detection feature.
	 *
	 * @since    1.0.0
	 * @param    string    $image_content    The raw binary content of the image file.
	 * @return   mixed|WP_Error             The API response or a WP_Error on failure.
	 */
	public function detect_face( $image_content ) {
		$transient_key   = 'aitnb_vision_res_' . md5( $image_content );
		$cached_response = get_transient( $transient_key );

		if ( false !== $cached_response ) {
			return $cached_response;
		}

		$args     = array(
			'image_content' => $image_content,
		);
		$response = $this->make_request( $args );

		if ( ! is_wp_error( $response ) ) {
			set_transient( $transient_key, $response, MONTH_IN_SECONDS );
		}

		return $response;
	}

	/**
	 * Builds the body of the request for the Google Vision API.
	 *
	 * This method is required by the abstract parent class. It formats the
	 * request payload according to the Google Vision API's specification.
	 *
	 * @since    1.0.0
	 * @access   protected
	 * @param    array      $args    The arguments for the request. Must contain 'image_content'.
	 * @return   array|WP_Error      The formatted request body or a WP_Error.
	 */
	protected function build_request_body( $args ) {
		if ( ! isset( $args['image_content'] ) || empty( $args['image_content'] ) ) {
			return new WP_Error( 'missing_image_content', __( 'Image content is required for the Vision API.', 'virtual-ai-fit-and-style-assistant' ) );
		}

		$base64_image = base64_encode( $args['image_content'] );

		$request_body = array(
			'requests' => array(
				array(
					'image'    => array(
						'content' => $base64_image,
					),
					'features' => array(
						array(
							'type'       => 'FACE_DETECTION',
							'maxResults' => 1,
						),
					),
				),
			),
		);

		return $request_body;
	}
}