<?php
/**
 * Livada SEO — Dashboard View
 *
 * @package Livada_SEO
 */

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

// ── Stats ──────────────────────────────────────────────────────────────────────

global $wpdb;

// Average SEO score across all scored posts (post + page).
// phpcs:ignore WordPress.DB.DirectDatabaseQuery
$avg_score = (float) $wpdb->get_var(
	"SELECT AVG(CAST(meta_value AS UNSIGNED))
	 FROM {$wpdb->postmeta}
	 WHERE meta_key = '_livada_seo_score'
	   AND meta_value > 0"
);

// Posts/pages missing a meta description.
// phpcs:ignore WordPress.DB.DirectDatabaseQuery
$no_desc = (int) $wpdb->get_var(
	"SELECT COUNT(DISTINCT p.ID)
	 FROM {$wpdb->posts} p
	 LEFT JOIN {$wpdb->postmeta} pm
	        ON pm.post_id = p.ID
	       AND pm.meta_key = '_livada_seo_description'
	 WHERE p.post_status = 'publish'
	   AND p.post_type IN ('post','page')
	   AND (pm.meta_value IS NULL OR pm.meta_value = '')"
);

// Posts/pages set to noindex.
// phpcs:ignore WordPress.DB.DirectDatabaseQuery
$noindex = (int) $wpdb->get_var(
	"SELECT COUNT(*)
	 FROM {$wpdb->postmeta}
	 WHERE meta_key = '_livada_seo_noindex'
	   AND meta_value = '1'"
);

// Posts/pages with no focus keyword.
// phpcs:ignore WordPress.DB.DirectDatabaseQuery
$no_keyword = (int) $wpdb->get_var(
	"SELECT COUNT(DISTINCT p.ID)
	 FROM {$wpdb->posts} p
	 LEFT JOIN {$wpdb->postmeta} pm
	        ON pm.post_id = p.ID
	       AND pm.meta_key = '_livada_seo_focus_keyword'
	 WHERE p.post_status = 'publish'
	   AND p.post_type IN ('post','page')
	   AND (pm.meta_value IS NULL OR pm.meta_value = '')"
);

// Posts with low SEO score (< 50).
// phpcs:ignore WordPress.DB.DirectDatabaseQuery
$low_score = (int) $wpdb->get_var(
	"SELECT COUNT(*)
	 FROM {$wpdb->postmeta}
	 WHERE meta_key = '_livada_seo_score'
	   AND CAST(meta_value AS UNSIGNED) BETWEEN 1 AND 49"
);

// Cornerstone posts.
// phpcs:ignore WordPress.DB.DirectDatabaseQuery
$cornerstones = (int) $wpdb->get_var(
	"SELECT COUNT(*)
	 FROM {$wpdb->postmeta}
	 WHERE meta_key = '_livada_seo_cornerstone'
	   AND meta_value = '1'"
);

// ── Plugin performance footprint ─────────────────────────────────────────────
// phpcs:ignore WordPress.DB.DirectDatabaseQuery
$transient_count = (int) $wpdb->get_var(
	"SELECT COUNT(*) FROM {$wpdb->options}
	 WHERE option_name LIKE '_transient_livada_seo_%'
	   AND option_name NOT LIKE '_transient_timeout_%'"
);

$redirects_count = class_exists( 'Livada_SEO_Redirects' ) ? Livada_SEO_Redirects::count_redirects() : 0;

// 404 log row count (table may not exist yet).
$log_count = 0;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery
$has_404_table = (string) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->prefix . 'livada_seo_404_log' ) );
if ( '' !== $has_404_table ) {
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery
	$log_count = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}livada_seo_404_log" );
}

// Background tasks status.
//
// Only `livada_seo_cron_audit` is a true recurring cron event (daily, scheduled
// by class-site-audit.php on `init`). Sitemap refresh and IndexNow pings are
// not recurring crons by design:
//   - Sitemap is lazily generated and cached in a transient (12 h TTL),
//     invalidated on save_post. There is no cron to reschedule.
//   - IndexNow uses one-shot `wp_schedule_single_event` per URL change
//     (hook `livada_seo_indexnow_ping`). We display the next pending ping
//     when one is queued, otherwise an "on demand" status.
$cron_rows = [];

// 1. Daily audit — recurring cron.
$audit_next  = wp_next_scheduled( 'livada_seo_cron_audit' );
$cron_rows[] = [
	'label' => __( 'Daily audit', 'livada-seo' ),
	'next'  => $audit_next ? human_time_diff( time(), (int) $audit_next ) : __( 'not scheduled', 'livada-seo' ),
	'ok'    => (bool) $audit_next,
];

// 2. Sitemap — lazy cache, not a cron. Show the freshest sub-sitemap cache.
// The sitemap module stores transients with the prefix `livada_seo_sitemap_`
// (one per post type / taxonomy / news). We pick the latest expiry as a
// proxy for "the cache is warm" — there's no single index transient.
$sitemap_label = __( 'Sitemap cache', 'livada-seo' );
if ( class_exists( 'Livada_SEO_Sitemap' ) ) {
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery
	$max_expiry = (int) $wpdb->get_var(
		"SELECT MAX(option_value) FROM {$wpdb->options}
		 WHERE option_name LIKE '_transient_timeout_livada_seo_sitemap_%'"
	);
	if ( $max_expiry > time() ) {
		$cron_rows[] = [
			'label' => $sitemap_label,
			'next'  => sprintf(
				/* translators: %s: human-readable time until the cache expires */
				__( 'fresh — refreshes in %s', 'livada-seo' ),
				human_time_diff( time(), $max_expiry )
			),
			'ok'    => true,
		];
	} else {
		$cron_rows[] = [
			'label' => $sitemap_label,
			'next'  => __( 'on demand (regenerated on next request)', 'livada-seo' ),
			'ok'    => true,
		];
	}
}

// 3. IndexNow — one-shot scheduled events.
$indexnow_next = wp_next_scheduled( 'livada_seo_indexnow_ping' );
$cron_rows[]   = [
	'label' => __( 'IndexNow', 'livada-seo' ),
	'next'  => $indexnow_next
		? sprintf(
			/* translators: %s: human-readable time until the next ping fires */
			__( 'ping in %s', 'livada-seo' ),
			human_time_diff( time(), (int) $indexnow_next )
		)
		: __( 'on demand (no ping queued)', 'livada-seo' ),
	'ok'    => true,
];

// Sitemap stats — counts per CPT + taxonomy emitted in the index.
$sitemap_stats = [];
if ( class_exists( 'Livada_SEO_Sitemap' ) ) {
	$cfg_pt   = (array) Livada_SEO_Loader::get_setting( 'sitemap_post_types', [ 'post', 'page' ] );
	$cfg_tax  = (array) Livada_SEO_Loader::get_setting( 'sitemap_taxonomies', [ 'category' ] );
	$deny     = Livada_SEO_Sitemap::get_template_cpts();
	$reg_pt   = get_post_types( [ 'public' => true ] );
	$reg_tax  = get_taxonomies( [ 'public' => true ] );

	foreach ( array_intersect( array_diff( $cfg_pt, $deny ), $reg_pt ) as $pt ) {
		$counts = wp_count_posts( $pt );
		$sitemap_stats[] = [
			'kind'  => 'post_type',
			'slug'  => $pt,
			'count' => isset( $counts->publish ) ? (int) $counts->publish : 0,
		];
	}

	foreach ( array_intersect( $cfg_tax, $reg_tax ) as $tax ) {
		$term_count = wp_count_terms( [ 'taxonomy' => $tax, 'hide_empty' => true ] );
		$sitemap_stats[] = [
			'kind'  => 'taxonomy',
			'slug'  => $tax,
			'count' => is_wp_error( $term_count ) ? 0 : (int) $term_count,
		];
	}
}

$sitemap_total = array_sum( array_column( $sitemap_stats, 'count' ) );

// Last audit timestamp (from the cached results).
$last_audit_label = __( 'never', 'livada-seo' );
if ( class_exists( 'Livada_SEO_Site_Audit' ) ) {
	$audit_cached = get_transient( Livada_SEO_Site_Audit::CACHE_KEY );
	if ( is_array( $audit_cached ) && isset( $audit_cached['generated_at'] ) ) {
		$ts = strtotime( (string) $audit_cached['generated_at'] );
		if ( $ts ) {
			$last_audit_label = sprintf(
				/* translators: %s: time diff like "2 hours" */
				__( '%s ago', 'livada-seo' ),
				human_time_diff( $ts, time() )
			);
		}
	}
}

// Total redirections.
$total_redirects = class_exists( 'Livada_SEO_Redirects' ) ? Livada_SEO_Redirects::count_redirects() : 0;

// 404s logged in the last 30 days.
$total_404s = 0;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery
$table_exists = (string) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->prefix . 'livada_seo_404_log' ) );
if ( $table_exists ) {
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery
	$total_404s = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}livada_seo_404_log" );
}

// Site Audit — pull cached counts without re-running the audit.
$audit_issues = 0;
$audit_red    = 0;
if ( class_exists( 'Livada_SEO_Site_Audit' ) ) {
	$audit_cached = get_transient( Livada_SEO_Site_Audit::CACHE_KEY );
	if ( is_array( $audit_cached ) && isset( $audit_cached['summary'] ) ) {
		$audit_issues = (int) ( $audit_cached['summary']['total_issues'] ?? 0 );
		$audit_red    = (int) ( $audit_cached['summary']['posts_red']    ?? 0 )
			+ (int) ( $audit_cached['summary']['site_red']  ?? 0 );
	}
}

// URL helpers (defensive: the filter helper might be missing on a partial install).
$url_low   = class_exists( 'Livada_SEO_Admin_Filters' ) ? Livada_SEO_Admin_Filters::url_for( 'low_score',    'post' ) : '#';
$url_desc  = class_exists( 'Livada_SEO_Admin_Filters' ) ? Livada_SEO_Admin_Filters::url_for( 'missing_desc', 'post' ) : '#';
$url_idx   = class_exists( 'Livada_SEO_Admin_Filters' ) ? Livada_SEO_Admin_Filters::url_for( 'noindex',      'post' ) : '#';
$url_kw    = class_exists( 'Livada_SEO_Admin_Filters' ) ? Livada_SEO_Admin_Filters::url_for( 'no_keyword',   'post' ) : '#';
$url_cs    = class_exists( 'Livada_SEO_Admin_Filters' ) ? Livada_SEO_Admin_Filters::url_for( 'cornerstone',  'post' ) : '#';
$url_red   = admin_url( 'admin.php?page=livada-seo-redirects' );
$url_404   = admin_url( 'admin.php?page=livada-seo-404' );
$url_bulk  = admin_url( 'admin.php?page=livada-seo-bulk' );
$url_audit = admin_url( 'admin.php?page=livada-seo-audit' );
?>
<div class="wrap livada-seo-wrap has-ls-hero">
	<h1><?php esc_html_e( 'Livada SEO — Dashboard', 'livada-seo' ); ?></h1>

	<?php include LIVADA_SEO_PATH . 'includes/admin/views/_partials/header.php'; ?>

	<?php if ( isset( $_GET['updated'] ) ) : // phpcs:ignore ?>
		<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Settings saved.', 'livada-seo' ); ?></p></div>
	<?php endif; ?>

	<p class="description" style="max-width:720px; margin-bottom: var(--ls-space-4);">
		<?php esc_html_e( 'Click any card to jump straight to the affected posts and fix them.', 'livada-seo' ); ?>
	</p>

	<?php
	// ── AI Visibility teaser ──────────────────────────────────────────────────
	if ( ! class_exists( 'Livada_SEO_AI_Visibility' ) ) {
		$aiv_file = LIVADA_SEO_PATH . 'includes/class-ai-visibility.php';
		if ( file_exists( $aiv_file ) ) {
			require_once $aiv_file;
		}
	}
	if ( class_exists( 'Livada_SEO_AI_Visibility' ) ) :
		$aiv        = Livada_SEO_AI_Visibility::get_report();
		$aiv_score  = (int) $aiv['score'];
		$aiv_grade  = (string) $aiv['grade'];
		$aiv_url    = admin_url( 'admin.php?page=livada-seo-ai-visibility' );

		if ( $aiv_score >= 75 ) {
			$aiv_color = '#4F46E5';
		} elseif ( $aiv_score >= 55 ) {
			$aiv_color = '#0EA5E9';
		} elseif ( $aiv_score >= 35 ) {
			$aiv_color = '#F59E0B';
		} else {
			$aiv_color = '#DC2626';
		}
		?>
		<a href="<?php echo esc_url( $aiv_url ); ?>"
		   class="ls-section"
		   style="display:flex;align-items:center;gap:20px;text-decoration:none;color:inherit;margin-bottom:var(--ls-space-4);border-left:4px solid <?php echo esc_attr( $aiv_color ); ?>;"
		   title="<?php esc_attr_e( 'Open the full AI Visibility report', 'livada-seo' ); ?>">
			<span style="position:relative;flex:0 0 auto;width:72px;height:72px;display:inline-flex;align-items:center;justify-content:center;border-radius:50%;background:conic-gradient(<?php echo esc_attr( $aiv_color ); ?> <?php echo esc_attr( (string) ( $aiv_score * 3.6 ) ); ?>deg, #ececec 0);">
				<span style="position:absolute;inset:7px;background:#fff;border-radius:50%;"></span>
				<span style="position:relative;font-size:22px;font-weight:700;color:#2C2A29;"><?php echo esc_html( (string) $aiv_score ); ?></span>
			</span>
			<span style="flex:1;">
				<span style="display:block;font-size:16px;font-weight:700;color:#2C2A29;">
					<?php esc_html_e( 'AI Visibility Score', 'livada-seo' ); ?>
					<span style="font-weight:600;color:#6b7280;font-size:13px;margin-left:6px;"><?php echo esc_html( sprintf( __( 'Grade %s', 'livada-seo' ), $aiv_grade ) ); ?></span>
				</span>
				<span style="display:block;color:#555;margin-top:2px;"><?php echo esc_html( (string) $aiv['headline'] ); ?></span>
			</span>
			<span class="dashicons dashicons-arrow-right-alt2" aria-hidden="true" style="flex:0 0 auto;color:#6b7280;"></span>
		</a>
	<?php endif; ?>

	<div class="livada-card-grid">

		<!-- Average SEO Score → low-score filter -->
		<a class="livada-card livada-card--link <?php echo $low_score > 0 ? 'livada-card--warning' : 'livada-card--ok'; ?>"
		   href="<?php echo esc_url( $url_low ); ?>"
		   title="<?php esc_attr_e( 'Show posts with SEO score below 50', 'livada-seo' ); ?>">
			<div class="livada-card__icon dashicons dashicons-chart-area"></div>
			<div class="livada-card__body">
				<h2 class="livada-card__value"><?php echo $avg_score > 0 ? esc_html( number_format( $avg_score, 0 ) ) : '—'; ?></h2>
				<p class="livada-card__label"><?php esc_html_e( 'Average SEO Score', 'livada-seo' ); ?></p>
				<?php if ( $low_score > 0 ) : ?>
					<p class="livada-card__sub">
						<?php
						printf(
							/* translators: %d: post count */
							esc_html( _n( '%d post needs work →', '%d posts need work →', $low_score, 'livada-seo' ) ),
							(int) $low_score
						);
						?>
					</p>
				<?php endif; ?>
			</div>
		</a>

		<!-- Posts without description → missing_desc filter -->
		<a class="livada-card livada-card--link <?php echo $no_desc > 0 ? 'livada-card--warning' : 'livada-card--ok'; ?>"
		   href="<?php echo esc_url( $url_desc ); ?>"
		   title="<?php esc_attr_e( 'Show posts missing a meta description', 'livada-seo' ); ?>">
			<div class="livada-card__icon dashicons dashicons-admin-page"></div>
			<div class="livada-card__body">
				<h2 class="livada-card__value"><?php echo esc_html( $no_desc ); ?></h2>
				<p class="livada-card__label"><?php esc_html_e( 'Posts without meta description', 'livada-seo' ); ?></p>
				<?php if ( $no_desc > 0 ) : ?>
					<p class="livada-card__sub"><?php esc_html_e( 'Click to fix →', 'livada-seo' ); ?></p>
				<?php endif; ?>
			</div>
		</a>

		<!-- Noindex posts → noindex filter -->
		<a class="livada-card livada-card--link <?php echo $noindex > 0 ? 'livada-card--info' : ''; ?>"
		   href="<?php echo esc_url( $url_idx ); ?>"
		   title="<?php esc_attr_e( 'Show posts flagged as noindex', 'livada-seo' ); ?>">
			<div class="livada-card__icon dashicons dashicons-hidden"></div>
			<div class="livada-card__body">
				<h2 class="livada-card__value"><?php echo esc_html( $noindex ); ?></h2>
				<p class="livada-card__label"><?php esc_html_e( 'Noindex posts/pages', 'livada-seo' ); ?></p>
				<?php if ( $noindex > 0 ) : ?>
					<p class="livada-card__sub"><?php esc_html_e( 'Review →', 'livada-seo' ); ?></p>
				<?php endif; ?>
			</div>
		</a>

		<!-- Posts without focus keyword -->
		<a class="livada-card livada-card--link <?php echo $no_keyword > 0 ? 'livada-card--warning' : 'livada-card--ok'; ?>"
		   href="<?php echo esc_url( $url_kw ); ?>"
		   title="<?php esc_attr_e( 'Show posts with no focus keyword', 'livada-seo' ); ?>">
			<div class="livada-card__icon dashicons dashicons-tag"></div>
			<div class="livada-card__body">
				<h2 class="livada-card__value"><?php echo esc_html( $no_keyword ); ?></h2>
				<p class="livada-card__label"><?php esc_html_e( 'Posts without focus keyword', 'livada-seo' ); ?></p>
				<?php if ( $no_keyword > 0 ) : ?>
					<p class="livada-card__sub"><?php esc_html_e( 'Add keywords →', 'livada-seo' ); ?></p>
				<?php endif; ?>
			</div>
		</a>

		<!-- Redirections -->
		<a class="livada-card livada-card--link"
		   href="<?php echo esc_url( $url_red ); ?>"
		   title="<?php esc_attr_e( 'Manage redirections', 'livada-seo' ); ?>">
			<div class="livada-card__icon dashicons dashicons-randomize"></div>
			<div class="livada-card__body">
				<h2 class="livada-card__value"><?php echo esc_html( $total_redirects ); ?></h2>
				<p class="livada-card__label"><?php esc_html_e( 'Active redirections', 'livada-seo' ); ?></p>
				<p class="livada-card__sub"><?php esc_html_e( 'Manage →', 'livada-seo' ); ?></p>
			</div>
		</a>

		<!-- 404 monitor -->
		<a class="livada-card livada-card--link <?php echo $total_404s > 0 ? 'livada-card--warning' : 'livada-card--ok'; ?>"
		   href="<?php echo esc_url( $url_404 ); ?>"
		   title="<?php esc_attr_e( 'Open the 404 monitor', 'livada-seo' ); ?>">
			<div class="livada-card__icon dashicons dashicons-warning"></div>
			<div class="livada-card__body">
				<h2 class="livada-card__value"><?php echo esc_html( $total_404s ); ?></h2>
				<p class="livada-card__label"><?php esc_html_e( '404s logged', 'livada-seo' ); ?></p>
				<?php if ( $total_404s > 0 ) : ?>
					<p class="livada-card__sub"><?php esc_html_e( 'Convert to redirects →', 'livada-seo' ); ?></p>
				<?php endif; ?>
			</div>
		</a>

		<!-- Cornerstone posts -->
		<a class="livada-card livada-card--link <?php echo $cornerstones > 0 ? 'livada-card--ok' : ''; ?>"
		   href="<?php echo esc_url( $url_cs ); ?>"
		   title="<?php esc_attr_e( 'Show cornerstone content', 'livada-seo' ); ?>">
			<div class="livada-card__icon dashicons dashicons-star-filled"></div>
			<div class="livada-card__body">
				<h2 class="livada-card__value"><?php echo esc_html( (string) $cornerstones ); ?></h2>
				<p class="livada-card__label"><?php esc_html_e( 'Cornerstone posts', 'livada-seo' ); ?></p>
				<?php if ( $cornerstones > 0 ) : ?>
					<p class="livada-card__sub"><?php esc_html_e( 'Review →', 'livada-seo' ); ?></p>
				<?php else : ?>
					<p class="livada-card__sub"><?php esc_html_e( 'Mark your flagship articles', 'livada-seo' ); ?></p>
				<?php endif; ?>
			</div>
		</a>

		<!-- Site Audit -->
		<a class="livada-card livada-card--link <?php echo $audit_red > 0 ? 'livada-card--warning' : ( $audit_issues > 0 ? '' : 'livada-card--ok' ); ?>"
		   href="<?php echo esc_url( $url_audit ); ?>"
		   title="<?php esc_attr_e( 'Open the Site Audit dashboard', 'livada-seo' ); ?>">
			<div class="livada-card__icon dashicons dashicons-clipboard"></div>
			<div class="livada-card__body">
				<h2 class="livada-card__value"><?php echo esc_html( (string) $audit_issues ); ?></h2>
				<p class="livada-card__label"><?php esc_html_e( 'Site Audit issues', 'livada-seo' ); ?></p>
				<p class="livada-card__sub">
					<?php
					if ( $audit_red > 0 ) {
						printf(
							/* translators: %d: number of red checks */
							esc_html( _n( '%d failure → fix now', '%d failures → fix now', $audit_red, 'livada-seo' ) ),
							(int) $audit_red
						);
					} elseif ( $audit_issues > 0 ) {
						esc_html_e( 'Review warnings →', 'livada-seo' );
					} else {
						esc_html_e( 'Run audit →', 'livada-seo' );
					}
					?>
				</p>
			</div>
		</a>

	</div><!-- .livada-card-grid -->

	<!-- Plugin footprint -->
	<section class="ls-section">
		<header class="ls-section__head">
			<h2 class="ls-section__title">
				<span class="dashicons dashicons-performance" aria-hidden="true"></span>
				<?php esc_html_e( 'Plugin footprint', 'livada-seo' ); ?>
			</h2>
			<span class="ls-pill ls-pill--info"><?php esc_html_e( 'Zero frontend overhead', 'livada-seo' ); ?></span>
		</header>

		<div class="ls-perf-grid">
			<div>
				<p class="ls-perf-stat__label"><?php esc_html_e( 'Transients in cache', 'livada-seo' ); ?></p>
				<p class="ls-perf-stat__value"><?php echo esc_html( (string) $transient_count ); ?></p>
			</div>
			<div>
				<p class="ls-perf-stat__label"><?php esc_html_e( 'Redirects table rows', 'livada-seo' ); ?></p>
				<p class="ls-perf-stat__value"><?php echo esc_html( (string) $redirects_count ); ?></p>
			</div>
			<div>
				<p class="ls-perf-stat__label"><?php esc_html_e( '404 log rows', 'livada-seo' ); ?></p>
				<p class="ls-perf-stat__value"><?php echo esc_html( (string) $log_count ); ?></p>
			</div>
			<div>
				<p class="ls-perf-stat__label"><?php esc_html_e( 'Last audit run', 'livada-seo' ); ?></p>
				<p class="ls-perf-stat__value" style="font-size:14px;"><?php echo esc_html( $last_audit_label ); ?></p>
			</div>
		</div>

		<table class="widefat" style="margin-top: var(--ls-space-4);">
			<thead>
				<tr>
					<th style="width:40%;"><?php esc_html_e( 'Cron event', 'livada-seo' ); ?></th>
					<th><?php esc_html_e( 'Next run', 'livada-seo' ); ?></th>
				</tr>
			</thead>
			<tbody>
				<?php foreach ( $cron_rows as $cr ) : ?>
					<tr>
						<td><?php echo esc_html( $cr['label'] ); ?></td>
						<td>
							<?php if ( $cr['ok'] ) : ?>
								<span class="ls-dot ls-dot--ok" aria-hidden="true"></span>
								<?php
								/* translators: %s: relative time like "in 2 hours" */
								echo esc_html( sprintf( __( 'in %s', 'livada-seo' ), $cr['next'] ) );
								?>
							<?php else : ?>
								<span class="ls-dot ls-dot--danger" aria-hidden="true"></span>
								<?php echo esc_html( $cr['next'] ); ?>
							<?php endif; ?>
						</td>
					</tr>
				<?php endforeach; ?>
			</tbody>
		</table>
	</section>

	<!-- Sitemap inventory -->
	<?php if ( ! empty( $sitemap_stats ) ) : ?>
	<section class="ls-section">
		<header class="ls-section__head">
			<h2 class="ls-section__title">
				<span class="dashicons dashicons-media-spreadsheet" aria-hidden="true"></span>
				<?php esc_html_e( 'Sitemap inventory', 'livada-seo' ); ?>
				<span class="ls-pill">
					<?php
					printf(
						/* translators: %d: total URL count */
						esc_html( _n( '%d URL', '%d URLs', (int) $sitemap_total, 'livada-seo' ) ),
						(int) $sitemap_total
					);
					?>
				</span>
			</h2>
			<a href="<?php echo esc_url( home_url( '/sitemap.xml' ) ); ?>" target="_blank" rel="noopener" class="button">
				<?php esc_html_e( 'View sitemap →', 'livada-seo' ); ?>
			</a>
		</header>

		<table class="widefat">
			<thead>
				<tr>
					<th style="width:30%;"><?php esc_html_e( 'Kind', 'livada-seo' ); ?></th>
					<th><?php esc_html_e( 'Slug', 'livada-seo' ); ?></th>
					<th style="text-align:right;"><?php esc_html_e( 'URLs', 'livada-seo' ); ?></th>
					<th><?php esc_html_e( 'Sub-sitemap', 'livada-seo' ); ?></th>
				</tr>
			</thead>
			<tbody>
				<?php foreach ( $sitemap_stats as $row ) :
					$sub_url = home_url( '/sitemap-' . $row['slug'] . '.xml' );
				?>
					<tr>
						<td>
							<?php if ( $row['kind'] === 'post_type' ) : ?>
								<span class="ls-pill ls-pill--info"><?php esc_html_e( 'Post type', 'livada-seo' ); ?></span>
							<?php else : ?>
								<span class="ls-pill"><?php esc_html_e( 'Taxonomy', 'livada-seo' ); ?></span>
							<?php endif; ?>
						</td>
						<td><code><?php echo esc_html( $row['slug'] ); ?></code></td>
						<td style="text-align:right; font-weight:600;"><?php echo esc_html( (string) $row['count'] ); ?></td>
						<td>
							<a href="<?php echo esc_url( $sub_url ); ?>" target="_blank" rel="noopener">
								<?php echo esc_html( '/sitemap-' . $row['slug'] . '.xml' ); ?>
							</a>
						</td>
					</tr>
				<?php endforeach; ?>
			</tbody>
		</table>
	</section>
	<?php endif; ?>

	<!-- Quick links -->
	<section class="livada-quick-links">
		<h2><?php esc_html_e( 'Quick Links', 'livada-seo' ); ?></h2>
		<ul>
			<li><a href="<?php echo esc_url( admin_url( 'admin.php?page=livada-seo-general' ) ); ?>" class="button"><?php esc_html_e( 'General Settings', 'livada-seo' ); ?></a></li>
			<li><a href="<?php echo esc_url( admin_url( 'admin.php?page=livada-seo-titles' ) ); ?>" class="button"><?php esc_html_e( 'Titles &amp; Metas', 'livada-seo' ); ?></a></li>
			<li><a href="<?php echo esc_url( admin_url( 'admin.php?page=livada-seo-schema' ) ); ?>" class="button"><?php esc_html_e( 'Schema', 'livada-seo' ); ?></a></li>
			<li><a href="<?php echo esc_url( $url_bulk ); ?>" class="button"><?php esc_html_e( 'Bulk Editor', 'livada-seo' ); ?></a></li>
			<li><a href="<?php echo esc_url( $url_audit ); ?>" class="button"><?php esc_html_e( 'Site Audit', 'livada-seo' ); ?></a></li>
			<li><a href="<?php echo esc_url( $url_red ); ?>" class="button"><?php esc_html_e( 'Redirections', 'livada-seo' ); ?></a></li>
			<li><a href="<?php echo esc_url( $url_404 ); ?>" class="button"><?php esc_html_e( '404 Monitor', 'livada-seo' ); ?></a></li>
			<li><a href="<?php echo esc_url( admin_url( 'admin.php?page=livada-seo-tools' ) ); ?>" class="button"><?php esc_html_e( 'Tools / Import', 'livada-seo' ); ?></a></li>
		</ul>
	</section>
</div>
