<?php
/**
 * Log Tab Template — Speed Test History
 *
 * Gated to Personal+ plans. Free users see an upsell.
 *
 * @package SpeedInChina
 */

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

global $speeinch_fs;
$current_tab      = 'log';
$speeinch_is_paid = $speeinch_fs->is_plan( 'personal', true ) || $speeinch_fs->is_plan( 'pro', true ) || $speeinch_fs->is_plan( 'agency', true );
?>
<div class="wrap speeinch-wrap">
	<h1><?php esc_html_e( 'Speed in China', 'speed-in-china' ); ?></h1>

	<?php require_once SPEEINCH_PLUGIN_PATH . 'admin/templates/nav-tabs.php'; ?>

	<?php if ( ! $speeinch_is_paid ) : ?>
		<!-- Upgrade upsell for free users -->
		<div class="speeinch_container speeinch-upsell-card" style="text-align:center;">
			<div class="speeinch-lock-icon">🔒</div>
			<h2><?php esc_html_e( '📊 Speed Test History', 'speed-in-china' ); ?></h2>
			<p><?php esc_html_e( 'Keep a history of your speed tests and easily view detailed timing breakdowns, optimization suggestions, and performance trends.', 'speed-in-china' ); ?></p>

			<!-- Blurred preview -->
			<div class="speeinch-blurred-preview">
				<table class="widefat striped" style="opacity: 0.3; pointer-events: none;">
					<thead>
						<tr>
							<th><?php esc_html_e( 'Location', 'speed-in-china' ); ?></th>
							<th><?php esc_html_e( 'DNS', 'speed-in-china' ); ?></th>
							<th><?php esc_html_e( 'TCP', 'speed-in-china' ); ?></th>
							<th><?php esc_html_e( 'TLS', 'speed-in-china' ); ?></th>
							<th><?php esc_html_e( 'TTFB', 'speed-in-china' ); ?></th>
							<th><?php esc_html_e( 'Total', 'speed-in-china' ); ?></th>
							<th><?php esc_html_e( 'Status', 'speed-in-china' ); ?></th>
						</tr>
					</thead>
					<tbody>
						<tr><td>Shanghai, CN</td><td>83ms</td><td>180ms</td><td>188ms</td><td>781ms</td><td><strong>1414ms</strong></td><td>HTTP 200</td></tr>
						<tr><td>Beijing, CN</td><td>12ms</td><td>241ms</td><td>249ms</td><td>550ms</td><td><strong>1043ms</strong></td><td>HTTP 200</td></tr>
						<tr><td>Guangzhou, CN</td><td>3ms</td><td>196ms</td><td>199ms</td><td>793ms</td><td><strong>1192ms</strong></td><td>HTTP 200</td></tr>
					</tbody>
				</table>
			</div>

			<div class="speeinch-upgrade-cta">
				<p><strong><?php esc_html_e( 'Upgrade to Personal to unlock test history', 'speed-in-china' ); ?></strong></p>
				<ul class="speeinch-feature-list">
					<li>✅ <?php esc_html_e( 'View last 10 speed test results', 'speed-in-china' ); ?></li>
					<li>✅ <?php esc_html_e( 'Per-location timing breakdown (DNS, TCP, TLS, TTFB)', 'speed-in-china' ); ?></li>
					<li>✅ <?php esc_html_e( 'Automated optimization suggestions', 'speed-in-china' ); ?></li>
					<li>✅ <?php esc_html_e( 'Weekly speed tests (vs monthly on free)', 'speed-in-china' ); ?></li>
				</ul>
				<a href="<?php echo esc_url( $speeinch_fs->get_upgrade_url() ); ?>" class="button button-primary button-hero">
					<?php esc_html_e( '⬆️ Upgrade to Personal', 'speed-in-china' ); ?>
				</a>
			</div>
		</div>
	<?php else : ?>
		<?php
		$speeinch_history = get_option( 'speeinch_speed_test_history', array() );
		$has_history      = ! empty( $speeinch_history );
		?>

		<?php if ( $has_history ) : ?>
		<div class="speeinch_container speeinch-history-container">
			<h2><?php esc_html_e( '📊 Speed Test History', 'speed-in-china' ); ?></h2>
			<p class="description" style="align-self:flex-start;margin:0 0 15px;">
				<?php
				/* translators: %d: number of test runs stored */
				echo esc_html( sprintf( __( 'Showing the last %d test run(s). Results are stored locally and retained between sessions.', 'speed-in-china' ), count( $speeinch_history ) ) );
				?>
			</p>

			<?php
			foreach ( $speeinch_history as $index => $entry ) :
				$timestamp   = isset( $entry['timestamp'] ) ? $entry['timestamp'] : '';
				$domain      = isset( $entry['domain'] ) ? $entry['domain'] : '';
				$locations   = isset( $entry['locations'] ) ? $entry['locations'] : array();
				$suggestions = isset( $entry['suggestions'] ) ? $entry['suggestions'] : array();

				// Calculate average total time
				$total_times = array_filter(
					array_map(
						function ( $loc ) {
							return isset( $loc['timings']['total'] ) ? $loc['timings']['total'] : null;
						},
						$locations
					)
				);
				$avg_total   = ! empty( $total_times ) ? round( array_sum( $total_times ) / count( $total_times ) ) : 0;

				// Determine overall status
				$status_class = 'speeinch-status-good';
				$status_label = __( 'Fast', 'speed-in-china' );
				if ( $avg_total > 3000 ) {
					$status_class = 'speeinch-status-critical';
					$status_label = __( 'Slow', 'speed-in-china' );
				} elseif ( $avg_total > 1500 ) {
					$status_class = 'speeinch-status-warning';
					$status_label = __( 'Moderate', 'speed-in-china' );
				}
				?>
			<div class="speeinch-history-entry<?php echo $index === 0 ? ' speeinch-history-latest speeinch-history-expanded' : ''; ?>">
				<div class="speeinch-history-header" onclick="this.parentElement.classList.toggle('speeinch-history-expanded')">
					<div class="speeinch-history-meta">
						<?php if ( $index === 0 ) : ?>
							<span class="speeinch-badge speeinch-badge-latest"><?php esc_html_e( 'Latest', 'speed-in-china' ); ?></span>
						<?php endif; ?>
						<strong><?php echo esc_html( $domain ); ?></strong>
						<span class="speeinch-history-date"><?php echo esc_html( $timestamp ); ?></span>
					</div>
					<div class="speeinch-history-summary">
						<span class="speeinch-avg-time"><strong><?php echo esc_html( $avg_total ); ?>ms</strong> <?php esc_html_e( 'avg', 'speed-in-china' ); ?></span>
						<span class="speeinch-status-badge <?php echo esc_attr( $status_class ); ?>"><?php echo esc_html( $status_label ); ?></span>
						<span class="speeinch-expand-icon">▼</span>
					</div>
				</div>

				<div class="speeinch-history-details">
					<table class="widefat striped speeinch-history-table">
						<thead>
							<tr>
								<th><?php esc_html_e( 'Location', 'speed-in-china' ); ?></th>
								<th><?php esc_html_e( 'DNS', 'speed-in-china' ); ?></th>
								<th><?php esc_html_e( 'TCP', 'speed-in-china' ); ?></th>
								<th><?php esc_html_e( 'TLS', 'speed-in-china' ); ?></th>
								<th><?php esc_html_e( 'TTFB', 'speed-in-china' ); ?></th>
								<th><?php esc_html_e( 'Download', 'speed-in-china' ); ?></th>
								<th><?php esc_html_e( 'Total', 'speed-in-china' ); ?></th>
								<th><?php esc_html_e( 'Status', 'speed-in-china' ); ?></th>
							</tr>
						</thead>
						<tbody>
							<?php
							foreach ( $locations as $loc ) :
								$timings     = isset( $loc['timings'] ) ? $loc['timings'] : array();
								$total       = isset( $timings['total'] ) ? $timings['total'] : 0;
								$total_class = $total > 3000 ? 'speeinch-timing-critical' : ( $total > 1500 ? 'speeinch-timing-warning' : 'speeinch-timing-good' );
								?>
							<tr>
								<td><?php echo esc_html( isset( $loc['location'] ) ? $loc['location'] : '—' ); ?></td>
								<td><?php echo isset( $timings['dns'] ) ? esc_html( $timings['dns'] . 'ms' ) : '—'; ?></td>
								<td><?php echo isset( $timings['tcp'] ) ? esc_html( $timings['tcp'] . 'ms' ) : '—'; ?></td>
								<td><?php echo isset( $timings['tls'] ) ? esc_html( $timings['tls'] . 'ms' ) : '—'; ?></td>
								<td><?php echo isset( $timings['firstByte'] ) ? esc_html( $timings['firstByte'] . 'ms' ) : '—'; ?></td>
								<td><?php echo isset( $timings['download'] ) ? esc_html( $timings['download'] . 'ms' ) : '—'; ?></td>
								<td class="<?php echo esc_attr( $total_class ); ?>"><strong><?php echo esc_html( $total . 'ms' ); ?></strong></td>
								<td><?php echo esc_html( isset( $loc['status'] ) ? $loc['status'] : '—' ); ?></td>
							</tr>
							<?php endforeach; ?>
						</tbody>
					</table>

					<?php if ( ! empty( $suggestions ) ) : ?>
					<div class="speeinch-suggestions">
						<h4><?php esc_html_e( '💡 Optimization Suggestions', 'speed-in-china' ); ?></h4>
						<ul>
							<?php
							foreach ( $suggestions as $sug ) :
								if ( empty( $sug['suggestion'] ) ) {
									continue;
								}
								?>
							<li>
								<strong><?php echo esc_html( $sug['metric'] ); ?></strong>
								(<?php echo esc_html( $sug['value_ms'] . 'ms / ' . $sug['threshold'] . 'ms threshold' ); ?>):
								<?php echo esc_html( $sug['suggestion'] ); ?>
							</li>
							<?php endforeach; ?>
						</ul>
					</div>
					<?php endif; ?>
				</div>
			</div>
			<?php endforeach; ?>
		</div>
		<?php else : ?>
		<div class="speeinch_container" style="text-align:center;">
			<h2><?php esc_html_e( '📊 Speed Test History', 'speed-in-china' ); ?></h2>
			<p><?php esc_html_e( 'No speed tests have been run yet. Go to the Speed Test tab to run your first test.', 'speed-in-china' ); ?></p>
			<a href="?page=speed-in-china" class="button button-primary"><?php esc_html_e( '⏱ Run Speed Test', 'speed-in-china' ); ?></a>
		</div>
		<?php endif; ?>
	<?php endif; ?>

	<!--Features-->
	<?php require_once SPEEINCH_PLUGIN_PATH . 'admin/templates/features.php'; ?>
</div>
