<?php
/** Begrenzte, inhaltsarme Verwaltung des gespeicherten Agent-Memory. */

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

define( 'WPAGENT_COMPANION_MEMORY_ADMIN_PAGE_SIZE', 20 );

/** @return array<string,mixed>|WP_Error */
function wpagent_companion_memory_admin_query( $input = array() ) {
	$input = is_array( $input ) ? $input : array();
	$search = wpagent_state_text( $input['search'] ?? '', 200, 'memory_search' );
	if ( is_wp_error( $search ) ) {
		return $search;
	}
	$page = isset( $input['page_number'] ) && is_scalar( $input['page_number'] ) ? (int) $input['page_number'] : 1;
	$page = max( 1, min( 50, $page ) );
	$state = wpagent_memory_current_state();
	if ( is_wp_error( $state ) ) {
		return $state;
	}
	$items = array_values( array_filter( $state['memories'], static function ( array $memory ) use ( $search ): bool {
		return '' === $search || false !== stripos( $memory['title'] . "\n" . $memory['content'] . "\n" . implode( ' ', $memory['tags'] ), $search );
	} ) );
	usort( $items, static fn( array $a, array $b ): int => strcmp( $b['updated_at'], $a['updated_at'] ) );
	$total = count( $items );
	$pages = max( 1, (int) ceil( $total / WPAGENT_COMPANION_MEMORY_ADMIN_PAGE_SIZE ) );
	$page = min( $page, $pages );
	$items = array_map( static function ( array $memory ): array {
		return array(
			'id' => $memory['id'], 'title' => $memory['title'], 'tags' => $memory['tags'], 'updated_at' => $memory['updated_at'],
			'content_bytes' => strlen( $memory['content'] ),
		);
	}, array_slice( $items, ( $page - 1 ) * WPAGENT_COMPANION_MEMORY_ADMIN_PAGE_SIZE, WPAGENT_COMPANION_MEMORY_ADMIN_PAGE_SIZE ) );
	return array( 'items' => $items, 'total' => $total, 'page' => $page, 'pages' => $pages, 'search' => $search, 'state_hash' => $state['state_hash'], 'audit' => array_slice( $state['audit'], -10 ) );
}

function wpagent_companion_memory_admin_redirect( string $flag ): void {
	wp_safe_redirect( add_query_arg( array( 'page' => 'wpagently-context', $flag => '1' ), admin_url( 'admin.php' ) ) );
	exit;
}

function wpagent_companion_memory_delete(): void {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'Keine Berechtigung.', 'wp-agent-companion' ), '', array( 'response' => 403 ) );
	}
	check_admin_referer( 'wpagent_companion_memory_delete' );
	$result = wpagent_exec_delete_memory( array(
		'id' => isset( $_POST['memory_id'] ) ? wp_unslash( $_POST['memory_id'] ) : '',
		'expected_state_hash' => isset( $_POST['memory_state_hash'] ) ? wp_unslash( $_POST['memory_state_hash'] ) : '',
	) );
	if ( is_wp_error( $result ) ) {
		$data = $result->get_error_data();
		wp_die( esc_html( $result->get_error_message() ), esc_html__( 'Memory konnte nicht gelöscht werden.', 'wp-agent-companion' ), array( 'response' => is_array( $data ) ? max( 400, absint( $data['status'] ?? 409 ) ) : 409 ) );
	}
	wpagent_companion_memory_admin_redirect( 'memory_deleted' );
}
add_action( 'admin_post_wpagently_delete_memory', 'wpagent_companion_memory_delete' );

function wpagent_companion_memory_wipe(): void {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'Keine Berechtigung.', 'wp-agent-companion' ), '', array( 'response' => 403 ) );
	}
	check_admin_referer( 'wpagent_companion_memory_wipe' );
	$result = wpagent_exec_wipe_memory( array(
		'confirmation' => isset( $_POST['confirm_memory_wipe'] ) ? wp_unslash( $_POST['confirm_memory_wipe'] ) : '',
		'expected_state_hash' => isset( $_POST['memory_state_hash'] ) ? wp_unslash( $_POST['memory_state_hash'] ) : '',
	) );
	if ( is_wp_error( $result ) ) {
		$data = $result->get_error_data();
		wp_die( esc_html( $result->get_error_message() ), esc_html__( 'Memories konnten nicht gelöscht werden.', 'wp-agent-companion' ), array( 'response' => is_array( $data ) ? max( 400, absint( $data['status'] ?? 409 ) ) : 409 ) );
	}
	wpagent_companion_memory_admin_redirect( 'memory_wiped' );
}
add_action( 'admin_post_wpagently_wipe_memory', 'wpagent_companion_memory_wipe' );

/** @param array<string,mixed> $query */
function wpagent_companion_render_memory_admin_pagination( array $query ): void {
	if ( $query['pages'] < 2 ) {
		return;
	}
	$base = array( 'page' => 'wpagently-context', 'memory_search' => $query['search'] );
	?>
	<p class="tablenav-pages">
		<?php if ( $query['page'] > 1 ) : ?><a class="button" href="<?php echo esc_url( add_query_arg( array_merge( $base, array( 'memory_page' => $query['page'] - 1 ) ), admin_url( 'admin.php' ) ) ); ?>"><?php esc_html_e( 'Vorherige Seite', 'wp-agent-companion' ); ?></a><?php endif; ?>
		<span><?php echo esc_html( sprintf( __( 'Seite %1$d von %2$d', 'wp-agent-companion' ), $query['page'], $query['pages'] ) ); ?></span>
		<?php if ( $query['page'] < $query['pages'] ) : ?><a class="button" href="<?php echo esc_url( add_query_arg( array_merge( $base, array( 'memory_page' => $query['page'] + 1 ) ), admin_url( 'admin.php' ) ) ); ?>"><?php esc_html_e( 'Nächste Seite', 'wp-agent-companion' ); ?></a><?php endif; ?>
	</p>
	<?php
}

function wpagent_companion_render_memory_admin(): void {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}
	$query = wpagent_companion_memory_admin_query( array(
		'search' => isset( $_GET['memory_search'] ) ? wp_unslash( $_GET['memory_search'] ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		'page_number' => isset( $_GET['memory_page'] ) ? wp_unslash( $_GET['memory_page'] ) : 1, // phpcs:ignore WordPress.Security.NonceVerification.Recommended
	) );
	?>
	<h2><?php esc_html_e( 'Gespeicherte Memories', 'wp-agent-companion' ); ?></h2>
	<p><?php esc_html_e( 'Die Übersicht zeigt nie den gespeicherten Memory-Inhalt. Suche darf ihn finden, rendert ihn aber nicht.', 'wp-agent-companion' ); ?></p>
	<?php if ( is_wp_error( $query ) ) : ?>
		<div class="notice notice-error"><p><?php echo esc_html( $query->get_error_message() ); ?></p></div>
		<?php return; ?>
	<?php endif; ?>
	<?php if ( isset( $_GET['memory_deleted'] ) || isset( $_GET['memory_wiped'] ) ) : // phpcs:ignore WordPress.Security.NonceVerification.Recommended ?>
		<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Memory-Verwaltung aktualisiert.', 'wp-agent-companion' ); ?></p></div>
	<?php endif; ?>
	<form method="get" action="<?php echo esc_url( admin_url( 'admin.php' ) ); ?>">
		<input type="hidden" name="page" value="wpagently-context">
		<label for="memory_search" class="screen-reader-text"><?php esc_html_e( 'Memories durchsuchen', 'wp-agent-companion' ); ?></label>
		<input id="memory_search" name="memory_search" maxlength="200" value="<?php echo esc_attr( $query['search'] ); ?>" placeholder="<?php esc_attr_e( 'Titel, Tag oder Inhalt durchsuchen', 'wp-agent-companion' ); ?>">
		<?php submit_button( __( 'Memories suchen', 'wp-agent-companion' ), 'secondary', 'submit', false ); ?>
	</form>
	<p><?php echo esc_html( sprintf( __( '%d Memory-Einträge', 'wp-agent-companion' ), $query['total'] ) ); ?></p>
	<table class="widefat striped"><thead><tr><th><?php esc_html_e( 'ID', 'wp-agent-companion' ); ?></th><th><?php esc_html_e( 'Titel', 'wp-agent-companion' ); ?></th><th><?php esc_html_e( 'Tags', 'wp-agent-companion' ); ?></th><th><?php esc_html_e( 'Aktualisiert', 'wp-agent-companion' ); ?></th><th><?php esc_html_e( 'Inhalt', 'wp-agent-companion' ); ?></th><th><?php esc_html_e( 'Aktion', 'wp-agent-companion' ); ?></th></tr></thead><tbody>
	<?php foreach ( $query['items'] as $memory ) : ?>
		<tr><td><code><?php echo esc_html( $memory['id'] ); ?></code></td><td><?php echo esc_html( $memory['title'] ); ?></td><td><?php echo esc_html( implode( ', ', $memory['tags'] ) ); ?></td><td><?php echo esc_html( $memory['updated_at'] ); ?></td><td><?php echo esc_html( sprintf( __( '%d Bytes, nicht angezeigt', 'wp-agent-companion' ), $memory['content_bytes'] ) ); ?></td><td><form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>"><input type="hidden" name="action" value="wpagently_delete_memory"><input type="hidden" name="memory_id" value="<?php echo esc_attr( $memory['id'] ); ?>"><input type="hidden" name="memory_state_hash" value="<?php echo esc_attr( $query['state_hash'] ); ?>"><?php wp_nonce_field( 'wpagent_companion_memory_delete' ); ?><?php submit_button( __( 'Löschen', 'wp-agent-companion' ), 'delete small', 'submit', false ); ?></form></td></tr>
	<?php endforeach; ?>
	<?php if ( ! $query['items'] ) : ?><tr><td colspan="6"><?php esc_html_e( 'Keine Memories gefunden.', 'wp-agent-companion' ); ?></td></tr><?php endif; ?>
	</tbody></table>
	<?php wpagent_companion_render_memory_admin_pagination( $query ); ?>
	<details style="margin-top:20px"><summary><strong><?php esc_html_e( 'Alle Memories endgültig löschen', 'wp-agent-companion' ); ?></strong></summary>
		<p><?php echo esc_html( sprintf( __( 'Tippe zur Bestätigung exakt „%s“ ein. Die Inhalte können nicht wiederhergestellt werden.', 'wp-agent-companion' ), WPAGENT_COMPANION_MEMORY_WIPE_CONFIRMATION ) ); ?></p>
		<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>"><input type="hidden" name="action" value="wpagently_wipe_memory"><input type="hidden" name="memory_state_hash" value="<?php echo esc_attr( $query['state_hash'] ); ?>"><label><input name="confirm_memory_wipe" maxlength="64" required></label><?php wp_nonce_field( 'wpagent_companion_memory_wipe' ); ?><?php submit_button( __( 'Alle Memories löschen', 'wp-agent-companion' ), 'delete', 'submit', false ); ?></form>
	</details>
	<?php if ( $query['audit'] ) : ?><h3><?php esc_html_e( 'Letzte Memory-Aktionen', 'wp-agent-companion' ); ?></h3><table class="widefat striped"><thead><tr><th><?php esc_html_e( 'Aktion', 'wp-agent-companion' ); ?></th><th><?php esc_html_e( 'Zeit', 'wp-agent-companion' ); ?></th><th><?php esc_html_e( 'Memory-ID', 'wp-agent-companion' ); ?></th><th><?php esc_html_e( 'Nutzer-ID', 'wp-agent-companion' ); ?></th><th><?php esc_html_e( 'Anzahl', 'wp-agent-companion' ); ?></th></tr></thead><tbody><?php foreach ( array_reverse( $query['audit'] ) as $entry ) : ?><tr><td><?php echo esc_html( $entry['action'] ); ?></td><td><?php echo esc_html( $entry['at'] ); ?></td><td><code><?php echo esc_html( $entry['memory_id'] ); ?></code></td><td><?php echo esc_html( $entry['actor_id'] ); ?></td><td><?php echo esc_html( $entry['total'] ); ?></td></tr><?php endforeach; ?></tbody></table><?php endif; ?>
	<?php
}
