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

add_action('admin_enqueue_scripts', function () {
    $page = isset($_GET['page']) ? sanitize_key((string) $_GET['page']) : '';
    $tab  = isset($_GET['tab']) ? sanitize_key((string) $_GET['tab']) : '';

    if ($page === 'aegisseo' && $tab === 'issues') {
        wp_enqueue_script('jquery');
    }
});

add_action('wp_ajax_aegisseo_quick_generate', function () {
    if (!current_user_can('edit_posts')) {
        wp_send_json_error(array('message' => 'forbidden'), 403);
    }
    check_ajax_referer('aegisseo_quick_fix', 'nonce');

    $post_id = isset($_POST['post_id']) ? absint($_POST['post_id']) : 0;
    $field   = isset($_POST['field']) ? sanitize_key(wp_unslash($_POST['field'])) : '';

    if (!$post_id || !get_post($post_id) || !current_user_can('edit_post', $post_id)) {
        wp_send_json_error(array('message' => 'invalid_post'), 400);
    }

    $allowed = array(
        'meta_description' => '_aegisseo_description',
        'og_title'         => '_aegisseo_og_title',
        'og_description'   => '_aegisseo_og_description',
        'twitter_title'    => '_aegisseo_twitter_title',
        'twitter_description' => '_aegisseo_twitter_description',
    );
    if (!isset($allowed[$field])) {
        wp_send_json_error(array('message' => 'invalid_field'), 400);
    }

    $meta_key = $allowed[$field];
    $old = (string) get_post_meta($post_id, $meta_key, true);

    // Save rollback snapshot (per-user) BEFORE writing.
    $uid = get_current_user_id();
    $snap_key = 'aegisseo_quickfix_' . $field;
    $snap = (array) get_user_meta($uid, $snap_key, true);
    $snap[$post_id] = $old;
    update_user_meta($uid, $snap_key, $snap);

    // Lightweight local generator (no external services).
    $post = get_post($post_id);
    $title = $post ? get_the_title($post_id) : '';
    $raw = '';
    if ($post) {
        $raw = (string) $post->post_content;
    }
    $text = wp_strip_all_tags(strip_shortcodes($raw));
    $text = preg_replace('/\s+/u', ' ', $text);
    $text = trim($text);

    $generated = '';
    if ($field === 'meta_description' || $field === 'og_description' || $field === 'twitter_description') {
        // Prefer first meaningful paragraph-like chunk.
        $candidate = $text;
        if (strlen($candidate) < 40) {
            $candidate = $title . '. ' . $candidate;
        }
        // Make a noticeably longer paragraph (target ~240-320 chars).
        $candidate = mb_substr($candidate, 0, 360);
        $candidate = rtrim($candidate, " \t\n\r\0\x0B.,;:-");
        if ($title) {
            $generated = $title . ' — ' . $candidate;
        } else {
            $generated = $candidate;
        }
        // Ensure it's not tiny.
        if (mb_strlen($generated) < 160) {
            $generated .= '. Learn more on this page, including key details, benefits, and next steps.';
        }
    } else {
        // Titles: use post title if available.
        $generated = $title ? $title : ('Post #' . $post_id);
    }

    update_post_meta($post_id, $meta_key, $generated);

	$uid = get_current_user_id();
	$snap_key = 'aegisseo_quickfix_' . $field;
	$snap = (array) get_user_meta($uid, $snap_key, true);

	$snap[$post_id] = array(
		'old' => $old,
		'new' => $generated,
		'ts'  => time(),
	);

	update_user_meta($uid, $snap_key, $snap);

    wp_send_json_success(array(
        'post_id' => $post_id,
        'field'   => $field,
        'meta_key'=> $meta_key,
        'value'   => $generated,
    ));
});

add_action('wp_ajax_aegisseo_quick_rollback', function () {
    if (!current_user_can('edit_posts')) {
        wp_send_json_error(array('message' => 'forbidden'), 403);
    }
    check_ajax_referer('aegisseo_quick_fix', 'nonce');

    $post_id = isset($_POST['post_id']) ? absint($_POST['post_id']) : 0;
    $field   = isset($_POST['field']) ? sanitize_key(wp_unslash($_POST['field'])) : '';

    if (!$post_id || !get_post($post_id) || !current_user_can('edit_post', $post_id)) {
        wp_send_json_error(array('message' => 'invalid_post'), 400);
    }

    $allowed = array(
        'meta_description' => '_aegisseo_description',
        'og_title'         => '_aegisseo_og_title',
        'og_description'   => '_aegisseo_og_description',
        'twitter_title'    => '_aegisseo_twitter_title',
        'twitter_description' => '_aegisseo_twitter_description',
    );
    if (!isset($allowed[$field])) {
        wp_send_json_error(array('message' => 'invalid_field'), 400);
    }

    $uid = get_current_user_id();
    $snap_key = 'aegisseo_quickfix_' . $field;
    $snap = (array) get_user_meta($uid, $snap_key, true);

    if (!array_key_exists($post_id, $snap)) {
        wp_send_json_error(array('message' => 'no_snapshot'), 404);
    }

    $meta_key = $allowed[$field];
	$snapv = $snap[$post_id];

	// New format: array('old' => ..., 'new' => ...)
	if (is_array($snapv) && array_key_exists('old', $snapv)) {
		$restore = (string) $snapv['old'];
	} else {
		// Backward compat: old format stored a string
		$restore = (string) $snapv;
	}

	update_post_meta($post_id, $meta_key, $restore);

	// Remove snapshot once used (so button disappears after rollback).
	unset($snap[$post_id]);
	update_user_meta($uid, $snap_key, $snap);

    wp_send_json_success(array(
        'post_id' => $post_id,
        'field'   => $field,
        'meta_key'=> $meta_key,
        'value'   => $restore,
    ));
});
/**
 * Non-JS (admin-post.php) handlers for Selection List Generate/Rollback
 * Mirrors the working bottom table method (POST + nonce).
 */

add_action('admin_post_aegisseo_sel_generate_meta', function () {

    if (!current_user_can('edit_posts')) {
        wp_die('Forbidden', 403);
    }

    check_admin_referer('aegisseo_sel_generate_meta');

    $post_id = isset($_POST['post_id']) ? absint($_POST['post_id']) : 0;
    $field   = isset($_POST['field']) ? sanitize_key(wp_unslash($_POST['field'])) : '';

    if (!$post_id || !get_post($post_id) || !current_user_can('edit_post', $post_id)) {
        wp_die('Invalid post', 400);
    }

    $allowed = array(
        'meta_description'     => '_aegisseo_description',
        'og_title'             => '_aegisseo_og_title',
        'og_description'       => '_aegisseo_og_description',
        'twitter_title'        => '_aegisseo_twitter_title',
        'twitter_description'  => '_aegisseo_twitter_description',
    );

    if (!isset($allowed[$field])) {
        wp_die('Invalid field', 400);
    }

    $meta_key = $allowed[$field];
    $old = (string) get_post_meta($post_id, $meta_key, true);

    // Generate
    $generated = '';
    if ($field === 'meta_description' || $field === 'og_description' || $field === 'twitter_description') {
        $candidate = '';
        if (has_excerpt($post_id)) {
            $candidate = get_the_excerpt($post_id);
        } else {
            $content = (string) get_post_field('post_content', $post_id);
            $content = wp_strip_all_tags($content);
            $content = preg_replace('/\s+/', ' ', $content);
            $candidate = trim($content);
        }
        if ($candidate !== '') {
            $candidate = mb_substr($candidate, 0, 170);
            $candidate = rtrim($candidate, " \t\n\r\0\x0B.,;:!-");
            $generated = $candidate;
        }
        if (mb_strlen($generated) < 160) {
            $generated .= '. Learn more on this page, including key details, benefits, and next steps.';
        }
    } else {
        $title = get_the_title($post_id);
        $generated = $title ? $title : ('Post #' . $post_id);
    }

    update_post_meta($post_id, $meta_key, $generated);

    // Save snapshot (per-user) so Selection List shows Old/New and enables Rollback
    $uid = get_current_user_id();
    $snap_key = 'aegisseo_quickfix_' . $field;
    $snap = (array) get_user_meta($uid, $snap_key, true);

    $snap[$post_id] = array(
        'old' => $old,
        'new' => $generated,
        'ts'  => time(),
    );

    update_user_meta($uid, $snap_key, $snap);

    $ref = wp_get_referer();
    if (!$ref) { $ref = admin_url('admin.php?page=aegisseo&tab=issues'); }
    wp_safe_redirect($ref);
    exit;
});

add_action('admin_post_aegisseo_sel_rollback_meta', function () {

    if (!current_user_can('edit_posts')) {
        wp_die('Forbidden', 403);
    }

    check_admin_referer('aegisseo_sel_rollback_meta');

    $post_id = isset($_POST['post_id']) ? absint($_POST['post_id']) : 0;
    $field   = isset($_POST['field']) ? sanitize_key(wp_unslash($_POST['field'])) : '';

    if (!$post_id || !get_post($post_id) || !current_user_can('edit_post', $post_id)) {
        wp_die('Invalid post', 400);
    }

    $allowed = array(
        'meta_description'     => '_aegisseo_description',
        'og_title'             => '_aegisseo_og_title',
        'og_description'       => '_aegisseo_og_description',
        'twitter_title'        => '_aegisseo_twitter_title',
        'twitter_description'  => '_aegisseo_twitter_description',
    );

    if (!isset($allowed[$field])) {
        wp_die('Invalid field', 400);
    }

    $meta_key = $allowed[$field];

    // Load snapshot
    $uid = get_current_user_id();
    $snap_key = 'aegisseo_quickfix_' . $field;
    $snap = (array) get_user_meta($uid, $snap_key, true);

    if (!isset($snap[$post_id])) {
        $ref = wp_get_referer();
        if (!$ref) { $ref = admin_url('admin.php?page=aegisseo&tab=issues'); }
        wp_safe_redirect($ref);
        exit;
    }

    $snapv = $snap[$post_id];

    $restore = '';
    if (is_array($snapv) && array_key_exists('old', $snapv)) {
        $restore = (string) $snapv['old'];
    } else {
        // Backward compat
        $restore = (string) $snapv;
    }

    update_post_meta($post_id, $meta_key, $restore);

    // Remove snapshot so New clears and button flips back
    unset($snap[$post_id]);
    update_user_meta($uid, $snap_key, $snap);

    $ref = wp_get_referer();
    if (!$ref) { $ref = admin_url('admin.php?page=aegisseo&tab=issues'); }
    wp_safe_redirect($ref);
    exit;
});
$aegisseo_has_pro = false;
if (function_exists('aegisseo') && isset(aegisseo()->license) && aegisseo()->license) {
    $aegisseo_has_pro = (bool) aegisseo()->license->is_pro();
}
if (!$aegisseo_has_pro && class_exists('AegisSEO\\Utils\\License')) {
    \AegisSEO\Utils\License::render_pro_banner(
        __('Upgrade to PRO', 'aegisseo'),
        __('PRO feature: SEO Ops Center, Issues & Fixex, Evidence and Migration Wizard with advanced autopilot detection, guided fixes, and bulk remediation actions are available in AegisSEO PRO.', 'aegisseo')
    );
    echo '<p class="description" style="margin-top:10px;">' . esc_html__('Activate a PRO license to unlock Issues & Fixes.', 'aegisseo') . '</p>';
    return;
}

$applied = isset($_GET['applied']) ? (int) $_GET['applied'] : 0;
$fix     = isset($_GET['fix']) ? sanitize_key($_GET['fix']) : '';
$post_id = isset($_GET['post_id']) ? (int) $_GET['post_id'] : 0;

if ($applied === 1) {
    echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('Fix applied successfully.', 'aegisseo') . '</p></div>';
} elseif (isset($_GET['rolled']) && (int) $_GET['rolled'] === 1) {
    echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('Rollback completed.', 'aegisseo') . '</p></div>';
} elseif (isset($_GET['error'])) {
    echo '<div class="notice notice-error"><p>' . esc_html__('Could not apply fix. Please try again.', 'aegisseo') . '</p></div>';
}

$args = array(
    'post_type'      => array('post', 'page'),
    'post_status'    => array('publish'),
    'posts_per_page' => 50,
    'orderby'        => 'modified',
    'order'          => 'DESC',
    'fields'         => 'ids',
);

$ids = get_posts($args);

$rows = array();

foreach ($ids as $pid) {
    $title_override = (string) get_post_meta($pid, '_aegisseo_title', true);
    $desc_override  = (string) get_post_meta($pid, '_aegisseo_description', true);

    $post = get_post($pid);
    if (!$post) { continue; }

    $content_raw = wp_strip_all_tags((string) $post->post_content, true);
    $content_raw = preg_replace('/\s+/', ' ', $content_raw);
    $content_raw = trim($content_raw);

    $word_count = 0;
    if ($content_raw !== '') {
        $word_count = str_word_count($content_raw);
    }

    $issues = array();

    if ($desc_override === '') {
        $issues[] = __('Missing meta description override', 'aegisseo');
    }

    if ($word_count > 0 && $word_count < 300) {
        $issues[] = sprintf(__('Thin content (%d words)', 'aegisseo'), $word_count);
    }
$schema_type = '';
if (!empty(aegisseo()->schema) && method_exists(aegisseo()->schema, 'resolve_schema_type')) {
    $schema_type = (string) aegisseo()->schema->resolve_schema_type($post->ID);
    $schema_issues = (array) aegisseo()->schema->validate_schema($post->ID, $schema_type);
    foreach ($schema_issues as $si) {
        $issues[] = $si;
    }
}

    if (empty($issues)) { continue; }

    $rows[] = array(
        'ID'     => $pid,
        'title'  => get_the_title($pid),
        'type'   => $post->post_type,
        'issues' => $issues,
        'desc_missing' => ($desc_override === ''),
        'schema_issues' => !empty($schema_issues) ? 1 : 0,
    );
}

?>
<h2><?php echo esc_html__('Issues & Fixes', 'aegisseo'); ?></h2>
<?php
// Bulk rollback notice
if (isset($_GET['bulk_rolled']) && (int) $_GET['bulk_rolled'] === 1) {
    $ok = isset($_GET['ok']) ? (int) $_GET['ok'] : 0;
    $fail = isset($_GET['fail']) ? (int) $_GET['fail'] : 0;

    echo '<div class="notice notice-success is-dismissible"><p>';
    echo esc_html(sprintf(__('Bulk rollback completed. Rolled back: %d. Skipped/failed: %d.', 'aegisseo'), $ok, $fail));
    echo '</p></div>';
} elseif (isset($_GET['bulk_rolled']) && (int) $_GET['bulk_rolled'] === 0) {
    echo '<div class="notice notice-error is-dismissible"><p>';
    echo esc_html__('Bulk rollback did not run. No events were selected or request was blocked.', 'aegisseo');
    echo '</p></div>';
}
?>
<?php
if (isset($_GET['pack']) && (int) $_GET['pack'] === 1 && !empty($_GET['pack_id'])) {
    $pack_id = sanitize_text_field(wp_unslash($_GET['pack_id']));
    $pack_name = isset($_GET['pack_name']) ? sanitize_key($_GET['pack_name']) : '';
    $changed = isset($_GET['changed']) ? (int) $_GET['changed'] : 0;
    $flagged = isset($_GET['flagged']) ? (int) $_GET['flagged'] : 0;
    echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('Fix Pack applied.', 'aegisseo') . ' <strong>' . esc_html($pack_name) . '</strong> — ' . esc_html(sprintf(__('Changed: %d, Flagged: %d', 'aegisseo'), $changed, $flagged)) . '</p>';
    $rollback_url = wp_nonce_url(admin_url('admin-post.php?action=aegisseo_rollback_fix_pack&pack_id=' . urlencode($pack_id)), 'aegisseo_fix_pack_rollback');
    echo '<p style="margin:6px 0 0;"><a class="button" href="' . esc_url($rollback_url) . '">' . esc_html__('Rollback this Fix Pack', 'aegisseo') . '</a></p></div>';
} elseif (isset($_GET['rolled_pack']) && (int) $_GET['rolled_pack'] === 1) {
    $rolled = isset($_GET['rolled']) ? (int) $_GET['rolled'] : 0;
    echo '<div class="notice notice-success is-dismissible"><p>' . esc_html(sprintf(__('Fix Pack rolled back (%d changes).', 'aegisseo'), $rolled)) . '</p></div>';
}
?>

<div style="margin:14px 0; padding:12px; border:1px solid #dcdcde; background:#fff; border-radius:8px;">
    <div style="display:flex; align-items:flex-start; justify-content:space-between; gap:12px; flex-wrap:wrap;">
        <div>
            <strong><?php echo esc_html__('Fix Packs (batch actions with rollback)', 'aegisseo'); ?></strong>
            <div class="description" style="margin-top:6px;">
                <?php echo esc_html__('Run a safe batch fix. Every change is logged into the Evidence Timeline so you can rollback.', 'aegisseo'); ?>
            </div>
        </div>
        <div style="display:flex; gap:8px; flex-wrap:wrap;">
            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="margin:0;">
                <?php wp_nonce_field('aegisseo_fix_pack'); ?>
                <input type="hidden" name="action" value="aegisseo_apply_fix_pack" />
                <input type="hidden" name="pack" value="duplicate_titles" />
                <button class="button"><?php echo esc_html__('Fix duplicate titles', 'aegisseo'); ?></button>
            </form>
            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="margin:0;">
                <?php wp_nonce_field('aegisseo_fix_pack'); ?>
                <input type="hidden" name="action" value="aegisseo_apply_fix_pack" />
                <input type="hidden" name="pack" value="missing_og_image" />
                <button class="button"><?php echo esc_html__('Fix missing OG image', 'aegisseo'); ?></button>
            </form>
            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="margin:0;">
                <?php wp_nonce_field('aegisseo_fix_pack'); ?>
                <input type="hidden" name="action" value="aegisseo_apply_fix_pack" />
                <input type="hidden" name="pack" value="generate_meta_descriptions" />
                <button class="button"><?php echo esc_html__('Generate meta descriptions', 'aegisseo'); ?></button>
            </form>
            
            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="margin:0;">
                <?php wp_nonce_field('aegisseo_fix_pack'); ?>
                <input type="hidden" name="action" value="aegisseo_apply_fix_pack" />
                <input type="hidden" name="pack" value="orphan_pages" />
                <button class="button"><?php echo esc_html__('Find orphan pages', 'aegisseo'); ?></button>
            </form>
        </div>
    </div>
</div>

<p class="description"><?php echo esc_html__('One screen: find issues, apply safe fixes, and track what changed. ', 'aegisseo'); ?></p>

<?php if (empty($rows)): ?>
    <div class="notice notice-info"><p><?php echo esc_html__('No issues detected in the last 50 published posts/pages using current checks.', 'aegisseo'); ?></p></div>
<?php else: ?>
    <table class="widefat fixed striped">
        <thead>
            <tr>
                <th style="width:70px;"><?php echo esc_html__('ID', 'aegisseo'); ?></th>
                <th><?php echo esc_html__('Title', 'aegisseo'); ?></th>
                <th style="width:110px;"><?php echo esc_html__('Type', 'aegisseo'); ?></th>
                <th><?php echo esc_html__('Issues', 'aegisseo'); ?></th>
                <th style="width:240px;"><?php echo esc_html__('Fix', 'aegisseo'); ?></th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($rows as $r): ?>
            <tr>
                <td><?php echo (int) $r['ID']; ?></td>
                <td>
                    <strong><?php echo esc_html($r['title']); ?></strong>
                    <div class="row-actions">
                        <span class="edit"><a href="<?php echo esc_url(get_edit_post_link($r['ID'])); ?>"><?php echo esc_html__('Edit', 'aegisseo'); ?></a></span>
                        |
                        <span class="view"><a href="<?php echo esc_url(get_permalink($r['ID'])); ?>" target="_blank" rel="noopener"><?php echo esc_html__('View', 'aegisseo'); ?></a></span>
                    </div>
                </td>
                <td><?php echo esc_html($r['type']); ?></td>
                <td>
                    <ul style="margin:0; padding-left:18px;">
                        <?php foreach ($r['issues'] as $issue): ?>
                            <li><?php echo esc_html($issue); ?></li>
                        <?php endforeach; ?>
                    </ul>
                </td>
                <td>
                    <?php if ($r['desc_missing']): ?>
                        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="display:inline-block; margin:0;">
                            <?php wp_nonce_field('aegisseo_apply_fix'); ?>
                            <input type="hidden" name="action" value="aegisseo_apply_fix" />
                            <input type="hidden" name="post_id" value="<?php echo (int) $r['ID']; ?>" />
                            <input type="hidden" name="fix_type" value="gen_meta_desc" />
                            <button type="submit" class="button button-primary"><?php echo esc_html__('Generate Meta Description', 'aegisseo'); ?></button>
                        </form>
                    <?php else: ?>
                        <span class="dashicons dashicons-yes" style="color:#46b450;"></span>
                        <?php echo esc_html__('No safe one-click fix available (yet).', 'aegisseo'); ?>
                    <?php endif; ?>

<?php

$pid = (int) $r['ID'];

$current_schema_type = (string) get_post_meta($pid, '_aegisseo_schema_type', true);
$schema_sug = array();
if (isset(aegisseo()->autopilot) && aegisseo()->autopilot) {
    $schema_sug = aegisseo()->autopilot->suggest_schema($pid);
}

if ($current_schema_type === '' && !empty($schema_sug['type'])): ?>
    <div style="margin-top:10px; padding:10px; border:1px solid #dcdcde; background:#fff;">
        <strong><?php echo esc_html__('Autopilot: Schema Suggestion', 'aegisseo'); ?></strong>
        <div style="margin-top:6px;">
            <span class="dashicons dashicons-lightbulb" style="color:#2271b1;"></span>
            <?php echo esc_html($schema_sug['type']); ?>
            <span style="color:#666;">(<?php echo esc_html__('why', 'aegisseo'); ?>)</span>
        </div>
        <?php if (!empty($schema_sug['why']) && is_array($schema_sug['why'])): ?>
            <ul style="margin:6px 0 0 18px;">
                <?php foreach ($schema_sug['why'] as $w): ?>
                    <li><?php echo esc_html($w); ?></li>
                <?php endforeach; ?>
            </ul>
        <?php endif; ?>
        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="margin-top:8px;">
            <?php wp_nonce_field('aegisseo_schema_approve'); ?>
            <input type="hidden" name="action" value="aegisseo_schema_approve" />
            <input type="hidden" name="post_id" value="<?php echo (int) $pid; ?>" />
            <input type="hidden" name="schema_type" value="<?php echo esc_attr($schema_sug['type']); ?>" />
            <button type="submit" class="button button-secondary"><?php echo esc_html__('Approve & Apply Schema', 'aegisseo'); ?></button>
        </form>
    </div>
<?php elseif ($current_schema_type !== ''): ?>
    <div style="margin-top:10px; color:#1d2327;">
        <span class="dashicons dashicons-yes" style="color:#46b450;"></span>
        <?php echo esc_html__('Schema locked:', 'aegisseo'); ?> <strong><?php echo esc_html($current_schema_type); ?></strong>
    </div>
<?php endif; ?>

<?php
global $wpdb;
$tred = $wpdb->prefix . 'aegisseo_redirects';
$pending_redirects = $wpdb->get_results($wpdb->prepare(
    "SELECT * FROM {$tred} WHERE is_suggestion=1 AND suggestion_status=%s AND source_post_id=%d ORDER BY id DESC LIMIT 5",
    'pending',
    $pid
), ARRAY_A);

if (!empty($pending_redirects)): ?>
    <div style="margin-top:10px; padding:10px; border:1px solid #dcdcde; background:#fff;">
        <strong><?php echo esc_html__('Autopilot: Redirect Suggestions', 'aegisseo'); ?></strong>
        <ul style="margin:8px 0 0 18px;">
            <?php foreach ($pending_redirects as $pr): ?>
                <li style="margin-bottom:8px;">
                    <code><?php echo esc_html($pr['source']); ?></code>
                    &rarr;
                    <code><?php echo esc_html($pr['target']); ?></code>
                    <div style="margin-top:6px;">
                        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="display:inline-block; margin:0 6px 0 0;">
                            <?php wp_nonce_field('aegisseo_redirect_approve'); ?>
                            <input type="hidden" name="action" value="aegisseo_redirect_approve" />
                            <input type="hidden" name="id" value="<?php echo (int) $pr['id']; ?>" />
                            <button type="submit" class="button button-secondary button-small"><?php echo esc_html__('Approve & Enable', 'aegisseo'); ?></button>
                        </form>
                        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="display:inline-block; margin:0;">
                            <?php wp_nonce_field('aegisseo_redirect_dismiss'); ?>
                            <input type="hidden" name="action" value="aegisseo_redirect_dismiss" />
                            <input type="hidden" name="id" value="<?php echo (int) $pr['id']; ?>" />
                            <button type="submit" class="button button-link-delete button-small"><?php echo esc_html__('Dismiss', 'aegisseo'); ?></button>
                        </form>
                    </div>
                </li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<?php
$link_sugs = array();
if (isset(aegisseo()->autopilot) && aegisseo()->autopilot) {
    $max_links = 3;
if (function_exists('aegisseo') && isset(aegisseo()->options) && aegisseo()->options) {
    $max_links = (int) aegisseo()->options->get('autopilot_max_internal_links', 3);
    if ($max_links <= 0) { $max_links = 3; }
}
$link_sugs = aegisseo()->autopilot->suggest_internal_links($pid, $max_links);
}

if (!empty($link_sugs)): 
    $post_obj = get_post($pid);
    $orig = $post_obj ? (string)$post_obj->post_content : '';
    $preview = aegisseo()->autopilot->apply_internal_links($pid, $link_sugs, 3);
    $proposed = (!empty($preview['new_content'])) ? (string)$preview['new_content'] : $orig;
    ?>
    <div style="margin-top:10px; padding:10px; border:1px solid #dcdcde; background:#fff;">
        <strong><?php echo esc_html__('Autopilot: Internal Link Suggestions (max 3)', 'aegisseo'); ?></strong>
        <ul style="margin:8px 0 0 18px;">
            <?php foreach ($link_sugs as $ls): ?>
                <li>
                    <em><?php echo esc_html($ls['anchor']); ?></em>
                    &rarr;
                    <a href="<?php echo esc_url(get_edit_post_link((int)$ls['target_id'])); ?>"><?php echo esc_html($ls['title']); ?></a>
                </li>
            <?php endforeach; ?>
        </ul>

        <details style="margin-top:8px;">
            <summary><?php echo esc_html__('Preview diff (safe preview)', 'aegisseo'); ?></summary>
            <div style="margin-top:8px; background:#fff;">
                <?php
                if (function_exists('wp_text_diff')) {
                    echo wp_text_diff(wp_strip_all_tags($orig), wp_strip_all_tags($proposed), array('show_split_view' => true));
                } else {
                    echo '<pre style="white-space:pre-wrap;">' . esc_html(wp_strip_all_tags($proposed)) . '</pre>';
                }
                ?>
            </div>
        </details>

        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="margin-top:8px;">
            <?php wp_nonce_field('aegisseo_apply_links'); ?>
            <input type="hidden" name="action" value="aegisseo_apply_links" />
            <input type="hidden" name="post_id" value="<?php echo (int) $pid; ?>" />
            <button type="submit" class="button button-secondary"><?php echo esc_html__('Approve & Apply Links', 'aegisseo'); ?></button>
            <span class="description" style="margin-left:6px;"><?php echo esc_html__('Applies up to 3 internal links by inserting anchors into safe text nodes only.', 'aegisseo'); ?></span>
        </form>
    </div>
<?php endif; ?>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
<?php endif; ?>


<hr style="margin:24px 0;" />
<h2><?php echo esc_html__('Recent SEO Events', 'aegisseo'); ?></h2>
<p class="description"><?php echo esc_html__('Aegis-style audit trail. Rollback restores the previous value for AegisSEO meta fields.', 'aegisseo'); ?></p>

<?php
// === Events filtering (UI) ===
// Default content types (checked):
$evt_default = array(); // block everything unless enabled

// Auto-include common FAQ/DOC post types if they exist on this site.
foreach (array('faq','faqs','document','documents','doc','docs') as $maybe_pt) {
    if (post_type_exists($maybe_pt)) { $evt_default[] = $maybe_pt; }
}

// Per-user saved filters (so selections persist when leaving the tab).
$evt_filters_meta_key = 'aegisseo_issues_evt_filters_v1';
$evt_saved = array();

if (is_user_logged_in()) {
    $evt_saved = get_user_meta(get_current_user_id(), $evt_filters_meta_key, true);
    if (!is_array($evt_saved)) { $evt_saved = array(); }
}

$evt_saved_pts = array();
if (isset($evt_saved['evt_pt']) && is_array($evt_saved['evt_pt'])) {
    foreach ($evt_saved['evt_pt'] as $pt) {
        $pt = sanitize_key((string) $pt);
        if ($pt !== '') { $evt_saved_pts[] = $pt; }
    }
}
$evt_saved_pts = array_values(array_unique($evt_saved_pts));

$evt_saved_plugin = '';
if (isset($evt_saved['evt_plugin'])) {
    $evt_saved_plugin = sanitize_key((string) $evt_saved['evt_plugin']);
}

// Read selected checkboxes (prefer GET; otherwise fallback to saved).
$evt_selected = array();
if (isset($_GET['evt_pt'])) {
    $raw = $_GET['evt_pt'];
    if (!is_array($raw)) { $raw = array($raw); }
    foreach ($raw as $pt) {
        $pt = sanitize_key((string) $pt);
        if ($pt !== '') { $evt_selected[] = $pt; }
    }
} else {
    $evt_selected = $evt_saved_pts;
}
$evt_selected = array_values(array_unique($evt_selected));

// Plugin dropdown option (prefer GET; otherwise fallback to saved).
$evt_plugin = isset($_GET['evt_plugin'])
    ? sanitize_key((string) $_GET['evt_plugin'])
    : $evt_saved_plugin;

$evt_plugin_pts = array();

// Build plugin dropdown list from registered post types.
$all_pts = get_post_types(array(), 'names');
$plugin_options = array(); // key => label

if (is_array($all_pts)) {
    foreach ($all_pts as $pt) {
        $pt = (string) $pt;
        if ($pt === '' || $pt === 'aegisseo' || stripos($pt, 'aegisseo') === 0) { continue; }

        // Candidate plugin-ish post types: non-public or prefixed types (aegis*, as_*, etc.)
        $obj = get_post_type_object($pt);
        $is_public = ($obj && !empty($obj->public));
        $is_pluginish = (!$is_public) || (stripos($pt, 'aegis') === 0) || (stripos($pt, 'as_') === 0);

        if (!$is_pluginish) { continue; }

        // Group key heuristic: first token before "_" or full prefix.
        $key = $pt;
        if (false !== strpos($pt, '_')) { $key = substr($pt, 0, strpos($pt, '_')); }
        if ($key === '') { $key = $pt; }

        // Only keep plausible plugin keys.
        if (strlen($key) < 3) { continue; }
        if (stripos($key, 'aegis') !== 0 && stripos($key, 'as') !== 0) { continue; }

        if (!isset($plugin_options[$key])) {
            $plugin_options[$key] = strtoupper($key);
        }
        if ($evt_plugin && $key === $evt_plugin) {
            $evt_plugin_pts[] = $pt;
        }
    }
}

$evt_allowed_pts = array_values(array_unique(array_merge($evt_selected, $evt_plugin_pts)));

if (is_user_logged_in() && isset($_GET['evt_save'])) {
    $nonce = isset($_GET['aegisseo_evt_nonce']) ? sanitize_text_field((string) $_GET['aegisseo_evt_nonce']) : '';
    if ($nonce && wp_verify_nonce($nonce, 'aegisseo_save_evt_filters')) {
        update_user_meta(
            get_current_user_id(),
            $evt_filters_meta_key,
            array(
                'evt_pt'     => $evt_selected,
                'evt_plugin' => $evt_plugin,
            )
        );
    }
}

// Helper for checkbox checked state.
function aegisseo_evt_pt_checked($pt, $selected) {
    return in_array($pt, $selected, true) ? 'checked="checked"' : '';
}
?>

<form method="get" style="margin:0 0 12px 0;">
    <?php
    // Preserve current page/tab query args.
    foreach ($_GET as $k => $v) {
        if (in_array($k, array('evt_page','evt_pt','evt_plugin'), true)) { continue; }
        if (is_array($v)) { continue; }
        echo '<input type="hidden" name="' . esc_attr($k) . '" value="' . esc_attr((string) $v) . '" />';
    }
    ?>
	<?php wp_nonce_field('aegisseo_save_evt_filters', 'aegisseo_evt_nonce'); ?>
    <div style="display:flex; align-items:center; gap:12px; flex-wrap:wrap;">
        <strong><?php echo esc_html__('Show events for:', 'aegisseo'); ?></strong>

        <label style="display:inline-flex; align-items:center; gap:6px;">
            <input type="checkbox" name="evt_pt[]" value="page" <?php echo aegisseo_evt_pt_checked('page', $evt_selected); ?> />
            <?php echo esc_html__('Pages', 'aegisseo'); ?>
        </label>

        <label style="display:inline-flex; align-items:center; gap:6px;">
            <input type="checkbox" name="evt_pt[]" value="post" <?php echo aegisseo_evt_pt_checked('post', $evt_selected); ?> />
            <?php echo esc_html__('Posts', 'aegisseo'); ?>
        </label>

        <label style="display:inline-flex; align-items:center; gap:6px;">
            <input type="checkbox" name="evt_pt[]" value="faq" <?php echo aegisseo_evt_pt_checked('faq', $evt_selected); ?> />
            <?php echo esc_html__('FAQ', 'aegisseo'); ?>
        </label>

        <label style="display:inline-flex; align-items:center; gap:6px;">
            <input type="checkbox" name="evt_pt[]" value="document" <?php echo aegisseo_evt_pt_checked('document', $evt_selected); ?> />
            <?php echo esc_html__('Documents', 'aegisseo'); ?>
        </label>

        <label style="display:inline-flex; align-items:center; gap:6px;">
            <input type="checkbox" name="evt_pt[]" value="attachment" <?php echo aegisseo_evt_pt_checked('attachment', $evt_selected); ?> />
            <?php echo esc_html__('Images/Video', 'aegisseo'); ?>
        </label>

        <span style="margin-left:6px;"><?php echo esc_html__('Include plugin reports:', 'aegisseo'); ?></span>
        <select name="evt_plugin">
            <option value=""><?php echo esc_html__('— None —', 'aegisseo'); ?></option>
            <?php foreach ($plugin_options as $k => $label): ?>
                <option value="<?php echo esc_attr($k); ?>" <?php selected($evt_plugin, $k); ?>><?php echo esc_html($label); ?></option>
            <?php endforeach; ?>
        </select>

        <button class="button button-primary" type="submit" name="evt_save" value="1">
			<?php echo esc_html__('Save', 'aegisseo'); ?>
		</button>
    </div>
</form>
<?php
// Selection-only list (content objects). Block everything unless enabled.
$evt_selected_labels = array();
$evt_label_map = array(
    'page'      => __('Pages', 'aegisseo'),
    'post'      => __('Posts', 'aegisseo'),
    'attachment'=> __('Images/Video', 'aegisseo'),
    'faq'       => __('FAQ', 'aegisseo'),
    'faqs'      => __('FAQ', 'aegisseo'),
    'document'  => __('Documents', 'aegisseo'),
    'documents' => __('Documents', 'aegisseo'),
    'doc'       => __('Documents', 'aegisseo'),
    'docs'      => __('Documents', 'aegisseo'),
);
foreach ($evt_selected as $pt) {
    $evt_selected_labels[] = isset($evt_label_map[$pt]) ? $evt_label_map[$pt] : $pt;
}
?>
<div style="border:1px solid #dcdcde; background:#fff; padding:12px; margin:12px 0;">
    <div style="margin:0 0 8px 0;">
        <strong><?php echo esc_html__('Selection List (Enabled Only)', 'aegisseo'); ?></strong>
        <span style="color:#666; margin-left:8px;"><?php echo esc_html__('This list is based ONLY on the checkboxes above. Nothing is shown unless enabled.', 'aegisseo'); ?></span>
    </div>

    <?php if (empty($evt_selected)) : ?>
        <p style="margin:0;"><?php echo esc_html__('No post types enabled. Check one or more boxes above and click Apply.', 'aegisseo'); ?></p>
    <?php else : ?>
        <div style="margin:0 0 10px 0;">
            <?php foreach ($evt_selected_labels as $lbl) : ?>
                <span style="display:inline-block; padding:2px 8px; border:1px solid #dcdcde; border-radius:999px; margin:0 6px 6px 0; background:#f6f7f7;">
                    <?php echo esc_html($lbl); ?>
                </span>
            <?php endforeach; ?>
        </div>
        <?php
            
        // Pagination: Selection List
        $sel_per_page = isset($_GET['sel_per_page']) ? (int) $_GET['sel_per_page'] : 25;
        if (!in_array($sel_per_page, array(25, 50), true)) { $sel_per_page = 25; }
        $sel_paged = isset($_GET['sel_paged']) ? max(1, (int) $_GET['sel_paged']) : 1;
// List recent objects for the enabled post types (do not include plugin reports here).
            $evt_list_q = new WP_Query(array(
                'post_type'      => $evt_selected,
                'post_status'    => 'any',
                'posts_per_page' => $sel_per_page,
                'orderby'        => 'modified',
                'order'          => 'DESC',
                'no_found_rows'  => false,
                'paged'          => $sel_paged,
                'fields'         => 'ids',
            ));
        ?>
        <?php
        // Selection List pagination UI
        $sel_total = (int) $evt_list_q->found_posts;
        $sel_total_pages = (int) $evt_list_q->max_num_pages;
        $sel_base_args = $_GET;
        ?>
        <div style="display:flex; align-items:center; gap:10px; margin:10px 0 8px 0;">
            <label for="aegisseo-sel-per-page"><strong><?php echo esc_html__('Per page:', 'aegisseo'); ?></strong></label>
            <select id="aegisseo-sel-per-page">
                <option value="25" <?php selected($sel_per_page, 25); ?>>25</option>
                <option value="50" <?php selected($sel_per_page, 50); ?>>50</option>
            </select>
            <?php if ($sel_total_pages > 1): ?>
                <span style="color:#666;"><?php echo esc_html(sprintf(__('Page %d of %d', 'aegisseo'), $sel_paged, $sel_total_pages)); ?></span>
            <?php endif; ?>
            <span style="margin-left:auto;"></span>
            <?php if ($sel_total_pages > 1): ?>
                <div class="tablenav-pages" style="margin:0;">
                    <?php
                    $sel_base_args['sel_per_page'] = $sel_per_page;
                    $sel_base_args['sel_paged'] = '%#%';
                    echo paginate_links(array(
                        'base'      => esc_url(add_query_arg($sel_base_args)),
                        'format'    => '',
                        'current'   => $sel_paged,
                        'total'     => $sel_total_pages,
                        'prev_text' => '&lsaquo;',
                        'next_text' => '&rsaquo;',
                        'type'      => 'plain',
                    ));
                    ?>
                </div>
            <?php endif; ?>
        </div>

        <form id="aegisseo-selectionlist-form" method="post" action="#">
            <button type="button" class="button" id="aegisseo-sel-rollback-selected" disabled>
                <?php echo esc_html__('Rollback Selected', 'aegisseo'); ?>
            </button>
            <span class="description" style="margin-left:8px;">
                <?php echo esc_html__('Rollback the most recent AegisSEO change for each selected item.', 'aegisseo'); ?>
            </span>

            <table class="widefat striped" style="margin-top:10px;">
                <thead>
                    <tr>
                        <th style="width:34px;"><input type="checkbox" id="aegisseo-sel-select-all" /></th>
                        <th style="width:160px;"><?php echo esc_html__('When', 'aegisseo'); ?></th>
                        <th style="width:110px;"><?php echo esc_html__('Type', 'aegisseo'); ?></th>
                        <th><?php echo esc_html__('Object', 'aegisseo'); ?></th>
                        <th style="width:170px;"><?php echo esc_html__('Field', 'aegisseo'); ?></th>
                        <th><?php echo esc_html__('Old', 'aegisseo'); ?></th>
                        <th><?php echo esc_html__('New', 'aegisseo'); ?></th>
                        <th style="width:180px;"><?php echo esc_html__('User', 'aegisseo'); ?></th>
                        <th style="width:140px;"><?php echo esc_html__('Action', 'aegisseo'); ?></th>
                    </tr>
                </thead>
                <tbody>
                <?php if (empty($evt_list_q->posts)) : ?>
                    <tr><td colspan="9"><?php echo esc_html__('No items to show. Enable one or more content types above and click Save.', 'aegisseo'); ?></td></tr>
                <?php else : ?>
                    <?php
					// Build a "latest event" map for meta description so Selection List can show Old/New + Rollback
					$sel_evt_map = array();

					// Pull a larger slice of recent events (same source as bottom table)
					$sel_recent_events = aegisseo()->events->get_recent_paged(2000, 0, null, null, $evt_allowed_pts);

					if (!empty($sel_recent_events)) {
						foreach ($sel_recent_events as $ev) {
							$otype = isset($ev['object_type']) ? (string) $ev['object_type'] : '';
							$oid   = isset($ev['object_id']) ? (int) $ev['object_id'] : 0;
							$mkey  = isset($ev['meta_key']) ? (string) $ev['meta_key'] : '';

							// We only care about post meta description events
							if ($otype !== 'post' || $oid <= 0) { continue; }
							if ($mkey !== '_aegisseo_description') { continue; }

							// Only keep the most recent event per post
							if (!isset($sel_evt_map[$oid])) {
								$sel_evt_map[$oid] = $ev; // contains id, old_value, new_value, event_type, user_id, created_at, etc.
							}
						}
					}

                    foreach ($evt_list_q->posts as $pid) :
                        $p = get_post($pid);
                        if (!$p) { continue; }
                        $ptype = (string) $p->post_type;
                        $when = !empty($p->post_modified_gmt) ? get_date_from_gmt($p->post_modified_gmt, 'Y-m-d H:i:s') : '';
                        $email = '';
                        if (!empty($p->post_author)) {
                            $u = get_user_by('id', (int) $p->post_author);
                            if ($u && !empty($u->user_email)) { $email = $u->user_email; }
                        }

                        $title = get_the_title($pid);
                        if ($title === '') { $title = sprintf('#%d', $pid); }
                        $edit_link = get_edit_post_link($pid, '');

                        $cur_desc = (string) get_post_meta($pid, '_aegisseo_description', true);
                        $needs_desc = (mb_strlen(trim($cur_desc)) < 160);

                    ?>
                        <tr>
                            <td><input type="checkbox" class="aegisseo-sel-row" value="<?php echo esc_attr($pid); ?>" /></td>
                            <td><?php echo esc_html($when); ?></td>
                            <td><span class="aegisseo-pill"><?php echo esc_html($ptype); ?></span></td>
                            <td>
                                <?php if ($edit_link): ?>
                                    <a href="<?php echo esc_url($edit_link); ?>"><?php echo esc_html($title); ?></a>
                                <?php else: ?>
                                    <?php echo esc_html($title); ?>
                                <?php endif; ?>
                                <span style="color:#666;"><?php echo ' (' . esc_html($ptype) . ')'; ?></span>
                            </td>
							<td><?php echo esc_html($needs_desc ? 'meta_description' : '—'); ?></td>

							<?php
							$oldv = '—';
							$newv = '—';

							// Pull latest event for this post (if any)
							$sel_ev = isset($sel_evt_map[$pid]) ? $sel_evt_map[$pid] : null;

							if ($sel_ev) {
								$oldv = isset($sel_ev['old_value']) ? $sel_ev['old_value'] : '—';
								$newv = isset($sel_ev['new_value']) ? $sel_ev['new_value'] : '—';

								// Normalize empty values
								if ($oldv === null || (is_string($oldv) && trim($oldv) === '')) { $oldv = '—'; }
								if ($newv === null || (is_string($newv) && trim($newv) === '')) { $newv = '—'; }
							}
							?>
							<td>
							  <span title="<?php echo esc_attr((string) $oldv); ?>">
								<?php echo esc_html(function_exists('aegisseo_evt_short') ? aegisseo_evt_short($oldv) : wp_html_excerpt($oldv, 80, '...')); ?>
							  </span>
							</td>
							<td>
							  <span title="<?php echo esc_attr((string) $newv); ?>">
								<?php echo esc_html(function_exists('aegisseo_evt_short') ? aegisseo_evt_short($newv) : wp_html_excerpt($newv, 80, '...')); ?>
							  </span>
							</td>

							<td><?php echo esc_html($email); ?></td>
							<td>
							  <?php
							// Local copies (Selection List renders before the bottom table defines these arrays).
							$sel_can_rollback_keys = array(
								'_aegisseo_title',
								'_aegisseo_description',
								'_aegisseo_canonical',
								'_aegisseo_robots',
								'_aegisseo_focus_phrase',
								'_aegisseo_schema_mode',
								'post_content',
							);

							$sel_can_rollback_types = array('meta_add','meta_update','meta_delete','fix_applied','links_applied');

							$sel_ev   = isset($sel_evt_map[$pid]) ? $sel_evt_map[$pid] : null;
							  $can_rb   = false;
							  $event_id = 0;

							  if ($sel_ev) {
								  $otype = isset($sel_ev['object_type']) ? (string) $sel_ev['object_type'] : '';
								  $etype = isset($sel_ev['event_type']) ? (string) $sel_ev['event_type'] : '';
								  $mkey  = isset($sel_ev['meta_key']) ? (string) $sel_ev['meta_key'] : '';
								  $event_id = isset($sel_ev['id']) ? (int) $sel_ev['id'] : 0;

								  $old_tmp = isset($sel_ev['old_value']) ? (string) $sel_ev['old_value'] : '';
								  $new_tmp = isset($sel_ev['new_value']) ? (string) $sel_ev['new_value'] : '';

								  // Match bottom rules: post + allowed types + allowed keys + must actually differ
								  $can_rb = ($otype === 'post'
									  && $event_id > 0
									  && in_array($etype, $sel_can_rollback_types, true)
									  && in_array($mkey,  $sel_can_rollback_keys,  true)
								  );

								  if ($can_rb && $old_tmp === $new_tmp) { $can_rb = false; }
							  }

							  if ($can_rb): ?>
								  <!-- SAME as bottom table: aegisseo_rollback_event -->
								  <form method="post"
										action="<?php echo esc_url(admin_url('admin-post.php')); ?>"
										style="margin:0;"
										onsubmit="return confirm('<?php echo esc_js(__('Rollback this change?', 'aegisseo')); ?>');">
									  <?php wp_nonce_field('aegisseo_rollback_event'); ?>
									  <input type="hidden" name="action" value="aegisseo_rollback_event" />
									  <input type="hidden" name="event_id" value="<?php echo (int) $event_id; ?>" />
									  <button type="submit" class="button button-small"><?php echo esc_html__('Rollback', 'aegisseo'); ?></button>
								  </form>

							  <?php elseif ($needs_desc): ?>
								  <!-- SAME as top Fix Packs: aegisseo_apply_fix -->
								  <form method="post"
										action="<?php echo esc_url(admin_url('admin-post.php')); ?>"
										style="margin:0;"
										onsubmit="return confirm('<?php echo esc_js(__('Generate meta description now?', 'aegisseo')); ?>');">
									  <?php wp_nonce_field('aegisseo_apply_fix'); ?>
									  <input type="hidden" name="action" value="aegisseo_apply_fix" />
									  <input type="hidden" name="post_id" value="<?php echo (int) $pid; ?>" />
									  <input type="hidden" name="fix_type" value="gen_meta_desc" />
									  <button type="submit" class="button button-small button-primary"><?php echo esc_html__('Generate Meta', 'aegisseo'); ?></button>
								  </form>

							  <?php else: ?>
								  <a class="button button-small" href="<?php echo esc_url($edit_link); ?>">
									  <?php echo esc_html__('Edit', 'aegisseo'); ?>
								  </a>
							  <?php endif; ?>
							</td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </form>

        <script>
        (function($){
            // per-page selector reload
            $('#aegisseo-sel-per-page').on('change', function(){
                var v = $(this).val();
                var url = new URL(window.location.href);
                url.searchParams.set('sel_per_page', v);
                url.searchParams.set('sel_paged', '1');
                window.location.href = url.toString();
            });

            // select all
            $('#aegisseo-sel-select-all').on('change', function(){
                $('.aegisseo-sel-row').prop('checked', this.checked).trigger('change');
            });

            function selUpdateBtn(){
                var any = $('.aegisseo-sel-row:checked').length > 0;
                $('#aegisseo-sel-rollback-selected').prop('disabled', !any);
            }
            $(document).on('change', '.aegisseo-sel-row', selUpdateBtn);
            selUpdateBtn();

            // Mass rollback selected (meta description snapshot only)
            $('#aegisseo-sel-rollback-selected').on('click', function(e){
                e.preventDefault();
                var ids = $('.aegisseo-sel-row:checked').map(function(){ return $(this).val(); }).get();
                if (!ids.length) return;
                if (!confirm('Rollback the last generated Meta Description for selected items?')) return;

                var i = 0;
                function next(){
                    if (i >= ids.length) { window.location.reload(); return; }
                    var pid = ids[i++];
                    $.post(ajaxurl, {action:'aegisseo_quick_rollback', nonce: "<?php echo esc_js(wp_create_nonce('aegisseo_quick_fix')); ?>", post_id: pid, field:'meta_description'})
                      .always(next);
                }
                next();
            });
        })(jQuery);
        </script>

    <?php endif; ?>
</div>


<?php
$events = array();
if (isset(aegisseo()->events) && aegisseo()->events) {
	$per_page = isset($_GET['evt_per_page']) ? (int) $_GET['evt_per_page'] : 25;
    if (!in_array($per_page, array(25, 50), true)) { $per_page = 25; }

	$page = isset($_GET['evt_page']) ? max(1, (int) $_GET['evt_page']) : 1;
	$offset = ($page - 1) * $per_page;

	// You will implement these two methods in the events class:
	if (empty($evt_allowed_pts)) {
        // Block everything unless explicitly enabled via the checkboxes or plugin dropdown.
        $total = 0;
        $events = array();
    } else {
        $total = (int) aegisseo()->events->count_all(null, null, $evt_allowed_pts);
        $events = aegisseo()->events->get_recent_paged($per_page, $offset, null, null, $evt_allowed_pts);
    }
	$total_pages = ($per_page > 0) ? max(1, (int) ceil($total / $per_page)) : 1;
}

$can_rollback_keys = array(
    '_aegisseo_title',
    '_aegisseo_description',
    '_aegisseo_canonical',
    '_aegisseo_robots',
    '_aegisseo_focus_phrase',
    '_aegisseo_schema_mode',
    'post_content',
);

$can_rollback_types = array('meta_add','meta_update','meta_delete','fix_applied','links_applied');

function aegisseo_evt_short($v) {
    if (null === $v) { return '—'; }
    $v = (string) $v;
    $v = trim($v);
    if ($v === '') { return '—'; }
    if (mb_strlen($v) > 80) { return mb_substr($v, 0, 80) . '…'; }
    return $v;
}
?>

<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" id="aegisseo-bulk-rollback-form" style="margin:0;">
    <?php wp_nonce_field('aegisseo_bulk_rollback_events'); ?>
    <input type="hidden" name="action" value="aegisseo_bulk_rollback_events" />

    <div style="margin:10px 0;">
        <button type="submit" class="button button-secondary" id="aegisseo-bulk-rollback-btn" disabled onclick="return confirm('<?php echo esc_js(__('Rollback selected changes?', 'aegisseo')); ?>');">
            <?php echo esc_html__('Rollback Selected', 'aegisseo'); ?>
        </button>
        <span class="description" style="margin-left:10px;"><?php echo esc_html__('Select multiple rollbackable rows and rollback in one action.', 'aegisseo'); ?></span>
    </div>
	
	<div style="margin:8px 0 12px; display:flex; align-items:center; gap:10px;">
		<strong><?php echo esc_html(sprintf(__('Total events: %d', 'aegisseo'), $total)); ?></strong>
        <span style="margin-left:auto;"></span>
        <label for="aegisseo-evt-per-page"><strong><?php echo esc_html__('Per page:', 'aegisseo'); ?></strong></label>
        <select id="aegisseo-evt-per-page">
            <option value="25" <?php selected($per_page, 25); ?>>25</option>
            <option value="50" <?php selected($per_page, 50); ?>>50</option>
        </select>
	</div>


	<?php if ($total_pages > 1): ?>
		<div class="tablenav top">
			<div class="tablenav-pages">
				<?php
				$base_url = remove_query_arg(array('evt_page'), $_SERVER['REQUEST_URI']);
				$prev = max(1, $page - 1);
				$next = min($total_pages, $page + 1);

				echo '<span class="pagination-links">';
				if ($page > 1) {
					echo '<a class="prev-page button" href="' . esc_url(add_query_arg('evt_page', $prev, $base_url)) . '">&lsaquo;</a> ';
				} else {
					echo '<span class="tablenav-pages-navspan button disabled">&lsaquo;</span> ';
				}

				echo '<span class="paging-input">' . esc_html($page) . ' / ' . esc_html($total_pages) . '</span>';

				if ($page < $total_pages) {
					echo ' <a class="next-page button" href="' . esc_url(add_query_arg('evt_page', $next, $base_url)) . '">&rsaquo;</a>';
				} else {
					echo ' <span class="tablenav-pages-navspan button disabled">&rsaquo;</span>';
				}
				echo '</span>';
				?>
			</div>
		</div>
	<?php endif; ?>

<table class="widefat striped">
    <thead>
        <tr>
            <th style="width:34px;"><input type="checkbox" id="aegisseo-evt-select-all" /></th>
            <th style="width:140px;"><?php echo esc_html__('When', 'aegisseo'); ?></th>
            <th style="width:110px;"><?php echo esc_html__('Type', 'aegisseo'); ?></th>
            <th><?php echo esc_html__('Object', 'aegisseo'); ?></th>
            <th style="width:170px;"><?php echo esc_html__('Field', 'aegisseo'); ?></th>
            <th><?php echo esc_html__('Old', 'aegisseo'); ?></th>
            <th><?php echo esc_html__('New', 'aegisseo'); ?></th>
            <th style="width:90px;"><?php echo esc_html__('User', 'aegisseo'); ?></th>
            <th style="width:110px;"><?php echo esc_html__('Action', 'aegisseo'); ?></th>
        </tr>
    </thead>
    <tbody>
    <?php if (empty($events)) : ?>
        <tr><td colspan="9"><?php echo esc_html__('No events recorded yet.', 'aegisseo'); ?></td></tr>
    <?php else : ?>
        <?php foreach ($events as $e) : ?>
            <?php
                $etype = isset($e['event_type']) ? (string) $e['event_type'] : '';
                $otype = isset($e['object_type']) ? (string) $e['object_type'] : '';
                $oid   = isset($e['object_id']) ? (int) $e['object_id'] : 0;
                $mkey  = isset($e['meta_key']) ? (string) $e['meta_key'] : '';
                $oldv  = isset($e['old_value']) ? $e['old_value'] : null;
                $newv  = isset($e['new_value']) ? $e['new_value'] : null;
                $when  = isset($e['created_at']) ? (string) $e['created_at'] : '';
                $uid   = isset($e['user_id']) ? (int) $e['user_id'] : 0;

                $obj_label = $otype . ':' . $oid;
                $obj_link = '';
                if ($otype === 'post' && $oid > 0) {
                    $ptitle = get_the_title($oid);
                    if ($ptitle) {
                        $obj_label = $ptitle . ' (#' . $oid . ')';
                        $obj_link = get_edit_post_link($oid, '');
                    }
                }

                $u = $uid ? get_userdata($uid) : null;
                $uname = ($u && !empty($u->user_login)) ? $u->user_login : '—';

                $can_rb = ($otype === 'post' && in_array($etype, $can_rollback_types, true) && in_array($mkey, $can_rollback_keys, true));
                if ($can_rb && (string)$oldv === (string)$newv) { $can_rb = false; }
            ?>
            <tr>
                <td style="text-align:center;">
                    <?php if ($can_rb) : ?>
                        <input type="checkbox" class="aegisseo-evt-cb" name="event_ids[]" value="<?php echo (int) $e['id']; ?>" />
                    <?php else : ?>
                        <input type="checkbox" disabled />
                    <?php endif; ?>
                </td>
                <td><?php echo esc_html($when); ?></td>
                <td><code><?php echo esc_html($etype); ?></code></td>
                <td>
                    <?php if ($obj_link) : ?>
                        <a href="<?php echo esc_url($obj_link); ?>"><?php echo esc_html($obj_label); ?></a>
                    <?php else : ?>
                        <?php echo esc_html($obj_label); ?>
                    <?php endif; ?>
                </td>
                <td><code><?php echo esc_html($mkey ? $mkey : '—'); ?></code></td>
                <td><span title="<?php echo esc_attr((string)$oldv); ?>"><?php echo esc_html(aegisseo_evt_short($oldv)); ?></span></td>
                <td><span title="<?php echo esc_attr((string)$newv); ?>"><?php echo esc_html(aegisseo_evt_short($newv)); ?></span></td>
                <td><?php echo esc_html($uname); ?></td>
                <td>
                    <?php if ($can_rb) : ?>
                        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="margin:0; display:inline-block;" onsubmit="return confirm('<?php echo esc_js(__('Rollback this change?', 'aegisseo')); ?>');">
                            <?php wp_nonce_field('aegisseo_rollback_event'); ?>
                            <input type="hidden" name="action" value="aegisseo_rollback_event" />
                            <input type="hidden" name="event_id" value="<?php echo (int) $e['id']; ?>" />
                            <button type="submit" class="button button-small"><?php echo esc_html__('Rollback', 'aegisseo'); ?></button>
                        </form>
                    <?php else : ?>
                        <span style="color:#666;">—</span>
                    <?php endif; ?>
                </td>
            </tr>
        <?php endforeach; ?>
    <?php endif; ?>
    </tbody>
</table>

<script>
(function($){
  $('#aegisseo-evt-per-page').on('change', function(){
    var v = $(this).val();
    var url = new URL(window.location.href);
    url.searchParams.set('evt_per_page', v);
    url.searchParams.set('evt_page', '1');
    window.location.href = url.toString();
  });
})(jQuery);
</script>


<?php
    // Live previews (SERP + Social) shown below Events.
    $aegisseo_prev_url   = home_url('/');
    $aegisseo_prev_host  = preg_replace('#^https?://#', '', $aegisseo_prev_url);
    $aegisseo_prev_title = get_bloginfo('name');
    $aegisseo_prev_desc  = get_bloginfo('description');
?>
<div style="display:flex; gap:16px; margin-top:16px; flex-wrap:wrap;">
    <div style="flex:1; min-width:320px; border:1px solid #dcdcde; background:#fff; padding:12px;">
        <h4 style="margin:0 0 8px 0;"><?php echo esc_html__('Live SERP Preview', 'aegisseo'); ?></h4>
        <div style="margin:0 0 8px 0;">
            <button type="button" class="button button-small aegisseo-device-toggle is-active" data-device="desktop"><?php echo esc_html__('Desktop', 'aegisseo'); ?></button>
            <button type="button" class="button button-small aegisseo-device-toggle" data-device="mobile"><?php echo esc_html__('Mobile', 'aegisseo'); ?></button>
        </div>
        <div class="aegisseo-serp-preview" data-device="desktop">
            <div style="color:#1d2327; font-size:18px; line-height:1.3; margin-bottom:2px;"><?php echo esc_html($aegisseo_prev_title); ?></div>
            <div style="color:#006621; font-size:13px; margin-bottom:4px;"><?php echo esc_html($aegisseo_prev_host); ?></div>
            <div style="color:#3c4043; font-size:13px;"><?php echo esc_html($aegisseo_prev_desc); ?></div>
        </div>
    </div>

    <div style="flex:1; min-width:320px; border:1px solid #dcdcde; background:#fff; padding:12px;">
        <h4 style="margin:0 0 8px 0;"><?php echo esc_html__('Live Social Preview', 'aegisseo'); ?></h4>
        <div style="margin:0 0 8px 0;">
            <button type="button" class="button button-small aegisseo-social-toggle is-active" data-social="og"><?php echo esc_html__('Open Graph', 'aegisseo'); ?></button>
            <button type="button" class="button button-small aegisseo-social-toggle" data-social="twitter"><?php echo esc_html__('Twitter', 'aegisseo'); ?></button>
        </div>
        <div class="aegisseo-social-preview" data-social="og" style="border:1px solid #dcdcde; display:flex; min-height:90px;">
            <div style="width:120px; background:#f6f7f7; display:flex; align-items:center; justify-content:center; color:#666; font-size:12px;">
                <?php echo esc_html__('No image set', 'aegisseo'); ?>
            </div>
            <div style="padding:10px;">
                <div style="color:#6a6a6a; font-size:11px; margin-bottom:4px;"><?php echo esc_html(strtoupper((string) parse_url($aegisseo_prev_url, PHP_URL_HOST))); ?></div>
                <div style="font-weight:600; margin-bottom:2px;"><?php echo esc_html($aegisseo_prev_title); ?></div>
                <div style="color:#3c4043; font-size:13px;"><?php echo esc_html($aegisseo_prev_desc); ?></div>
            </div>
        </div>
    </div>
</div>

<script>
jQuery(function($){
    var $form = $('#aegisseo-bulk-rollback-form');
    if (!$form.length) { return; }

    var $selectAll = $('#aegisseo-evt-select-all');
    var $boxes = $form.find('input.aegisseo-evt-cb');
    var $btn = $('#aegisseo-bulk-rollback-btn');

    function sync(){
        var checked = $boxes.filter(':checked').length;

        // Enable/disable the bulk rollback button
        $btn.prop('disabled', checked === 0);

        // Header checkbox states
        if ($selectAll.length) {
            $selectAll.prop('checked', checked > 0 && checked === $boxes.length);
            $selectAll.prop('indeterminate', checked > 0 && checked < $boxes.length);
        }
    }

    // Use namespaced handlers so we don’t double-bind
    $selectAll.off('change.aegisseo').on('change.aegisseo', function(){
        var on = $(this).is(':checked');
        $boxes.prop('checked', on);
        sync();
    });

    $form.off('change.aegisseo', 'input.aegisseo-evt-cb')
         .on('change.aegisseo', 'input.aegisseo-evt-cb', function(){
            sync();
         });

    sync();
});
</script>
</form>

<?php
$orphans = get_posts(array(
    'post_type' => 'page',
    'post_status' => 'publish',
    'numberposts' => 50,
    'meta_key' => '_aegisseo_orphan',
    'meta_value' => '1',
    'fields' => 'ids',
));
if (!empty($orphans)):
?>
<div style="margin-top:16px; padding:12px; border:1px solid #dcdcde; background:#fff; border-radius:8px;">
    <strong><?php echo esc_html__('Orphan Pages (needs internal links)', 'aegisseo'); ?></strong>
    <p class="description" style="margin-top:6px;"><?php echo esc_html__('These pages were detected as having no inbound mentions in published content (best-effort). Add at least one internal link from a relevant hub page.', 'aegisseo'); ?></p>
    <ul style="margin:8px 0 0; padding-left:18px;">
        <?php foreach ((array)$orphans as $oid): ?>
            <li>
                <a href="<?php echo esc_url(get_edit_post_link((int)$oid)); ?>"><?php echo esc_html(get_the_title((int)$oid)); ?></a>
                <span style="color:#666;"> — <?php echo esc_html(get_permalink((int)$oid)); ?></span>
            </li>
        <?php endforeach; ?>
    </ul>
</div>
<?php endif; ?>


<script>
(function(){
  var nonce = "<?php echo esc_js(wp_create_nonce('aegisseo_quick_fix')); ?>";

  function postAjax(action, data){
    data = data || {};
    data.action = action;
    data.nonce = nonce;
    return window.jQuery.post(ajaxurl, data);
  }

  // Quick generate buttons
  jQuery(document).on('click', '.aegisseo-quick-generate', function(e){
    e.preventDefault();
    var $btn = jQuery(this);
    var postId = parseInt($btn.data('post'), 10) || 0;
    var field = String($btn.data('field') || '');
    if (!postId || !field) return;

    var label = $btn.text();
    $btn.prop('disabled', true).text('Generating…');
    postAjax('aegisseo_quick_generate', {post_id: postId, field: field})
      .done(function(resp){
        if (resp && resp.success) {
          alert('Generated successfully.');
          window.location.reload();
          return;
        }
        alert('Generate failed.');
      })
      .fail(function(){ alert('Generate failed (request).'); })
      .always(function(){ $btn.prop('disabled', false).text(label); });
  });

  // Quick rollback buttons
  jQuery(document).on('click', '.aegisseo-quick-rollback', function(e){
    e.preventDefault();
    var $btn = jQuery(this);
    var postId = parseInt($btn.data('post'), 10) || 0;
    var field = String($btn.data('field') || '');
    if (!postId || !field) return;

    if (!confirm('Rollback the last generated change for this field?')) return;

    var label = $btn.text();
    $btn.prop('disabled', true).text('Rolling back…');
    postAjax('aegisseo_quick_rollback', {post_id: postId, field: field})
      .done(function(resp){
        if (resp && resp.success) {
          alert('Rollback complete.');
          window.location.reload();
          return;
        }
        alert('Rollback failed.');
      })
      .fail(function(){ alert('Rollback failed (request).'); })
      .always(function(){ $btn.prop('disabled', false).text(label); });
  });
})();
</script>
