<?php
/**
 * Shortcode Handler class for managing plugin shortcodes
 *
 * This class handles the registration and rendering of all plugin shortcodes,
 * including the chat widget and contact form shortcodes.
 *
 * @package Askany
 * @since 1.0.0
 */
namespace Askany;

use ask\askany\wpnts_nts_fs;

/**
 * Shortcode Handler class for managing plugin shortcodes
 *
 * @package Askany
 * @since 1.0.0
 */
class ShortcodeHandler {
	/**
	 * API Manager instance for handling AI interactions.
	 *
	 * @var ApiManager
	 */
	private $api_manager;

	/**
	 * Constructor for ShortcodeHandler.
	 *
	 * Initializes the API Manager instance.
	 */
	public function __construct( $api_manager ) {
		$this->api_manager = $api_manager;
	}

	/**
	 * Initialize shortcodes.
	 *
	 * @return void
	 */
	public function init() {
		add_shortcode('askany_chat', array( $this, 'render_chat_interface' ));
	}

	/**
	 * Render chat widget shortcode.
	 *
	 * @param array  $atts    Shortcode attributes.
	 * @param string $content Shortcode content.
	 * @return string Rendered shortcode output.
	 */
	public function render_chat_interface( $atts ) {
		// Parse attributes.
		$atts = shortcode_atts(
			array(
				'title' => '',
				'placeholder' => __('Type your question here...', 'askany'),
				'button_text' => __('Send', 'askany'),
				'theme' => 'light',
				'position' => 'inline',
				'width' => '350px',
				'height' => '500px',
			),
			$atts,
			'askany_chat'
		);

		// Sanitize attributes first.
		$title = esc_html($atts['title']);
		$placeholder = esc_attr($atts['placeholder']);
		$button_text = esc_html($atts['button_text']);
		$theme = in_array($atts['theme'], array( 'light', 'dark' )) ? $atts['theme'] : 'light';
		$position = in_array($atts['position'], array( 'left', 'right', 'inline', 'bottom-left', 'bottom-right' )) ? $atts['position'] : 'inline';
		$width = esc_attr($atts['width']);
		$height = esc_attr($atts['height']);

		// Get settings.
		$settings = $this->api_manager->get_settings();

		// Check if API is enabled.
		if ( ! $settings['api_enabled'] ) {
			return sprintf(
				'<div class="askany-chat-disabled">%s</div>',
				esc_html__('Chat is currently disabled. Please contact the administrator.', 'askany')
			);
		}

		// Handle floating widget position logic.
		if ( $settings['floating_widget_enabled'] ) {
			// If position is 'inline' in shortcode, use the global position setting.
			if ( $position === 'inline' ) {
				$position = $settings['widget_position'];
			}
		}

		// Set title based on priority.
		// 1. Shortcode title if provided.
		// 2. Settings chat header text.
		// 3. Default "Ask Me Anything".
		$header_text = ! empty($atts['title']) ? $atts['title'] :
				( ! empty($settings['chat_header_text']) ? $settings['chat_header_text'] :
				__('Ask Me Anything', 'askany') );
		$header_text = esc_html($header_text);

		// Get home page data
		$database = new Database();

		// Get agents for home page display
		$agents = array();
		if ( ! empty($settings['show_agents']) ) {
			$agents = $database->get_agents();
		}

		// Get FAQs for home page
		$faqs = array();
		if ( ! empty($settings['show_faq']) ) {
			$faqs = $database->get_home_faqs();
		}

		// Get custom links for home page
		$custom_links = array();
		if ( ! empty($settings['show_custom_links']) ) {
			$custom_links = $database->get_home_links();
		}

		// Start output buffering.
		ob_start();

		// Include the frontend widget template.
		include ASKANY_PLUGIN_DIR . 'templates/frontend-widget.php';

		// Return the buffered content.
		return ob_get_clean();
	}

	/**
	 * Handle AJAX request for chat response.
	 *
	 * @return void
	 */
	public function get_chat_response() {
		// Set the correct content type header.
		header('Content-Type: application/json');

		// Prevent any accidental output before JSON.
		ob_start();

		check_ajax_referer('askany_chat_nonce', 'nonce');

		$message = isset($_POST['message']) ? sanitize_text_field( wp_unslash($_POST['message'] )) : '';
		if ( empty($message) ) {
			wp_send_json_error(array(
				'message' => __('Please enter a message.', 'askany'),
			));
		}

		// Get settings.
		$settings = $this->api_manager->get_settings();

		// Check if API is enabled.
		if ( ! $settings['api_enabled'] ) {
			wp_send_json_error(array(
				'message' => __('Chat API is currently disabled. Please contact the administrator.', 'askany'),
			));
		}

		// Get response from API.
		$response = $this->api_manager->get_response($message);

		// If API fails and fallback is enabled, use fallback response.
		if ( ! $response && $settings['fallback_enabled'] ) {
			$response = array(
				'message' => __('I apologize, but I am currently unable to process your request. Please try again later.', 'askany'),
				'products' => array(),
			);
		} elseif ( ! $response ) {
			wp_send_json_error(array(
				'message' => __('Sorry, I could not process your request at this time.', 'askany'),
			));
		}

		// Store chat history in database.
		global $wpdb;
		$table_name = $wpdb->prefix . 'askany_chat_history';

		$wpdb->insert(
			$table_name,
			array(
				'message' => $message,
				'response' => $response['message'],
				'created_at' => current_time('mysql'),
			),
			array( '%s', '%s', '%s' )
		);

		// Clean any buffered output.
		ob_clean();

		// Manually send JSON response.
		echo json_encode(array(
			'success' => true,
			'data' => $response,
		));

		wp_die();
	}
}
