<?php
/**
 * DBA_EEurope_Admin
 *
 * WordPress admin interface for Eastern Europe GeoBot.
 * Features: status cards, country/city toggles, schedule config,
 * Generate Now with live progress, Scan & Fix Links, Disable CTA,
 * custom title queue, recent posts table, rotation status.
 *
 * @since 3.0.0
 */

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

class DBA_EEurope_Admin {

    private static $instance = null;

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

    private function __construct() {
        add_action( 'admin_menu',               array( $this, 'add_menu' ), 26 );
        add_action( 'admin_init',               array( $this, 'register_settings' ) );
        add_action( 'wp_ajax_dba_eeurope_save', array( $this, 'ajax_save' ) );
        add_action( 'wp_ajax_dba_eeurope_add_custom_title',    array( $this, 'ajax_add_custom_title' ) );
        add_action( 'wp_ajax_dba_eeurope_remove_custom_title', array( $this, 'ajax_remove_custom_title' ) );
        add_action( 'wp_ajax_dba_eeurope_save_comparisons',    array( $this, 'ajax_save_comparisons' ) );
    }

    public function add_menu() {
        add_submenu_page(
            'dba-settings',
            'Eastern Europe GeoBot',
            '🇪🇺 Eastern Europe',
            'manage_options',
            'dba-eeurope',
            array( $this, 'render_page' )
        );
    }

    public function register_settings() {
        register_setting( 'dba_eeurope_settings_group', 'dba_eeurope_settings' );
    }

    /* ── AJAX: Save all settings ── */

    public function ajax_save() {
        check_ajax_referer( 'dba_admin_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error();

        $settings = get_option( 'dba_eeurope_settings', array() );

        $settings['enabled']        = ! empty( $_POST['enabled'] );
        $settings['posts_per_run']  = max( 1, intval( $_POST['posts_per_run'] ?? 3 ) );
        $settings['cooldown_days']  = max( 0, intval( $_POST['cooldown_days'] ?? 5 ) );
        $settings['post_status']    = sanitize_key( $_POST['post_status'] ?? 'publish' );
        $settings['author_id']      = intval( $_POST['author_id'] ?? 1 );
        $settings['category_id']    = intval( $_POST['category_id'] ?? 0 );
        $settings['word_count_min'] = max( 800, intval( $_POST['word_count_min'] ?? 1000 ) );
        $settings['word_count_max'] = max( 1000, intval( $_POST['word_count_max'] ?? 1800 ) );
        $settings['cron_hour']      = max( 0, min( 23, intval( $_POST['cron_hour'] ?? 9 ) ) );
        $settings['cta_text']       = sanitize_text_field( $_POST['cta_text'] ?? '' );
        $settings['cta_link_text']  = sanitize_text_field( $_POST['cta_link_text'] ?? '' );
        $settings['cta_link_url']   = esc_url_raw( $_POST['cta_link_url'] ?? '' );
        $settings['disable_cta']    = ! empty( $_POST['disable_cta'] );
        $settings['comparison_mode'] = sanitize_key( $_POST['comparison_mode'] ?? 'auto' );

        $days = array();
        if ( ! empty( $_POST['posting_days'] ) && is_array( $_POST['posting_days'] ) ) {
            foreach ( $_POST['posting_days'] as $d ) {
                $d = strtolower( sanitize_key( $d ) );
                if ( in_array( $d, DBA_EEurope_Scheduler::ALL_DAYS, true ) ) $days[] = $d;
            }
        }
        $settings['posting_days'] = $days ?: array( 'thursday', 'friday' );

        update_option( 'dba_eeurope_settings', $settings );

        $countries = DBA_EEurope_Registry::get_countries();
        $enabled_countries = array();
        foreach ( $countries as $key => $cfg ) {
            $cs = get_option( $cfg['settings_option'], array() );
            $cs['enabled'] = ! empty( $_POST['country_enabled'][ $key ] );
            if ( $cs['enabled'] ) $enabled_countries[] = $key;
            if ( ! empty( $_POST['country_cities'][ $key ] ) && is_array( $_POST['country_cities'][ $key ] ) ) {
                $cs['active_communes'] = array_map( 'sanitize_text_field', $_POST['country_cities'][ $key ] );
            } else {
                $cs['active_communes'] = array();
            }
            update_option( $cfg['settings_option'], $cs );
        }
        $settings['enabled_countries'] = $enabled_countries;
        update_option( 'dba_eeurope_settings', $settings );

        DBA_EEurope_Scheduler::reschedule();
        wp_send_json_success( array( 'message' => 'Settings saved. ' . count( $enabled_countries ) . ' countries enabled.' ) );
    }

    /* ── AJAX: Custom Title Queue ── */

    public function ajax_add_custom_title() {
        check_ajax_referer( 'dba_admin_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error();
        $title   = sanitize_text_field( wp_unslash( $_POST['custom_title'] ?? '' ) );
        $country = sanitize_key( $_POST['custom_country'] ?? '' );
        if ( empty( $title ) ) wp_send_json_error( 'Title is empty.' );

        // Validate country if specified
        if ( $country && $country !== 'any' ) {
            $valid = DBA_EEurope_Registry::get_country( $country );
            if ( ! $valid ) wp_send_json_error( 'Invalid country: ' . $country );
        }

        $queue = get_option( 'dba_eeurope_custom_title_queue', array() );
        $queue[] = array(
            'title'    => $title,
            'country'  => $country ?: 'any',
            'added'    => current_time( 'mysql' ),
            'added_by' => get_current_user_id(),
        );
        update_option( 'dba_eeurope_custom_title_queue', $queue );

        $label = $country && $country !== 'any'
            ? DBA_EEurope_Registry::get_country( $country )['label'] ?? $country
            : 'any country';
        wp_send_json_success( array( 'message' => 'Title queued for ' . $label . ': "' . $title . '"', 'count' => count( $queue ) ) );
    }

    public function ajax_remove_custom_title() {
        check_ajax_referer( 'dba_admin_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error();
        $index = intval( $_POST['index'] ?? -1 );
        $queue = get_option( 'dba_eeurope_custom_title_queue', array() );
        if ( isset( $queue[ $index ] ) ) {
            array_splice( $queue, $index, 1 );
            update_option( 'dba_eeurope_custom_title_queue', $queue );
        }
        wp_send_json_success( array( 'message' => 'Removed.', 'count' => count( $queue ) ) );
    }

    /* ── AJAX: Save theme comparison flags ── */

    public function ajax_save_comparisons() {
        check_ajax_referer( 'dba_admin_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error();

        $themes = DBA_EEurope_Scheduler::get_themes();
        $posted = isset( $_POST['theme_comparison'] ) && is_array( $_POST['theme_comparison'] ) ? $_POST['theme_comparison'] : array();

        $overrides = array();
        foreach ( $themes as $t ) {
            $tk = sanitize_key( $t['key'] );
            $overrides[ $tk ] = ! empty( $posted[ $tk ] ) ? 1 : 0;
        }

        update_option( 'dba_eeurope_theme_comparison', $overrides, false );

        $on  = array_keys( array_filter( $overrides ) );
        $off = array_keys( array_diff_key( $overrides, array_flip( $on ) ) );
        error_log( 'DBA EEurope: Comparison flags saved — ON: ' . ( $on ? implode( ', ', $on ) : 'none' ) . ' | OFF: ' . ( $off ? implode( ', ', $off ) : 'none' ) );

        wp_send_json_success( array( 'message' => 'Comparison settings saved. 🔀 ' . count( $on ) . ' themes allow comparison, 🔒 ' . count( $off ) . ' locked.' ) );
    }

    /* ══════════════════════════════════════════════════════════════
     *  ADMIN PAGE RENDER
     * ══════════════════════════════════════════════════════════════ */

    public function render_page() {
        $settings   = get_option( 'dba_eeurope_settings', array() );
        $countries  = DBA_EEurope_Registry::get_countries();
        $rotation   = DBA_EEurope_Registry::get_rotation_state();
        $enabled    = DBA_EEurope_Registry::get_enabled_countries();
        $next_key   = DBA_EEurope_Registry::peek_next_country();
        $themes     = DBA_EEurope_Scheduler::get_themes();

        global $wpdb;
        $post_count = $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_eeurope_auto_created' AND p.post_status IN ('publish','draft','pending','future')" );

        $cooldown_days = max( 0, absint( $settings['cooldown_days'] ?? 5 ) );
        $next_eligible = DBA_EEurope_Registry::peek_next_eligible_country( $cooldown_days );

        $posting_days = ! empty( $settings['posting_days'] ) ? (array) $settings['posting_days'] : array( 'thursday', 'friday' );
        $cron_hour = isset( $settings['cron_hour'] ) ? intval( $settings['cron_hour'] ) : 9;
        $cron_active = false;
        $next_run_ts = false;
        foreach ( $posting_days as $pd ) {
            $ts = wp_next_scheduled( DBA_EEurope_Scheduler::CRON_HOOK, array( $pd ) );
            if ( $ts ) { $cron_active = true; if ( ! $next_run_ts || $ts < $next_run_ts ) $next_run_ts = $ts; }
        }

        $last_theme_key = '';
        $last_post = $wpdb->get_row( "SELECT p.ID FROM {$wpdb->posts} p INNER JOIN {$wpdb->postmeta} pm ON pm.post_id = p.ID AND pm.meta_key = '_dba_eeurope_auto_created' WHERE p.post_status IN ('publish','draft') ORDER BY p.post_date DESC LIMIT 1" );
        if ( $last_post ) $last_theme_key = get_post_meta( $last_post->ID, '_dba_eeurope_theme', true );

        $title_queue = get_option( 'dba_eeurope_custom_title_queue', array() );

        $recent_posts = $wpdb->get_results(
            "SELECT p.ID, p.post_title, p.post_status, p.post_date,
                    t.meta_value AS theme_key, c.meta_value AS country_key, ci.meta_value AS city_name
             FROM {$wpdb->posts} p
             INNER JOIN {$wpdb->postmeta} pm ON pm.post_id = p.ID AND pm.meta_key = '_dba_eeurope_auto_created'
             LEFT JOIN {$wpdb->postmeta} t  ON t.post_id  = p.ID AND t.meta_key  = '_dba_eeurope_theme'
             LEFT JOIN {$wpdb->postmeta} c  ON c.post_id  = p.ID AND c.meta_key  = '_dba_eeurope_country'
             LEFT JOIN {$wpdb->postmeta} ci ON ci.post_id = p.ID AND ci.meta_key = '_dba_eeurope_city'
             WHERE p.post_status IN ('publish','draft','pending','future')
             ORDER BY p.post_date DESC LIMIT 10"
        );

        $flags = array(
            'poland'=>'🇵🇱','czech_republic'=>'🇨🇿','serbia'=>'🇷🇸','croatia'=>'🇭🇷',
            'slovenia'=>'🇸🇮','slovakia'=>'🇸🇰','hungary'=>'🇭🇺','romania'=>'🇷🇴',
            'bulgaria'=>'🇧🇬','estonia'=>'🇪🇪','latvia'=>'🇱🇻','lithuania'=>'🇱🇹',
        );
        ?>
        <div class="wrap">
            <h1>🇪🇺 Eastern Europe GeoBot</h1>
            <p>Automated article generation for 12 Eastern European countries with anti-hallucination validation.</p>

            <!-- ══ STATUS CARDS ══ -->
            <div style="display:flex;gap:16px;flex-wrap:wrap;margin:20px 0;">
                <div style="flex:1;min-width:180px;background:#fff;border:1px solid #e5e7eb;border-radius:8px;padding:16px;">
                    <div style="color:#666;font-size:12px;font-weight:600;margin-bottom:6px;">Module Status</div>
                    <?php if ( ! empty( $settings['enabled'] ) ) : ?>
                        <span style="display:inline-block;padding:4px 12px;background:#dcfce7;color:#166534;border-radius:12px;font-weight:700;font-size:13px;">● ACTIVE</span>
                    <?php else : ?>
                        <span style="display:inline-block;padding:4px 12px;background:#fee2e2;color:#991b1b;border-radius:12px;font-weight:700;font-size:13px;">● DISABLED</span>
                    <?php endif; ?>
                    <div style="margin-top:6px;font-size:12px;color:#888;">Posts: <?php echo intval( $post_count ); ?> | <?php echo count( $enabled ); ?>/<?php echo count( $countries ); ?> countries</div>
                </div>
                <div style="flex:1;min-width:180px;background:#fff;border:1px solid #e5e7eb;border-radius:8px;padding:16px;">
                    <div style="color:#666;font-size:12px;font-weight:600;margin-bottom:6px;">Schedule</div>
                    <div style="font-weight:600;">Every <?php echo esc_html( implode( ', ', array_map( function($d){ return substr(ucfirst($d),0,3); }, $posting_days ) ) ); ?> at <?php echo sprintf( '%02d:00', $cron_hour ); ?></div>
                    <div style="margin-top:4px;font-size:12px;">Cron: <?php echo $cron_active ? '✅ Active' : '❌ Inactive'; ?></div>
                </div>
                <div style="flex:1;min-width:180px;background:#fff;border:1px solid #e5e7eb;border-radius:8px;padding:16px;">
                    <div style="color:#666;font-size:12px;font-weight:600;margin-bottom:6px;">Next Run</div>
                    <?php if ( $next_run_ts ) : ?>
                        <div style="font-weight:600;"><?php echo date_i18n( 'l, j F Y', $next_run_ts + ( get_option( 'gmt_offset', 0 ) * 3600 ) ); ?></div>
                        <div style="font-size:12px;">at <?php echo sprintf( '%02d:00', $cron_hour ); ?> (Europe/Luxembourg)</div>
                    <?php else : ?>
                        <div style="color:#999;">Not scheduled</div>
                    <?php endif; ?>
                </div>
                <div style="flex:1;min-width:180px;background:#fff;border:1px solid #e5e7eb;border-radius:8px;padding:16px;">
                    <div style="color:#666;font-size:12px;font-weight:600;margin-bottom:6px;">Last Theme Used</div>
                    <div style="font-weight:600;"><?php echo esc_html( $last_theme_key ?: '—' ); ?></div>
                    <div style="margin-top:4px;font-size:12px;">Next: <?php echo $next_key ? ( ( $flags[ $next_key ] ?? '' ) . ' ' . ( $countries[ $next_key ]['label'] ?? $next_key ) ) : 'None'; ?></div>
                </div>
            </div>

            <!-- Generate Now + Progress -->
            <div style="margin:16px 0;display:flex;gap:8px;flex-wrap:wrap;">
                <button type="button" class="button button-primary" id="dba-eeurope-generate-now">🚀 Generate Now</button>
                <button type="button" class="button" id="dba-eeurope-reset-rotation">🔄 Reset Rotation</button>
                <button type="button" class="button" id="dba-eeurope-cleanup">🧹 Cleanup Counters</button>
                <button type="button" class="button" id="dba-eeurope-scan-fix-links">🔗 Scan & Fix Links</button>
            </div>
            <div id="dba-eeurope-progress" style="display:none;background:#fff;border:1px solid #ccd0d4;border-radius:4px;padding:16px;margin:16px 0;">
                <div id="dba-eeurope-progress-label" style="font-weight:600;margin-bottom:8px;"></div>
                <div style="background:#e5e5e5;border-radius:3px;overflow:hidden;height:24px;">
                    <div id="dba-eeurope-progress-bar" style="background:#2271b1;height:100%;width:0%;transition:width 0.3s;border-radius:3px;"></div>
                </div>
                <div id="dba-eeurope-progress-detail" style="color:#666;margin-top:6px;font-size:12px;"></div>
            </div>

            <form id="dba-eeurope-settings-form">
                <?php wp_nonce_field( 'dba_admin_nonce', 'nonce' ); ?>
                <h2>General Settings</h2>
                <table class="form-table">
                    <tr><th>Module Enabled</th><td><label><input type="checkbox" name="enabled" value="1" <?php checked( ! empty( $settings['enabled'] ) ); ?>> Enable Eastern Europe GeoBot</label></td></tr>
                    <tr><th>Posts per Cron Run</th><td><input type="number" name="posts_per_run" value="<?php echo esc_attr( $settings['posts_per_run'] ?? 3 ); ?>" min="1" max="12" style="width:80px;"></td></tr>
                    <tr><th>Cooldown (days)</th><td><input type="number" name="cooldown_days" value="<?php echo esc_attr( $settings['cooldown_days'] ?? 5 ); ?>" min="0" max="30" style="width:80px;"> <span class="description">Skip country if it posted within N days.</span></td></tr>
                    <tr><th>Post Status</th><td><select name="post_status"><option value="publish" <?php selected( ( $settings['post_status'] ?? 'publish' ), 'publish' ); ?>>Publish</option><option value="draft" <?php selected( ( $settings['post_status'] ?? '' ), 'draft' ); ?>>Draft</option></select></td></tr>
                    <tr><th>Word Count</th><td>Min: <input type="number" name="word_count_min" value="<?php echo esc_attr( $settings['word_count_min'] ?? 1000 ); ?>" min="800" max="2000" style="width:80px;"> Max: <input type="number" name="word_count_max" value="<?php echo esc_attr( $settings['word_count_max'] ?? 1800 ); ?>" min="1000" max="3000" style="width:80px;"></td></tr>
                    <tr><th>Posting Days</th><td><?php $active_days = ! empty( $settings['posting_days'] ) ? (array) $settings['posting_days'] : array( 'thursday', 'friday' ); foreach ( DBA_EEurope_Scheduler::ALL_DAYS as $d ) : ?><label style="margin-right:12px;"><input type="checkbox" name="posting_days[]" value="<?php echo esc_attr( $d ); ?>" <?php checked( in_array( $d, $active_days ) ); ?>> <?php echo ucfirst( $d ); ?></label><?php endforeach; ?></td></tr>
                    <tr><th>Cron Hour (CET)</th><td><input type="number" name="cron_hour" value="<?php echo esc_attr( $settings['cron_hour'] ?? 9 ); ?>" min="0" max="23" style="width:80px;"> :00</td></tr>
                </table>

                <h2>Countries & Cities</h2>
                <table class="widefat striped" style="max-width:900px;">
                    <thead><tr><th>Country</th><th>Enabled</th><th>Cities</th><th>Gov Portal</th></tr></thead>
                    <tbody>
                    <?php
                    $gov_portals = DBA_EEurope_Cities::get_government_portals();
                    foreach ( $countries as $key => $cfg ) :
                        $cs = get_option( $cfg['settings_option'], array() );
                        $is_enabled = ! empty( $cs['enabled'] );
                        $active = ! empty( $cs['active_communes'] ) ? $cs['active_communes'] : array();
                        $all_cities = DBA_EEurope_Cities::get_country_cities( $key );
                        $flag = $flags[ $key ] ?? '';
                        $gov = $gov_portals[ $key ] ?? '';
                    ?>
                        <tr>
                            <td><strong><?php echo $flag . ' ' . esc_html( $cfg['label'] ); ?></strong></td>
                            <td><input type="checkbox" name="country_enabled[<?php echo esc_attr( $key ); ?>]" value="1" <?php checked( $is_enabled ); ?>></td>
                            <td><?php foreach ( $all_cities as $city ) : ?><label style="display:inline-block;margin:2px 8px 2px 0;"><input type="checkbox" name="country_cities[<?php echo esc_attr( $key ); ?>][]" value="<?php echo esc_attr( $city['name'] ); ?>" <?php checked( empty( $active ) || in_array( $city['name'], $active ) ); ?>> <?php echo esc_html( $city['name'] ); ?></label><?php endforeach; ?></td>
                            <td style="font-size:11px;color:#666;"><?php echo esc_html( $gov ); ?></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>

                <h2>🎯 Call to Action</h2>
                <table class="form-table">
                    <tr><th>CTA Text</th><td><textarea name="cta_text" rows="2" style="width:100%;max-width:600px;" placeholder="Damalion supports international investors..."><?php echo esc_textarea( $settings['cta_text'] ?? '' ); ?></textarea></td></tr>
                    <tr><th>CTA Link Text</th><td><input type="text" name="cta_link_text" value="<?php echo esc_attr( $settings['cta_link_text'] ?? '' ); ?>" style="width:300px;" placeholder="Contact your Damalion experts now."></td></tr>
                    <tr><th>CTA Link URL</th><td><input type="url" name="cta_link_url" value="<?php echo esc_attr( $settings['cta_link_url'] ?? '' ); ?>" style="width:400px;" placeholder="https://www.damalion.com/lets-connect/"></td></tr>
                    <tr><th>Disable CTA</th><td><label><input type="checkbox" name="disable_cta" value="1" <?php checked( ! empty( $settings['disable_cta'] ) ); ?>> Don't append CTA block to posts</label></td></tr>
                    <tr><th>Country Comparison</th><td>
                        <select name="comparison_mode">
                            <option value="auto" <?php selected( ( $settings['comparison_mode'] ?? 'auto' ), 'auto' ); ?>>Auto — per theme (recommended)</option>
                            <option value="always" <?php selected( ( $settings['comparison_mode'] ?? '' ), 'always' ); ?>>Always allow — all themes can compare countries</option>
                            <option value="never" <?php selected( ( $settings['comparison_mode'] ?? '' ), 'never' ); ?>>Never — strict single-country lock on all themes</option>
                        </select>
                        <p class="description">Controls whether GPT can reference other countries. "Auto" uses per-theme flags (see Themes table).</p>
                    </td></tr>
                </table>

                <p class="submit"><button type="submit" class="button button-primary button-large">💾 Save Settings</button></p>
            </form>

            <!-- ══ CUSTOM TITLE QUEUE ══ -->
            <h2>✏️ Custom Title Queue</h2>
            <p style="color:#666;">Assign a title to a specific country. It will wait in the queue until that country comes up in rotation. Set "Any" for auto-matching (title is scanned for country names).</p>
            <div style="display:flex;gap:8px;max-width:900px;margin-bottom:12px;align-items:center;">
                <select id="dba-eeurope-custom-country" style="min-width:160px;padding:6px;">
                    <option value="any">🌐 Any (auto-detect)</option>
                    <?php foreach ( $countries as $ck => $cc ) : ?>
                    <option value="<?php echo esc_attr( $ck ); ?>"><?php echo ( $flags[ $ck ] ?? '' ) . ' ' . esc_html( $cc['label'] ); ?></option>
                    <?php endforeach; ?>
                </select>
                <input type="text" id="dba-eeurope-custom-title" style="flex:1;padding:6px 10px;" placeholder="e.g. How to Register a Company in Warsaw, Poland">
                <button type="button" class="button button-primary" id="dba-eeurope-add-title">➕ Add to Queue</button>
            </div>
            <?php if ( ! empty( $title_queue ) ) : ?>
            <table class="widefat striped" style="max-width:900px;">
                <thead><tr><th>#</th><th>Country</th><th>Title</th><th>Added</th><th></th></tr></thead>
                <tbody>
                <?php foreach ( $title_queue as $qi => $qt ) :
                    $qt_country = $qt['country'] ?? 'any';
                    $qt_label   = 'any';
                    if ( $qt_country && $qt_country !== 'any' ) {
                        $qt_cfg = DBA_EEurope_Registry::get_country( $qt_country );
                        $qt_label = ( $flags[ $qt_country ] ?? '' ) . ' ' . ( $qt_cfg['label'] ?? $qt_country );
                    } else {
                        $qt_label = '🌐 Any';
                    }
                ?>
                    <tr>
                        <td><?php echo $qi + 1; ?></td>
                        <td><span style="display:inline-block;padding:2px 8px;background:#e0e7ff;color:#3730a3;border-radius:4px;font-size:11px;font-weight:600;"><?php echo esc_html( $qt_label ); ?></span></td>
                        <td><strong><?php echo esc_html( $qt['title'] ); ?></strong></td>
                        <td style="font-size:12px;color:#888;"><?php echo esc_html( $qt['added'] ?? '' ); ?></td>
                        <td><button type="button" class="button button-small dba-eeurope-remove-title" data-index="<?php echo $qi; ?>" style="color:#dc3232;">✕</button></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            <?php else : ?>
                <p style="color:#999;font-style:italic;">Queue is empty. Titles will be auto-generated by theme rotation.</p>
            <?php endif; ?>

            <!-- ══ RECENT POSTS ══ -->
            <h2 style="margin-top:28px;">📄 Recent EEurope Posts</h2>
            <?php if ( ! empty( $recent_posts ) ) : ?>
            <table class="widefat striped" style="max-width:1000px;">
                <thead><tr><th>ID</th><th>Title</th><th>Country</th><th>Theme</th><th>Status</th><th>Date</th></tr></thead>
                <tbody>
                <?php foreach ( $recent_posts as $rp ) :
                    $rp_flag = $flags[ $rp->country_key ] ?? '';
                    $rp_country = isset( $countries[ $rp->country_key ] ) ? $countries[ $rp->country_key ]['label'] : ( $rp->country_key ?: '—' );
                    $sc_map = array( 'publish'=>array('#dcfce7','#166534'), 'draft'=>array('#fef3c7','#92400e'), 'pending'=>array('#f3e8ff','#6b21a8'), 'future'=>array('#dbeafe','#1e40af') );
                    $sc = $sc_map[ $rp->post_status ] ?? array('#f3f4f6','#333');
                ?>
                <tr>
                    <td><a href="<?php echo get_edit_post_link( $rp->ID ); ?>">#<?php echo $rp->ID; ?></a></td>
                    <td><a href="<?php echo get_edit_post_link( $rp->ID ); ?>"><?php echo esc_html( $rp->post_title ); ?></a></td>
                    <td><?php echo $rp_flag . ' ' . esc_html( $rp_country ); ?></td>
                    <td><span style="display:inline-block;padding:2px 8px;background:#e0e7ff;color:#3730a3;border-radius:4px;font-size:11px;font-weight:600;"><?php echo esc_html( $rp->theme_key ?: '—' ); ?></span></td>
                    <td><span style="display:inline-block;padding:2px 8px;background:<?php echo $sc[0]; ?>;color:<?php echo $sc[1]; ?>;border-radius:4px;font-size:11px;font-weight:600;"><?php echo ucfirst( $rp->post_status ); ?></span></td>
                    <td style="font-size:12px;"><?php echo date_i18n( 'j M Y H:i', strtotime( $rp->post_date ) ); ?></td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            <?php else : ?>
                <p style="color:#999;">No posts generated yet.</p>
            <?php endif; ?>

            <h2 style="margin-top:28px;">Themes (rotation)</h2>
            <p style="font-size:12px;color:#888;max-width:900px;">
                <strong>🔒 Single</strong> = article strictly about ONE country (title/keyphrase locked to that country). <strong>🔀 Compare</strong> = may reference other countries for comparison (primary country stays 70%+ focus).
            </p>
            <?php $comp_overrides = get_option( 'dba_eeurope_theme_comparison', array() ); ?>
            <table class="widefat striped" style="max-width:900px;">
                <thead><tr><th>#</th><th>Theme</th><th>Prompt Context</th><th style="width:120px;">Allow Comparison</th></tr></thead>
                <tbody>
                <?php foreach ( $themes as $i => $t ) :
                    $tk = $t['key'];
                    // DB override takes priority, then fall back to hardcoded default
                    $is_comp = isset( $comp_overrides[ $tk ] ) ? (bool) $comp_overrides[ $tk ] : ! empty( $t['allow_comparison'] );
                ?>
                    <tr>
                        <td><?php echo $i + 1; ?></td>
                        <td><strong><?php echo esc_html( $t['label'] ); ?></strong></td>
                        <td style="font-size:12px;color:#555;"><?php echo esc_html( $t['prompt_context'] ); ?></td>
                        <td style="text-align:center;">
                            <label><input type="checkbox" name="theme_comparison[<?php echo esc_attr( $tk ); ?>]" value="1" <?php checked( $is_comp ); ?>> 🔀</label>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            <p class="submit"><button type="button" class="button" id="dba-eeurope-save-comparisons">💾 Save Theme Comparison Settings</button></p>

            <!-- ══ PLAGIARISM DETECTION & GOOGLE PENALTY COMPLIANCE ══ -->
            <?php
            $plag_class_loaded = class_exists( 'DBA_Plagiarism' );
            $core_settings     = get_option( 'dba_settings', array() );
            $cs_user           = ! empty( $core_settings['copyscape_user'] ) ? $core_settings['copyscape_user'] : '';
            $cs_key            = ! empty( $core_settings['copyscape_key'] )  ? $core_settings['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['google_search_key'] ) && ! empty( $core_settings['google_search_cx'] );
            $dedupe_active     = class_exists( 'DBA_EEurope_Dedupe' );
            ?>
            <div style="background:#f8fafc;border:1px solid #c6dbef;border-left:4px solid #2271b1;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 EEurope 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. Add keys in Settings for full coverage.</span>
                                <?php endif; ?>
                            <?php elseif ( $copyscape_active ) : ?>
                                <strong style="color:#6b7280;">STANDBY</strong> <span style="font-size:11px;">(Copyscape active, fallback not needed)</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>
                </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 before publishing. Any gate failure = article REJECTED and regenerated (up to 2 retries). Failed articles are logged with full error trace.
                </p>
            </div>

            <h2 style="margin-top:28px;">Anti-Hallucination Features</h2>
            <table class="widefat" style="max-width:700px;">
                <tr><td>✅ Verified corporate data injected into prompts (legal form, CIT, capital)</td></tr>
                <tr><td>✅ Government URL registry (factual grounding, never linked)</td></tr>
                <tr><td>✅ Zero-source policy (no "according to" — eliminates fake citations)</td></tr>
                <tr><td>✅ AI slop phrase detection (<?php echo count( DBA_EEurope_Validator::SLOP_PHRASES ); ?> phrases monitored)</td></tr>
                <tr><td>✅ Placeholder rejection (<?php echo count( DBA_EEurope_Validator::PLACEHOLDERS ); ?> patterns)</td></tr>
                <tr><td>✅ Fake institution detection (<?php echo count( DBA_EEurope_Validator::FAKE_INSTITUTIONS ); ?> known hallucinations)</td></tr>
                <tr><td>✅ URL fabrication blocker (only damalion.com allowed)</td></tr>
                <tr><td>✅ Style validation (passive voice ≤10%, transitions ≥30%)</td></tr>
                <tr><td>✅ Density control (city max 3x, country max 4x)</td></tr>
                <tr><td>✅ Self-learning from editor corrections (last 5 posts)</td></tr>
                <tr><td>✅ Title deduplication (90-day window, 85% similarity threshold)</td></tr>
                <tr><td>✅ Retry with feedback (up to 3 attempts on validation failure)</td></tr>
            </table>
        </div>

        <script>
        jQuery(function($) {
            var nonce = $('#nonce').val() || $('input[name="nonce"]').val();
            $('#dba-eeurope-settings-form').on('submit', function(e) {
                e.preventDefault();
                $.post(ajaxurl, $(this).serialize() + '&action=dba_eeurope_save', function(r) { alert(r.success ? r.data.message : 'Save failed'); });
            });
            var pollTimer;
            function pollProgress() {
                $.post(ajaxurl, {action:'dba_eeurope_progress', nonce:nonce}, function(r) {
                    if (!r.success || !r.data) return; var d = r.data;
                    if (typeof d === 'string') try { d = JSON.parse(d); } catch(e) { return; }
                    if (d.status === 'idle') return;
                    $('#dba-eeurope-progress').show();
                    $('#dba-eeurope-progress-label').text(d.label || '');
                    $('#dba-eeurope-progress-bar').css('width', (d.percent||0) + '%');
                    $('#dba-eeurope-progress-detail').text(d.detail || '');
                    if (d.status === 'done' || d.status === 'error' || d.status === 'deferred') { clearInterval(pollTimer); $('#dba-eeurope-generate-now').prop('disabled', false); }
                });
            }
            $('#dba-eeurope-generate-now').on('click', function() {
                $(this).prop('disabled', true); $('#dba-eeurope-progress').show();
                $('#dba-eeurope-progress-label').text('🚀 Starting...'); $('#dba-eeurope-progress-bar').css('width', '0%');
                pollTimer = setInterval(pollProgress, 1500);
                $.post(ajaxurl, {action:'dba_eeurope_generate_now', nonce:nonce}, function(r) { clearInterval(pollTimer); pollProgress(); $('#dba-eeurope-generate-now').prop('disabled', false); });
            });
            $('#dba-eeurope-reset-rotation').on('click', function() { $.post(ajaxurl, {action:'dba_eeurope_reset_rotation', nonce:nonce}, function(r) { alert(r.success ? r.data.message : 'Failed'); location.reload(); }); });
            $('#dba-eeurope-cleanup').on('click', function() { $.post(ajaxurl, {action:'dba_eeurope_cleanup_counter', nonce:nonce}, function(r) { alert(r.success ? r.data.message : 'Failed'); }); });
            $('#dba-eeurope-scan-fix-links').on('click', function() {
                $(this).prop('disabled', true).text('Scanning...');
                $.post(ajaxurl, {action:'dba_eeurope_scan_fix_links', nonce:nonce}, function(r) {
                    $('#dba-eeurope-scan-fix-links').prop('disabled', false).text('🔗 Scan & Fix Links');
                    if (r.success) { var msg = r.data.message; if (r.data.log && r.data.log.length) msg += "\n\n" + r.data.log.join("\n"); alert(msg); } else { alert('Scan failed'); }
                });
            });
            // Custom Title Queue — with country
            $('#dba-eeurope-add-title').on('click', function() {
                var t = $('#dba-eeurope-custom-title').val().trim();
                var c = $('#dba-eeurope-custom-country').val();
                if (!t) { alert('Please enter a title.'); return; }
                $.post(ajaxurl, {action:'dba_eeurope_add_custom_title', nonce:nonce, custom_title:t, custom_country:c}, function(r) { if (r.success) { alert(r.data.message); location.reload(); } else { alert(r.data || 'Failed to add title.'); } });
            });
            // Auto-detect country from title text
            var countryMap = {
                'poland':'poland','warsaw':'poland','kraków':'poland','krakow':'poland','wrocław':'poland','wroclaw':'poland','gdańsk':'poland','gdansk':'poland','łódź':'poland','lodz':'poland','poznań':'poland','poznan':'poland',
                'czech republic':'czech_republic','prague':'czech_republic','brno':'czech_republic','ostrava':'czech_republic',
                'serbia':'serbia','belgrade':'serbia','novi sad':'serbia','niš':'serbia','nis':'serbia',
                'croatia':'croatia','zagreb':'croatia','split':'croatia','rijeka':'croatia',
                'slovenia':'slovenia','ljubljana':'slovenia','maribor':'slovenia','celje':'slovenia',
                'slovakia':'slovakia','bratislava':'slovakia','košice':'slovakia','kosice':'slovakia','prešov':'slovakia','presov':'slovakia',
                'hungary':'hungary','budapest':'hungary','debrecen':'hungary','szeged':'hungary',
                'romania':'romania','bucharest':'romania','cluj':'romania','timișoara':'romania','timisoara':'romania',
                'bulgaria':'bulgaria','sofia':'bulgaria','plovdiv':'bulgaria','varna':'bulgaria',
                'estonia':'estonia','tallinn':'estonia','tartu':'estonia','narva':'estonia',
                'latvia':'latvia','riga':'latvia','daugavpils':'latvia','liepāja':'latvia','liepaja':'latvia',
                'lithuania':'lithuania','vilnius':'lithuania','kaunas':'lithuania','klaipėda':'lithuania','klaipeda':'lithuania'
            };
            $('#dba-eeurope-custom-title').on('blur change', function() {
                var val = $(this).val().toLowerCase();
                if ($('#dba-eeurope-custom-country').val() !== 'any') return; // Don't override manual selection
                for (var term in countryMap) {
                    if (val.indexOf(term) !== -1) {
                        $('#dba-eeurope-custom-country').val(countryMap[term]);
                        return;
                    }
                }
            });
            $('.dba-eeurope-remove-title').on('click', function() {
                var idx = $(this).data('index');
                if (!confirm('Remove this title from queue?')) return;
                $.post(ajaxurl, {action:'dba_eeurope_remove_custom_title', nonce:nonce, index:idx}, function(r) { if (r.success) location.reload(); });
            });
            // Save theme comparison flags
            $('#dba-eeurope-save-comparisons').on('click', function() {
                var btn = $(this).prop('disabled',true).text('Saving...');
                var data = {action:'dba_eeurope_save_comparisons', nonce:nonce};
                $('input[name^="theme_comparison"]').each(function() {
                    data[$(this).attr('name')] = $(this).is(':checked') ? 1 : 0;
                });
                $.post(ajaxurl, data, function(r) {
                    btn.prop('disabled',false).text('💾 Save Theme Comparison Settings');
                    alert(r.success ? r.data.message : 'Save failed');
                });
            });
        });
        </script>
        <?php
    }
}
