<?php
/**
 * Cache module — CDN tab view
 *
 * @var Blaminhor_Essentials_Module_Cache $module
 * @var array                             $settings
 *
 * @package BlaminhorEssentials
 */

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

<h2><?php esc_html_e( 'Generic CDN URL rewrite', 'blaminhor-essentials' ); ?></h2>
<p class="description">
	<?php esc_html_e( 'Serves your images, CSS, JS and fonts from a CDN (BunnyCDN, KeyCDN, Cloudflare, StackPath…) instead of from your server. Visitors get assets from the closest server to them. The WordPress admin and the HTML itself never go through the CDN.', 'blaminhor-essentials' ); ?>
</p>

<table class="form-table">
	<tr>
		<th scope="row"><?php esc_html_e( 'Enable', 'blaminhor-essentials' ); ?></th>
		<td>
			<label>
				<input type="checkbox" name="cdn_enabled" value="1" <?php checked( $settings['cdn_enabled'] ); ?>>
				<?php esc_html_e( 'Rewrite asset URLs to the CDN', 'blaminhor-essentials' ); ?>
			</label>
		</td>
	</tr>
	<tr>
		<th scope="row">
			<label for="be-cdn-url"><?php esc_html_e( 'CDN URL', 'blaminhor-essentials' ); ?></label>
		</th>
		<td>
			<input
				type="url"
				id="be-cdn-url"
				name="cdn_url"
				value="<?php echo esc_attr( $settings['cdn_url'] ); ?>"
				class="regular-text code"
				placeholder="https://cdn.example.com">
			<p class="description"><?php esc_html_e( 'The CDN address you configured at your provider (e.g. cdn.mysite.com). HTTPS is added automatically if you forget it.', 'blaminhor-essentials' ); ?></p>
		</td>
	</tr>
	<tr>
		<th scope="row">
			<label for="be-cdn-excluded-extensions"><?php esc_html_e( 'Exclusions', 'blaminhor-essentials' ); ?></label>
		</th>
		<td>
			<textarea
				id="be-cdn-excluded-extensions"
				name="cdn_excluded_extensions"
				rows="3"
				class="large-text code"
				placeholder="pdf&#10;/wp-content/plugins/somthing-broken/"><?php echo esc_textarea( $settings['cdn_excluded_extensions'] ); ?></textarea>
			<p class="description"><?php esc_html_e( 'File extensions or URL substrings to never rewrite. One per line. .html, .php, .xml, .json are always excluded.', 'blaminhor-essentials' ); ?></p>
		</td>
	</tr>
</table>

<div class="notice notice-info inline" style="margin-top:24px;">
	<p>
		<strong><?php esc_html_e( 'Tip:', 'blaminhor-essentials' ); ?></strong>
		<?php esc_html_e( 'Make sure your CDN is configured to pull from your origin (Origin URL = your site URL, no path prefix) and to honour the Cache-Control / Expires headers set by the Page Cache tab.', 'blaminhor-essentials' ); ?>
	</p>
</div>

<h2><?php esc_html_e( 'Cloudflare', 'blaminhor-essentials' ); ?></h2>
<p class="description">
	<?php
	$detected_label = '';
	if ( isset( $module->host_detector ) && method_exists( $module->host_detector, 'label' ) ) {
		$detected_label = (string) $module->host_detector->label();
	}
	if ( '' !== $detected_label ) {
		printf(
			/* translators: %s: detected hosting provider */
			esc_html__( 'Detected hosting provider: %s.', 'blaminhor-essentials' ),
			'<strong>' . esc_html( $detected_label ) . '</strong>'
		);
		echo ' ';
	}
	esc_html_e( 'A focused Cloudflare integration: targeted per-URL purge on every save, one-click Development Mode toggle, and one-click "Apply recommended Cloudflare settings for WordPress". The API token is encrypted at rest and never displayed in plain text. APO, WAF rules and Analytics dashboards stay out of scope — those live in Cloudflare\'s official plugin.', 'blaminhor-essentials' );
	?>
</p>

<?php
// Warn when the official Cloudflare plugin is also active: running both
// auto-purges burns API quota and confuses the post-publish behaviour.
if ( ! function_exists( 'is_plugin_active' ) ) {
	require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
$cf_official_active = is_plugin_active( 'cloudflare/cloudflare.php' );
if ( $cf_official_active ) :
	?>
	<div class="notice notice-warning inline" style="margin-top:12px;">
		<p>
			<strong><?php esc_html_e( 'Cloudflare official plugin detected.', 'blaminhor-essentials' ); ?></strong>
			<?php esc_html_e( 'The built-in Cloudflare integration is meant for users who would rather not install a second plugin just for cache purging. Since you already run the official Cloudflare plugin (which covers APO, WAF rules and Analytics), keep it and leave the integration below OFF — running both auto-purges hits the API twice on every publish.', 'blaminhor-essentials' ); ?>
		</p>
	</div>
<?php endif; ?>

<table class="form-table">
	<tr>
		<th scope="row"><?php esc_html_e( 'Enable Cloudflare integration', 'blaminhor-essentials' ); ?></th>
		<td>
			<label>
				<input type="checkbox" name="cloudflare_enabled" value="1" <?php checked( ! empty( $settings['cloudflare_enabled'] ) ); ?>>
				<?php esc_html_e( 'Auto-purge the Cloudflare zone on content changes (targeted per URL)', 'blaminhor-essentials' ); ?>
			</label>
		</td>
	</tr>
	<tr>
		<th scope="row">
			<label for="be-cf-zone-id"><?php esc_html_e( 'Zone ID', 'blaminhor-essentials' ); ?></label>
		</th>
		<td>
			<input type="text" id="be-cf-zone-id" name="cloudflare_zone_id" class="regular-text code" autocomplete="off"
				value="<?php echo esc_attr( isset( $settings['cloudflare_zone_id'] ) ? (string) $settings['cloudflare_zone_id'] : '' ); ?>">
			<p class="description"><?php esc_html_e( 'Found on the Cloudflare dashboard, in the right-hand sidebar of your domain overview.', 'blaminhor-essentials' ); ?></p>
		</td>
	</tr>
	<tr>
		<th scope="row">
			<label for="be-cf-api-token"><?php esc_html_e( 'API token', 'blaminhor-essentials' ); ?></label>
		</th>
		<td>
			<?php $has_token = ! empty( $settings['cloudflare_api_token'] ); ?>
			<input type="password" id="be-cf-api-token" name="cloudflare_api_token" class="regular-text code" autocomplete="off"
				value="<?php echo $has_token ? '__BE_KEEP__' : ''; ?>">
			<p class="description">
				<?php esc_html_e( 'Go to https://dash.cloudflare.com/profile/api-tokens. For purge only, the "Zone Cache Purge" permission is enough. To also use Development Mode and Apply Recommended Settings below, add "Zone Settings: Edit" on the same zone. If the field already shows __BE_KEEP__, leave it alone — that just means the existing token is not being shown in plain text.', 'blaminhor-essentials' ); ?>
			</p>
		</td>
	</tr>
</table>

<?php
// Cloudflare advanced actions stay visible even when the integration is not
// yet configured, so users can discover the feature surface. Buttons are
// disabled until enable + zone + token are all set; an inline notice spells
// out what is missing.
$cf_zone       = isset( $settings['cloudflare_zone_id'] ) ? (string) $settings['cloudflare_zone_id'] : '';
$cf_configured = ! empty( $settings['cloudflare_enabled'] )
	&& '' !== $cf_zone
	&& ! empty( $settings['cloudflare_api_token'] );
$cf_disabled_attr = $cf_configured ? '' : ' disabled aria-disabled="true"';
$cf_nonce         = wp_create_nonce( 'blaminhor_essentials_module_cache' );
?>
<h3 style="margin-top:24px;"><?php esc_html_e( 'Cloudflare advanced actions', 'blaminhor-essentials' ); ?></h3>
<p class="description">
	<?php esc_html_e( 'These actions call the Cloudflare API directly. Their availability depends on the permissions of the token configured above.', 'blaminhor-essentials' ); ?>
</p>

<?php if ( ! $cf_configured ) : ?>
	<div class="notice notice-info inline" style="margin-top:8px;">
		<p>
			<?php esc_html_e( 'Enable the Cloudflare integration and provide both a Zone ID and an API token above to activate the actions below.', 'blaminhor-essentials' ); ?>
		</p>
	</div>
<?php endif; ?>

<div class="be-cf-token-caps" style="margin-top:8px;">
	<button type="button" class="button" id="be-cf-refresh-caps" data-nonce="<?php echo esc_attr( $cf_nonce ); ?>"<?php echo $cf_disabled_attr; ?>>
		<?php esc_html_e( 'Check token permissions', 'blaminhor-essentials' ); ?>
	</button>
	<span class="be-cf-token-caps-status" style="margin-left:8px;"></span>
</div>

<table class="form-table" style="margin-top:16px;">
	<tr>
		<th scope="row"><?php esc_html_e( 'Development mode', 'blaminhor-essentials' ); ?></th>
		<td>
			<button type="button" class="button button-secondary" id="be-cf-dev-mode-on" data-nonce="<?php echo esc_attr( $cf_nonce ); ?>"<?php echo $cf_disabled_attr; ?>>
				<?php esc_html_e( 'Turn ON (3 hours)', 'blaminhor-essentials' ); ?>
			</button>
			<button type="button" class="button" id="be-cf-dev-mode-off" data-nonce="<?php echo esc_attr( $cf_nonce ); ?>"<?php echo $cf_disabled_attr; ?>>
				<?php esc_html_e( 'Turn OFF', 'blaminhor-essentials' ); ?>
			</button>
			<p class="description">
				<?php esc_html_e( 'Bypasses the Cloudflare edge cache for 3 hours, so changes hit visitors immediately while you debug. Cloudflare turns it off automatically when the 3 hours are up.', 'blaminhor-essentials' ); ?>
			</p>
		</td>
	</tr>
	<tr>
		<th scope="row"><?php esc_html_e( 'Recommended settings for WordPress', 'blaminhor-essentials' ); ?></th>
		<td>
			<button type="button" class="button button-primary" id="be-cf-apply-recommended" data-nonce="<?php echo esc_attr( $cf_nonce ); ?>"<?php echo $cf_disabled_attr; ?>>
				<?php esc_html_e( 'Apply recommended settings', 'blaminhor-essentials' ); ?>
			</button>
			<?php if ( $cf_configured && isset( $module->cloudflare ) && $module->cloudflare->has_snapshot() ) : ?>
				<button type="button" class="button" id="be-cf-reset-settings" data-nonce="<?php echo esc_attr( $cf_nonce ); ?>">
					<?php esc_html_e( 'Restore previous settings', 'blaminhor-essentials' ); ?>
				</button>
			<?php endif; ?>
			<p class="description">
				<?php esc_html_e( 'One click sets the Cloudflare zone to a WordPress-friendly baseline: 4-hour browser cache, Always Online, Brotli, aggressive cache level, medium security, email obfuscation. Cloudflare Rocket Loader and minification stay OFF — Rocket Loader regularly breaks builders and the minifiers are best left to this plugin. A snapshot of the previous values is saved, so "Restore previous settings" can put everything back.', 'blaminhor-essentials' ); ?>
			</p>
		</td>
	</tr>
</table>

<?php if ( $cf_configured ) : ?>
	<script>
	jQuery(function($){
		function ajaxAction(action, nonce, extra) {
			extra = extra || {};
			extra.action = action;
			extra._ajax_nonce = nonce;
			return $.post(ajaxurl, extra);
		}
		function flash($el, msg, type) {
			$el.css('color', type === 'error' ? '#d63638' : '#00a32a').text(msg);
		}

		$('#be-cf-dev-mode-on').on('click', function(){
			ajaxAction('ap_cache_cf_dev_mode_toggle', $(this).data('nonce'), { enable: '1' })
				.done(function(r){ flash($('.be-cf-token-caps-status'), r.data && r.data.message ? r.data.message : 'OK', r.success ? 'ok' : 'error'); })
				.fail(function(){ flash($('.be-cf-token-caps-status'), 'Request failed', 'error'); });
		});
		$('#be-cf-dev-mode-off').on('click', function(){
			ajaxAction('ap_cache_cf_dev_mode_toggle', $(this).data('nonce'), { enable: '0' })
				.done(function(r){ flash($('.be-cf-token-caps-status'), r.data && r.data.message ? r.data.message : 'OK', r.success ? 'ok' : 'error'); })
				.fail(function(){ flash($('.be-cf-token-caps-status'), 'Request failed', 'error'); });
		});
		$('#be-cf-apply-recommended').on('click', function(){
			if (!window.confirm('<?php echo esc_js( __( 'Apply Cloudflare recommended settings? The current values will be snapshotted so you can restore them.', 'blaminhor-essentials' ) ); ?>')) { return; }
			ajaxAction('ap_cache_cf_apply_recommended', $(this).data('nonce'))
				.done(function(r){ flash($('.be-cf-token-caps-status'), r.data && r.data.message ? r.data.message : 'OK', r.success ? 'ok' : 'error'); setTimeout(function(){ location.reload(); }, 800); })
				.fail(function(){ flash($('.be-cf-token-caps-status'), 'Request failed', 'error'); });
		});
		$('#be-cf-reset-settings').on('click', function(){
			if (!window.confirm('<?php echo esc_js( __( 'Restore the previous Cloudflare settings from the snapshot?', 'blaminhor-essentials' ) ); ?>')) { return; }
			ajaxAction('ap_cache_cf_reset_settings', $(this).data('nonce'))
				.done(function(r){ flash($('.be-cf-token-caps-status'), r.data && r.data.message ? r.data.message : 'OK', r.success ? 'ok' : 'error'); setTimeout(function(){ location.reload(); }, 800); })
				.fail(function(){ flash($('.be-cf-token-caps-status'), 'Request failed', 'error'); });
		});
		$('#be-cf-refresh-caps').on('click', function(){
			ajaxAction('ap_cache_cf_capabilities', $(this).data('nonce'))
				.done(function(r){
					if (r.success && r.data) {
						var c = r.data;
						var parts = [];
						parts.push(c.token_valid ? '<?php echo esc_js( __( 'Token valid', 'blaminhor-essentials' ) ); ?>' : '<?php echo esc_js( __( 'Token invalid', 'blaminhor-essentials' ) ); ?>');
						parts.push((c.can_purge ? '✓ ' : '✗ ') + '<?php echo esc_js( __( 'Purge', 'blaminhor-essentials' ) ); ?>');
						parts.push((c.can_read_settings ? '✓ ' : '✗ ') + '<?php echo esc_js( __( 'Read settings', 'blaminhor-essentials' ) ); ?>');
						parts.push((c.can_write_settings ? '✓ ' : '✗ ') + '<?php echo esc_js( __( 'Write settings', 'blaminhor-essentials' ) ); ?>');
						flash($('.be-cf-token-caps-status'), parts.join(' · '), c.token_valid ? 'ok' : 'error');
					} else {
						flash($('.be-cf-token-caps-status'), 'Probe failed', 'error');
					}
				})
				.fail(function(){ flash($('.be-cf-token-caps-status'), 'Request failed', 'error'); });
		});
	});
	</script>
<?php endif; ?>
