<?php
if ( ! defined( 'ABSPATH' ) ) { exit; }
if ( class_exists( 'Truebe_Admin_Chat' ) ) { return; }

/**
 * Truebe internal research chat. Formerly its own top-level page; now rendered
 * as the "Chat" tab inside Fact Library (see Truebe_Admin_Seeds). This class
 * keeps only the rendering logic and asset localization; Fact Library owns
 * the menu entry, tab nav, and enqueue call.
 */
class Truebe_Admin_Chat {

	public static function init() {
		// Intentionally empty: page retired as a standalone menu item, now a
		// tab inside Fact Library. Kept so truebe.php's require/init calls
		// don't need to change.
	}

	/**
	 * Internal chat greets the logged-in admin by name with the site's local
	 * time of day, matching the greeting style used on other Truebe pages.
	 * The truebe_chat_greeting option remains the public widget's greeting.
	 */
	public static function internal_greeting() {
		$user = wp_get_current_user();
		$name = ( $user && $user->exists() ) ? $user->display_name : __( 'there', 'truebe-fact-based-ai-chatbot' );
		$hour = (int) current_time( 'H' );
		if ( $hour < 12 ) {
			/* translators: %s: the logged-in user's display name */
			$text = sprintf( __( 'Good morning, %s.', 'truebe-fact-based-ai-chatbot' ), $name );
		} elseif ( $hour < 17 ) {
			/* translators: %s: the logged-in user's display name */
			$text = sprintf( __( 'Good afternoon, %s.', 'truebe-fact-based-ai-chatbot' ), $name );
		} else {
			/* translators: %s: the logged-in user's display name */
			$text = sprintf( __( 'Good evening, %s.', 'truebe-fact-based-ai-chatbot' ), $name );
		}
		return "\xF0\x9F\x9A\x80 " . $text;
	}

	/** Localize truebeChat for chat.js. Called by Fact Library's enqueue_assets when tab=chat. */
	public static function enqueue_assets() {
		wp_enqueue_script( 'truebe-chat', plugins_url( '../assets/chat.js', __FILE__ ), array(), (string) filemtime( plugin_dir_path( __FILE__ ) . '../assets/chat.js' ), true );
		wp_localize_script(
			'truebe-chat',
			'truebeChat',
			array(
				'ajax'         => esc_url_raw( admin_url( 'admin-ajax.php' ) ),
				'viewDoc'      => esc_url_raw( admin_url( 'admin-post.php' ) ),
				'viewDocNonce' => wp_create_nonce( 'truebe_view_doc' ),
				'nonce'        => wp_create_nonce( 'truebe_chat' ),
				'greeting'     => self::internal_greeting(),
				'accent'   => get_option( 'truebe_chat_accent', '#0f6e56' ),
				'bot'      => get_option( 'truebe_chat_bot_color', '#f6f7f7' ),
				'fallback' => get_option( 'truebe_chat_fallback_color', '#fff9e6' ),
			)
		);
	}

	/** Strip the upload hash prefix so names show a readable filename. */
	private static function clean_doc_name( $raw ) {
		$raw  = (string) $raw;
		$base = basename( $raw );
		if ( preg_match( '/^[a-f0-9]+\.[0-9]+_(.+)$/i', $base, $m ) ) {
			return $m[1];
		}
		return $base;
	}

	/** Renders just the chat card (no page wrap/h1) so Fact Library can embed it as a tab. */
	public static function render_body() {
		if ( ! current_user_can( 'manage_options' ) ) { return; }

		$accent    = get_option( 'truebe_chat_accent', '#0f6e56' );
		$header    = get_option( 'truebe_chat_header', '' );
		$head_text = '' !== $header ? $header : get_bloginfo( 'name' );
		$audio     = ( '1' === (string) get_option( 'truebe_chat_audio', '0' ) );
		$ph        = $audio ? __( 'Type or speak…', 'truebe-fact-based-ai-chatbot' ) : __( 'Type your question…', 'truebe-fact-based-ai-chatbot' );

		$documents = class_exists( 'Truebe_Seeds' ) && method_exists( 'Truebe_Seeds', 'list_documents' ) ? Truebe_Seeds::list_documents() : array();
		?>
		<p style="color:#646970;font-size:13px;margin:0 0 24px;"><?php esc_html_e( 'Use to do research from the documents in your Fact Library.', 'truebe-fact-based-ai-chatbot' ); ?></p>

		<div class="truebe-ap-pv" id="tb-chat-pv" style="max-width:820px;">
			<div class="truebe-ap-pvhead" style="display:flex;align-items:center;justify-content:space-between;gap:12px;">
				<span><?php echo esc_html( $head_text ); ?></span>
				<?php if ( ! empty( $documents ) ) : ?>
					<select id="tb-chat-doc" style="width:220px;max-width:220px;padding:6px 30px 6px 10px;border:1px solid #dcdcde;border-radius:8px;font-size:13px;line-height:1.4;min-height:0;height:auto;color:#1d2327;-webkit-appearance:none;appearance:none;background:#fff url('data:image/svg+xml;charset=US-ASCII,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%2212%22 height=%228%22 viewBox=%220 0 12 8%22%3E%3Cpath fill=%22%23646970%22 d=%22M1.4 0L6 4.6 10.6 0 12 1.4l-6 6-6-6z%22/%3E%3C/svg%3E') no-repeat right 10px center;">
					<option value=""><?php esc_html_e( 'All documents', 'truebe-fact-based-ai-chatbot' ); ?></option>
					<?php foreach ( $documents as $d ) :
						$raw   = (string) $d['source_doc'];
						$name  = self::clean_doc_name( $raw );
						$stamp = ! empty( $d['uploaded_at'] ) ? mysql2date( 'M j, Y g:ia', $d['uploaded_at'] ) : '';
						$label = $stamp ? $name . '  —  ' . $stamp : $name;
					?>
						<option value="<?php echo esc_attr( $raw ); ?>"><?php echo esc_html( $label ); ?></option>
					<?php endforeach; ?>
				</select>
				<?php endif; ?>
			</div>
			<div class="truebe-ap-chatlog" id="tb-chat-log" style="max-height:460px;overflow-y:auto;"></div>
			<div class="truebe-ap-inrow">
				<div class="truebe-ap-inbox" style="flex:1;display:flex;align-items:center;">
					<input type="text" id="tb-chat-input" placeholder="<?php echo esc_attr( $ph ); ?>" style="border:none;outline:none;background:transparent;width:100%;">
				</div>
				<div class="truebe-ap-ic" id="tb-chat-send" style="color:<?php echo esc_attr( $accent ); ?>;cursor:pointer;"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 2L11 13m11-11l-7 20-4-9-9-4 20-7z"/></svg></div>
			</div>
		</div>
		<?php
	}
}