<?php
/**
 * Widget injector: adds the chat widget IFRAME to the storefront.
 *
 * @package KwiroAISalesAgent
 */

defined( 'ABSPATH' ) || exit;

/**
 * Class Kwiro_Widget_Injector
 *
 * Injects the AI Sales Assistant chat widget IFRAME into WooCommerce store
 * frontend pages. Only loads when the widget is enabled and the API is configured.
 */
class Kwiro_Widget_Injector {

	/**
	 * API Client instance.
	 *
	 * @var Kwiro_API_Client
	 */
	private $api_client;

	/**
	 * Constructor.
	 *
	 * @param Kwiro_API_Client $api_client API client instance.
	 */
	public function __construct( $api_client ) {
		$this->api_client = $api_client;

		if ( ! is_admin() ) {
			$this->register_hooks();
		}
	}

	/**
	 * Register frontend hooks. The widget script is enqueued (not inlined) so
	 * wp.org's "all JS must be enqueued" rule is satisfied. The wrapper
	 * div + iframe HTML still prints in `wp_footer`.
	 */
	private function register_hooks() {
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_widget_script' ) );
		add_action( 'wp_footer', array( $this, 'inject_widget' ) );
	}

	/**
	 * Enqueue the widget controller JS. Dynamic config (POSITION_SIDE,
	 * WIDGET_ORIGIN) is passed in via wp_add_inline_script.
	 */
	public function enqueue_widget_script() {
		if ( ! $this->should_display() ) {
			return;
		}

		$settings      = get_option( 'kwiro_settings', array() );
		$position      = $settings['widget_position'] ?? 'bottom-right';
		$pos_side      = 'bottom-right' === $position ? 'right' : 'left';
		$widget_url    = $this->get_widget_url();
		$widget_origin = '';
		$parts         = wp_parse_url( $widget_url );
		if ( ! empty( $parts['scheme'] ) && ! empty( $parts['host'] ) ) {
			$widget_origin = $parts['scheme'] . '://' . $parts['host'];
			if ( ! empty( $parts['port'] ) ) {
				$widget_origin .= ':' . $parts['port'];
			}
		}

		wp_enqueue_script(
			'kwiro-widget',
			KWIRO_PLUGIN_URL . 'assets/js/widget-injector.js',
			array(),
			KWIRO_VERSION,
			true
		);

		// `before` position so the global is defined before widget-injector.js
		// runs. wp_add_inline_script is the documented best practice for non-
		// string data (per the WP review email's citation of the function).
		wp_add_inline_script(
			'kwiro-widget',
			'window.kwiroWidget = ' . wp_json_encode(
				array(
					'positionSide' => $pos_side,
					'widgetOrigin' => esc_url_raw( $widget_origin ),
				)
			) . ';',
			'before'
		);
	}

	/**
	 * Check if the widget should be displayed.
	 *
	 * @return bool
	 */
	public function should_display() {
		// Must be configured with API credentials.
		if ( ! $this->api_client->is_configured() ) {
			return false;
		}

		// Check widget enabled setting.
		$settings = get_option( 'kwiro_settings', array() );
		if ( empty( $settings['widget_enabled'] ) ) {
			return false;
		}

		// Don't show in admin, login, or REST API requests.
		if ( is_admin() || wp_doing_ajax() || defined( 'REST_REQUEST' ) ) {
			return false;
		}

		/**
		 * Filter whether the widget should display.
		 *
		 * @param bool $display Whether to display the widget.
		 */
		return apply_filters( 'kwiro_display_widget', true );
	}

	/**
	 * Get the widget URL with configuration parameters.
	 *
	 * @return string Widget IFRAME URL.
	 */
	public function get_widget_url() {
		$base_url = $this->get_widget_base_url();
		$settings = get_option( 'kwiro_settings', array() );

		$params = array(
			'apiKey'    => get_option( 'kwiro_public_key', '' ),
			'apiUrl'    => $this->get_api_url(),
			'storeId'   => $this->api_client->get_store_id(),
			'color'     => rawurlencode( $settings['widget_color'] ?? '#1d1d1f' ),
			'position'  => $settings['widget_position'] ?? 'bottom-right',
			'botName'   => $settings['bot_name'] ?? 'AI Assistant',
			'welcome'   => $settings['welcome_message'] ?? '',
			'poweredBy' => ! empty( $settings['powered_by'] ) ? 'true' : 'false',
			'pageType'  => $this->get_page_context_type(),
			'pageName'  => $this->get_page_context_name(),
		);

		return add_query_arg( $params, $base_url );
	}

	/**
	 * Get the widget base URL.
	 *
	 * @return string
	 */
	private function get_widget_base_url() {
		if ( defined( 'KWIRO_WIDGET_URL' ) ) {
			return KWIRO_WIDGET_URL;
		}
		return 'https://widget.kwiro.ai';
	}

	/**
	 * Get the API URL.
	 *
	 * @return string
	 */
	private function get_api_url() {
		// Public API URL is browser-facing (may differ from server-side URL in Docker setups).
		if ( defined( 'KWIRO_PUBLIC_API_URL' ) ) {
			return KWIRO_PUBLIC_API_URL;
		}
		if ( defined( 'KWIRO_API_URL' ) ) {
			return KWIRO_API_URL;
		}
		return 'https://api.kwiro.ai';
	}

	/**
	 * Detect WooCommerce page type for contextual greeting.
	 */
	private function get_page_context_type() {
		if ( function_exists( 'is_product' ) && is_product() ) {
			return 'product';
		}
		// Fallback: check post type directly (works with ?p= URLs).
		if ( is_singular( 'product' ) ) {
			return 'product';
		}
		if ( function_exists( 'is_shop' ) && is_shop() ) {
			return 'shop';
		}
		if ( function_exists( 'is_product_category' ) && is_product_category() ) {
			return 'category';
		}
		if ( function_exists( 'is_cart' ) && is_cart() ) {
			return 'cart';
		}
		if ( function_exists( 'is_checkout' ) && is_checkout() ) {
			return 'checkout';
		}
		return 'general';
	}

	/**
	 * Get the current product/category name for personalized greeting.
	 */
	private function get_page_context_name() {
		if ( function_exists( 'is_product' ) && is_product() ) {
			return get_the_title();
		}
		if ( function_exists( 'is_product_category' ) && is_product_category() ) {
			$term = get_queried_object();
			return $term ? $term->name : '';
		}
		return '';
	}

	/**
	 * Inject the widget IFRAME into the page footer.
	 */
	public function inject_widget() {
		if ( ! $this->should_display() ) {
			return;
		}

		$widget_url = $this->get_widget_url();
		$settings   = get_option( 'kwiro_settings', array() );
		$position   = $settings['widget_position'] ?? 'bottom-right';

		// Position CSS based on setting.
		$position_css = 'bottom-right' === $position
			? 'right: 0; left: auto;'
			: 'left: 0; right: auto;';
		?>
		<div
			id="kwiro-chat-widget-wrap"
			style="position: fixed; bottom: 0; <?php echo esc_attr( $position_css ); ?> width: 420px; height: 380px; border-radius: 0; background: rgba(255,255,255,0.001); box-shadow: none; overflow: hidden; z-index: 999999; pointer-events: auto; max-width: 100vw; isolation: isolate; will-change: backdrop-filter, transform; transform: translateZ(0); -webkit-transform: translateZ(0); transition: width 300ms cubic-bezier(.2,.8,.2,1), height 300ms cubic-bezier(.2,.8,.2,1), bottom 300ms cubic-bezier(.2,.8,.2,1), right 300ms cubic-bezier(.2,.8,.2,1), left 300ms cubic-bezier(.2,.8,.2,1), border-radius 300ms cubic-bezier(.2,.8,.2,1), box-shadow 300ms cubic-bezier(.2,.8,.2,1), backdrop-filter 300ms cubic-bezier(.2,.8,.2,1);"
		>
			<iframe
				id="kwiro-chat-widget"
				src="<?php echo esc_url( $widget_url ); ?>"
				style="position: absolute; inset: 0; width: 100%; height: 100%; border: none; background: transparent; display: block;"
				allowtransparency="true"
				title="<?php echo esc_attr__( 'Kwiro AI Sales Agent', 'kwiro-ai-sales-agent' ); ?>"
				sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
				allow="clipboard-write"
				loading="lazy"
			></iframe>
		</div>
		<?php
	}
}
