<?php
/**
 * Analytics admin page & dashboard widget.
 *
 * @package IGIT_RPWT
 */

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

class IGIT_RPWT_Analytics_Page {

	/** Admin submenu slug. */
	const PAGE_SLUG = 'igit-rpwt-analytics';

	public function __construct() {
		// Note: 'admin_menu' hook deliberately omitted — Analytics is accessible
		// via the Analytics tab in Settings, not as a standalone sidebar item.

		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
		add_action( 'wp_dashboard_setup',    array( $this, 'register_dashboard_widget' ) );
	}

	// ── Menu ─────────────────────────────────────────────────────────────────

	public function add_submenu() {
		add_submenu_page(
			'igit-rpwt',
			__( 'Related Posts Analytics', 'igit-related-posts-with-thumb-images-after-posts' ),
			__( 'Analytics', 'igit-related-posts-with-thumb-images-after-posts' ),
			'manage_options',
			self::PAGE_SLUG,
			array( $this, 'render_page' )
		);
	}

	// ── Assets ───────────────────────────────────────────────────────────────

	public function enqueue_assets( $hook ) {
		// Load styles on the analytics page, the main settings page, and the dashboard.
		if ( 'igit-rpwt_page_' . self::PAGE_SLUG !== $hook && 'toplevel_page_igit-rpwt' !== $hook && 'index.php' !== $hook ) {
			return;
		}
		wp_enqueue_style(
			'igit-rpwt-analytics',
			IGIT_RPWT_PLUGIN_URL . 'assets/css/analytics.css',
			array(),
			IGIT_RPWT_VERSION
		);
	}

	// ── Analytics page ───────────────────────────────────────────────────────

	/**
	 * Render analytics data inside the main settings page Analytics tab.
	 * Shows the enable/disable toggle at the top, then data if tracking is on.
	 */
	public static function render_tab() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		// ── Enable/disable toggle (always visible at the top) ─────────────────
		$tracking_on = (bool) IGIT_RPWT_Settings::get( 'enable_click_tracking' );
		?>
		<div class="igit-rpwt-tracking-row">
			<span class="igit-rpwt-tracking-label"><?php esc_html_e( 'Enable Click Tracking', 'igit-related-posts-with-thumb-images-after-posts' ); ?></span>
			<label class="igit-rpwt-toggle" for="enable_click_tracking">
				<input type="checkbox" id="enable_click_tracking" name="igit_rpwt_settings[enable_click_tracking]" value="1" <?php checked( $tracking_on ); ?> />
				<span class="igit-rpwt-toggle-track"><span class="igit-rpwt-toggle-thumb"></span></span>
			</label>
			<p class="description"><?php esc_html_e( 'Record clicks on related post links for analytics (stored in DB).', 'igit-related-posts-with-thumb-images-after-posts' ); ?></p>
		</div>
		<?php
		if ( ! $tracking_on ) {
			return;
		}

		// ── Source filter from URL param ──────────────────────────────────────
		$active_source = isset( $_GET['click_source'] ) ? sanitize_key( $_GET['click_source'] ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( ! in_array( $active_source, array( 'widget', 'nudge' ), true ) ) {
			$active_source = '';
		}

		$days         = 30;
		$top_posts    = IGIT_RPWT_Analytics::get_top_posts( $days, 20, $active_source );
		$all_time     = IGIT_RPWT_Analytics::get_total_clicks( 0, $active_source );
		$last30       = IGIT_RPWT_Analytics::get_total_clicks( $days, $active_source );
		$unique_posts = count( IGIT_RPWT_Analytics::get_top_posts( 0, 9999, $active_source ) );
		$by_source    = IGIT_RPWT_Analytics::get_clicks_by_source( $days );

		if ( '' === $active_source ) {
			$daily     = IGIT_RPWT_Analytics::get_daily_totals_by_source( $days );
			$max_daily = 1;
			foreach ( $daily as $row ) {
				$day_total = $row['widget_total'] + $row['nudge_total'];
				if ( $day_total > $max_daily ) {
					$max_daily = $day_total;
				}
			}
		} else {
			$daily     = IGIT_RPWT_Analytics::get_daily_totals( $days, $active_source );
			$max_daily = $daily ? (int) max( array_column( $daily, 'daily_total' ) ) : 1;
		}

		$max_clicks = $top_posts ? (int) max( array_column( $top_posts, 'total_clicks' ) ) : 1;

		// Build current URL for tabs.
		$base_url = admin_url( 'admin.php?page=igit-rpwt&tab=analytics' );
		?>
		<div class="igit-rpwt-analytics-tab-content">

			<!-- ── Source filter tabs ────────────────────────────────── -->
			<div class="igit-rpwt-source-tabs">
				<a href="<?php echo esc_url( $base_url ); ?>" class="igit-rpwt-source-tab<?php echo '' === $active_source ? ' is-active' : ''; ?>">
					<?php esc_html_e( 'All Sources', 'igit-related-posts-with-thumb-images-after-posts' ); ?>
				</a>
				<a href="<?php echo esc_url( add_query_arg( 'click_source', 'widget', $base_url ) ); ?>" class="igit-rpwt-source-tab<?php echo 'widget' === $active_source ? ' is-active' : ''; ?>">
					<?php esc_html_e( 'Related Posts', 'igit-related-posts-with-thumb-images-after-posts' ); ?>
				</a>
				<a href="<?php echo esc_url( add_query_arg( 'click_source', 'nudge', $base_url ) ); ?>" class="igit-rpwt-source-tab<?php echo 'nudge' === $active_source ? ' is-active' : ''; ?>">
					<?php esc_html_e( 'Post Nudges', 'igit-related-posts-with-thumb-images-after-posts' ); ?>
				</a>
			</div>

			<!-- ── Summary cards ─────────────────────────────────────── -->
			<div class="igit-rpwt-stat-cards">
				<div class="igit-rpwt-stat-card">
					<div class="igit-rpwt-stat-value"><?php echo esc_html( number_format_i18n( $last30 ) ); ?></div>
					<div class="igit-rpwt-stat-label"><?php esc_html_e( 'Clicks (last 30 days)', 'igit-related-posts-with-thumb-images-after-posts' ); ?></div>
				</div>
				<div class="igit-rpwt-stat-card">
					<div class="igit-rpwt-stat-value"><?php echo esc_html( number_format_i18n( $all_time ) ); ?></div>
					<div class="igit-rpwt-stat-label"><?php esc_html_e( 'Total Clicks (all time)', 'igit-related-posts-with-thumb-images-after-posts' ); ?></div>
				</div>
				<div class="igit-rpwt-stat-card">
					<div class="igit-rpwt-stat-value"><?php echo esc_html( number_format_i18n( $unique_posts ) ); ?></div>
					<div class="igit-rpwt-stat-label"><?php esc_html_e( 'Posts Clicked (all time)', 'igit-related-posts-with-thumb-images-after-posts' ); ?></div>
				</div>
				<?php if ( '' === $active_source ) : ?>
				<div class="igit-rpwt-stat-card igit-rpwt-stat-card--widget">
					<div class="igit-rpwt-stat-value"><?php echo esc_html( number_format_i18n( $by_source['widget'] ) ); ?></div>
					<div class="igit-rpwt-stat-label"><?php esc_html_e( 'Widget Clicks (last 30d)', 'igit-related-posts-with-thumb-images-after-posts' ); ?></div>
				</div>
				<div class="igit-rpwt-stat-card igit-rpwt-stat-card--nudge">
					<div class="igit-rpwt-stat-value"><?php echo esc_html( number_format_i18n( $by_source['nudge'] ) ); ?></div>
					<div class="igit-rpwt-stat-label"><?php esc_html_e( 'Nudge Clicks (last 30d)', 'igit-related-posts-with-thumb-images-after-posts' ); ?></div>
				</div>
				<?php endif; ?>
			</div>

			<?php if ( $daily ) : ?>
			<!-- ── Activity chart ────────────────────────────────────── -->
			<div class="igit-rpwt-chart-card">
				<h2>
					<?php esc_html_e( 'Click Activity', 'igit-related-posts-with-thumb-images-after-posts' ); ?>
					<?php if ( '' === $active_source ) : ?>
					<span class="igit-rpwt-chart-legend">
						<span class="igit-rpwt-legend-dot igit-rpwt-legend-dot--widget"></span><?php esc_html_e( 'Widget', 'igit-related-posts-with-thumb-images-after-posts' ); ?>
						<span class="igit-rpwt-legend-dot igit-rpwt-legend-dot--nudge"></span><?php esc_html_e( 'Nudge', 'igit-related-posts-with-thumb-images-after-posts' ); ?>
					</span>
					<?php endif; ?>
				</h2>
				<div class="igit-rpwt-bar-chart" role="img" aria-label="<?php esc_attr_e( 'Daily click activity over the last 30 days', 'igit-related-posts-with-thumb-images-after-posts' ); ?>">
					<?php
					if ( '' === $active_source ) {
						$daily_map = array();
						foreach ( $daily as $row ) {
							$daily_map[ $row['click_date'] ] = $row;
						}
						for ( $i = $days - 1; $i >= 0; $i-- ) {
							$date         = wp_date( 'Y-m-d', strtotime( "-{$i} days" ) );
							$widget_count = isset( $daily_map[ $date ] ) ? (int) $daily_map[ $date ]['widget_total'] : 0;
							$nudge_count  = isset( $daily_map[ $date ] ) ? (int) $daily_map[ $date ]['nudge_total']  : 0;
							$total        = $widget_count + $nudge_count;
							$widget_pct   = $max_daily > 0 ? round( ( $widget_count / $max_daily ) * 100 ) : 0;
							$nudge_pct    = $max_daily > 0 ? round( ( $nudge_count / $max_daily ) * 100 ) : 0;
							?>
							<span class="igit-rpwt-bar-wrap igit-rpwt-bar-wrap--dual" title="<?php echo esc_attr( $date . ': ' . $total . ' (' . $widget_count . ' widget + ' . $nudge_count . ' nudge)' ); ?>">
								<span class="igit-rpwt-bar igit-rpwt-bar--nudge" style="height:<?php echo esc_attr( max( $nudge_pct > 0 ? 2 : 0, $nudge_pct ) ); ?>%"></span>
								<span class="igit-rpwt-bar igit-rpwt-bar--widget" style="height:<?php echo esc_attr( max( $widget_pct > 0 ? 2 : 0, $widget_pct ) ); ?>%"></span>
							</span>
							<?php
						}
					} else {
						$daily_map = array();
						foreach ( $daily as $row ) {
							$daily_map[ $row['click_date'] ] = (int) $row['daily_total'];
						}
						$bar_class = 'widget' === $active_source ? 'igit-rpwt-bar igit-rpwt-bar--widget' : 'igit-rpwt-bar igit-rpwt-bar--nudge';
						for ( $i = $days - 1; $i >= 0; $i-- ) {
							$date  = wp_date( 'Y-m-d', strtotime( "-{$i} days" ) );
							$count = isset( $daily_map[ $date ] ) ? $daily_map[ $date ] : 0;
							$pct   = $max_daily > 0 ? round( ( $count / $max_daily ) * 100 ) : 0;
							?>
							<span class="igit-rpwt-bar-wrap" title="<?php echo esc_attr( $date . ': ' . $count ); ?>">
								<span class="<?php echo esc_attr( $bar_class ); ?>" style="height:<?php echo esc_attr( max( 2, $pct ) ); ?>%"></span>
							</span>
							<?php
						}
					}
					?>
				</div>
				<div class="igit-rpwt-chart-labels">
					<span><?php echo esc_html( wp_date( get_option( 'date_format' ), strtotime( '-29 days' ) ) ); ?></span>
					<span><?php esc_html_e( 'Today', 'igit-related-posts-with-thumb-images-after-posts' ); ?></span>
				</div>
			</div>
			<?php endif; ?>

			<!-- ── Top posts table ───────────────────────────────────── -->
			<div class="igit-rpwt-analytics-table-card">
				<h2><?php esc_html_e( 'Most Clicked Related Posts', 'igit-related-posts-with-thumb-images-after-posts' ); ?></h2>

				<?php if ( empty( $top_posts ) ) : ?>
					<p class="igit-rpwt-no-data"><?php esc_html_e( 'No click data yet. Visitors need to view posts that display a related posts block.', 'igit-related-posts-with-thumb-images-after-posts' ); ?></p>
				<?php else : ?>
				<table class="widefat striped igit-rpwt-analytics-table">
					<thead>
						<tr>
							<th scope="col"><?php esc_html_e( '#', 'igit-related-posts-with-thumb-images-after-posts' ); ?></th>
							<th scope="col"><?php esc_html_e( 'Post', 'igit-related-posts-with-thumb-images-after-posts' ); ?></th>
							<?php if ( '' === $active_source ) : ?>
							<th scope="col"><?php esc_html_e( 'Source', 'igit-related-posts-with-thumb-images-after-posts' ); ?></th>
							<?php endif; ?>
							<th scope="col"><?php esc_html_e( 'Clicks', 'igit-related-posts-with-thumb-images-after-posts' ); ?></th>
							<th scope="col"><?php esc_html_e( 'Share', 'igit-related-posts-with-thumb-images-after-posts' ); ?></th>
						</tr>
					</thead>
					<tbody>
						<?php foreach ( $top_posts as $i => $row ) :
							$pid    = absint( $row['target_post_id'] );
							$clicks = absint( $row['total_clicks'] );
							$post   = get_post( $pid );
							if ( ! $post ) {
								continue;
							}
							$pct       = $max_clicks > 0 ? round( ( $clicks / $max_clicks ) * 100 ) : 0;
							$pt_obj    = get_post_type_object( $post->post_type );
							$type_name = $pt_obj ? $pt_obj->labels->singular_name : $post->post_type;
							$src_val   = isset( $row['click_source'] ) ? $row['click_source'] : '';
						?>
						<tr>
							<td class="igit-rpwt-rank"><?php echo esc_html( $i + 1 ); ?></td>
							<td class="igit-rpwt-post-cell">
								<?php $thumb = get_the_post_thumbnail( $pid, array( 36, 36 ) );
								if ( $thumb ) : ?>
									<span class="igit-rpwt-ath"><?php echo $thumb; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span>
								<?php endif; ?>
								<span class="igit-rpwt-post-info">
									<a href="<?php echo esc_url( get_edit_post_link( $pid ) ); ?>" class="igit-rpwt-post-title"><?php echo esc_html( get_the_title( $pid ) ); ?></a>
									<span class="igit-rpwt-post-type"><?php echo esc_html( $type_name ); ?></span>
								</span>
							</td>
							<?php if ( '' === $active_source ) : ?>
							<td class="igit-rpwt-source-cell">
								<?php if ( $src_val ) : ?>
								<span class="igit-rpwt-source-badge igit-rpwt-source-badge--<?php echo esc_attr( $src_val ); ?>">
									<?php echo 'nudge' === $src_val ? esc_html__( 'Nudge', 'igit-related-posts-with-thumb-images-after-posts' ) : esc_html__( 'Widget', 'igit-related-posts-with-thumb-images-after-posts' ); ?>
								</span>
								<?php endif; ?>
							</td>
							<?php endif; ?>
							<td class="igit-rpwt-click-count"><strong><?php echo esc_html( number_format_i18n( $clicks ) ); ?></strong></td>
							<td class="igit-rpwt-bar-cell">
								<span class="igit-rpwt-inline-bar<?php echo 'nudge' === $src_val ? ' igit-rpwt-inline-bar--nudge' : ''; ?>" style="width:<?php echo esc_attr( $pct ); ?>%"></span>
							</td>
						</tr>
						<?php endforeach; ?>
					</tbody>
				</table>
				<?php endif; ?>
			</div>

		</div><!-- .igit-rpwt-analytics-tab-content -->
		<?php
	}

	public function render_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have permission to access this page.', 'igit-related-posts-with-thumb-images-after-posts' ) );
		}

		if ( ! IGIT_RPWT_Settings::get( 'enable_click_tracking' ) ) {
			?>
			<div class="wrap">
				<h1><?php esc_html_e( 'Related Posts Analytics', 'igit-related-posts-with-thumb-images-after-posts' ); ?></h1>
				<div class="igit-rpwt-analytics-notice">
					<p><?php esc_html_e( 'Click tracking is currently disabled. Enable it in Settings to start collecting data.', 'igit-related-posts-with-thumb-images-after-posts' ); ?></p>
					<a href="<?php echo esc_url( admin_url( 'admin.php?page=igit-rpwt' ) ); ?>" class="button button-primary">
						<?php esc_html_e( 'Go to Settings', 'igit-related-posts-with-thumb-images-after-posts' ); ?>
					</a>
				</div>
			</div>
			<?php
			return;
		}

		// ── Source filter from URL param ──────────────────────────────────────
		$active_source = isset( $_GET['click_source'] ) ? sanitize_key( $_GET['click_source'] ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( ! in_array( $active_source, array( 'widget', 'nudge' ), true ) ) {
			$active_source = '';
		}

		$days         = 30;
		$top_posts    = IGIT_RPWT_Analytics::get_top_posts( $days, 20, $active_source );
		$all_time     = IGIT_RPWT_Analytics::get_total_clicks( 0, $active_source );
		$last30       = IGIT_RPWT_Analytics::get_total_clicks( $days, $active_source );
		$unique_posts = count( IGIT_RPWT_Analytics::get_top_posts( 0, 9999, $active_source ) );
		$by_source    = IGIT_RPWT_Analytics::get_clicks_by_source( $days );

		if ( '' === $active_source ) {
			$daily     = IGIT_RPWT_Analytics::get_daily_totals_by_source( $days );
			$max_daily = 1;
			foreach ( $daily as $row ) {
				$day_total = $row['widget_total'] + $row['nudge_total'];
				if ( $day_total > $max_daily ) {
					$max_daily = $day_total;
				}
			}
		} else {
			$daily     = IGIT_RPWT_Analytics::get_daily_totals( $days, $active_source );
			$max_daily = $daily ? (int) max( array_column( $daily, 'daily_total' ) ) : 1;
		}

		$max_clicks = $top_posts ? (int) max( array_column( $top_posts, 'total_clicks' ) ) : 1;

		$base_url    = admin_url( 'admin.php?page=' . self::PAGE_SLUG );
		?>
		<div class="wrap igit-rpwt-analytics-wrap">

			<h1 class="igit-rpwt-analytics-title">
				<?php esc_html_e( 'Related Posts Analytics', 'igit-related-posts-with-thumb-images-after-posts' ); ?>
				<span class="igit-rpwt-analytics-period"><?php esc_html_e( 'Last 30 days', 'igit-related-posts-with-thumb-images-after-posts' ); ?></span>
			</h1>

			<!-- ── Source filter tabs ──────────────────────────────────── -->
			<div class="igit-rpwt-source-tabs">
				<a href="<?php echo esc_url( $base_url ); ?>" class="igit-rpwt-source-tab<?php echo '' === $active_source ? ' is-active' : ''; ?>">
					<?php esc_html_e( 'All Sources', 'igit-related-posts-with-thumb-images-after-posts' ); ?>
				</a>
				<a href="<?php echo esc_url( add_query_arg( 'click_source', 'widget', $base_url ) ); ?>" class="igit-rpwt-source-tab<?php echo 'widget' === $active_source ? ' is-active' : ''; ?>">
					<?php esc_html_e( 'Related Posts', 'igit-related-posts-with-thumb-images-after-posts' ); ?>
				</a>
				<a href="<?php echo esc_url( add_query_arg( 'click_source', 'nudge', $base_url ) ); ?>" class="igit-rpwt-source-tab<?php echo 'nudge' === $active_source ? ' is-active' : ''; ?>">
					<?php esc_html_e( 'Post Nudges', 'igit-related-posts-with-thumb-images-after-posts' ); ?>
				</a>
			</div>

			<!-- ── Summary cards ───────────────────────────────────────── -->
			<div class="igit-rpwt-stat-cards">
				<div class="igit-rpwt-stat-card">
					<div class="igit-rpwt-stat-value"><?php echo esc_html( number_format_i18n( $last30 ) ); ?></div>
					<div class="igit-rpwt-stat-label"><?php esc_html_e( 'Clicks (last 30 days)', 'igit-related-posts-with-thumb-images-after-posts' ); ?></div>
				</div>
				<div class="igit-rpwt-stat-card">
					<div class="igit-rpwt-stat-value"><?php echo esc_html( number_format_i18n( $all_time ) ); ?></div>
					<div class="igit-rpwt-stat-label"><?php esc_html_e( 'Total Clicks (all time)', 'igit-related-posts-with-thumb-images-after-posts' ); ?></div>
				</div>
				<div class="igit-rpwt-stat-card">
					<div class="igit-rpwt-stat-value"><?php echo esc_html( number_format_i18n( $unique_posts ) ); ?></div>
					<div class="igit-rpwt-stat-label"><?php esc_html_e( 'Posts Clicked (all time)', 'igit-related-posts-with-thumb-images-after-posts' ); ?></div>
				</div>
				<?php if ( '' === $active_source ) : ?>
				<div class="igit-rpwt-stat-card igit-rpwt-stat-card--widget">
					<div class="igit-rpwt-stat-value"><?php echo esc_html( number_format_i18n( $by_source['widget'] ) ); ?></div>
					<div class="igit-rpwt-stat-label"><?php esc_html_e( 'Widget Clicks (last 30d)', 'igit-related-posts-with-thumb-images-after-posts' ); ?></div>
				</div>
				<div class="igit-rpwt-stat-card igit-rpwt-stat-card--nudge">
					<div class="igit-rpwt-stat-value"><?php echo esc_html( number_format_i18n( $by_source['nudge'] ) ); ?></div>
					<div class="igit-rpwt-stat-label"><?php esc_html_e( 'Nudge Clicks (last 30d)', 'igit-related-posts-with-thumb-images-after-posts' ); ?></div>
				</div>
				<?php endif; ?>
			</div>

			<?php if ( $daily ) : ?>
			<!-- ── Activity chart ──────────────────────────────────────── -->
			<div class="igit-rpwt-chart-card">
				<h2>
					<?php esc_html_e( 'Click Activity', 'igit-related-posts-with-thumb-images-after-posts' ); ?>
					<?php if ( '' === $active_source ) : ?>
					<span class="igit-rpwt-chart-legend">
						<span class="igit-rpwt-legend-dot igit-rpwt-legend-dot--widget"></span><?php esc_html_e( 'Widget', 'igit-related-posts-with-thumb-images-after-posts' ); ?>
						<span class="igit-rpwt-legend-dot igit-rpwt-legend-dot--nudge"></span><?php esc_html_e( 'Nudge', 'igit-related-posts-with-thumb-images-after-posts' ); ?>
					</span>
					<?php endif; ?>
				</h2>
				<div class="igit-rpwt-bar-chart" role="img" aria-label="<?php esc_attr_e( 'Daily click activity over the last 30 days', 'igit-related-posts-with-thumb-images-after-posts' ); ?>">
					<?php
					if ( '' === $active_source ) {
						$daily_map = array();
						foreach ( $daily as $row ) {
							$daily_map[ $row['click_date'] ] = $row;
						}
						for ( $i = $days - 1; $i >= 0; $i-- ) {
							$date         = wp_date( 'Y-m-d', strtotime( "-{$i} days" ) );
							$widget_count = isset( $daily_map[ $date ] ) ? (int) $daily_map[ $date ]['widget_total'] : 0;
							$nudge_count  = isset( $daily_map[ $date ] ) ? (int) $daily_map[ $date ]['nudge_total']  : 0;
							$total        = $widget_count + $nudge_count;
							$widget_pct   = $max_daily > 0 ? round( ( $widget_count / $max_daily ) * 100 ) : 0;
							$nudge_pct    = $max_daily > 0 ? round( ( $nudge_count / $max_daily ) * 100 ) : 0;
							?>
							<span class="igit-rpwt-bar-wrap igit-rpwt-bar-wrap--dual" title="<?php echo esc_attr( $date . ': ' . $total . ' (' . $widget_count . ' widget + ' . $nudge_count . ' nudge)' ); ?>">
								<span class="igit-rpwt-bar igit-rpwt-bar--nudge" style="height:<?php echo esc_attr( max( $nudge_pct > 0 ? 2 : 0, $nudge_pct ) ); ?>%"></span>
								<span class="igit-rpwt-bar igit-rpwt-bar--widget" style="height:<?php echo esc_attr( max( $widget_pct > 0 ? 2 : 0, $widget_pct ) ); ?>%"></span>
							</span>
							<?php
						}
					} else {
						$daily_map = array();
						foreach ( $daily as $row ) {
							$daily_map[ $row['click_date'] ] = (int) $row['daily_total'];
						}
						$bar_class = 'widget' === $active_source ? 'igit-rpwt-bar igit-rpwt-bar--widget' : 'igit-rpwt-bar igit-rpwt-bar--nudge';
						for ( $i = $days - 1; $i >= 0; $i-- ) {
							$date  = wp_date( 'Y-m-d', strtotime( "-{$i} days" ) );
							$count = isset( $daily_map[ $date ] ) ? $daily_map[ $date ] : 0;
							$pct   = $max_daily > 0 ? round( ( $count / $max_daily ) * 100 ) : 0;
							?>
							<span class="igit-rpwt-bar-wrap" title="<?php echo esc_attr( $date . ': ' . $count ); ?>">
								<span class="<?php echo esc_attr( $bar_class ); ?>" style="height:<?php echo esc_attr( max( 2, $pct ) ); ?>%"></span>
							</span>
							<?php
						}
					}
					?>
				</div>
				<div class="igit-rpwt-chart-labels">
					<span><?php echo esc_html( wp_date( get_option( 'date_format' ), strtotime( '-29 days' ) ) ); ?></span>
					<span><?php esc_html_e( 'Today', 'igit-related-posts-with-thumb-images-after-posts' ); ?></span>
				</div>
			</div>
			<?php endif; ?>

			<!-- ── Top posts table ─────────────────────────────────────── -->
			<div class="igit-rpwt-analytics-table-card">
				<h2><?php esc_html_e( 'Most Clicked Related Posts', 'igit-related-posts-with-thumb-images-after-posts' ); ?></h2>

				<?php if ( empty( $top_posts ) ) : ?>
					<p class="igit-rpwt-no-data"><?php esc_html_e( 'No click data yet. Visitors need to view posts that display a related posts block.', 'igit-related-posts-with-thumb-images-after-posts' ); ?></p>
				<?php else : ?>
				<table class="widefat striped igit-rpwt-analytics-table">
					<thead>
						<tr>
							<th scope="col"><?php esc_html_e( '#', 'igit-related-posts-with-thumb-images-after-posts' ); ?></th>
							<th scope="col"><?php esc_html_e( 'Post', 'igit-related-posts-with-thumb-images-after-posts' ); ?></th>
							<?php if ( '' === $active_source ) : ?>
							<th scope="col"><?php esc_html_e( 'Source', 'igit-related-posts-with-thumb-images-after-posts' ); ?></th>
							<?php endif; ?>
							<th scope="col"><?php esc_html_e( 'Clicks', 'igit-related-posts-with-thumb-images-after-posts' ); ?></th>
							<th scope="col"><?php esc_html_e( 'Share', 'igit-related-posts-with-thumb-images-after-posts' ); ?></th>
						</tr>
					</thead>
					<tbody>
						<?php foreach ( $top_posts as $i => $row ) :
							$pid    = absint( $row['target_post_id'] );
							$clicks = absint( $row['total_clicks'] );
							$post   = get_post( $pid );
							if ( ! $post ) {
								continue;
							}
							$pct       = $max_clicks > 0 ? round( ( $clicks / $max_clicks ) * 100 ) : 0;
							$pt_obj    = get_post_type_object( $post->post_type );
							$type_name = $pt_obj ? $pt_obj->labels->singular_name : $post->post_type;
							$src_val   = isset( $row['click_source'] ) ? $row['click_source'] : '';
						?>
						<tr>
							<td class="igit-rpwt-rank"><?php echo esc_html( $i + 1 ); ?></td>
							<td class="igit-rpwt-post-cell">
								<?php $thumb = get_the_post_thumbnail( $pid, array( 36, 36 ) );
								if ( $thumb ) : ?>
									<span class="igit-rpwt-ath"><?php echo $thumb; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span>
								<?php endif; ?>
								<span class="igit-rpwt-post-info">
									<a href="<?php echo esc_url( get_edit_post_link( $pid ) ); ?>" class="igit-rpwt-post-title"><?php echo esc_html( get_the_title( $pid ) ); ?></a>
									<span class="igit-rpwt-post-type"><?php echo esc_html( $type_name ); ?></span>
								</span>
							</td>
							<?php if ( '' === $active_source ) : ?>
							<td class="igit-rpwt-source-cell">
								<?php if ( $src_val ) : ?>
								<span class="igit-rpwt-source-badge igit-rpwt-source-badge--<?php echo esc_attr( $src_val ); ?>">
									<?php echo 'nudge' === $src_val ? esc_html__( 'Nudge', 'igit-related-posts-with-thumb-images-after-posts' ) : esc_html__( 'Widget', 'igit-related-posts-with-thumb-images-after-posts' ); ?>
								</span>
								<?php endif; ?>
							</td>
							<?php endif; ?>
							<td class="igit-rpwt-click-count"><strong><?php echo esc_html( number_format_i18n( $clicks ) ); ?></strong></td>
							<td class="igit-rpwt-bar-cell">
								<span class="igit-rpwt-inline-bar<?php echo 'nudge' === $src_val ? ' igit-rpwt-inline-bar--nudge' : ''; ?>" style="width:<?php echo esc_attr( $pct ); ?>%"></span>
							</td>
						</tr>
						<?php endforeach; ?>
					</tbody>
				</table>
				<?php endif; ?>
			</div>

		</div>
		<?php
	}

	// ── Dashboard widget ─────────────────────────────────────────────────────

	public function register_dashboard_widget() {
		if ( ! IGIT_RPWT_Settings::get( 'enable_click_tracking' ) ) {
			return;
		}
		wp_add_dashboard_widget(
			'igit_rpwt_analytics',
			__( 'Related Posts – Top Clicked', 'igit-related-posts-with-thumb-images-after-posts' ),
			array( $this, 'render_dashboard_widget' )
		);
	}

	public function render_dashboard_widget() {
		$top       = IGIT_RPWT_Analytics::get_top_posts( 30, 5 );
		$total     = IGIT_RPWT_Analytics::get_total_clicks( 30 );
		$by_source = IGIT_RPWT_Analytics::get_clicks_by_source( 30 );

		if ( empty( $top ) ) {
			echo '<p>' . esc_html__( 'No click data in the last 30 days.', 'igit-related-posts-with-thumb-images-after-posts' ) . '</p>';
			printf(
				'<p><a href="%s">%s</a></p>',
				esc_url( admin_url( 'options-general.php?page=igit-rpwt' ) ),
				esc_html__( 'Enable Click Tracking in Settings', 'igit-related-posts-with-thumb-images-after-posts' )
			);
			return;
		}

		$max = (int) max( array_column( $top, 'total_clicks' ) );

		echo '<p class="igit-rpwt-widget-total">';
		printf(
			/* translators: %s = formatted number of clicks */
			esc_html__( '%s clicks in the last 30 days', 'igit-related-posts-with-thumb-images-after-posts' ),
			'<strong>' . esc_html( number_format_i18n( $total ) ) . '</strong>'
		);
		echo '</p>';

		echo '<p class="igit-rpwt-widget-breakdown">';
		echo '<span class="igit-rpwt-source-badge igit-rpwt-source-badge--widget">' . esc_html__( 'Widget', 'igit-related-posts-with-thumb-images-after-posts' ) . '</span> ';
		echo esc_html( number_format_i18n( $by_source['widget'] ) );
		echo ' &nbsp; ';
		echo '<span class="igit-rpwt-source-badge igit-rpwt-source-badge--nudge">' . esc_html__( 'Nudge', 'igit-related-posts-with-thumb-images-after-posts' ) . '</span> ';
		echo esc_html( number_format_i18n( $by_source['nudge'] ) );
		echo '</p>';

		echo '<ol class="igit-rpwt-widget-list">';
		foreach ( $top as $row ) {
			$pid    = absint( $row['target_post_id'] );
			$clicks = absint( $row['total_clicks'] );
			$title  = get_the_title( $pid );
			if ( ! $title ) {
				continue;
			}
			$pct = $max > 0 ? round( ( $clicks / $max ) * 100 ) : 0;
			echo '<li class="igit-rpwt-widget-item">';
			printf(
				'<span class="igit-rpwt-widget-title"><a href="%s">%s</a></span>',
				esc_url( get_permalink( $pid ) ),
				esc_html( $title )
			);
			echo '<span class="igit-rpwt-widget-bar-wrap"><span class="igit-rpwt-widget-bar" style="width:' . esc_attr( $pct ) . '%"></span></span>';
			echo '<span class="igit-rpwt-widget-count">' . esc_html( number_format_i18n( $clicks ) ) . '</span>';
			echo '</li>';
		}
		echo '</ol>';

		printf(
			'<p class="igit-rpwt-widget-footer"><a href="%s">%s &rarr;</a></p>',
			esc_url( admin_url( 'admin.php?page=' . self::PAGE_SLUG ) ),
			esc_html__( 'View full analytics', 'igit-related-posts-with-thumb-images-after-posts' )
		);
	}
}
