<?php
/**
 * Dashboard widget for Card-Testing Defense status.
 *
 * Expects $state (TrustLens_Lockdown_State) in scope.
 *
 * @package TrustLens
 */
defined( 'ABSPATH' ) || exit;

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

$is_enabled = (bool) get_option( 'trustlens_module_card_testing_enabled', false );
$page_url   = admin_url( 'admin.php?page=' . TrustLens_Admin_Card_Testing_Page::PAGE_SLUG . '#settings' );

if ( ! $is_enabled ) :
	?>
	<p style="color: #646970;">
		<?php esc_html_e( 'Card-Testing Defense is currently disabled.', 'trustlens' ); ?>
	</p>
	<p>
		<a class="button button-primary" href="<?php echo esc_url( $page_url ); ?>">
			<?php esc_html_e( 'Enable Card-Testing Defense', 'trustlens' ); ?>
		</a>
	</p>
	<?php
	return;
endif;

global $wpdb;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Real-time dashboard widget count from a custom table; table name from $wpdb->prefix.
$last_24h_declines = (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)"
);

$current = $state->current_state();
?>
<?php if ( 'PANIC' === $current ) : ?>
	<p style="color: #dc3232; font-weight: bold;">
		<?php echo esc_html( '🚨 ' ); ?><?php esc_html_e( 'Active attack — panic freeze in effect', 'trustlens' ); ?>
	</p>
<?php elseif ( 'TARGETED' === $current ) : ?>
	<p style="color: #ffb900;">
		<?php echo esc_html( '⚠ ' ); ?><?php esc_html_e( 'Active attack — targeted blocking engaged', 'trustlens' ); ?>
	</p>
<?php else : ?>
	<p style="color: #46b450;">
		<?php echo esc_html( '✓ ' ); ?><?php esc_html_e( 'No active attack', 'trustlens' ); ?>
	</p>
<?php endif; ?>

<p>
	<?php
	printf(
		/* translators: %d: count of declines in last 24 hours. */
		esc_html__( 'Last 24h: %d declined payment attempt(s)', 'trustlens' ),
		absint( $last_24h_declines )
	);
	?>
</p>

<p>
	<a class="button" href="<?php echo esc_url( admin_url( 'admin.php?page=' . TrustLens_Admin_Card_Testing_Page::PAGE_SLUG ) ); ?>">
		<?php esc_html_e( 'Open Card-Testing Defense', 'trustlens' ); ?>
	</a>
</p>
