<?php

use Antimanual\API;
/**
 * Enqueue Scripts and css for frontend for Antimanual Chatbot
 *
 * @package Antimanual_Chatbot
 * @since   1.0.0
 */

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

function antimanual_enqueue_chatbot_scripts() {
	if ( is_admin() || is_login() || ! atml_is_module_enabled( 'chatbot' ) || ! atml_option( 'chatbot_enabled' ) ) {
		return;
	}

	$js_ver  = (string) filemtime( ANTIMANUAL_DIR . 'assets/js/chatbot.js' ) ?: ANTIMANUAL_VERSION;
	$css_ver = (string) filemtime( ANTIMANUAL_DIR . 'assets/css/frontend-custom.css' ) ?: ANTIMANUAL_VERSION;

	wp_enqueue_script( 'antimanual-custom', ANTIMANUAL_JS . 'chatbot.js', [ 'jquery', 'wp-i18n' ], $js_ver, true );
	wp_set_script_translations( 'antimanual-custom', 'antimanual', ANTIMANUAL_DIR . 'languages' );
	wp_enqueue_style( 'antimanual-custom', ANTIMANUAL_URL . 'assets/css/frontend-custom.css', [], $css_ver );

	// Attach the user-configured chatbot variables inline so public pages do not
	// trigger an extra uncached admin-ajax stylesheet request on every load.
	$dynamic_css = function_exists( 'antimanual_get_dynamic_css' ) ? antimanual_get_dynamic_css() : '';
	if ( '' !== $dynamic_css ) {
		wp_add_inline_style( 'antimanual-custom', $dynamic_css );
	}

	$chatbot_config  = atml_get_chatbot_configs();
	$welcome_message = $chatbot_config['wlc_msg'] ?? atml_option( 'chatbot_wlc_msg' );
	$is_pro          = atml_is_pro();

	// Cross-domain embed scope: read the parent product label from the iframe
	// URL. Sanitized + length-capped here; the server REST layer re-validates
	// and locks it onto the conversation on first turn.
	//
	// Multiple param names accepted so customer snippets are forgiving:
	//   ?ctx=Eazydocs          (canonical, what our admin generator emits)
	//   ?embed_context=...     (alternate, in case someone copies the field name)
	//   ?context=...           (alternate human-readable)
	$embed_context_raw = '';
	foreach ( [ 'ctx', 'embed_context', 'context' ] as $candidate_key ) {
		if ( isset( $_GET[ $candidate_key ] ) ) {
			$value = sanitize_text_field( wp_unslash( $_GET[ $candidate_key ] ) );
			if ( '' !== $value ) {
				$embed_context_raw = $value;
				break;
			}
		}
	}
	if ( '' !== $embed_context_raw ) {
		$embed_context_raw = function_exists( 'mb_substr' )
			? mb_substr( $embed_context_raw, 0, 200, 'UTF-8' )
			: substr( $embed_context_raw, 0, 200 );
	}

	// Pre-fill lead with the logged-in user's email/name so the lead form is skipped.
	$lead_prefill = null;
	if ( is_user_logged_in() ) {
		$current_user = wp_get_current_user();
		if ( ! empty( $current_user->user_email ) ) {
			$lead_prefill = [
				'email' => sanitize_email( $current_user->user_email ),
				'name'  => sanitize_text_field( $current_user->display_name ?: '' ),
			];
		}
	}

	wp_localize_script(
		'antimanual-custom',
		'antimanual_chatbot_vars',
		[
			'ajaxurl'         => admin_url( 'admin-ajax.php' ),
			'rest_url'        => API::url(),
			'bot_avatar'      => ANTIMANUAL_URL . 'assets/icons/bot.png',
			'welcome_message' => $welcome_message,
			'nonce'           => wp_create_nonce( 'wp_rest' ),
			'embed_context'   => $embed_context_raw,
			'lead'            => [
				'collect_email'  => $is_pro ? atml_boolval_mixed( $chatbot_config['collect_email'] ?? false ) : false,
				'email_required' => $is_pro ? atml_boolval_mixed( $chatbot_config['email_required'] ?? false ) : false,
				'collect_name'   => $is_pro ? atml_boolval_mixed( $chatbot_config['collect_name'] ?? false ) : false,
				'name_required'  => $is_pro ? atml_boolval_mixed( $chatbot_config['name_required'] ?? false ) : false,
				'prompt'         => $is_pro ? ( $chatbot_config['email_prompt'] ?? '' ) : '',
				'prefill'        => $lead_prefill,
			],
			'mobile'          => [
				'show_on_mobile' => $is_pro ? atml_boolval_mixed( $chatbot_config['show_on_mobile'] ?? true ) : true,
				'position'       => $is_pro ? ( $chatbot_config['mobile_position'] ?? 'bottom-right' ) : 'bottom-right',
			],
			'display'         => [
				'desktop_position'  => $chatbot_config['desktop_position'] ?: 'bottom-right',
				'input_placeholder' => $chatbot_config['input_placeholder'] ?: '',
				'suggested_label'   => $chatbot_config['suggested_label'] ?: '',
				'show_avatar'       => atml_boolval_mixed( $chatbot_config['show_avatar'] ?? false ),
				'custom_avatar_url' => $chatbot_config['custom_avatar_url'] ?: '',
			],
			'feedback_enabled' => atml_boolval_mixed( $chatbot_config['feedback_enabled'] ?? false ),
			'irrelevant_ans'   => $chatbot_config['irrelevant_ans'] ?: '',
			// Phase 5: streaming flag. Off by default. When on, chatbot.js
			// uses fetch()+ReadableStream against /messages/stream and falls
			// back to /messages on any failure (non-OpenAI provider, custom
			// answer match, handoff trigger, network error, etc.).
			'streaming_enabled' => (bool) apply_filters(
				'antimanual_chatbot_streaming_enabled',
				atml_boolval_mixed( atml_option( 'chatbot_streaming_enabled' ) )
			),
			'escalation'       => [
				'enabled' => $is_pro ? atml_boolval_mixed( $chatbot_config['escalation_enabled'] ?? false ) : false,
				'type'    => $is_pro ? ( $chatbot_config['escalation_type'] ?: 'email' ) : 'email',
				'message' => $is_pro ? ( $chatbot_config['escalation_message'] ?: '' ) : '',
				'email'   => $is_pro ? ( $chatbot_config['escalation_email'] ?: '' ) : '',
				'url'     => $is_pro ? ( $chatbot_config['escalation_url'] ?: '' ) : '',
				'show_button' => $is_pro ? atml_boolval_mixed( $chatbot_config['live_chat_button_enabled'] ?? false ) : false,
				'button_label' => $is_pro ? ( $chatbot_config['live_chat_button_label'] ?: __( 'Chat with a Human', 'antimanual' ) ) : __( 'Chat with a Human', 'antimanual' ),
				'live_chat_available' => $is_pro && class_exists('\Antimanual_Pro\LiveChat') ? \Antimanual_Pro\LiveChat::any_agent_available() : false,
			],
			'live_chat'       => [
				'attachments_enabled' => $is_pro
					&& atml_boolval_mixed( $chatbot_config['escalation_enabled'] ?? false )
					&& 'live_chat' === ( $chatbot_config['escalation_type'] ?? 'email' )
					&& atml_boolval_mixed( $chatbot_config['image_attachments_enabled'] ?? false ),
				'max_upload_size'    => $is_pro ? wp_max_upload_size() : 0,
				'upgrade_message'    => $is_pro
					? __( 'Image attachments are disabled in the chatbot configuration.', 'antimanual' )
					: __( 'Image attachments are available in Antimanual Pro.', 'antimanual' ),
				'allowed_image_types' => $is_pro && class_exists( '\Antimanual_Pro\LiveChat' )
					? array_values( \Antimanual_Pro\LiveChat::allowed_image_mime_types() )
					: [],
			],
		]
	);
}

add_action( 'wp_enqueue_scripts', 'antimanual_enqueue_chatbot_scripts' );
