<?php
/**
 * AI Assistant for the WPadmin plugin chatbox class.
 *
 * @package Ai_Assistant_For_The_Wpadmin
 * @since 1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
} // Exit if accessed directly

/**
 * Chatbox class for the AI Assistant for the WPadmin plugin
 *
 * This class handles the chatbox functionality in the WordPress admin area.
 * It includes methods for enqueueing scripts and styles, rendering the chatbox,
 * and handling AJAX requests for chat messages.
 *
 * @package Ai_Assistant_For_The_Wpadmin
 * @since 1.0.0
 */
class Ai_Assistant_For_Wpadmin_Chatbox {
	/**
	 * Constructor method for the class.
	 * Hooks into WordPress actions to enqueue assets and render the chatbox.
	 */
	public function __construct() {
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
		add_action( 'admin_footer', array( $this, 'render_chatbox' ) );
		add_action( 'wp_ajax_handle_chat_message', array( $this, 'handle_chat_message' ) );
	}
	/**
	 * Enqueues the necessary scripts and styles for the chatbox.
	 * Only enqueues them for users with the 'manage_options' capability.
	 *
	 * @return void
	 */
	public function enqueue_assets() {
		if ( current_user_can( 'manage_options' ) ) {

			wp_enqueue_style(
				'Ai_Assistant_For_Wpadmin_Chatbox_style',
				AI_ASSISTANT_URL . 'assets/css/main.css',
				array(),
				AI_ASSISTANT_VERSION
			);
			wp_enqueue_style(
				'highlight_css',
				AI_ASSISTANT_URL . 'assets/css/highlight.min.css',
				array(),
				'11.11.1'
			);
			wp_enqueue_script(
				'highlight_js',
				AI_ASSISTANT_URL . 'assets/js/highlight.min.js',
				array(),
				'11.11.1',
				true
			);

			wp_enqueue_script(
				'Ai_Assistant_For_Wpadmin_Chatbox',
				AI_ASSISTANT_URL . 'assets/js/main.js',
				array( 'jquery', 'highlight_js' ),
				AI_ASSISTANT_VERSION,
				true
			);

			wp_add_inline_script( 'highlight-js', 'hljs.highlightAll();' );

		}
	}

	/**
	 * Renders the chatbox HTML in the admin footer.
	 * Only renders it for users with the 'manage_options' capability.
	 *
	 * @return void
	 */
	public function render_chatbox() {
		if ( current_user_can( 'manage_options' ) ) {
			include AI_ASSISTANT_DIR . 'templates/ai-assistant-for-wpadmin-chatbox.php';
		}
	}

	/**
	 * Handles the AJAX request for chat messages.
	 * Validates the nonce and checks if the message is empty.
	 * If valid, it processes the message and returns the response.
	 *
	 * @return void
	 */
	public function handle_chat_message() {
		check_ajax_referer( 'ai_assistant_for_the_wpadmin_nonce', 'nonce' );
		if ( ! isset( $_POST['question'] ) || empty( $_POST['question'] ) ) {
			wp_send_json_error( __( 'Please enter a message.', 'ai-assistant-for-wpadmin' ) );
		}
		$message  = sanitize_text_field( wp_unslash( $_POST['question'] ) );
		$context  = sanitize_text_field( wp_unslash( isset( $_POST['context'] ) ? $_POST['context'] : 'Dashboard' ) );
		$path_url = sanitize_text_field( wp_unslash( isset( $_POST['pathUrl'] ) ? $_POST['pathUrl'] : '' ) );
		$response = $this->get_ai_response( $message, $context, $path_url );
		wp_send_json_success( $response );
	}


	/**
	 * Sends the message to the AI API and returns the response.
	 * It prepares the data, makes a POST request to the API, and processes the response.
	 *
	 * @param string $message The message to send to the AI API.
	 * @param string $context The context of the request (e.g., Dashboard).
	 * @param string $path_url The URL path of the current page.
	 * @return string The AI's response or an error message.
	 */
	public function get_ai_response( $message, $context = 'Dashboard', $path_url = '' ) {
		$site_url         = Ai_Assistant_For_Wpadmin_Subscription::get_site_url();
		$encoded_site_url = base64_encode( $site_url );//phpcs:ignore
		$active_plugins   = get_option( 'active_plugins' );
		$active_plugins   = array_map(
			function ( $plugin ) {
				return array(
					'name'    => $plugin,
					'slug'    => basename( $plugin, '.php' ),
					'version' => get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin )['Version'],
					'status'  => 'active',
				);
			},
			$active_plugins
		);
		$active_themes    = wp_get_themes();
		$active_themes    = array_map(
			function ( $theme ) {
				return array(
					'name'    => $theme->get( 'Name' ),
					'slug'    => $theme->get_stylesheet(),
					'version' => $theme->get( 'Version' ),
					'status'  => 'active',
				);
			},
			$active_themes
		);
		$active_themes    = array_values( $active_themes );
		$active_plugins   = wp_json_encode( $active_plugins );
		$active_themes    = wp_json_encode( $active_themes );
		$prompt_message   = $message;
		$data_file        = array(
			'site_url'                => $encoded_site_url,
			'external_active_plugins' => $active_plugins,
			'external_active_themes'  => $active_themes,
			'prompt_message'          => $prompt_message,
			'path_url'                => $path_url,
			'path_page_title'         => $context,
		);
		$api_url          = AI_ASSISTANT_MIDDLEWARE . 'wp-json/wpadmin-app-helper/v1/process-prompt';
		$response         = wp_remote_post(
			$api_url,
			array(
				'method'  => 'POST',
				'body'    => wp_json_encode( $data_file ),
				'headers' => array(
					'Content-Type' => 'application/json',
					'Accept'       => 'application/json',
				),
				'timeout' => AI_ASSISTANT_TIMEOUT,
			)
		);
		if ( is_wp_error( $response ) ) {
			return __( 'An error occurred while processing your request. Please try again later.', 'ai-assistant-for-wpadmin' );
		}
		$response_body = wp_remote_retrieve_body( $response );
		$response_data = json_decode( $response_body, true );
		if ( isset( $response_data['success'] ) && $response_data['success'] ) {
			$message   = $response_data['response']['content'][0]['text']['value'];
			$parsedown = new Parsedown();
			$message   = $parsedown->text( $message );
			$message   = preg_replace_callback(
				'#<code>(https?://[^\s<]+)</code>#i',
				function ( $matches ) {
					$url = htmlspecialchars( $matches[1], ENT_QUOTES, 'UTF-8' );
					return '<a href="' . $url . '" target="__blank">' . $url . '</a>';
				},
				$message
			);
			return $message;
		} else {
			$message = isset( $response_data['message'] ) ? $response_data['message'] : __( 'An error occurred while processing your request. Please try again later.', 'ai-assistant-for-wpadmin' );
			$message = preg_replace_callback(
				'#(https?://[^\s<]+)#i',
				function ( $matches ) {
					$url = htmlspecialchars( $matches[1], ENT_QUOTES, 'UTF-8' );
					return '<a href="' . $url . '" target="__blank">' . $url . '</a>';
				},
				$message
			);
			return $message;
		}
	}
}

new Ai_Assistant_For_Wpadmin_Chatbox();
