<?php
/**
 * Card-Testing Defense — consolidated admin page.
 *
 * Replaces the prior Status/Settings/Allowlists/History tab layout with a
 * single vertical-stack page, mirroring the Stripe-style visual system used
 * by the Chargeback Monitor page. Pro-only sections (allowlists, 24h
 * intelligence) are inlined and gated by wstl_can_use_pro().
 *
 * Expects in scope:
 *   - $state (TrustLens_Lockdown_State)
 *
 * @package TrustLens
 * @since   1.2.2
 */

defined( 'ABSPATH' ) || exit;

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

global $wpdb;

$is_pro        = function_exists( 'wstl_can_use_pro' ) && wstl_can_use_pro();
$current_state = $state->current_state();
$targeted      = $state->currently_targeted();
$panic_expires = $state->panic_expires_at();
$panic_nonce   = wp_create_nonce( TrustLens_Panic_Button_AJAX::NONCE_NAME );

$thresholds = wp_parse_args(
	get_option( 'trustlens_card_testing_thresholds', array() ),
	TrustLens_Velocity_Detector::DEFAULT_THRESHOLDS
);

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Real-time hero metrics from a custom table; table name from $wpdb->prefix.
// 24-hour volumetrics (available to all tiers; used for hero metrics).
$declines_24h = (int) $wpdb->get_var(
	"SELECT COUNT(*) FROM {$wpdb->prefix}trustlens_velocity_events
	 WHERE event_type = 'decline' AND created_at > DATE_SUB(UTC_TIMESTAMP(), INTERVAL 24 HOUR)"
);
$subs_24h = (int) $wpdb->get_var(
	"SELECT COUNT(*) FROM {$wpdb->prefix}trustlens_velocity_events
	 WHERE event_type = 'submission' AND created_at > DATE_SUB(UTC_TIMESTAMP(), INTERVAL 24 HOUR)"
);
// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$rate_24h = $subs_24h > 0 ? ( 100 * $declines_24h / $subs_24h ) : 0.0;

// Headline pill + description derived from lockdown state.
$state_meta = array(
	'IDLE'     => array(
		'label'  => __( 'Idle', 'trustlens' ),
		'pill'   => 'good',
		'desc'   => __( 'No active attack. Checkout is flowing normally.', 'trustlens' ),
		'action' => __( 'Nothing to do — protection is on. Adjust the thresholds below only if you get false alarms.', 'trustlens' ),
	),
	'TARGETED' => array(
		'label'  => __( 'Targeted', 'trustlens' ),
		'pill'   => 'warn',
		'desc'   => sprintf(
			/* translators: %d: number of fingerprints currently blocked. */
			_n(
				'%d fingerprint held at the gate. Clean customer checkouts are unaffected.',
				'%d fingerprints held at the gate. Clean customer checkouts are unaffected.',
				count( $targeted ),
				'trustlens'
			),
			count( $targeted )
		),
		'action' => __( 'No action needed — held fingerprints auto-release when the attack stops. If the decline rate keeps climbing, engage Panic Freeze.', 'trustlens' ),
	),
	'PANIC'    => array(
		'label'  => __( 'Panic Freeze', 'trustlens' ),
		'pill'   => 'danger',
		'desc'   => __( 'All new card attempts are being denied. Existing sessions complete normally.', 'trustlens' ),
		'action' => __( 'All checkouts are frozen. Deactivate once the attack subsides, or let the timer auto-expire.', 'trustlens' ),
	),
);
$meta = $state_meta[ $current_state ] ?? $state_meta['IDLE'];

// Pro intelligence data.
$by_code  = array();
$top_fps  = array();
$timeline = array();
$csv_url  = '';
if ( $is_pro && class_exists( 'TrustLens_Card_Testing_History_Query' ) ) {
	$history  = new TrustLens_Card_Testing_History_Query();
	$by_code  = $history->count_declines_by_code( 24 );
	$top_fps  = $history->top_fingerprints_by_declines( 24, 10 );
	$timeline = $history->timeline_hourly( 24 );
	$csv_url  = wp_nonce_url(
		admin_url( 'admin-post.php?action=trustlens_ct_history_csv&hours=24' ),
		'trustlens_card_testing_csv'
	);
}

// Pro allowlist data.
$allow_fps   = array();
$allow_cidrs = array();
if ( $is_pro && class_exists( 'TrustLens_Card_Testing_Allowlist_Repository' ) ) {
	$repo        = new TrustLens_Card_Testing_Allowlist_Repository();
	$allow_fps   = $repo->get_fingerprints();
	$allow_cidrs = $repo->get_ip_cidrs();
}

// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only flag-check for post-redirect notices.
$settings_saved   = isset( $_GET['settings-updated'] ) && 'true' === $_GET['settings-updated'];
$allowlist_saved  = ! empty( $_GET['updated'] );
// phpcs:enable
?>
<div class="wrap wstl-ct-page">
	<?php
	wstl_render_page_header( array(
		'title'    => __( 'Card-Testing Defense', 'trustlens' ),
		'meta'     => array(
			array( 'type' => 'date',  'value' => wp_date( 'F j, Y' ) ),
			array( 'type' => 'state', 'value' => $meta['label'], 'level' => $meta['pill'], 'href' => '#panic' ),
			array( 'type' => 'text',  'value' => $meta['desc'] ),
		),
		'actions' => '<a href="#panic" class="button">' . esc_html__( 'Panic Freeze', 'trustlens' ) . '</a>',
	) );
	?>
	<hr class="wp-header-end">

	<?php if ( $settings_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; ?>
	<?php if ( $allowlist_saved ) : ?>
		<div class="notice notice-success is-dismissible" style="margin-left:0;margin-right:0;"><p><?php esc_html_e( 'Allowlist updated.', 'trustlens' ); ?></p></div>
	<?php endif; ?>

	<!-- =========================================================
	     HERO — state + panic controls + live targeted feed
	     ========================================================= -->
	<div class="ct-card ct-hero" id="panic">
		<div class="ct-hero-l">
			<div class="ct-hero-state ct-state-<?php echo esc_attr( strtolower( $current_state ) ); ?>">
				<?php echo esc_html( $meta['label'] ); ?>
			</div>
			<?php if ( 'PANIC' === $current_state && $panic_expires ) : ?>
				<div class="ct-hero-sub">
					<?php
					/* translators: %s: formatted freeze-expiry time. */
					printf( esc_html__( 'Freeze expires %s.', 'trustlens' ), esc_html( date_i18n( 'H:i:s', $panic_expires ) ) );
					?>
				</div>
			<?php endif; ?>

			<?php if ( ! empty( $meta['action'] ) ) : ?>
				<p class="ct-hero-action"><?php echo esc_html( $meta['action'] ); ?></p>
			<?php endif; ?>

			<div class="ct-hero-metrics">
				<div class="m"><div class="v"><?php echo esc_html( number_format_i18n( $declines_24h ) ); ?></div><div class="l"><?php esc_html_e( '24h declines', 'trustlens' ); ?></div></div>
				<div class="m"><div class="v"><?php echo esc_html( number_format_i18n( $subs_24h ) ); ?></div><div class="l"><?php esc_html_e( '24h submissions', 'trustlens' ); ?></div></div>
				<div class="m"><div class="v"><?php echo esc_html( number_format_i18n( $rate_24h, 1 ) . '%' ); ?></div><div class="l"><?php esc_html_e( 'Decline rate', 'trustlens' ); ?></div></div>
				<div class="m"><div class="v"><?php echo esc_html( (string) count( $targeted ) ); ?></div><div class="l"><?php esc_html_e( 'Held fingerprints', 'trustlens' ); ?></div></div>
			</div>
		</div>

		<div class="ct-hero-r">
			<h4><?php esc_html_e( 'Panic Freeze', 'trustlens' ); ?></h4>
			<p><?php esc_html_e( 'Immediately deny every new card attempt for a fixed window.', 'trustlens' ); ?></p>
			<?php if ( 'PANIC' === $current_state ) : ?>
				<button type="button" class="button button-secondary" id="tl-ct-panic-deactivate" data-nonce="<?php echo esc_attr( $panic_nonce ); ?>">
					<?php esc_html_e( 'Deactivate Freeze', 'trustlens' ); ?>
				</button>
			<?php else : ?>
				<div class="ct-panic-row">
					<select id="tl-ct-panic-duration">
						<option value="300"><?php esc_html_e( '5 min', 'trustlens' ); ?></option>
						<option value="900" selected><?php esc_html_e( '15 min', 'trustlens' ); ?></option>
						<option value="1800"><?php esc_html_e( '30 min', 'trustlens' ); ?></option>
					</select>
					<button type="button" class="button button-primary" id="tl-ct-panic-activate" data-nonce="<?php echo esc_attr( $panic_nonce ); ?>">
						<?php esc_html_e( 'Engage', 'trustlens' ); ?>
					</button>
				</div>
			<?php endif; ?>
		</div>

		<div class="ct-hero-r ct-hero-feed">
			<h4><?php esc_html_e( 'Targeted now', 'trustlens' ); ?></h4>
			<?php if ( empty( $targeted ) ) : ?>
				<p class="wstl-empty"><?php esc_html_e( 'No fingerprints held.', 'trustlens' ); ?></p>
			<?php else : ?>
				<ul class="ct-feed">
					<?php foreach ( $targeted as $fp => $expires_at ) : ?>
						<li>
							<span class="hash" title="<?php echo esc_attr( (string) $fp ); ?>"><?php echo esc_html( (string) $fp ); ?></span>
							<span class="ttl"><?php echo esc_html( date_i18n( 'H:i', (int) $expires_at ) ); ?></span>
						</li>
					<?php endforeach; ?>
				</ul>
			<?php endif; ?>
		</div>
	</div>

	<!-- =========================================================
	     TWO-COLUMN — Settings + Allowlists (Pro)
	     ========================================================= -->
	<div class="ct-two">
		<div class="ct-card" id="settings">
			<h3><?php esc_html_e( 'Detection Settings', 'trustlens' ); ?></h3>
			<form method="post" action="<?php echo esc_url( admin_url( 'options.php' ) ); ?>">
				<?php settings_fields( 'trustlens_card_testing' ); ?>
				<table class="form-table ct-form" role="presentation">
					<tr>
						<th scope="row">
							<label for="trustlens_module_card_testing_enabled"><?php esc_html_e( 'Enable Card-Testing Defense', 'trustlens' ); ?></label>
						</th>
						<td>
							<label>
								<input type="checkbox" id="trustlens_module_card_testing_enabled" name="trustlens_module_card_testing_enabled"
									value="1" <?php checked( (bool) get_option( 'trustlens_module_card_testing_enabled', false ) ); ?> />
								<?php esc_html_e( 'Detect and block card-testing attacks before requests reach the payment gateway.', 'trustlens' ); ?>
							</label>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Declines in 60s', 'trustlens' ); ?>
							<?php
							// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Self-escaped helper output.
							echo wstl_help_tip( __( 'A "fingerprint" is one device/browser. If a single fingerprint is declined this many times within 60 seconds, TrustLens locks it down — a classic stolen-card-testing pattern.', 'trustlens' ) );
							?>
						</th>
						<td>
							<input type="number" name="trustlens_card_testing_thresholds[declines_60s]"
								value="<?php echo esc_attr( (int) $thresholds['declines_60s'] ); ?>" min="1" max="100" class="small-text" />
							<span class="ct-unit"><?php esc_html_e( 'per fingerprint', 'trustlens' ); ?></span>
							<p class="description"><?php esc_html_e( 'Trigger lockdown when a fingerprint crosses this rate.', 'trustlens' ); ?></p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Submissions in 60s', 'trustlens' ); ?>
							<?php
							// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Self-escaped helper output.
							echo wstl_help_tip( __( 'Total checkout attempts from one fingerprint within 60 seconds. A rapid burst is a sign of automated card testing.', 'trustlens' ) );
							?>
						</th>
						<td>
							<input type="number" name="trustlens_card_testing_thresholds[submissions_60s]"
								value="<?php echo esc_attr( (int) $thresholds['submissions_60s'] ); ?>" min="1" max="200" class="small-text" />
							<span class="ct-unit"><?php esc_html_e( 'per fingerprint', 'trustlens' ); ?></span>
						</td>
					</tr>
					<tr>
						<th scope="row">
							<label for="trustlens_card_testing_retention_hours"><?php esc_html_e( 'Event retention', 'trustlens' ); ?></label>
						</th>
						<td>
							<input type="number" id="trustlens_card_testing_retention_hours" name="trustlens_card_testing_retention_hours"
								value="<?php echo esc_attr( (int) get_option( 'trustlens_card_testing_retention_hours', 48 ) ); ?>" min="24" max="168" class="small-text" />
							<span class="ct-unit"><?php esc_html_e( 'hours (24–168)', 'trustlens' ); ?></span>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'VIP customer bypass', 'trustlens' ); ?>
							<?php
							// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Self-escaped helper output.
							echo wstl_help_tip( __( 'Repeat customers (at least one completed order) are never blocked by card-testing rules. Reduces false positives, but a returning customer could still be missed — leave on unless you see repeat fraud.', 'trustlens' ) );
							?>
						</th>
						<td>
							<label>
								<input type="checkbox" name="trustlens_card_testing_bypass_vip_customers"
									value="1" <?php checked( (bool) get_option( 'trustlens_card_testing_bypass_vip_customers', true ) ); ?> />
								<?php esc_html_e( 'Never block customers with at least one completed order.', 'trustlens' ); ?>
							</label>
						</td>
					</tr>
				</table>
				<?php submit_button( __( 'Save changes', 'trustlens' ) ); ?>
			</form>
		</div>

		<?php if ( $is_pro ) : ?>
			<div class="ct-card" id="allowlists">
				<h3>
					<?php esc_html_e( 'Allowlists', 'trustlens' ); ?>
					<span class="ct-pro-tag"><?php esc_html_e( 'PRO', 'trustlens' ); ?></span>
				</h3>
				<p class="description" style="margin-top:-6px;margin-bottom:14px;">
					<?php esc_html_e( 'Fingerprints and IP ranges here bypass the defense entirely. Useful for QA devices and integration partners.', 'trustlens' ); ?>
				</p>

				<div class="ct-sub-label"><?php esc_html_e( 'Fingerprints', 'trustlens' ); ?></div>
				<?php if ( ! empty( $allow_fps ) ) : ?>
					<div class="ct-chips">
						<?php foreach ( $allow_fps as $fp ) : ?>
							<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="ct-chip">
								<input type="hidden" name="action" value="trustlens_ct_allowlist" />
								<input type="hidden" name="tl_ct_action" value="remove_fp" />
								<input type="hidden" name="fp" value="<?php echo esc_attr( $fp ); ?>" />
								<?php wp_nonce_field( 'trustlens_card_testing_allowlists' ); ?>
								<span class="hash"><?php echo esc_html( $fp ); ?></span>
								<button type="submit" aria-label="<?php esc_attr_e( 'Remove fingerprint', 'trustlens' ); ?>">&times;</button>
							</form>
						<?php endforeach; ?>
					</div>
				<?php endif; ?>
				<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="ct-allow-add">
					<input type="hidden" name="action" value="trustlens_ct_allowlist" />
					<input type="hidden" name="tl_ct_action" value="add_fp" />
					<?php wp_nonce_field( 'trustlens_card_testing_allowlists' ); ?>
					<input type="text" name="fp" required placeholder="<?php esc_attr_e( 'Paste fingerprint hash', 'trustlens' ); ?>" />
					<button type="submit" class="button"><?php esc_html_e( 'Add', 'trustlens' ); ?></button>
				</form>

				<div class="ct-sub-label" style="margin-top:20px;"><?php esc_html_e( 'IP ranges', 'trustlens' ); ?></div>
				<?php if ( ! empty( $allow_cidrs ) ) : ?>
					<div class="ct-chips">
						<?php foreach ( $allow_cidrs as $cidr ) : ?>
							<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="ct-chip">
								<input type="hidden" name="action" value="trustlens_ct_allowlist" />
								<input type="hidden" name="tl_ct_action" value="remove_cidr" />
								<input type="hidden" name="cidr" value="<?php echo esc_attr( $cidr ); ?>" />
								<?php wp_nonce_field( 'trustlens_card_testing_allowlists' ); ?>
								<span class="hash"><?php echo esc_html( $cidr ); ?></span>
								<button type="submit" aria-label="<?php esc_attr_e( 'Remove CIDR', 'trustlens' ); ?>">&times;</button>
							</form>
						<?php endforeach; ?>
					</div>
				<?php endif; ?>
				<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="ct-allow-add">
					<input type="hidden" name="action" value="trustlens_ct_allowlist" />
					<input type="hidden" name="tl_ct_action" value="add_cidr" />
					<?php wp_nonce_field( 'trustlens_card_testing_allowlists' ); ?>
					<input type="text" name="cidr" required placeholder="<?php esc_attr_e( 'e.g. 10.0.0.0/24 or 203.0.113.55', 'trustlens' ); ?>" />
					<button type="submit" class="button"><?php esc_html_e( 'Add', 'trustlens' ); ?></button>
				</form>
			</div>
		<?php else : ?>
			<div class="ct-card ct-upsell">
				<h3><?php esc_html_e( 'Allowlists & 24-hour intelligence', 'trustlens' ); ?> <span class="ct-pro-tag"><?php esc_html_e( 'PRO', 'trustlens' ); ?></span></h3>
				<p><?php esc_html_e( 'Upgrade to TrustLens Pro to allowlist trusted fingerprints and IP ranges, and to unlock 24-hour attack intelligence (hourly timeline, decline codes, top attackers, CSV export).', 'trustlens' ); ?></p>
				<p><a class="button button-primary" href="<?php echo esc_url( wstl_get_upgrade_url() ); ?>"><?php esc_html_e( 'Upgrade to Pro', 'trustlens' ); ?></a></p>
			</div>
		<?php endif; ?>
	</div>

	<!-- =========================================================
	     24-HOUR INTELLIGENCE (PRO) — full-width
	     ========================================================= -->
	<?php if ( $is_pro ) : ?>
		<div class="ct-card" id="intelligence">
			<h3>
				<?php esc_html_e( '24-hour intelligence', 'trustlens' ); ?>
				<span class="ct-pro-tag"><?php esc_html_e( 'PRO', 'trustlens' ); ?></span>
				<?php if ( $csv_url ) : ?>
					<a class="ct-link-right" href="<?php echo esc_url( $csv_url ); ?>"><?php esc_html_e( 'Export CSV', 'trustlens' ); ?></a>
				<?php endif; ?>
			</h3>
			<div class="ct-chart-wrap">
				<canvas id="tl-ct-timeline" data-series="<?php echo esc_attr( wp_json_encode( $timeline ) ); ?>"></canvas>
			</div>

			<div class="ct-two ct-two-tables">
				<div>
					<div class="ct-sub-label"><?php esc_html_e( 'Decline codes', 'trustlens' ); ?></div>
					<?php if ( empty( $by_code ) ) : ?>
						<p class="wstl-empty"><?php esc_html_e( 'No declines recorded in the last 24 hours.', 'trustlens' ); ?></p>
					<?php else : ?>
						<table class="ct-table">
							<tbody>
								<?php foreach ( $by_code as $code => $count ) : ?>
									<tr>
										<td class="hash"><?php echo esc_html( (string) $code ); ?></td>
										<td class="num"><?php echo esc_html( number_format_i18n( (int) $count ) ); ?></td>
									</tr>
								<?php endforeach; ?>
							</tbody>
						</table>
					<?php endif; ?>
				</div>
				<div>
					<div class="ct-sub-label"><?php esc_html_e( 'Top attacking fingerprints', 'trustlens' ); ?></div>
					<?php if ( empty( $top_fps ) ) : ?>
						<p class="wstl-empty"><?php esc_html_e( 'No attackers recorded in the last 24 hours.', 'trustlens' ); ?></p>
					<?php else : ?>
						<table class="ct-table">
							<tbody>
								<?php foreach ( $top_fps as $row ) : ?>
									<tr>
										<td class="hash"><?php echo esc_html( (string) $row->fingerprint_hash ); ?></td>
										<td class="num"><?php echo esc_html( number_format_i18n( (int) $row->decline_count ) ); ?></td>
									</tr>
								<?php endforeach; ?>
							</tbody>
						</table>
					<?php endif; ?>
				</div>
			</div>
		</div>
	<?php endif; ?>
</div>
