<?php

/**
 * Dashboard widget for Checkout Shield statistics.
 *
 * @package Carticy\CheckoutShield\Admin
 */
declare (strict_types = 1);
namespace Carticy\CheckoutShield\Admin;

use Carticy\CheckoutShield\Services\LoggingService;
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;

    /**
     * Logging service.
     *
     * @var LoggingService
     */
    private LoggingService $logging_service;

    /**
     * Constructor.
     *
     * @param StatsService   $stats_service   Stats service instance.
     * @param LoggingService $logging_service Logging service instance.
     */
    public function __construct( StatsService $stats_service, LoggingService $logging_service ) {
        $this->stats_service = $stats_service;
        $this->logging_service = $logging_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', 'balanced' );
        // 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 
        ?>
			<?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 
        }
        ?>
			</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>
				<?php 
        if ( !carticy_checkoutshield_fs()->is_paying() ) {
            ?>
					&nbsp;|&nbsp;
					<a href="<?php 
            echo esc_url( carticy_checkoutshield_fs()->get_upgrade_url() );
            ?>" style="color: #00a32a; font-weight: 600;">
						<?php 
            esc_html_e( 'Unlock Pro Features', 'carticy-checkout-shield-for-woocommerce' );
            ?>
					</a>
				<?php 
        }
        ?>
			</div>
		</div>
		<?php 
    }

    /**
     * Render recent blocks table (Pro feature).
     */
    private function render_recent_blocks() : void {
        $blocks = $this->logging_service->get_recent_blocks( 5 );
        if ( empty( $blocks ) ) {
            return;
        }
        ?>
		<div class="ccs-recent-blocks">
			<div class="ccs-recent-blocks-title"><?php 
        esc_html_e( 'Recent Blocks', 'carticy-checkout-shield-for-woocommerce' );
        ?></div>
			<table class="ccs-recent-blocks-table">
				<thead>
					<tr>
						<th><?php 
        esc_html_e( 'Time', 'carticy-checkout-shield-for-woocommerce' );
        ?></th>
						<th><?php 
        esc_html_e( 'Email', 'carticy-checkout-shield-for-woocommerce' );
        ?></th>
						<th><?php 
        esc_html_e( 'Payment', 'carticy-checkout-shield-for-woocommerce' );
        ?></th>
						<th><?php 
        esc_html_e( 'Reason', 'carticy-checkout-shield-for-woocommerce' );
        ?></th>
					</tr>
				</thead>
				<tbody>
					<?php 
        foreach ( $blocks as $block ) {
            ?>
						<tr>
							<td><?php 
            echo esc_html( human_time_diff( $block['time'], time() ) );
            ?></td>
							<td><?php 
            echo esc_html( ( !empty( $block['email'] ) ? $block['email'] : "\\u2014" ) );
            ?></td>
							<td><?php 
            echo esc_html( ( !empty( $block['payment_method'] ) ? $block['payment_method'] : "\\u2014" ) );
            ?></td>
							<td><span class="ccs-reason-badge"><?php 
            echo esc_html( $block['reason'] );
            ?></span></td>
						</tr>
					<?php 
        }
        ?>
				</tbody>
			</table>
		</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; }

			/* Recent Blocks Table */
			.ccs-recent-blocks {
				border-bottom: 1px solid #dcdcde;
			}
			.ccs-recent-blocks-title {
				padding: 10px 12px 0;
				font-size: 11px;
				font-weight: 600;
				text-transform: uppercase;
				color: #646970;
			}
			.ccs-recent-blocks-table {
				width: 100%;
				border-collapse: collapse;
				font-size: 12px;
			}
			.ccs-recent-blocks-table th {
				text-align: left;
				padding: 6px 8px;
				font-size: 10px;
				text-transform: uppercase;
				color: #646970;
				border-bottom: 1px solid #f0f0f1;
			}
			.ccs-recent-blocks-table td {
				padding: 5px 8px;
				border-bottom: 1px solid #f0f0f1;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				max-width: 120px;
			}
			.ccs-recent-blocks-table tr:last-child td {
				border-bottom: none;
			}
			.ccs-reason-badge {
				display: inline-block;
				padding: 1px 6px;
				border-radius: 3px;
				background: #f8e8e8;
				color: #d63638;
				font-size: 10px;
				font-weight: 500;
			}

			/* Footer */
			.ccs-widget-footer {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 12px;
				font-size: 13px;
				flex-wrap: wrap;
				gap: 4px;
			}
		';
        wp_add_inline_style( 'dashboard', $css );
    }

}
