<?php
/**
 * Shared Captcha Dashboard Widget
 *
 * Roadmap item #29 UI surface: a single WP dashboard widget that shows a
 * consolidated view of challenge counters from every enabled captcha module.
 *
 * Registration is idempotent — the first captcha module to call
 * {@see self::register()} wires the hook once; subsequent calls from other
 * modules noop. Nothing runs if no captcha module is enabled.
 *
 * @package WP_PowerSuite\Captcha\Shared
 * @since 1.1.0
 */

namespace WP_PowerSuite\Captcha\Shared;

/**
 * Dashboard widget.
 */
final class DashboardWidget {

	private static bool $registered = false;

	/**
	 * Module IDs that opted in, used when rendering the widget.
	 *
	 * @var array<string,string> module_id => Display label
	 */
	private static array $providers = [];

	/**
	 * Opt a provider into the widget. Safe to call multiple times.
	 *
	 * @param string $module_id Module id (e.g. `google-recaptcha`).
	 * @param string $label     Human-readable label for the widget row.
	 */
	public static function register( string $module_id, string $label ): void {
		$module_id = sanitize_key( $module_id );
		if ( $module_id === '' ) {
			return;
		}
		self::$providers[ $module_id ] = $label;
		if ( self::$registered ) {
			return;
		}
		self::$registered = true;
		add_action( 'wp_dashboard_setup', [ self::class, 'bootstrap' ] );
	}

	/**
	 * WordPress hook target: register the widget when the dashboard loads.
	 */
	public static function bootstrap(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		if ( empty( self::$providers ) ) {
			return;
		}
		wp_add_dashboard_widget(
			'wpps_captcha_overview',
			esc_html__( 'WP PowerSuite Captcha Activity', 'wp-powersuite' ),
			[ self::class, 'render' ]
		);
	}

	/**
	 * Dashboard widget body.
	 */
	public static function render(): void {
		echo '<table class="widefat striped" style="border:0"><thead><tr>';
		echo '<th>' . esc_html__( 'Provider', 'wp-powersuite' ) . '</th>';
		echo '<th>' . esc_html__( 'Passed (30d)', 'wp-powersuite' ) . '</th>';
		echo '<th>' . esc_html__( 'Failed (30d)', 'wp-powersuite' ) . '</th>';
		echo '</tr></thead><tbody>';
		foreach ( self::$providers as $id => $label ) {
			$summary = Counters::summary( $id );
			echo '<tr>';
			echo '<td>' . esc_html( $label ) . '</td>';
			echo '<td>' . esc_html( (string) $summary['passed'] ) . '</td>';
			echo '<td>' . esc_html( (string) $summary['failed'] ) . '</td>';
			echo '</tr>';
		}
		echo '</tbody></table>';
		echo '<p class="description" style="margin-top:8px">' . esc_html__( 'Rolling 30-day window. Only providers that are enabled contribute data.', 'wp-powersuite' ) . '</p>';
	}
}
