<?php
/** WordPress-Adminsteuerung für native Ninja-Forms-Abilities. */

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

function wpagent_companion_ninjaforms_access_handler(): void {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'Keine Berechtigung.', 'wp-agent-companion' ) );
	}
	check_admin_referer( 'wpagent_companion_ninjaforms_access' );
	$mode    = isset( $_POST['ninjaforms_access_mode'] ) ? sanitize_key( wp_unslash( $_POST['ninjaforms_access_mode'] ) ) : '';
	$group   = isset( $_POST['ninjaforms_access_group'] ) ? sanitize_key( wp_unslash( $_POST['ninjaforms_access_group'] ) ) : '';
	$user_id = isset( $_POST['connection_user'] ) ? absint( $_POST['connection_user'] ) : 0;
	if ( ! in_array( $mode, array( 'enable', 'disable' ), true ) || ! array_key_exists( $group, wpagent_companion_ninjaforms_access_capabilities() ) ) {
		wp_die( esc_html__( 'Ungültige Aktion.', 'wp-agent-companion' ), esc_html__( 'Ninja-Forms-Rechte', 'wp-agent-companion' ), array( 'response' => 400 ) );
	}
	$result = wpagent_companion_ninjaforms_set_user_access( $user_id, $group, 'enable' === $mode );
	wp_safe_redirect( add_query_arg( array( 'page' => 'wpagently-connect', 'ninjaforms_access' => is_wp_error( $result ) ? 'error' : ( 'enable' === $mode ? 'enabled' : 'disabled' ) ), admin_url( 'admin.php' ) ) );
	exit;
}
add_action( 'admin_post_wpagently_ninjaforms_access', 'wpagent_companion_ninjaforms_access_handler' );

/** Gibt die vier MCP-Expositionsschalter innerhalb des Kontrollformulars aus. */
function wpagent_companion_ninjaforms_control_controls(): void {
	$status  = wpagent_companion_ninjaforms_integration_status();
	$trusted = array_flip( wpagent_companion_trusted_external_abilities() );
	$profile_readonly = 'readonly' === wpagent_companion_profile();
	if ( ! $status['detected'] ) {
		return;
	}
	$labels = array(
		'forms'       => __( 'Formulare und Strukturen lesen', 'wp-agent-companion' ),
		'submissions' => __( 'Einreichungen lesen und exportieren', 'wp-agent-companion' ),
		'write'       => __( 'Formulare bearbeiten und einbetten', 'wp-agent-companion' ),
		'delivery'    => __( 'Einreichungs-E-Mails erneut auslösen', 'wp-agent-companion' ),
	);
	?>
	<details style="margin-top:20px" open>
		<summary style="cursor:pointer"><strong><?php esc_html_e( 'Ninja Forms-Integration', 'wp-agent-companion' ); ?></strong></summary>
		<p><?php esc_html_e( 'WPAgently nutzt 24 native Ninja-Forms-Abilities und trennt Formularzugriff, personenbezogene Einreichungen, Schreibzugriff und E-Mail-Auslösung. Acht riskante Provider-Abilities bleiben in Quarantäne.', 'wp-agent-companion' ); ?></p>
		<table class="widefat striped"><tbody>
		<?php foreach ( $labels as $group => $label ) : ?>
			<?php
			$available = $status[ 'available_' . $group ];
			$enabled   = ! empty( $available ) && empty( array_diff( $available, array_keys( $trusted ) ) );
			$profile_blocks_group = $profile_readonly && in_array( $group, array( 'write', 'delivery' ), true );
			?>
			<tr><th style="width:280px"><?php echo esc_html( $label ); ?></th><td>
				<?php if ( $profile_blocks_group && $enabled ) : ?><input type="hidden" name="ninjaforms_<?php echo esc_attr( $group ); ?>_enabled" value="1"><?php endif; ?>
				<label><input type="checkbox" name="ninjaforms_<?php echo esc_attr( $group ); ?>_enabled" value="1" <?php checked( $enabled ); ?> <?php disabled( empty( $available ) || $profile_blocks_group ); ?>> <?php esc_html_e( 'Native Ability-Gruppe über den wpagently-MCP-Server freigeben', 'wp-agent-companion' ); ?></label><br>
				<?php if ( $profile_blocks_group ) : ?><small><?php esc_html_e( 'Diese Schreibgruppe bleibt im Profil Nur lesen vollständig gesperrt.', 'wp-agent-companion' ); ?></small><br><?php endif; ?>
				<?php /* translators: 1: available abilities, 2: registered abilities. */ ?>
				<small><?php echo esc_html( sprintf( __( '%1$d von %2$d erwarteten Abilities sind aktuell öffentlich verfügbar.', 'wp-agent-companion' ), count( $available ), count( $status[ 'registered_' . $group ] ) ) ); ?></small>
			</td></tr>
		<?php endforeach; ?>
		</tbody></table>
		<p class="description"><?php esc_html_e( 'Einreichungen können personenbezogene Daten enthalten. process-submission kann echte E-Mails versenden und bleibt deshalb doppelt opt-in-pflichtig.', 'wp-agent-companion' ); ?></p>
	</details>
	<?php
}

/**
 * @param array<int,array{id:int,login:string,name:string,roles:string[]}> $users
 */
function wpagent_companion_ninjaforms_connection_controls( array $users, int $selected_user_id ): void {
	$status = wpagent_companion_ninjaforms_integration_status();
	if ( ( ! $status['detected'] && ! wpagent_companion_ninjaforms_capability_grants() ) || ! $users ) {
		return;
	}
	$definitions = array(
		'forms'       => __( 'Formulare lesen', 'wp-agent-companion' ),
		'submissions' => __( 'Einreichungen lesen', 'wp-agent-companion' ),
		'write'       => __( 'Formulare bearbeiten', 'wp-agent-companion' ),
		'delivery'    => __( 'Einreichungs-E-Mails auslösen', 'wp-agent-companion' ),
	);
	?>
	<h2><?php esc_html_e( 'Ninja Forms für den Agent-Nutzer', 'wp-agent-companion' ); ?></h2>
	<?php /* translators: %s: Ninja Forms capability name wrapped in code markup. */ ?>
	<p><?php echo wp_kses_post( sprintf( __( 'Die Freigabe gilt nur während passender Aufrufe am wpagently-MCP-Endpunkt. Das Recht %s wird nie dauerhaft vergeben.', 'wp-agent-companion' ), '<code>nf_edit_forms</code>' ) ); ?></p>
	<?php foreach ( $definitions as $group => $label ) : ?>
		<h3><?php echo esc_html( $label ); ?></h3>
		<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
			<input type="hidden" name="action" value="wpagently_ninjaforms_access">
			<input type="hidden" name="ninjaforms_access_group" value="<?php echo esc_attr( $group ); ?>">
			<?php wp_nonce_field( 'wpagent_companion_ninjaforms_access' ); ?>
			<select name="connection_user" required>
			<?php foreach ( $users as $user ) : ?>
				<?php $state = wpagent_companion_ninjaforms_user_access( (int) $user['id'], $group ); ?>
				<option value="<?php echo esc_attr( (string) $user['id'] ); ?>" <?php selected( $selected_user_id, $user['id'] ); ?>><?php echo esc_html( $user['name'] . ' (' . $user['login'] . ')' . ( ! is_wp_error( $state ) && $state['enabled'] ? ' · ' . __( 'aktiv', 'wp-agent-companion' ) : '' ) ); ?></option>
			<?php endforeach; ?>
			</select>
			<p><button class="button button-secondary" type="submit" name="ninjaforms_access_mode" value="enable" <?php disabled( empty( $status[ 'available_' . $group ] ) ); ?>><?php esc_html_e( 'Recht aktivieren', 'wp-agent-companion' ); ?></button> <button class="button" type="submit" name="ninjaforms_access_mode" value="disable"><?php esc_html_e( 'Von wpagently ergänztes Recht entfernen', 'wp-agent-companion' ); ?></button></p>
		</form>
	<?php endforeach; ?>
	<?php
}
