<?php
/**
 * Statistics admin page.
 *
 * @package Relatedly
 * @since   2.0.0
 * @since   2.3.0 Split basic free stats from premium advanced reporting.
 *
 * @var bool   $is_premium       Whether advanced statistics are available.
 * @var bool   $tracking_enabled Whether click and impression tracking is enabled.
 * @var array  $summary_30       Summary statistics for the last 30 days.
 * @var array  $summary_7        Summary statistics for the last 7 days.
 * @var array  $top_posts        Top clicked posts.
 * @var array  $top_sources      Top source posts.
 * @var array  $daily            Daily click and impression counts.
 * @var int    $total_rows       Number of stored tracking rows.
 * @var string $export_url       CSV export URL for premium users.
 * @var string $start_date_30    Default start date for the current period.
 * @var string $start_date_7     Default start date for the short period.
 * @var string $start_date_60    Default start date for the prior comparison period.
 * @var string $start_date_31    Default end date for the prior comparison period.
 * @var string $end_date         Default end date.
 */

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
defined( 'ABSPATH' ) || exit;

use Relatedly\Premium\LicenseManager;

$summary_30      = is_array( $summary_30 ) ? $summary_30 : [];
$summary_7       = is_array( $summary_7 ) ? $summary_7 : [];
$top_posts       = is_array( $top_posts ) ? $top_posts : [];
$top_sources     = is_array( $top_sources ) ? $top_sources : [];
$daily           = is_array( $daily ) ? $daily : [];
$upgrade_url     = LicenseManager::checkout_url();
$settings_url    = admin_url( 'admin.php?page=relatedly&tab=general' );
$total_clicks    = (int) ( $summary_30['total_clicks'] ?? 0 );
$total_views     = (int) ( $summary_30['total_impressions'] ?? 0 );
$overall_ctr     = (float) ( $summary_30['ctr'] ?? 0 );
$short_clicks    = (int) ( $summary_7['total_clicks'] ?? 0 );
$short_views     = (int) ( $summary_7['total_impressions'] ?? 0 );
$short_ctr       = (float) ( $summary_7['ctr'] ?? 0 );
$breakdown       = isset( $summary_30['breakdown'] ) && is_array( $summary_30['breakdown'] ) ? $summary_30['breakdown'] : [];
$inline_ctr      = (float) ( $breakdown['inline']['ctr'] ?? 0 );
$end_content_ctr = (float) ( $breakdown['end_content']['ctr'] ?? 0 );
$floating_ctr    = (float) ( $breakdown['floating']['ctr'] ?? 0 );
?>
<div class="wrap relatedly-statistics-wrap">
	<h1><?php echo esc_html( get_admin_page_title() ); ?></h1>

	<?php if ( ! $tracking_enabled ) : ?>
		<div class="notice notice-warning">
			<p>
				<?php esc_html_e( 'Relatedly Stats are turned off, so no new clicks or views are being recorded.', 'relatedly' ); ?>
				<a href="<?php echo esc_url( $settings_url ); ?>"><?php esc_html_e( 'Turn stats on in General Settings.', 'relatedly' ); ?></a>
			</p>
		</div>
	<?php endif; ?>

	<?php if ( ! $is_premium ) : ?>
		<div class="relatedly-stats-toolbar">
			<strong><?php esc_html_e( 'Basic stats for the last 30 days', 'relatedly' ); ?></strong>
			<span class="relatedly-stats-sep">|</span>
			<span><?php esc_html_e( 'Upgrade for filters, charts, CSV export, comparisons, and per-post analytics.', 'relatedly' ); ?></span>
			<a class="button button-primary" href="<?php echo esc_url( $upgrade_url ); ?>" target="_blank" rel="noopener noreferrer">
				<?php esc_html_e( 'View Plans', 'relatedly' ); ?>
			</a>
		</div>
	<?php else : ?>
		<div class="relatedly-stats-toolbar">
			<label class="relatedly-stats-label" for="relatedly-start-date"><?php esc_html_e( 'From', 'relatedly' ); ?></label>
			<input type="text" id="relatedly-start-date" class="relatedly-date-input" value="<?php echo esc_attr( $start_date_30 ); ?>">
			<label class="relatedly-stats-label" for="relatedly-end-date"><?php esc_html_e( 'To', 'relatedly' ); ?></label>
			<input type="text" id="relatedly-end-date" class="relatedly-date-input" value="<?php echo esc_attr( $end_date ); ?>">
			<button type="button" class="button button-primary" id="relatedly-apply-date-filter"><?php esc_html_e( 'Apply', 'relatedly' ); ?></button>
			<button type="button" class="button" id="relatedly-reset-date-filter"><?php esc_html_e( 'Reset', 'relatedly' ); ?></button>
			<?php if ( '' !== $export_url ) : ?>
				<a class="button" id="relatedly-export-csv" href="<?php echo esc_url( $export_url ); ?>"><?php esc_html_e( 'Export CSV', 'relatedly' ); ?></a>
			<?php endif; ?>
			<span id="relatedly-stats-loading" class="spinner relatedly-inline-spinner relatedly-is-hidden" aria-hidden="true"></span>
		</div>
	<?php endif; ?>

	<div class="relatedly-kpi-grid">
		<div class="relatedly-kpi-card">
			<span class="relatedly-kpi-label"><?php esc_html_e( 'Clicks', 'relatedly' ); ?></span>
			<span class="relatedly-kpi-value" id="relatedly-total-clicks"><?php echo esc_html( number_format_i18n( $total_clicks ) ); ?></span>
		</div>
		<div class="relatedly-kpi-card">
			<span class="relatedly-kpi-label"><?php esc_html_e( 'Views', 'relatedly' ); ?></span>
			<span class="relatedly-kpi-value" id="relatedly-total-impressions"><?php echo esc_html( number_format_i18n( $total_views ) ); ?></span>
		</div>
		<div class="relatedly-kpi-card">
			<span class="relatedly-kpi-label"><?php esc_html_e( 'Click Rate', 'relatedly' ); ?></span>
			<span class="relatedly-kpi-value" id="relatedly-ctr"><?php echo esc_html( $overall_ctr . '%' ); ?></span>
		</div>
		<div class="relatedly-kpi-card">
			<span class="relatedly-kpi-label"><?php esc_html_e( 'Inline Click Rate', 'relatedly' ); ?></span>
			<span class="relatedly-kpi-value" id="relatedly-inline-ctr"><?php echo esc_html( $inline_ctr . '%' ); ?></span>
		</div>
		<div class="relatedly-kpi-card">
			<span class="relatedly-kpi-label"><?php esc_html_e( 'End of Post Click Rate', 'relatedly' ); ?></span>
			<span class="relatedly-kpi-value" id="relatedly-end-content-ctr"><?php echo esc_html( $end_content_ctr . '%' ); ?></span>
		</div>
		<div class="relatedly-kpi-card">
			<span class="relatedly-kpi-label"><?php esc_html_e( 'Floating Click Rate', 'relatedly' ); ?></span>
			<span class="relatedly-kpi-value" id="relatedly-floating-ctr"><?php echo esc_html( $floating_ctr . '%' ); ?></span>
		</div>
	</div>

	<?php if ( ! $is_premium ) : ?>
		<div class="relatedly-tables-grid">
			<div class="relatedly-table-card">
				<h2><?php esc_html_e( 'Top Clicked Posts', 'relatedly' ); ?></h2>
				<?php if ( ! empty( $top_posts ) ) : ?>
					<table class="widefat striped">
						<thead>
							<tr>
								<th><?php esc_html_e( 'Post', 'relatedly' ); ?></th>
								<th class="relatedly-num"><?php esc_html_e( 'Clicks', 'relatedly' ); ?></th>
								<th class="relatedly-num"><?php esc_html_e( 'Views', 'relatedly' ); ?></th>
								<th class="relatedly-num"><?php esc_html_e( 'Click Rate', 'relatedly' ); ?></th>
							</tr>
						</thead>
						<tbody>
							<?php foreach ( $top_posts as $post_row ) : ?>
								<tr>
									<td><?php echo esc_html( $post_row['title'] ); ?></td>
									<td class="relatedly-num"><?php echo esc_html( number_format_i18n( (int) $post_row['clicks'] ) ); ?></td>
									<td class="relatedly-num"><?php echo esc_html( number_format_i18n( (int) $post_row['impressions'] ) ); ?></td>
									<td class="relatedly-num"><?php echo esc_html( $post_row['ctr'] . '%' ); ?></td>
								</tr>
							<?php endforeach; ?>
						</tbody>
					</table>
				<?php else : ?>
					<p><?php esc_html_e( 'No clicks have been recorded for this period yet.', 'relatedly' ); ?></p>
				<?php endif; ?>
			</div>

			<div class="relatedly-table-card">
				<h2><?php esc_html_e( 'Last 7 Days', 'relatedly' ); ?></h2>
				<table class="widefat striped">
					<tbody>
						<tr>
							<th><?php esc_html_e( 'Clicks', 'relatedly' ); ?></th>
							<td class="relatedly-num"><?php echo esc_html( number_format_i18n( $short_clicks ) ); ?></td>
						</tr>
						<tr>
							<th><?php esc_html_e( 'Views', 'relatedly' ); ?></th>
							<td class="relatedly-num"><?php echo esc_html( number_format_i18n( $short_views ) ); ?></td>
						</tr>
						<tr>
							<th><?php esc_html_e( 'Click Rate', 'relatedly' ); ?></th>
							<td class="relatedly-num"><?php echo esc_html( $short_ctr . '%' ); ?></td>
						</tr>
					</tbody>
				</table>
			</div>
		</div>

		<div class="relatedly-comparison-card">
			<h2><?php esc_html_e( 'Advanced Reports', 'relatedly' ); ?></h2>
			<p><?php esc_html_e( 'Paid plans add custom date ranges, trend charts, top source posts, CSV export, period comparison, and per-post analytics.', 'relatedly' ); ?></p>
			<p>
				<a class="button button-primary" href="<?php echo esc_url( $upgrade_url ); ?>" target="_blank" rel="noopener noreferrer">
					<?php esc_html_e( 'Upgrade for Advanced Reports', 'relatedly' ); ?>
				</a>
			</p>
		</div>
	<?php else : ?>
		<div class="relatedly-chart-grid">
			<div class="relatedly-chart-card">
				<h2><?php esc_html_e( 'Clicks and Views', 'relatedly' ); ?></h2>
				<div class="relatedly-chart-canvas-wrap">
					<canvas id="relatedly-chart"></canvas>
				</div>
			</div>
			<div class="relatedly-chart-card">
				<h2><?php esc_html_e( 'Click Rate Trend', 'relatedly' ); ?></h2>
				<div class="relatedly-chart-canvas-wrap">
					<canvas id="relatedly-ctr-chart"></canvas>
				</div>
			</div>
		</div>

		<div class="relatedly-tables-grid">
			<div class="relatedly-table-card">
				<h2><?php esc_html_e( 'Top Clicked Posts', 'relatedly' ); ?></h2>
				<table class="widefat striped" id="relatedly-top-posts-table">
					<thead>
						<tr>
							<th><?php esc_html_e( 'Post', 'relatedly' ); ?></th>
							<th class="relatedly-num"><?php esc_html_e( 'Clicks', 'relatedly' ); ?></th>
							<th class="relatedly-num"><?php esc_html_e( 'Views', 'relatedly' ); ?></th>
							<th class="relatedly-num"><?php esc_html_e( 'Click Rate', 'relatedly' ); ?></th>
							<th><?php esc_html_e( 'Details', 'relatedly' ); ?></th>
						</tr>
					</thead>
					<tbody>
						<?php foreach ( $top_posts as $post_row ) : ?>
							<tr>
								<td><?php echo esc_html( $post_row['title'] ); ?></td>
								<td class="relatedly-num"><?php echo esc_html( number_format_i18n( (int) $post_row['clicks'] ) ); ?></td>
								<td class="relatedly-num"><?php echo esc_html( number_format_i18n( (int) $post_row['impressions'] ) ); ?></td>
								<td class="relatedly-num"><?php echo esc_html( $post_row['ctr'] . '%' ); ?></td>
								<td><button type="button" class="button button-small relatedly-view-post-analytics" data-post-id="<?php echo esc_attr( (string) $post_row['post_id'] ); ?>"><?php esc_html_e( 'View', 'relatedly' ); ?></button></td>
							</tr>
						<?php endforeach; ?>
					</tbody>
				</table>
			</div>

			<div class="relatedly-table-card">
				<h2><?php esc_html_e( 'Top Source Posts', 'relatedly' ); ?></h2>
				<table class="widefat striped" id="relatedly-top-sources-table">
					<thead>
						<tr>
							<th><?php esc_html_e( 'Post', 'relatedly' ); ?></th>
							<th class="relatedly-num"><?php esc_html_e( 'Clicks', 'relatedly' ); ?></th>
							<th class="relatedly-num"><?php esc_html_e( 'Views', 'relatedly' ); ?></th>
							<th class="relatedly-num"><?php esc_html_e( 'Click Rate', 'relatedly' ); ?></th>
							<th><?php esc_html_e( 'Details', 'relatedly' ); ?></th>
						</tr>
					</thead>
					<tbody>
						<?php foreach ( $top_sources as $post_row ) : ?>
							<tr>
								<td><?php echo esc_html( $post_row['title'] ); ?></td>
								<td class="relatedly-num"><?php echo esc_html( number_format_i18n( (int) $post_row['clicks'] ) ); ?></td>
								<td class="relatedly-num"><?php echo esc_html( number_format_i18n( (int) $post_row['impressions'] ) ); ?></td>
								<td class="relatedly-num"><?php echo esc_html( $post_row['ctr'] . '%' ); ?></td>
								<td><button type="button" class="button button-small relatedly-view-post-analytics" data-post-id="<?php echo esc_attr( (string) $post_row['post_id'] ); ?>"><?php esc_html_e( 'View', 'relatedly' ); ?></button></td>
							</tr>
						<?php endforeach; ?>
					</tbody>
				</table>
			</div>
		</div>

		<div class="relatedly-comparison-card">
			<h2><?php esc_html_e( 'Compare Periods', 'relatedly' ); ?></h2>
			<div class="relatedly-comparison-fields">
				<div class="relatedly-comparison-group">
					<label for="relatedly-period1-start"><?php esc_html_e( 'Previous', 'relatedly' ); ?></label>
					<input type="text" id="relatedly-period1-start" value="<?php echo esc_attr( $start_date_60 ); ?>">
					<span><?php esc_html_e( 'to', 'relatedly' ); ?></span>
					<input type="text" id="relatedly-period1-end" value="<?php echo esc_attr( $start_date_31 ); ?>">
				</div>
				<div class="relatedly-comparison-group">
					<label for="relatedly-period2-start"><?php esc_html_e( 'Current', 'relatedly' ); ?></label>
					<input type="text" id="relatedly-period2-start" value="<?php echo esc_attr( $start_date_30 ); ?>">
					<span><?php esc_html_e( 'to', 'relatedly' ); ?></span>
					<input type="text" id="relatedly-period2-end" value="<?php echo esc_attr( $end_date ); ?>">
				</div>
				<button type="button" class="button button-primary" id="relatedly-compare-periods"><?php esc_html_e( 'Compare', 'relatedly' ); ?></button>
			</div>
			<div id="relatedly-comparison-results" class="relatedly-comparison-results relatedly-is-hidden"></div>
		</div>

		<div id="relatedly-post-analytics-modal" class="relatedly-modal" role="dialog" aria-modal="true" aria-labelledby="relatedly-post-analytics-title">
			<div class="relatedly-modal-dialog">
				<div class="relatedly-modal-header">
					<h2 id="relatedly-post-analytics-title"><?php esc_html_e( 'Post Analytics', 'relatedly' ); ?></h2>
					<button type="button" class="button button-small" id="relatedly-close-analytics-modal"><?php esc_html_e( 'Close', 'relatedly' ); ?></button>
				</div>
				<div class="relatedly-modal-body" id="relatedly-post-analytics-content"></div>
			</div>
		</div>
	<?php endif; ?>

	<p class="description">
		<?php
		printf(
			/* translators: %s: number of stored tracking rows. */
			esc_html__( 'Stored tracking rows: %s', 'relatedly' ),
			esc_html( number_format_i18n( $total_rows ) )
		);
		?>
	</p>
</div>
