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

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

$psi_key_set = '' !== $module->audit_psi->get_api_key();
?>

<h2><?php esc_html_e( 'Performance audit', 'blaminhor-essentials' ); ?></h2>
<p class="description">
	<?php esc_html_e( 'Two complementary audits, both producing actionable recommendations linked to the relevant tab of this page.', 'blaminhor-essentials' ); ?>
</p>

<div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:24px;">

	<div class="blaminhor-essentials-card" style="padding:16px;">
		<h3 style="margin-top:0;">🟢 <?php esc_html_e( 'Google PageSpeed Insights', 'blaminhor-essentials' ); ?></h3>
		<p class="description">
			<?php esc_html_e( 'Runs an official Google PageSpeed Insights audit: Performance score, real visitor speed measurements (Core Web Vitals), and around 50 technical checks. Free with a Google API key (25,000 audits per day).', 'blaminhor-essentials' ); ?>
		</p>

		<details <?php echo $psi_key_set ? '' : 'open'; ?> style="margin:12px 0;">
			<summary><strong><?php esc_html_e( 'How to get a free API key (step by step)', 'blaminhor-essentials' ); ?></strong></summary>
			<p style="margin:8px 0 0 0;"><?php esc_html_e( 'No billing account needed for this API.', 'blaminhor-essentials' ); ?></p>
			<ol style="margin:8px 0 0 24px;">
				<li><a href="https://console.cloud.google.com" target="_blank" rel="noopener noreferrer">console.cloud.google.com</a></li>
				<li><?php esc_html_e( 'Create a new project (any name will do) using the project selector at the top, next to the Google Cloud logo. If you have multiple Google accounts, double-check the avatar in the top-right corner — restrictions and quotas live per account.', 'blaminhor-essentials' ); ?></li>
				<li><?php esc_html_e( 'In the Library, search for "PageSpeed Insights API" and click the blue "Enable" button. Wait until the button changes to "Manage" with a green "API enabled" badge. Make sure the project selector at the top still shows the project you just created — it is easy to land on the wrong project here.', 'blaminhor-essentials' ); ?></li>
				<li><?php esc_html_e( 'Go to Credentials → "+ CREATE CREDENTIALS" → "API key", and copy it here.', 'blaminhor-essentials' ); ?></li>
				<li><?php esc_html_e( 'After creation, click the new key to edit it. Scroll to "API restrictions" and either leave "Don\'t restrict key" (simplest) OR select "Restrict key" and tick "PageSpeed Insights API" in the dropdown. If PSI is not in the dropdown, the API was not enabled in this project — go back to the previous step. Click "Save" and wait ~30 seconds for Google to propagate the change.', 'blaminhor-essentials' ); ?></li>
				<li><?php esc_html_e( 'Optional but recommended for security: on the same key edit page, scroll to "Application restrictions" and choose "HTTP referrers". Add your site domain (e.g. https://www.example.com/*). The plugin sends the site URL as Referer, so it must be in the allowed list — otherwise Google rejects the call with a "referer blocked" error.', 'blaminhor-essentials' ); ?></li>
			</ol>
		</details>

		<p>
			<label for="be-psi-key" class="screen-reader-text"><?php esc_html_e( 'API key', 'blaminhor-essentials' ); ?></label>
			<input type="password" id="be-psi-key" placeholder="AIzaSy…" class="regular-text code"
				value="<?php echo $psi_key_set ? esc_attr( '••••••••' . substr( md5( $module->audit_psi->get_api_key() ), 0, 4 ) ) : ''; ?>"
				autocomplete="off">
			<button type="button" class="button" id="be-psi-save"><?php esc_html_e( 'Save key', 'blaminhor-essentials' ); ?></button>
			<button type="button" class="button" id="be-psi-test"><?php esc_html_e( 'Test', 'blaminhor-essentials' ); ?></button>
		</p>

		<p>
			<button type="button" class="button button-primary be-audit-run" data-engine="psi">
				<?php esc_html_e( 'Run PSI audit now', 'blaminhor-essentials' ); ?>
			</button>
		</p>
	</div>

	<div class="blaminhor-essentials-card" style="padding:16px;">
		<h3 style="margin-top:0;">🟡 <?php esc_html_e( 'Built-in audit (no API key)', 'blaminhor-essentials' ); ?></h3>
		<p class="description">
			<?php esc_html_e( 'A local audit that inspects server responses, the rendered HTML and your active plugins. Covers around 80% of Google\'s recommendations without sending anything outside. No quota, no key to configure.', 'blaminhor-essentials' ); ?>
		</p>
		<p>
			<button type="button" class="button button-primary be-audit-run" data-engine="internal">
				<?php esc_html_e( 'Run internal audit now', 'blaminhor-essentials' ); ?>
			</button>
		</p>
	</div>

</div>

<table class="form-table">
	<tr>
		<th scope="row"><?php esc_html_e( 'Auto-run schedule', 'blaminhor-essentials' ); ?></th>
		<td>
			<select name="audit_schedule">
				<option value="never"  <?php selected( $settings['audit_schedule'], 'never' ); ?>><?php esc_html_e( 'Never (manual only)', 'blaminhor-essentials' ); ?></option>
				<option value="weekly" <?php selected( $settings['audit_schedule'], 'weekly' ); ?>><?php esc_html_e( 'Weekly', 'blaminhor-essentials' ); ?></option>
				<option value="daily"  <?php selected( $settings['audit_schedule'], 'daily' ); ?>><?php esc_html_e( 'Daily', 'blaminhor-essentials' ); ?></option>
			</select>
			<p class="description"><?php esc_html_e( 'Runs the selected audit automatically and stores the report. Default is "never" so you do not unintentionally consume your Google quota.', 'blaminhor-essentials' ); ?></p>
		</td>
	</tr>
</table>

<?php
// PSI score history graph — only shown when at least 2 data points exist for
// the same engine. Lets you see whether your changes are improving the score
// or making it worse, instead of staring at one isolated number.
$be_audit_history = (array) get_option( 'blaminhor_essentials_cache_audit_history', array() );
foreach ( array( 'psi' => 'PageSpeed Insights', 'internal' => __( 'Built-in audit', 'blaminhor-essentials' ) ) as $be_eng => $be_label ) {
	$be_points = isset( $be_audit_history[ $be_eng ] ) && is_array( $be_audit_history[ $be_eng ] ) ? $be_audit_history[ $be_eng ] : array();
	if ( count( $be_points ) < 2 ) {
		continue;
	}
	$be_w = 480;
	$be_h = 80;
	$be_pad = 8;
	$be_n = count( $be_points );
	$be_step = ( $be_w - 2 * $be_pad ) / max( 1, $be_n - 1 );
	$be_path = '';
	$be_polypts = '';
	foreach ( $be_points as $be_i => $be_p ) {
		$be_x = $be_pad + $be_i * $be_step;
		$be_score = max( 0, min( 100, (int) $be_p['score'] ) );
		$be_y = $be_pad + ( 100 - $be_score ) * ( $be_h - 2 * $be_pad ) / 100;
		$be_path .= ( 0 === $be_i ? 'M' : 'L' ) . round( $be_x, 1 ) . ',' . round( $be_y, 1 ) . ' ';
		$be_polypts .= round( $be_x, 1 ) . ',' . round( $be_y, 1 ) . ' ';
	}
	$be_first = (int) $be_points[0]['score'];
	$be_last  = (int) $be_points[ $be_n - 1 ]['score'];
	$be_delta = $be_last - $be_first;
	$be_delta_label = ( $be_delta >= 0 ? '+' : '' ) . $be_delta;
	$be_delta_color = $be_delta > 0 ? '#0a6b1d' : ( $be_delta < 0 ? '#c33' : '#666' );
	?>
	<h3 style="margin-top:24px;">
		<?php
		/* translators: 1: engine label e.g. PageSpeed Insights, 2: number of audits */
		echo esc_html( sprintf( __( 'Score history — %1$s (%2$d audits)', 'blaminhor-essentials' ), $be_label, $be_n ) );
		?>
		<span style="margin-left:12px;font-size:13px;color:<?php echo esc_attr( $be_delta_color ); ?>;">
			<?php echo esc_html( $be_delta_label ); ?>
		</span>
	</h3>
	<svg width="<?php echo (int) $be_w; ?>" height="<?php echo (int) $be_h; ?>" viewBox="0 0 <?php echo (int) $be_w; ?> <?php echo (int) $be_h; ?>" style="background:#f6f7f7;border:1px solid #ddd;border-radius:3px;">
		<line x1="<?php echo (int) $be_pad; ?>" x2="<?php echo (int) ( $be_w - $be_pad ); ?>" y1="<?php echo (int) ( $be_pad + ( 100 - 90 ) * ( $be_h - 2 * $be_pad ) / 100 ); ?>" y2="<?php echo (int) ( $be_pad + ( 100 - 90 ) * ( $be_h - 2 * $be_pad ) / 100 ); ?>" stroke="#0a6b1d" stroke-dasharray="2,3" stroke-width="0.5" />
		<line x1="<?php echo (int) $be_pad; ?>" x2="<?php echo (int) ( $be_w - $be_pad ); ?>" y1="<?php echo (int) ( $be_pad + ( 100 - 50 ) * ( $be_h - 2 * $be_pad ) / 100 ); ?>" y2="<?php echo (int) ( $be_pad + ( 100 - 50 ) * ( $be_h - 2 * $be_pad ) / 100 ); ?>" stroke="#dba617" stroke-dasharray="2,3" stroke-width="0.5" />
		<polyline points="<?php echo esc_attr( trim( $be_polypts ) ); ?>" fill="none" stroke="#2271b1" stroke-width="2" />
		<?php foreach ( $be_points as $be_i => $be_p ) :
			$be_x = $be_pad + $be_i * $be_step;
			$be_score = max( 0, min( 100, (int) $be_p['score'] ) );
			$be_y = $be_pad + ( 100 - $be_score ) * ( $be_h - 2 * $be_pad ) / 100;
			$be_dt = wp_date( 'Y-m-d H:i', (int) $be_p['ts'] );
			?>
			<circle cx="<?php echo esc_attr( round( $be_x, 1 ) ); ?>" cy="<?php echo esc_attr( round( $be_y, 1 ) ); ?>" r="2.5" fill="#2271b1">
				<title><?php echo esc_html( sprintf( '%d — %s', $be_score, $be_dt ) ); ?></title>
			</circle>
		<?php endforeach; ?>
	</svg>
	<p class="description" style="margin-top:4px;">
		<?php
		/* translators: 1: first score, 2: latest score */
		echo esc_html( sprintf( __( 'From %1$d to %2$d. Hover a dot to see the date and score of each run.', 'blaminhor-essentials' ), $be_first, $be_last ) );
		?>
	</p>
	<?php
}
?>

<h3><?php esc_html_e( 'Latest results', 'blaminhor-essentials' ); ?></h3>
<div id="be-audit-results">
	<p class="description"><?php esc_html_e( 'Run an audit to see results here.', 'blaminhor-essentials' ); ?></p>
</div>

<hr style="margin:32px 0;">

<h3><?php esc_html_e( 'Render watchdog', 'blaminhor-essentials' ); ?></h3>
<p class="description">
	<?php esc_html_e( 'Automatically checks that the cached version of your home page renders correctly to anonymous visitors. Runs after every cache purge, every settings save, and once a day. If a broken page is detected, the offending optimisation is disabled automatically and you are notified here.', 'blaminhor-essentials' ); ?>
</p>

<p>
	<button type="button" class="button button-primary" id="be-watchdog-run">
		<?php esc_html_e( 'Check rendering now', 'blaminhor-essentials' ); ?>
	</button>
	<span id="be-watchdog-status" style="margin-left:12px;color:#646970;"></span>
</p>
<?php
$be_last_run = isset( $module->render_watchdog ) ? $module->render_watchdog->get_recent_log( 1 ) : array();
$be_last     = ! empty( $be_last_run ) ? $be_last_run[0] : null;
?>
<p class="description" style="margin-top:8px;color:#0a6b1d;">
	&#10003;
	<?php
	if ( $be_last && isset( $be_last['ts'] ) ) {
		/* translators: %s: relative time, e.g. "2 hours" */
		echo esc_html( sprintf( __( 'Monitoring is active. Last check: %s ago.', 'blaminhor-essentials' ), human_time_diff( (int) $be_last['ts'], time() ) ) );
	} else {
		esc_html_e( 'Monitoring is active. No check has run yet.', 'blaminhor-essentials' );
	}
	?>
</p>

<?php
$be_watchdog_log = isset( $module->render_watchdog ) ? $module->render_watchdog->get_recent_log( 5 ) : array();
if ( ! empty( $be_watchdog_log ) ) :
	?>
	<details style="margin-top:12px;">
		<summary><strong><?php esc_html_e( 'Recent watchdog runs', 'blaminhor-essentials' ); ?></strong></summary>
		<table class="widefat striped" style="margin-top:8px;">
			<thead>
				<tr>
					<th><?php esc_html_e( 'When', 'blaminhor-essentials' ); ?></th>
					<th><?php esc_html_e( 'Event', 'blaminhor-essentials' ); ?></th>
					<th><?php esc_html_e( 'Status', 'blaminhor-essentials' ); ?></th>
					<th><?php esc_html_e( 'Signals', 'blaminhor-essentials' ); ?></th>
				</tr>
			</thead>
			<tbody>
				<?php foreach ( $be_watchdog_log as $be_entry ) :
					$be_when_abs = wp_date( 'Y-m-d H:i', isset( $be_entry['ts'] ) ? (int) $be_entry['ts'] : time() );
					$be_event    = isset( $be_entry['event'] ) ? (string) $be_entry['event'] : '';
					$be_ok       = isset( $be_entry['ok'] ) ? (bool) $be_entry['ok'] : false;
					$be_flags    = isset( $be_entry['flags'] ) ? (array) $be_entry['flags'] : array();
					$be_disabled = isset( $be_entry['disabled'] ) ? (array) $be_entry['disabled'] : array();
					$be_status_text = '';
					$be_status_color = '#646970';
					if ( 'auto_rollback_recovered' === $be_event ) {
						$be_status_text  = __( 'Recovered (auto)', 'blaminhor-essentials' );
						$be_status_color = '#dba617';
					} elseif ( 'auto_rollback_unrecovered' === $be_event ) {
						$be_status_text  = __( 'Unrecovered', 'blaminhor-essentials' );
						$be_status_color = '#c33';
					} elseif ( $be_ok ) {
						$be_status_text  = __( 'Healthy', 'blaminhor-essentials' );
						$be_status_color = '#0a6b1d';
					} else {
						$be_status_text  = __( 'Broken', 'blaminhor-essentials' );
						$be_status_color = '#c33';
					}
					?>
					<tr>
						<td><?php echo esc_html( $be_when_abs ); ?></td>
						<td><code><?php echo esc_html( $be_event ); ?></code></td>
						<td><span style="color:<?php echo esc_attr( $be_status_color ); ?>;font-weight:600;"><?php echo esc_html( $be_status_text ); ?></span></td>
						<td>
							<?php if ( ! empty( $be_flags ) ) : ?>
								<code style="font-size:11px;"><?php echo esc_html( implode( ', ', $be_flags ) ); ?></code>
							<?php endif; ?>
							<?php if ( ! empty( $be_disabled ) ) : ?>
								<br><small><?php echo esc_html( __( 'Disabled:', 'blaminhor-essentials' ) . ' ' . implode( ', ', $be_disabled ) ); ?></small>
							<?php endif; ?>
						</td>
					</tr>
				<?php endforeach; ?>
			</tbody>
		</table>
	</details>
<?php endif; ?>
