<?php

class BrizyPro_Admin_Ai extends Brizy_Admin_AbstractApi {

	const AJAX_ACTION = '_ai';

	protected function initializeApiActions() {
		add_action( 'wp_ajax_' . Brizy_Editor::prefix( self::AJAX_ACTION ), [ $this, 'cloudProxy' ] );
	}

	public function cloudProxy() {

		if ( ! Brizy_Editor_User::is_user_allowed() ) {
			$this->error( 400, 'The user has no capabilities to use this feature.' );
		}

		if ( ! BrizyPro_Admin_License::_init()->isValidLicense() ) {
			$this->error( 400, 'The user must have a license to use this feature.' );
		}

		if ( ! wp_verify_nonce( $this->getRequestNonce(), Brizy_Editor_API::nonce ) ) {
			$this->error( 400, 'Invalid token, please refresh page and try again.' );
		}

		$http     = new WP_Http();
		$response = $http->request( BrizyPro_Config::AI_URL . '?api_path=/v1/chat/completions', [
			'headers' => [
				'x-auth-wp-license-key' => BrizyPro_Admin_License::_init()->getCurrentLicense()['key'],
				'Content-Type'          => 'application/json',
			],
			'body'    => file_get_contents( "php://input" ),
			'method'  => 'POST',
			'timeout' => 120
		] );

		$status = wp_remote_retrieve_response_code( $response );

		if ( is_wp_error( $response ) || 200 != $status ) {
			$this->error( $status, wp_remote_retrieve_response_message( $response ) );
		}

		wp_send_json( json_decode( wp_remote_retrieve_body( $response ), true ) );
	}

	protected function getRequestNonce() {
		return $this->param('hash');
	}
}