<?php
/**
 * DBA Comfisc Admin — Comptabilité & Fiscalité Dashboard
 *
 * Full admin panel mirroring GeoBot feature set:
 *   - Enable/disable toggle
 *   - Publishing Days (Mon–Sun checkboxes)
 *   - Posts per Run (1–5)
 *   - Post status, Author
 *   - Word Count Range (min–max)
 *   - French categories (from config, default: Comptabilité/Fiscalité)
 *   - Active themes (36 themes, grouped by 4 clusters)
 *   - CTA settings (editable text, link text, link URL, disable toggle)
 *   - Coverage stats bar
 *   - Recent posts table
 *   - 🛡 Plagiarism Detection status panel
 *   - 🧠 Kaizen Learning Engine status panel
 *   - 🛡 Anti-Orphan Protection status panel
 *   - 🔒 Isolation Keys
 *   - ⚡ Generate Now
 *
 * @package DamalionBlogAI
 * @subpackage Comfisc
 * @since 2.19.0
 */

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

class DBA_Comfisc_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, 'register_menu' ), 14 );
        add_action( 'wp_ajax_dba_comfisc_save_settings',  array( $this, 'ajax_save_settings' ) );
        add_action( 'wp_ajax_dba_comfisc_generate_now',   array( $this, 'ajax_generate_now' ) );
        add_action( 'wp_ajax_dba_comfisc_fix_orphans',    array( $this, 'ajax_fix_orphans' ) );
    }

    public function register_menu() {
        add_submenu_page(
            'dba-settings',
            'Comfisc (Comptabilité)',
            '🟤 Comfisc (FR)',
            'manage_options',
            'dba-comfisc',
            array( $this, 'render_page' )
        );
    }

    /* ═══════════════════════════════════════════════════════════
     *  AJAX: Save Settings
     * ═══════════════════════════════════════════════════════════ */

    public function ajax_save_settings() {
        check_ajax_referer( 'dba_comfisc_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( 'Permission denied' );

        $lang = sanitize_key( $_POST['lang'] ?? 'fr' );
        $option_key = 'dba_comfisc_' . $lang . '_settings';

        $settings = array(
            'enabled'          => ! empty( $_POST['enabled'] ),
            'publishing_days'  => array_map( 'absint', (array) ( $_POST['publishing_days'] ?? array() ) ),
            'posts_per_run'    => max( 1, min( 5, absint( $_POST['posts_per_run'] ?? 1 ) ) ),
            'post_status'      => sanitize_text_field( $_POST['post_status'] ?? 'publish' ),
            'author_id'        => absint( $_POST['author_id'] ?? 1 ),
            'word_count_min'   => max( 400, absint( $_POST['word_count_min'] ?? 800 ) ),
            'word_count_max'   => max( 600, absint( $_POST['word_count_max'] ?? 1200 ) ),
            'category_name'    => sanitize_text_field( $_POST['category_name'] ?? 'Comptabilité/Fiscalité' ),
            'extra_categories' => array_map( 'sanitize_text_field', (array) ( $_POST['extra_categories'] ?? array() ) ),
            'active_themes'    => array_map( 'sanitize_key', (array) ( $_POST['active_themes'] ?? array() ) ),
            'cta_text'         => sanitize_textarea_field( $_POST['cta_text'] ?? '' ),
            'cta_link_text'    => sanitize_text_field( $_POST['cta_link_text'] ?? '' ),
            'cta_link_url'     => esc_url_raw( $_POST['cta_link_url'] ?? '' ),
            'cta_disabled'     => ! empty( $_POST['cta_disabled'] ),
        );

        // Resolve French category name → WP term ID
        $settings['category_id'] = self::resolve_category_by_name( $settings['category_name'] );
        $settings['extra_category_ids'] = array();
        foreach ( $settings['extra_categories'] as $cat_name ) {
            $cid = self::resolve_category_by_name( $cat_name );
            if ( $cid > 0 ) $settings['extra_category_ids'][] = $cid;
        }

        // Ensure word_count_max > word_count_min
        if ( $settings['word_count_max'] <= $settings['word_count_min'] ) {
            $settings['word_count_max'] = $settings['word_count_min'] + 400;
        }

        update_option( $option_key, $settings );

        // Reschedule cron with new days
        if ( class_exists( 'DBA_Comfisc_Scheduler' ) ) {
            DBA_Comfisc_Scheduler::deactivate_language( $lang );
            if ( $settings['enabled'] ) {
                $languages = DBA_Comfisc_Loader::get_languages();
                if ( isset( $languages[ $lang ] ) ) {
                    DBA_Comfisc_Scheduler::activate_language( $lang, $languages[ $lang ] );
                }
            }
        }

        wp_send_json_success( array( 'message' => 'Paramètres enregistrés.', 'settings' => $settings ) );
    }

    private static function resolve_category_by_name( $name ) {
        if ( empty( $name ) ) return 0;
        $term = get_term_by( 'name', $name, 'category' );
        if ( $term && ! is_wp_error( $term ) ) return (int) $term->term_id;
        $slug = sanitize_title( $name );
        $term = get_term_by( 'slug', $slug, 'category' );
        if ( $term && ! is_wp_error( $term ) ) return (int) $term->term_id;
        return 0;
    }

    /* ═══════════════════════════════════════════════════════════
     *  AJAX: Generate Now
     * ═══════════════════════════════════════════════════════════ */

    public function ajax_generate_now() {
        check_ajax_referer( 'dba_comfisc_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( 'Permission denied' );

        $lang = sanitize_key( $_POST['lang'] ?? 'fr' );

        if ( ! class_exists( 'DBA_Comfisc_Generator' ) ) {
            wp_send_json_error( 'Generator class not loaded.' );
        }

        $languages = DBA_Comfisc_Loader::get_languages();
        if ( empty( $languages[ $lang ] ) ) {
            wp_send_json_error( 'Language config not found: ' . $lang );
        }

        $result = DBA_Comfisc_Generator::run( $lang, $languages[ $lang ], true );

        if ( is_wp_error( $result ) ) {
            wp_send_json_error( $result->get_error_message() );
        }

        wp_send_json_success( array(
            'message' => 'Article généré avec succès !',
            'post_id' => $result['post_id'] ?? 0,
            'edit_url' => ! empty( $result['post_id'] ) ? get_edit_post_link( $result['post_id'], 'raw' ) : '',
        ) );
    }

    /* ═══════════════════════════════════════════════════════════
     *  AJAX: Fix All Orphan Posts
     * ═══════════════════════════════════════════════════════════ */

    public function ajax_fix_orphans() {
        check_ajax_referer( 'dba_comfisc_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( 'Permission denied' );

        $lang = sanitize_key( $_POST['lang'] ?? 'fr' );

        if ( ! class_exists( 'DBA_Comfisc_Anti_Orphan' ) ) {
            wp_send_json_error( 'Anti-Orphan class not loaded.' );
        }

        $result = DBA_Comfisc_Anti_Orphan::fix_all_orphans( $lang );

        // Get fresh stats after fix
        $stats = DBA_Comfisc_Anti_Orphan::get_orphan_stats( $lang );

        wp_send_json_success( array(
            'message'        => sprintf(
                'Scan terminé : %d articles analysés. %d blocs "Articles connexes" ajoutés, %d liens pilier corrigés, %d backlinks injectés.',
                $result['scanned'],
                $result['fixed_related'],
                $result['fixed_pillar'],
                $result['fixed_backlinks']
            ),
            'result'         => $result,
            'orphans_remaining' => $stats['orphan_count'],
        ) );
    }

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

    public function render_page() {
        if ( ! class_exists( 'DBA_Comfisc_Loader' ) ) {
            echo '<div class="wrap"><h1>🟤 Comfisc</h1><div class="notice notice-error"><p>Comfisc Loader introuvable.</p></div></div>';
            return;
        }

        $languages = DBA_Comfisc_Loader::get_languages();
        $nonce     = wp_create_nonce( 'dba_comfisc_nonce' );

        ?>
        <div class="wrap">
        <h1 style="display:flex;align-items:center;gap:10px;">
            <span style="font-size:28px;">🟤</span> Comfisc — Comptabilité & Fiscalité
            <small style="font-size:13px;color:#666;">v2.19.0</small>
        </h1>

        <?php foreach ( $languages as $lang => $config ) :
            $option_key = 'dba_comfisc_' . $lang . '_settings';
            $settings   = get_option( $option_key, array() );
            $enabled    = ! empty( $settings['enabled'] );

            // Resolved settings with defaults
            $post_status    = $settings['post_status'] ?? 'publish';
            $author_id      = $settings['author_id'] ?? 1;
            $posts_per_run  = isset( $settings['posts_per_run'] ) ? absint( $settings['posts_per_run'] ) : 1;
            $word_min       = $settings['word_count_min'] ?? 800;
            $word_max       = $settings['word_count_max'] ?? 1200;
            $default_cat    = $config['default_category'] ?? 'Comptabilité/Fiscalité';
            $saved_cat_name = $settings['category_name'] ?? $default_cat;
            $extra_cats     = $settings['extra_categories'] ?? array();
            $categories_fr  = $config['categories_fr'] ?? array();
            $active_themes  = $settings['active_themes'] ?? array();
            $all_themes     = $config['themes'] ?? array();

            // CTA settings
            $cta_text      = $settings['cta_text'] ?? ( $config['cta_defaults']['text'] ?? '' );
            $cta_link_text = $settings['cta_link_text'] ?? ( $config['cta_defaults']['link_text'] ?? '' );
            $cta_link_url  = $settings['cta_link_url'] ?? ( $config['cta_defaults']['link_url'] ?? '' );
            $cta_disabled  = ! empty( $settings['cta_disabled'] );

            // Publishing days: settings first, then config
            $config_days    = $config['schedule']['days'] ?? array( 1, 3, 5 );
            $publishing_days = ! empty( $settings['publishing_days'] ) ? $settings['publishing_days'] : $config_days;

            // Cluster grouping
            $clusters = array();
            foreach ( $all_themes as $slug => $theme ) {
                $cl = $theme['cluster'] ?? 0;
                $cl_label = $theme['cluster_label'] ?? 'Cluster ' . $cl;
                if ( ! isset( $clusters[ $cl ] ) ) {
                    $clusters[ $cl ] = array( 'label' => $cl_label, 'themes' => array() );
                }
                $clusters[ $cl ]['themes'][ $slug ] = $theme;
            }
            ksort( $clusters );

            // Schedule info
            $sched_info = class_exists( 'DBA_Comfisc_Scheduler' )
                ? DBA_Comfisc_Scheduler::get_schedule_info( $lang, $config )
                : array( 'next_run' => 'Scheduler non chargé', 'frequency' => '—', 'posts_per_run' => 1 );

            // Coverage stats
            $prefix = '_dba_comfisc_' . $lang . '_';
            $total_published = 0;
            $themes_written = array();
            try {
                $cov_q = new WP_Query( array(
                    'post_type'      => 'post',
                    'post_status'    => 'publish',
                    'posts_per_page' => 500,
                    'fields'         => 'ids',
                    'meta_query'     => array( array( 'key' => $prefix . 'auto_created', 'compare' => 'EXISTS' ) ),
                ) );
                $total_published = $cov_q->found_posts;
                if ( $cov_q->posts ) {
                    foreach ( $cov_q->posts as $wp_id ) {
                        $t = get_post_meta( $wp_id, $prefix . 'theme', true );
                        if ( $t ) $themes_written[ $t ] = true;
                    }
                }
                wp_reset_postdata();
            } catch ( Exception $e ) {
                // Silently continue
            }
            $themes_covered = count( $themes_written );
            $themes_total   = count( $all_themes );
            $coverage_pct   = $themes_total > 0 ? round( $themes_covered / $themes_total * 100, 1 ) : 0;

            // Recent posts
            $recent_posts = get_posts( array(
                'post_type'      => 'post',
                'post_status'    => array( 'publish', 'draft', 'pending' ),
                'posts_per_page' => 10,
                'meta_query'     => array( array( 'key' => $prefix . 'auto_created', 'compare' => 'EXISTS' ) ),
                'orderby'        => 'date',
                'order'          => 'DESC',
            ) );

            // Authors
            $authors = get_users( array( 'role__in' => array( 'administrator', 'editor', 'author' ), 'number' => 50 ) );

            // Day names
            $day_map = array( 1 => 'Lundi', 2 => 'Mardi', 3 => 'Mercredi', 4 => 'Jeudi', 5 => 'Vendredi', 6 => 'Samedi', 7 => 'Dimanche' );
        ?>

        <!-- ═══════════════════════════════════════════════════════════
             LANGUAGE CARD
             ═══════════════════════════════════════════════════════════ -->
        <div class="postbox" style="padding:20px;margin-bottom:24px;">

            <!-- Header -->
            <p style="font-size:15px;color:#555;margin-top:0;">
                Articles automatiques comptabilité & fiscalité Luxembourg en français.
                Langue : <strong>FR</strong> | Catégorie : <strong><?php echo esc_html( $saved_cat_name ); ?></strong> | Thèmes : <strong><?php echo $themes_total; ?></strong>
            </p>

            <!-- Status bar -->
            <div style="background:<?php echo $enabled ? '#f0fdf4' : '#fef2f2'; ?>;border-left:4px solid <?php echo $enabled ? '#22c55e' : '#ef4444'; ?>;padding:12px;margin-bottom:16px;">
                <strong>Statut :</strong>
                <?php echo $enabled ? '🟢 ACTIVÉ' : '🔴 DÉSACTIVÉ'; ?>
                &nbsp;|&nbsp; <strong>Planning :</strong> <?php echo esc_html( $sched_info['frequency'] ?? '—' ); ?>
                &nbsp;|&nbsp; <strong>Prochaine exécution :</strong> <?php echo esc_html( $sched_info['next_run'] ?? '—' ); ?>
                <button type="button" class="button dba-comfisc-generate" data-lang="<?php echo esc_attr( $lang ); ?>" style="margin-left:10px;">🚀 Générer maintenant</button>
            </div>

            <!-- Coverage bar -->
            <div style="background:#f0f9ff;border-left:4px solid #3b82f6;padding:12px;margin-bottom:16px;">
                <strong>Couverture :</strong> <?php echo $themes_covered; ?>/<?php echo $themes_total; ?> thèmes traités (<?php echo $coverage_pct; ?>%)
                &nbsp;|&nbsp; <strong>Total publié :</strong> <?php echo $total_published; ?> articles
                &nbsp;|&nbsp; <strong>Articles/exécution :</strong> <?php echo $posts_per_run; ?>
            </div>

            <!-- ══ SETTINGS FORM ══ -->
            <form class="dba-comfisc-form" data-lang="<?php echo esc_attr( $lang ); ?>" method="post" action="" onsubmit="return false;">
                <table class="form-table">
                    <!-- Enable -->
                    <tr>
                        <th>Activer 🟤 Comfisc</th>
                        <td><label><input type="checkbox" name="enabled" value="1" <?php checked( $enabled ); ?>> Activer la génération automatique Comfisc</label></td>
                    </tr>

                    <!-- Publishing Days -->
                    <tr>
                        <th>Jours de publication</th>
                        <td>
                            <?php foreach ( $day_map as $num => $label ) : ?>
                                <label style="margin-right:14px;"><input type="checkbox" name="publishing_days[]" value="<?php echo $num; ?>"
                                    <?php checked( in_array( $num, $publishing_days, false ) ); ?>> <?php echo esc_html( $label ); ?></label>
                            <?php endforeach; ?>
                            <p class="description">Par défaut : Lundi, Mercredi, Vendredi.</p>
                        </td>
                    </tr>

                    <!-- Posts per Run -->
                    <tr>
                        <th>Articles par exécution</th>
                        <td>
                            <input type="number" name="posts_per_run" value="<?php echo esc_attr( $posts_per_run ); ?>" min="1" max="5" style="width:60px;">
                            <p class="description">Nombre d'articles à générer par exécution programmée (1–5).</p>
                        </td>
                    </tr>

                    <!-- Post Status -->
                    <tr>
                        <th>Statut des articles</th>
                        <td>
                            <select name="post_status">
                                <option value="publish" <?php selected( $post_status, 'publish' ); ?>>Publié</option>
                                <option value="draft" <?php selected( $post_status, 'draft' ); ?>>Brouillon</option>
                                <option value="pending" <?php selected( $post_status, 'pending' ); ?>>En attente de relecture</option>
                            </select>
                        </td>
                    </tr>

                    <!-- Author -->
                    <tr>
                        <th>Auteur</th>
                        <td>
                            <select name="author_id">
                                <?php foreach ( $authors as $a ) : ?>
                                    <option value="<?php echo esc_attr( $a->ID ); ?>" <?php selected( $author_id, $a->ID ); ?>>
                                        <?php echo esc_html( $a->display_name ); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                    </tr>

                    <!-- Word Count Range -->
                    <tr>
                        <th>Nombre de mots</th>
                        <td>
                            <input type="number" name="word_count_min" value="<?php echo esc_attr( $word_min ); ?>" min="400" max="2000" style="width:80px;">
                            –
                            <input type="number" name="word_count_max" value="<?php echo esc_attr( $word_max ); ?>" min="600" max="3000" style="width:80px;"> mots
                        </td>
                    </tr>

                    <!-- Category -->
                    <tr>
                        <th>Catégorie principale</th>
                        <td>
                            <select name="category_name">
                                <?php foreach ( $categories_fr as $cat_name ) : ?>
                                    <option value="<?php echo esc_attr( $cat_name ); ?>" <?php selected( $saved_cat_name, $cat_name ); ?>>
                                        <?php echo esc_html( $cat_name ); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <p class="description">« <?php echo esc_html( $default_cat ); ?> » est toujours assignée automatiquement.</p>
                        </td>
                    </tr>

                    <!-- Extra Categories -->
                    <tr>
                        <th>Catégories additionnelles</th>
                        <td>
                            <div style="max-height:160px;overflow-y:auto;border:1px solid #ddd;padding:10px;border-radius:4px;background:#fafafa;">
                                <?php foreach ( $categories_fr as $cat_name ) :
                                    if ( $cat_name === $saved_cat_name ) continue; ?>
                                    <label style="display:block;margin:2px 0;font-size:13px;">
                                        <input type="checkbox" name="extra_categories[]" value="<?php echo esc_attr( $cat_name ); ?>"
                                            <?php checked( in_array( $cat_name, $extra_cats, true ) ); ?>>
                                        <?php echo esc_html( $cat_name ); ?>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        </td>
                    </tr>

                    <!-- Active Themes -->
                    <tr>
                        <th>Thèmes actifs (<?php echo $themes_total; ?>)</th>
                        <td>
                            <div style="max-height:360px;overflow-y:auto;border:1px solid #ddd;padding:10px;border-radius:4px;background:#fafafa;">
                                <label style="display:block;margin-bottom:8px;font-weight:600;">
                                    <input type="checkbox" class="dba-comfisc-select-all"> Tout sélectionner / Tout désélectionner
                                </label>
                                <hr style="margin:6px 0;">
                                <?php foreach ( $clusters as $cl_num => $cl_data ) : ?>
                                    <div style="margin:10px 0 4px;font-weight:700;font-size:13px;color:#374151;">
                                        <?php echo esc_html( $cl_data['label'] ); ?> (<?php echo count( $cl_data['themes'] ); ?>)
                                    </div>
                                    <?php foreach ( $cl_data['themes'] as $slug => $theme ) : ?>
                                        <label style="display:block;margin:2px 0 2px 16px;font-size:13px;">
                                            <input type="checkbox" name="active_themes[]" value="<?php echo esc_attr( $slug ); ?>"
                                                <?php checked( empty( $active_themes ) || in_array( $slug, $active_themes, true ) ); ?>>
                                            <?php echo esc_html( $theme['short_label'] ?? $slug ); ?>
                                        </label>
                                    <?php endforeach; ?>
                                <?php endforeach; ?>
                            </div>
                            <p class="description">Tout coché = alternance des <?php echo $themes_total; ?> thèmes. 4 clusters × 9.</p>
                        </td>
                    </tr>
                </table>

                <!-- ══ CTA SECTION ══ -->
                <h3 style="margin-top:30px;">📢 Appel à l'action (CTA)</h3>
                <table class="form-table">
                    <tr>
                        <th>Texte du CTA</th>
                        <td><textarea name="cta_text" rows="3" style="width:100%;max-width:600px;"><?php echo esc_textarea( $cta_text ); ?></textarea></td>
                    </tr>
                    <tr>
                        <th>Texte du lien CTA</th>
                        <td><input type="text" name="cta_link_text" value="<?php echo esc_attr( $cta_link_text ); ?>" style="width:100%;max-width:400px;"></td>
                    </tr>
                    <tr>
                        <th>URL du lien CTA</th>
                        <td><input type="url" name="cta_link_url" value="<?php echo esc_attr( $cta_link_url ); ?>" style="width:100%;max-width:500px;"></td>
                    </tr>
                    <tr>
                        <th>Désactiver le CTA</th>
                        <td><label><input type="checkbox" name="cta_disabled" value="1" <?php checked( $cta_disabled ); ?>> Ne pas ajouter le bloc CTA aux articles</label></td>
                    </tr>
                </table>

                <!-- Save + Generate -->
                <p style="margin-top:20px;">
                    <button type="submit" class="button button-primary dba-comfisc-save" data-lang="<?php echo esc_attr( $lang ); ?>">💾 Enregistrer</button>
                    <button type="button" class="button dba-comfisc-generate" data-lang="<?php echo esc_attr( $lang ); ?>" style="margin-left:10px;">⚡ Générer maintenant</button>
                    <span class="dba-comfisc-status" data-lang="<?php echo esc_attr( $lang ); ?>" style="margin-left:12px;"></span>
                </p>
            </form>

            <!-- ══ PLAGIARISM DETECTION PANEL ══ -->
            <div style="margin-top:30px;">
                <h3>🛡 Détection de plagiat & Conformité Google</h3>
                <table class="widefat" style="max-width:800px;">
                    <tbody>
                    <tr>
                        <td style="width:30px;">
                            <?php echo class_exists( 'DBA_Plagiarism' ) ? '🟢' : '🟡'; ?>
                        </td>
                        <td>
                            <strong>Détection interne de doublons</strong><br>
                            <?php echo class_exists( 'DBA_Plagiarism' )
                                ? '<span style="color:#166534;">ACTIF — Jaccard shingling (3-gram) contre tous les articles existants. Seuil : 35% = REJET.</span>'
                                : '<span style="color:#9a3412;">NON DISPONIBLE — La classe DBA_Plagiarism n\'est pas chargée.</span>'; ?>
                        </td>
                    </tr>
                    <tr>
                        <td>🟢</td>
                        <td>
                            <strong>Anti-template IA</strong><br>
                            <span style="color:#166534;">ACTIF — Le prompt système ordonne de varier structure, vocabulaire et angle par thème. Relance en cas d'échec.</span>
                        </td>
                    </tr>
                    <tr>
                        <td>🟢</td>
                        <td>
                            <strong>Règles anti-pénalité Google</strong><br>
                            <span style="color:#166534;">ACTIF — Pas de &lt;hr&gt;, pas de &lt;strong&gt; excessif, pas de "Dernière mise à jour", CTA exclu du scoring plagiat.</span>
                        </td>
                    </tr>
                    </tbody>
                </table>
                <p style="font-size:12px;color:#666;margin-top:6px;">
                    Pipeline : Recherche → Génération → Validation (style + structure) → Plagiat (PORTE DURE) → Création post → Kaizen → DALL-E → Anti-Orphan → Publication.
                </p>
            </div>

            <!-- ══ KAIZEN LEARNING ENGINE PANEL ══ -->
            <div style="margin-top:24px;">
                <h3>🧠 Moteur d'apprentissage Kaizen — <?php echo class_exists( 'DBA_Comfisc_Kaizen' ) ? 'ACTIF' : 'NON CHARGÉ'; ?></h3>
                <?php if ( class_exists( 'DBA_Comfisc_Kaizen' ) ) : ?>
                    <?php
                    $overused = array();
                    $corrections_count = 0;
                    try {
                        $overused = DBA_Comfisc_Kaizen::get_overused_transitions( $lang );
                        if ( method_exists( 'DBA_Comfisc_Kaizen', 'detect_corrections' ) ) {
                            $corr = DBA_Comfisc_Kaizen::detect_corrections( $lang );
                            $corrections_count = is_array( $corr ) ? count( $corr ) : 0;
                        }
                    } catch ( Exception $e ) {
                        // Silently continue
                    }
                    ?>
                    <table class="widefat" style="max-width:800px;">
                        <tbody>
                        <tr>
                            <td>📊</td>
                            <td><strong>Articles suivis</strong> — diff tracking actif pour détecter les corrections éditeur</td>
                        </tr>
                        <tr>
                            <td>✏️</td>
                            <td><strong>Corrections éditeur</strong> — <?php echo $corrections_count > 0
                                ? $corrections_count . ' corrections détectées (intégrées dans la prochaine génération)'
                                : 'Aucune correction détectée'; ?></td>
                        </tr>
                        <?php if ( ! empty( $overused ) ) : ?>
                        <tr>
                            <td>⚠️</td>
                            <td>
                                <strong>Transitions suremployées</strong> — blacklistées pour la prochaine génération :<br>
                                <?php foreach ( $overused as $word => $count ) : ?>
                                    <span style="color:#dc2626;">✗ <?php echo esc_html( $word ); ?> (<?php echo $count; ?>× dans les 10 derniers articles)</span>&nbsp;&nbsp;
                                <?php endforeach; ?>
                            </td>
                        </tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                <?php else : ?>
                    <p style="color:#999;">Module Kaizen non chargé.</p>
                <?php endif; ?>
            </div>

            <!-- ══ ANTI-ORPHAN PROTECTION PANEL ══ -->
            <div style="margin-top:24px;">
                <h3>🛡 Protection Anti-Orphan — Maillage interne</h3>
                <?php
                $pillar_id     = intval( get_option( 'dba_comfisc_' . $lang . '_pillar_page_id', 0 ) );
                $ao_audit_next = wp_next_scheduled( 'dba_comfisc_weekly_orphan_audit' );

                // Get orphan stats (defensive)
                $ao_stats = array( 'total' => 0, 'linked' => 0, 'orphan_count' => 0, 'pillar_linked' => 0, 'pillar_orphans' => 0, 'orphans' => array() );
                if ( class_exists( 'DBA_Comfisc_Anti_Orphan' ) ) {
                    try {
                        $ao_stats = DBA_Comfisc_Anti_Orphan::get_orphan_stats( $lang );
                    } catch ( Exception $e ) {}
                }
                $ao_total   = $ao_stats['total'];
                $ao_linked  = $ao_stats['linked'];
                $ao_orphans = $ao_stats['orphan_count'];
                $ao_pillar  = $ao_stats['pillar_linked'];
                $ao_list    = $ao_stats['orphans'];
                ?>

                <!-- Orphan summary bar -->
                <?php if ( $ao_orphans > 0 ) : ?>
                <div style="background:#fef2f2;border-left:4px solid #ef4444;padding:12px;margin-bottom:14px;">
                    <strong>⚠️ <?php echo $ao_orphans; ?> article(s) orphelin(s)</strong> — Google n'indexe pas les articles sans liens internes.
                    Cliquez « Corriger tous les orphelins » pour injecter les cross-links et mettre à jour la page pilier.
                </div>
                <?php elseif ( $ao_total > 0 ) : ?>
                <div style="background:#f0fdf4;border-left:4px solid #22c55e;padding:12px;margin-bottom:14px;">
                    <strong>✅ TOUS LES ARTICLES LIÉS</strong> — <?php echo $ao_total; ?>/<?php echo $ao_total; ?> articles possèdent un bloc « Articles connexes ».
                </div>
                <?php endif; ?>

                <!-- Status table -->
                <table class="widefat" style="max-width:800px;">
                    <tbody>
                    <tr>
                        <td style="width:30px;"><?php echo $pillar_id ? '✅' : '❌'; ?></td>
                        <td>
                            <strong>Page pilier / Hub</strong> —
                            <?php if ( $pillar_id ) : ?>
                                Configurée (#<?php echo $pillar_id; ?>)
                                <a href="<?php echo esc_url( get_edit_post_link( $pillar_id ) ); ?>" target="_blank">Modifier</a>
                                | <?php echo $ao_pillar; ?>/<?php echo $ao_total; ?> articles liés depuis le hub
                            <?php else : ?>
                                Non créée. Ajoutez <code>dba_comfisc_<?php echo $lang; ?>_pillar_page_id</code> dans wp_options.
                            <?php endif; ?>
                        </td>
                    </tr>
                    <tr>
                        <td><?php echo ( $ao_orphans === 0 && $ao_total > 0 ) ? '✅' : '⚠️'; ?></td>
                        <td>
                            <strong>Cross-Links</strong> — <?php echo $ao_linked; ?>/<?php echo $ao_total; ?> articles possèdent le bloc « Articles connexes »
                            <?php if ( $ao_orphans > 0 ) : ?>
                                — <strong style="color:#dc2626;"><?php echo $ao_orphans; ?> orphelin(s) à corriger</strong>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <tr>
                        <td>✅</td>
                        <td><strong>Auto-lien à la publication</strong> — Nouveaux articles auto-liés au pilier + cross-linkés avec les articles connexes</td>
                    </tr>
                    <tr>
                        <td>✅</td>
                        <td><strong>Backlinks automatiques</strong> — À chaque publication, les articles existants reçoivent un backlink vers le nouvel article</td>
                    </tr>
                    <tr>
                        <td>✅</td>
                        <td><strong>Audit hebdomadaire cron</strong> — Prochain : <?php echo $ao_audit_next
                            ? date_i18n( 'Y-m-d H:i', $ao_audit_next + ( get_option( 'gmt_offset', 0 ) * 3600 ) )
                            : 'Non programmé'; ?></td>
                    </tr>
                    </tbody>
                </table>

                <!-- Fix All Orphans button -->
                <p style="margin-top:14px;">
                    <button type="button" class="button button-primary dba-comfisc-fix-orphans" data-lang="<?php echo esc_attr( $lang ); ?>"
                        style="background:#dc2626;border-color:#b91c1c;<?php echo $ao_orphans === 0 ? 'background:#059669;border-color:#047857;' : ''; ?>">
                        🔗 Corriger tous les orphelins (<?php echo $ao_orphans; ?>)
                    </button>
                    <span class="dba-comfisc-orphan-status" data-lang="<?php echo esc_attr( $lang ); ?>" style="margin-left:12px;"></span>
                </p>

                <!-- Orphan posts list -->
                <?php if ( ! empty( $ao_list ) ) : ?>
                <div style="margin-top:12px;">
                    <h4 style="margin-bottom:8px;color:#991b1b;">⚠️ Articles orphelins (<?php echo $ao_orphans; ?> trouvés, max 15 affichés)</h4>
                    <table class="widefat striped" style="max-width:800px;">
                        <thead><tr><th>Date</th><th>Titre</th><th>Thème</th><th>Actions</th></tr></thead>
                        <tbody>
                        <?php foreach ( $ao_list as $orph ) : ?>
                            <tr>
                                <td><code><?php echo esc_html( $orph['date'] ?? '' ); ?></code></td>
                                <td><a href="<?php echo esc_url( get_edit_post_link( $orph['id'] ) ); ?>" target="_blank"><?php echo esc_html( $orph['title'] ); ?></a></td>
                                <td style="font-size:12px;"><?php echo esc_html( $orph['theme'] ?? '' ); ?></td>
                                <td><a href="<?php echo esc_url( get_permalink( $orph['id'] ) ); ?>" target="_blank" class="button button-small">Voir</a></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>
            </div>

            <!-- ══ RECENT POSTS TABLE ══ -->
            <?php if ( ! empty( $recent_posts ) ) : ?>
            <div style="margin-top:24px;">
                <h3>📝 Articles récents (10 derniers)</h3>
                <table class="widefat striped" style="max-width:950px;">
                    <thead>
                        <tr><th>Date</th><th>Titre</th><th>Cluster</th><th>Statut</th><th>Mots</th><th>Actions</th></tr>
                    </thead>
                    <tbody>
                    <?php foreach ( $recent_posts as $p ) :
                        $wc = str_word_count( wp_strip_all_tags( $p->post_content ) );
                        $theme_meta = get_post_meta( $p->ID, $prefix . 'theme', true );
                        $cluster_lbl = '';
                        if ( $theme_meta && isset( $all_themes[ $theme_meta ]['cluster_label'] ) ) {
                            $cluster_lbl = $all_themes[ $theme_meta ]['cluster_label'];
                        }
                    ?>
                        <tr>
                            <td><code><?php echo esc_html( get_the_date( 'Y-m-d', $p ) ); ?></code></td>
                            <td><a href="<?php echo esc_url( get_edit_post_link( $p->ID ) ); ?>" target="_blank"><?php echo esc_html( $p->post_title ); ?></a></td>
                            <td style="font-size:12px;"><?php echo esc_html( $cluster_lbl ); ?></td>
                            <td>
                                <?php
                                $labels = array( 'publish' => 'Publié', 'draft' => 'Brouillon', 'pending' => 'En attente' );
                                $st_color = $p->post_status === 'publish' ? '#166534' : ( $p->post_status === 'draft' ? '#9a3412' : '#666' );
                                echo '<span style="color:' . $st_color . ';font-weight:600;">' . esc_html( $labels[ $p->post_status ] ?? ucfirst( $p->post_status ) ) . '</span>';
                                ?>
                            </td>
                            <td style="text-align:center;"><?php echo number_format( $wc ); ?></td>
                            <td><a href="<?php echo esc_url( get_permalink( $p->ID ) ); ?>" target="_blank" class="button button-small">Voir</a></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php endif; ?>

            <!-- ══ ISOLATION KEYS ══ -->
            <div style="margin-top:24px;">
                <h3>🔒 Clés d'isolation</h3>
                <table class="widefat" style="max-width:600px;font-size:13px;">
                    <tbody>
                        <tr><td style="font-weight:600;">Cron hook</td><td><code>dba_comfisc_<?php echo $lang; ?>_cron</code></td></tr>
                        <tr><td style="font-weight:600;">Settings option</td><td><code>dba_comfisc_<?php echo $lang; ?>_settings</code></td></tr>
                        <tr><td style="font-weight:600;">Post meta prefix</td><td><code>_dba_comfisc_<?php echo $lang; ?>_*</code></td></tr>
                        <tr><td style="font-weight:600;">Progress transient</td><td><code>dba_comfisc_<?php echo $lang; ?>_generation_progress</code></td></tr>
                        <tr><td style="font-weight:600;">Daily lock</td><td><code>dba_comfisc_<?php echo $lang; ?>_ran_YYYY-MM-DD</code></td></tr>
                        <tr><td style="font-weight:600;">Pillar page ID</td><td><code>dba_comfisc_<?php echo $lang; ?>_pillar_page_id</code></td></tr>
                        <tr><td style="font-weight:600;">Timezone</td><td><code>Europe/Luxembourg</code></td></tr>
                    </tbody>
                </table>
            </div>

        </div><!-- .postbox -->
        <?php endforeach; ?>

        </div><!-- .wrap -->

        <!-- ══ JAVASCRIPT ══ -->
        <script>
        jQuery(function($){
            // Save settings
            $('.dba-comfisc-form').on('submit', function(e){
                e.preventDefault();
                var $form = $(this), lang = $form.data('lang');
                var $btn = $form.find('.dba-comfisc-save'), $st = $form.find('.dba-comfisc-status');
                $btn.prop('disabled', true).text('Enregistrement...');
                $st.text('').css('color','');

                var data = {
                    action: 'dba_comfisc_save_settings',
                    nonce: '<?php echo $nonce; ?>',
                    lang: lang,
                    enabled: $form.find('[name="enabled"]').is(':checked') ? 1 : 0,
                    publishing_days: $form.find('[name="publishing_days[]"]:checked').map(function(){ return $(this).val(); }).get(),
                    posts_per_run: $form.find('[name="posts_per_run"]').val(),
                    post_status: $form.find('[name="post_status"]').val(),
                    author_id: $form.find('[name="author_id"]').val(),
                    word_count_min: $form.find('[name="word_count_min"]').val(),
                    word_count_max: $form.find('[name="word_count_max"]').val(),
                    category_name: $form.find('[name="category_name"]').val(),
                    extra_categories: $form.find('[name="extra_categories[]"]:checked').map(function(){ return $(this).val(); }).get(),
                    active_themes: $form.find('[name="active_themes[]"]:checked').map(function(){ return $(this).val(); }).get(),
                    cta_text: $form.find('[name="cta_text"]').val(),
                    cta_link_text: $form.find('[name="cta_link_text"]').val(),
                    cta_link_url: $form.find('[name="cta_link_url"]').val(),
                    cta_disabled: $form.find('[name="cta_disabled"]').is(':checked') ? 1 : 0
                };

                $.post(ajaxurl, data, function(r){
                    $st.text(r.success ? '✅ ' + r.data.message : '❌ ' + (r.data||'Erreur'))
                       .css('color', r.success ? '#166534' : '#dc3232');
                    $btn.prop('disabled', false).text('💾 Enregistrer');
                }).fail(function(){
                    $st.text('❌ Erreur réseau').css('color','#dc3232');
                    $btn.prop('disabled', false).text('💾 Enregistrer');
                });
                return false;
            });

            // Generate Now
            $('.dba-comfisc-generate').on('click', function(){
                var $btn = $(this), lang = $btn.data('lang');
                var $st = $btn.closest('.postbox').find('.dba-comfisc-status');
                if (!confirm('Générer un article Comfisc maintenant ?')) return;
                $btn.prop('disabled', true).text('Génération...');
                $st.text('⏳ Génération en cours... 30–60 secondes.').css('color','#0073aa');

                $.post(ajaxurl, {
                    action: 'dba_comfisc_generate_now',
                    nonce: '<?php echo $nonce; ?>',
                    lang: lang
                }, function(r){
                    if (r.success) {
                        $st.html('✅ ' + r.data.message + ' <a href="' + r.data.edit_url + '" target="_blank">Modifier →</a>').css('color','#166534');
                    } else {
                        $st.text('❌ ' + (r.data || 'Échec')).css('color','#dc3232');
                    }
                    $btn.prop('disabled', false).text('⚡ Générer maintenant');
                }).fail(function(){
                    $st.text('❌ Erreur réseau').css('color','#dc3232');
                    $btn.prop('disabled', false).text('⚡ Générer maintenant');
                });
            });

            // Select All
            $('.dba-comfisc-select-all').on('change', function(){
                $(this).closest('div').find('[name="active_themes[]"]').prop('checked', $(this).is(':checked'));
            });

            // Fix All Orphans
            $('.dba-comfisc-fix-orphans').on('click', function(){
                var $btn  = $(this), lang = $btn.data('lang');
                var $st   = $('.dba-comfisc-orphan-status[data-lang="' + lang + '"]');
                var count = $btn.text().match(/\d+/);

                if (!confirm('Corriger tous les articles orphelins Comfisc (' + lang.toUpperCase() + ') ?\n\nCette opération va :\n• Ajouter le bloc « Articles connexes » aux articles qui en manquent\n• Lier les articles au hub/pilier\n• Injecter des backlinks croisés\n\nContinuer ?')) return;

                $btn.prop('disabled', true).text('🔄 Correction en cours...');
                $st.text('⏳ Analyse et correction de tous les articles... cela peut prendre 30–60 secondes.').css('color','#0073aa');

                $.post(ajaxurl, {
                    action: 'dba_comfisc_fix_orphans',
                    nonce: '<?php echo $nonce; ?>',
                    lang: lang
                }, function(r){
                    if (r.success) {
                        $st.text('✅ ' + r.data.message).css('color','#166534');
                        $btn.text('🔗 Corriger tous les orphelins (' + r.data.orphans_remaining + ')');
                        if (r.data.orphans_remaining === 0) {
                            $btn.css({'background':'#059669','border-color':'#047857'});
                        }
                    } else {
                        $st.text('❌ ' + (r.data || 'Échec de la correction')).css('color','#dc3232');
                    }
                    $btn.prop('disabled', false);
                }).fail(function(){
                    $st.text('❌ Erreur réseau').css('color','#dc3232');
                    $btn.prop('disabled', false).text('🔗 Corriger tous les orphelins');
                });
            });
        });
        </script>
        <?php
    }
}
