<?php
/**
 * BaseCloud Boost — Dashboard View
 *
 * @package BaseCloud\Boost
 */

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

use BaseCloud\Boost\Core\Page_Cache;
use BaseCloud\Boost\Core\Cache_Preloader;
use BaseCloud\Boost\Core\Metrics_Collector;
use BaseCloud\Boost\Admin\Admin_Controller;

$page_cache    = new Page_Cache();
$stats         = $page_cache->get_cache_stats();
$preloader     = new Cache_Preloader();
$progress      = $preloader->get_preload_progress();
$controller    = new Admin_Controller();
$conflicts     = $controller->detect_conflicts();
$options       = (array) get_option( BCBOOST_OPTIONS_KEY, [] );
$metrics_col   = new Metrics_Collector();
$perf_stats    = $metrics_col->get_all();
$hit_rate      = $metrics_col->get_hit_rate();
$total_saved   = $metrics_col->get_total_saved_bytes();
$last_purge    = $perf_stats['last_purge'] ? human_time_diff( (int) $perf_stats['last_purge'] ) . ' ago' : '—';
$last_webhook  = $perf_stats['last_webhook_sent'] ? human_time_diff( (int) $perf_stats['last_webhook_sent'] ) . ' ago' : '—';

$features = [
	'cache_enabled'        => __( 'Page Cache', 'basecloud-boost' ),
	'minify_html'          => __( 'HTML Minification', 'basecloud-boost' ),
	'minify_css'           => __( 'CSS Minification', 'basecloud-boost' ),
	'combine_css'          => __( 'CSS Combining', 'basecloud-boost' ),
	'minify_js'            => __( 'JS Minification', 'basecloud-boost' ),
	'defer_js'             => __( 'JS Deferral', 'basecloud-boost' ),
	'lazy_load_images'     => __( 'Image Lazy Loading', 'basecloud-boost' ),
	'browser_cache'        => __( 'Browser Cache Headers', 'basecloud-boost' ),
	'gzip_compression'     => __( 'GZIP Compression', 'basecloud-boost' ),
	'critical_css_enabled' => __( 'Critical CSS', 'basecloud-boost' ),
	'serve_webp'           => __( 'WebP Serving', 'basecloud-boost' ),
];
?>
<div class="bcboost-wrap">

	<?php include __DIR__ . '/partials/header.php'; ?>

	<!-- Page Header -->
	<div class="bcboost-page-header">
		<div>
			<h2 class="bcboost-page-title"><?php esc_html_e( 'Dashboard', 'basecloud-boost' ); ?></h2>
			<p class="bcboost-page-subtitle"><?php esc_html_e( 'Performance overview — serving cached pages at the speed of light', 'basecloud-boost' ); ?></p>
		</div>
		<button class="bcboost-btn bcboost-btn--primary" id="bcboost-clear-cache-main">
			<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>
			<?php esc_html_e( 'Boost Cache', 'basecloud-boost' ); ?>
		</button>
	</div>

	<!-- Conflict Warning -->
	<?php if ( ! empty( $conflicts ) ) : ?>
		<div class="bcboost-notice bcboost-notice--warning" role="alert">
			<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
			<div>
				<strong><?php esc_html_e( 'Plugin Conflict Detected', 'basecloud-boost' ); ?></strong>
				<?php
				printf(
					' ' . esc_html__( 'The following caching plugins are active and may conflict: %s.', 'basecloud-boost' ),
					'<strong>' . esc_html( implode( ', ', $conflicts ) ) . '</strong>'
				);
				?>
			</div>
		</div>
	<?php endif; ?>

	<!-- Stats Grid -->
	<div class="bcboost-stats-grid">

		<div class="bcboost-stat-card">
			<div class="bcboost-stat-icon-wrap">
				<span class="dashicons dashicons-media-document bcboost-stat-icon" aria-hidden="true"></span>
			</div>
			<div>
				<div class="bcboost-stat-value" data-count="<?php echo (int) $stats['count']; ?>">
					<?php echo esc_html( number_format_i18n( $stats['count'] ) ); ?>
				</div>
				<div class="bcboost-stat-label"><?php esc_html_e( 'Cached Pages', 'basecloud-boost' ); ?></div>
			</div>
		</div>

		<div class="bcboost-stat-card">
			<div class="bcboost-stat-icon-wrap bcboost-stat-icon-wrap--purple">
				<span class="dashicons dashicons-database bcboost-stat-icon bcboost-stat-icon--purple" aria-hidden="true"></span>
			</div>
			<div>
				<div class="bcboost-stat-value"><?php echo esc_html( size_format( $stats['size'] ) ); ?></div>
				<div class="bcboost-stat-label"><?php esc_html_e( 'Cache Size', 'basecloud-boost' ); ?></div>
			</div>
		</div>

		<div class="bcboost-stat-card">
			<div class="bcboost-stat-icon-wrap bcboost-stat-icon-wrap--blue">
				<span class="dashicons dashicons-clock bcboost-stat-icon bcboost-stat-icon--blue" aria-hidden="true"></span>
			</div>
			<div>
				<div class="bcboost-stat-value">
					<?php echo $stats['newest'] ? esc_html( human_time_diff( $stats['newest'] ) . ' ago' ) : '—'; ?>
				</div>
				<div class="bcboost-stat-label"><?php esc_html_e( 'Last Cached', 'basecloud-boost' ); ?></div>
			</div>
		</div>

		<div class="bcboost-stat-card">
			<div class="bcboost-stat-icon-wrap <?php echo ( $options['cache_enabled'] ?? true ) ? '' : 'bcboost-stat-icon-wrap--purple'; ?>">
				<span class="dashicons dashicons-<?php echo ( $options['cache_enabled'] ?? true ) ? 'yes-alt' : 'dismiss'; ?> bcboost-stat-icon" aria-hidden="true"></span>
			</div>
			<div>
				<div class="bcboost-stat-value bcboost-stat-value--<?php echo ( $options['cache_enabled'] ?? true ) ? 'active' : 'inactive'; ?>">
					<?php echo ( $options['cache_enabled'] ?? true ) ? esc_html__( 'Active', 'basecloud-boost' ) : esc_html__( 'Disabled', 'basecloud-boost' ); ?>
				</div>
				<div class="bcboost-stat-label"><?php esc_html_e( 'Cache Status', 'basecloud-boost' ); ?></div>
			</div>
		</div>

	</div>

	<!-- Performance Metrics -->
	<div class="bcboost-metrics-grid">

		<!-- Hit Rate Ring -->
		<div class="bcboost-card bcboost-card--metrics">
			<h3>
				<span class="bcboost-section-icon" aria-hidden="true">
					<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>
				</span>
				<?php esc_html_e( 'Cache Performance', 'basecloud-boost' ); ?>
			</h3>
			<?php
			$bcb_proxy = (bool) BCBOOST_get_option( 'varnish_enabled', false )
				|| \BaseCloud\Boost\Compatibility\Varnish::is_detected();
			?>
			<?php if ( $bcb_proxy ) : ?>
			<p class="bcboost-proxy-note" style="margin:0 0 14px;padding:10px 12px;border-radius:8px;background:rgba(74,222,128,.08);border:1px solid rgba(74,222,128,.25);font-size:12px;line-height:1.5;">
				<strong><?php esc_html_e( 'Served via a reverse proxy (e.g. Varnish).', 'basecloud-boost' ); ?></strong>
				<?php esc_html_e( 'A reverse proxy is caching your optimized pages in front of BaseCloud Boost, so most visits are served by it and never reach PHP. The hit rate below counts only requests that reach PHP — it is not your true cache performance. Your pages are still fully cached and served fast, and Boost purges the proxy automatically whenever the cache is cleared.', 'basecloud-boost' ); ?>
			</p>
			<?php endif; ?>
			<div class="bcboost-hit-rate-wrap">
				<div class="bcboost-hit-rate-ring" style="--hit-rate: <?php echo (int) $hit_rate; ?>">
					<svg viewBox="0 0 120 120" class="bcboost-ring-svg" aria-hidden="true">
						<circle cx="60" cy="60" r="50" class="bcboost-ring-track"/>
						<circle cx="60" cy="60" r="50" class="bcboost-ring-fill"
							style="stroke-dasharray: <?php echo round( $hit_rate * 3.14159, 1 ); ?> 314.159"/>
					</svg>
					<div class="bcboost-ring-label">
						<span class="bcboost-ring-value" data-count="<?php echo esc_attr( $hit_rate ); ?>" data-suffix="%">
							<?php echo esc_html( number_format( $hit_rate, 1 ) ); ?>%
						</span>
						<span class="bcboost-ring-desc"><?php esc_html_e( 'Hit Rate', 'basecloud-boost' ); ?></span>
					</div>
				</div>
				<div class="bcboost-hit-rate-details">
					<div class="bcboost-hrd-row">
						<span class="bcboost-hrd-dot bcboost-hrd-dot--green"></span>
						<span class="bcboost-hrd-key"><?php esc_html_e( 'Cache Hits', 'basecloud-boost' ); ?></span>
						<span class="bcboost-hrd-val" data-count="<?php echo (int) $perf_stats['hits']; ?>">
							<?php echo esc_html( number_format_i18n( (int) $perf_stats['hits'] ) ); ?>
						</span>
					</div>
					<div class="bcboost-hrd-row">
						<span class="bcboost-hrd-dot bcboost-hrd-dot--purple"></span>
						<span class="bcboost-hrd-key"><?php esc_html_e( 'Cache Misses', 'basecloud-boost' ); ?></span>
						<span class="bcboost-hrd-val" data-count="<?php echo (int) $perf_stats['misses']; ?>">
							<?php echo esc_html( number_format_i18n( (int) $perf_stats['misses'] ) ); ?>
						</span>
					</div>
					<div class="bcboost-hrd-row">
						<span class="bcboost-hrd-dot bcboost-hrd-dot--blue"></span>
						<span class="bcboost-hrd-key"><?php esc_html_e( 'Last Purge', 'basecloud-boost' ); ?></span>
						<span class="bcboost-hrd-val"><?php echo esc_html( $last_purge ); ?></span>
					</div>
				</div>
			</div>
		</div>

		<!-- Bytes Saved -->
		<div class="bcboost-card bcboost-card--metrics">
			<h3>
				<span class="bcboost-section-icon" aria-hidden="true">
					<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>
				</span>
				<?php esc_html_e( 'Bytes Saved by Minification', 'basecloud-boost' ); ?>
			</h3>
			<div class="bcboost-bytes-grid">
				<div class="bcboost-bytes-item">
					<span class="bcboost-bytes-label"><?php esc_html_e( 'HTML', 'basecloud-boost' ); ?></span>
					<span class="bcboost-bytes-bar-wrap">
						<span class="bcboost-bytes-bar bcboost-bytes-bar--green" style="width:<?php echo $total_saved > 0 ? min( 100, round( (int) $perf_stats['html_saved'] / $total_saved * 100 ) ) : 0; ?>%"></span>
					</span>
					<span class="bcboost-bytes-val"><?php echo esc_html( size_format( (int) $perf_stats['html_saved'] ) ); ?></span>
				</div>
				<div class="bcboost-bytes-item">
					<span class="bcboost-bytes-label"><?php esc_html_e( 'CSS', 'basecloud-boost' ); ?></span>
					<span class="bcboost-bytes-bar-wrap">
						<span class="bcboost-bytes-bar bcboost-bytes-bar--blue" style="width:<?php echo $total_saved > 0 ? min( 100, round( (int) $perf_stats['css_saved'] / $total_saved * 100 ) ) : 0; ?>%"></span>
					</span>
					<span class="bcboost-bytes-val"><?php echo esc_html( size_format( (int) $perf_stats['css_saved'] ) ); ?></span>
				</div>
				<div class="bcboost-bytes-item">
					<span class="bcboost-bytes-label"><?php esc_html_e( 'JS', 'basecloud-boost' ); ?></span>
					<span class="bcboost-bytes-bar-wrap">
						<span class="bcboost-bytes-bar bcboost-bytes-bar--purple" style="width:<?php echo $total_saved > 0 ? min( 100, round( (int) $perf_stats['js_saved'] / $total_saved * 100 ) ) : 0; ?>%"></span>
					</span>
					<span class="bcboost-bytes-val"><?php echo esc_html( size_format( (int) $perf_stats['js_saved'] ) ); ?></span>
				</div>
				<div class="bcboost-bytes-total">
					<span><?php esc_html_e( 'Total Saved', 'basecloud-boost' ); ?></span>
					<strong><?php echo esc_html( size_format( $total_saved ) ); ?></strong>
				</div>
			</div>
			<?php if ( ! empty( $options['webhook_enabled'] ) ) : ?>
			<div class="bcboost-webhook-status-mini">
				<span class="dashicons dashicons-cloud-upload" aria-hidden="true"></span>
				<?php
				printf(
					/* translators: %s = time since last webhook */
					esc_html__( 'Last webhook: %s', 'basecloud-boost' ),
					'<strong>' . esc_html( $last_webhook ) . '</strong>'
				);
				?>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=basecloud-webhook' ) ); ?>" class="bcboost-link">
					<?php esc_html_e( 'Configure', 'basecloud-boost' ); ?> &rarr;
				</a>
			</div>
			<?php endif; ?>
		</div>

	</div>

	<!-- Preloader Progress (only when running) -->
	<?php if ( in_array( $progress['status'], [ 'starting', 'running' ], true ) ) : ?>
		<div class="bcboost-card bcboost-card--accent-green" id="bcboost-preloader-card">
			<h3>
				<span class="bcboost-section-icon" aria-hidden="true">
					<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>
				</span>
				<?php esc_html_e( 'Cache Preloader Running', 'basecloud-boost' ); ?>
			</h3>
			<div class="bcboost-preloader-status bcboost-preloader-status--running">
				<span class="bcboost-status-dot"></span>
				<?php esc_html_e( 'Preloading cache&hellip;', 'basecloud-boost' ); ?>
				<span style="margin-left:10px;font-size:12px;opacity:.75;">
					<?php
					if ( ( $progress['mode'] ?? '' ) === 'chained' ) {
						esc_html_e( 'Chained loopback — warming without visitor traffic', 'basecloud-boost' );
					} elseif ( ( $progress['mode'] ?? '' ) === 'cron' ) {
						esc_html_e( 'WP-Cron fallback mode', 'basecloud-boost' );
					}
					if ( isset( $progress['remaining'] ) ) {
						printf(
							/* translators: %s: number of URLs still queued */
							' · ' . esc_html__( '%s in queue', 'basecloud-boost' ),
							esc_html( number_format_i18n( (int) $progress['remaining'] ) )
						);
					}
					?>
				</span>
			</div>
			<div style="margin-top:16px;">
				<div class="bcboost-progress-bar">
					<div class="bcboost-progress-fill" id="bcboost-progress-fill"
						style="width: <?php echo (int) $progress['percentage']; ?>%"></div>
				</div>
				<div class="bcboost-progress-label" id="bcboost-progress-label">
					<?php printf(
						esc_html__( '%1$d of %2$d pages preloaded (%3$d%%)', 'basecloud-boost' ),
						(int) $progress['completed'],
						(int) $progress['total'],
						(int) $progress['percentage']
					); ?>
				</div>
				<div class="bcboost-current-url" id="bcboost-current-url"><?php echo esc_html( $progress['current_url'] ); ?></div>
			</div>
		</div>
	<?php endif; ?>

	<!-- Quick Actions -->
	<div class="bcboost-card bcboost-card--accent-green">
		<h3>
			<span class="bcboost-section-icon" aria-hidden="true">
				<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>
			</span>
			<?php esc_html_e( 'Quick Actions', 'basecloud-boost' ); ?>
		</h3>
		<div class="bcboost-actions-row">
			<button class="bcboost-btn bcboost-btn--primary" id="bcboost-clear-cache-main">
				<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>
				<?php esc_html_e( 'Boost Cache', 'basecloud-boost' ); ?>
			</button>
			<button class="bcboost-btn bcboost-btn--secondary" id="bcboost-start-preloader">
				<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>
				<?php esc_html_e( 'Start Preloader', 'basecloud-boost' ); ?>
			</button>
			<button class="bcboost-btn bcboost-btn--secondary" id="bcboost-run-db-cleanup">
				<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M21 12c0 1.66-4 3-9 3s-9-1.34-9-3"/><path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"/></svg>
				<?php esc_html_e( 'DB Cleanup', 'basecloud-boost' ); ?>
			</button>
		</div>
	</div>

	<!-- Optimization Status -->
	<div class="bcboost-card">
		<h3>
			<span class="bcboost-section-icon" aria-hidden="true">
				<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>
			</span>
			<?php esc_html_e( 'Optimization Status', 'basecloud-boost' ); ?>
		</h3>
		<div class="bcboost-feature-grid">
			<?php foreach ( $features as $key => $label ) :
				$enabled = ! empty( $options[ $key ] );
			?>
				<div class="bcboost-feature-item bcboost-feature-item--<?php echo $enabled ? 'enabled' : 'disabled'; ?>">
					<span class="dashicons dashicons-<?php echo $enabled ? 'yes-alt' : 'minus-alt'; ?>" aria-hidden="true"></span>
					<span class="bcboost-feature-label"><?php echo esc_html( $label ); ?></span>
					<span class="bcboost-feature-badge"><?php echo $enabled ? esc_html__( 'ON', 'basecloud-boost' ) : esc_html__( 'OFF', 'basecloud-boost' ); ?></span>
				</div>
			<?php endforeach; ?>
		</div>
	</div>

</div>
