<?php
/**
 * Users admin page for Clicks User Manager.
 *
 * @package WP_User_Management
 */

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

/**
 * Render the All Users admin page.
 */
function wpum_render_users_page() {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'Permission denied.', 'clicks-user-manager' ) );
	}

	// Collect filter params from GET (filters are applied via GET for bookmarkability).
	$params = array(
		'role'        => isset( $_GET['role'] ) ? sanitize_key( wp_unslash( $_GET['role'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification
		'search'      => isset( $_GET['s'] ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification
		'date_from'   => isset( $_GET['date_from'] ) ? sanitize_text_field( wp_unslash( $_GET['date_from'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification
		'date_to'     => isset( $_GET['date_to'] ) ? sanitize_text_field( wp_unslash( $_GET['date_to'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification
		'last_login'  => isset( $_GET['last_login'] ) ? sanitize_key( wp_unslash( $_GET['last_login'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification
		'inactive'    => isset( $_GET['inactive'] ) ? absint( wp_unslash( $_GET['inactive'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification
		'post_count'  => isset( $_GET['post_count'] ) ? sanitize_key( wp_unslash( $_GET['post_count'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification
		'orders'      => isset( $_GET['orders'] ) ? sanitize_key( wp_unslash( $_GET['orders'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification
		'login_from'  => isset( $_GET['login_from'] ) ? sanitize_text_field( wp_unslash( $_GET['login_from'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification
		'login_to'    => isset( $_GET['login_to'] ) ? sanitize_text_field( wp_unslash( $_GET['login_to'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification
		'ltv_min'     => isset( $_GET['ltv_min'] ) ? sanitize_text_field( wp_unslash( $_GET['ltv_min'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification
		'ltv_max'     => isset( $_GET['ltv_max'] ) ? sanitize_text_field( wp_unslash( $_GET['ltv_max'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification
		'aov_min'     => isset( $_GET['aov_min'] ) ? sanitize_text_field( wp_unslash( $_GET['aov_min'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification
		'aov_max'     => isset( $_GET['aov_max'] ) ? sanitize_text_field( wp_unslash( $_GET['aov_max'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification
		'meta_key'    => isset( $_GET['meta_key'] ) ? sanitize_key( wp_unslash( $_GET['meta_key'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification
		'meta_value'  => isset( $_GET['meta_value'] ) ? sanitize_text_field( wp_unslash( $_GET['meta_value'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification
		'orderby'     => isset( $_GET['orderby'] ) ? sanitize_key( wp_unslash( $_GET['orderby'] ) ) : 'registered', // phpcs:ignore WordPress.Security.NonceVerification
		'order'       => isset( $_GET['order'] ) ? sanitize_key( wp_unslash( $_GET['order'] ) ) : 'DESC', // phpcs:ignore WordPress.Security.NonceVerification
		'per_page'    => isset( $_GET['per_page'] ) ? absint( wp_unslash( $_GET['per_page'] ) ) : 20, // phpcs:ignore WordPress.Security.NonceVerification
		'paged'       => isset( $_GET['paged'] ) ? max( 1, absint( wp_unslash( $_GET['paged'] ) ) ) : 1, // phpcs:ignore WordPress.Security.NonceVerification
	);

	$query_args = wpum_build_query_args( $params );
	$user_query = new WP_User_Query( $query_args );
	$users      = $user_query->get_results();
	$total      = (int) $user_query->get_total();

	$per_page   = isset( $query_args['number'] ) ? (int) $query_args['number'] : 20;
	$paged      = $params['paged'];
	$total_pages = $per_page > 0 ? (int) ceil( $total / $per_page ) : 1;

	$base_url = admin_url( 'admin.php?page=clicks-user-manager' );
	$all_roles = wp_roles()->roles;

	$wc_active     = wpum_is_woocommerce_active();
	$order_counts  = $wc_active ? wpum_get_customer_order_counts() : array();

	?>
	<div class="wrap wpum-wrap">
		<?php wpum_upsell_banner(); ?>
		<h1 class="wp-heading-inline"><?php esc_html_e( 'User Management', 'clicks-user-manager' ); ?></h1>
		<span class="wpum-total-badge"><?php
			/* translators: %d: total users count */
			printf(
				esc_html( _n( '%s user', '%s users', $total, 'clicks-user-manager' ) ),
				esc_html( number_format_i18n( $total ) )
			);
		?></span>

		<hr class="wp-header-end" />

		<!-- Notices placeholder -->
		<div id="wpum-notice-wrap">
			<?php if ( isset( $_GET['wpum_notice'] ) && 'switched_back' === $_GET['wpum_notice'] ) : // phpcs:ignore WordPress.Security.NonceVerification ?>
				<div class="wpum-notice success">
					<span>✓ <?php esc_html_e( 'Switched back to administrator session successfully.', 'clicks-user-manager' ); ?></span>
					<button type="button" class="wpum-notice-dismiss">&times;</button>
				</div>
			<?php endif; ?>
			<?php if ( isset( $_GET['wpum_error'] ) && 'imp_limit' === $_GET['wpum_error'] ) : // phpcs:ignore WordPress.Security.NonceVerification ?>
				<div class="wpum-notice error">
					<span>✗ <?php esc_html_e( 'Free version limit reached: You can only impersonate users up to 3 times per month. Please upgrade to Pro for unlimited logins.', 'clicks-user-manager' ); ?></span>
					<button type="button" class="wpum-notice-dismiss">&times;</button>
				</div>
			<?php endif; ?>
		</div>

		<!-- Filter Bar -->
		<div class="wpum-filter-bar">
			<form id="wpum-filter-form" method="get" action="<?php echo esc_url( $base_url ); ?>">
				<input type="hidden" name="page" value="clicks-user-manager" />

				<div class="wpum-filter-row">
					<?php wpum_render_segments_selector(); ?>

					<!-- Search -->
					<div class="wpum-filter-group wpum-filter-search">
						<input type="search"
							name="s"
							id="wpum-search"
							class="regular-text"
							placeholder="<?php esc_attr_e( 'Search by name, email or username…', 'clicks-user-manager' ); ?>"
							value="<?php echo esc_attr( $params['search'] ); ?>"
						/>
					</div>

					<!-- Role -->
					<div class="wpum-filter-group">
						<select name="role" id="wpum-filter-role">
							<?php wpum_role_dropdown_options( $params['role'] ); ?>
						</select>
					</div>

					<!-- Last Login -->
					<div class="wpum-filter-group">
						<select name="last_login" id="wpum-filter-last-login">
							<option value=""><?php esc_html_e( 'Last Login: Any', 'clicks-user-manager' ); ?></option>
							<option value="today" <?php selected( $params['last_login'], 'today' ); ?>><?php esc_html_e( 'Today', 'clicks-user-manager' ); ?></option>
							<option value="this_week" <?php selected( $params['last_login'], 'this_week' ); ?>><?php esc_html_e( 'This Week', 'clicks-user-manager' ); ?></option>
							<option value="this_month" <?php selected( $params['last_login'], 'this_month' ); ?>><?php esc_html_e( 'This Month', 'clicks-user-manager' ); ?></option>
							<option value="never" <?php selected( $params['last_login'], 'never' ); ?>><?php esc_html_e( 'Never Logged In', 'clicks-user-manager' ); ?></option>
						</select>
					</div>

					<!-- Inactive -->
					<div class="wpum-filter-group">
						<select name="inactive" id="wpum-filter-inactive">
							<option value=""><?php esc_html_e( 'Inactive: Any', 'clicks-user-manager' ); ?></option>
							<option value="30" <?php selected( $params['inactive'], '30' ); ?>><?php esc_html_e( 'No login 30 days', 'clicks-user-manager' ); ?></option>
							<option value="60" <?php selected( $params['inactive'], '60' ); ?>><?php esc_html_e( 'No login 60 days', 'clicks-user-manager' ); ?></option>
							<option value="90" <?php selected( $params['inactive'], '90' ); ?>><?php esc_html_e( 'No login 90 days', 'clicks-user-manager' ); ?></option>
						</select>
					</div>

					<!-- Post count -->
					<div class="wpum-filter-group">
						<select name="post_count" id="wpum-filter-post-count">
							<option value=""><?php esc_html_e( 'Posts: Any', 'clicks-user-manager' ); ?></option>
							<option value="has_posts" <?php selected( $params['post_count'], 'has_posts' ); ?>><?php esc_html_e( 'Has Posts', 'clicks-user-manager' ); ?></option>
							<option value="no_posts" <?php selected( $params['post_count'], 'no_posts' ); ?>><?php esc_html_e( 'No Posts', 'clicks-user-manager' ); ?></option>
						</select>
					</div>

					<?php if ( $wc_active ) : ?>
					<!-- WooCommerce orders -->
					<div class="wpum-filter-group">
						<select name="orders" id="wpum-filter-orders">
							<option value=""><?php esc_html_e( 'Orders: Any', 'clicks-user-manager' ); ?></option>
							<option value="has_orders" <?php selected( $params['orders'], 'has_orders' ); ?>><?php esc_html_e( 'Has Ordered', 'clicks-user-manager' ); ?></option>
							<option value="no_orders" <?php selected( $params['orders'], 'no_orders' ); ?>><?php esc_html_e( 'No Orders', 'clicks-user-manager' ); ?></option>
							<option value="1" <?php selected( $params['orders'], '1' ); ?>><?php esc_html_e( '1 Order', 'clicks-user-manager' ); ?></option>
							<option value="2_5" <?php selected( $params['orders'], '2_5' ); ?>><?php esc_html_e( '2–5 Orders', 'clicks-user-manager' ); ?></option>
							<option value="6_plus" <?php selected( $params['orders'], '6_plus' ); ?>><?php esc_html_e( '6+ Orders', 'clicks-user-manager' ); ?></option>
						</select>
					</div>
					<?php endif; ?>

					<!-- Date range -->
					<div class="wpum-filter-group">
						<input type="date" name="date_from" id="wpum-date-from" value="<?php echo esc_attr( $params['date_from'] ); ?>" placeholder="<?php esc_attr_e( 'From', 'clicks-user-manager' ); ?>" title="<?php esc_attr_e( 'Registered From', 'clicks-user-manager' ); ?>" />
					</div>
					<div class="wpum-filter-group">
						<input type="date" name="date_to" id="wpum-date-to" value="<?php echo esc_attr( $params['date_to'] ); ?>" placeholder="<?php esc_attr_e( 'To', 'clicks-user-manager' ); ?>" title="<?php esc_attr_e( 'Registered To', 'clicks-user-manager' ); ?>" />
					</div>

					<div class="wpum-filter-group">
						<button type="submit" class="button button-primary"><?php esc_html_e( 'Filter', 'clicks-user-manager' ); ?></button>
						<a href="<?php echo esc_url( $base_url ); ?>" class="button"><?php esc_html_e( 'Reset', 'clicks-user-manager' ); ?></a>
						<button type="button" id="wpum-toggle-adv-filters" class="button button-secondary">
							<span class="dashicons dashicons-filter" style="margin-top: 4px;"></span>
							<?php esc_html_e( 'Advanced Filters', 'clicks-user-manager' ); ?>
						</button>
					</div>
				</div>

				<!-- Advanced Filters Section -->
				<div class="wpum-adv-filters-panel" id="wpum-adv-filters-panel" style="display:none; position:relative; background:#f6f7f7; border:1px solid #c3c4c7; padding:15px; margin-top:10px; border-radius:4px;">
					<?php if ( ! wpum_is_pro() ) : ?>
						<div class="wpum-pro-overlay" style="position:absolute; inset:0; background:rgba(246, 247, 247, 0.85); display:flex; align-items:center; justify-content:center; flex-direction:column; z-index:10; border-radius:4px;">
							<span style="font-size:28px; margin-bottom:5px;">🔒</span>
							<strong style="color:#000; font-size:14px;"><?php esc_html_e( 'Advanced Filters is a Pro Feature', 'clicks-user-manager' ); ?></strong>
							<p style="margin:5px 0 0; font-size:11px;"><a href="<?php echo esc_url( admin_url('admin.php?page=clicks-user-manager-about') ); ?>" class="button button-primary button-small"><?php esc_html_e( 'Upgrade to Pro', 'clicks-user-manager' ); ?></a></p>
						</div>
					<?php endif; ?>

					<h4 style="margin: 0 0 12px 0; font-weight:600;"><?php esc_html_e( 'Advanced Segmentation Filters', 'clicks-user-manager' ); ?></h4>
					
					<div style="display:flex; flex-wrap:wrap; gap:15px;">
						<!-- Last Login Date Range -->
						<div style="flex:1; min-width: 220px;">
							<label style="display:block; font-weight:600; margin-bottom:4px; font-size:12px;"><?php esc_html_e( 'Last Login Date Range', 'clicks-user-manager' ); ?></label>
							<div style="display:flex; gap:5px; align-items:center;">
								<input type="date" name="login_from" value="<?php echo esc_attr( $params['login_from'] ); ?>" style="width: 100%;" title="<?php esc_attr_e( 'Login From', 'clicks-user-manager' ); ?>" />
								<span>-</span>
								<input type="date" name="login_to" value="<?php echo esc_attr( $params['login_to'] ); ?>" style="width: 100%;" title="<?php esc_attr_e( 'Login To', 'clicks-user-manager' ); ?>" />
							</div>
						</div>

						<!-- Custom Meta Filter -->
						<div style="flex:1; min-width: 220px;">
							<label style="display:block; font-weight:600; margin-bottom:4px; font-size:12px;"><?php esc_html_e( 'Filter by Custom User Meta', 'clicks-user-manager' ); ?></label>
							<div style="display:flex; gap:5px; align-items:center;">
								<input type="text" name="meta_key" placeholder="<?php esc_attr_e( 'Meta key…', 'clicks-user-manager' ); ?>" value="<?php echo esc_attr( $params['meta_key'] ); ?>" style="width: 100%;" />
								<span>=</span>
								<input type="text" name="meta_value" placeholder="<?php esc_attr_e( 'Value…', 'clicks-user-manager' ); ?>" value="<?php echo esc_attr( $params['meta_value'] ); ?>" style="width: 100%;" />
							</div>
						</div>

						<?php if ( $wc_active ) : ?>
							<!-- WooCommerce LTV Filter -->
							<div style="flex:1; min-width: 220px;">
								<label style="display:block; font-weight:600; margin-bottom:4px; font-size:12px;"><?php esc_html_e( 'WooCommerce Lifetime Value (LTV)', 'clicks-user-manager' ); ?></label>
								<div style="display:flex; gap:5px; align-items:center;">
									<input type="number" step="0.01" name="ltv_min" placeholder="<?php esc_attr_e( 'Min spent $…', 'clicks-user-manager' ); ?>" value="<?php echo esc_attr( $params['ltv_min'] ); ?>" style="width: 100%;" />
									<span>-</span>
									<input type="number" step="0.01" name="ltv_max" placeholder="<?php esc_attr_e( 'Max spent $…', 'clicks-user-manager' ); ?>" value="<?php echo esc_attr( $params['ltv_max'] ); ?>" style="width: 100%;" />
								</div>
							</div>

							<!-- WooCommerce AOV Filter -->
							<div style="flex:1; min-width: 220px;">
								<label style="display:block; font-weight:600; margin-bottom:4px; font-size:12px;"><?php esc_html_e( 'WooCommerce Average Order Value (AOV)', 'clicks-user-manager' ); ?></label>
								<div style="display:flex; gap:5px; align-items:center;">
									<input type="number" step="0.01" name="aov_min" placeholder="<?php esc_attr_e( 'Min AOV $…', 'clicks-user-manager' ); ?>" value="<?php echo esc_attr( $params['aov_min'] ); ?>" style="width: 100%;" />
									<span>-</span>
									<input type="number" step="0.01" name="aov_max" placeholder="<?php esc_attr_e( 'Max AOV $…', 'clicks-user-manager' ); ?>" value="<?php echo esc_attr( $params['aov_max'] ); ?>" style="width: 100%;" />
								</div>
							</div>
						<?php endif; ?>
					</div>
				</div>
			</form>
		</div>

		<!-- Bulk Actions Bar -->
		<div class="wpum-bulk-bar">
			<div class="wpum-bulk-left">
				<select id="wpum-bulk-action">
					<option value=""><?php esc_html_e( '— Bulk Actions —', 'clicks-user-manager' ); ?></option>
					<option value="delete"><?php esc_html_e( 'Delete', 'clicks-user-manager' ); ?></option>
					<option value="change_role"><?php esc_html_e( 'Change Role', 'clicks-user-manager' ); ?></option>
					<option value="export_csv"><?php esc_html_e( 'Export Selected to CSV', 'clicks-user-manager' ); ?></option>
					<option value="bulk_mail"><?php esc_html_e( 'Send Bulk Mail', 'clicks-user-manager' ); ?></option>
					<option value="bulk_note"><?php esc_html_e( 'Add Note (Pro)', 'clicks-user-manager' ); ?></option>
				</select>

				<select id="wpum-bulk-role" style="display:none;">
					<?php
					foreach ( $all_roles as $role_key => $role ) {
						$role_name = translate_user_role( $role['name'] );
						echo '<option value="' . esc_attr( $role_key ) . '">' . esc_html( $role_name ) . '</option>';
					}
					?>
				</select>

				<button type="button" id="wpum-apply-bulk" class="button button-primary">
					<?php esc_html_e( 'Apply', 'clicks-user-manager' ); ?>
				</button>

				<span class="wpum-spinner" id="wpum-bulk-spinner"></span>
				<span class="wpum-selected-count" id="wpum-selected-count"></span>
			</div>

			<div class="wpum-bulk-right">
				<select id="wpum-per-page" title="<?php esc_attr_e( 'Users per page', 'clicks-user-manager' ); ?>">
					<option value="20" <?php selected( $per_page, 20 ); ?>><?php esc_html_e( '20 per page', 'clicks-user-manager' ); ?></option>
					<option value="50" <?php selected( $per_page, 50 ); ?>><?php esc_html_e( '50 per page', 'clicks-user-manager' ); ?></option>
					<option value="100" <?php selected( $per_page, 100 ); ?>><?php esc_html_e( '100 per page', 'clicks-user-manager' ); ?></option>
				</select>
			</div>
		</div>

		<!-- Users Table -->
		<div class="wpum-table-wrap">
			<table class="widefat wpum-users-table" id="wpum-users-table">
				<thead>
					<tr>
						<th class="wpum-col-cb"><input type="checkbox" id="wpum-select-all" title="<?php esc_attr_e( 'Select all', 'clicks-user-manager' ); ?>" /></th>
						<?php
						$cols = array(
							'login'      => __( 'Username', 'clicks-user-manager' ),
							'email'      => __( 'Email', 'clicks-user-manager' ),
							'role'       => __( 'Role', 'clicks-user-manager' ),
							'registered' => __( 'Registered', 'clicks-user-manager' ),
							'last_login' => __( 'Last Login', 'clicks-user-manager' ),
							'post_count' => __( 'Posts', 'clicks-user-manager' ),
						);

						if ( $wc_active ) {
							$cols['orders'] = __( 'Orders', 'clicks-user-manager' );
						}

						$cols['notes'] = __( 'Notes', 'clicks-user-manager' );

						foreach ( $cols as $col_key => $col_label ) :
							$is_sortable   = in_array( $col_key, array( 'login', 'email', 'registered', 'last_login', 'post_count' ), true );
							$current_order = $params['orderby'] === $col_key ? $params['order'] : '';
							$next_order    = ( 'ASC' === $current_order ) ? 'DESC' : 'ASC';
							$sort_url      = add_query_arg( array( 'orderby' => $col_key, 'order' => $next_order ), $base_url );
							$sort_class    = '';
							if ( $current_order ) {
								$sort_class = 'ASC' === $current_order ? 'sorted asc' : 'sorted desc';
							}
							?>
							<th class="<?php echo esc_attr( 'wpum-col-' . $col_key . ' ' . $sort_class ); ?>">
								<?php if ( $is_sortable ) : ?>
									<a href="<?php echo esc_url( $sort_url ); ?>">
										<?php echo esc_html( $col_label ); ?>
										<span class="sorting-indicators">
											<span class="sorting-indicator asc" aria-hidden="true"></span>
											<span class="sorting-indicator desc" aria-hidden="true"></span>
										</span>
									</a>
								<?php else : ?>
									<?php echo esc_html( $col_label ); ?>
								<?php endif; ?>
							</th>
							<?php
						endforeach;
						?>
						<th class="wpum-col-actions"><?php esc_html_e( 'Actions', 'clicks-user-manager' ); ?></th>
					</tr>
				</thead>
				<tbody>
					<?php if ( empty( $users ) ) : ?>
						<tr>
							<td colspan="<?php echo esc_attr( $wc_active ? 10 : 9 ); ?>" class="wpum-no-users">
								<?php esc_html_e( 'No users found matching your filters.', 'clicks-user-manager' ); ?>
							</td>
						</tr>
					<?php else : ?>
						<?php foreach ( $users as $user ) :
							$last_login    = get_user_meta( $user->ID, '_wpum_last_login', true );
							$post_count    = wpum_count_user_published_posts( $user->ID );
							$roles_display = array();
							foreach ( $user->roles as $r ) {
								$roles_display[] = isset( $all_roles[ $r ]['name'] ) ? translate_user_role( $all_roles[ $r ]['name'] ) : $r;
							}
							$edit_url       = get_edit_user_link( $user->ID );
							$posts_url      = add_query_arg( array( 'post_type' => 'post', 'author' => $user->ID ), admin_url( 'edit.php' ) );
							$is_current     = ( get_current_user_id() === $user->ID );
							?>
							<tr data-user-id="<?php echo esc_attr( $user->ID ); ?>" class="<?php echo $is_current ? 'wpum-current-user' : ''; ?>">
								<td class="wpum-col-cb">
									<?php if ( ! $is_current ) : ?>
										<input type="checkbox" class="wpum-user-cb" value="<?php echo esc_attr( $user->ID ); ?>" />
									<?php endif; ?>
								</td>
								<td class="wpum-col-login">
									<strong><a href="<?php echo esc_url( $edit_url ); ?>"><?php echo esc_html( $user->user_login ); ?></a></strong>
									<?php if ( $is_current ) : ?>
										<span class="wpum-you-badge"><?php esc_html_e( 'You', 'clicks-user-manager' ); ?></span>
									<?php endif; ?>
									<?php if ( $user->first_name || $user->last_name ) : ?>
										<br /><span class="wpum-display-name"><?php echo esc_html( trim( $user->first_name . ' ' . $user->last_name ) ); ?></span>
									<?php endif; ?>
								</td>
								<td class="wpum-col-email">
									<a href="mailto:<?php echo esc_attr( $user->user_email ); ?>"><?php echo esc_html( $user->user_email ); ?></a>
								</td>
								<td class="wpum-col-role">
									<?php echo esc_html( implode( ', ', $roles_display ) ); ?>
								</td>
								<td class="wpum-col-registered">
									<?php echo esc_html( wp_date( get_option( 'date_format' ), strtotime( $user->user_registered ) ) ); ?>
								</td>
								<td class="wpum-col-last-login">
									<?php if ( $last_login ) : ?>
										<?php echo esc_html( wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $last_login ) ) ); ?>
									<?php else : ?>
										<span class="wpum-never"><?php esc_html_e( 'Never', 'clicks-user-manager' ); ?></span>
									<?php endif; ?>
								</td>
								<td class="wpum-col-post-count">
									<?php if ( $post_count > 0 ) : ?>
										<a href="<?php echo esc_url( $posts_url ); ?>"><?php echo esc_html( number_format_i18n( $post_count ) ); ?></a>
									<?php else : ?>
										0
									<?php endif; ?>
								</td>
								<?php if ( $wc_active ) : ?>
								<td class="wpum-col-orders">
									<?php
									$order_count = isset( $order_counts[ $user->ID ] ) ? $order_counts[ $user->ID ] : 0;
									if ( $order_count > 0 ) :
										$orders_url = admin_url( 'admin.php?page=wc-orders&_customer_user=' . $user->ID );
										?>
										<a href="<?php echo esc_url( $orders_url ); ?>"><?php echo esc_html( number_format_i18n( $order_count ) ); ?></a>
									<?php else : ?>
										0
									<?php endif; ?>
								</td>
								<?php endif; ?>
								<td class="wpum-col-notes">
									<?php
									$notes = wpum_get_user_notes( $user->ID );
									$note_count = count( $notes );
									?>
									<button type="button" class="wpum-notes-trigger button button-link" data-user-id="<?php echo esc_attr( $user->ID ); ?>" data-username="<?php echo esc_attr( $user->user_login ); ?>">
										<span class="dashicons dashicons-admin-comments"></span>
										<span class="wpum-notes-count"><?php echo esc_html( $note_count ); ?></span>
									</button>
								</td>
								<td class="wpum-col-actions">
									<div class="wpum-row-actions">
										<button type="button" class="button button-small wpum-quick-edit-trigger" data-user-id="<?php echo esc_attr( $user->ID ); ?>" data-username="<?php echo esc_attr( $user->user_login ); ?>" title="<?php esc_attr_e( 'Quick Edit', 'clicks-user-manager' ); ?>">
											<span class="dashicons dashicons-edit"></span>
										</button>
										<?php if ( ! $is_current ) : ?>
											<a href="<?php echo esc_url( admin_url( '?wpum_action=login_as&user_id=' . $user->ID . '&_wpnonce=' . wp_create_nonce( 'wpum_login_as_nonce' ) ) ); ?>" class="button button-small" title="<?php esc_attr_e( 'Login As User', 'clicks-user-manager' ); ?>">
												<span class="dashicons dashicons-admin-network"></span>
											</a>
											<button type="button"
												class="button button-small wpum-delete-single button-link-delete"
												data-user-id="<?php echo esc_attr( $user->ID ); ?>"
												data-username="<?php echo esc_attr( $user->user_login ); ?>"
												title="<?php esc_attr_e( 'Delete User', 'clicks-user-manager' ); ?>">
												<span class="dashicons dashicons-trash"></span>
											</button>
										<?php endif; ?>
										<?php if ( $post_count > 0 ) : ?>
											<a href="<?php echo esc_url( $posts_url ); ?>" class="button button-small" title="<?php esc_attr_e( 'View Posts', 'clicks-user-manager' ); ?>">
												<span class="dashicons dashicons-admin-post"></span>
											</a>
										<?php endif; ?>
									</div>
								</td>
							</tr>
						<?php endforeach; ?>
					<?php endif; ?>
				</tbody>
			</table>
		</div>

		<!-- Pagination -->
		<?php if ( $total_pages > 1 ) : ?>
			<div class="wpum-pagination">
				<span class="wpum-pagination-info">
					<?php
					$start = ( ( $paged - 1 ) * $per_page ) + 1;
					$end   = min( $paged * $per_page, $total );
					/* translators: 1: start, 2: end, 3: total */
					printf( esc_html__( 'Showing %1$s–%2$s of %3$s users', 'clicks-user-manager' ), esc_html( number_format_i18n( $start ) ), esc_html( number_format_i18n( $end ) ), esc_html( number_format_i18n( $total ) ) );
					?>
				</span>

				<span class="wpum-pagination-links">
					<?php
					$page_links = paginate_links(
						array(
							'base'      => add_query_arg( 'paged', '%#%', $base_url ),
							'format'    => '',
							'prev_text' => '&laquo;',
							'next_text' => '&raquo;',
							'total'     => $total_pages,
							'current'   => $paged,
							'add_args'  => array_filter(
								array(
									's'          => $params['search'],
									'role'       => $params['role'],
									'date_from'  => $params['date_from'],
									'date_to'    => $params['date_to'],
									'last_login' => $params['last_login'],
									'inactive'   => $params['inactive'],
									'post_count' => $params['post_count'],
									'orders'     => $params['orders'],
									'login_from' => $params['login_from'],
									'login_to'   => $params['login_to'],
									'ltv_min'    => $params['ltv_min'],
									'ltv_max'    => $params['ltv_max'],
									'aov_min'    => $params['aov_min'],
									'aov_max'    => $params['aov_max'],
									'meta_key'   => $params['meta_key'],
									'meta_value' => $params['meta_value'],
									'orderby'    => $params['orderby'],
									'order'      => $params['order'],
									'per_page'   => $per_page !== 20 ? $per_page : '',
								)
							),
						)
					);
					echo wp_kses_post( $page_links );
					?>
				</span>
			</div>
		<?php endif; ?>

	</div>

	<!-- Delete Confirmation Modal -->
	<div id="wpum-delete-modal" class="wpum-modal" aria-hidden="true" role="dialog" aria-labelledby="wpum-modal-title">
		<div class="wpum-modal-backdrop"></div>
		<div class="wpum-modal-dialog">
			<div class="wpum-modal-header">
				<h2 id="wpum-modal-title">
					<span class="dashicons dashicons-warning"></span>
					<?php esc_html_e( 'Confirm Deletion', 'clicks-user-manager' ); ?>
				</h2>
			</div>
			<div class="wpum-modal-body">
				<p id="wpum-modal-message"></p>
				<p class="wpum-modal-warning"><?php esc_html_e( 'This action cannot be undone.', 'clicks-user-manager' ); ?></p>
			</div>
			<div class="wpum-modal-footer">
				<button type="button" id="wpum-modal-cancel" class="button button-large"><?php esc_html_e( 'Cancel', 'clicks-user-manager' ); ?></button>
				<button type="button" id="wpum-modal-confirm" class="button button-large button-delete-confirm"><?php esc_html_e( 'Yes, Delete', 'clicks-user-manager' ); ?></button>
			</div>
		</div>
	</div>

	<!-- Bulk Mail Modal -->
	<div id="wpum-mail-modal" class="wpum-modal" aria-hidden="true" role="dialog" aria-labelledby="wpum-mail-modal-title">
		<div class="wpum-modal-backdrop"></div>
		<div class="wpum-modal-dialog wpum-modal-large">
			<div class="wpum-modal-header">
				<h2 id="wpum-mail-modal-title">
					<span class="dashicons dashicons-email-alt"></span>
					<?php esc_html_e( 'Send Bulk Email', 'clicks-user-manager' ); ?>
				</h2>
				<button type="button" class="wpum-modal-close" id="wpum-mail-modal-close" aria-label="<?php esc_attr_e( 'Close', 'clicks-user-manager' ); ?>">&times;</button>
			</div>
			<div class="wpum-modal-body">
				<p class="description">
					<?php esc_html_e( 'You can personalise messages using: {first_name}, {last_name}, {username}, {email}.', 'clicks-user-manager' ); ?>
					<?php if ( wpum_is_pro() ) : ?>
						<span style="display:block; margin-top:4px; color:#2271b1; font-weight:600;"><?php esc_html_e( 'Pro Tokens: {registration_date}, {last_login_date}, {wc_total_spent}, {wc_order_count}, {wc_last_order_date}, {meta:key}', 'clicks-user-manager' ); ?></span>
					<?php else : ?>
						<span style="display:block; margin-top:4px; color:#646970;"><?php esc_html_e( 'Upgrade to Pro for more tokens: {registration_date}, {last_login_date}, {wc_total_spent}, {meta:key}', 'clicks-user-manager' ); ?></span>
					<?php endif; ?>
				</p>
				<table class="form-table">
					<tr>
						<th><label for="wpum-mail-subject"><?php esc_html_e( 'Subject', 'clicks-user-manager' ); ?> <span class="required">*</span></label></th>
						<td><input type="text" id="wpum-mail-subject" class="large-text" placeholder="<?php esc_attr_e( 'Email subject…', 'clicks-user-manager' ); ?>" /></td>
					</tr>
					<tr>
						<th><label for="wpum-mail-message"><?php esc_html_e( 'Message', 'clicks-user-manager' ); ?> <span class="required">*</span></label></th>
						<td>
							<textarea id="wpum-mail-message" class="large-text" rows="10" placeholder="<?php esc_attr_e( 'Your message here…', 'clicks-user-manager' ); ?>"></textarea>
						</td>
					</tr>
				</table>
				<div id="wpum-mail-result" class="wpum-mail-result" style="display:none;"></div>
			</div>
			<div class="wpum-modal-footer">
				<button type="button" id="wpum-mail-cancel" class="button button-large"><?php esc_html_e( 'Cancel', 'clicks-user-manager' ); ?></button>
				<button type="button" id="wpum-mail-send" class="button button-primary button-large">
					<span class="dashicons dashicons-email"></span>
					<?php esc_html_e( 'Send Emails', 'clicks-user-manager' ); ?>
				</button>
				<span class="wpum-spinner" id="wpum-mail-spinner"></span>
			</div>
		</div>
	</div>
	</div>

	<!-- User Notes Modal -->
	<div id="wpum-notes-modal" class="wpum-modal" aria-hidden="true" role="dialog" aria-labelledby="wpum-notes-modal-title">
		<div class="wpum-modal-backdrop"></div>
		<div class="wpum-modal-dialog">
			<div class="wpum-notes-modal-content">
				<div class="wpum-modal-header">
					<h2 id="wpum-notes-modal-title">
						<span class="dashicons dashicons-admin-comments"></span>
						<?php esc_html_e( 'User Notes:', 'clicks-user-manager' ); ?> <span id="wpum-notes-modal-username" style="font-weight:bold;"></span>
					</h2>
					<button type="button" class="wpum-modal-close" id="wpum-notes-modal-close" aria-label="<?php esc_attr_e( 'Close', 'clicks-user-manager' ); ?>">&times;</button>
				</div>
				<div class="wpum-modal-body">
					<!-- Add note section -->
					<div id="wpum-add-note-wrap">
						<textarea id="wpum-new-note-text" placeholder="<?php esc_attr_e( 'Type note here…', 'clicks-user-manager' ); ?>" rows="3" style="width:100%; margin-bottom: 8px;"></textarea>
						<div class="wpum-note-actions" style="display:flex; justify-content:space-between; align-items:center;">
							<button type="button" id="wpum-save-note-btn" class="button button-primary button-small"><?php esc_html_e( 'Add Note', 'clicks-user-manager' ); ?></button>
							<span id="wpum-note-limit-msg" class="wpum-note-limit-msg description"></span>
						</div>
					</div>
					<hr />
					<!-- Notes list -->
					<div id="wpum-notes-list" class="wpum-notes-list" style="max-height: 250px; overflow-y: auto;">
						<p class="description wpum-no-notes"><?php esc_html_e( 'No notes yet.', 'clicks-user-manager' ); ?></p>
					</div>
				</div>
			</div>
		</div>
	</div>

	<!-- Bulk Note Modal -->
	<div id="wpum-bulk-note-modal" class="wpum-modal" aria-hidden="true" role="dialog" aria-labelledby="wpum-bulk-note-title">
		<div class="wpum-modal-backdrop"></div>
		<div class="wpum-modal-dialog">
			<div class="wpum-modal-header">
				<h2 id="wpum-bulk-note-title">
					<span class="dashicons dashicons-admin-comments"></span>
					<?php esc_html_e( 'Bulk Add Note', 'clicks-user-manager' ); ?>
					<?php if ( ! wpum_is_pro() ) : ?>
						<span class="wpum-pro-badge-inline" style="background:#ffb900; color:#000; font-size:10px; padding:2px 6px; border-radius:3px; margin-left:5px; font-weight:bold; vertical-align:middle; text-transform:uppercase;">PRO</span>
					<?php endif; ?>
				</h2>
				<button type="button" class="wpum-modal-close" id="wpum-bulk-note-close" aria-label="<?php esc_attr_e( 'Close', 'clicks-user-manager' ); ?>">&times;</button>
			</div>
			<div class="wpum-modal-body">
				<?php if ( wpum_is_pro() ) : ?>
					<p class="description"><?php esc_html_e( 'Add this note to all selected users.', 'clicks-user-manager' ); ?></p>
					<textarea id="wpum-bulk-note-text" placeholder="<?php esc_attr_e( 'Type note here…', 'clicks-user-manager' ); ?>" rows="4" style="width:100%;"></textarea>
				<?php else : ?>
					<div class="wpum-pro-lock-message" style="text-align:center; padding: 20px 10px;">
						<span class="wpum-lock-icon" style="font-size:32px; display:block; margin-bottom:10px;">🔒</span>
						<h3><?php esc_html_e( 'Bulk Notes is a Pro Feature', 'clicks-user-manager' ); ?></h3>
						<p><?php esc_html_e( 'Upgrade to the Premium version to add notes to multiple users in bulk.', 'clicks-user-manager' ); ?></p>
						<p style="margin-top:15px;"><a href="<?php echo esc_url( admin_url( 'admin.php?page=clicks-user-manager-about' ) ); ?>" class="button button-primary"><?php esc_html_e( 'Upgrade to Pro', 'clicks-user-manager' ); ?></a></p>
					</div>
				<?php endif; ?>
			</div>
			<div class="wpum-modal-footer">
				<button type="button" id="wpum-bulk-note-cancel" class="button button-large"><?php esc_html_e( 'Cancel', 'clicks-user-manager' ); ?></button>
				<?php if ( wpum_is_pro() ) : ?>
					<button type="button" id="wpum-bulk-note-save" class="button button-primary button-large"><?php esc_html_e( 'Add Note to Selected', 'clicks-user-manager' ); ?></button>
				<?php endif; ?>
			</div>
		</div>
	</div>

	<!-- Save Segment Modal -->
	<div id="wpum-save-segment-modal" class="wpum-modal" aria-hidden="true" role="dialog" aria-labelledby="wpum-save-segment-title">
		<div class="wpum-modal-backdrop"></div>
		<div class="wpum-modal-dialog">
			<div class="wpum-modal-header">
				<h2 id="wpum-save-segment-title">
					<span class="dashicons dashicons-star-filled" style="color:#ffb900;"></span>
					<?php esc_html_e( 'Save Current Filters', 'clicks-user-manager' ); ?>
				</h2>
				<button type="button" class="wpum-modal-close" id="wpum-save-segment-close" aria-label="<?php esc_attr_e( 'Close', 'clicks-user-manager' ); ?>">&times;</button>
			</div>
			<div class="wpum-modal-body">
				<p class="description"><?php esc_html_e( 'Enter a name for this filter template so you can reload it later with one click.', 'clicks-user-manager' ); ?></p>
				<table class="form-table" style="margin-top: 15px;">
					<tr>
						<th style="width: 120px; padding: 10px 0;"><label for="wpum-segment-name" style="font-weight:600;"><?php esc_html_e( 'Segment Name', 'clicks-user-manager' ); ?> <span class="required">*</span></label></th>
						<td style="padding: 10px 0;">
							<input type="text" id="wpum-segment-name" class="regular-text" placeholder="<?php esc_attr_e( 'e.g. Inactive Customers', 'clicks-user-manager' ); ?>" style="width:100%;" />
						</td>
					</tr>
				</table>
				<div id="wpum-segment-limit-msg" style="margin-top: 10px;"></div>
			</div>
			<div class="wpum-modal-footer">
				<button type="button" id="wpum-save-segment-cancel" class="button button-large"><?php esc_html_e( 'Cancel', 'clicks-user-manager' ); ?></button>
				<button type="button" id="wpum-save-segment-confirm" class="button button-primary button-large"><?php esc_html_e( 'Save Template', 'clicks-user-manager' ); ?></button>
			</div>
		</div>
	</div>

	<!-- Quick Edit Drawer -->
	<div class="wpum-drawer-backdrop" id="wpum-quick-edit-backdrop"></div>
	<div class="wpum-drawer" id="wpum-quick-edit-drawer">
		<div class="wpum-drawer-header">
			<h2>
				<span class="dashicons dashicons-admin-users" style="color: #2271b1;"></span>
				<?php esc_html_e( 'Quick Edit:', 'clicks-user-manager' ); ?> <span id="wpum-qe-username" style="font-weight:bold;"></span>
			</h2>
			<button type="button" class="wpum-drawer-close" id="wpum-quick-edit-close" aria-label="<?php esc_attr_e( 'Close', 'clicks-user-manager' ); ?>">&times;</button>
		</div>
		<div class="wpum-drawer-body">
			<form id="wpum-quick-edit-form">
				<input type="hidden" id="wpum-qe-user-id" name="ID" value="" />

				<p style="margin-bottom: 20px;">
					<a href="" id="wpum-qe-full-edit-link" target="_blank" class="button button-secondary button-small">
						<?php esc_html_e( 'Go to Full Edit Page ↗', 'clicks-user-manager' ); ?>
					</a>
				</p>

				<h3><?php esc_html_e( 'Account Details', 'clicks-user-manager' ); ?></h3>

				<div class="wpum-drawer-field-group">
					<label for="wpum-qe-email"><?php esc_html_e( 'Email Address', 'clicks-user-manager' ); ?> <span class="required">*</span></label>
					<input type="email" id="wpum-qe-email" name="user_email" required class="regular-text" />
				</div>

				<div class="wpum-drawer-field-group">
					<label for="wpum-qe-first-name"><?php esc_html_e( 'First Name', 'clicks-user-manager' ); ?></label>
					<input type="text" id="wpum-qe-first-name" name="first_name" class="regular-text" />
				</div>

				<div class="wpum-drawer-field-group">
					<label for="wpum-qe-last-name"><?php esc_html_e( 'Last Name', 'clicks-user-manager' ); ?></label>
					<input type="text" id="wpum-qe-last-name" name="last_name" class="regular-text" />
				</div>

				<div class="wpum-drawer-field-group">
					<label for="wpum-qe-display-name"><?php esc_html_e( 'Display Name', 'clicks-user-manager' ); ?></label>
					<input type="text" id="wpum-qe-display-name" name="display_name" class="regular-text" />
				</div>

				<div class="wpum-drawer-field-group">
					<label for="wpum-qe-role"><?php esc_html_e( 'Role', 'clicks-user-manager' ); ?></label>
					<select id="wpum-qe-role" name="role">
						<?php
						foreach ( $all_roles as $role_key => $role ) {
							$role_name = translate_user_role( $role['name'] );
							echo '<option value="' . esc_attr( $role_key ) . '">' . esc_html( $role_name ) . '</option>';
						}
						?>
					</select>
				</div>

				<h3><?php esc_html_e( 'Custom Meta Fields', 'clicks-user-manager' ); ?></h3>
				<div id="wpum-qe-meta-section">
					<!-- Meta fields list populated by JS -->
				</div>
			</form>
		</div>
		<div class="wpum-drawer-footer">
			<button type="button" id="wpum-qe-save-btn" class="button button-primary"><?php esc_html_e( 'Save Changes', 'clicks-user-manager' ); ?></button>
			<button type="button" id="wpum-qe-cancel-btn" class="button button-secondary"><?php esc_html_e( 'Cancel', 'clicks-user-manager' ); ?></button>
			<span class="wpum-spinner" id="wpum-qe-spinner" style="margin-left:auto;"></span>
		</div>
	</div>

	<?php
}
