<?php
/**
 * DBA_LATAM_Admin — Settings + live progress bar.
 * @since 2.11.0
 * @updated 2.17.0 — Kaizen panel, Anti-Orphan panel, Gates F/G/H
 */
if ( ! defined( 'ABSPATH' ) ) exit;

class DBA_LATAM_Admin {
    private static $instance = null;
    public static function get_instance() { if (!self::$instance) self::$instance = new self(); return self::$instance; }

    private function __construct() {
        add_action( 'admin_menu', array( $this, 'menu' ), 30 );
        add_action( 'admin_init', array( $this, 'reg' ) );
        add_action( 'wp_ajax_dba_latam_run_orphan_audit',   array( $this, 'ajax_run_orphan_audit' ) );
        add_action( 'wp_ajax_dba_latam_flush_kaizen_cache', array( $this, 'ajax_flush_kaizen_cache' ) );
    }

    public function menu() { add_submenu_page( 'dba-settings', 'LATAM GeoBot', '🌎 LATAM GeoBot', 'manage_options', 'dba-latam', array( $this, 'page' ) ); }
    public function reg()  { register_setting( 'dba_latam_settings_group', 'dba_latam_settings', array( 'sanitize_callback' => array( $this, 'clean' ) ) ); }

    public function clean( $in ) {
        $c = array();
        $c['enabled']        = !empty($in['enabled']);
        $c['post_status']    = in_array($in['post_status']??'',array('publish','draft','pending')) ? $in['post_status'] : 'publish';
        $c['author_id']      = absint($in['author_id']??1);
        $c['category_id']    = absint($in['category_id']??0);
        $c['word_count_min'] = absint($in['word_count_min']??500);
        $c['word_count_max'] = absint($in['word_count_max']??800);
        $c['posts_per_run']  = max( 1, min( 5, absint($in['posts_per_run']??3) ) );
        $c['cooldown_days']  = max( 0, min( 30, absint($in['cooldown_days']??5) ) );

        // Posting days (checkboxes)
        $valid_days = array( 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday' );
        $c['posting_days'] = array();
        if ( ! empty( $in['posting_days'] ) && is_array( $in['posting_days'] ) ) {
            foreach ( $in['posting_days'] as $d ) {
                $d = strtolower( sanitize_key( $d ) );
                if ( in_array( $d, $valid_days, true ) ) $c['posting_days'][] = $d;
            }
        }
        if ( empty( $c['posting_days'] ) ) $c['posting_days'] = array( 'saturday', 'sunday' );

        // Cron hour (0-23 in CET)
        $c['cron_hour'] = max( 0, min( 23, absint( $in['cron_hour'] ?? 7 ) ) );

        $c['cta_text']       = sanitize_text_field($in['cta_text']??'');
        $c['cta_link_text']  = sanitize_text_field($in['cta_link_text']??'');
        $c['cta_link_url']   = esc_url_raw($in['cta_link_url']??'');
        $c['enabled_countries'] = array();
        if (!empty($in['enabled_countries']) && is_array($in['enabled_countries']))
            foreach ($in['enabled_countries'] as $k) $c['enabled_countries'][] = sanitize_key($k);
        foreach (DBA_LATAM_Registry::get_countries() as $k=>$cfg) {
            $cs = get_option($cfg['settings_option'], array());
            $cs['enabled'] = in_array($k, $c['enabled_countries']);
            update_option($cfg['settings_option'], $cs);
        }

        // Reschedule crons to match new posting_days + cron_hour.
        // WordPress saves the option AFTER clean() returns, so we defer reschedule
        // to shutdown where the fresh settings are already persisted.
        add_action( 'shutdown', array( 'DBA_LATAM_Scheduler', 'reschedule' ) );

        return $c;
    }

    /* ── AJAX: Anti-Orphan Audit (all LATAM countries) ── */
    public function ajax_run_orphan_audit() {
        check_ajax_referer( 'dba_admin_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( 'Unauthorized' );
        if ( ! class_exists( 'DBA_LATAM_Anti_Orphan' ) ) {
            wp_send_json_error( 'Anti-Orphan class not loaded. Upload class-latam-anti-orphan.php and require it in your plugin loader.' );
        }
        $ao = DBA_LATAM_Anti_Orphan::get_instance();
        $fixed = 0; $orphaned = 0; $total = 0; $details = array();
        foreach ( DBA_LATAM_Registry::get_countries() as $k => $cfg ) {
            $r = $ao->audit_country( $k );
            if ( is_array( $r ) ) { $fixed += intval($r['fixed']??0); $orphaned += intval($r['orphaned']??0); $total += intval($r['total']??0); if(!empty($r['fixed'])) $details[] = $cfg['label'].': fixed '.$r['fixed']; }
        }
        wp_send_json_success( array( 'total'=>$total, 'orphaned'=>$orphaned, 'fixed'=>$fixed, 'details'=>$details, 'message'=>"Audited {$total} posts. Fixed {$fixed} orphans." ) );
    }

    /* ── AJAX: Flush Kaizen Cache ── */
    public function ajax_flush_kaizen_cache() {
        check_ajax_referer( 'dba_admin_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( 'Unauthorized' );
        if ( ! class_exists( 'DBA_LATAM_Kaizen' ) ) {
            wp_send_json_error( 'Kaizen class not loaded. Upload class-latam-kaizen.php and require it in your plugin loader.' );
        }
        DBA_LATAM_Kaizen::invalidate_cache();
        wp_send_json_success( array( 'message' => 'Kaizen cache flushed for all LATAM countries.' ) );
    }

    public function page() {
        $s  = get_option('dba_latam_settings', array());
        $co = DBA_LATAM_Registry::get_countries();
        $ro = DBA_LATAM_Registry::get_rotation_state();
        $cool = absint($s['cooldown_days'] ?? 5);
        $ref_ts = DBA_LATAM_Registry::get_next_scheduled_run_ts();
        $nx = DBA_LATAM_Registry::peek_next_eligible_country($cool, $ref_ts);
        $en = !empty($s['enabled_countries']) ? $s['enabled_countries'] : array();
        $th = DBA_LATAM_Scheduler::get_themes();
        $cs = get_option('dba_schedule_settings', array());
        global $wpdb;
        // Count only REAL posts (not orphaned meta)
        $tot = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->postmeta} pm INNER JOIN {$wpdb->posts} p ON pm.post_id = p.ID WHERE pm.meta_key='_dba_latam_auto_created' AND p.post_status IN ('publish','draft','pending','future')");
        $nc  = $nx ? DBA_LATAM_Registry::get_country($nx) : null;
        ?>
        <div class="wrap" style="max-width:1100px">
        <h1 style="display:flex;align-items:center;gap:10px">
            <span style="font-size:32px">🌎</span> LATAM GeoBot
            <span style="background:#1a365d;color:#fff;padding:3px 12px;border-radius:4px;font-size:13px">v2.11.0</span>
        </h1>
        <?php
        $display_days = !empty($s['posting_days']) ? array_map('ucfirst', $s['posting_days']) : array('Saturday','Sunday');
        $display_hour = isset($s['cron_hour']) ? intval($s['cron_hour']) : 7;
        ?>
        <p style="font-size:15px;color:#555">Automated investment posts for 15 LATAM countries. <b><?php echo absint($s['posts_per_run']??3); ?> post(s)/run</b> — <?php echo esc_html(implode(', ', $display_days)); ?> at <?php echo esc_html(sprintf('%02d:00', $display_hour)); ?> CET.</p>

        <?php
        $core_days = $cs['posting_days'] ?? array();
        $latam_days_check = !empty($s['posting_days']) ? $s['posting_days'] : array('saturday','sunday');
        $overlap_days = array_intersect($core_days, $latam_days_check);
        if(!empty($overlap_days)):
        ?>
        <div style="background:#fff5f5;border:2px solid #c53030;border-radius:8px;padding:16px 20px;margin:20px 0">
            <h3 style="color:#c53030;margin:0 0 6px">⚠️ Schedule Conflict</h3>
            <p style="margin:0;color:#742a2a">Core Bot also runs on <b><?php echo esc_html(implode(', ', array_map('ucfirst', $overlap_days))); ?></b>. The Conflict Center will queue them, but consider separating. <a href="<?php echo admin_url('admin.php?page=dba-settings'); ?>">Core schedule →</a></p>
        </div>
        <?php endif; ?>

        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:16px;margin:20px 0">
            <div style="background:#fff;border:1px solid #e0e0e0;border-radius:8px;padding:16px;text-align:center"><div id="dba-tot" style="font-size:28px;font-weight:bold;color:#1a365d"><?php echo intval($tot); ?></div><div style="font-size:12px;color:#666">Total Posts</div></div>
            <div style="background:#fff;border:1px solid #e0e0e0;border-radius:8px;padding:16px;text-align:center"><div style="font-size:28px;font-weight:bold;color:#4a7c59"><?php echo count($en); ?>/<?php echo count($co); ?></div><div style="font-size:12px;color:#666">Countries On</div></div>
            <div style="background:#fff;border:1px solid #e0e0e0;border-radius:8px;padding:16px;text-align:center"><div style="font-size:28px;font-weight:bold;color:#2d5f8a"><?php echo $nc?esc_html($nc['label']):'—'; ?></div><div style="font-size:12px;color:#666">Next</div></div>
            <div style="background:#fff;border:1px solid #e0e0e0;border-radius:8px;padding:16px;text-align:center"><div style="font-size:16px;font-weight:bold;color:#666"><?php echo !empty($ro['last_run'])?esc_html($ro['last_run']):'Never'; ?></div><div style="font-size:12px;color:#666">Last Run</div></div>
        </div>

        <!-- BUTTONS -->
        <div style="margin:20px 0">
            <div style="display:flex;gap:10px;flex-wrap:wrap;margin-bottom:8px">
                <button type="button" class="button button-primary" id="dba-go" style="background:#1a365d;border-color:#1a365d;font-size:14px;padding:6px 20px">🚀 Generate Now (Next Country)</button>
                <button type="button" class="button" id="dba-scan-links" style="background:#0e7c42;border-color:#0e7c42;color:#fff;font-size:14px;padding:6px 20px">🔍 Scan & Fix Links</button>
                <button type="button" class="button" id="dba-rst">🔄 Reset Rotation</button>
                <button type="button" class="button" id="dba-clean" style="color:#c53030;border-color:#c53030">🧹 Fix Counter (Clean Orphans)</button>
            </div>
            <p style="font-size:12px;color:#888;margin:0 0 10px">Auto-enables Brazil + creates "LATAM Investment" category if nothing configured.</p>

            <div id="pb" style="display:none;background:#fff;border:2px solid #d0d5dd;border-radius:10px;padding:24px;max-width:750px;box-shadow:0 2px 8px rgba(0,0,0,.08)">
                <div style="background:#e2e8f0;border-radius:8px;height:32px;overflow:hidden;margin-bottom:14px">
                    <div id="pb-bar" style="height:100%;width:0%;background:linear-gradient(90deg,#1a365d,#2d5f8a);border-radius:8px;transition:width .5s;display:flex;align-items:center;justify-content:center;color:#fff;font-size:13px;font-weight:bold;min-width:40px">0%</div>
                </div>
                <div id="pb-lbl" style="font-size:17px;font-weight:bold;color:#1a365d;margin-bottom:4px">🚀 Starting...</div>
                <div id="pb-det" style="font-size:13px;color:#666;white-space:pre-wrap;margin-bottom:14px"></div>
                <div style="border-top:1px solid #e2e8f0;padding-top:12px">
                    <div style="font-size:11px;font-weight:bold;color:#999;text-transform:uppercase;margin-bottom:6px">Generation Log</div>
                    <div id="pb-log" style="font-family:monospace;font-size:12px;color:#444;max-height:240px;overflow-y:auto;line-height:1.8"></div>
                </div>
            </div>
        </div>

        <!-- SETTINGS -->
        <form method="post" action="options.php">
        <?php settings_fields('dba_latam_settings_group'); ?>
        <h2 style="border-bottom:2px solid #1a365d;padding-bottom:8px;margin-top:30px">General Settings</h2>
        <table class="form-table">
            <tr><th>Enable Module</th><td><label><input type="checkbox" name="dba_latam_settings[enabled]" value="1" <?php checked(!empty($s['enabled'])); ?>> Auto-post on selected days</label></td></tr>
            <tr><th>Posting Days</th><td>
                <?php
                $saved_days = !empty($s['posting_days']) ? (array) $s['posting_days'] : array('saturday','sunday');
                $all_days = array('monday'=>'Mon','tuesday'=>'Tue','wednesday'=>'Wed','thursday'=>'Thu','friday'=>'Fri','saturday'=>'Sat','sunday'=>'Sun');
                foreach ($all_days as $dk=>$dl):
                    $chk = in_array($dk, $saved_days) ? 'checked' : '';
                ?>
                <label style="margin-right:14px;<?php echo in_array($dk,array('saturday','sunday')) ? 'font-weight:bold;' : ''; ?>">
                    <input type="checkbox" name="dba_latam_settings[posting_days][]" value="<?php echo esc_attr($dk); ?>" <?php echo $chk; ?>>
                    <?php echo $dl; ?>
                </label>
                <?php endforeach; ?>
                <p class="description">Select which days LATAM GeoBot should run. Default: Sat & Sun.</p>
            </td></tr>
            <tr><th>Cron Hour (CET)</th><td>
                <select name="dba_latam_settings[cron_hour]" style="width:120px">
                    <?php $saved_hour = isset($s['cron_hour']) ? intval($s['cron_hour']) : 7;
                    for ($h=0; $h<=23; $h++): ?>
                    <option value="<?php echo $h; ?>" <?php selected($h, $saved_hour); ?>><?php echo sprintf('%02d:00', $h); ?></option>
                    <?php endfor; ?>
                </select>
                <p class="description">Hour in Europe/Luxembourg (CET/CEST). Default: 07:00.</p>
            </td></tr>
            <tr><th>Post Status</th><td><select name="dba_latam_settings[post_status]"><option value="publish" <?php selected($s['post_status']??'','publish'); ?>>Publish</option><option value="draft" <?php selected($s['post_status']??'','draft'); ?>>Draft</option><option value="pending" <?php selected($s['post_status']??'','pending'); ?>>Pending</option></select></td></tr>
            <tr><th>Author ID</th><td><input type="number" name="dba_latam_settings[author_id]" min="1" value="<?php echo esc_attr($s['author_id']??1); ?>" style="width:80px"></td></tr>
            <tr><th>Category</th><td><?php wp_dropdown_categories(array('name'=>'dba_latam_settings[category_id]','selected'=>$s['category_id']??0,'show_option_none'=>'— Auto "LATAM Investment" —','option_none_value'=>0,'hide_empty'=>false,'hierarchical'=>true)); ?></td></tr>
            <tr><th>Word Count</th><td><input type="number" name="dba_latam_settings[word_count_min]" min="300" value="<?php echo esc_attr($s['word_count_min']??500); ?>" style="width:80px"> – <input type="number" name="dba_latam_settings[word_count_max]" min="300" value="<?php echo esc_attr($s['word_count_max']??800); ?>" style="width:80px"> words</td></tr>
            <tr><th>Posts per Run</th><td><input type="number" name="dba_latam_settings[posts_per_run]" min="1" max="5" value="<?php echo esc_attr($s['posts_per_run']??3); ?>" style="width:80px"><p class="description">Unique-country posts per cron run. Max = number of enabled countries.</p></td></tr>
            <tr><th>Cooldown (days)</th><td><input type="number" name="dba_latam_settings[cooldown_days]" min="0" max="30" value="<?php echo esc_attr($s['cooldown_days']??5); ?>" style="width:80px"><p class="description">Avoid repeating same country within this many days. 0 = no cooldown.</p></td></tr>
            <tr><th>CTA Text</th><td><textarea name="dba_latam_settings[cta_text]" rows="2" style="width:100%;max-width:600px"><?php echo esc_textarea($s['cta_text']??'Damalion supports international investors, entrepreneurs, and family offices establishing and structuring their business in {Country}.'); ?></textarea><p class="description"><code>{Country}</code> = country</p></td></tr>
            <tr><th>CTA Link Text</th><td><input type="text" name="dba_latam_settings[cta_link_text]" style="width:400px" value="<?php echo esc_attr($s['cta_link_text']??'Contact your Damalion experts now.'); ?>"></td></tr>
            <tr><th>CTA Link URL</th><td><input type="url" name="dba_latam_settings[cta_link_url]" style="width:400px" value="<?php echo esc_attr($s['cta_link_url']??'https://www.damalion.com/lets-connect/'); ?>"></td></tr>
        </table>

        <h2 style="border-bottom:2px solid #4a7c59;padding-bottom:8px;margin-top:30px">Country Rotation</h2>
        <table class="widefat striped" style="max-width:700px;margin:15px 0">
            <thead><tr><th style="width:40px">#</th><th style="width:50px">On</th><th>Country</th><th>Cities</th></tr></thead>
            <tbody>
            <?php $i=1; foreach(DBA_LATAM_Registry::ROTATION_ORDER as $k):
                $cf=$co[$k]??null; if(!$cf) continue;
                $cn=wp_list_pluck(DBA_LATAM_Cities::get_country_cities($k),'name');
            ?>
            <tr style="<?php echo ($k===$nx)?'background:#e8f4fd;':''; ?>">
                <td style="font-weight:bold;color:#1a365d"><?php echo $i; ?></td>
                <td><input type="checkbox" name="dba_latam_settings[enabled_countries][]" value="<?php echo esc_attr($k); ?>" <?php checked(in_array($k,$en)); ?>></td>
                <td><b><?php echo esc_html($cf['label']); ?></b><?php if($k===$nx): ?> <span style="background:#2d5f8a;color:#fff;padding:1px 8px;border-radius:3px;font-size:10px">NEXT</span><?php endif; ?></td>
                <td style="font-size:12px;color:#666"><?php echo esc_html(implode(', ',$cn)); ?></td>
            </tr>
            <?php $i++; endforeach; ?>
            </tbody>
        </table>

        <h2 style="border-bottom:2px solid #2d5f8a;padding-bottom:8px;margin-top:30px">Themes (9 rotating)</h2>
        <table class="widefat striped" style="max-width:700px;margin:15px 0">
            <thead><tr><th style="width:40px">#</th><th>Theme</th></tr></thead>
            <tbody><?php foreach($th as $x=>$t): ?><tr><td><?php echo $x+1; ?></td><td><?php echo esc_html($t['label']); ?></td></tr><?php endforeach; ?></tbody>
        </table>

        <h2 style="border-bottom:2px solid #059669;padding-bottom:8px;margin-top:30px">🌐 Content Sources</h2>
        <div style="background:#ecfdf5;border:1px solid #6ee7b7;border-radius:8px;padding:16px 20px;margin:15px 0;max-width:700px">
            <p style="margin:0 0 8px;color:#065f46;font-weight:bold">2-phase generation:</p>
            <p style="margin:4px 0;font-size:14px;color:#555"><b>1. Research:</b> Google News RSS — fresh headlines about country+city+topic (2025/2026)</p>
            <p style="margin:4px 0;font-size:14px;color:#555"><b>2. Writing:</b> GPT writes grounded in news context — references events, figures, dates</p>
            <p style="margin:4px 0;font-size:14px;color:#555"><b>Fallback:</b> If no news found, GPT uses general knowledge</p>
            <p style="margin:8px 0 0;font-size:12px;color:#047857">Uses your existing OpenAI key from Core Settings. No extra API keys.</p>
        </div>

        <h2 style="border-bottom:2px solid #a855f7;padding-bottom:8px;margin-top:30px">🔍 Yoast SEO (Auto)</h2>
        <div style="background:#faf5ff;border:1px solid #d8b4fe;border-radius:8px;padding:16px 20px;margin:15px 0;max-width:700px">
            <p style="margin:2px 0;font-size:14px"><b>Meta Description</b> → <code>_yoast_wpseo_metadesc</code> (135 chars max)</p>
            <p style="margin:2px 0;font-size:14px"><b>Focus Keyphrase</b> → <code>_yoast_wpseo_focuskw</code> (2-4 words)</p>
            <p style="margin:2px 0;font-size:14px"><b>Featured Image</b> → DALL-E 3 city photo</p>
        </div>

        <h2 style="border-bottom:2px solid #f59e0b;padding-bottom:8px;margin-top:30px">🔗 Internal Links</h2>
        <div style="background:#fffbeb;border:1px solid #fcd34d;border-radius:8px;padding:16px 20px;margin:15px 0;max-width:700px">
            <p style="margin:0;color:#92400e">Shared registry. Scan from <a href="<?php echo admin_url('admin.php?page=dba-settings'); ?>">Core Settings</a>.</p>
        </div>

        <!-- ══ PLAGIARISM DETECTION & GOOGLE PENALTY COMPLIANCE ══ -->
        <?php
        $plag_class_loaded = class_exists( 'DBA_Plagiarism' );
        $core_settings_plag = get_option( 'dba_settings', array() );
        $cs_user = ! empty( $core_settings_plag['copyscape_user'] ) ? $core_settings_plag['copyscape_user'] : '';
        $cs_key  = ! empty( $core_settings_plag['copyscape_key'] )  ? $core_settings_plag['copyscape_key']  : '';
        $copyscape_active  = $plag_class_loaded && ! empty( $cs_user ) && ! empty( $cs_key );
        $web_fallback      = $plag_class_loaded && ! $copyscape_active;
        $google_key        = ! empty( $core_settings_plag['google_search_key'] ) && ! empty( $core_settings_plag['google_search_cx'] );
        ?>
        <div style="background:#f8fafc;border:1px solid #c6dbef;border-left:4px solid #1a365d;border-radius:6px;padding:18px 22px;margin-top:28px;max-width:1000px;">
            <h2 style="margin-top:0;color:#1e3a5f;">🛡 Plagiarism Detection & Google Penalty Compliance — <?php echo $plag_class_loaded ? '<span style="color:#166534;">ACTIVE</span>' : '<span style="color:#991b1b;">INACTIVE</span>'; ?></h2>
            <table class="widefat" style="border:none;background:transparent;">
                <!-- Gate A -->
                <tr>
                    <td style="width:28px;vertical-align:top;padding:8px 4px;">
                        <?php if ( $plag_class_loaded ) : ?>
                            <span style="display:inline-block;width:20px;height:20px;background:#dcfce7;color:#166534;text-align:center;line-height:20px;border-radius:3px;font-size:12px;font-weight:700;">✓</span>
                        <?php else : ?>
                            <span style="display:inline-block;width:20px;height:20px;background:#fee2e2;color:#991b1b;text-align:center;line-height:20px;border-radius:3px;font-size:12px;font-weight:700;">✕</span>
                        <?php endif; ?>
                    </td>
                    <td style="padding:8px 6px;"><strong>Gate A — Internal Duplicate Detection</strong></td>
                    <td style="padding:8px 6px;color:#555;">
                        Jaccard 3-gram shingling against ALL existing Damalion posts. Threshold: <?php echo $plag_class_loaded ? DBA_Plagiarism::INTERNAL_SIMILARITY_THRESHOLD * 100 : 35; ?>% overlap = REJECT.
                        <strong style="color:<?php echo $plag_class_loaded ? '#166534' : '#991b1b'; ?>;"><?php echo $plag_class_loaded ? 'ENABLED' : 'DISABLED — class not loaded'; ?></strong>
                    </td>
                </tr>
                <!-- Gate B -->
                <tr>
                    <td style="width:28px;vertical-align:top;padding:8px 4px;">
                        <span style="display:inline-block;width:20px;height:20px;background:#dcfce7;color:#166534;text-align:center;line-height:20px;border-radius:3px;font-size:12px;font-weight:700;">✓</span>
                    </td>
                    <td style="padding:8px 6px;"><strong>Gate B — Sentence-Level Uniqueness</strong></td>
                    <td style="padding:8px 6px;color:#555;">
                        Compares every sentence (&gt;30 chars) against last 30 LATAM posts. 90% similarity = flagged. Max 15% duplicate sentences allowed.
                        <strong style="color:#166534;">ENABLED</strong>
                    </td>
                </tr>
                <!-- Gate C -->
                <tr>
                    <td style="width:28px;vertical-align:top;padding:8px 4px;">
                        <?php if ( $copyscape_active ) : ?>
                            <span style="display:inline-block;width:20px;height:20px;background:#dcfce7;color:#166534;text-align:center;line-height:20px;border-radius:3px;font-size:12px;font-weight:700;">✓</span>
                        <?php else : ?>
                            <span style="display:inline-block;width:20px;height:20px;background:#fef3c7;color:#92400e;text-align:center;line-height:20px;border-radius:3px;font-size:12px;font-weight:700;">⚠</span>
                        <?php endif; ?>
                    </td>
                    <td style="padding:8px 6px;"><strong>Gate C — Copyscape API</strong></td>
                    <td style="padding:8px 6px;color:#555;">
                        <?php if ( $copyscape_active ) : ?>
                            Copyscape Premium API active. Web-wide plagiarism detection on every article.
                            <strong style="color:#166534;">ENABLED</strong>
                        <?php else : ?>
                            <span style="color:#c2410c;">Not configured.</span> Add Copyscape credentials in <a href="<?php echo admin_url( 'admin.php?page=dba-settings' ); ?>">Settings</a> for web-wide plagiarism detection. Fallback: web sentence sampling.
                        <?php endif; ?>
                    </td>
                </tr>
                <!-- Gate D -->
                <tr>
                    <td style="width:28px;vertical-align:top;padding:8px 4px;">
                        <?php if ( $web_fallback ) : ?>
                            <span style="display:inline-block;width:20px;height:20px;background:#dcfce7;color:#166534;text-align:center;line-height:20px;border-radius:3px;font-size:12px;font-weight:700;">✓</span>
                        <?php else : ?>
                            <span style="display:inline-block;width:20px;height:20px;background:#f3f4f6;color:#6b7280;text-align:center;line-height:20px;border-radius:3px;font-size:12px;font-weight:700;">—</span>
                        <?php endif; ?>
                    </td>
                    <td style="padding:8px 6px;"><strong>Gate D — Web Sentence Sampling</strong></td>
                    <td style="padding:8px 6px;color:#555;">
                        <?php echo $plag_class_loaded ? DBA_Plagiarism::SAMPLE_SENTENCES : 5; ?> random sentences searched via Google to detect web-wide matches. Active when Copyscape is not configured.
                        <?php if ( $web_fallback ) : ?>
                            <strong style="color:#166534;">ENABLED (fallback)</strong>
                            <?php if ( ! $google_key ) : ?>
                                <br><span style="font-size:11px;color:#92400e;">⚠️ Google Custom Search API not configured — web sampling limited.</span>
                            <?php endif; ?>
                        <?php elseif ( $copyscape_active ) : ?>
                            <strong style="color:#6b7280;">STANDBY</strong> <span style="font-size:11px;">(Copyscape active)</span>
                        <?php else : ?>
                            <strong style="color:#991b1b;">DISABLED</strong>
                        <?php endif; ?>
                    </td>
                </tr>
                <!-- Gate E -->
                <tr>
                    <td style="width:28px;vertical-align:top;padding:8px 4px;">
                        <span style="display:inline-block;width:20px;height:20px;background:#dcfce7;color:#166534;text-align:center;line-height:20px;border-radius:3px;font-size:12px;font-weight:700;">✓</span>
                    </td>
                    <td style="padding:8px 6px;"><strong>Gate E — AI Prompt Anti-Template</strong></td>
                    <td style="padding:8px 6px;color:#555;">
                        System prompt instructs AI to vary sentence structure, vocabulary, and narrative angle per city. Retry on validation failure.
                        <strong style="color:#166534;">ENABLED</strong>
                    </td>
                </tr>
                <!-- Gate F — Structural Clone -->
                <?php $gf_ok = class_exists( 'DBA_LATAM_Kaizen' ); $gf_ico = $gf_ok ? array('#dcfce7','#166534','✓') : array('#fee2e2','#991b1b','✕'); ?>
                <tr>
                    <td style="width:28px;vertical-align:top;padding:8px 4px;"><span style="display:inline-block;width:20px;height:20px;background:<?php echo $gf_ico[0]; ?>;color:<?php echo $gf_ico[1]; ?>;text-align:center;line-height:20px;border-radius:3px;font-size:12px;font-weight:700;"><?php echo $gf_ico[2]; ?></span></td>
                    <td style="padding:8px 6px;"><strong>Gate F — Structural Clone Detection</strong></td>
                    <td style="padding:8px 6px;color:#555;">Compares paragraph structure hash (H2 count, paragraphs/section, avg length) against last 10 posts. 4+ identical = REJECT. <strong style="color:<?php echo $gf_ok?'#166534':'#991b1b'; ?>;"><?php echo $gf_ok?'ENABLED':'DISABLED — update validator'; ?></strong></td>
                </tr>
                <!-- Gate G — Opener/Transition -->
                <tr>
                    <td style="width:28px;vertical-align:top;padding:8px 4px;"><span style="display:inline-block;width:20px;height:20px;background:<?php echo $gf_ico[0]; ?>;color:<?php echo $gf_ico[1]; ?>;text-align:center;line-height:20px;border-radius:3px;font-size:12px;font-weight:700;"><?php echo $gf_ico[2]; ?></span></td>
                    <td style="padding:8px 6px;"><strong>Gate G — Opener &amp; Transition Repetition</strong></td>
                    <td style="padding:8px 6px;color:#555;">Section openers (first 3 words) compared across last 10 posts. Same transition 3+ times in one article = REJECT. <strong style="color:<?php echo $gf_ok?'#166534':'#991b1b'; ?>;"><?php echo $gf_ok?'ENABLED':'DISABLED'; ?></strong></td>
                </tr>
                <!-- Gate H — Title Dedup -->
                <tr>
                    <td style="width:28px;vertical-align:top;padding:8px 4px;"><span style="display:inline-block;width:20px;height:20px;background:<?php echo $gf_ico[0]; ?>;color:<?php echo $gf_ico[1]; ?>;text-align:center;line-height:20px;border-radius:3px;font-size:12px;font-weight:700;"><?php echo $gf_ico[2]; ?></span></td>
                    <td style="padding:8px 6px;"><strong>Gate H — Title Deduplication</strong></td>
                    <td style="padding:8px 6px;color:#555;">Title skeleton (minus city name) compared at 85% similarity against last 90 days. Match = REJECT. <strong style="color:<?php echo $gf_ok?'#166534':'#991b1b'; ?>;"><?php echo $gf_ok?'ENABLED':'DISABLED'; ?></strong></td>
                </tr>
            </table>
            <p style="margin-bottom:0;font-size:12px;color:#555;border-top:1px solid #e2e8f0;padding-top:10px;margin-top:6px;">
                <strong>Pipeline:</strong> Every article passes through Gates A → B → (C or D) → E → F → G → H before publishing. Any gate failure = article REJECTED and regenerated (up to 2 retries). Failed articles are logged with full error trace.
            </p>
        </div>

        <!-- ══════════════════════════════════════════════════════════════ -->
        <!--  🧠 KAIZEN LEARNING ENGINE                                    -->
        <!-- ══════════════════════════════════════════════════════════════ -->
        <?php
        $kz_loaded = class_exists( 'DBA_LATAM_Kaizen' );
        $kz_tracked = 0; $kz_edited = 0; $kz_corrections = array(); $kz_overused = array();

        if ( $kz_loaded ) {
            global $wpdb;
            $kz_ids = $wpdb->get_col(
                "SELECT pm.post_id FROM {$wpdb->postmeta} pm
                 INNER JOIN {$wpdb->posts} p ON pm.post_id = p.ID
                 WHERE pm.meta_key = '_dba_latam_auto_created'
                 AND p.post_status IN ('publish','draft')
                 AND p.post_date > DATE_SUB(NOW(), INTERVAL 7 DAY)
                 ORDER BY p.post_date DESC LIMIT 20"
            );
            foreach ( $kz_ids as $kz_pid ) {
                $orig = get_post_meta( $kz_pid, '_dba_latam_original_content', true );
                if ( empty( $orig ) ) continue;
                $kz_tracked++;
                $curr = get_post_field( 'post_content', $kz_pid );
                $o_wc = str_word_count( strip_tags( $orig ) );
                $c_wc = str_word_count( strip_tags( $curr ) );
                if ( $o_wc > 0 && abs( $c_wc - $o_wc ) / $o_wc * 100 > 5 ) {
                    $kz_edited++;
                    $dir = $c_wc > $o_wc ? 'expanded' : 'trimmed';
                    $kz_corrections[] = array( 'id' => $kz_pid, 'title' => get_the_title( $kz_pid ), 'info' => "Content {$dir}: {$o_wc} → {$c_wc} words" );
                }
                $ot = get_post_meta( $kz_pid, '_dba_latam_original_title', true );
                $ct = get_the_title( $kz_pid );
                if ( ! empty( $ot ) && $ot !== $ct ) {
                    $kz_corrections[] = array( 'id' => $kz_pid, 'title' => $ct, 'info' => 'Title rewritten' );
                }
            }
            // Overused transitions — check a few LATAM country keys
            foreach ( array( 'brazil', 'mexico', 'argentina', 'colombia' ) as $kz_ck ) {
                $ov = DBA_LATAM_Kaizen::get_overused_transitions( $kz_ck );
                if ( is_array( $ov ) ) $kz_overused = array_merge( $kz_overused, $ov );
            }
            $kz_overused = array_unique( $kz_overused );
        }
        ?>
        <div style="background:<?php echo $kz_loaded ? '#f5f3ff' : '#fef2f2'; ?>;border:1px solid <?php echo $kz_loaded ? '#c4b5fd' : '#fca5a5'; ?>;border-left:4px solid <?php echo $kz_loaded ? '#7c3aed' : '#dc2626'; ?>;border-radius:6px;padding:18px 22px;margin-top:28px;max-width:1000px;">
            <h2 style="margin-top:0;color:<?php echo $kz_loaded ? '#5b21b6' : '#991b1b'; ?>;">🧠 Kaizen Learning Engine — <?php echo $kz_loaded
                ? '<span style="color:#166534;">ACTIVE</span>'
                : '<span style="color:#991b1b;">NOT LOADED</span> <span style="font-size:12px;font-weight:normal;color:#991b1b;">— Upload class-latam-kaizen.php &amp; require it</span>'; ?></h2>

            <?php if ( $kz_loaded ) : ?>
            <table class="widefat" style="border:none;background:transparent;">
                <tr>
                    <td style="padding:8px 6px;width:250px;"><strong>📊 Tracked Posts (7 days)</strong></td>
                    <td style="padding:8px 6px;"><?php echo $kz_tracked; ?> posts with originals stored for diff tracking</td>
                </tr>
                <tr>
                    <td style="padding:8px 6px;"><strong>✏️ Editor Corrections</strong></td>
                    <td style="padding:8px 6px;">
                        <?php if ( ! empty( $kz_corrections ) ) : ?>
                            <span style="color:#c2410c;font-weight:bold;"><?php echo count( $kz_corrections ); ?> corrections detected</span> — AI learns from these on next generation
                        <?php else : ?>
                            <span style="color:#166534;">No corrections — AI output matches published content ✓</span>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php if ( ! empty( $kz_overused ) ) : ?>
                <tr>
                    <td style="padding:8px 6px;"><strong>⚠️ Blacklisted Transitions</strong></td>
                    <td style="padding:8px 6px;color:#c2410c;"><?php echo count( $kz_overused ); ?> transitions blocked for next generation</td>
                </tr>
                <?php endif; ?>
            </table>

            <?php if ( ! empty( $kz_corrections ) ) : ?>
            <div style="background:#fff;border:1px solid #ddd6fe;border-radius:4px;padding:10px 15px;margin:10px 0;max-height:180px;overflow-y:auto;font-size:12px;">
                <strong>Corrections (injected into AI prompt):</strong><br>
                <?php foreach ( array_slice( $kz_corrections, 0, 10 ) as $kc ) : ?>
                    <div style="padding:3px 0;border-bottom:1px solid #f5f3ff;">
                        📝 <a href="<?php echo admin_url( 'post.php?post=' . $kc['id'] . '&action=edit' ); ?>" target="_blank"><?php echo esc_html( $kc['title'] ); ?></a>
                        — <?php echo esc_html( $kc['info'] ); ?>
                    </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>

            <?php if ( ! empty( $kz_overused ) ) : ?>
            <div style="background:#fffbeb;border:1px solid #fcd34d;border-radius:4px;padding:10px 15px;margin:10px 0;font-size:12px;">
                <strong>AI told to avoid:</strong>
                <?php foreach ( array_slice( $kz_overused, 0, 8 ) as $ow ) : ?>
                    <span style="display:inline-block;background:#fff;border:1px solid #e5e7eb;border-radius:3px;padding:2px 8px;margin:2px 3px;font-size:11px;">✗ <?php echo esc_html( $ow ); ?></span>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>

            <div style="margin-top:10px;display:flex;gap:10px;align-items:center;">
                <button type="button" class="button" id="dba-flush-kaizen">🔄 Flush Kaizen Cache</button>
                <span id="dba-kaizen-msg" style="font-size:13px;"></span>
            </div>
            <?php endif; ?>
        </div>

        <!-- ══════════════════════════════════════════════════════════════ -->
        <!--  🛡️ ANTI-ORPHAN PROTECTION                                   -->
        <!-- ══════════════════════════════════════════════════════════════ -->
        <?php
        $ao_loaded = class_exists( 'DBA_LATAM_Anti_Orphan' );
        $ao_orphans = array(); $ao_total = 0; $ao_linked = 0; $ao_gov_linked = 0;

        if ( $ao_loaded ) {
            $ao_stats = DBA_LATAM_Anti_Orphan::get_orphan_stats();
            $ao_total        = $ao_stats['total'];
            $ao_linked       = $ao_stats['linked'];
            $ao_gov_linked   = $ao_stats['gov_linked'];
            $ao_orphan_count = $ao_stats['orphan_count'];
            $ao_orphans      = $ao_stats['orphans'];
        } else {
            global $wpdb;
            $ao_all_ids = $wpdb->get_col(
                "SELECT pm.post_id FROM {$wpdb->postmeta} pm
                 INNER JOIN {$wpdb->posts} p ON pm.post_id = p.ID
                 WHERE pm.meta_key = '_dba_latam_auto_created' AND p.post_status = 'publish'
                 ORDER BY p.post_date DESC"
            );
            $ao_total = count( $ao_all_ids );
            foreach ( $ao_all_ids as $ao_pid ) {
                $pc = get_post_field( 'post_content', $ao_pid );
                if ( strpos( $pc, 'dba-latam-related' ) !== false ) $ao_linked++;
                if ( strpos( $pc, 'dba-latam-gov-link' ) !== false ) $ao_gov_linked++;
                if ( strpos( $pc, 'dba-latam-related' ) === false && count($ao_orphans) < 10 ) {
                    $ao_orphans[] = array( 'id' => $ao_pid, 'title' => get_the_title( $ao_pid ) );
                }
            }
            $ao_orphan_count = $ao_total - $ao_linked;
        }

        $ao_cron = wp_next_scheduled( 'dba_latam_weekly_orphan_audit' );
        ?>
        <div style="background:<?php echo $ao_orphan_count > 0 ? '#fffbeb' : '#f0fdf4'; ?>;border:1px solid <?php echo $ao_orphan_count > 0 ? '#fcd34d' : '#86efac'; ?>;border-left:4px solid <?php echo $ao_orphan_count > 0 ? '#f59e0b' : '#22c55e'; ?>;border-radius:6px;padding:18px 22px;margin-top:20px;max-width:1000px;">
            <h2 style="margin-top:0;color:<?php echo $ao_orphan_count > 0 ? '#92400e' : '#166534'; ?>;">🛡️ Anti-Orphan Protection — <?php
                if ( ! $ao_loaded ) {
                    echo '<span style="color:#991b1b;">NOT LOADED</span> <span style="font-size:12px;font-weight:normal;">— Upload class-latam-anti-orphan.php</span>';
                } elseif ( $ao_orphan_count > 0 ) {
                    echo '<span style="color:#c2410c;">' . $ao_orphan_count . ' ORPHAN' . ( $ao_orphan_count > 1 ? 'S' : '' ) . '</span>';
                } else {
                    echo '<span style="color:#166534;">ALL ' . $ao_total . ' POSTS LINKED ✓</span>';
                }
            ?></h2>

            <table class="widefat" style="border:none;background:transparent;">
                <tr>
                    <td style="padding:8px 6px;width:250px;"><strong><?php echo $ao_orphan_count === 0 ? '✅' : '⚠️'; ?> Cross-City Links</strong></td>
                    <td style="padding:8px 6px;"><?php echo $ao_linked; ?>/<?php echo $ao_total; ?> posts have internal cross-links
                        <?php if ( $ao_orphan_count > 0 ) : ?>
                            — <span style="color:#c2410c;font-weight:bold;"><?php echo $ao_orphan_count; ?> posts have NO cross-links</span>
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <td style="padding:8px 6px;"><strong><?php echo $ao_loaded ? '✅' : '❌'; ?> Auto-Link on Publish</strong></td>
                    <td style="padding:8px 6px;"><?php echo $ao_loaded ? 'New posts auto-linked to related cities + gov authority URLs on creation' : 'NOT ACTIVE — class not loaded'; ?></td>
                </tr>
                <tr>
                    <td style="padding:8px 6px;"><strong><?php echo $ao_gov_linked > 0 ? '✅' : '⚠️'; ?> 🏛️ Government Authority Links</strong></td>
                    <td style="padding:8px 6px;"><?php echo $ao_gov_linked; ?>/<?php echo $ao_total; ?> posts have .gov outbound authority links
                        <?php if ( $ao_total > 0 && $ao_gov_linked < $ao_total ) : ?>
                            — <span style="color:#c2410c;"><?php echo $ao_total - $ao_gov_linked; ?> missing gov links</span> (audit will fix)
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <td style="padding:8px 6px;"><strong><?php echo $ao_cron ? '✅' : '⚠️'; ?> Weekly Audit Cron</strong></td>
                    <td style="padding:8px 6px;"><?php echo $ao_cron ? 'Next: ' . esc_html( date( 'Y-m-d H:i', $ao_cron ) ) : 'Not scheduled — will activate after first generation with Anti-Orphan loaded'; ?></td>
                </tr>
            </table>

            <?php if ( ! empty( $ao_orphans ) ) : ?>
            <div style="background:#fff;border:1px solid <?php echo $ao_orphan_count > 0 ? '#fcd34d' : '#ddd'; ?>;border-radius:4px;padding:10px 15px;margin:10px 0;max-height:180px;overflow-y:auto;font-size:12px;">
                <strong>Orphaned posts (no cross-links):</strong><br>
                <?php foreach ( $ao_orphans as $ao_item ) : ?>
                    <div style="padding:3px 0;border-bottom:1px solid #fef3c7;">
                        ❌ <a href="<?php echo admin_url( 'post.php?post=' . $ao_item['id'] . '&action=edit' ); ?>" target="_blank">#<?php echo $ao_item['id']; ?> — <?php echo esc_html( $ao_item['title'] ); ?></a>
                    </div>
                <?php endforeach; ?>
                <?php if ( $ao_orphan_count > 8 ) : ?>
                    <div style="padding:3px 0;color:#999;">… and <?php echo $ao_orphan_count - 8; ?> more</div>
                <?php endif; ?>
            </div>
            <?php endif; ?>

            <?php if ( $ao_loaded ) : ?>
            <div style="margin-top:10px;display:flex;gap:10px;align-items:center;">
                <button type="button" class="button button-primary" id="dba-run-audit" <?php echo $ao_orphan_count === 0 ? 'disabled' : ''; ?> style="background:#1a365d;border-color:#1a365d;">🔧 Fix All Orphans (<?php echo $ao_orphan_count; ?>)</button>
                <span id="dba-audit-msg" style="font-size:13px;"></span>
            </div>
            <?php endif; ?>
        </div>

        <?php submit_button('Save LATAM Settings'); ?>
        </form>
        </div>

        <script>
        jQuery(function($){
            var A='<?php echo admin_url("admin-ajax.php"); ?>',
                N='<?php echo wp_create_nonce("dba_admin_nonce"); ?>',
                T=null, S=-1;

            // GENERATE NOW
            $('#dba-go').on('click',function(){
                var B=$(this).prop('disabled',1).html('⏳ Running...');
                $('#pb').slideDown(200);
                $('#pb-bar').css({width:'0%',background:'linear-gradient(90deg,#1a365d,#2d5f8a)'}).text('0%');
                $('#pb-lbl').text('🚀 Starting...'); $('#pb-det').text(''); $('#pb-log').html('');
                S=-1;
                T=setInterval(poll,1500);
                $.ajax({
                    url:A, method:'POST', timeout:180000,
                    data:{action:'dba_latam_generate_now',nonce:N},
                    success:function(r){
                        setTimeout(poll,500);
                        setTimeout(function(){
                            stop(); B.prop('disabled',0).html('🚀 Generate Now (Next Country)');
                            if(r.success && r.data){
                                var d=r.data;
                                $('#pb-bar').css('width',(d.percent||100)+'%').text((d.percent||100)+'%');
                                if(d.status==='success') $('#pb-bar').css('background','linear-gradient(90deg,#38a169,#48bb78)');
                                else if(d.status==='error') $('#pb-bar').css('background','#c53030');
                                $('#pb-lbl').text(d.label||'Done'); $('#pb-det').text(d.detail||'');
                                if(d.status==='success') setTimeout(function(){location.reload();},3000);
                            }
                        },1000);
                    },
                    error:function(x){
                        stop();
                        $('#pb-bar').css({width:'100%',background:'#c53030'}).text('ERROR');
                        $('#pb-lbl').text('❌ Request failed');
                        $('#pb-det').text(x.status+' '+x.statusText+'\n\nCheck Posts — it may have been created before timeout.');
                        B.prop('disabled',0).html('🚀 Generate Now (Next Country)');
                    }
                });
            });

            function poll(){
                $.post(A,{action:'dba_latam_progress',nonce:N},function(r){
                    if(!r.success||!r.data||r.data.status==='idle') return;
                    var d=r.data, p=d.percent||0;
                    $('#pb-bar').css('width',p+'%').text(p+'%');
                    if(d.status==='success') $('#pb-bar').css('background','linear-gradient(90deg,#38a169,#48bb78)');
                    else if(d.status==='error') $('#pb-bar').css('background','#c53030');
                    $('#pb-lbl').text(d.label||''); $('#pb-det').text(d.detail||'');
                    if(d.step>S){
                        S=d.step;
                        var ic=d.status==='success'?'✅':(d.status==='error'?'❌':'🔵');
                        var L=$('#pb-log');
                        L.append('<div>'+(d.time||'')+' '+ic+' '+(d.label||'')+'</div>');
                        L.scrollTop(L[0].scrollHeight);
                    }
                });
            }
            function stop(){if(T){clearInterval(T);T=null;}}

            // RESET ROTATION
            $('#dba-rst').on('click',function(){
                if(!confirm('Reset rotation to Brazil?')) return;
                $.post(A,{action:'dba_latam_reset_rotation',nonce:N},function(r){if(r.success){alert(r.data.message);location.reload();}});
            });

            // CLEAN ORPHANS / FIX COUNTER
            $('#dba-clean').on('click',function(){
                if(!confirm('Clean orphaned meta and fix the counter?')) return;
                var B=$(this).prop('disabled',1).text('🧹 Cleaning...');
                $.post(A,{action:'dba_latam_cleanup_counter',nonce:N},function(r){
                    B.prop('disabled',0).text('🧹 Fix Counter (Clean Orphans)');
                    if(r.success){
                        $('#dba-tot').text(r.data.count);
                        alert(r.data.message);
                    } else {
                        alert('Failed');
                    }
                });
            });

            // SCAN & FIX LINKS — re-scan all LATAM posts and optimize internal links
            $('#dba-scan-links').on('click',function(){
                if(!confirm('Scan all existing LATAM posts and inject/fix SEO-optimized internal links?\n\nThis may take 30-60 seconds.')) return;
                var B=$(this).prop('disabled',1).html('⏳ Scanning...');
                $('#pb').slideDown(200);
                $('#pb-bar').css({width:'10%',background:'linear-gradient(90deg,#0e7c42,#38a169)'}).text('10%');
                $('#pb-lbl').text('🔍 Scanning LATAM posts for SEO links...'); $('#pb-det').text(''); $('#pb-log').html('');
                $.ajax({
                    url:A, method:'POST', timeout:120000,
                    data:{action:'dba_latam_scan_fix_links',nonce:N},
                    success:function(r){
                        B.prop('disabled',0).html('🔍 Scan & Fix Links');
                        if(r.success && r.data){
                            var d=r.data;
                            $('#pb-bar').css({width:'100%',background:'linear-gradient(90deg,#38a169,#48bb78)'}).text('100%');
                            $('#pb-lbl').text('✅ ' + d.message);
                            $('#pb-det').text(d.details||'');
                            var L=$('#pb-log');
                            if(d.log){d.log.forEach(function(l){L.append('<div>'+l+'</div>');});}
                            L.scrollTop(L[0].scrollHeight);
                        } else {
                            $('#pb-bar').css({width:'100%',background:'#c53030'}).text('ERROR');
                            $('#pb-lbl').text('❌ Scan failed');
                            $('#pb-det').text(r.data && r.data.message ? r.data.message : 'Unknown error');
                        }
                    },
                    error:function(x){
                        B.prop('disabled',0).html('🔍 Scan & Fix Links');
                        $('#pb-bar').css({width:'100%',background:'#c53030'}).text('ERROR');
                        $('#pb-lbl').text('❌ Request failed');
                        $('#pb-det').text(x.status+' '+x.statusText);
                    }
                });
            });

            // ═══ KAIZEN: Flush Cache ═══
            $('#dba-flush-kaizen').on('click',function(){
                var B=$(this).prop('disabled',1).text('⏳ Flushing...');
                var M=$('#dba-kaizen-msg');
                $.post(A,{action:'dba_latam_flush_kaizen_cache',nonce:N},function(r){
                    B.prop('disabled',0).text('🔄 Flush Kaizen Cache');
                    if(r.success){
                        M.css('color','#166534').text('✅ '+r.data.message);
                    } else {
                        M.css('color','#991b1b').text('❌ '+(typeof r.data==='string'?r.data:r.data.message||'Failed'));
                    }
                }).fail(function(x){ B.prop('disabled',0).text('🔄 Flush Kaizen Cache'); M.css('color','#991b1b').text('❌ '+x.statusText); });
            });

            // ═══ ANTI-ORPHAN: Run Audit ═══
            $('#dba-run-audit').on('click',function(){
                if(!confirm('Run orphan audit across all 15 LATAM countries and fix missing cross-links?')) return;
                var B=$(this).prop('disabled',1).text('⏳ Auditing...');
                var M=$('#dba-audit-msg');
                M.css('color','#555').text('⏳ Scanning all countries…');
                $.post(A,{action:'dba_latam_run_orphan_audit',nonce:N},function(r){
                    B.prop('disabled',0);
                    if(r.success){
                        var d=r.data;
                        M.css('color','#166534').text('✅ '+d.message);
                        B.text('🔧 Fix All Orphans ('+(d.orphaned-d.fixed)+')');
                        if(d.orphaned-d.fixed<=0) B.prop('disabled',1);
                        if(d.fixed>0) setTimeout(function(){location.reload();},2000);
                    } else {
                        M.css('color','#991b1b').text('❌ '+(typeof r.data==='string'?r.data:r.data.message||'Failed'));
                        B.text('🔧 Fix All Orphans');
                    }
                }).fail(function(x){ B.prop('disabled',0).text('🔧 Fix All Orphans'); M.css('color','#991b1b').text('❌ '+x.statusText); });
            });
        });
        </script>
        <?php
    }
}
