<?php
/**
 * Livada SEO — Site Audit View
 *
 * Renders the cached audit results with sortable per-post table + site-wide
 * checks summary. The "Run audit now" button triggers an AJAX re-run.
 *
 * @package Livada_SEO
 */

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

if ( ! class_exists( 'Livada_SEO_Site_Audit' ) ) {
	echo '<div class="wrap"><h1>' . esc_html__( 'Site Audit', 'livada-seo' ) . '</h1>';
	echo '<p>' . esc_html__( 'The Site Audit module is not active. Enable it in General settings.', 'livada-seo' ) . '</p></div>';
	return;
}

$results   = Livada_SEO_Site_Audit::get_results();
$summary   = isset( $results['summary'] ) && is_array( $results['summary'] ) ? $results['summary'] : [];
$site_wide = isset( $results['site_wide'] ) && is_array( $results['site_wide'] ) ? $results['site_wide'] : [];
$per_post  = isset( $results['per_post'] ) && is_array( $results['per_post'] ) ? $results['per_post'] : [];

$generated   = isset( $results['generated_at'] ) ? (string) $results['generated_at'] : '';
$duration_ms = isset( $results['duration_ms'] )  ? (int) $results['duration_ms']     : 0;

// Filter posts by status if ?filter=red|orange|green is passed.
$filter = isset( $_GET['status'] ) ? sanitize_key( $_GET['status'] ) : ''; // phpcs:ignore
if ( in_array( $filter, [ 'red', 'orange', 'green' ], true ) ) {
	$per_post = array_values(
		array_filter(
			$per_post,
			static function ( $row ) use ( $filter ) {
				return isset( $row['status'] ) && $row['status'] === $filter;
			}
		)
	);
}

$status_label = [
	'green'  => __( 'Pass',    'livada-seo' ),
	'orange' => __( 'Warning', 'livada-seo' ),
	'red'    => __( 'Fail',    'livada-seo' ),
];
$status_color = [
	'green'  => '#22c55e',
	'orange' => '#f59e0b',
	'red'    => '#ef4444',
];
?>
<div class="wrap livada-seo-wrap has-ls-hero">
<?php include LIVADA_SEO_PATH . 'includes/admin/views/_partials/header.php'; ?>
	<h1>
		<?php esc_html_e( 'Site Audit', 'livada-seo' ); ?>
		<button type="button" class="page-title-action" id="livada-audit-run">
			<?php esc_html_e( 'Run audit now', 'livada-seo' ); ?>
		</button>
		<a class="page-title-action" href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=livada_seo_audit_export_csv' ), 'livada_seo_audit_export' ) ); ?>">
			<?php esc_html_e( 'Export CSV', 'livada-seo' ); ?>
		</a>
		<span id="livada-audit-status" class="description" style="margin-left:12px;"></span>
	</h1>

	<?php if ( '' !== $generated ) : ?>
		<p class="description">
			<?php
			printf(
				/* translators: 1: timestamp, 2: duration in ms */
				esc_html__( 'Last run: %1$s — %2$d ms.', 'livada-seo' ),
				esc_html( $generated ),
				(int) $duration_ms
			);
			?>
		</p>
	<?php endif; ?>

	<!-- ── Summary cards ─────────────────────────────────────────────── -->
	<div class="livada-card-grid">

		<a class="livada-card livada-card--link"
		   href="<?php echo esc_url( remove_query_arg( 'status' ) ); ?>">
			<div class="livada-card__icon dashicons dashicons-list-view"></div>
			<div class="livada-card__body">
				<h2 class="livada-card__value"><?php echo (int) ( $summary['total_posts'] ?? 0 ); ?></h2>
				<p class="livada-card__label"><?php esc_html_e( 'Posts audited', 'livada-seo' ); ?></p>
			</div>
		</a>

		<a class="livada-card livada-card--link <?php echo ( (int) ( $summary['posts_red'] ?? 0 ) > 0 ) ? 'livada-card--warning' : 'livada-card--ok'; ?>"
		   href="<?php echo esc_url( add_query_arg( 'status', 'red' ) ); ?>">
			<div class="livada-card__icon dashicons dashicons-warning"></div>
			<div class="livada-card__body">
				<h2 class="livada-card__value"><?php echo (int) ( $summary['posts_red'] ?? 0 ); ?></h2>
				<p class="livada-card__label"><?php esc_html_e( 'Posts failing', 'livada-seo' ); ?></p>
				<p class="livada-card__sub"><?php esc_html_e( 'Click to filter →', 'livada-seo' ); ?></p>
			</div>
		</a>

		<a class="livada-card livada-card--link <?php echo ( (int) ( $summary['posts_orange'] ?? 0 ) > 0 ) ? 'livada-card--warning' : ''; ?>"
		   href="<?php echo esc_url( add_query_arg( 'status', 'orange' ) ); ?>">
			<div class="livada-card__icon dashicons dashicons-info"></div>
			<div class="livada-card__body">
				<h2 class="livada-card__value"><?php echo (int) ( $summary['posts_orange'] ?? 0 ); ?></h2>
				<p class="livada-card__label"><?php esc_html_e( 'Posts with warnings', 'livada-seo' ); ?></p>
				<p class="livada-card__sub"><?php esc_html_e( 'Click to filter →', 'livada-seo' ); ?></p>
			</div>
		</a>

		<a class="livada-card livada-card--link <?php echo ( (int) ( $summary['posts_green'] ?? 0 ) > 0 ) ? 'livada-card--ok' : ''; ?>"
		   href="<?php echo esc_url( add_query_arg( 'status', 'green' ) ); ?>">
			<div class="livada-card__icon dashicons dashicons-yes-alt"></div>
			<div class="livada-card__body">
				<h2 class="livada-card__value"><?php echo (int) ( $summary['posts_green'] ?? 0 ); ?></h2>
				<p class="livada-card__label"><?php esc_html_e( 'Posts passing', 'livada-seo' ); ?></p>
				<p class="livada-card__sub"><?php esc_html_e( 'Click to filter →', 'livada-seo' ); ?></p>
			</div>
		</a>

	</div>

	<!-- ── Site-wide checks ──────────────────────────────────────────── -->
	<h2 style="margin-top:32px;"><?php esc_html_e( 'Site-wide checks', 'livada-seo' ); ?></h2>
	<table class="wp-list-table widefat fixed striped">
		<thead>
			<tr>
				<th style="width: 18%;"><?php esc_html_e( 'Status', 'livada-seo' ); ?></th>
				<th style="width: 22%;"><?php esc_html_e( 'Check', 'livada-seo' ); ?></th>
				<th><?php esc_html_e( 'Detail', 'livada-seo' ); ?></th>
			</tr>
		</thead>
		<tbody>
			<?php foreach ( $site_wide as $row ) :
				$status  = isset( $row['status'] )  ? (string) $row['status']  : 'orange';
				$key     = isset( $row['check'] )   ? (string) $row['check']   : '';
				$message = isset( $row['message'] ) ? (string) $row['message'] : '';
				$color   = $status_color[ $status ] ?? '#999';
				$label   = $status_label[ $status ] ?? $status;
			?>
				<tr>
					<td>
						<span style="display:inline-flex;align-items:center;gap:6px;">
							<span style="width:10px;height:10px;border-radius:50%;background:<?php echo esc_attr( $color ); ?>;display:inline-block;" aria-hidden="true"></span>
							<?php echo esc_html( $label ); ?>
						</span>
					</td>
					<td><code><?php echo esc_html( $key ); ?></code></td>
					<td><?php echo esc_html( $message ); ?></td>
				</tr>
			<?php endforeach; ?>
		</tbody>
	</table>

	<!-- ── Per-post results ──────────────────────────────────────────── -->
	<h2 style="margin-top:32px;">
		<?php esc_html_e( 'Per-post results', 'livada-seo' ); ?>
		<?php if ( '' !== $filter ) : ?>
			<small style="font-weight:400;">
				—
				<?php
				printf(
					/* translators: %s: status filter name */
					esc_html__( 'filtered by %s', 'livada-seo' ),
					esc_html( $status_label[ $filter ] ?? $filter )
				);
				?>
				·
				<a href="<?php echo esc_url( remove_query_arg( 'status' ) ); ?>"><?php esc_html_e( 'clear', 'livada-seo' ); ?></a>
			</small>
		<?php endif; ?>
	</h2>

	<?php if ( empty( $per_post ) ) : ?>
		<p class="description">
			<?php esc_html_e( 'No posts match the current filter.', 'livada-seo' ); ?>
		</p>
	<?php else : ?>
		<table class="wp-list-table widefat fixed striped">
			<thead>
				<tr>
					<th style="width: 8%;"><?php esc_html_e( 'Status', 'livada-seo' ); ?></th>
					<th><?php esc_html_e( 'Post', 'livada-seo' ); ?></th>
					<th style="width: 50%;"><?php esc_html_e( 'Issues', 'livada-seo' ); ?></th>
					<th style="width: 12%;"><?php esc_html_e( 'Actions', 'livada-seo' ); ?></th>
				</tr>
			</thead>
			<tbody>
				<?php foreach ( $per_post as $row ) :
					$status   = isset( $row['status'] ) ? (string) $row['status'] : 'orange';
					$color    = $status_color[ $status ] ?? '#999';
					$label    = $status_label[ $status ] ?? $status;
					$post_id  = isset( $row['post_id'] ) ? (int) $row['post_id'] : 0;
					$title    = isset( $row['title'] )   ? (string) $row['title']   : '';
					$edit_url = isset( $row['edit_url'] ) ? (string) $row['edit_url'] : '';
					$view_url = isset( $row['view_url'] ) ? (string) $row['view_url'] : '';

					$issue_messages = [];
					if ( isset( $row['checks'] ) && is_array( $row['checks'] ) ) {
						foreach ( $row['checks'] as $c ) {
							$cs = isset( $c['status'] ) ? (string) $c['status'] : 'orange';
							if ( 'green' === $cs ) {
								continue;
							}
							$cmsg = isset( $c['message'] ) ? (string) $c['message'] : '';
							if ( '' !== $cmsg ) {
								$issue_messages[] = '[' . $cs . '] ' . $cmsg;
							}
						}
					}
				?>
					<tr>
						<td>
							<span style="display:inline-flex;align-items:center;gap:6px;">
								<span style="width:10px;height:10px;border-radius:50%;background:<?php echo esc_attr( $color ); ?>;display:inline-block;" aria-hidden="true"></span>
								<?php echo esc_html( $label ); ?>
							</span>
						</td>
						<td>
							<strong><?php echo esc_html( $title ); ?></strong>
							<br><small>ID #<?php echo (int) $post_id; ?></small>
						</td>
						<td>
							<?php if ( empty( $issue_messages ) ) : ?>
								<em><?php esc_html_e( 'All checks passed.', 'livada-seo' ); ?></em>
							<?php else : ?>
								<ul style="margin:0;list-style:disc;padding-left:18px;">
									<?php foreach ( $issue_messages as $msg ) : ?>
										<li style="font-size:12px;line-height:1.4;"><?php echo esc_html( $msg ); ?></li>
									<?php endforeach; ?>
								</ul>
							<?php endif; ?>
						</td>
						<td>
							<?php if ( '' !== $edit_url ) : ?>
								<a href="<?php echo esc_url( $edit_url ); ?>"><?php esc_html_e( 'Edit', 'livada-seo' ); ?></a>
							<?php endif; ?>
							<?php if ( '' !== $view_url ) : ?>
								·
								<a href="<?php echo esc_url( $view_url ); ?>" target="_blank" rel="noopener"><?php esc_html_e( 'View', 'livada-seo' ); ?></a>
							<?php endif; ?>
						</td>
					</tr>
				<?php endforeach; ?>
			</tbody>
		</table>
	<?php endif; ?>
</div>

<script>
(function () {
	'use strict';

	var data    = window.livadaSEO || {};
	var ajaxUrl = data.ajaxUrl || '<?php echo esc_js( admin_url( 'admin-ajax.php' ) ); ?>';
	var nonce   = data.nonce   || '<?php echo esc_js( wp_create_nonce( 'livada_seo_admin_nonce' ) ); ?>';

	var btn      = document.getElementById( 'livada-audit-run' );
	var statusEl = document.getElementById( 'livada-audit-status' );

	if ( ! btn ) { return; }

	btn.addEventListener( 'click', function () {
		btn.disabled = true;
		statusEl.textContent = '<?php echo esc_js( __( 'Running…', 'livada-seo' ) ); ?>';

		var body = new URLSearchParams( {
			action: 'livada_seo_run_audit',
			nonce:  nonce,
		} );

		fetch( ajaxUrl, {
			method:      'POST',
			credentials: 'same-origin',
			headers:     { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
			body:        body.toString(),
		} )
			.then( function ( r ) { return r.json(); } )
			.then( function ( res ) {
				if ( res && res.success ) {
					statusEl.textContent = '<?php echo esc_js( __( 'Done — reloading…', 'livada-seo' ) ); ?>';
					setTimeout( function () { window.location.reload(); }, 600 );
				} else {
					btn.disabled = false;
					statusEl.textContent = ( res && res.data && res.data.message ) || '<?php echo esc_js( __( 'Failed.', 'livada-seo' ) ); ?>';
				}
			} )
			.catch( function () {
				btn.disabled = false;
				statusEl.textContent = '<?php echo esc_js( __( 'Network error.', 'livada-seo' ) ); ?>';
			} );
	} );
})();
</script>
