<?php
/** WordPress-Admin-Freigabe für RFC-8628-Gerätecodes. */

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

function wpagent_companion_oauth_device_menu(): void {
	add_submenu_page(
		null,
		__( 'Gerät autorisieren', 'wp-agent-companion' ),
		__( 'Gerät autorisieren', 'wp-agent-companion' ),
		'manage_options',
		'wpagently-oauth-device',
		'wpagent_companion_oauth_device_page'
	);
}
add_action( 'admin_menu', 'wpagent_companion_oauth_device_menu', 30 );

function wpagent_companion_oauth_device_decision(): void {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'Keine Berechtigung.', 'wp-agent-companion' ), '', array( 'response' => 403 ) );
	}
	check_admin_referer( 'wpagent_companion_oauth_device' );
	$decision = isset( $_POST['decision'] ) ? sanitize_key( wp_unslash( $_POST['decision'] ) ) : '';
	$user_code = isset( $_POST['user_code'] ) && is_scalar( $_POST['user_code'] ) ? (string) wp_unslash( $_POST['user_code'] ) : '';
	$user_id = isset( $_POST['connection_user'] ) ? absint( $_POST['connection_user'] ) : 0;
	$result = wpagent_companion_oauth_decide_device_code( $user_code, $user_id, 'approve' === $decision );
	if ( is_wp_error( $result ) ) {
		wp_die( esc_html( $result->get_error_message() ), esc_html__( 'Gerät konnte nicht autorisiert werden', 'wp-agent-companion' ), array( 'response' => 400 ) );
	}
	wp_safe_redirect(
		add_query_arg(
			array(
				'page'          => 'wpagently-oauth-device',
				'device_result' => ! empty( $result['approved'] ) ? 'approved' : 'denied',
			),
			admin_url( 'admin.php' )
		)
	);
	exit;
}
add_action( 'admin_post_wpagently_oauth_device_decision', 'wpagent_companion_oauth_device_decision' );

function wpagent_companion_oauth_device_page(): void {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}
	$raw_code = isset( $_GET['user_code'] ) && is_scalar( $_GET['user_code'] ) ? (string) wp_unslash( $_GET['user_code'] ) : '';
	$user_code = wpagent_companion_oauth_normalize_device_user_code( $raw_code );
	$found = is_string( $user_code ) ? wpagent_companion_oauth_device_record_by_user_code( $user_code ) : null;
	$record = is_array( $found ) && absint( $found['record']['expires_at'] ?? 0 ) > time() && 'pending' === (string) ( $found['record']['status'] ?? '' ) ? $found['record'] : null;
	$users = wpagent_companion_connection_users( false );
	$result = isset( $_GET['device_result'] ) ? sanitize_key( wp_unslash( $_GET['device_result'] ) ) : '';
	?>
	<div class="wrap wpagently-admin wpagently-oauth-consent">
		<div class="wpagently-admin__head">
			<h1><?php esc_html_e( 'Gerät autorisieren', 'wp-agent-companion' ); ?></h1>
		</div>
		<?php if ( 'approved' === $result ) : ?>
			<div class="notice notice-success"><p><?php esc_html_e( 'Das Gerät wurde freigegeben. Es erhält seinen Zugang beim nächsten Abruf.', 'wp-agent-companion' ); ?></p></div>
		<?php elseif ( 'denied' === $result ) : ?>
			<div class="notice notice-info"><p><?php esc_html_e( 'Die Gerätefreigabe wurde abgelehnt.', 'wp-agent-companion' ); ?></p></div>
		<?php endif; ?>
		<?php if ( ! $record ) : ?>
			<p><?php esc_html_e( 'Gib den achtstelligen Code ein, den die wp-agent-CLI anzeigt.', 'wp-agent-companion' ); ?></p>
			<form method="get" action="<?php echo esc_url( admin_url( 'admin.php' ) ); ?>">
				<input type="hidden" name="page" value="wpagently-oauth-device">
				<label for="wpagently-device-code"><?php esc_html_e( 'Gerätecode', 'wp-agent-companion' ); ?></label>
				<input class="wpagently-code-input" id="wpagently-device-code" name="user_code" type="text" required maxlength="9" pattern="[A-Za-z2-9]{4}-[A-Za-z2-9]{4}" autocomplete="one-time-code" value="<?php echo esc_attr( is_string( $user_code ) ? $user_code : '' ); ?>">
				<?php submit_button( __( 'Code prüfen', 'wp-agent-companion' ), 'secondary', '', false ); ?>
			</form>
			<?php if ( '' !== $raw_code ) : ?>
				<div class="notice notice-error"><p><?php esc_html_e( 'Der Gerätecode ist ungültig, abgelaufen oder wurde bereits verwendet.', 'wp-agent-companion' ); ?></p></div>
			<?php endif; ?>
			<?php return; ?>
		<?php endif; ?>
		<div class="wpagently-card">
			<p><?php esc_html_e( 'Dieses Gerät fordert Zugriff auf folgende wpagently-Ressource an:', 'wp-agent-companion' ); ?></p>
			<ul>
				<li><strong><?php esc_html_e( 'Client', 'wp-agent-companion' ); ?>:</strong> <?php echo esc_html( (string) $record['client_name'] ); ?></li>
				<li><strong><?php esc_html_e( 'Ressource', 'wp-agent-companion' ); ?>:</strong> <?php echo esc_html( (string) $record['resource'] ); ?></li>
				<li><strong><?php esc_html_e( 'Berechtigungen', 'wp-agent-companion' ); ?>:</strong> <?php echo esc_html( (string) $record['scope'] ); ?></li>
			</ul>
			<?php if ( empty( $users ) ) : ?>
				<div class="notice notice-warning inline"><p><?php esc_html_e( 'Es gibt keinen geeigneten Redakteur. Lege zuerst unter wpagently > Agent verbinden einen dedizierten Agent-Nutzer an.', 'wp-agent-companion' ); ?></p></div>
			<?php else : ?>
				<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
					<input type="hidden" name="action" value="wpagently_oauth_device_decision">
					<input type="hidden" name="user_code" value="<?php echo esc_attr( $user_code ); ?>">
					<?php wp_nonce_field( 'wpagent_companion_oauth_device' ); ?>
					<p>
						<label for="wpagently-device-user"><?php esc_html_e( 'Agent-Nutzer', 'wp-agent-companion' ); ?></label><br>
						<select id="wpagently-device-user" name="connection_user">
							<?php foreach ( $users as $user ) : ?>
								<option value="<?php echo esc_attr( (string) $user['id'] ); ?>"><?php echo esc_html( $user['label'] ); ?></option>
							<?php endforeach; ?>
						</select>
					</p>
					<?php submit_button( __( 'Gerät freigeben', 'wp-agent-companion' ), 'primary', 'decision', false, array( 'value' => 'approve' ) ); ?>
					<?php submit_button( __( 'Ablehnen', 'wp-agent-companion' ), 'secondary', 'decision', false, array( 'value' => 'deny' ) ); ?>
				</form>
			<?php endif; ?>
		</div>
	</div>
	<?php
}
