<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use LoginAsUser\Module;
use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

if ( ! function_exists( 'wp_powersuite_is_license_valid' ) || ! wp_powersuite_is_license_valid() ) {
	$license_page_url = admin_url( 'admin.php?page=powersuite-license' );
	?>
	<div class="wp-powersuite-module-settings wpps-settings-panel" data-module-id="<?php echo esc_attr( $module_id ?? 'login-as-user' ); ?>">
		<div class="notice notice-warning inline" style="margin:0;">
			<p>
				<?php esc_html_e( 'Login as User requires an active license. Activate your license to configure user impersonation.', 'wp-powersuite' ); ?>
				<a href="<?php echo esc_url( $license_page_url ); ?>"><?php esc_html_e( 'Activate license', 'wp-powersuite' ); ?></a>
			</p>
		</div>
	</div>
	<?php
	return;
}

if ( ! isset( $module_id ) || empty( $module_id ) ) {
	$module_id = 'login-as-user';
}

$settings = OptionStoreModuleSettingsRepository::forModule( $module_id )->all( Module::getDefaultSettings() );
if ( ! is_array( $settings ) ) {
	$settings = Module::getDefaultSettings();
}

$session_duration = max( 5, min( 1440, absint( $settings['session_duration_minutes'] ?? 60 ) ) );
$audit_max        = max( 10, min( 500, absint( $settings['audit_max_entries'] ?? 100 ) ) );
$blocked_caps     = is_string( $settings['blocked_target_capabilities'] ?? '' )
	? $settings['blocked_target_capabilities']
	: 'manage_options, manage_network, edit_users';

$audit_rows = get_option( Module::AUDIT_OPTION_KEY, [] );
if ( ! is_array( $audit_rows ) ) {
	$audit_rows = [];
}
$audit_rows = array_reverse( $audit_rows );

$event_labels = [
	'start'            => __( 'Started impersonation', 'wp-powersuite' ),
	'switch_back'      => __( 'Switched back', 'wp-powersuite' ),
	'expired'          => __( 'Session expired', 'wp-powersuite' ),
	'logout'           => __( 'Ended on logout', 'wp-powersuite' ),
	'module_disabled'  => __( 'Module disabled', 'wp-powersuite' ),
	'invalid_original' => __( 'Invalid original user', 'wp-powersuite' ),
];
?>

<div class="wp-powersuite-module-settings" data-module-id="<?php echo esc_attr( $module_id ); ?>">
	<form class="wp-powersuite-module-settings-form" data-module-id="<?php echo esc_attr( $module_id ); ?>">
		<?php wp_nonce_field( 'wp_powersuite_save_module_settings_' . $module_id, 'wp_powersuite_nonce' ); ?>

		<p class="description">
			<?php esc_html_e( 'Allow trusted administrators to preview the site as another user for support or QA. Impersonation sessions are time-limited and recorded below.', 'wp-powersuite' ); ?>
		</p>

		<table class="form-table" role="presentation">
			<tbody>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_session_duration_minutes">
							<?php esc_html_e( 'Session time limit (minutes)', 'wp-powersuite' ); ?>
						</label>
					</th>
					<td>
						<input
							type="number"
							id="<?php echo esc_attr( $module_id ); ?>_session_duration_minutes"
							name="<?php echo esc_attr( $module_id ); ?>[session_duration_minutes]"
							value="<?php echo esc_attr( $session_duration ); ?>"
							min="5"
							max="1440"
							class="small-text wp-powersuite-advanced-setting"
							data-setting-key="session_duration_minutes"
						/>
						<p class="description"><?php esc_html_e( 'Maximum duration before the administrator is switched back automatically (5–1440 minutes).', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_audit_max_entries">
							<?php esc_html_e( 'Audit log retention (entries)', 'wp-powersuite' ); ?>
						</label>
					</th>
					<td>
						<input
							type="number"
							id="<?php echo esc_attr( $module_id ); ?>_audit_max_entries"
							name="<?php echo esc_attr( $module_id ); ?>[audit_max_entries]"
							value="<?php echo esc_attr( $audit_max ); ?>"
							min="10"
							max="500"
							class="small-text wp-powersuite-advanced-setting"
							data-setting-key="audit_max_entries"
						/>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_blocked_target_capabilities">
							<?php esc_html_e( 'Blocked target capabilities', 'wp-powersuite' ); ?>
						</label>
					</th>
					<td>
						<textarea
							id="<?php echo esc_attr( $module_id ); ?>_blocked_target_capabilities"
							name="<?php echo esc_attr( $module_id ); ?>[blocked_target_capabilities]"
							rows="4"
							class="large-text code wp-powersuite-advanced-setting"
							data-setting-key="blocked_target_capabilities"
						><?php echo esc_textarea( $blocked_caps ); ?></textarea>
						<p class="description"><?php esc_html_e( 'One capability per line. Users with any listed capability cannot be impersonated.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
			</tbody>
		</table>
	</form>

	<h3><?php esc_html_e( 'Recent impersonation audit log', 'wp-powersuite' ); ?></h3>
	<?php if ( $audit_rows === [] ) : ?>
		<p><?php esc_html_e( 'No impersonation events recorded yet.', 'wp-powersuite' ); ?></p>
	<?php else : ?>
		<table class="widefat striped">
			<thead>
				<tr>
					<th scope="col"><?php esc_html_e( 'Time', 'wp-powersuite' ); ?></th>
					<th scope="col"><?php esc_html_e( 'Event', 'wp-powersuite' ); ?></th>
					<th scope="col"><?php esc_html_e( 'Administrator', 'wp-powersuite' ); ?></th>
					<th scope="col"><?php esc_html_e( 'Target user', 'wp-powersuite' ); ?></th>
					<th scope="col"><?php esc_html_e( 'IP', 'wp-powersuite' ); ?></th>
				</tr>
			</thead>
			<tbody>
				<?php foreach ( array_slice( $audit_rows, 0, 25 ) as $row ) : ?>
					<?php
					if ( ! is_array( $row ) ) {
						continue;
					}
					$event   = isset( $row['e'] ) ? (string) $row['e'] : 'start';
					$actor   = isset( $row['a'] ) ? (int) $row['a'] : 0;
					$target  = isset( $row['b'] ) ? (int) $row['b'] : 0;
					$actor_u = $actor > 0 ? get_userdata( $actor ) : false;
					$tgt_u   = $target > 0 ? get_userdata( $target ) : false;
					?>
					<tr>
						<td><?php echo esc_html( isset( $row['t'] ) ? (string) $row['t'] : '' ); ?></td>
						<td><?php echo esc_html( $event_labels[ $event ] ?? $event ); ?></td>
						<td>
							<?php
							if ( $actor_u ) {
								echo esc_html( $actor_u->user_login . ' (#' . $actor . ')' );
							} elseif ( $actor > 0 ) {
								echo esc_html( '#' . $actor );
							} else {
								echo '&mdash;';
							}
							?>
						</td>
						<td>
							<?php
							if ( $tgt_u ) {
								echo esc_html( $tgt_u->user_login . ' (#' . $target . ')' );
							} elseif ( $target > 0 ) {
								echo esc_html( '#' . $target );
							} else {
								echo '&mdash;';
							}
							?>
						</td>
						<td><?php echo esc_html( isset( $row['i'] ) ? (string) $row['i'] : '' ); ?></td>
					</tr>
				<?php endforeach; ?>
			</tbody>
		</table>
	<?php endif; ?>
</div>
