<?php
/**
 * BaseCloud Boost — Advanced Settings
 *
 * @package BaseCloud\Boost
 */

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

$options = (array) get_option( BCBOOST_OPTIONS_KEY, [] );
?>
<div class="bcboost-wrap">
	<?php include __DIR__ . '/partials/header.php'; ?>

	<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
		<?php wp_nonce_field( 'BCBOOST_save_settings' ); ?>
		<input type="hidden" name="action" value="BCBOOST_save_settings">
		<input type="hidden" name="BCBOOST_tab_checkboxes" value="gzip_compression,browser_cache,stale_while_revalidate,heartbeat_control,disable_emojis,disable_embeds,disable_dashicons,remove_query_strings,critical_css_enabled,critical_css_auto,varnish_enabled">

		<div class="bcboost-card bcboost-card--accent-green">
			<h3><span class="bcboost-section-icon">🗜️</span> <?php esc_html_e( 'Compression & Browser Cache', 'basecloud-boost' ); ?></h3>

			<div class="bcboost-field bcboost-field--toggle">
				<label>
					<span class="bcboost-field-label"><?php esc_html_e( 'GZIP Compression', 'basecloud-boost' ); ?></span>
					<span class="bcboost-field-desc"><?php esc_html_e( 'Enable GZIP compression via .htaccess for static files. Reduces transfer size by up to 70%.', 'basecloud-boost' ); ?></span>
				</label>
				<label class="bcboost-toggle">
					<input type="checkbox" name="gzip_compression" value="1" <?php checked( ! empty( $options['gzip_compression'] ) ); ?>>
					<span class="bcboost-toggle-slider"></span>
				</label>
			</div>

			<div class="bcboost-field bcboost-field--toggle">
				<label>
					<span class="bcboost-field-label"><?php esc_html_e( 'Browser Cache Headers', 'basecloud-boost' ); ?></span>
					<span class="bcboost-field-desc"><?php esc_html_e( 'Add far-future Expires headers for static assets so browsers cache them locally.', 'basecloud-boost' ); ?></span>
				</label>
				<label class="bcboost-toggle">
					<input type="checkbox" name="browser_cache" value="1" <?php checked( ! empty( $options['browser_cache'] ) ); ?>>
					<span class="bcboost-toggle-slider"></span>
				</label>
			</div>

			<div class="bcboost-field bcboost-field--toggle">
				<label>
					<span class="bcboost-field-label"><?php esc_html_e( 'Stale-While-Revalidate', 'basecloud-boost' ); ?></span>
					<span class="bcboost-field-desc"><?php esc_html_e( 'Add stale-while-revalidate=3600 to Cache-Control headers. Allows CDNs and browsers to serve a stale cached page instantly while refreshing it in the background — zero-latency for returning visitors.', 'basecloud-boost' ); ?></span>
				</label>
				<label class="bcboost-toggle">
					<input type="checkbox" name="stale_while_revalidate" value="1" <?php checked( ! empty( $options['stale_while_revalidate'] ) ); ?>>
					<span class="bcboost-toggle-slider"></span>
				</label>
			</div>
		</div>

		<?php
		$bcb_host_detector = new \BaseCloud\Boost\Compatibility\Host_Detector();
		$bcb_detected_host = $bcb_host_detector->detect();
		$bcb_host_has_fpc  = $bcb_host_detector->host_has_page_cache();
		$bcb_oc_backend    = \BaseCloud\Boost\Compatibility\Object_Cache_Compat::backend();
		$bcb_varnish_seen  = \BaseCloud\Boost\Compatibility\Varnish::is_detected();
		?>
		<div class="bcboost-card bcboost-card--accent-blue">
			<h3><span class="bcboost-section-icon">🧩</span> <?php esc_html_e( 'Server Cache &amp; Compatibility', 'basecloud-boost' ); ?></h3>

			<div class="bcboost-field">
				<span class="bcboost-field-label"><?php esc_html_e( 'Detected environment', 'basecloud-boost' ); ?></span>
				<span class="bcboost-field-desc" style="margin-top:8px;display:block;line-height:1.9;">
					<?php
					/* translators: %s: hosting environment name */
					printf( esc_html__( 'Hosting: %s', 'basecloud-boost' ), '<strong>' . esc_html( ucfirst( $bcb_detected_host ) ) . '</strong>' );
					if ( $bcb_host_has_fpc ) {
						echo ' — ' . esc_html__( 'this host runs its own page cache, so BaseCloud Boost’s file cache is disabled automatically to avoid double-caching.', 'basecloud-boost' );
					}
					echo '<br>';
					if ( '' !== $bcb_oc_backend ) {
						/* translators: %s: object cache backend name (e.g. Object Cache Pro) */
						printf( esc_html__( 'Object cache: %s — detected and running alongside BaseCloud Boost. No conflicts: Boost never installs an object-cache.php drop-in and never flushes the object cache.', 'basecloud-boost' ), '<strong>' . esc_html( $bcb_oc_backend ) . '</strong>' );
					} else {
						esc_html_e( 'Object cache: none detected (a persistent object cache like Redis / Object Cache Pro is recommended and fully compatible).', 'basecloud-boost' );
					}
					echo '<br>';
					echo $bcb_varnish_seen
						? esc_html__( 'Varnish: detected in front of this request.', 'basecloud-boost' )
						: esc_html__( 'Varnish: not detected on this request.', 'basecloud-boost' );

					// Turnkey notice: on Cloudways we purge Varnish automatically.
					if ( \BaseCloud\Boost\Compatibility\Host_Detector::is_cloudways() && empty( $options['varnish_enabled'] ) ) {
						echo '<br><strong>✓ ' . esc_html__( 'Cloudways detected — BaseCloud Boost automatically purges Cloudways Varnish whenever you clear the cache. No setup needed; your changes show immediately.', 'basecloud-boost' ) . '</strong>';
					}
					?>
				</span>
			</div>

			<div class="bcboost-field bcboost-field--toggle">
				<label>
					<span class="bcboost-field-label"><?php esc_html_e( 'Purge Varnish on Cache Clear', 'basecloud-boost' ); ?></span>
					<span class="bcboost-field-desc"><?php esc_html_e( 'When BaseCloud Boost clears a page, also send a PURGE/BAN to Varnish so the reverse proxy never serves stale HTML. Requires the VCL below so Varnish trusts and honours the requests.', 'basecloud-boost' ); ?></span>
				</label>
				<label class="bcboost-toggle">
					<input type="checkbox" name="varnish_enabled" value="1" <?php checked( ! empty( $options['varnish_enabled'] ) ); ?>>
					<span class="bcboost-toggle-slider"></span>
				</label>
			</div>

			<div class="bcboost-field">
				<label class="bcboost-field-label" for="varnish_mode"><?php esc_html_e( 'Reverse Proxy Type', 'basecloud-boost' ); ?></label>
				<span class="bcboost-field-desc"><?php esc_html_e( 'Self-managed: you control the VCL — Boost sends PURGE (single URL) / BAN (site) and you paste the VCL below. Cloudways: managed Varnish you cannot edit — Boost sends URLPURGE (single URL) and a PURGE to /?purgeall (site), to 127.0.0.1:8080. For Cloudways, set Varnish Servers to 127.0.0.1:8080, ignore the VCL below, and add the cookie "bcboost-nocache" under Cloudways → Application → Varnish Settings → Excluded Cookies.', 'basecloud-boost' ); ?></span>
				<select id="varnish_mode" name="varnish_mode" class="bcboost-select" style="margin-top:10px;">
					<?php foreach ( [ 'self' => 'Self-managed (PURGE / BAN + VCL)', 'cloudways' => 'Cloudways (managed Varnish — URLPURGE / ?purgeall)' ] as $bcb_vm => $bcb_vm_label ) : ?>
						<option value="<?php echo esc_attr( $bcb_vm ); ?>" <?php selected( (string) ( $options['varnish_mode'] ?? 'self' ), $bcb_vm ); ?>><?php echo esc_html( $bcb_vm_label ); ?></option>
					<?php endforeach; ?>
				</select>
			</div>

			<div class="bcboost-field">
				<label class="bcboost-field-label" for="varnish_servers"><?php esc_html_e( 'Varnish Servers', 'basecloud-boost' ); ?></label>
				<span class="bcboost-field-desc"><?php esc_html_e( 'One host[:port] per line (e.g. 127.0.0.1:6081). Leave blank to send purges to your site’s own hostname. The site domain is preserved in the Host header so Varnish matches the right cached object.', 'basecloud-boost' ); ?></span>
				<textarea id="varnish_servers" name="varnish_servers" class="bcboost-textarea bcboost-input--wide" rows="2" style="margin-top:10px;font-family:monospace;" placeholder="127.0.0.1:6081"><?php echo esc_textarea( $options['varnish_servers'] ?? '' ); ?></textarea>
			</div>

			<div class="bcboost-field">
				<label class="bcboost-field-label" for="varnish_purge_method"><?php esc_html_e( 'Site-wide Purge Method', 'basecloud-boost' ); ?></label>
				<span class="bcboost-field-desc"><?php esc_html_e( 'How to clear everything. BAN (recommended) invalidates the whole host in one request; PURGE sends a regex purge for VCLs that only support PURGE.', 'basecloud-boost' ); ?></span>
				<select id="varnish_purge_method" name="varnish_purge_method" class="bcboost-select" style="margin-top:10px;">
					<?php foreach ( [ 'ban' => 'BAN (recommended)', 'purge' => 'PURGE (regex)' ] as $bcb_v => $bcb_label ) : ?>
						<option value="<?php echo esc_attr( $bcb_v ); ?>" <?php selected( (string) ( $options['varnish_purge_method'] ?? 'ban' ), $bcb_v ); ?>><?php echo esc_html( $bcb_label ); ?></option>
					<?php endforeach; ?>
				</select>
			</div>

			<div class="bcboost-field">
				<label class="bcboost-field-label"><?php esc_html_e( 'Varnish VCL snippet', 'basecloud-boost' ); ?></label>
				<span class="bcboost-field-desc"><?php esc_html_e( 'Add this to your Varnish default.vcl and reload Varnish so it trusts this server and honours PURGE/BAN.', 'basecloud-boost' ); ?></span>
				<textarea readonly class="bcboost-textarea bcboost-input--wide" rows="10" style="margin-top:10px;font-family:monospace;" onclick="this.select();"><?php echo esc_textarea( \BaseCloud\Boost\Compatibility\Varnish::get_vcl_snippet() ); ?></textarea>
			</div>
		</div>

		<div class="bcboost-card bcboost-card--accent-purple">
			<h3><span class="bcboost-section-icon">💓</span> <?php esc_html_e( 'Heartbeat Control', 'basecloud-boost' ); ?></h3>

			<div class="bcboost-field bcboost-field--toggle">
				<label>
					<span class="bcboost-field-label"><?php esc_html_e( 'Optimize Heartbeat', 'basecloud-boost' ); ?></span>
					<span class="bcboost-field-desc"><?php esc_html_e( 'Reduce WordPress Heartbeat API frequency to decrease server load from admin AJAX polling.', 'basecloud-boost' ); ?></span>
				</label>
				<label class="bcboost-toggle">
					<input type="checkbox" name="heartbeat_control" value="1" <?php checked( ! empty( $options['heartbeat_control'] ) ); ?>>
					<span class="bcboost-toggle-slider"></span>
				</label>
			</div>

			<div class="bcboost-field">
				<label class="bcboost-field-label" for="heartbeat_interval"><?php esc_html_e( 'Heartbeat Interval (seconds)', 'basecloud-boost' ); ?></label>
				<span class="bcboost-field-desc"><?php esc_html_e( 'Minimum: 15 seconds. Recommended: 60 seconds for production sites.', 'basecloud-boost' ); ?></span>
				<select id="heartbeat_interval" name="heartbeat_interval" class="bcboost-select" style="margin-top:10px;">
					<?php foreach ( [ 15, 30, 60, 120, 300 ] as $secs ) : ?>
						<option value="<?php echo $secs; ?>" <?php selected( (int) ( $options['heartbeat_interval'] ?? 60 ), $secs ); ?>>
							<?php echo esc_html( $secs . ' ' . __( 'seconds', 'basecloud-boost' ) ); ?>
						</option>
					<?php endforeach; ?>
				</select>
			</div>
		</div>

		<div class="bcboost-card">
			<h3><span class="bcboost-section-icon">🔬</span> <?php esc_html_e( 'WordPress Optimizations', 'basecloud-boost' ); ?></h3>

			<div class="bcboost-field bcboost-field--toggle">
				<label>
					<span class="bcboost-field-label"><?php esc_html_e( 'Disable WordPress Emojis', 'basecloud-boost' ); ?></span>
					<span class="bcboost-field-desc"><?php esc_html_e( 'Remove the emoji detection script and DNS prefetch that WordPress loads on every page.', 'basecloud-boost' ); ?></span>
				</label>
				<label class="bcboost-toggle">
					<input type="checkbox" name="disable_emojis" value="1" <?php checked( ! empty( $options['disable_emojis'] ) ); ?>>
					<span class="bcboost-toggle-slider"></span>
				</label>
			</div>

			<div class="bcboost-field bcboost-field--toggle">
				<label>
					<span class="bcboost-field-label"><?php esc_html_e( 'Disable oEmbed / Embeds', 'basecloud-boost' ); ?></span>
					<span class="bcboost-field-desc"><?php esc_html_e( 'Remove the oEmbed script and discovery links to reduce requests.', 'basecloud-boost' ); ?></span>
				</label>
				<label class="bcboost-toggle">
					<input type="checkbox" name="disable_embeds" value="1" <?php checked( ! empty( $options['disable_embeds'] ) ); ?>>
					<span class="bcboost-toggle-slider"></span>
				</label>
			</div>

			<div class="bcboost-field bcboost-field--toggle">
				<label>
					<span class="bcboost-field-label"><?php esc_html_e( 'Disable Dashicons on Frontend', 'basecloud-boost' ); ?></span>
					<span class="bcboost-field-desc"><?php esc_html_e( 'Dequeue the Dashicons stylesheet for non-logged-in visitors. Saves ~20 KB per page for users who do not need the admin icons.', 'basecloud-boost' ); ?></span>
				</label>
				<label class="bcboost-toggle">
					<input type="checkbox" name="disable_dashicons" value="1" <?php checked( ! empty( $options['disable_dashicons'] ) ); ?>>
					<span class="bcboost-toggle-slider"></span>
				</label>
			</div>

			<div class="bcboost-field bcboost-field--toggle">
				<label>
					<span class="bcboost-field-label"><?php esc_html_e( 'Remove Query Strings (legacy)', 'basecloud-boost' ); ?></span>
					<span class="bcboost-field-desc">
						<?php esc_html_e( 'Legacy option — leave OFF. The ?ver= query string is the cache-busting token: it is what makes browsers fetch new CSS/JS after an update. Removing it can leave visitors seeing outdated styles and scripts even after you clear the cache, and it has no PageSpeed benefit (query strings have not affected scores for years). If enabled, BaseCloud Boost substitutes a file-modification-time version for local assets instead of stripping it, so updates still bust the cache.', 'basecloud-boost' ); ?>
					</span>
				</label>
				<label class="bcboost-toggle">
					<input type="checkbox" name="remove_query_strings" value="1" <?php checked( ! empty( $options['remove_query_strings'] ) ); ?>>
					<span class="bcboost-toggle-slider"></span>
				</label>
			</div>

			<div class="bcboost-field">
				<label class="bcboost-field-label" for="limit_post_revisions"><?php esc_html_e( 'Limit Post Revisions', 'basecloud-boost' ); ?></label>
				<span class="bcboost-field-desc"><?php esc_html_e( 'Maximum number of post revisions to keep. Set to 0 to disable revisions.', 'basecloud-boost' ); ?></span>
				<input type="number" id="limit_post_revisions" name="limit_post_revisions" class="bcboost-input" value="<?php echo (int) ( $options['limit_post_revisions'] ?? 10 ); ?>" min="0" max="100" style="margin-top:10px;">
			</div>
		</div>

		<div class="bcboost-card bcboost-card--accent-blue">
			<h3><span class="bcboost-section-icon">🎯</span> <?php esc_html_e( 'Critical CSS', 'basecloud-boost' ); ?></h3>

			<div class="bcboost-field bcboost-field--toggle">
				<label>
					<span class="bcboost-field-label"><?php esc_html_e( 'Enable Critical CSS', 'basecloud-boost' ); ?></span>
					<span class="bcboost-field-desc"><?php esc_html_e( 'Inline critical above-the-fold CSS in the <head>. Required before Async CSS (File Optimization) can take effect — without it, async delivery is automatically held off to protect page-builder layouts.', 'basecloud-boost' ); ?></span>
				</label>
				<label class="bcboost-toggle">
					<input type="checkbox" name="critical_css_enabled" value="1" <?php checked( ! empty( $options['critical_css_enabled'] ) ); ?>>
					<span class="bcboost-toggle-slider"></span>
				</label>
			</div>

			<div class="bcboost-field">
				<label class="bcboost-field-label" for="critical_css"><?php esc_html_e( 'Site-Wide Fallback CSS', 'basecloud-boost' ); ?></label>
				<span class="bcboost-field-desc"><?php esc_html_e( 'Above-the-fold CSS used when no per-template CSS below covers a page. Resolution order per page: per-URL override → template CSS → "Everything else" template → this fallback.', 'basecloud-boost' ); ?></span>
				<textarea id="critical_css" name="critical_css" class="bcboost-textarea bcboost-input--wide" rows="8" style="margin-top:10px;font-family:monospace;"><?php echo esc_textarea( $options['critical_css'] ?? '' ); ?></textarea>
			</div>

			<div class="bcboost-field bcboost-field--toggle">
				<label>
					<span class="bcboost-field-label"><?php esc_html_e( 'Built-In Critical CSS Generator (Beta)', 'basecloud-boost' ); ?></span>
					<span class="bcboost-field-desc"><?php esc_html_e( 'Let Boost create per-template critical CSS itself — pure PHP, right on this server, no external service. It reads each template\'s page, keeps only the stylesheet rules the above-the-fold content actually uses, and fills the Per-Template store below when you press Generate. It never switches anything else on: you stay in control — review the results, then enable Critical CSS (above) and, if you want the full speed win, Async CSS under File Optimization. Pages the generator does not cover automatically keep safe render-blocking CSS. A configured service endpoint below takes precedence when both are set.', 'basecloud-boost' ); ?></span>
				</label>
				<label class="bcboost-toggle">
					<input type="checkbox" name="critical_css_auto" value="1" <?php checked( ! empty( $options['critical_css_auto'] ) ); ?>>
					<span class="bcboost-toggle-slider"></span>
				</label>
			</div>

			<div class="bcboost-field">
				<label class="bcboost-field-label" for="critical_css_remote_endpoint"><?php esc_html_e( 'Generation Service Endpoint (optional)', 'basecloud-boost' ); ?></label>
				<span class="bcboost-field-desc"><?php esc_html_e( 'OFF by default (leave blank). URL of a critical-CSS generation service. When set, a "Generate for all templates" button appears in the Per-Template Critical CSS section below. Responses are size-capped and sanitized before storage.', 'basecloud-boost' ); ?></span>
				<input type="url" id="critical_css_remote_endpoint" name="critical_css_remote_endpoint" class="bcboost-input bcboost-input--wide" style="margin-top:10px;" placeholder="https://" value="<?php echo esc_attr( (string) ( $options['critical_css_remote_endpoint'] ?? '' ) ); ?>">
			</div>
		</div>

		<div class="bcboost-form-footer">
			<button type="submit" class="bcboost-btn bcboost-btn--primary">
				<span class="dashicons dashicons-saved"></span>
				<?php esc_html_e( 'Save Settings', 'basecloud-boost' ); ?>
			</button>
		</div>
	</form>

	<?php
	// ── Per-Template Critical CSS (separate form — its own store, not bcboost_options) ──
	$bcb_ccss_class  = '\BaseCloud\Boost\Optimizer\Critical_CSS';
	$bcb_ccss_ok     = class_exists( $bcb_ccss_class );
	$bcb_ccss_store  = $bcb_ccss_ok ? $bcb_ccss_class::get_store() : [ 'templates' => [], 'urls' => [], 'stale' => null ];
	$bcb_ccss_labels = $bcb_ccss_ok ? $bcb_ccss_class::template_labels() : [];
	$bcb_ccss_stale  = $bcb_ccss_ok ? $bcb_ccss_class::get_stale() : null;
	$bcb_ccss_notice = get_transient( 'bcboost_ccss_notice' );
	if ( false !== $bcb_ccss_notice ) {
		delete_transient( 'bcboost_ccss_notice' );
	}
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- display-only flag set by our own redirects.
	$bcb_ccss_state = isset( $_GET['BCBOOST_ccss'] ) ? sanitize_key( (string) $_GET['BCBOOST_ccss'] ) : '';
	?>
	<div class="bcboost-card bcboost-card--accent-blue">
		<h3><span class="bcboost-section-icon">🧩</span> <?php esc_html_e( 'Per-Template Critical CSS', 'basecloud-boost' ); ?></h3>

		<?php if ( 'saved' === $bcb_ccss_state || 'generated' === $bcb_ccss_state ) : ?>
			<div class="notice notice-success inline"><p><?php esc_html_e( 'Per-template critical CSS saved. Page cache purged so visitors get the new inline CSS.', 'basecloud-boost' ); ?></p></div>
		<?php elseif ( 'error' === $bcb_ccss_state ) : ?>
			<div class="notice notice-error inline"><p><?php esc_html_e( 'Some critical CSS entries could not be saved.', 'basecloud-boost' ); ?></p></div>
		<?php endif; ?>
		<?php if ( is_string( $bcb_ccss_notice ) && '' !== $bcb_ccss_notice ) : ?>
			<div class="notice notice-info inline"><p><?php echo esc_html( $bcb_ccss_notice ); ?></p></div>
		<?php endif; ?>

		<?php if ( null !== $bcb_ccss_stale ) : ?>
			<div class="notice notice-warning inline">
				<p>
					<strong><?php esc_html_e( 'Critical CSS may be stale.', 'basecloud-boost' ); ?></strong>
					<?php
					printf(
						/* translators: 1: trigger description, 2: date */
						esc_html__( 'Trigger: %1$s on %2$s. The stored CSS was extracted from the previous stylesheets — regenerate any entries older than that date, then re-check the affected pages.', 'basecloud-boost' ),
						esc_html( $bcb_ccss_stale['reason'] ),
						esc_html( wp_date( (string) get_option( 'date_format' ) . ' H:i', $bcb_ccss_stale['time'] ) )
					);
					?>
				</p>
				<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="margin:0 0 8px;">
					<?php wp_nonce_field( 'BCBOOST_critical_css' ); ?>
					<input type="hidden" name="action" value="BCBOOST_dismiss_ccss_stale">
					<button type="submit" class="button"><?php esc_html_e( 'Dismiss — CSS verified current', 'basecloud-boost' ); ?></button>
				</form>
			</div>
		<?php endif; ?>

		<p class="bcboost-field-desc">
			<?php esc_html_e( 'One critical-CSS block per template keeps the store small while covering every layout. Generate with the team tool (tools/generate-critical-css) or a paste from your own extraction, then save. Pages whose template has CSS stored get async CSS (when enabled); pages without coverage automatically keep render-blocking CSS — nothing can break.', 'basecloud-boost' ); ?>
		</p>

		<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
			<?php wp_nonce_field( 'BCBOOST_critical_css' ); ?>
			<input type="hidden" name="action" value="BCBOOST_save_critical_css">

			<?php foreach ( $bcb_ccss_labels as $bcb_tpl => $bcb_label ) :
				$bcb_entry = $bcb_ccss_store['templates'][ $bcb_tpl ] ?? null;
				$bcb_has   = is_array( $bcb_entry ) && ! empty( $bcb_entry['css'] );
				?>
				<details style="margin:10px 0;border:1px solid #dcdcde;border-radius:4px;padding:8px 12px;">
					<summary style="cursor:pointer;font-weight:600;">
						<?php echo esc_html( $bcb_label ); ?> (<code><?php echo esc_html( $bcb_tpl ); ?></code>) —
						<?php if ( $bcb_has ) : ?>
							<span style="color:#00a32a;">✔ <?php echo esc_html( size_format( strlen( (string) $bcb_entry['css'] ) ) ); ?></span>
							<?php echo esc_html( sprintf(
								/* translators: 1: date, 2: source */
								__( 'saved %1$s (%2$s)', 'basecloud-boost' ),
								wp_date( (string) get_option( 'date_format' ), (int) ( $bcb_entry['updated'] ?? 0 ) ),
								(string) ( $bcb_entry['source'] ?? 'manual' )
							) ); ?>
							<?php if ( $bcb_ccss_ok && $bcb_ccss_class::is_entry_stale( $bcb_entry ) ) : ?>
								<span style="color:#dba617;">⚠ <?php esc_html_e( 'possibly stale', 'basecloud-boost' ); ?></span>
							<?php endif; ?>
						<?php else : ?>
							<span style="color:#8c8f94;"><?php esc_html_e( 'empty — pages fall back to "Everything else", then Site-Wide Fallback, else stay render-blocking', 'basecloud-boost' ); ?></span>
						<?php endif; ?>
					</summary>
					<textarea name="BCBOOST_ccss_tpl[<?php echo esc_attr( $bcb_tpl ); ?>]" class="bcboost-textarea bcboost-input--wide" rows="6" style="margin-top:8px;font-family:monospace;" placeholder="<?php esc_attr_e( '/* Above-the-fold CSS for this template. Leave empty to clear. */', 'basecloud-boost' ); ?>"><?php echo esc_textarea( $bcb_has ? (string) $bcb_entry['css'] : '' ); ?></textarea>
				</details>
			<?php endforeach; ?>

			<?php if ( ! empty( $bcb_ccss_store['urls'] ) ) : ?>
				<h4 style="margin:16px 0 4px;"><?php esc_html_e( 'Per-URL overrides (set via WP-CLI)', 'basecloud-boost' ); ?></h4>
				<table class="widefat striped" style="max-width:720px;">
					<thead><tr><th><?php esc_html_e( 'Path', 'basecloud-boost' ); ?></th><th><?php esc_html_e( 'Size', 'basecloud-boost' ); ?></th><th><?php esc_html_e( 'Updated', 'basecloud-boost' ); ?></th><th></th></tr></thead>
					<tbody>
					<?php foreach ( $bcb_ccss_store['urls'] as $bcb_path => $bcb_uentry ) :
						$bcb_del = wp_nonce_url(
							add_query_arg(
								[ 'action' => 'BCBOOST_delete_critical_css_url', 'ccss_url' => rawurlencode( (string) $bcb_path ) ],
								admin_url( 'admin-post.php' )
							),
							'BCBOOST_critical_css'
						);
						?>
						<tr>
							<td><code><?php echo esc_html( (string) $bcb_path ); ?></code></td>
							<td><?php echo esc_html( size_format( strlen( (string) ( $bcb_uentry['css'] ?? '' ) ) ) ); ?></td>
							<td><?php echo esc_html( wp_date( (string) get_option( 'date_format' ), (int) ( $bcb_uentry['updated'] ?? 0 ) ) ); ?></td>
							<td><a href="<?php echo esc_url( $bcb_del ); ?>" onclick="return confirm('<?php echo esc_js( __( 'Delete this per-URL override?', 'basecloud-boost' ) ); ?>');"><?php esc_html_e( 'Delete', 'basecloud-boost' ); ?></a></td>
						</tr>
					<?php endforeach; ?>
					</tbody>
				</table>
			<?php endif; ?>

			<div class="bcboost-form-footer">
				<button type="submit" class="bcboost-btn bcboost-btn--primary">
					<span class="dashicons dashicons-saved"></span>
					<?php esc_html_e( 'Save Per-Template CSS', 'basecloud-boost' ); ?>
				</button>
			</div>
		</form>

		<?php
		$bcb_ccss_remote = $bcb_ccss_ok && '' !== $bcb_ccss_class::remote_endpoint();
		$bcb_ccss_local  = ! empty( $options['critical_css_auto'] );
		?>
		<?php if ( $bcb_ccss_remote || $bcb_ccss_local ) : ?>
			<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="margin-top:12px;">
				<?php wp_nonce_field( 'BCBOOST_critical_css' ); ?>
				<input type="hidden" name="action" value="BCBOOST_generate_critical_css">
				<button type="submit" class="button button-secondary" onclick="return confirm('<?php echo esc_js( __( 'Generate critical CSS for every template? Existing entries will be overwritten and the page cache purged.', 'basecloud-boost' ) ); ?>');">
					<?php echo $bcb_ccss_remote
						? esc_html__( 'Generate for all templates (remote service)', 'basecloud-boost' )
						: esc_html__( 'Generate for all templates (built-in, Beta)', 'basecloud-boost' ); ?>
				</button>
				<span class="bcboost-field-desc" style="display:block;margin-top:4px;">
					<?php echo $bcb_ccss_remote
						? esc_html__( 'Runs one render per template against the configured endpoint. Verify each template afterwards — generated critical CSS is only as good as the render.', 'basecloud-boost' )
						: esc_html__( 'Extracts above-the-fold CSS per template with the built-in PHP generator. Review each result below afterwards — then choose yourself whether to enable Critical CSS and Async CSS. Nothing is switched on automatically.', 'basecloud-boost' ); ?>
				</span>
			</form>
		<?php endif; ?>
	</div>

	<?php
	// ── Fleet Ops (BaseCloud CRM) — separate forms: settings save + pairing actions ──
	$bcb_fo_enabled = ! empty( $options['fleet_ops_enabled'] );
	$bcb_fo_strict  = ! empty( $options['fleet_ops_strict'] );
	$bcb_fo_key_set = \BaseCloud\Boost\Core\Crypto::has_secret( (string) ( $options['fleet_ops_key'] ?? '' ) );

	// Show-once pairing key: stored encrypted in a short-lived transient by the
	// generate handler, decrypted here for a single render, then deleted.
	$bcb_fo_new_key = '';
	$bcb_fo_blob    = get_transient( 'bcboost_fleet_ops_new_key' );
	if ( is_string( $bcb_fo_blob ) && '' !== $bcb_fo_blob ) {
		delete_transient( 'bcboost_fleet_ops_new_key' );
		$bcb_fo_new_key = \BaseCloud\Boost\Core\Crypto::decrypt( $bcb_fo_blob );
	}

	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- display-only flag set by our own redirects.
	$bcb_fo_state = isset( $_GET['BCBOOST_fleet_ops'] ) ? sanitize_key( (string) $_GET['BCBOOST_fleet_ops'] ) : '';
	$bcb_fo_audit = class_exists( '\BaseCloud\Boost\Core\Fleet_Ops' ) ? \BaseCloud\Boost\Core\Fleet_Ops::get_audit( 5 ) : [];
	?>
	<div class="bcboost-card bcboost-card--accent-purple">
		<h3>
			<span class="bcboost-section-icon">🛰️</span> <?php esc_html_e( 'Fleet Ops (BaseCloud CRM)', 'basecloud-boost' ); ?>
			<?php if ( ! defined( 'BCBOOST_FLEET_OPS_READY' ) || ! BCBOOST_FLEET_OPS_READY ) : ?>
				<span class="bcboost-feature-badge" style="background:var(--bcboost-warning-light);color:var(--bcboost-warning-ink,var(--bcboost-warning));border:1px solid var(--bcboost-warning);margin-left:auto;">
					<?php esc_html_e( 'Unavailable Right Now', 'basecloud-boost' ); ?>
				</span>
			<?php endif; ?>
		</h3>

		<?php if ( ! defined( 'BCBOOST_FLEET_OPS_READY' ) || ! BCBOOST_FLEET_OPS_READY ) : ?>
			<?php
			// The BaseCloud CRM (the other side of this API) is still being built.
			// The plugin-side code ships and stays dormant — API disabled by
			// default, no key can be paired — but the controls are hidden so
			// nobody pairs against a service that does not exist yet. Flip by
			// defining BCBOOST_FLEET_OPS_READY as true (wp-config or a release
			// that ships the constant) once the CRM goes live.
			?>
			<p class="bcboost-field-desc">
				<?php esc_html_e( 'Coming soon: BaseCloud will monitor and care for this site remotely — health checks, cache clearing, cache warming and scheduled speed tests, all from one central dashboard, with read-only + safe actions and a revocable pairing key. This feature is not available yet; it activates in a future update once the BaseCloud service goes live. Nothing to configure here until then.', 'basecloud-boost' ); ?>
			</p>
		<?php else : ?>

		<?php if ( 'revoked' === $bcb_fo_state ) : ?>
			<div class="notice notice-success inline"><p><?php esc_html_e( 'Fleet Ops pairing key revoked. All bcboost/v1 API requests are now refused until a new key is generated and paired.', 'basecloud-boost' ); ?></p></div>
		<?php endif; ?>

		<?php if ( 'paired' === $bcb_fo_state && '' !== $bcb_fo_new_key ) : ?>
			<div class="notice notice-warning inline">
				<p>
					<strong><?php esc_html_e( 'New pairing key — shown ONCE.', 'basecloud-boost' ); ?></strong>
					<?php esc_html_e( 'Copy it into the BaseCloud CRM site registry now. It is stored encrypted here and can never be displayed again — if it is lost, generate a new one.', 'basecloud-boost' ); ?>
				</p>
				<p>
					<input type="text" readonly class="bcboost-input bcboost-input--wide" style="font-family:monospace;" value="<?php echo esc_attr( $bcb_fo_new_key ); ?>" onclick="this.select();">
				</p>
			</div>
		<?php elseif ( 'paired' === $bcb_fo_state ) : ?>
			<div class="notice notice-error inline"><p><?php esc_html_e( 'The one-time key display has expired (it lives for 5 minutes and one page view). Generate a new pairing key.', 'basecloud-boost' ); ?></p></div>
		<?php endif; ?>

		<p class="bcboost-field-desc">
			<?php esc_html_e( 'Lets the BaseCloud CRM monitor and operate this site remotely: health telemetry, cache purge, cache preload, and scheduled PSI runs. Read + safe verbs only — no settings can be changed through this API. OFF by default; every request requires the pairing key; revoking the key cuts access instantly.', 'basecloud-boost' ); ?>
		</p>

		<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
			<?php wp_nonce_field( 'BCBOOST_save_settings' ); ?>
			<input type="hidden" name="action" value="BCBOOST_save_settings">
			<input type="hidden" name="BCBOOST_tab_checkboxes" value="fleet_ops_enabled,fleet_ops_strict">

			<div class="bcboost-field bcboost-field--toggle">
				<label>
					<span class="bcboost-field-label"><?php esc_html_e( 'Enable Fleet Ops API', 'basecloud-boost' ); ?></span>
					<span class="bcboost-field-desc"><?php esc_html_e( 'Kill-switch for the bcboost/v1 REST API. While off, every request is refused (403) even with a valid key.', 'basecloud-boost' ); ?></span>
				</label>
				<label class="bcboost-toggle">
					<input type="checkbox" name="fleet_ops_enabled" value="1" <?php checked( $bcb_fo_enabled ); ?>>
					<span class="bcboost-toggle-slider"></span>
				</label>
			</div>

			<div class="bcboost-field bcboost-field--toggle">
				<label>
					<span class="bcboost-field-label"><?php esc_html_e( 'Strict Mode (signed requests)', 'basecloud-boost' ); ?></span>
					<span class="bcboost-field-desc"><?php esc_html_e( 'Additionally require a timestamp (±5 min), a single-use nonce, and an HMAC-SHA256 signature on every request. Turn on once the CRM side signs its calls — unsigned requests are then refused.', 'basecloud-boost' ); ?></span>
				</label>
				<label class="bcboost-toggle">
					<input type="checkbox" name="fleet_ops_strict" value="1" <?php checked( $bcb_fo_strict ); ?>>
					<span class="bcboost-toggle-slider"></span>
				</label>
			</div>

			<div class="bcboost-form-footer">
				<button type="submit" class="bcboost-btn bcboost-btn--primary">
					<span class="dashicons dashicons-saved"></span>
					<?php esc_html_e( 'Save Fleet Ops Settings', 'basecloud-boost' ); ?>
				</button>
			</div>
		</form>

		<div class="bcboost-field">
			<span class="bcboost-field-label"><?php esc_html_e( 'Pairing key', 'basecloud-boost' ); ?></span>
			<span class="bcboost-field-desc" style="margin-top:8px;display:block;">
				<?php echo $bcb_fo_key_set
					? esc_html__( 'A pairing key is set (stored encrypted — it is never displayed or exported).', 'basecloud-boost' )
					: esc_html__( 'No pairing key set — the API refuses all requests until one is generated and pasted into the CRM.', 'basecloud-boost' ); ?>
			</span>
			<div style="display:flex;gap:8px;margin-top:10px;flex-wrap:wrap;">
				<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="margin:0;">
					<?php wp_nonce_field( 'BCBOOST_fleet_ops' ); ?>
					<input type="hidden" name="action" value="BCBOOST_fleet_ops_generate_key">
					<button type="submit" class="button button-secondary" <?php echo $bcb_fo_key_set ? 'onclick="return confirm(\'' . esc_js( __( 'Generate a NEW pairing key? The current key stops working immediately and the CRM must be updated with the new one.', 'basecloud-boost' ) ) . '\');"' : ''; ?>>
						<?php echo $bcb_fo_key_set
							? esc_html__( 'Regenerate pairing key', 'basecloud-boost' )
							: esc_html__( 'Generate pairing key', 'basecloud-boost' ); ?>
					</button>
				</form>
				<?php if ( $bcb_fo_key_set ) : ?>
					<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="margin:0;">
						<?php wp_nonce_field( 'BCBOOST_fleet_ops' ); ?>
						<input type="hidden" name="action" value="BCBOOST_fleet_ops_revoke_key">
						<button type="submit" class="button" onclick="return confirm('<?php echo esc_js( __( 'Revoke the pairing key? All CRM access to this site stops immediately.', 'basecloud-boost' ) ); ?>');">
							<?php esc_html_e( 'Revoke key', 'basecloud-boost' ); ?>
						</button>
					</form>
				<?php endif; ?>
			</div>
		</div>

		<div class="bcboost-field">
			<span class="bcboost-field-label"><?php esc_html_e( 'REST endpoint', 'basecloud-boost' ); ?></span>
			<span class="bcboost-field-desc"><?php esc_html_e( 'Base URL the CRM calls (GET /health, POST /purge, POST /preload, POST /psi). Requests authenticate via the X-BCBoost-Key header.', 'basecloud-boost' ); ?></span>
			<input type="text" readonly class="bcboost-input bcboost-input--wide" style="margin-top:10px;font-family:monospace;" value="<?php echo esc_attr( rest_url( 'bcboost/v1/' ) ); ?>" onclick="this.select();">
		</div>

		<div class="bcboost-field">
			<span class="bcboost-field-label"><?php esc_html_e( 'Recent API activity', 'basecloud-boost' ); ?></span>
			<?php if ( empty( $bcb_fo_audit ) ) : ?>
				<span class="bcboost-field-desc" style="margin-top:8px;display:block;"><?php esc_html_e( 'No Fleet Ops requests recorded yet.', 'basecloud-boost' ); ?></span>
			<?php else : ?>
				<table class="widefat striped" style="max-width:720px;margin-top:10px;">
					<thead><tr><th><?php esc_html_e( 'Time', 'basecloud-boost' ); ?></th><th><?php esc_html_e( 'Route', 'basecloud-boost' ); ?></th><th><?php esc_html_e( 'Result', 'basecloud-boost' ); ?></th><th><?php esc_html_e( 'IP', 'basecloud-boost' ); ?></th></tr></thead>
					<tbody>
					<?php foreach ( $bcb_fo_audit as $bcb_fo_row ) : ?>
						<tr>
							<td><?php echo esc_html( wp_date( (string) get_option( 'date_format' ) . ' H:i:s', (int) ( $bcb_fo_row['time'] ?? 0 ) ) ); ?></td>
							<td><code><?php echo esc_html( (string) ( $bcb_fo_row['route'] ?? '' ) ); ?></code></td>
							<td><?php echo esc_html( (string) ( $bcb_fo_row['result'] ?? '' ) ); ?></td>
							<td><?php echo esc_html( (string) ( $bcb_fo_row['ip'] ?? '' ) ); ?></td>
						</tr>
					<?php endforeach; ?>
					</tbody>
				</table>
			<?php endif; ?>
		</div>

		<?php endif; // BCBOOST_FLEET_OPS_READY ?>
	</div>
</div>
