<?php
/**
 * Admin dashboard view for AR analytics.
 *
 * @var array $summary
 * @var array $plugins
 * @var array $config
 * @var int   $range_days
 * @var string|null $plugin_scope
 *
 * @package ARForWordPress
 */

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

$domain = isset( $config['text_domain'] ) ? $config['text_domain'] : 'ar-for-wordpress';

$counts          = isset( $summary['counts'] ) ? $summary['counts'] : array();
$daily_series    = isset( $summary['daily_series'] ) ? $summary['daily_series'] : array();
$device_breakdown = isset( $summary['device_breakdown'] ) ? $summary['device_breakdown'] : array();
$top_models      = isset( $summary['top_models'] ) ? $summary['top_models'] : array();
$top_pages       = isset( $summary['top_pages'] ) ? $summary['top_pages'] : array();
$recent_events   = isset( $summary['recent_events'] ) ? $summary['recent_events'] : array();

$counts = wp_parse_args(
	$counts,
	array(
		'total'          => 0,
		'viewer_load'    => 0,
		'ar_launch'      => 0,
		'variant_change' => 0,
	)
);

$current_url = admin_url( 'admin.php' );

$range_options = array(
	7  => __( 'Last 7 days', $domain ),
	14 => __( 'Last 14 days', $domain ),
	30 => __( 'Last 30 days', $domain ),
	60 => __( 'Last 60 days', $domain ),
);

$max_daily = 0;
foreach ( $daily_series as $day ) {
	$max_daily = max( $max_daily, (int) $day['count'] );
}
$max_daily = max( 1, $max_daily );

?>
<div class="wrap ar-analytics-wrap">
	<h1><?php echo esc_html__( 'AR Insights Dashboard', $domain ); ?></h1>

	<form method="get" class="ar-analytics-filters">
		<input type="hidden" name="page" value="<?php echo esc_attr( $config['menu_slug'] ); ?>">

		<label for="ar-analytics-plugin" class="screen-reader-text"><?php esc_html_e( 'Plugin scope', $domain ); ?></label>
		<select id="ar-analytics-plugin" name="plugin_id" onchange="this.form.submit()">
			<option value=""><?php esc_html_e( 'All plugins', $domain ); ?></option>
			<?php foreach ( $plugins as $id => $plugin_config ) : ?>
				<option value="<?php echo esc_attr( $id ); ?>" <?php selected( $plugin_scope, $id ); ?>>
					<?php echo esc_html( $plugin_config['plugin_name'] ? $plugin_config['plugin_name'] : $id ); ?>
				</option>
			<?php endforeach; ?>
		</select>

		<label for="ar-analytics-range" class="screen-reader-text"><?php esc_html_e( 'Date range', $domain ); ?></label>
		<select id="ar-analytics-range" name="range" onchange="this.form.submit()">
			<?php foreach ( $range_options as $value => $label ) : ?>
				<option value="<?php echo esc_attr( $value ); ?>" <?php selected( $range_days, $value ); ?>>
					<?php echo esc_html( $label ); ?>
				</option>
			<?php endforeach; ?>
		</select>

		<noscript>
			<button type="submit" class="button button-primary"><?php esc_html_e( 'Filter', $domain ); ?></button>
		</noscript>
	</form>

	<div class="ar-analytics-summary">
		<div class="ar-analytics-card">
			<p class="ar-metric-label"><?php esc_html_e( 'Total events', $domain ); ?></p>
			<p class="ar-metric-value"><?php echo esc_html( number_format_i18n( $counts['total'] ) ); ?></p>
		</div>
		<div class="ar-analytics-card">
			<p class="ar-metric-label"><?php esc_html_e( 'Viewer loads', $domain ); ?></p>
			<p class="ar-metric-value"><?php echo esc_html( number_format_i18n( $counts['viewer_load'] ) ); ?></p>
		</div>
		<div class="ar-analytics-card">
			<p class="ar-metric-label"><?php esc_html_e( 'AR launches', $domain ); ?></p>
			<p class="ar-metric-value"><?php echo esc_html( number_format_i18n( $counts['ar_launch'] ) ); ?></p>
		</div>
		<div class="ar-analytics-card">
			<p class="ar-metric-label"><?php esc_html_e( 'Variant changes', $domain ); ?></p>
			<p class="ar-metric-value"><?php echo esc_html( number_format_i18n( $counts['variant_change'] ) ); ?></p>
		</div>
	</div>

	<section class="ar-analytics-section">
		<header>
			<h2><?php esc_html_e( 'Daily engagement', $domain ); ?></h2>
		</header>
		<?php if ( empty( $daily_series ) ) : ?>
			<p class="description"><?php esc_html_e( 'No events recorded for the selected period.', $domain ); ?></p>
		<?php else : ?>
			<?php
			$max_daily = 0;
			foreach ( $daily_series as $series_day ) {
				$max_daily = max( $max_daily, (int) $series_day['count'] );
			}
			$max_daily = max( 1, $max_daily );
			?>
			<div class="ar-analytics-chart">
				<?php foreach ( $daily_series as $day ) : ?>
					<?php
						$count     = (int) $day['count'];
						$max_bar_height = 140;
						$height_ratio   = $max_daily ? ( $count / $max_daily ) : 0;
						$bar_height     = (int) round( $height_ratio * $max_bar_height );
						if ( $count > 0 ) {
							$bar_height = max( 6, $bar_height );
						} else {
							$bar_height = 0;
						}
						$bar_height = min( $max_bar_height, $bar_height );
						$day_label = isset( $day['day'] ) ? $day['day'] : '';
					?>
					<div class="ar-analytics-bar has-visual" aria-label="<?php echo esc_attr( sprintf( __( '%1$s: %2$d events', $domain ), $day_label, $count ) ); ?>" role="img">
						<div class="ar-analytics-bar-visual">
							<div class="ar-analytics-bar-inner" style="height: <?php echo esc_attr( $bar_height ); ?>px"></div>
						</div>
						<span class="ar-analytics-bar-count"><?php echo esc_html( $count ); ?></span>
						<span class="ar-analytics-bar-label"><?php echo esc_html( gmdate( get_option( 'date_format' ), strtotime( $day_label ) ) ); ?></span>
					</div>
				<?php endforeach; ?>
			</div>
		<?php endif; ?>
	</section>

	<div class="ar-analytics-grid">
		<section class="ar-analytics-section">
			<header>
				<h2><?php esc_html_e( 'Top models', $domain ); ?></h2>
			</header>
			<?php if ( empty( $top_models ) ) : ?>
				<p class="description"><?php esc_html_e( 'No model level data yet.', $domain ); ?></p>
			<?php else : ?>
				<table class="widefat ar-analytics-table">
					<thead>
						<tr>
							<th scope="col"><?php esc_html_e( 'Model', $domain ); ?></th>
							<th scope="col"><?php esc_html_e( 'Events', $domain ); ?></th>
						</tr>
					</thead>
					<tbody>
						<?php foreach ( $top_models as $row ) : ?>
							<tr>
								<td>
									<?php
									$title = isset( $row['title'] ) ? $row['title'] : '';
									$model = isset( $row['id'] ) ? $row['id'] : '';
									if ( is_numeric( $model ) ) {
										$edit_link = get_edit_post_link( (int) $model );
										if ( $edit_link ) {
											printf(
												'<a href="%1$s">%2$s</a>',
												esc_url( $edit_link ),
												esc_html( $title ? $title : $model )
											);
										} else {
											echo esc_html( $title ? $title : $model );
										}
									} else {
										echo esc_html( $title ? $title : $model );
									}
									?>
								</td>
								<td><?php echo esc_html( number_format_i18n( (int) $row['count'] ) ); ?></td>
							</tr>
						<?php endforeach; ?>
					</tbody>
				</table>
			<?php endif; ?>
		</section>

		<section class="ar-analytics-section">
			<header>
				<h2><?php esc_html_e( 'Top pages', $domain ); ?></h2>
			</header>
			<?php if ( empty( $top_pages ) ) : ?>
				<p class="description"><?php esc_html_e( 'No page level data yet.', $domain ); ?></p>
			<?php else : ?>
				<table class="widefat ar-analytics-table">
					<thead>
						<tr>
							<th scope="col"><?php esc_html_e( 'Page', $domain ); ?></th>
							<th scope="col"><?php esc_html_e( 'Events', $domain ); ?></th>
						</tr>
					</thead>
					<tbody>
						<?php foreach ( $top_pages as $row ) : ?>
							<tr>
								<td>
									<?php
									$url   = isset( $row['url'] ) ? $row['url'] : '';
									$label = isset( $row['label'] ) ? $row['label'] : $url;
									if ( $url ) {
										printf(
											'<a href="%1$s" target="_blank" rel="noopener noreferrer">%2$s</a>',
											esc_url( $url ),
											esc_html( $label )
										);
									} else {
										echo esc_html( $label );
									}
									?>
								</td>
								<td><?php echo esc_html( number_format_i18n( (int) $row['count'] ) ); ?></td>
							</tr>
						<?php endforeach; ?>
					</tbody>
				</table>
			<?php endif; ?>
		</section>

		<section class="ar-analytics-section">
			<header>
				<h2><?php esc_html_e( 'Device breakdown', $domain ); ?></h2>
			</header>
			<?php if ( empty( $device_breakdown ) ) : ?>
				<p class="description"><?php esc_html_e( 'No device data captured yet.', $domain ); ?></p>
			<?php else : ?>
				<ul class="ar-analytics-device-list">
					<?php
					$total_devices = 0;
					foreach ( $device_breakdown as $device_row ) {
						$total_devices += (int) $device_row['count'];
					}
					$total_devices = max( 1, $total_devices );
					foreach ( $device_breakdown as $device_row ) :
						$count = (int) $device_row['count'];
						$percent = round( ( $count / $total_devices ) * 100 );
						?>
						<li>
							<span class="ar-device-name"><?php echo esc_html( $device_row['label'] ); ?></span>
							<span class="ar-device-count"><?php echo esc_html( number_format_i18n( $count ) ); ?></span>
							<div class="ar-device-progress">
								<div style="width: <?php echo esc_attr( min( 100, $percent ) ); ?>%"></div>
							</div>
							<span class="ar-device-percent"><?php echo esc_html( $percent ); ?>%</span>
						</li>
					<?php endforeach; ?>
				</ul>
			<?php endif; ?>
		</section>
	</div>

	<section class="ar-analytics-section">
		<header>
			<h2><?php esc_html_e( 'Recent events', $domain ); ?></h2>
		</header>
		<?php if ( empty( $recent_events ) ) : ?>
			<p class="description"><?php esc_html_e( 'Events will appear here after visitors interact with your models.', $domain ); ?></p>
		<?php else : ?>
			<table class="widefat ar-analytics-table">
				<thead>
					<tr>
						<th scope="col"><?php esc_html_e( 'Time', $domain ); ?></th>
						<th scope="col"><?php esc_html_e( 'Event', $domain ); ?></th>
						<th scope="col"><?php esc_html_e( 'Model/Variant', $domain ); ?></th>
						<th scope="col"><?php esc_html_e( 'Device', $domain ); ?></th>
						<th scope="col"><?php esc_html_e( 'Page', $domain ); ?></th>
					</tr>
				</thead>
				<tbody>
					<?php foreach ( $recent_events as $event ) : ?>
						<tr>
							<td>
								<?php
								$time = isset( $event['timestamp'] ) ? (int) $event['timestamp'] : 0;
								echo esc_html( $time ? date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $time ) : __( 'Unknown', $domain ) );
								?>
							</td>
							<td><?php echo esc_html( isset( $event['type'] ) ? ucfirst( str_replace( '_', ' ', $event['type'] ) ) : '' ); ?></td>
							<td>
								<?php
								$model = isset( $event['model_id'] ) ? $event['model_id'] : '';
								$variant = isset( $event['variant'] ) ? $event['variant'] : '';
								if ( $model ) {
									echo esc_html( $model );
								} else {
									echo '&mdash;';
								}
								if ( $variant ) {
									printf( ' <span class="ar-variant-tag">%s</span>', esc_html( $variant ) );
								}
								?>
							</td>
							<td><?php echo esc_html( isset( $event['device'] ) ? $event['device'] : __( 'Unknown', $domain ) ); ?></td>
							<td>
								<?php
								$page_url = isset( $event['page_url'] ) ? $event['page_url'] : '';
								if ( $page_url ) {
									printf(
										'<a href="%1$s" target="_blank" rel="noopener noreferrer">%2$s</a>',
										esc_url( $page_url ),
										esc_html( $page_url )
									);
								} else {
									echo '&mdash;';
								}
								?>
							</td>
						</tr>
					<?php endforeach; ?>
				</tbody>
			</table>
		<?php endif; ?>
	</section>
</div>

