<?php
/**
 * Chargeback Monitor page (Pro).
 *
 * Executive-split layout (Stripe-like variant C):
 *   Left  — threshold focus: hero ratio, network-program progress bars,
 *           12-month trend chart, all-time outcomes.
 *   Right — activity feed: recent dispute events grouped by day,
 *           top-disputed customers, inline alert-threshold setting.
 *   Footer — historical card-brand backfill control.
 *
 * @package TrustLens
 * @since   1.2.1
 */

defined( 'ABSPATH' ) || exit;

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- View template; variables are scoped to the including method, not the global namespace.

if ( ! current_user_can( 'manage_woocommerce' ) ) {
	return;
}
if ( ! class_exists( 'TrustLens_Chargeback_Monitor' ) || ! wstl_can_use_pro() ) {
	?>
	<div class="wrap wstl-wrap">
		<h1 class="screen-reader-text"><?php esc_html_e( 'Chargeback Monitor', 'trustlens' ); ?></h1>
		<hr class="wp-header-end">

		<?php
		wstl_render_pro_upsell(
			__( 'Advanced Chargeback Monitor', 'trustlens' ),
			__( 'Your free dashboard already shows the blended chargeback-ratio speedometer. Pro adds a dedicated monitor that breaks the ratio down by card network and warns you before you cross a threshold.', 'trustlens' ),
			array(
				__( 'Per-brand ratios for Visa (VDMP/VFMP), Mastercard (ECP), Amex, and Discover', 'trustlens' ),
				__( '12-month trend chart plus a trailing-30-day window alongside the calendar month', 'trustlens' ),
				__( 'Daily email alerts before any brand crosses its network threshold', 'trustlens' ),
				__( 'Representment-ready Dispute Evidence Reports for your most-disputed customers', 'trustlens' ),
			),
			array(
				array( __( 'Chargeback ratio', 'trustlens' ), __( 'Blended only', 'trustlens' ), __( 'Per-brand breakdown', 'trustlens' ) ),
				array( __( 'History', 'trustlens' ), __( 'Current month', 'trustlens' ), __( '12-month trend + 30-day window', 'trustlens' ) ),
				array( __( 'Alerts', 'trustlens' ), __( 'On-screen only', 'trustlens' ), __( 'Daily email before threshold', 'trustlens' ) ),
			),
			__( 'Stay off the radar', 'trustlens' ),
			__( 'Built for stores that depend on staying under Visa and Mastercard monitoring thresholds.', 'trustlens' )
		);
		?>
	</div>
	<?php
	return;
}

global $wpdb;

$monitor  = new TrustLens_Chargeback_Monitor();
$ratios   = $monitor->get_ratios();
$trend    = $monitor->get_trend( 12 );
$warn_pct = (int) get_option( 'trustlens_chargeback_alert_threshold_pct', 70 );
$status   = TrustLens_Chargeback_Monitor::get_threshold_status( $ratios['calendar_month'], $warn_pct );
$nearest  = TrustLens_Chargeback_Monitor::get_nearest_threshold( $ratios['calendar_month'] );

$month_blended    = $ratios['calendar_month']['blended'];
$trailing_blended = $ratios['trailing_30']['blended'];

// Store-wide dispute outcomes (all time).
$customers_table = $wpdb->prefix . 'trustlens_customers';
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Table name from $wpdb->prefix, safe.
$outcomes = $wpdb->get_row(
	"SELECT
		COALESCE(SUM(total_disputes), 0)  AS total_disputes,
		COALESCE(SUM(disputes_won), 0)    AS disputes_won,
		COALESCE(SUM(disputes_lost), 0)   AS disputes_lost,
		COALESCE(SUM(CASE WHEN total_disputes > 0 THEN 1 ELSE 0 END), 0) AS customers_affected
	 FROM {$customers_table}"
);
// phpcs:enable

$total_disputes     = (int) ( $outcomes->total_disputes ?? 0 );
$disputes_won       = (int) ( $outcomes->disputes_won ?? 0 );
$disputes_lost      = (int) ( $outcomes->disputes_lost ?? 0 );
$disputes_pending   = max( 0, $total_disputes - $disputes_won - $disputes_lost );
$customers_affected = (int) ( $outcomes->customers_affected ?? 0 );
$settled            = $disputes_won + $disputes_lost;
$win_rate           = $settled > 0 ? (int) round( 100 * $disputes_won / $settled ) : 0;

// Top 5 disputed customers.
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Table name from $wpdb->prefix, safe.
$top_disputed = $wpdb->get_results(
	"SELECT email_hash, customer_email, trust_score, segment, total_disputes, disputes_won, disputes_lost, is_blocked
	 FROM {$customers_table}
	 WHERE total_disputes > 0
	 ORDER BY total_disputes DESC, disputes_lost DESC
	 LIMIT 5"
);
// phpcs:enable

// Recent 10 dispute events joined to customer row for email + profile context.
$events_table = $wpdb->prefix . 'trustlens_events';
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Table names from $wpdb->prefix, safe.
$recent_disputes = $wpdb->get_results( $wpdb->prepare(
	"SELECT e.id, e.email_hash, e.event_type, e.event_data, e.order_id, e.created_at,
	        c.customer_email, c.total_disputes
	 FROM {$events_table} e
	 LEFT JOIN {$customers_table} c ON c.email_hash = e.email_hash
	 WHERE e.event_type IN (%s, %s)
	 ORDER BY e.created_at DESC
	 LIMIT 10",
	'dispute_created',
	'dispute_closed'
) );
// phpcs:enable

// Group events by local-date day for the activity timeline.
$tz            = wp_timezone();
$today_key     = ( new DateTimeImmutable( 'now', $tz ) )->format( 'Y-m-d' );
$yesterday_key = ( new DateTimeImmutable( 'yesterday', $tz ) )->format( 'Y-m-d' );
$events_by_day = array();
foreach ( $recent_disputes as $event ) {
	$local_day                         = wp_date( 'Y-m-d', strtotime( (string) $event->created_at ) );
	$events_by_day[ $local_day ][]     = $event;
}

// Headline status label derived from get_nearest_threshold().
$headline_label = __( 'Healthy', 'trustlens' );
$headline_class = 'good';
$headline_sub   = __( 'No card orders yet.', 'trustlens' );
if ( null !== $nearest ) {
	$thr_pct   = number_format( 100 * (float) $nearest['threshold'], 2 );
	$to_hit    = (int) $nearest['disputes_to_hit'];
	$nearest_l = $nearest['label'];
	if ( 'danger' === $nearest['status'] ) {
		$headline_label = __( 'Action needed', 'trustlens' );
		$headline_class = 'danger';
		$headline_sub   = sprintf(
			/* translators: 1: program label, 2: threshold percent */
			__( 'Over the %1$s line (%2$s%%). Review and respond to open disputes now.', 'trustlens' ),
			$nearest_l,
			$thr_pct
		);
	} elseif ( $to_hit > 0 && $to_hit <= 3 ) {
		$headline_label = __( 'Approaching threshold', 'trustlens' );
		$headline_class = 'warn';
		$headline_sub   = sprintf(
			/* translators: 1: disputes-to-hit, 2: program label, 3: threshold percent */
			_n( '%1$d dispute from %2$s (%3$s%%).', '%1$d disputes from %2$s (%3$s%%).', $to_hit, 'trustlens' ),
			$to_hit,
			$nearest_l,
			$thr_pct
		);
	} else {
		$headline_sub = sprintf(
			/* translators: 1: disputes-to-hit, 2: program label */
			__( '%1$d disputes of room to the nearest line (%2$s).', 'trustlens' ),
			$to_hit,
			$nearest_l
		);
	}
}

$brand_detector           = new TrustLens_Card_Brand_Detector();
$dispute_report_available = class_exists( 'TrustLens_Dispute_Report' );
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only display-side check for the standard settings-updated flag WP adds to the redirect URL.
$just_saved = isset( $_GET['settings-updated'] ) && 'true' === $_GET['settings-updated'];
?>
<div class="wrap wstl-cb-monitor">
	<?php
	wstl_render_page_header( array(
		'title'    => __( 'Chargeback Monitor', 'trustlens' ),
		'meta'     => array(
			array( 'type' => 'date',  'value' => wp_date( 'F Y', time() ) ),
			array( 'type' => 'state', 'value' => $headline_label, 'level' => $headline_class, 'href' => '#wstl-cb-threshold' ),
			array( 'type' => 'text',  'value' => $headline_sub ),
		),
		'actions' => '<a href="#wstl-cb-threshold" class="button">' . esc_html__( 'Settings', 'trustlens' ) . '</a>',
	) );
	?>
	<hr class="wp-header-end">
	<?php if ( $just_saved ) : ?>
		<div class="notice notice-success is-dismissible" style="margin-left:0;margin-right:0;">
			<p><?php esc_html_e( 'Settings saved.', 'trustlens' ); ?></p>
		</div>
	<?php endif; ?>

	<div class="wstl-cb-split">

		<div class="wstl-cb-left">

			<!-- Hero: blended ratio + trailing 30 + win rate -->
			<div class="wstl-cb-card wstl-cb-hero">
				<div class="wstl-cb-hero-left">
					<div class="wstl-cb-hero-val"><?php echo esc_html( number_format( 100 * (float) $month_blended['ratio'], 2 ) ); ?>%</div>
					<div class="wstl-cb-hero-sub">
						<?php
						printf(
							/* translators: 1: disputes, 2: orders */
							esc_html__( 'Calendar month · %1$d disputes / %2$d card orders', 'trustlens' ),
							(int) $month_blended['disputes'],
							(int) $month_blended['orders']
						);
						?>
					</div>
				</div>
				<div class="wstl-cb-hero-right">
					<div class="wstl-cb-hero-stat">
						<div class="v"><?php echo esc_html( number_format( 100 * (float) $trailing_blended['ratio'], 2 ) ); ?>%</div>
						<div class="l"><?php esc_html_e( 'Trailing 30 days', 'trustlens' ); ?></div>
					</div>
					<div class="wstl-cb-hero-stat">
						<div class="v"><?php echo esc_html( $settled > 0 ? $win_rate . '%' : '—' ); ?></div>
						<div class="l"><?php esc_html_e( 'Win rate (all time)', 'trustlens' ); ?></div>
					</div>
				</div>
			</div>

			<!-- Open disputes worklist -->
			<?php
			$wstl_open_disputes = wstl_get_open_disputes( 100 );
			$wstl_now           = time();
			?>
			<div class="wstl-cb-card wstl-cb-worklist">
				<h3><?php esc_html_e( 'Open disputes', 'trustlens' ); ?></h3>

				<?php if ( empty( $wstl_open_disputes ) ) : ?>
					<p class="wstl-cb-worklist-empty"><?php esc_html_e( 'No open disputes — you\'re all clear.', 'trustlens' ); ?></p>
				<?php else : ?>
					<table class="wstl-cb-worklist-table widefat striped">
						<thead>
							<tr>
								<th><?php esc_html_e( 'Deadline', 'trustlens' ); ?></th>
								<th><?php esc_html_e( 'Customer', 'trustlens' ); ?></th>
								<th><?php esc_html_e( 'Order', 'trustlens' ); ?></th>
								<th><?php esc_html_e( 'Amount', 'trustlens' ); ?></th>
								<th><?php esc_html_e( 'Reason', 'trustlens' ); ?></th>
								<th><?php esc_html_e( 'Source', 'trustlens' ); ?></th>
								<th><?php esc_html_e( 'Actions', 'trustlens' ); ?></th>
							</tr>
						</thead>
						<tbody>
							<?php foreach ( $wstl_open_disputes as $wstl_d ) : ?>
								<?php
								$wstl_cd      = wstl_format_due_countdown( $wstl_d->due_by, $wstl_now );
								$wstl_email   = $wstl_d->customer_email ? $wstl_d->customer_email : __( 'Unknown customer', 'trustlens' );
								$wstl_report  = ( '' !== (string) $wstl_d->email_hash && class_exists( 'TrustLens_Dispute_Report' ) )
									? TrustLens_Dispute_Report::get_report_url( (string) $wstl_d->email_hash, (int) $wstl_d->order_id )
									: '';
								$wstl_order_l = $wstl_d->order_id ? get_edit_post_link( (int) $wstl_d->order_id ) : '';
								?>
								<tr>
									<td><span class="wstl-cb-due wstl-cb-due--<?php echo esc_attr( $wstl_cd['severity'] ); ?>"><?php echo esc_html( $wstl_cd['label'] ); ?></span></td>
									<td><?php echo esc_html( $wstl_email ); ?></td>
									<td>
										<?php if ( $wstl_order_l ) : ?>
											<a href="<?php echo esc_url( $wstl_order_l ); ?>">#<?php echo esc_html( (string) $wstl_d->order_id ); ?></a>
										<?php else : ?>
											<?php echo $wstl_d->order_id ? esc_html( '#' . $wstl_d->order_id ) : '—'; ?>
										<?php endif; ?>
									</td>
									<td><?php echo wp_kses_post( wc_price( (float) $wstl_d->amount, array( 'currency' => (string) $wstl_d->currency ) ) ); ?></td>
									<td><?php echo esc_html( ucwords( str_replace( '_', ' ', (string) $wstl_d->reason ) ) ); ?></td>
									<td><?php echo esc_html( ucfirst( (string) $wstl_d->gateway ) ); ?></td>
									<td>
										<?php if ( $wstl_report ) : ?>
											<a class="button button-small" href="<?php echo esc_url( $wstl_report ); ?>" target="_blank" rel="noopener"><?php esc_html_e( 'Evidence', 'trustlens' ); ?></a>
										<?php endif; ?>
										<?php
										$wstl_att = ( $wstl_d->order_id && class_exists( 'TrustLens_Dispute_Attestation' ) )
											? TrustLens_Dispute_Attestation::registration_status( (int) $wstl_d->order_id )
											: 'none';
										if ( 'registered' === $wstl_att ) :
											?>
											<span class="wstl-att wstl-att--ok" title="<?php esc_attr_e( 'Evidence report registered with the verification service.', 'trustlens' ); ?>">&#10003; <?php esc_html_e( 'Registered', 'trustlens' ); ?></span>
										<?php elseif ( 'pending' === $wstl_att ) : ?>
											<span class="wstl-att wstl-att--pending" title="<?php esc_attr_e( 'Registration did not reach the verification service yet; TrustLens retries automatically.', 'trustlens' ); ?>"><?php esc_html_e( 'Verify pending', 'trustlens' ); ?></span>
										<?php endif; ?>
									</td>
								</tr>
							<?php endforeach; ?>
						</tbody>
					</table>
					<p class="wstl-cb-worklist-note"><?php esc_html_e( 'Respond to each dispute in your payment provider before its deadline. "No deadline" means the provider did not supply one (or it was added manually).', 'trustlens' ); ?></p>
				<?php endif; ?>
			</div>

			<!-- Network program progress -->
			<div class="wstl-cb-card">
				<h3><?php esc_html_e( 'Network program progress', 'trustlens' ); ?></h3>
				<?php foreach ( $status as $key => $row ) :
					$ratio_pct     = number_format( 100 * (float) $row['ratio'], 3 );
					$threshold_pct = number_format( 100 * (float) $row['threshold'], 2 );
					$progress      = 0.0;
					if ( (float) $row['threshold'] > 0 ) {
						$progress = min( 100, max( 0, 100 * (float) $row['ratio'] / (float) $row['threshold'] ) );
					}
					$bar_class = 'good';
					$tag_class = 'good';
					$tag_text  = __( 'OK', 'trustlens' );
					if ( 'no_data' === $row['status'] ) {
						$bar_class = 'muted';
						$tag_class = 'muted';
						$tag_text  = __( 'No data', 'trustlens' );
					} elseif ( 'danger' === $row['status'] ) {
						$bar_class = 'danger';
						$tag_class = 'danger';
						$tag_text  = __( 'Over', 'trustlens' );
					} elseif ( 'warning' === $row['status'] ) {
						$bar_class = 'warn';
						$tag_class = 'warn';
						$tag_text  = round( $progress ) . '%';
					}
				?>
					<div class="wstl-cb-prog-row">
						<div class="wstl-cb-prog-label">
							<?php echo esc_html( $row['label'] ); ?>
							<small><?php echo esc_html( $threshold_pct ); ?>% <?php esc_html_e( 'threshold', 'trustlens' ); ?></small>
						</div>
						<div class="wstl-cb-bar wstl-cb-bar-<?php echo esc_attr( $bar_class ); ?>">
							<span style="width: <?php echo esc_attr( (string) $progress ); ?>%;"></span>
						</div>
						<div class="wstl-cb-prog-pct<?php echo 'danger' === $row['status'] ? ' is-danger' : ( 'warning' === $row['status'] ? ' is-warn' : '' ); ?>">
							<?php echo 'no_data' === $row['status'] ? '—' : esc_html( $ratio_pct . '%' ); ?>
						</div>
						<div class="wstl-cb-prog-tag">
							<span class="wstl-cb-pill wstl-cb-pill-<?php echo esc_attr( $tag_class ); ?>"><?php echo esc_html( $tag_text ); ?></span>
						</div>
					</div>
				<?php endforeach; ?>
			</div>

			<!-- 12-month trend chart -->
			<div class="wstl-cb-card">
				<h3><?php esc_html_e( '12-month trend · blended', 'trustlens' ); ?></h3>
				<div class="wstl-cb-chart-wrap">
					<canvas id="wstl-chargeback-trend"></canvas>
				</div>
			</div>

			<!-- Outcomes -->
			<div class="wstl-cb-card">
				<h3><?php esc_html_e( 'Outcomes · all time', 'trustlens' ); ?></h3>
				<div class="wstl-cb-outcomes">
					<div class="wstl-cb-outcome">
						<div class="v"><?php echo esc_html( number_format( $total_disputes ) ); ?></div>
						<div class="l"><?php esc_html_e( 'Total', 'trustlens' ); ?></div>
					</div>
					<div class="wstl-cb-outcome is-won">
						<div class="v"><?php echo esc_html( number_format( $disputes_won ) ); ?></div>
						<div class="l"><?php esc_html_e( 'Won', 'trustlens' ); ?></div>
					</div>
					<div class="wstl-cb-outcome is-lost">
						<div class="v"><?php echo esc_html( number_format( $disputes_lost ) ); ?></div>
						<div class="l"><?php esc_html_e( 'Lost', 'trustlens' ); ?></div>
					</div>
					<div class="wstl-cb-outcome is-pending">
						<div class="v"><?php echo esc_html( number_format( $disputes_pending ) ); ?></div>
						<div class="l"><?php esc_html_e( 'Pending', 'trustlens' ); ?></div>
					</div>
					<div class="wstl-cb-outcome">
						<div class="v"><?php echo esc_html( number_format( $customers_affected ) ); ?></div>
						<div class="l"><?php esc_html_e( 'Customers', 'trustlens' ); ?></div>
					</div>
					<div class="wstl-cb-outcome">
						<div class="v"><?php echo esc_html( $settled > 0 ? $win_rate . '%' : '—' ); ?></div>
						<div class="l"><?php esc_html_e( 'Win rate', 'trustlens' ); ?></div>
					</div>
				</div>
			</div>
		</div>

		<div class="wstl-cb-right">

			<!-- Activity feed -->
			<div class="wstl-cb-card">
				<h3><?php esc_html_e( 'Recent activity', 'trustlens' ); ?></h3>
				<?php if ( empty( $events_by_day ) ) : ?>
					<p class="wstl-empty"><?php esc_html_e( 'No dispute events recorded yet.', 'trustlens' ); ?></p>
				<?php else : ?>
					<?php foreach ( $events_by_day as $day => $events ) :
						if ( $day === $today_key ) {
							$day_label = __( 'Today', 'trustlens' ) . ' · ' . wp_date( 'M j', strtotime( $day ) );
						} elseif ( $day === $yesterday_key ) {
							$day_label = __( 'Yesterday', 'trustlens' ) . ' · ' . wp_date( 'M j', strtotime( $day ) );
						} else {
							$day_label = wp_date( 'M j · D', strtotime( $day ) );
						}
					?>
						<div class="wstl-cb-dayhead"><?php echo esc_html( $day_label ); ?></div>
						<?php foreach ( $events as $event ) :
							$data         = is_string( $event->event_data ) ? json_decode( $event->event_data, true ) : array();
							if ( ! is_array( $data ) ) {
								$data = array();
							}
							$order_id     = (int) $event->order_id;
							$order_link   = $order_id > 0 ? admin_url( 'post.php?post=' . $order_id . '&action=edit' ) : '';
							$brand        = $order_id > 0 ? $brand_detector->get_brand( $order_id ) : 'unknown';
							$reason       = isset( $data['reason'] ) ? str_replace( '_', ' ', (string) $data['reason'] ) : '';
							$status_str   = (string) ( $data['status'] ?? 'pending' );
							$source       = (string) ( $data['source'] ?? 'unknown' );
							$amount       = isset( $data['amount'] ) && is_numeric( $data['amount'] ) ? (float) $data['amount'] : null;
							$email        = (string) ( $event->customer_email ?? '' );
							if ( '' === $email ) {
								$email = substr( (string) $event->email_hash, 0, 10 ) . '…';
							}

							$event_class = '';
							if ( 'dispute_created' === $event->event_type ) {
								$event_class = 'is-warn';
								$title       = __( 'Dispute opened', 'trustlens' );
							} elseif ( 'dispute_closed' === $event->event_type ) {
								$won         = ! empty( $data['won'] );
								$event_class = $won ? 'is-good' : 'is-danger';
								$title       = $won
									? __( 'Dispute closed · Won', 'trustlens' )
									: __( 'Dispute closed · Lost', 'trustlens' );
							} else {
								$title = (string) $event->event_type;
							}

							$time_str = wp_date( 'H:i', strtotime( (string) $event->created_at ) );
						?>
							<div class="wstl-cb-event <?php echo esc_attr( $event_class ); ?>">
								<div class="wstl-cb-event-head">
									<div class="wstl-cb-event-title"><?php echo esc_html( $title ); ?></div>
									<div class="wstl-cb-event-time"><?php echo esc_html( $time_str ); ?></div>
								</div>
								<div class="wstl-cb-event-body">
									<?php if ( $order_link ) : ?>
										<a href="<?php echo esc_url( $order_link ); ?>"><strong>#<?php echo esc_html( (string) $order_id ); ?></strong></a>
									<?php else : ?>
										<strong>—</strong>
									<?php endif; ?>
									<?php if ( null !== $amount && function_exists( 'wc_price' ) ) : ?>
										· <?php echo wp_kses_post( wc_price( $amount ) ); ?>
									<?php endif; ?>
									· <em><?php echo esc_html( $email ); ?></em>
								</div>
								<div class="wstl-cb-event-tags">
									<span class="wstl-cb-tag"><?php echo esc_html( strtoupper( $brand ) ); ?></span>
									<?php if ( '' !== $reason ) : ?>
										<span class="wstl-cb-tag"><?php echo esc_html( $reason ); ?></span>
									<?php endif; ?>
									<?php if ( '' !== $source && 'unknown' !== $source ) : ?>
										<span class="wstl-cb-tag wstl-cb-tag-muted"><?php echo esc_html( $source ); ?></span>
									<?php endif; ?>
								</div>
							</div>
						<?php endforeach; ?>
					<?php endforeach; ?>
				<?php endif; ?>
			</div>

			<!-- Top disputed customers -->
			<div class="wstl-cb-card">
				<h3><?php esc_html_e( 'Top disputed customers', 'trustlens' ); ?></h3>
				<?php if ( empty( $top_disputed ) ) : ?>
					<p class="wstl-empty"><?php esc_html_e( 'No customers with recorded disputes yet.', 'trustlens' ); ?></p>
				<?php else : ?>
					<table class="wstl-cb-table">
						<tbody>
						<?php foreach ( $top_disputed as $c ) :
							$profile_url = admin_url( 'admin.php?page=trustlens-customers&customer=' . rawurlencode( (string) $c->email_hash ) );
							$email_display = (string) ( $c->customer_email ?? '' );
							if ( '' === $email_display ) {
								$email_display = substr( (string) $c->email_hash, 0, 10 ) . '…';
							}
						?>
							<tr>
								<td>
									<a href="<?php echo esc_url( $profile_url ); ?>"><?php echo esc_html( $email_display ); ?></a>
									<?php if ( (int) $c->is_blocked ) : ?>
										<span class="wstl-cb-pill wstl-cb-pill-danger"><?php esc_html_e( 'Blocked', 'trustlens' ); ?></span>
									<?php endif; ?>
								</td>
								<td class="wstl-cb-table-num"><strong><?php echo esc_html( (string) $c->total_disputes ); ?></strong></td>
								<td class="wstl-cb-table-action">
									<?php if ( $dispute_report_available ) :
										$report_url = TrustLens_Dispute_Report::get_report_url( (string) $c->email_hash );
									?>
										<a class="wstl-cb-link" href="<?php echo esc_url( $report_url ); ?>" target="_blank">
											<?php esc_html_e( 'Evidence →', 'trustlens' ); ?>
										</a>
									<?php else : ?>
										<a class="wstl-cb-link" href="<?php echo esc_url( $profile_url ); ?>">
											<?php esc_html_e( 'Profile →', 'trustlens' ); ?>
										</a>
									<?php endif; ?>
								</td>
							</tr>
						<?php endforeach; ?>
						</tbody>
					</table>
				<?php endif; ?>
			</div>

			<!-- Chargeback settings (Pro): auto-block, ratio alert %, report verification -->
			<?php
			// File is @fs_premium_only; present + reached only in the Pro build,
			// inside this page's wstl_can_use_pro() guard.
			$wstl_cb_settings_partial = TRUSTLENS_PLUGIN_DIR . 'admin/views/chargeback-monitor-settings-pro.php';
			if ( file_exists( $wstl_cb_settings_partial ) ) {
				include $wstl_cb_settings_partial;
			}
			?>

		</div>

	</div>

	<!-- Backfill footer -->
	<div class="wstl-cb-card wstl-cb-footer">
		<h3><?php esc_html_e( 'Card brand backfill', 'trustlens' ); ?></h3>
		<p class="description">
			<?php
			printf(
				/* translators: %s: link to Historical Sync */
				esc_html__( 'Only needed if you ran %s before 15 April 2026. Going forward, Historical Sync captures card brand automatically.', 'trustlens' ),
				'<a href="' . esc_url( admin_url( 'admin.php?page=trustlens-settings&tab=data' ) ) . '">' . esc_html__( 'Historical Sync', 'trustlens' ) . '</a>'
			);
			?>
		</p>
		<p>
			<button type="button" id="wstl-chargeback-backfill-start" class="button button-secondary">
				<?php esc_html_e( 'Start backfill', 'trustlens' ); ?>
			</button>
			<span id="wstl-chargeback-backfill-progress" class="wstl-cb-backfill-progress"></span>
		</p>
	</div>
</div>

<script>
window.TrustLensChargeback = <?php echo wp_json_encode( array(
	'trend' => $trend,
	'nonce' => wp_create_nonce( 'trustlens_admin' ),
	'i18n'  => array(
		'error'    => __( 'Error. Check debug log.', 'trustlens' ),
		'failed'   => __( 'Request failed.', 'trustlens' ),
		'complete' => __( 'Backfill complete.', 'trustlens' ),
		'status'   => /* translators: %processed, %updated, %remaining are replaced with counts in JS. */ __( 'Processed: %processed · Updated: %updated · Remaining: %remaining', 'trustlens' ),
	),
) ); ?>;
// Sync the range slider and number input for the alert-threshold control.
(function(){
	var r = document.getElementById('wstl-cb-alert-range');
	var n = document.getElementById('wstl-cb-alert-pct');
	if (!r || !n) return;
	r.addEventListener('input', function(){ n.value = r.value; });
	n.addEventListener('input', function(){ r.value = n.value; });
})();
</script>
