<?php
/**
 * Cache module — Advanced tab view
 *
 * Variables in scope (see class-module-cache.php::render_tab):
 *
 *   @var Blaminhor_Essentials_Module_Cache $module
 *   @var array                             $settings
 *
 * @package BlaminhorEssentials
 */

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

$safe_mode_active = $module->safe_mode->is_active();
$disk_usage       = $module->storage->disk_usage();
$server_software  = $module->environment->get_server_software();
$dropin_installed = $module->dropin_installer->is_installed();
$is_suspended     = $module->conflict_detector->should_suspend_optimizations();
$last_purge       = (int) get_option( 'blaminhor_essentials_cache_last_purge', 0 );
?>

<h2><?php esc_html_e( 'Health check', 'blaminhor-essentials' ); ?></h2>
<p class="description">
	<?php esc_html_e( 'Runs a full health check of the Cache module: all files in place, cache works correctly (1st visit generated + 2nd visit served from cache), purge functional, scheduled tasks running, tables OK, no other cache plugin interfering. You can copy the report to share it with support if you ever have an issue.', 'blaminhor-essentials' ); ?>
</p>

<p>
	<button type="button" class="button button-primary be-cache-health-run">
		<?php esc_html_e( 'Run health check', 'blaminhor-essentials' ); ?>
	</button>
	<button type="button" class="button button-secondary be-cache-health-copy" style="margin-left:8px;display:none;">
		<?php esc_html_e( 'Copy JSON report', 'blaminhor-essentials' ); ?>
	</button>
	<span class="be-cache-health-status" style="margin-left:12px;color:#646970;"></span>
</p>

<div class="be-cache-health-summary" style="display:none;margin:12px 0 8px;font-weight:600;"></div>
<div class="be-cache-health-results" style="display:none;"></div>
<details class="be-cache-health-json" style="display:none;margin-top:12px;">
	<summary style="cursor:pointer;color:#646970;"><?php esc_html_e( 'Show raw JSON', 'blaminhor-essentials' ); ?></summary>
	<textarea readonly class="large-text code be-cache-health-json-payload" rows="14" style="font-family:Consolas,Monaco,monospace;font-size:11px;"></textarea>
</details>

<h2 style="margin-top:32px;"><?php esc_html_e( 'Cache status', 'blaminhor-essentials' ); ?></h2>

<table class="form-table">
	<tr>
		<th scope="row"><?php esc_html_e( 'Server', 'blaminhor-essentials' ); ?></th>
		<td>
			<code><?php echo esc_html( ucfirst( $server_software ) ); ?></code>
			<?php if ( ! $module->environment->supports_htaccess() ) : ?>
				<p class="description"><?php esc_html_e( 'No .htaccess support detected — browser cache and GZIP rules cannot be written automatically.', 'blaminhor-essentials' ); ?></p>
			<?php endif; ?>
		</td>
	</tr>
	<tr>
		<th scope="row"><?php esc_html_e( 'Drop-in', 'blaminhor-essentials' ); ?></th>
		<td>
			<?php if ( $dropin_installed ) : ?>
				<span style="color:#3a8a4a;">●</span> <?php esc_html_e( 'Installed and active.', 'blaminhor-essentials' ); ?>
			<?php elseif ( $is_suspended ) : ?>
				<span style="color:#dba617;">●</span> <?php esc_html_e( 'Yielded to another cache plugin — Reinstall is unavailable while the conflict persists.', 'blaminhor-essentials' ); ?>
			<?php else : ?>
				<span style="color:#c33;">●</span> <?php esc_html_e( 'Not installed (page cache served via PHP fallback).', 'blaminhor-essentials' ); ?>
				<button type="button" class="button button-secondary be-cache-resync-dropin" style="margin-left:8px;">
					<?php esc_html_e( 'Reinstall now', 'blaminhor-essentials' ); ?>
				</button>
			<?php endif; ?>
		</td>
	</tr>
	<tr>
		<th scope="row"><?php esc_html_e( 'Disk usage', 'blaminhor-essentials' ); ?></th>
		<td>
			<code class="be-cache-disk-usage"><?php echo esc_html( blaminhor_essentials_format_size( $disk_usage ) ); ?></code>
			<button type="button" class="button button-secondary be-cache-refresh-stats">
				<?php esc_html_e( 'Refresh', 'blaminhor-essentials' ); ?>
			</button>
			<button type="button" class="button button-primary be-cache-purge-all" style="margin-left:8px;">
				<?php esc_html_e( 'Purge all', 'blaminhor-essentials' ); ?>
			</button>
			<?php if ( $last_purge > 0 ) : ?>
				<p class="description">
					<?php
					printf(
						/* translators: %s: human-readable time difference */
						esc_html__( 'Last manual purge: %s ago.', 'blaminhor-essentials' ),
						esc_html( human_time_diff( $last_purge, time() ) )
					);
					?>
				</p>
			<?php endif; ?>
		</td>
	</tr>
	<tr>
		<th scope="row"><?php esc_html_e( 'Safe mode', 'blaminhor-essentials' ); ?></th>
		<td>
			<label class="blaminhor-essentials-switch">
				<input type="checkbox" class="be-cache-safe-mode-toggle" <?php checked( $safe_mode_active ); ?>>
				<span class="slider"></span>
			</label>
			<p class="description">
				<?php esc_html_e( 'Completely turns the cache off — all visitors see the live version of the site. Useful when you suspect a bug is caused by the cache and want to check without breaking everything. Re-enable when you are done.', 'blaminhor-essentials' ); ?>
			</p>
			<p class="description">
				<?php
				printf(
					/* translators: %s: query string parameter */
					esc_html__( 'Tip: append %s to any URL while logged in as administrator to bypass the cache for the current request only.', 'blaminhor-essentials' ),
					'<code>?be_no_cache=1</code>'
				);
				?>
			</p>
		</td>
	</tr>
</table>

<h2><?php esc_html_e( 'Exclusions', 'blaminhor-essentials' ); ?></h2>
<p class="description">
	<?php esc_html_e( 'Pages you NEVER want to cache, on top of the ones already excluded automatically (cart, checkout, customer account, WP admin, and all logged-in visitors). One URL per line.', 'blaminhor-essentials' ); ?>
</p>

<table class="form-table">
	<tr>
		<th scope="row">
			<label for="be-cache-exclude-urls"><?php esc_html_e( 'Excluded URLs', 'blaminhor-essentials' ); ?></label>
		</th>
		<td>
			<textarea id="be-cache-exclude-urls" name="exclude_urls" rows="4" class="large-text code" placeholder="/some-page&#10;/category/private/(.*)"><?php echo esc_textarea( $settings['exclude_urls'] ); ?></textarea>
			<p class="description"><?php esc_html_e( 'One URL per line. Wildcards * supported. Lines starting with # are ignored.', 'blaminhor-essentials' ); ?></p>
		</td>
	</tr>
	<tr>
		<th scope="row">
			<label for="be-cache-exclude-cookies"><?php esc_html_e( 'Excluded cookies', 'blaminhor-essentials' ); ?></label>
		</th>
		<td>
			<textarea id="be-cache-exclude-cookies" name="exclude_cookies" rows="3" class="large-text code" placeholder="my_membership_session&#10;custom_personalization"><?php echo esc_textarea( $settings['exclude_cookies'] ); ?></textarea>
			<p class="description"><?php esc_html_e( 'Visitors with these cookies bypass the cache. One cookie name per line (substring match).', 'blaminhor-essentials' ); ?></p>
		</td>
	</tr>
	<tr>
		<th scope="row">
			<label for="be-cache-exclude-uas"><?php esc_html_e( 'Excluded user agents', 'blaminhor-essentials' ); ?></label>
		</th>
		<td>
			<textarea id="be-cache-exclude-uas" name="exclude_user_agents" rows="3" class="large-text code" placeholder="lighthouse&#10;Pingdom"><?php echo esc_textarea( $settings['exclude_user_agents'] ); ?></textarea>
			<p class="description"><?php esc_html_e( 'Bots and tools to never serve cached content (substring match against User-Agent).', 'blaminhor-essentials' ); ?></p>
		</td>
	</tr>
</table>

<h2 style="margin-top:32px;"><?php esc_html_e( 'Theme & builder compatibility', 'blaminhor-essentials' ); ?></h2>
<p class="description">
	<?php esc_html_e( 'Each adapter fixes a known compatibility issue with a popular theme or page builder (Avada, Elementor, Divi…) and makes sure their own caches stay in sync with this one. Loaded automatically when the theme or builder is detected. Tick a box to disable a specific adapter if you notice a conflict with another customisation on your site.', 'blaminhor-essentials' ); ?>
</p>

<table class="form-table">
	<?php
	$summary = isset( $module->theme_compat ) ? $module->theme_compat->summary() : array();
	if ( empty( $summary ) ) :
		?>
		<tr>
			<td><em><?php esc_html_e( 'No theme/builder adapter is registered.', 'blaminhor-essentials' ); ?></em></td>
		</tr>
		<?php
	else :
		$disabled_set = array_flip( (array) ( $settings['theme_compat_disabled'] ?? array() ) );
		foreach ( $summary as $row ) :
			$id        = (string) $row['id'];
			$is_active = ! empty( $row['active'] );
			$is_disab  = isset( $disabled_set[ $id ] );
			?>
			<tr>
				<th scope="row"><?php echo esc_html( $row['label'] ); ?></th>
				<td>
					<?php if ( $is_active ) : ?>
						<span style="display:inline-block;background:#d4f4dd;color:#0a6b1d;padding:2px 8px;border-radius:3px;font-size:12px;">
							<?php esc_html_e( 'Detected — adapter active', 'blaminhor-essentials' ); ?>
						</span>
					<?php else : ?>
						<span style="display:inline-block;background:#eee;color:#666;padding:2px 8px;border-radius:3px;font-size:12px;">
							<?php esc_html_e( 'Not detected on this site', 'blaminhor-essentials' ); ?>
						</span>
					<?php endif; ?>
					<br>
					<label style="margin-top:6px;display:inline-block;">
						<input type="checkbox" name="theme_compat_disabled[]" value="<?php echo esc_attr( $id ); ?>" <?php checked( $is_disab ); ?>>
						<?php esc_html_e( 'Disable this adapter', 'blaminhor-essentials' ); ?>
					</label>
				</td>
			</tr>
			<?php
		endforeach;
	endif;
	?>
</table>

<h2 style="margin-top:32px;"><?php esc_html_e( 'Settings backup', 'blaminhor-essentials' ); ?></h2>
<p class="description">
	<?php esc_html_e( 'Export every Cache & Performance setting as a JSON file to replicate your configuration on another site, or share it with support for diagnostic. Importing a file replaces all current cache settings — encrypted secrets (Cloudflare API token) are intentionally excluded and remain untouched.', 'blaminhor-essentials' ); ?>
</p>

<table class="form-table">
	<tr>
		<th scope="row"><?php esc_html_e( 'Export', 'blaminhor-essentials' ); ?></th>
		<td>
			<button type="button" class="button button-secondary be-cache-export-settings">
				<?php esc_html_e( 'Download settings as JSON', 'blaminhor-essentials' ); ?>
			</button>
			<span class="be-cache-export-status" style="margin-left:10px;color:#646970;"></span>
			<p class="description">
				<?php esc_html_e( 'The file contains all toggles, allow/deny lists and module options. No site content, no API key, no user data.', 'blaminhor-essentials' ); ?>
			</p>
		</td>
	</tr>
	<tr>
		<th scope="row"><?php esc_html_e( 'Import', 'blaminhor-essentials' ); ?></th>
		<td>
			<input type="file" accept=".json,application/json" class="be-cache-import-file">
			<button type="button" class="button button-primary be-cache-import-settings" style="margin-left:8px;" disabled>
				<?php esc_html_e( 'Import settings', 'blaminhor-essentials' ); ?>
			</button>
			<p class="description">
				<?php esc_html_e( 'Pick a JSON file previously exported from this plugin. Current settings will be overwritten — this cannot be undone, export your current configuration first if you want a fallback.', 'blaminhor-essentials' ); ?>
			</p>
			<div class="be-cache-import-status" style="margin-top:8px;"></div>
		</td>
	</tr>
</table>
