<?php
/**
 * Answyr Chat — front-end widget loader.
 *
 * Enqueues the deflection widget and passes it the endpoints + copy. Ported from
 * the SimplyChat widget class onto the shared plugin. Display sitewide or via the
 * [answyr_chat] shortcode.
 *
 * @package Answyr
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

final class Answyr_Chat_Widget {

	public function register(): void {
		add_action( 'wp_enqueue_scripts', array( $this, 'maybe_enqueue' ) );
		add_shortcode( 'answyr_chat', array( $this, 'shortcode' ) );
	}

	public function maybe_enqueue(): void {
		if ( 'shortcode' === Answyr_Settings::get( 'chat_display_mode', 'sitewide' ) ) {
			return; // shortcode enqueues on demand
		}
		if ( ! $this->available() ) {
			return; // login required and visitor is anonymous
		}
		$this->enqueue();
	}

	public function shortcode(): string {
		if ( ! $this->available() ) {
			return '';
		}
		$this->enqueue();
		return '<div id="answyr-chat-inline" data-inline="true"></div>';
	}

	/** Whether chat should render for the current visitor (mirrors the REST login gate). */
	private function available(): bool {
		return ! Answyr_Settings::chat_requires_login() || is_user_logged_in();
	}

	public function enqueue(): void {
		wp_enqueue_style( 'answyr-tokens', ANSWYR_URL . 'assets/tokens.css', array(), ANSWYR_VERSION );
		wp_enqueue_style( 'answyr-chat', ANSWYR_URL . 'assets/chat-widget.css', array( 'answyr-tokens' ), ANSWYR_VERSION );
		wp_enqueue_script( 'answyr-md', ANSWYR_URL . 'assets/markdown.js', array(), ANSWYR_VERSION, true );
		wp_enqueue_script( 'answyr-chat', ANSWYR_URL . 'assets/chat-widget.js', array( 'answyr-md' ), ANSWYR_VERSION, true );
		wp_localize_script(
			'answyr-chat',
			'AnswyrChat',
			array(
				'endpoint'      => esc_url_raw( rest_url( 'answyr/v1/chat' ) ),
				'escalateUrl'   => esc_url_raw( rest_url( 'answyr/v1/chat/escalate' ) ),
				'nonce'         => wp_create_nonce( 'wp_rest' ),
				'title'         => Answyr_Settings::get( 'chat_title', __( 'Ask a question', 'answyr' ) ),
				'placeholder'   => Answyr_Settings::get( 'chat_placeholder', __( 'Type your question…', 'answyr' ) ),
				'welcome'       => Answyr_Settings::get( 'chat_welcome', __( 'Hi! I can answer questions from our knowledge base. How can I help you?', 'answyr' ) ),
				'escalateLabel' => __( 'Create a support ticket', 'answyr' ),
				'canEscalate'   => Answyr_Settings::module_enabled( 'desk' ),
				'userEmail'     => is_user_logged_in() ? sanitize_email( wp_get_current_user()->user_email ) : '',
				'portalUrl'     => esc_url_raw( trim( (string) Answyr_Settings::get( 'portal_url', '' ) ) ),
				'primaryColor'  => Answyr_Settings::get( 'chat_color', '#2271b1' ),
			)
		);
	}
}
