<?php
if ( ! defined( 'ABSPATH' ) ) {
	die( '-1' );
}

add_action( 'wp_ajax_wpb_ai_api_get_response', 'wpbGetAiApiResponse' );
add_action( 'wp_ajax_wpb_ai_generate_content_check_cache', 'wpbGetGenerateAiContentCheckCache' );
add_action( 'wp_ajax_wpb_ai_get_modal_data', 'wpbGetModalAiData' );

if ( ! function_exists( 'wpbGetAiApiResponse' ) ) {
	/**
	 * Get response from AI API.
	 *
	 * @sine 7.2
	 */
	function wpbGetAiApiResponse() {
		vc_user_access()->checkAdminNonce()->validateDie();

		require_once vc_path_dir( 'CORE_DIR', 'ai/class-vc-ai-api-connector.php' );
		$ai_api_connector = new Vc_Ai_Api_Connector();

		$content = $ai_api_connector->get_ai_content( vc_request_param( 'data' ) );

		if ( is_wp_error( $content ) ) {
			wp_send_json_error( $content );
		}

		wp_send_json_success( $content );
	}
}

if ( ! function_exists( 'wpbGetGenerateAiContentCheckCache' ) ) {
	/**
	 * Get content generated by AI.
	 *
	 * @sine 7.2
	 */
	function wpbGetGenerateAiContentCheckCache() {
		vc_user_access()->checkAdminNonce()->validateDie();

		require_once vc_path_dir( 'CORE_DIR', 'ai/class-vc-ai-api-connector.php' );
		$api_connector = new Vc_Ai_Api_Connector();

		$content = $api_connector->get_api_response_data_from_cache( vc_request_param( 'data' ) );
		if ( is_wp_error( $content ) ) {
			wp_send_json_error( $content );
		}

		wp_send_json_success( $content );
	}
}

if ( ! function_exists( 'wpbGetModalAiData' ) ) {
	/**
	 * Gen AI modal content.
	 *
	 * @sine 7.2
	 */
	function wpbGetModalAiData() {
		vc_user_access()->checkAdminNonce()->validateDie();

		require_once vc_path_dir( 'CORE_DIR', 'ai/class-vc-ai-modal-controller.php' );
		$modal_controller = new Vc_Ai_Modal_Controller();

		$data = $modal_controller->get_modal_data( vc_request_param( 'data' ) );

		// in case of error we should it inside modal content
		wp_send_json_success( $data );
	}
}
