<?php
/**
 * Flight Log screen: the change timeline with culprits, plus headline state.
 *
 * @package SEO_Flight_Recorder
 */

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

global $wpdb;

$sfrec_state  = get_option( 'sfrec_state', array() );
$sfrec_counts = SFRec_Admin::open_counts();
$sfrec_filter = isset( $_GET['sfrec_severity'] ) ? sanitize_key( wp_unslash( $_GET['sfrec_severity'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only display filter.
if ( ! in_array( $sfrec_filter, array( 'critical', 'warning', 'info', '' ), true ) ) {
	$sfrec_filter = '';
}

if ( '' !== $sfrec_filter ) {
	$sfrec_rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}sfrec_changes WHERE severity = %s ORDER BY id DESC LIMIT 100", $sfrec_filter ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- own table.
} else {
	$sfrec_rows = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}sfrec_changes ORDER BY id DESC LIMIT 100" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- own table.
}

$sfrec_page_urls = array();
foreach ( (array) $wpdb->get_results( "SELECT id, url, label FROM {$wpdb->prefix}sfrec_pages" ) as $sfrec_page_row ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- own table.
	$sfrec_page_urls[ (int) $sfrec_page_row->id ] = '' !== $sfrec_page_row->label ? $sfrec_page_row->label : $sfrec_page_row->url;
}

$sfrec_msg = isset( $_GET['sfrec_msg'] ) ? sanitize_key( wp_unslash( $_GET['sfrec_msg'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only notice key.
?>
<div class="wrap sfrec-wrap">
	<h1><?php esc_html_e( 'SEO Flight Recorder — Flight Log', 'buildsbyluke-seo-flight-recorder' ); ?></h1>

	<?php if ( 'check-started' === $sfrec_msg ) : ?>
		<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Check started. Results land in the log below (large page lists complete in the background).', 'buildsbyluke-seo-flight-recorder' ); ?></p></div>
	<?php elseif ( 'run-active' === $sfrec_msg ) : ?>
		<div class="notice notice-info is-dismissible"><p><?php esc_html_e( 'A check is already running — give it a moment.', 'buildsbyluke-seo-flight-recorder' ); ?></p></div>
	<?php elseif ( 'change-updated' === $sfrec_msg ) : ?>
		<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Log entry updated.', 'buildsbyluke-seo-flight-recorder' ); ?></p></div>
	<?php elseif ( 'baseline-armed' === $sfrec_msg ) : ?>
		<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Baseline armed. Run your updates, then click "Compare against armed baseline".', 'buildsbyluke-seo-flight-recorder' ); ?></p></div>
	<?php elseif ( 'baseline-compared' === $sfrec_msg ) : ?>
		<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Baseline comparison complete — any differences are in the log below.', 'buildsbyluke-seo-flight-recorder' ); ?></p></div>
	<?php endif; ?>

	<?php if ( isset( $sfrec_state['loopback_ok'] ) && false === $sfrec_state['loopback_ok'] ) : ?>
		<div class="notice notice-error">
			<p>
				<strong><?php esc_html_e( 'Monitoring impaired.', 'buildsbyluke-seo-flight-recorder' ); ?></strong>
				<?php esc_html_e( 'This site cannot fetch its own pages (loopback request failed), so page checks cannot run. This is usually caused by password protection (Basic Auth), a firewall rule, or a host that blocks self-requests.', 'buildsbyluke-seo-flight-recorder' ); ?>
				<?php if ( ! empty( $sfrec_state['loopback_error'] ) ) : ?>
					<br /><code><?php echo esc_html( $sfrec_state['loopback_error'] ); ?></code>
				<?php endif; ?>
			</p>
		</div>
	<?php endif; ?>

	<div class="sfrec-headline">
		<?php if ( $sfrec_counts['critical'] > 0 ) : ?>
			<p class="sfrec-verdict sfrec-verdict-critical">
				<?php
				/* translators: %d: number of critical findings. */
				echo esc_html( sprintf( _n( '%d critical finding needs attention.', '%d critical findings need attention.', $sfrec_counts['critical'], 'buildsbyluke-seo-flight-recorder' ), $sfrec_counts['critical'] ) );
				?>
			</p>
		<?php else : ?>
			<p class="sfrec-verdict sfrec-verdict-ok"><?php esc_html_e( 'No open critical findings. The recorder is on duty.', 'buildsbyluke-seo-flight-recorder' ); ?></p>
		<?php endif; ?>
		<?php if ( ! empty( $sfrec_state['last_check'] ) ) : ?>
			<p class="sfrec-muted">
				<?php
				/* translators: %s: human time diff. */
				echo esc_html( sprintf( __( 'Last completed check: %s ago.', 'buildsbyluke-seo-flight-recorder' ), human_time_diff( (int) $sfrec_state['last_check'] ) ) );
				?>
			</p>
		<?php endif; ?>
		<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
			<input type="hidden" name="action" value="sfrec_check_now" />
			<?php wp_nonce_field( 'sfrec_check_now' ); ?>
			<button type="submit" class="button button-primary"><?php esc_html_e( 'Check now', 'buildsbyluke-seo-flight-recorder' ); ?></button>
		</form>
		<?php
		/**
		 * Armed-baseline controls (SFRec_Baseline, part of the free plugin).
		 */
		do_action( 'sfrec_flight_log_actions' );
		?>
	</div>

	<p class="sfrec-filters">
		<a href="<?php echo esc_url( admin_url( 'admin.php?page=seo-flight-recorder' ) ); ?>" <?php echo '' === $sfrec_filter ? 'class="current"' : ''; ?>><?php esc_html_e( 'All', 'buildsbyluke-seo-flight-recorder' ); ?></a> |
		<a href="<?php echo esc_url( add_query_arg( 'sfrec_severity', 'critical', admin_url( 'admin.php?page=seo-flight-recorder' ) ) ); ?>" <?php echo 'critical' === $sfrec_filter ? 'class="current"' : ''; ?>><?php esc_html_e( 'Critical', 'buildsbyluke-seo-flight-recorder' ); ?></a> |
		<a href="<?php echo esc_url( add_query_arg( 'sfrec_severity', 'warning', admin_url( 'admin.php?page=seo-flight-recorder' ) ) ); ?>" <?php echo 'warning' === $sfrec_filter ? 'class="current"' : ''; ?>><?php esc_html_e( 'Warnings', 'buildsbyluke-seo-flight-recorder' ); ?></a> |
		<a href="<?php echo esc_url( add_query_arg( 'sfrec_severity', 'info', admin_url( 'admin.php?page=seo-flight-recorder' ) ) ); ?>" <?php echo 'info' === $sfrec_filter ? 'class="current"' : ''; ?>><?php esc_html_e( 'Info', 'buildsbyluke-seo-flight-recorder' ); ?></a>
	</p>

	<?php if ( empty( $sfrec_rows ) ) : ?>
		<p><?php esc_html_e( 'Nothing recorded yet. Run "Check now" to capture the first snapshot — changes appear here from the second check onward.', 'buildsbyluke-seo-flight-recorder' ); ?></p>
	<?php else : ?>
		<table class="widefat striped sfrec-log">
			<thead>
				<tr>
					<th><?php esc_html_e( 'Severity', 'buildsbyluke-seo-flight-recorder' ); ?></th>
					<th><?php esc_html_e( 'Where', 'buildsbyluke-seo-flight-recorder' ); ?></th>
					<th><?php esc_html_e( 'What changed', 'buildsbyluke-seo-flight-recorder' ); ?></th>
					<th><?php esc_html_e( 'Likely cause', 'buildsbyluke-seo-flight-recorder' ); ?></th>
					<th><?php esc_html_e( 'When', 'buildsbyluke-seo-flight-recorder' ); ?></th>
					<th><?php esc_html_e( 'Status', 'buildsbyluke-seo-flight-recorder' ); ?></th>
				</tr>
			</thead>
			<tbody>
			<?php foreach ( $sfrec_rows as $sfrec_row ) : ?>
				<?php
				$sfrec_suspects = json_decode( (string) $sfrec_row->suspects, true );
				$sfrec_where    = ( 0 === (int) $sfrec_row->page_id )
					? __( 'Site-wide', 'buildsbyluke-seo-flight-recorder' )
					: ( isset( $sfrec_page_urls[ (int) $sfrec_row->page_id ] ) ? $sfrec_page_urls[ (int) $sfrec_row->page_id ] : ( '#' . (int) $sfrec_row->page_id ) );
				?>
				<tr class="sfrec-row-<?php echo esc_attr( $sfrec_row->severity ); ?><?php echo in_array( $sfrec_row->status, array( 'resolved', 'muted' ), true ) ? ' sfrec-row-closed' : ''; ?>">
					<td><span class="sfrec-badge sfrec-badge-<?php echo esc_attr( $sfrec_row->severity ); ?>"><?php echo esc_html( strtoupper( $sfrec_row->severity ) ); ?></span></td>
					<td><?php echo esc_html( $sfrec_where ); ?></td>
					<td>
						<strong><?php echo esc_html( $sfrec_row->field ); ?></strong><br />
						<?php if ( '' !== (string) $sfrec_row->before_val ) : ?>
							<span class="sfrec-before"><?php echo esc_html( wp_html_excerpt( (string) $sfrec_row->before_val, 90, '…' ) ); ?></span> →
						<?php endif; ?>
						<span class="sfrec-after"><?php echo esc_html( '' !== (string) $sfrec_row->after_val ? wp_html_excerpt( (string) $sfrec_row->after_val, 90, '…' ) : __( '(removed)', 'buildsbyluke-seo-flight-recorder' ) ); ?></span>
						<?php if ( '' !== (string) $sfrec_row->note ) : ?>
							<br /><em class="sfrec-muted"><?php echo esc_html( $sfrec_row->note ); ?></em>
						<?php endif; ?>
					</td>
					<td>
						<?php if ( 'content_edit' === $sfrec_row->classification ) : ?>
							<?php esc_html_e( 'Content edit on this page (expected)', 'buildsbyluke-seo-flight-recorder' ); ?>
						<?php elseif ( is_array( $sfrec_suspects ) && ! empty( $sfrec_suspects ) ) : ?>
							<?php foreach ( array_slice( $sfrec_suspects, 0, 3 ) as $sfrec_suspect ) : ?>
								<span class="sfrec-suspect"><?php echo esc_html( $sfrec_suspect ); ?></span><br />
							<?php endforeach; ?>
						<?php elseif ( 'site_change' === $sfrec_row->classification ) : ?>
							<?php esc_html_e( 'Site-level change', 'buildsbyluke-seo-flight-recorder' ); ?>
						<?php else : ?>
							<span class="sfrec-muted"><?php esc_html_e( 'No site event recorded in the window', 'buildsbyluke-seo-flight-recorder' ); ?></span>
						<?php endif; ?>
					</td>
					<td><?php echo esc_html( mysql2date( 'Y-m-d H:i', $sfrec_row->detected_at ) ); ?></td>
					<td>
						<?php if ( in_array( $sfrec_row->status, array( 'new', 'seen' ), true ) ) : ?>
							<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="sfrec-inline-form">
								<input type="hidden" name="action" value="sfrec_change_status" />
								<input type="hidden" name="sfrec_change_id" value="<?php echo esc_attr( (string) $sfrec_row->id ); ?>" />
								<?php wp_nonce_field( 'sfrec_change_status_' . (int) $sfrec_row->id ); ?>
								<button type="submit" name="sfrec_status" value="resolved" class="button-link"><?php esc_html_e( 'Resolve', 'buildsbyluke-seo-flight-recorder' ); ?></button>
								<button type="submit" name="sfrec_status" value="muted" class="button-link"><?php esc_html_e( 'Mute', 'buildsbyluke-seo-flight-recorder' ); ?></button>
							</form>
						<?php else : ?>
							<?php echo esc_html( $sfrec_row->status ); ?>
						<?php endif; ?>
					</td>
				</tr>
			<?php endforeach; ?>
			</tbody>
		</table>
	<?php endif; ?>

	<?php SFRec_Admin::render_upsell(); ?>
</div>
