<?php
/**
 * Customers list page template.
 *
 * @package TrustLens\Admin\Views
 * @since   1.0.0
 */

defined( 'ABSPATH' ) || exit;

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template variables scoped to included view file.

$current_segment = $segment;
$current_orderby = $orderby;
$current_order = $order;
$total_customers = (int) array_sum( $segment_counts );
$risk_total = (int) ( $segment_counts['risk'] ?? 0 ) + (int) ( $segment_counts['critical'] ?? 0 );

// Active advanced filters (used to preserve them across segment switches and to show "Clear").
$wstl_active_filters = array_filter(
	array(
		's'         => $search,
		'score_min' => $score_min,
		'score_max' => $score_max,
		'rate_min'  => $rate_min,
		'status'    => $status,
	),
	static function ( $value ) {
		return '' !== $value && null !== $value;
	}
);
$wstl_has_filters = ! empty( $wstl_active_filters );
?>

<div class="wrap wstl-wrap wstl-customers-page">
	<?php
	$wstl_cust_meta = array();
	if ( $risk_total > 0 ) {
		// Link to the score band (risk + critical) so the filtered list matches this count.
		$wstl_thr          = wp_parse_args( get_option( 'trustlens_segment_thresholds', array() ), array( 'caution' => 30 ) );
		$wstl_highrisk_max = max( 0, (int) $wstl_thr['caution'] - 1 );
		$wstl_cust_meta[]  = array(
			'type'  => 'state',
			'level' => 'danger',
			/* translators: %s: number of high-risk customers */
			'value' => sprintf( __( '%s high-risk', 'trustlens' ), number_format( $risk_total ) ),
			'href'  => add_query_arg(
				array( 'page' => 'trustlens-customers', 'score_max' => $wstl_highrisk_max ),
				admin_url( 'admin.php' )
			),
		);
	}
	/* translators: %s: total customers tracked */
	$wstl_cust_meta[] = array( 'type' => 'text', 'value' => sprintf( __( '%s tracked', 'trustlens' ), number_format( $total_customers ) ) );
	wstl_render_page_header( array(
		'title'    => __( 'Customers', 'trustlens' ),
		'meta'     => $wstl_cust_meta,
		'actions'  => '<button type="button" id="wstl-export-csv" class="button">' . esc_html__( 'Export CSV', 'trustlens' ) . '</button>',
	) );
	?>
	<hr class="wp-header-end">

	<!-- Filters -->
	<div class="wstl-customers-toolbar">
		<ul class="wstl-segment-filters">
			<li>
				<a href="<?php echo esc_url( add_query_arg( array_merge( array( 'page' => 'trustlens-customers' ), $wstl_active_filters ), admin_url( 'admin.php' ) ) ); ?>" <?php echo empty( $current_segment ) ? 'class="current"' : ''; ?>>
					<?php esc_html_e( 'All', 'trustlens' ); ?>
					<span class="count"><?php echo esc_html( number_format( $total_customers ) ); ?></span>
				</a>
			</li>
			<?php
			$segments = array( 'vip', 'trusted', 'normal', 'caution', 'risk', 'critical' );
			foreach ( $segments as $seg ) :
				$count = $segment_counts[ $seg ] ?? 0;
				$is_current = $current_segment === $seg;
				?>
				<li>
					<a href="<?php echo esc_url( add_query_arg( array_merge( array( 'page' => 'trustlens-customers', 'segment' => $seg ), $wstl_active_filters ), admin_url( 'admin.php' ) ) ); ?>" class="wstl-segfilter-<?php echo esc_attr( $seg ); ?><?php echo $is_current ? ' current' : ''; ?>">
						<?php echo esc_html( wstl_get_segment_label( $seg ) ); ?>
						<span class="count"><?php echo esc_html( number_format( $count ) ); ?></span>
					</a>
				</li>
			<?php endforeach; ?>
		</ul>

		<form method="get" class="wstl-customers-filters">
			<input type="hidden" name="page" value="trustlens-customers">
			<?php if ( $current_segment ) : ?>
				<input type="hidden" name="segment" value="<?php echo esc_attr( $current_segment ); ?>">
			<?php endif; ?>
			<?php if ( 'trust_score' !== $current_orderby ) : ?>
				<input type="hidden" name="orderby" value="<?php echo esc_attr( $current_orderby ); ?>">
				<input type="hidden" name="order" value="<?php echo esc_attr( $current_order ); ?>">
			<?php endif; ?>
			<input type="search" name="s" value="<?php echo esc_attr( $search ); ?>" placeholder="<?php esc_attr_e( 'Search by email…', 'trustlens' ); ?>" class="wstl-filter-search">
			<span class="wstl-filter-field">
				<span class="wstl-filter-label"><?php esc_html_e( 'Score', 'trustlens' ); ?></span>
				<input type="number" name="score_min" value="<?php echo esc_attr( $score_min ); ?>" min="0" max="100" placeholder="<?php esc_attr_e( 'min', 'trustlens' ); ?>" class="wstl-num">
				<span class="wstl-dash">&ndash;</span>
				<input type="number" name="score_max" value="<?php echo esc_attr( $score_max ); ?>" min="0" max="100" placeholder="<?php esc_attr_e( 'max', 'trustlens' ); ?>" class="wstl-num">
			</span>
			<span class="wstl-filter-field">
				<span class="wstl-filter-label"><?php esc_html_e( 'Return rate', 'trustlens' ); ?> &ge;</span>
				<input type="number" name="rate_min" value="<?php echo esc_attr( $rate_min ); ?>" min="0" max="100" placeholder="%" class="wstl-num">
			</span>
			<select name="status" class="wstl-filter-status">
				<option value=""><?php esc_html_e( 'Any status', 'trustlens' ); ?></option>
				<option value="blocked" <?php selected( $status, 'blocked' ); ?>><?php esc_html_e( 'Blocked', 'trustlens' ); ?></option>
				<option value="allowlisted" <?php selected( $status, 'allowlisted' ); ?>><?php esc_html_e( 'Allowlisted', 'trustlens' ); ?></option>
				<option value="flagged" <?php selected( $status, 'flagged' ); ?>><?php esc_html_e( 'Flagged', 'trustlens' ); ?></option>
			</select>
			<button type="submit" class="button button-primary"><?php esc_html_e( 'Apply', 'trustlens' ); ?></button>
			<?php if ( $wstl_has_filters ) : ?>
				<a class="wstl-filter-clear" href="<?php echo esc_url( $current_segment ? add_query_arg( array( 'page' => 'trustlens-customers', 'segment' => $current_segment ), admin_url( 'admin.php' ) ) : admin_url( 'admin.php?page=trustlens-customers' ) ); ?>"><?php esc_html_e( 'Clear filters', 'trustlens' ); ?></a>
			<?php endif; ?>
		</form>
	</div>

	<?php include TRUSTLENS_PLUGIN_DIR . 'admin/views/partials/segment-legend.php'; ?>

	<!-- Bulk Actions -->
	<form id="wstl-customers-form" method="post">
		<?php wp_nonce_field( 'wstl_bulk_action', 'wstl_bulk_nonce' ); ?>

		<div class="tablenav top wstl-customers-actions">
			<div class="alignleft actions bulkactions">
				<select name="wstl_bulk_action" id="wstl-bulk-action-selector">
					<option value=""><?php esc_html_e( 'Bulk Actions', 'trustlens' ); ?></option>
					<option value="block"><?php esc_html_e( 'Block', 'trustlens' ); ?></option>
					<option value="unblock"><?php esc_html_e( 'Unblock', 'trustlens' ); ?></option>
					<option value="allowlist"><?php esc_html_e( 'Add to Allowlist', 'trustlens' ); ?></option>
					<option value="remove_allowlist"><?php esc_html_e( 'Remove from Allowlist', 'trustlens' ); ?></option>
					<option value="recalculate"><?php esc_html_e( 'Recalculate Score', 'trustlens' ); ?></option>
					<option value="delete"><?php esc_html_e( 'Delete', 'trustlens' ); ?></option>
				</select>
				<button type="button" id="wstl-bulk-apply" class="button action">
					<?php esc_html_e( 'Apply', 'trustlens' ); ?>
				</button>
				<span class="spinner wstl-spinner-inline"></span>
				<span id="wstl-bulk-result" class="wstl-bulk-result"></span>
			</div>
			<span id="wstl-bulk-count" class="wstl-bulk-count" aria-live="polite"></span>
		</div>

		<!-- Customers Table -->
		<div class="wstl-customers-table-shell">
			<div class="wstl-customers-table-wrap">
				<table class="wp-list-table widefat fixed striped wstl-customers-table">
					<thead>
						<tr>
							<td class="manage-column column-cb check-column">
								<input type="checkbox" id="wstl-select-all">
							</td>
							<th class="column-customer wstl-col-28">
								<?php esc_html_e( 'Customer', 'trustlens' ); ?>
							</th>
							<th class="column-score sortable <?php echo $current_orderby === 'trust_score' ? 'sorted' : ''; ?> <?php echo esc_attr( strtolower( $current_order ) ); ?>">
								<a href="<?php echo esc_url( add_query_arg( array( 'orderby' => 'trust_score', 'order' => $current_orderby === 'trust_score' && $current_order === 'ASC' ? 'DESC' : 'ASC' ) ) ); ?>">
									<span><?php esc_html_e( 'Score', 'trustlens' ); ?></span>
									<span class="sorting-indicators"><span class="sorting-indicator asc" aria-hidden="true"></span><span class="sorting-indicator desc" aria-hidden="true"></span></span>
								</a>
							</th>
							<th class="column-orders sortable <?php echo $current_orderby === 'total_orders' ? 'sorted' : ''; ?> <?php echo esc_attr( strtolower( $current_order ) ); ?>">
								<a href="<?php echo esc_url( add_query_arg( array( 'orderby' => 'total_orders', 'order' => $current_orderby === 'total_orders' && $current_order === 'DESC' ? 'ASC' : 'DESC' ) ) ); ?>">
									<span><?php esc_html_e( 'Orders', 'trustlens' ); ?></span>
									<span class="sorting-indicators"><span class="sorting-indicator asc" aria-hidden="true"></span><span class="sorting-indicator desc" aria-hidden="true"></span></span>
								</a>
							</th>
							<th class="column-returns"><?php esc_html_e( 'Returns', 'trustlens' ); ?></th>
							<th class="column-rate sortable <?php echo $current_orderby === 'return_rate' ? 'sorted' : ''; ?> <?php echo esc_attr( strtolower( $current_order ) ); ?>">
								<a href="<?php echo esc_url( add_query_arg( array( 'orderby' => 'return_rate', 'order' => $current_orderby === 'return_rate' && $current_order === 'DESC' ? 'ASC' : 'DESC' ) ) ); ?>">
									<span><?php esc_html_e( 'Rate', 'trustlens' ); ?></span>
									<span class="sorting-indicators"><span class="sorting-indicator asc" aria-hidden="true"></span><span class="sorting-indicator desc" aria-hidden="true"></span></span>
								</a>
							</th>
							<th class="column-value sortable <?php echo $current_orderby === 'total_refund_value' ? 'sorted' : ''; ?> <?php echo esc_attr( strtolower( $current_order ) ); ?>">
								<a href="<?php echo esc_url( add_query_arg( array( 'orderby' => 'total_refund_value', 'order' => $current_orderby === 'total_refund_value' && $current_order === 'DESC' ? 'ASC' : 'DESC' ) ) ); ?>">
									<span><?php esc_html_e( 'Refunded', 'trustlens' ); ?></span>
									<span class="sorting-indicators"><span class="sorting-indicator asc" aria-hidden="true"></span><span class="sorting-indicator desc" aria-hidden="true"></span></span>
								</a>
							</th>
							<th class="column-actions"><?php esc_html_e( 'Actions', 'trustlens' ); ?></th>
						</tr>
					</thead>
					<tbody>
						<?php if ( empty( $customers ) ) : ?>
							<tr>
								<td colspan="8">
									<div class="wstl-empty"><?php esc_html_e( 'No customers match these filters.', 'trustlens' ); ?></div>
								</td>
							</tr>
						<?php else : ?>
							<?php foreach ( $customers as $customer ) : ?>
								<tr data-hash="<?php echo esc_attr( $customer->email_hash ); ?>">
									<th scope="row" class="check-column">
										<input type="checkbox" name="customers[]" value="<?php echo esc_attr( $customer->email_hash ); ?>" class="wstl-customer-checkbox">
									</th>
									<td class="column-customer">
										<span class="wstl-segment-badge wstl-segment-<?php echo esc_attr( $customer->segment ); ?>">
											<?php echo esc_html( wstl_get_segment_label( $customer->segment ) ); ?>
										</span>
										<strong>
											<a href="<?php echo esc_url( admin_url( 'admin.php?page=trustlens-customers&customer=' . $customer->email_hash ) ); ?>">
												<?php echo esc_html( $customer->customer_email ?: __( 'Guest', 'trustlens' ) ); ?>
											</a>
										</strong>
										<?php if ( $customer->is_blocked ) : ?>
											<span class="wstl-badge wstl-badge-blocked"><?php esc_html_e( 'Blocked', 'trustlens' ); ?></span>
										<?php endif; ?>
										<?php if ( $customer->is_allowlisted ) : ?>
											<span class="wstl-badge wstl-badge-allowlist"><?php esc_html_e( 'Allowlist', 'trustlens' ); ?></span>
										<?php endif; ?>
										<?php if ( ! empty( $customer->is_flagged ) ) : ?>
											<span class="wstl-badge wstl-badge-flagged"><?php esc_html_e( 'Flagged', 'trustlens' ); ?></span>
										<?php endif; ?>
										<br>
										<span class="wstl-customer-type">
											<?php echo $customer->customer_type === 'user' ? esc_html__( 'Registered', 'trustlens' ) : esc_html__( 'Guest', 'trustlens' ); ?>
										</span>
									</td>
									<td class="column-score">
										<span class="wstl-score wstl-score-<?php echo esc_attr( $customer->segment ); ?>">
											<?php echo esc_html( $customer->trust_score ); ?>
										</span>
									</td>
									<td class="column-orders"><?php echo esc_html( number_format( $customer->total_orders ) ); ?></td>
									<td class="column-returns"><?php echo esc_html( number_format( $customer->total_refunds ) ); ?></td>
									<td class="column-rate"><?php echo esc_html( number_format( $customer->return_rate, 0 ) ); ?>%</td>
									<td class="column-value"><?php echo wp_kses_post( wc_price( $customer->total_refund_value ) ); ?></td>
									<td class="column-actions">
										<a href="<?php echo esc_url( admin_url( 'admin.php?page=trustlens-customers&customer=' . $customer->email_hash ) ); ?>" class="button button-small">
											<?php esc_html_e( 'View', 'trustlens' ); ?>
										</a>
									</td>
								</tr>
							<?php endforeach; ?>
						<?php endif; ?>
					</tbody>
					<tfoot>
						<tr>
							<td class="manage-column column-cb check-column">
								<input type="checkbox" id="wstl-select-all-bottom">
							</td>
							<th class="column-customer"><?php esc_html_e( 'Customer', 'trustlens' ); ?></th>
							<th class="column-score"><?php esc_html_e( 'Score', 'trustlens' ); ?></th>
							<th class="column-orders"><?php esc_html_e( 'Orders', 'trustlens' ); ?></th>
							<th class="column-returns"><?php esc_html_e( 'Returns', 'trustlens' ); ?></th>
							<th class="column-rate"><?php esc_html_e( 'Rate', 'trustlens' ); ?></th>
							<th class="column-value"><?php esc_html_e( 'Refunded', 'trustlens' ); ?></th>
							<th class="column-actions"><?php esc_html_e( 'Actions', 'trustlens' ); ?></th>
						</tr>
					</tfoot>
				</table>
			</div>
		</div>

		<!-- Pagination -->
		<?php if ( $total_pages > 1 ) : ?>
			<div class="tablenav bottom wstl-customers-pagination">
				<div class="alignleft actions bulkactions">
					<select name="wstl_bulk_action_bottom" id="wstl-bulk-action-selector-bottom">
						<option value=""><?php esc_html_e( 'Bulk Actions', 'trustlens' ); ?></option>
						<option value="block"><?php esc_html_e( 'Block', 'trustlens' ); ?></option>
						<option value="unblock"><?php esc_html_e( 'Unblock', 'trustlens' ); ?></option>
						<option value="allowlist"><?php esc_html_e( 'Add to Allowlist', 'trustlens' ); ?></option>
						<option value="remove_allowlist"><?php esc_html_e( 'Remove from Allowlist', 'trustlens' ); ?></option>
						<option value="recalculate"><?php esc_html_e( 'Recalculate Score', 'trustlens' ); ?></option>
						<option value="delete"><?php esc_html_e( 'Delete', 'trustlens' ); ?></option>
					</select>
					<button type="button" id="wstl-bulk-apply-bottom" class="button action">
						<?php esc_html_e( 'Apply', 'trustlens' ); ?>
					</button>
				</div>

				<div class="tablenav-pages">
					<span class="displaying-num">
						<?php
						echo esc_html(
							sprintf(
								/* translators: %s: number of items */
								_n( '%s item', '%s items', $total, 'trustlens' ),
								number_format( $total )
							)
						);
						?>
					</span>
					<span class="pagination-links">
						<?php
						$pagination_args = array(
							'base'      => add_query_arg( 'paged', '%#%' ),
							'format'    => '',
							'prev_text' => '&laquo;',
							'next_text' => '&raquo;',
							'total'     => $total_pages,
							'current'   => $page,
						);
						// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- paginate_links() returns safe HTML.
						echo paginate_links( $pagination_args );
						?>
					</span>
				</div>
			</div>
		<?php endif; ?>
	</form>
</div>

<?php // phpcs:enable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound ?>
