<?php
/** Integrierter Chat und isolierte Website-Vorschau im WordPress-Backend. */

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

function wpagent_companion_chat_sanitized_preview_url( string $requested ): string {
	$url = wpagent_companion_chat_preview_url( $requested );
	if ( '' === $url ) {
		return '';
	}
	return add_query_arg(
		array(
			'wpagently_preview' => '1',
			'_wpnonce'          => wp_create_nonce( 'wpagently_chat_preview' ),
		),
		$url
	);
}

function wpagent_companion_chat_strip_preview_scripts( string $html ): string {
	$filtered = preg_replace( '~<script\b[^>]*>.*?</script\s*>~is', '', $html );
	if ( is_string( $filtered ) ) {
		$filtered = preg_replace( '~<base\b[^>]*>~i', '', $filtered );
	}
	if ( is_string( $filtered ) ) {
		$filtered = preg_replace_callback(
			'~<meta\b[^>]*>~i',
			static function ( array $match ): string {
				$decoded = html_entity_decode( $match[0], ENT_QUOTES | ENT_HTML5, 'UTF-8' );
				return preg_match( '~\bhttp-equiv\s*=\s*(?:(["\'])\s*refresh\s*\1|refresh\b)~i', $decoded ) ? '' : $match[0];
			},
			$filtered
		);
	}
	if ( is_string( $filtered ) ) {
		$filtered = preg_replace_callback(
			'~<link\b[^>]*>~i',
			static function ( array $match ): string {
				return preg_match( '~\brel\s*=\s*(["\'])?modulepreload\1~i', $match[0] ) ? '' : $match[0];
			},
			$filtered
		);
	}
	return is_string( $filtered ) ? $filtered : '';
}

function wpagent_companion_chat_preview_request_is_authorized(): bool {
	$mode = is_string( $_GET['wpagently_preview'] ?? null ) ? sanitize_text_field( wp_unslash( $_GET['wpagently_preview'] ) ) : '';
	if ( '1' !== $mode || ! current_user_can( 'manage_options' ) ) {
		return false;
	}
	$nonce = is_string( $_GET['_wpnonce'] ?? null ) ? sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ) : '';
	return (bool) wp_verify_nonce( $nonce, 'wpagently_chat_preview' );
}

function wpagent_companion_chat_start_sanitized_preview(): void {
	if ( ! array_key_exists( 'wpagently_preview', $_GET ) ) {
		return;
	}
	if ( ! wpagent_companion_chat_preview_request_is_authorized() ) {
		status_header( 403 );
		nocache_headers();
		wp_die(
			esc_html__( 'Die sichere Vorschau ist abgelaufen oder nicht erlaubt.', 'wp-agent-companion' ),
			esc_html__( 'Vorschau nicht verfügbar', 'wp-agent-companion' ),
			array( 'response' => 403 )
		);
	}
	show_admin_bar( false );
	nocache_headers();
	header( 'Referrer-Policy: same-origin' );
	header( "Content-Security-Policy: base-uri 'none'; form-action 'none'; frame-ancestors 'self'; frame-src 'none'; object-src 'none'; script-src 'none'" );
	ob_start( 'wpagent_companion_chat_strip_preview_scripts' );
}
add_action( 'template_redirect', 'wpagent_companion_chat_start_sanitized_preview', 0 );

function wpagent_companion_chat_menu(): void {
	add_submenu_page(
		'wpagently',
		__( 'Chat und Vorschau', 'wp-agent-companion' ),
		__( 'Chat und Vorschau', 'wp-agent-companion' ),
		'manage_options',
		'wpagently-chat',
		'wpagent_companion_chat_page'
	);
}
add_action( 'admin_menu', 'wpagent_companion_chat_menu', 20 );

function wpagent_companion_chat_assets( string $hook ): void {
	if ( 'wpagently_page_wpagently-chat' !== $hook ) {
		return;
	}
	$plugin_file = WPAGENT_COMPANION_DIR . 'wp-agent-companion.php';
	wp_enqueue_style( 'wpagently-chat', plugins_url( 'assets/chat-admin.css', $plugin_file ), array( 'wpagently-admin-base' ), WPAGENT_COMPANION_VERSION );
	wp_enqueue_script( 'wpagently-chat', plugins_url( 'assets/chat-admin.js', $plugin_file ), array(), WPAGENT_COMPANION_VERSION, true );
	wp_localize_script(
		'wpagently-chat',
		'wpagentlyChat',
		array(
			'planUrl'            => rest_url( 'wp-agent/chat/plan' ),
			'executeUrl'         => rest_url( 'wp-agent/chat/execute' ),
			'nonce'              => wp_create_nonce( 'wp_rest' ),
			'previewNonce'       => wp_create_nonce( 'wpagently_chat_preview' ),
			'previewDeniedPaths' => wpagent_companion_chat_preview_denied_paths(),
			'homeUrl'            => home_url( '/' ),
			'i18n'               => array(
				'working'       => __( 'Ich prüfe die Website und bereite eine Antwort vor …', 'wp-agent-companion' ),
				'failed'        => __( 'Die Anfrage ist fehlgeschlagen.', 'wp-agent-companion' ),
				'approve'       => __( 'Diese Aktion freigeben', 'wp-agent-companion' ),
				'approving'     => __( 'Wird ausgeführt …', 'wp-agent-companion' ),
				'completed'     => __( 'Ausgeführt und von der Ability geprüft.', 'wp-agent-companion' ),
				'actionFailed'  => __( 'Die Aktion konnte nicht ausgeführt werden.', 'wp-agent-companion' ),
				'badPreviewUrl' => __( 'Die Vorschau akzeptiert nur Pfade dieser Website.', 'wp-agent-companion' ),
				'plannedInputs' => __( 'Geplante Eingaben', 'wp-agent-companion' ),
				'selectElement' => __( 'Element auswählen', 'wp-agent-companion' ),
				'selecting'     => __( 'Auswahl beenden', 'wp-agent-companion' ),
				'clearSelection' => __( 'Auswahl löschen', 'wp-agent-companion' ),
				'selectedElement' => __( 'Ausgewähltes Element', 'wp-agent-companion' ),
				'pickerUnavailable' => __( 'Die Elementauswahl ist auf dieser Vorschauseite nicht verfügbar.', 'wp-agent-companion' ),
			),
		)
	);
}
add_action( 'admin_enqueue_scripts', 'wpagent_companion_chat_assets' );

function wpagent_companion_chat_page(): void {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}
	$capabilities = wpagent_companion_chat_capabilities();
	$users        = wpagent_companion_connection_users( false );
	$ready        = $capabilities['core_supported'] && $capabilities['provider_configured'] && $capabilities['gate_open'] && ! empty( $users );
	?>
	<div class="wrap wpagently-admin wpagently-chat-page">
		<div class="wpagently-chat-heading">
			<div>
				<p class="wpagently-chat-eyebrow"><?php esc_html_e( 'Sicherer Arbeitsbereich', 'wp-agent-companion' ); ?></p>
				<h1><?php esc_html_e( 'Chat und Website-Vorschau', 'wp-agent-companion' ); ?></h1>
				<p><?php esc_html_e( 'Lass den Assistenten deine Website untersuchen. Schreibende Aktionen werden erst nach deiner einzelnen Freigabe unter einem Redakteur ausgeführt.', 'wp-agent-companion' ); ?></p>
			</div>
			<a class="button" href="<?php echo esc_url( admin_url( 'options-connectors.php' ) ); ?>"><?php esc_html_e( 'KI-Connectors verwalten', 'wp-agent-companion' ); ?></a>
		</div>

		<?php if ( ! $ready ) : ?>
			<div class="notice notice-warning inline"><p>
				<?php echo esc_html( $capabilities['reason'] ?: __( 'Lege zuerst unter wpagently > Agent verbinden einen sicheren Redakteur an.', 'wp-agent-companion' ) ); ?>
			</p></div>
		<?php endif; ?>
		<div class="notice notice-info inline"><p><?php esc_html_e( 'Deine Nachrichten und die für die Antwort gelesenen Website-Daten werden direkt an den unter Einstellungen > Connectors gewählten KI-Anbieter gesendet. wpagently betreibt dafür keinen eigenen KI-Proxy.', 'wp-agent-companion' ); ?></p></div>

		<div class="wpagently-workspace">
			<section class="wpagently-chat-panel" aria-label="<?php esc_attr_e( 'Chat', 'wp-agent-companion' ); ?>">
				<div id="wpagently-chat-log" class="wpagently-chat-log" aria-live="polite">
					<div class="wpagently-message wpagently-message-assistant"><?php esc_html_e( 'Was möchtest du auf dieser Website prüfen oder ändern?', 'wp-agent-companion' ); ?></div>
				</div>
				<form id="wpagently-chat-form" class="wpagently-chat-form">
					<label for="wpagently-chat-user"><?php esc_html_e( 'Sicherer Agent-Nutzer', 'wp-agent-companion' ); ?></label>
					<select id="wpagently-chat-user" <?php disabled( empty( $users ) ); ?>>
						<?php foreach ( $users as $user ) : ?>
							<option value="<?php echo esc_attr( (string) $user['id'] ); ?>"><?php echo esc_html( $user['name'] . ' (' . $user['login'] . ')' ); ?></option>
						<?php endforeach; ?>
					</select>
					<label for="wpagently-chat-message"><?php esc_html_e( 'Nachricht', 'wp-agent-companion' ); ?></label>
					<textarea id="wpagently-chat-message" rows="4" maxlength="8000" placeholder="<?php esc_attr_e( 'Zum Beispiel: Prüfe die Startseite und schlage eine klarere Einleitung vor.', 'wp-agent-companion' ); ?>" <?php disabled( ! $ready ); ?>></textarea>
					<button class="button button-primary" type="submit" <?php disabled( ! $ready ); ?>><?php esc_html_e( 'Prüfen und Plan erstellen', 'wp-agent-companion' ); ?></button>
				</form>
			</section>

			<section class="wpagently-preview-panel" aria-label="<?php esc_attr_e( 'Website-Vorschau', 'wp-agent-companion' ); ?>">
				<form id="wpagently-preview-form" class="wpagently-preview-toolbar">
					<label class="screen-reader-text" for="wpagently-preview-path"><?php esc_html_e( 'Vorschaupfad', 'wp-agent-companion' ); ?></label>
					<input id="wpagently-preview-path" type="text" value="/" aria-describedby="wpagently-preview-help">
					<button class="button" type="submit"><?php esc_html_e( 'Öffnen', 'wp-agent-companion' ); ?></button>
					<button class="button" id="wpagently-preview-refresh" type="button"><?php esc_html_e( 'Neu laden', 'wp-agent-companion' ); ?></button>
					<button class="button" id="wpagently-preview-picker" type="button" aria-pressed="false"><?php esc_html_e( 'Element auswählen', 'wp-agent-companion' ); ?></button>
					<button class="button" id="wpagently-preview-clear" type="button" hidden><?php esc_html_e( 'Auswahl löschen', 'wp-agent-companion' ); ?></button>
				</form>
				<p id="wpagently-preview-help" class="screen-reader-text"><?php esc_html_e( 'Nur Pfade der aktuellen Website sind erlaubt.', 'wp-agent-companion' ); ?></p>
				<div id="wpagently-preview-error" class="wpagently-preview-error" role="alert"></div>
				<div id="wpagently-preview-selection" class="wpagently-preview-selection" aria-live="polite" hidden></div>
				<p class="description"><?php esc_html_e( 'Seitenskripte und Formulare bleiben in der Vorschau aus Sicherheitsgründen deaktiviert.', 'wp-agent-companion' ); ?></p>
				<iframe id="wpagently-preview" title="<?php esc_attr_e( 'Website-Vorschau', 'wp-agent-companion' ); ?>" src="<?php echo esc_url( wpagent_companion_chat_sanitized_preview_url( '/' ) ); ?>" referrerpolicy="same-origin" sandbox="allow-same-origin"></iframe>
			</section>
		</div>
	</div>
	<?php
}
