<?php
/** WordPress-Kontrollzentrum für Companion-Verbindung und Ability-Exposition. */

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

function wpagent_companion_control_menu(): void {
	add_menu_page(
		__( 'WPAgently', 'wp-agent-companion' ),
		__( 'WPAgently', 'wp-agent-companion' ),
		'manage_options',
		'wpagently',
		'wpagent_companion_control_page',
		'dashicons-shield-alt',
		58
	);
}
add_action( 'admin_menu', 'wpagent_companion_control_menu' );

function wpagent_companion_control_save(): void {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'Keine Berechtigung.', 'wp-agent-companion' ) );
	}
	check_admin_referer( 'wpagent_companion_control_save' );
	$paid = 'paid' === wpagent_companion_access_tier();

	update_option( WPAGENT_COMPANION_OPT_ENABLED, isset( $_POST['companion_enabled'] ) ? '1' : '0', false );
	$profile = isset( $_POST['ability_profile'] ) ? sanitize_key( wp_unslash( $_POST['ability_profile'] ) ) : 'content';
	if ( ! in_array( $profile, wpagent_companion_profiles(), true ) ) {
		$profile = 'content';
	}
	update_option( WPAGENT_COMPANION_OPT_PROFILE, $profile, false );

	$submitted = isset( $_POST['disabled_abilities'] ) && is_array( $_POST['disabled_abilities'] )
		? array_map( 'sanitize_text_field', wp_unslash( $_POST['disabled_abilities'] ) )
		: array();
	$catalog  = wpagent_companion_ability_catalog();
	$disabled = wpagent_companion_merge_disabled_abilities_for_tier(
		$submitted,
		wpagent_companion_disabled_abilities(),
		$catalog,
		$paid
	);
	update_option( WPAGENT_COMPANION_OPT_DISABLED_ABILITIES, $disabled, false );

	if ( $paid ) {
		$external_submitted = isset( $_POST['trusted_external_abilities'] ) && is_array( $_POST['trusted_external_abilities'] )
			? array_map( 'sanitize_text_field', wp_unslash( $_POST['trusted_external_abilities'] ) )
			: array();
		$trusted_external = wpagent_companion_merge_wpforms_trust(
			$external_submitted,
			isset( $_POST['wpforms_forms_enabled'] ),
			isset( $_POST['wpforms_entries_enabled'] ),
			isset( $_POST['wpforms_write_enabled'] )
		);
		$trusted_external = wpagent_companion_merge_ninjaforms_trust(
			$trusted_external,
			isset( $_POST['ninjaforms_forms_enabled'] ),
			isset( $_POST['ninjaforms_submissions_enabled'] ),
			isset( $_POST['ninjaforms_write_enabled'] ),
			isset( $_POST['ninjaforms_delivery_enabled'] )
		);
		update_option( WPAGENT_COMPANION_OPT_TRUSTED_EXTERNAL_ABILITIES, $trusted_external, false );
	}

	wp_safe_redirect( add_query_arg( array( 'page' => 'wpagently', 'updated' => '1' ), admin_url( 'admin.php' ) ) );
	exit;
}
add_action( 'admin_post_wpagently_save_control', 'wpagent_companion_control_save' );

function wpagent_companion_control_admin_notice(): void {
	if ( ! current_user_can( 'manage_options' ) || wpagent_companion_domain_matches() || ! wpagent_companion_enabled() ) {
		return;
	}
	printf(
		'<div class="notice notice-error"><p><strong>%1$s</strong> %2$s</p></div>',
		esc_html__( 'WPAgently wurde automatisch geschlossen.', 'wp-agent-companion' ),
		esc_html__( 'Die Website-Adresse stimmt nicht mit dem Domain Lock überein. Deaktiviere die alte Lizenzaktivierung und aktiviere diese Website bewusst neu.', 'wp-agent-companion' )
	);
}
add_action( 'admin_notices', 'wpagent_companion_control_admin_notice' );

function wpagent_companion_control_admin_bar( WP_Admin_Bar $bar ): void {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}
	$open  = wpagent_companion_gate_open();
	$power = function_exists( 'wpagent_power_is_enabled' ) && wpagent_power_is_enabled();
	$bar->add_node(
		array(
			'id'    => 'wpagently-status',
			'title' => $power ? __( 'WPAgently: Power aktiv', 'wp-agent-companion' ) : ( $open ? __( 'WPAgently: verbunden', 'wp-agent-companion' ) : __( 'WPAgently: geschlossen', 'wp-agent-companion' ) ),
			'href'  => admin_url( 'admin.php?page=wpagently' ),
			'meta'  => array( 'class' => $power ? 'wpagently-power-active' : '' ),
		)
	);
	if ( $open || $power ) {
		$bar->add_node(
			array(
				'id'     => 'wpagently-emergency-disable',
				'parent' => 'wpagently-status',
				'title'  => __( 'Alles sofort ausschalten', 'wp-agent-companion' ),
				'href'   => wp_nonce_url( admin_url( 'admin-post.php?action=wpagently_emergency_disable' ), 'wpagently_emergency_disable' ),
			)
		);
	}
}
add_action( 'admin_bar_menu', 'wpagent_companion_control_admin_bar', 90 );

function wpagent_companion_emergency_disable_handler(): void {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'Keine Berechtigung.', 'wp-agent-companion' ) );
	}
	check_admin_referer( 'wpagently_emergency_disable' );
	wpagent_companion_emergency_disable();
	wp_safe_redirect( add_query_arg( array( 'page' => 'wpagently', 'stopped' => '1' ), admin_url( 'admin.php' ) ) );
	exit;
}
add_action( 'admin_post_wpagently_emergency_disable', 'wpagent_companion_emergency_disable_handler' );

function wpagent_companion_control_page(): void {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}
	$paid        = 'paid' === wpagent_companion_access_tier();
	$catalog     = array_filter(
		wpagent_companion_ability_catalog(),
		static fn( array $definition, string $name ): bool => wpagent_companion_ability_entitled( $name ),
		ARRAY_FILTER_USE_BOTH
	);
	$disabled    = array_flip( wpagent_companion_disabled_abilities() );
	$diagnostics = wpagent_companion_diagnostics();
	$profile     = wpagent_companion_profile();
	$profile_readonly = 'readonly' === $profile;
	$enabled     = wpagent_companion_enabled_ability_names();
	$external_catalog = $paid ? wpagent_companion_external_ability_catalog() : array();
	$trusted_external = array_flip( wpagent_companion_trusted_external_abilities() );
	$wpforms_status = wpagent_companion_wpforms_integration_status();
	$wpforms_known = array_flip( wpagent_companion_wpforms_known_ability_names() );
	$ninjaforms_known = array_flip( wpagent_companion_ninjaforms_known_ability_names() );
	$generic_external_catalog = array_filter(
		$external_catalog,
		static fn( string $name ): bool => ! isset( $wpforms_known[ $name ] )
			&& ! isset( $ninjaforms_known[ $name ] )
			&& ( ! str_starts_with( $name, 'wpforms/' ) || wpagent_companion_ability_is_mcp_public( wpagent_companion_get_registered_ability( $name ) ) ),
		ARRAY_FILTER_USE_KEY
	);
	$wpforms_forms_enabled = ! empty( $wpforms_status['available_forms'] )
		&& empty( array_diff( $wpforms_status['available_forms'], array_keys( $trusted_external ) ) );
	$wpforms_entries_enabled = ! empty( $wpforms_status['available_entries'] )
		&& empty( array_diff( $wpforms_status['available_entries'], array_keys( $trusted_external ) ) );
	$wpforms_write_enabled = $wpforms_status['write_access_enabled']
		&& ! empty( $wpforms_status['available_write'] )
		&& empty( array_diff( $wpforms_status['available_write'], array_keys( $trusted_external ) ) );
	$groups      = array();
	foreach ( $catalog as $name => $definition ) {
		$groups[ $definition['group'] ][ $name ] = $definition;
	}
	?>
	<div class="wrap wpagently-admin">
		<div class="wpagently-admin__head">
			<h1><?php esc_html_e( 'WPAgently Kontrollzentrum', 'wp-agent-companion' ); ?></h1>
		</div>
		<?php if ( isset( $_GET['updated'] ) ) : // phpcs:ignore WordPress.Security.NonceVerification.Recommended ?>
			<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Einstellungen gespeichert.', 'wp-agent-companion' ); ?></p></div>
		<?php endif; ?>
		<?php if ( isset( $_GET['stopped'] ) ) : // phpcs:ignore WordPress.Security.NonceVerification.Recommended ?>
			<div class="notice notice-warning is-dismissible"><p><?php esc_html_e( 'Companion und alle Power-Stufen wurden ausgeschaltet.', 'wp-agent-companion' ); ?></p></div>
		<?php endif; ?>
		<?php if ( ! $paid ) : ?>
			<div class="notice notice-info"><p><strong><?php esc_html_e( 'WPAgently Free ist aktiv.', 'wp-agent-companion' ); ?></strong> <?php esc_html_e( 'Du kannst 34 geprüfte Kern-Abilities ohne Aufrufslimit und ohne Lizenzschlüssel verwenden. Eine Lizenz schaltet alle 414 Companion-Abilities, Integrationen und Power frei.', 'wp-agent-companion' ); ?></p></div>
		<?php endif; ?>
		<p>
			<a class="button button-primary" href="<?php echo esc_url( admin_url( 'admin.php?page=wpagently-connect' ) ); ?>"><?php esc_html_e( 'Agent verbinden', 'wp-agent-companion' ); ?></a>
			<a class="button" href="<?php echo esc_url( admin_url( 'admin.php?page=wpagently-context' ) ); ?>"><?php esc_html_e( 'Agent-Wissen öffnen', 'wp-agent-companion' ); ?></a>
			<a class="button" href="<?php echo esc_url( admin_url( 'tools.php?page=wpagently-license' ) ); ?>"><?php echo esc_html( $paid ? __( 'Lizenz verwalten', 'wp-agent-companion' ) : __( 'Free erweitern', 'wp-agent-companion' ) ); ?></a>
		</p>
		<h2><?php esc_html_e( 'Systemstatus', 'wp-agent-companion' ); ?></h2>
		<div class="wpagently-card wpagently-card--narrow">
		<table class="widefat striped"><tbody>
		<?php foreach ( $diagnostics as $check ) : ?>
			<tr><th class="wpagently-status-label"><?php echo esc_html( wpagent_companion_diagnostic_label( $check['name'] ) ); ?></th><td><span class="wpagently-badge <?php echo $check['ok'] ? 'wpagently-badge--safe' : 'wpagently-badge--risk'; ?>"><?php echo esc_html( $check['ok'] ? __( 'OK', 'wp-agent-companion' ) : __( 'Fehler', 'wp-agent-companion' ) ); ?></span> <?php echo esc_html( $check['detail'] ); ?></td></tr>
		<?php endforeach; ?>
		</tbody></table>
		</div>

		<form class="wpagently-form--narrow" method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
			<input type="hidden" name="action" value="wpagently_save_control">
			<?php wp_nonce_field( 'wpagent_companion_control_save' ); ?>
			<h2><?php esc_html_e( 'Verbindung', 'wp-agent-companion' ); ?></h2>
			<label><input type="checkbox" name="companion_enabled" value="1" <?php checked( wpagent_companion_enabled() ); ?>> <?php esc_html_e( 'Companion-Abilities und MCP-Server aktivieren', 'wp-agent-companion' ); ?></label>
			<?php if ( $paid ) : ?>
				<p class="description"><?php esc_html_e( 'Der Domain Lock bleibt unabhängig davon aktiv. Bei einer geklonten Website öffnet sich die Verbindung nicht automatisch.', 'wp-agent-companion' ); ?></p>
			<?php else : ?>
				<p class="description"><?php esc_html_e( 'Free ist an die Anmeldung und Berechtigungen dieser WordPress-Website gebunden. Der zusätzliche Domain Lock gehört zur bezahlten Lizenz.', 'wp-agent-companion' ); ?></p>
			<?php endif; ?>

			<h2><?php esc_html_e( 'Ability-Profil', 'wp-agent-companion' ); ?></h2>
			<select name="ability_profile" id="ability_profile">
			<?php foreach ( wpagent_companion_profiles() as $profile_name ) : ?>
				<option value="<?php echo esc_attr( $profile_name ); ?>" <?php selected( $profile, $profile_name ); ?>><?php echo esc_html( wpagent_companion_profile_label( $profile_name ) ); ?></option>
			<?php endforeach; ?>
			</select>
			<?php /* translators: 1: active ability count, 2: total ability count. */ ?>
			<p class="description"><strong><?php echo esc_html( sprintf( __( '%1$d von %2$d Abilities sind in diesem Profil aktiv.', 'wp-agent-companion' ), count( $enabled ), count( $catalog ) ) ); ?></strong> <?php echo esc_html( wpagent_companion_profile_description( $profile ) ); ?></p>

			<details style="margin-top:20px" <?php echo empty( $disabled ) ? '' : 'open'; ?>>
				<?php /* translators: %d: number of individually disabled abilities. */ ?>
				<summary style="cursor:pointer"><strong><?php esc_html_e( 'Erweiterte Feineinstellungen', 'wp-agent-companion' ); ?></strong> <?php echo esc_html( sprintf( __( '(%d einzeln deaktiviert)', 'wp-agent-companion' ), count( $disabled ) ) ); ?></summary>
				<p><?php esc_html_e( 'Markierte Abilities werden zusätzlich zum Profil vollständig aus REST und MCP entfernt.', 'wp-agent-companion' ); ?></p>
				<?php foreach ( $groups as $group => $abilities ) : ?>
					<details style="margin:8px 0 8px 16px">
						<?php /* translators: 1: ability group label, 2: ability count in the group. */ ?>
						<summary style="cursor:pointer"><?php echo esc_html( sprintf( __( '%1$s (%2$d)', 'wp-agent-companion' ), wpagent_companion_group_label( $group ), count( $abilities ) ) ); ?></summary>
						<table class="widefat striped" style="margin-top:8px"><thead><tr><th style="width:120px"><?php esc_html_e( 'Deaktivieren', 'wp-agent-companion' ); ?></th><th><?php esc_html_e( 'Ability', 'wp-agent-companion' ); ?></th></tr></thead><tbody>
						<?php foreach ( array_keys( $abilities ) as $name ) : ?>
							<?php $ability_definition = $abilities[ $name ]; ?>
							<?php /* translators: %s: machine-readable ability name. */ ?>
							<tr><td<?php echo empty( $ability_definition['readonly'] ) ? ' class="wpagently-rail--risk"' : ''; ?>><label><input type="checkbox" name="disabled_abilities[]" value="<?php echo esc_attr( $name ); ?>" <?php checked( isset( $disabled[ $name ] ) ); ?>><span class="screen-reader-text"><?php echo esc_html( sprintf( __( '%s deaktivieren', 'wp-agent-companion' ), $name ) ); ?></span></label></td><td><code><?php echo esc_html( $name ); ?></code></td></tr>
						<?php endforeach; ?>
						</tbody></table>
					</details>
				<?php endforeach; ?>
			</details>

			<?php if ( $paid && $wpforms_status['detected'] ) : ?>
			<details style="margin-top:20px" open>
				<summary style="cursor:pointer"><strong><?php esc_html_e( 'WPForms-Integration', 'wp-agent-companion' ); ?></strong></summary>
				<p><?php esc_html_e( 'WPAgently verwendet die nativen WPForms-Abilities. WPForms behält die Kontrolle über Berechtigungen, Schemas und Schreibzugriff. Es werden keine WPForms-Sicherheitsschalter überschrieben.', 'wp-agent-companion' ); ?></p>
				<table class="widefat striped"><tbody>
					<tr>
						<th style="width:240px"><?php esc_html_e( 'Formulare lesen', 'wp-agent-companion' ); ?></th>
						<td>
							<label><input type="checkbox" name="wpforms_forms_enabled" value="1" <?php checked( $wpforms_forms_enabled ); ?> <?php disabled( empty( $wpforms_status['available_forms'] ) ); ?>> <?php esc_html_e( 'Native Formular-Lese-Abilities freigeben', 'wp-agent-companion' ); ?></label><br>
							<?php /* translators: 1: available form abilities, 2: registered form abilities. */ ?>
							<small><?php echo esc_html( sprintf( __( '%1$d von %2$d registrierten Formular-Abilities sind von WPForms für MCP veröffentlicht.', 'wp-agent-companion' ), count( $wpforms_status['available_forms'] ), count( $wpforms_status['registered_forms'] ) ) ); ?></small>
						</td>
					</tr>
					<tr>
						<th><?php esc_html_e( 'Einträge lesen', 'wp-agent-companion' ); ?></th>
						<td>
							<label><input type="checkbox" name="wpforms_entries_enabled" value="1" <?php checked( $wpforms_entries_enabled ); ?> <?php disabled( empty( $wpforms_status['available_entries'] ) ); ?>> <?php esc_html_e( 'Native Eintrags-Abilities separat freigeben', 'wp-agent-companion' ); ?></label><br>
							<?php if ( empty( $wpforms_status['registered_entries'] ) ) : ?>
								<small><?php esc_html_e( 'Eintrags-Abilities sind in WPForms Lite nicht enthalten und benötigen derzeit WPForms Pro.', 'wp-agent-companion' ); ?></small>
							<?php else : ?>
								<?php /* translators: 1: available entry abilities, 2: registered entry abilities. */ ?>
								<small><?php echo esc_html( sprintf( __( '%1$d von %2$d registrierten Eintrags-Abilities sind von WPForms für MCP veröffentlicht. Einträge können personenbezogene Daten enthalten.', 'wp-agent-companion' ), count( $wpforms_status['available_entries'] ), count( $wpforms_status['registered_entries'] ) ) ); ?></small>
							<?php endif; ?>
						</td>
					</tr>
					<tr>
						<th><?php esc_html_e( 'Formulare bearbeiten', 'wp-agent-companion' ); ?></th>
						<td>
							<?php if ( $profile_readonly && $wpforms_write_enabled ) : ?><input type="hidden" name="wpforms_write_enabled" value="1"><?php endif; ?>
							<label><input type="checkbox" name="wpforms_write_enabled" value="1" <?php checked( $wpforms_write_enabled ); ?> <?php disabled( ! $wpforms_status['write_access_enabled'] || $profile_readonly ); ?>> <?php esc_html_e( 'Alle aktuell verfügbaren nativen Schreib-Abilities freigeben', 'wp-agent-companion' ); ?></label><br>
							<?php if ( $profile_readonly ) : ?>
								<small><?php esc_html_e( 'Schreib-Abilities bleiben im Profil Nur lesen vollständig gesperrt.', 'wp-agent-companion' ); ?></small><br>
							<?php endif; ?>
							<?php if ( ! $wpforms_status['write_access_enabled'] ) : ?>
								<small><?php esc_html_e( 'Der native WPForms-Schreibzugriff ist noch nicht vollständig aktiviert. Aktiviere ihn zuerst unter WPForms > Werkzeuge > AI MCP. Anschließend erscheint diese Freigabe.', 'wp-agent-companion' ); ?> <a href="<?php echo esc_url( admin_url( 'admin.php?page=wpforms-tools' ) ); ?>"><?php esc_html_e( 'WPForms-Werkzeuge öffnen', 'wp-agent-companion' ); ?></a></small>
							<?php else : ?>
								<?php /* translators: %d: available write abilities. */ ?>
								<small><?php echo esc_html( sprintf( __( 'WPForms veröffentlicht derzeit %d Schreib- und Schema-Abilities für MCP.', 'wp-agent-companion' ), count( $wpforms_status['available_write'] ) ) ); ?></small>
							<?php endif; ?>
						</td>
					</tr>
				</tbody></table>
				<p class="description"><?php esc_html_e( 'Der verbundene WordPress-Benutzer benötigt zusätzlich die von WPForms verlangten Rechte. Fehlende Rechte werden weiterhin von WPForms mit 403 abgelehnt.', 'wp-agent-companion' ); ?></p>
			</details>
			<?php endif; ?>

			<?php if ( $paid ) : ?>
				<?php wpagent_companion_ninjaforms_control_controls(); ?>
			<?php endif; ?>

			<?php if ( $paid && ! empty( $generic_external_catalog ) ) : ?>
			<details style="margin-top:20px" <?php echo empty( $trusted_external ) ? '' : 'open'; ?>>
				<summary style="cursor:pointer"><strong><?php esc_html_e( 'Abilities anderer Plugins', 'wp-agent-companion' ); ?></strong></summary>
				<p><?php esc_html_e( 'Diese Abilities stammen nicht von WPAgently. Prüfe den jeweiligen Anbieter und gib nur Funktionen frei, deren Wirkung du verstehst. WPAgently kann fremde Schreibpfade nicht verifizieren.', 'wp-agent-companion' ); ?></p>
				<table class="widefat striped"><thead><tr><th style="width:120px"><?php esc_html_e( 'Freigeben', 'wp-agent-companion' ); ?></th><th><?php esc_html_e( 'Ability', 'wp-agent-companion' ); ?></th><th><?php esc_html_e( 'Beschreibung', 'wp-agent-companion' ); ?></th></tr></thead><tbody>
				<?php foreach ( $generic_external_catalog as $name => $definition ) : ?>
					<?php $profile_blocks_ability = $profile_readonly && empty( $definition['readonly'] ); ?>
					<tr><td><label>
						<?php if ( $profile_blocks_ability && isset( $trusted_external[ $name ] ) ) : ?>
							<input type="hidden" name="trusted_external_abilities[]" value="<?php echo esc_attr( $name ); ?>">
						<?php endif; ?>
						<input type="checkbox" name="trusted_external_abilities[]" value="<?php echo esc_attr( $name ); ?>" <?php checked( isset( $trusted_external[ $name ] ) ); ?> <?php disabled( $profile_blocks_ability ); ?>><span class="screen-reader-text"><?php echo esc_html( $definition['label'] ); ?></span>
					</label></td><td><code><?php echo esc_html( $name ); ?></code><br><small><?php echo esc_html( $definition['readonly'] ? __( 'nur lesend', 'wp-agent-companion' ) : __( 'schreibend', 'wp-agent-companion' ) ); ?><?php echo $definition['destructive'] ? esc_html( ', ' . __( 'destruktiv', 'wp-agent-companion' ) ) : ''; ?><?php echo $profile_blocks_ability ? esc_html( ', ' . __( 'im Profil Nur lesen gesperrt', 'wp-agent-companion' ) ) : ''; ?></small></td><td><strong><?php echo esc_html( $definition['label'] ); ?></strong><br><?php echo esc_html( $definition['description'] ); ?></td></tr>
				<?php endforeach; ?>
				</tbody></table>
			</details>
			<?php endif; ?>
			<?php submit_button( __( 'WPAgently-Einstellungen speichern', 'wp-agent-companion' ) ); ?>
		</form>
	</div>
	<?php
}
