<?php
/**
 * Dashboard widget for Checkout Shield statistics.
 *
 * @package Carticy\CheckoutShield\Admin
 */

declare(strict_types=1);

namespace Carticy\CheckoutShield\Admin;

use Carticy\CheckoutShield\Services\StatsService;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Displays shield statistics on the WordPress dashboard.
 */
final class DashboardWidget {

	/**
	 * Widget ID.
	 */
	private const WIDGET_ID = 'carticy_checkout_shield_dashboard';

	/**
	 * Stats service.
	 *
	 * @var StatsService
	 */
	private StatsService $stats_service;

	/**
	 * Constructor.
	 *
	 * @param StatsService $stats_service Stats service instance.
	 */
	public function __construct( StatsService $stats_service ) {
		$this->stats_service = $stats_service;
	}

	/**
	 * Register hooks.
	 */
	public function register(): void {
		add_action( 'wp_dashboard_setup', array( $this, 'add_dashboard_widget' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_widget_styles' ) );
	}

	/**
	 * Add the dashboard widget.
	 */
	public function add_dashboard_widget(): void {
		// Only show to users who can manage WooCommerce.
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			return;
		}

		wp_add_dashboard_widget(
			self::WIDGET_ID,
			__( 'Checkout Shield', 'carticy-checkout-shield-for-woocommerce' ),
			array( $this, 'render_widget' )
		);
	}

	/**
	 * Render the widget content.
	 */
	public function render_widget(): void {
		$totals      = $this->stats_service->get_totals( 30 );
		$daily_stats = $this->stats_service->get_daily_stats( 7 );
		$max_daily   = $this->stats_service->get_max_daily_total( 7 );
		$mode        = get_option( 'carticy_checkout_shield_mode', 'learning' );

		// Ensure we have at least 1 for percentage calculations to avoid division by zero.
		$scale = max( $max_daily, 1 );
		?>
		<div class="ccs-widget">
			<?php $this->render_chart( $daily_stats, $scale ); ?>
			<?php $this->render_stats( $totals ); ?>
			<?php $this->render_footer( $mode ); ?>
		</div>
		<?php
	}

	/**
	 * Render the 7-day bar chart.
	 *
	 * @param array $daily_stats Daily stats array.
	 * @param int   $scale       Maximum value for scaling.
	 */
	private function render_chart( array $daily_stats, int $scale ): void {
		?>
		<div class="ccs-chart">
			<div class="ccs-chart-legend">
				<span class="ccs-legend-item ccs-legend-blocked"><?php esc_html_e( 'Blocked', 'carticy-checkout-shield-for-woocommerce' ); ?></span>
				<span class="ccs-legend-item ccs-legend-passed"><?php esc_html_e( 'Passed', 'carticy-checkout-shield-for-woocommerce' ); ?></span>
				<span class="ccs-legend-item ccs-legend-learning"><?php esc_html_e( 'Learning', 'carticy-checkout-shield-for-woocommerce' ); ?></span>
				<span class="ccs-legend-item ccs-legend-bypassed"><?php esc_html_e( 'Bypassed', 'carticy-checkout-shield-for-woocommerce' ); ?></span>
			</div>
			<div class="ccs-chart-bars">
				<?php foreach ( $daily_stats as $date => $day_stats ) : ?>
					<?php
					$blocked_pct = $scale > 0 ? ( $day_stats['blocked'] / $scale ) * 100 : 0;
					$passed_pct  = $scale > 0 ? ( $day_stats['passed'] / $scale ) * 100 : 0;
					$learn_pct   = $scale > 0 ? ( $day_stats['learning'] / $scale ) * 100 : 0;
					$bypass_pct  = $scale > 0 ? ( $day_stats['bypassed'] / $scale ) * 100 : 0;
					$day_label   = gmdate( 'D', strtotime( $date ) );

					// Build tooltip text.
					$tooltip_parts = array();
					if ( $day_stats['blocked'] > 0 ) {
						$tooltip_parts[] = sprintf(
							/* translators: %d: number of blocked requests */
							_n( '%d blocked', '%d blocked', $day_stats['blocked'], 'carticy-checkout-shield-for-woocommerce' ),
							$day_stats['blocked']
						);
					}
					if ( $day_stats['passed'] > 0 ) {
						$tooltip_parts[] = sprintf(
							/* translators: %d: number of passed requests */
							_n( '%d passed', '%d passed', $day_stats['passed'], 'carticy-checkout-shield-for-woocommerce' ),
							$day_stats['passed']
						);
					}
					if ( $day_stats['learning'] > 0 ) {
						$tooltip_parts[] = sprintf(
							/* translators: %d: number of learning requests */
							_n( '%d learning', '%d learning', $day_stats['learning'], 'carticy-checkout-shield-for-woocommerce' ),
							$day_stats['learning']
						);
					}
					if ( $day_stats['bypassed'] > 0 ) {
						$tooltip_parts[] = sprintf(
							/* translators: %d: number of bypassed requests */
							_n( '%d bypassed', '%d bypassed', $day_stats['bypassed'], 'carticy-checkout-shield-for-woocommerce' ),
							$day_stats['bypassed']
						);
					}
					$tooltip = empty( $tooltip_parts )
						? __( 'No activity', 'carticy-checkout-shield-for-woocommerce' )
						: implode( ', ', $tooltip_parts );
					?>
					<div class="ccs-chart-column">
						<div class="ccs-chart-bar"
							style="--blocked: <?php echo esc_attr( $blocked_pct ); ?>%; --passed: <?php echo esc_attr( $passed_pct ); ?>%; --learning: <?php echo esc_attr( $learn_pct ); ?>%; --bypassed: <?php echo esc_attr( $bypass_pct ); ?>%;"
							data-tooltip="<?php echo esc_attr( $tooltip ); ?>">
							<div class="ccs-bar-segment ccs-bar-bypassed"></div>
							<div class="ccs-bar-segment ccs-bar-learning"></div>
							<div class="ccs-bar-segment ccs-bar-passed"></div>
							<div class="ccs-bar-segment ccs-bar-blocked"></div>
						</div>
						<span class="ccs-chart-label"><?php echo esc_html( $day_label ); ?></span>
					</div>
				<?php endforeach; ?>
			</div>
		</div>
		<?php
	}

	/**
	 * Render the stats summary.
	 *
	 * @param array $totals Aggregated totals.
	 */
	private function render_stats( array $totals ): void {
		?>
		<div class="ccs-widget-stats">
			<div class="ccs-widget-stat ccs-widget-stat--blocked">
				<span class="ccs-widget-stat-value"><?php echo esc_html( number_format_i18n( $totals['blocked'] ) ); ?></span>
				<span class="ccs-widget-stat-label"><?php esc_html_e( 'Blocked', 'carticy-checkout-shield-for-woocommerce' ); ?></span>
			</div>
			<div class="ccs-widget-stat ccs-widget-stat--passed">
				<span class="ccs-widget-stat-value"><?php echo esc_html( number_format_i18n( $totals['passed'] ) ); ?></span>
				<span class="ccs-widget-stat-label"><?php esc_html_e( 'Passed', 'carticy-checkout-shield-for-woocommerce' ); ?></span>
			</div>
			<div class="ccs-widget-stat ccs-widget-stat--learning">
				<span class="ccs-widget-stat-value"><?php echo esc_html( number_format_i18n( $totals['learning'] ) ); ?></span>
				<span class="ccs-widget-stat-label"><?php esc_html_e( 'Learning', 'carticy-checkout-shield-for-woocommerce' ); ?></span>
			</div>
			<div class="ccs-widget-stat ccs-widget-stat--bypassed">
				<span class="ccs-widget-stat-value"><?php echo esc_html( number_format_i18n( $totals['bypassed'] ) ); ?></span>
				<span class="ccs-widget-stat-label"><?php esc_html_e( 'Bypassed', 'carticy-checkout-shield-for-woocommerce' ); ?></span>
			</div>
		</div>
		<?php
	}

	/**
	 * Render the footer with mode and links.
	 *
	 * @param string $mode Current operating mode.
	 */
	private function render_footer( string $mode ): void {
		?>
		<div class="ccs-widget-footer">
			<div>
				<?php esc_html_e( 'Mode:', 'carticy-checkout-shield-for-woocommerce' ); ?>
				<span class="ccs-widget-mode ccs-widget-mode--<?php echo esc_attr( $mode ); ?>">
					<?php echo esc_html( ucfirst( $mode ) ); ?>
				</span>
			</div>
			<div>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=wc-settings&tab=advanced&section=checkout_shield' ) ); ?>">
					<?php esc_html_e( 'Settings', 'carticy-checkout-shield-for-woocommerce' ); ?>
				</a>
				&nbsp;|&nbsp;
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=wc-status&tab=logs&source=carticy-checkout-shield' ) ); ?>">
					<?php esc_html_e( 'View Logs', 'carticy-checkout-shield-for-woocommerce' ); ?>
				</a>
			</div>
		</div>
		<?php
	}

	/**
	 * Enqueue widget styles on the dashboard.
	 *
	 * @param string $hook Current admin page hook.
	 */
	public function enqueue_widget_styles( string $hook ): void {
		if ( 'index.php' !== $hook ) {
			return;
		}

		// Only enqueue if user can see the widget.
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			return;
		}

		$css = '
			.ccs-widget {
				margin: -12px;
			}

			/* Chart Legend */
			.ccs-chart-legend {
				display: flex;
				gap: 12px;
				padding: 12px;
				border-bottom: 1px solid #dcdcde;
				flex-wrap: wrap;
			}
			.ccs-legend-item {
				display: flex;
				align-items: center;
				gap: 4px;
				font-size: 11px;
				color: #50575e;
			}
			.ccs-legend-item::before {
				content: "";
				display: block;
				width: 10px;
				height: 10px;
				border-radius: 2px;
			}
			.ccs-legend-blocked::before { background: #d63638; }
			.ccs-legend-passed::before { background: #00a32a; }
			.ccs-legend-learning::before { background: #dba617; }
			.ccs-legend-bypassed::before { background: #2271b1; }

			/* Chart Bars */
			.ccs-chart-bars {
				display: flex;
				gap: 8px;
				padding: 16px 12px;
				background: #f6f7f7;
				justify-content: space-between;
			}
			.ccs-chart-column {
				flex: 1;
				display: flex;
				flex-direction: column;
				align-items: center;
				min-width: 0;
			}
			.ccs-chart-bar {
				position: relative;
				width: 100%;
				height: 60px;
				background: #e0e0e0;
				border-radius: 3px 3px 0 0;
				display: flex;
				flex-direction: column-reverse;
				overflow: hidden;
				cursor: help;
			}
			.ccs-bar-segment {
				width: 100%;
				transition: height 0.3s ease;
			}
			.ccs-bar-blocked {
				height: var(--blocked, 0%);
				background: #d63638;
			}
			.ccs-bar-passed {
				height: var(--passed, 0%);
				background: #00a32a;
			}
			.ccs-bar-learning {
				height: var(--learning, 0%);
				background: #dba617;
			}
			.ccs-bar-bypassed {
				height: var(--bypassed, 0%);
				background: #2271b1;
			}
			.ccs-chart-label {
				font-size: 10px;
				color: #646970;
				margin-top: 4px;
				text-transform: uppercase;
			}

			/* Tooltip */
			.ccs-chart-bar::after {
				content: attr(data-tooltip);
				position: absolute;
				bottom: calc(100% + 8px);
				left: 50%;
				transform: translateX(-50%);
				background: #1d2327;
				color: #fff;
				padding: 6px 10px;
				border-radius: 4px;
				font-size: 11px;
				white-space: nowrap;
				opacity: 0;
				visibility: hidden;
				transition: opacity 0.2s, visibility 0.2s;
				z-index: 100;
				pointer-events: none;
			}
			.ccs-chart-bar::before {
				content: "";
				position: absolute;
				bottom: calc(100% + 4px);
				left: 50%;
				transform: translateX(-50%);
				border: 4px solid transparent;
				border-top-color: #1d2327;
				opacity: 0;
				visibility: hidden;
				transition: opacity 0.2s, visibility 0.2s;
				z-index: 100;
			}
			.ccs-chart-bar:hover::after,
			.ccs-chart-bar:hover::before {
				opacity: 1;
				visibility: visible;
			}

			/* Stats Grid */
			.ccs-widget-stats {
				display: flex;
				gap: 8px;
				padding: 12px;
				border-bottom: 1px solid #dcdcde;
				flex-wrap: wrap;
			}
			.ccs-widget-stat {
				flex: 1;
				display: flex;
				flex-direction: column;
				padding: 8px 10px;
				background: #f6f7f7;
				border-radius: 4px;
				min-width: 60px;
				text-align: center;
			}
			.ccs-widget-stat-value {
				font-size: 18px;
				font-weight: 600;
				line-height: 1.2;
			}
			.ccs-widget-stat-label {
				font-size: 10px;
				color: #646970;
				text-transform: uppercase;
				margin-top: 2px;
			}
			.ccs-widget-stat--blocked .ccs-widget-stat-value { color: #d63638; }
			.ccs-widget-stat--passed .ccs-widget-stat-value { color: #00a32a; }
			.ccs-widget-stat--learning .ccs-widget-stat-value { color: #996800; }
			.ccs-widget-stat--bypassed .ccs-widget-stat-value { color: #2271b1; }

			/* Mode Badge */
			.ccs-widget-mode {
				display: inline-block;
				padding: 2px 8px;
				border-radius: 3px;
				font-size: 11px;
				font-weight: 500;
				text-transform: uppercase;
			}
			.ccs-widget-mode--learning { background: #fcf0c3; color: #996800; }
			.ccs-widget-mode--permissive { background: #d6f4e9; color: #00a32a; }
			.ccs-widget-mode--balanced { background: #e7f0f5; color: #2271b1; }
			.ccs-widget-mode--strict { background: #f8e8e8; color: #d63638; }

			/* Footer */
			.ccs-widget-footer {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 12px;
				font-size: 13px;
			}
		';

		wp_add_inline_style( 'dashboard', $css );
	}
}
