<?php
/**
 * LuxStrat Admin Panel — with Theme Manager
 *
 * Settings, theme CRUD (add/edit/delete/reorder), manual triggers, post log.
 * Theme overrides stored in DB via dba_luxstrat_themes filter.
 *
 * @package DamalionBlogAI
 * @subpackage LuxStrat
 */
if ( ! defined( 'ABSPATH' ) ) exit;

class DBA_LuxStrat_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' ), 35 );

        // Settings
        add_action( 'wp_ajax_dba_luxstrat_save_settings',   array( $this, 'ajax_save_settings' ) );
        add_action( 'wp_ajax_dba_luxstrat_manual_run',       array( $this, 'ajax_manual_run' ) );
        add_action( 'wp_ajax_dba_luxstrat_reset_rotation',   array( $this, 'ajax_reset_rotation' ) );

        // Theme CRUD
        add_action( 'wp_ajax_dba_luxstrat_save_theme',       array( $this, 'ajax_save_theme' ) );
        add_action( 'wp_ajax_dba_luxstrat_delete_theme',     array( $this, 'ajax_delete_theme' ) );
        add_action( 'wp_ajax_dba_luxstrat_reorder_themes',   array( $this, 'ajax_reorder_themes' ) );
        add_action( 'wp_ajax_dba_luxstrat_get_theme',        array( $this, 'ajax_get_theme' ) );

        // Kaizen + Anti-Orphan
        add_action( 'wp_ajax_dba_luxstrat_run_orphan_audit',   array( $this, 'ajax_run_orphan_audit' ) );
        add_action( 'wp_ajax_dba_luxstrat_flush_kaizen_cache', array( $this, 'ajax_flush_kaizen_cache' ) );

        // Apply DB overrides to Registry themes
        add_filter( 'dba_luxstrat_themes', array( $this, 'apply_theme_overrides' ), 20 );
    }

    /* ══════════════════════════════════════════════════════════════
     *  AJAX: ORPHAN AUDIT + KAIZEN CACHE FLUSH
     * ══════════════════════════════════════════════════════════════ */

    public function ajax_run_orphan_audit() {
        check_ajax_referer( 'dba_admin_nonce', 'nonce' );
        if ( ! class_exists( 'DBA_LuxStrat_Anti_Orphan' ) ) {
            wp_send_json_error( 'Anti-Orphan class not loaded.' );
        }
        $result = DBA_LuxStrat_Anti_Orphan::audit_all();
        wp_send_json_success( $result );
    }

    public function ajax_flush_kaizen_cache() {
        check_ajax_referer( 'dba_admin_nonce', 'nonce' );
        if ( ! class_exists( 'DBA_LuxStrat_Kaizen' ) ) {
            wp_send_json_error( 'Kaizen class not loaded.' );
        }
        DBA_LuxStrat_Kaizen::invalidate_cache();
        wp_send_json_success( 'Cache flushed.' );
    }

    /* ══════════════════════════════════════════════════════════════
     *  THEME DB OVERLAY — merges custom themes + edits + ordering
     * ══════════════════════════════════════════════════════════════ */

    /**
     * Filter callback: merges DB overrides into hardcoded Registry themes.
     */
    public function apply_theme_overrides( $themes ) {
        // 1. Apply edits to existing themes
        $overrides = get_option( 'dba_luxstrat_theme_overrides', array() );
        foreach ( $overrides as $slug => $edits ) {
            if ( isset( $themes[ $slug ] ) ) {
                $themes[ $slug ] = array_merge( $themes[ $slug ], $edits );
            }
        }

        // 2. Add custom themes
        $custom = get_option( 'dba_luxstrat_custom_themes', array() );
        foreach ( $custom as $slug => $config ) {
            $themes[ $slug ] = $config;
        }

        // 3. Remove deleted themes
        $deleted = get_option( 'dba_luxstrat_deleted_themes', array() );
        foreach ( $deleted as $slug ) {
            unset( $themes[ $slug ] );
        }

        // 4. Apply ordering
        $order = get_option( 'dba_luxstrat_theme_order', array() );
        if ( ! empty( $order ) ) {
            $ordered = array();
            foreach ( $order as $slug ) {
                if ( isset( $themes[ $slug ] ) ) {
                    $ordered[ $slug ] = $themes[ $slug ];
                }
            }
            // Append any themes not in order list
            foreach ( $themes as $slug => $cfg ) {
                if ( ! isset( $ordered[ $slug ] ) ) {
                    $ordered[ $slug ] = $cfg;
                }
            }
            $themes = $ordered;
        }

        return $themes;
    }

    /**
     * Check if a theme is custom (DB-added) vs hardcoded (Registry).
     */
    private function is_custom_theme( $slug ) {
        $custom = get_option( 'dba_luxstrat_custom_themes', array() );
        return isset( $custom[ $slug ] );
    }

    public function register_menu() {
        add_submenu_page( 'dba-settings', 'LuxStrat — Luxembourg Structuring', '🏦 LuxStrat',
            'manage_options', 'dba-luxstrat', array( $this, 'render_page' ) );
    }

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

    public function render_page() {
        if ( ! current_user_can( 'manage_options' ) ) wp_die( 'Access denied.' );

        $settings      = get_option( 'dba_luxstrat_settings', array() );
        $all_themes    = DBA_LuxStrat_Registry::get_themes();
        $active_themes = ! empty( $settings['active_themes'] ) ? $settings['active_themes'] : array_keys( $all_themes );
        $last_theme    = get_option( 'dba_luxstrat_last_theme', '(none)' );
        $schedule_info = DBA_LuxStrat_Scheduler::get_schedule_info();
        $custom_themes = get_option( 'dba_luxstrat_custom_themes', array() );
        $deleted_themes = get_option( 'dba_luxstrat_deleted_themes', array() );

        $recent_posts = new WP_Query( array(
            'post_type' => 'post', 'post_status' => 'any', 'posts_per_page' => 20,
            'orderby' => 'date', 'order' => 'DESC',
            'meta_query' => array( array( 'key' => '_dba_luxstrat_auto_created', 'compare' => 'EXISTS' ) ),
        ) );

        ?>
        <div class="wrap">
            <h1 style="display:flex;align-items:center;gap:10px;">
                <span style="font-size:28px;">🏦</span> LuxStrat — Luxembourg Structuring Module
            </h1>
            <p style="font-size:14px;color:#555;max-width:800px;">
                Automated weekly publication of authoritative Luxembourg structuring articles.
                <strong>1 post every Sunday at 05:00 (Luxembourg time)</strong> — rotating through active themes.
            </p>

            <!-- ═══ STATUS CARDS ═══ -->
            <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:16px;margin:20px 0;">
                <div style="background:#fff;border:1px solid #ddd;border-radius:8px;padding:20px;">
                    <h3 style="margin:0 0 8px;font-size:14px;color:#666;">Module Status</h3>
                    <span style="display:inline-block;padding:4px 12px;border-radius:20px;font-size:13px;font-weight:600;
                        background:<?php echo ! empty( $settings['enabled'] ) ? '#dcfce7' : '#fee2e2'; ?>;
                        color:<?php echo ! empty( $settings['enabled'] ) ? '#166534' : '#991b1b'; ?>;">
                        <?php echo ! empty( $settings['enabled'] ) ? '● ACTIVE' : '○ DISABLED'; ?>
                    </span>
                </div>
                <div style="background:#fff;border:1px solid #ddd;border-radius:8px;padding:20px;">
                    <h3 style="margin:0 0 8px;font-size:14px;color:#666;">Schedule</h3>
                    <strong style="font-size:13px;"><?php echo esc_html( $schedule_info['frequency'] ); ?></strong>
                    <br><span style="font-size:12px;color:#888;">Cron: <?php echo $schedule_info['cron_active'] ? '✅ Active' : '❌ Inactive'; ?></span>
                </div>
                <div style="background:#fff;border:1px solid #ddd;border-radius:8px;padding:20px;">
                    <h3 style="margin:0 0 8px;font-size:14px;color:#666;">Next Run</h3>
                    <span style="font-size:13px;"><?php echo esc_html( $schedule_info['next_run'] ); ?></span>
                </div>
                <div style="background:#fff;border:1px solid #ddd;border-radius:8px;padding:20px;">
                    <h3 style="margin:0 0 8px;font-size:14px;color:#666;">Themes</h3>
                    <span style="font-size:20px;font-weight:bold;color:#2563eb;"><?php echo count( $all_themes ); ?></span>
                    <span style="font-size:12px;color:#888;"> active (<?php echo count( $custom_themes ); ?> custom)</span>
                </div>
                <div style="background:#fff;border:1px solid #ddd;border-radius:8px;padding:20px;">
                    <h3 style="margin:0 0 8px;font-size:14px;color:#666;">Last Theme</h3>
                    <span style="font-size:13px;font-weight:600;"><?php echo esc_html( $last_theme ); ?></span>
                </div>
            </div>

            <!-- ═══ THEME MANAGER ═══ -->
            <div style="background:#fff;border:1px solid #ddd;border-radius:8px;padding:24px;margin:20px 0;">
                <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;">
                    <h2 style="margin:0;">📚 Theme Manager</h2>
                    <div>
                        <button class="button" id="lux-theme-save-order" style="margin-right:8px;" title="Save current drag order">💾 Save Order</button>
                        <button class="button button-primary" id="lux-theme-add-new">➕ Add New Theme</button>
                    </div>
                </div>
                <p style="color:#666;font-size:12px;margin:0 0 12px;">Drag rows to reorder priority. First theme = highest priority in rotation. Custom themes can be fully edited/deleted. Hardcoded themes can be edited (overrides stored in DB).</p>

                <table class="widefat striped" id="lux-theme-table" style="font-size:13px;">
                    <thead>
                        <tr>
                            <th style="width:30px">⇕</th>
                            <th style="width:40px">#</th>
                            <th>Theme</th>
                            <th>Slug</th>
                            <th>Keywords</th>
                            <th>H2 Blueprint</th>
                            <th>Type</th>
                            <th style="width:50px">Active</th>
                            <th style="width:130px">Actions</th>
                        </tr>
                    </thead>
                    <tbody id="lux-theme-tbody">
                    <?php $i = 1; foreach ( $all_themes as $slug => $config ) :
                        $is_custom = isset( $custom_themes[ $slug ] );
                        $is_active = in_array( $slug, $active_themes, true );
                        $kw_count  = count( $config['keywords'] ?? array() );
                        $h2_count  = count( $config['h2_blueprint'] ?? array() );
                    ?>
                    <tr data-slug="<?php echo esc_attr( $slug ); ?>" style="cursor:grab;">
                        <td style="color:#999;cursor:grab;">☰</td>
                        <td><?php echo $i++; ?></td>
                        <td>
                            <span style="display:inline-block;width:12px;height:12px;border-radius:3px;background:<?php echo esc_attr( $config['color'] ?? '#666' ); ?>;vertical-align:middle;margin-right:6px;"></span>
                            <strong><?php echo esc_html( $config['short_label'] ?? $config['label'] ?? $slug ); ?></strong>
                            <br><span style="font-size:11px;color:#888;"><?php echo esc_html( mb_substr( $config['description'] ?? '', 0, 80 ) ); ?></span>
                        </td>
                        <td><code style="font-size:11px;"><?php echo esc_html( $slug ); ?></code></td>
                        <td style="text-align:center"><?php echo $kw_count; ?></td>
                        <td style="text-align:center"><?php echo $h2_count; ?></td>
                        <td>
                            <?php if ( $is_custom ) : ?>
                            <span style="background:#dbeafe;color:#1e40af;padding:2px 8px;border-radius:3px;font-size:11px;font-weight:600;">Custom</span>
                            <?php else : ?>
                            <span style="background:#f3f4f6;color:#666;padding:2px 8px;border-radius:3px;font-size:11px;">Built-in</span>
                            <?php endif; ?>
                        </td>
                        <td style="text-align:center">
                            <span style="color:<?php echo $is_active ? '#059669' : '#dc2626'; ?>;font-size:16px;"><?php echo $is_active ? '●' : '○'; ?></span>
                        </td>
                        <td style="white-space:nowrap;">
                            <button class="button button-small lux-theme-edit" data-slug="<?php echo esc_attr( $slug ); ?>" title="Edit theme">✏️</button>
                            <?php if ( $is_custom ) : ?>
                            <button class="button button-small lux-theme-delete" data-slug="<?php echo esc_attr( $slug ); ?>" title="Delete theme" style="color:#dc2626;">🗑️</button>
                            <?php else : ?>
                            <button class="button button-small lux-theme-disable" data-slug="<?php echo esc_attr( $slug ); ?>" title="Disable built-in theme" style="color:#f59e0b;">⊘</button>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>

                <?php if ( ! empty( $deleted_themes ) ) : ?>
                <details style="margin-top:12px;">
                    <summary style="cursor:pointer;font-size:12px;color:#888;">🗑️ Disabled themes (<?php echo count( $deleted_themes ); ?>)</summary>
                    <div style="margin:8px 0;font-size:12px;">
                        <?php foreach ( $deleted_themes as $ds ) : ?>
                        <span style="display:inline-block;background:#fef2f2;padding:2px 8px;border-radius:3px;margin:2px;">
                            <?php echo esc_html( $ds ); ?>
                            <button class="lux-theme-restore" data-slug="<?php echo esc_attr( $ds ); ?>" style="border:none;background:none;color:#2563eb;cursor:pointer;font-size:11px;text-decoration:underline;">restore</button>
                        </span>
                        <?php endforeach; ?>
                    </div>
                </details>
                <?php endif; ?>
            </div>

            <!-- ═══ THEME EDITOR MODAL ═══ -->
            <div id="lux-theme-modal" style="display:none;position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,.5);z-index:99999;overflow-y:auto;">
                <div style="max-width:800px;margin:40px auto;background:#fff;border-radius:12px;padding:28px;box-shadow:0 20px 60px rgba(0,0,0,.3);">
                    <h3 id="lux-modal-title" style="margin:0 0 16px;">Edit Theme</h3>
                    <input type="hidden" id="lux-te-original-slug" value="">

                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
                        <div>
                            <label style="font-size:12px;font-weight:600;">Slug (unique ID)</label>
                            <input type="text" id="lux-te-slug" style="width:100%;" placeholder="e.g., securitization_vehicle">
                        </div>
                        <div>
                            <label style="font-size:12px;font-weight:600;">Color</label>
                            <input type="color" id="lux-te-color" value="#2563eb" style="width:60px;height:32px;"> <span id="lux-te-color-hex" style="font-size:11px;color:#888;">#2563eb</span>
                        </div>
                        <div style="grid-column:1/-1;">
                            <label style="font-size:12px;font-weight:600;">Label (full name)</label>
                            <input type="text" id="lux-te-label" style="width:100%;" placeholder="e.g., Luxembourg Securitization Vehicles">
                        </div>
                        <div>
                            <label style="font-size:12px;font-weight:600;">Short Label</label>
                            <input type="text" id="lux-te-short-label" style="width:100%;" placeholder="e.g., Securitization">
                        </div>
                        <div>
                            <label style="font-size:12px;font-weight:600;">Categories EN (comma-separated slugs)</label>
                            <input type="text" id="lux-te-cats-en" style="width:100%;" placeholder="private-equity, investment-funds">
                        </div>
                        <div style="grid-column:1/-1;">
                            <label style="font-size:12px;font-weight:600;">Description</label>
                            <textarea id="lux-te-description" rows="2" style="width:100%;" placeholder="Brief description of what this theme covers..."></textarea>
                        </div>
                        <div style="grid-column:1/-1;">
                            <label style="font-size:12px;font-weight:600;">Keywords (one per line)</label>
                            <textarea id="lux-te-keywords" rows="4" style="width:100%;font-family:monospace;font-size:12px;" placeholder="securitization vehicle&#10;SPV Luxembourg&#10;special purpose vehicle&#10;SV Law 2004"></textarea>
                        </div>
                        <div style="grid-column:1/-1;">
                            <label style="font-size:12px;font-weight:600;">H2 Blueprint (one heading per line — used as article structure)</label>
                            <textarea id="lux-te-h2" rows="5" style="width:100%;font-family:monospace;font-size:12px;" placeholder="What Is a Luxembourg Securitization Vehicle?&#10;Legal Framework and the 2004 Law&#10;Tax Treatment and Exemptions&#10;Eligible Assets and Structures"></textarea>
                        </div>
                        <div style="grid-column:1/-1;">
                            <label style="font-size:12px;font-weight:600;">Pillar URLs (one per line — existing pages to link to)</label>
                            <textarea id="lux-te-pillars" rows="3" style="width:100%;font-family:monospace;font-size:12px;" placeholder="https://www.damalion.com/securitization-vehicle/&#10;https://www.damalion.com/investment-funds/"></textarea>
                        </div>
                    </div>

                    <div style="margin-top:16px;display:flex;justify-content:space-between;">
                        <button class="button" onclick="document.getElementById('lux-theme-modal').style.display='none'">Cancel</button>
                        <button class="button button-primary" id="lux-te-save">💾 Save Theme</button>
                    </div>
                </div>
            </div>

            <!-- ═══ SETTINGS FORM ═══ -->
            <div style="background:#fff;border:1px solid #ddd;border-radius:8px;padding:24px;margin:20px 0;max-width:900px;">
                <h2 style="margin-top:0;">⚙️ Settings</h2>
                <form id="dba-luxstrat-settings-form">
                    <?php wp_nonce_field( 'dba_admin_nonce', 'dba_luxstrat_nonce' ); ?>
                    <table class="form-table">
                        <tr>
                            <th scope="row">Enable Module</th>
                            <td><label><input type="checkbox" name="luxstrat_enabled" value="1" <?php checked( ! empty( $settings['enabled'] ) ); ?>> Enable weekly LuxStrat article generation</label></td>
                        </tr>
                        <tr>
                            <th scope="row">Active Themes</th>
                            <td>
                                <?php foreach ( $all_themes as $slug => $config ) : ?>
                                <label style="display:block;margin-bottom:8px;">
                                    <input type="checkbox" name="luxstrat_themes[]" value="<?php echo esc_attr( $slug ); ?>" <?php checked( in_array( $slug, $active_themes, true ) ); ?>>
                                    <span style="display:inline-block;width:12px;height:12px;border-radius:3px;background:<?php echo esc_attr( $config['color'] ?? '#666' ); ?>;margin:0 6px;vertical-align:middle;"></span>
                                    <?php echo esc_html( $config['label'] ?? $slug ); ?>
                                </label>
                                <?php endforeach; ?>
                                <p class="description">Themes rotate weekly. Theme order set in Theme Manager above.</p>
                            </td>
                        </tr>
                        <tr><th>Post Status</th><td>
                            <select name="luxstrat_post_status">
                                <option value="publish" <?php selected( ( $settings['post_status'] ?? 'publish' ), 'publish' ); ?>>Publish immediately</option>
                                <option value="draft" <?php selected( ( $settings['post_status'] ?? '' ), 'draft' ); ?>>Save as Draft</option>
                                <option value="pending" <?php selected( ( $settings['post_status'] ?? '' ), 'pending' ); ?>>Pending Review</option>
                            </select>
                        </td></tr>
                        <tr><th>Author</th><td><?php wp_dropdown_users( array( 'name' => 'luxstrat_author_id', 'selected' => ! empty( $settings['author_id'] ) ? $settings['author_id'] : 1, 'role__in' => array( 'administrator', 'editor', 'author' ) ) ); ?></td></tr>
                        <tr><th>Category</th><td><?php wp_dropdown_categories( array( 'name' => 'luxstrat_category_id', 'selected' => ! empty( $settings['category_id'] ) ? $settings['category_id'] : 0, 'show_option_none' => '— No category —', 'option_none_value' => '0', 'hide_empty' => false, 'hierarchical' => true ) ); ?></td></tr>
                        <tr><th>Word Count</th><td>
                            <input type="number" name="luxstrat_word_count_min" value="<?php echo esc_attr( $settings['word_count_min'] ?? 1000 ); ?>" min="500" max="3000" style="width:100px;"> to
                            <input type="number" name="luxstrat_word_count_max" value="<?php echo esc_attr( $settings['word_count_max'] ?? 1800 ); ?>" min="800" max="5000" style="width:100px;"> words
                        </td></tr>
                        <tr><th>WPML Language</th><td><input type="text" name="luxstrat_wpml_language" value="<?php echo esc_attr( $settings['wpml_language'] ?? 'en' ); ?>" style="width:80px;"></td></tr>
                        <tr><th>CTA Text</th><td><textarea name="luxstrat_cta_text" rows="2" style="width:100%;max-width:600px;"><?php echo esc_textarea( $settings['cta_text'] ?? 'Damalion supports institutional investors, fund managers, and family offices with compliant Luxembourg structuring solutions.' ); ?></textarea></td></tr>
                        <tr><th>CTA Link</th><td>
                            <input type="text" name="luxstrat_cta_link_text" value="<?php echo esc_attr( $settings['cta_link_text'] ?? 'Contact your Damalion experts now.' ); ?>" style="width:300px;" placeholder="Link text">
                            <input type="url" name="luxstrat_cta_link_url" value="<?php echo esc_attr( $settings['cta_link_url'] ?? 'https://www.damalion.com/lets-connect/' ); ?>" style="width:350px;" placeholder="https://...">
                        </td></tr>
                    </table>
                    <p><button type="submit" class="button button-primary" id="dba-luxstrat-save">💾 Save Settings</button></p>
                </form>
                <div id="dba-luxstrat-save-result" style="margin-top:10px;"></div>
            </div>

            <!-- ═══ ACTIONS ═══ -->
            <div style="background:#fff;border:1px solid #ddd;border-radius:8px;padding:24px;margin:20px 0;max-width:900px;">
                <h2 style="margin-top:0;">🚀 Actions</h2>
                <p>
                    <button class="button button-secondary" id="dba-luxstrat-run-now" style="margin-right:10px;">▶ Generate Now (Manual Run)</button>
                    <button class="button" id="dba-luxstrat-reset-rotation">🔄 Reset Theme Rotation</button>
                </p>
                <div id="dba-luxstrat-action-result" style="margin-top:10px;"></div>
            </div>

            <!-- ═══ RECENT POSTS ═══ -->
            <div style="background:#fff;border:1px solid #ddd;border-radius:8px;padding:24px;margin:20px 0;">
                <h2 style="margin-top:0;">📋 Recent LuxStrat Posts</h2>
                <?php if ( $recent_posts->have_posts() ) : ?>
                <table class="widefat striped" style="margin-top:10px;">
                    <thead><tr><th>ID</th><th>Title</th><th>Theme</th><th>Words</th><th>Status</th><th>Date</th></tr></thead>
                    <tbody>
                    <?php while ( $recent_posts->have_posts() ) : $recent_posts->the_post();
                        $pid = get_the_ID();
                        $ts  = get_post_meta( $pid, '_dba_luxstrat_theme', true );
                        $tl  = get_post_meta( $pid, '_dba_luxstrat_theme_label', true );
                        $wc  = get_post_meta( $pid, '_dba_luxstrat_word_count', true );
                        $ps  = get_post_status( $pid );
                        $tc  = DBA_LuxStrat_Registry::get_theme( $ts );
                    ?>
                    <tr>
                        <td><a href="<?php echo get_edit_post_link( $pid ); ?>">#<?php echo $pid; ?></a></td>
                        <td><a href="<?php the_permalink(); ?>" target="_blank"><?php the_title(); ?></a></td>
                        <td><?php if ($tc) : ?><span style="background:<?php echo esc_attr($tc['color']??'#666');?>;color:#fff;padding:2px 8px;border-radius:4px;font-size:11px;"><?php echo esc_html($tl?:$ts);?></span><?php else: echo esc_html($ts); endif;?></td>
                        <td><?php echo esc_html($wc?:'—');?></td>
                        <td><span style="padding:2px 8px;border-radius:4px;font-size:11px;background:<?php echo $ps==='publish'?'#dcfce7':'#fef9c3';?>;color:<?php echo $ps==='publish'?'#166534':'#854d0e';?>;"><?php echo ucfirst($ps);?></span></td>
                        <td><?php echo get_the_date('j M Y H:i');?></td>
                    </tr>
                    <?php endwhile; wp_reset_postdata(); ?>
                    </tbody>
                </table>
                <?php else : ?>
                <p style="color:#888;text-align:center;padding:30px;">No LuxStrat posts generated yet.</p>
                <?php endif; ?>
            </div>

            <!-- ══════════════════════════════════════════════════════════════ -->
            <!--  🧠 KAIZEN LEARNING ENGINE                                   -->
            <!-- ══════════════════════════════════════════════════════════════ -->
            <?php
            $kz_loaded = class_exists( 'DBA_LuxStrat_Kaizen' );
            ?>
            <div style="background:<?php echo $kz_loaded ? '#faf5ff' : '#fef2f2'; ?>;border:1px solid <?php echo $kz_loaded ? '#d8b4fe' : '#fca5a5'; ?>;border-left:4px solid <?php echo $kz_loaded ? '#9333ea' : '#dc2626'; ?>;border-radius:6px;padding:18px 22px;margin-top:20px;max-width:1000px;">
                <h2 style="margin-top:0;color:<?php echo $kz_loaded ? '#6b21a8' : '#991b1b'; ?>;">🧠 Kaizen Learning Engine — <?php
                    if ( ! $kz_loaded ) {
                        echo '<span style="color:#991b1b;">NOT LOADED</span> <span style="font-size:12px;font-weight:normal;">— Upload class-luxstrat-kaizen.php &amp; require it</span>';
                    } else {
                        echo '<span style="color:#6b21a8;">ACTIVE ✓</span>';
                    }
                ?></h2>
                <?php if ( $kz_loaded ) : ?>
                <table class="widefat" style="border:none;background:transparent;">
                    <?php
                    // Scan recent posts for corrections
                    $kz_corrections = DBA_LuxStrat_Kaizen::detect_corrections();
                    $kz_overused    = DBA_LuxStrat_Kaizen::get_overused_transitions();
                    ?>
                    <tr>
                        <td style="padding:8px 6px;width:250px;"><strong><?php echo !empty($kz_corrections) ? '🔍' : '✅'; ?> Editor Corrections</strong></td>
                        <td style="padding:8px 6px;"><?php echo count($kz_corrections); ?> corrections detected in last 14 days
                            <?php foreach (array_slice($kz_corrections, 0, 3) as $co) : ?>
                                <br><span style="font-size:11px;color:#666;">• <?php echo esc_html(strtoupper(str_replace('_',' ',$co['type']))) . ' [' . esc_html($co['theme']) . ']: ' . esc_html($co['detail']); ?></span>
                            <?php endforeach; ?>
                        </td>
                    </tr>
                    <tr>
                        <td style="padding:8px 6px;"><strong><?php echo !empty($kz_overused) ? '⚠️' : '✅'; ?> Overused Transitions</strong></td>
                        <td style="padding:8px 6px;"><?php echo !empty($kz_overused) ? '✗ ' . esc_html(implode(', ', $kz_overused)) : 'None — vocabulary is varied ✓'; ?></td>
                    </tr>
                    <tr>
                        <td style="padding:8px 6px;"><strong>🔄 Cache</strong></td>
                        <td style="padding:8px 6px;">
                            <button type="button" id="dba-luxstrat-flush-kaizen" class="button button-small" style="margin-right:8px;">Flush Kaizen Cache</button>
                            <span id="dba-luxstrat-kaizen-status" style="font-size:12px;"></span>
                        </td>
                    </tr>
                </table>
                <?php endif; ?>
            </div>

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

            if ( $ao_loaded ) {
                $ao_stats = DBA_LuxStrat_Anti_Orphan::get_orphan_stats();
                $ao_total        = $ao_stats['total'];
                $ao_linked       = $ao_stats['linked'];
                $ao_auth_linked  = $ao_stats['auth_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_luxstrat_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-luxstrat-related' ) !== false ) $ao_linked++;
                    if ( strpos( $pc, 'dba-luxstrat-auth-link' ) !== false ) $ao_auth_linked++;
                    if ( strpos( $pc, 'dba-luxstrat-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_luxstrat_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-luxstrat-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-Theme 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 themes + authority URLs on creation' : 'NOT ACTIVE — class not loaded'; ?></td>
                    </tr>
                    <tr>
                        <td style="padding:8px 6px;"><strong><?php echo $ao_auth_linked > 0 ? '✅' : '⚠️'; ?> 🏛️ Luxembourg Authority Links</strong></td>
                        <td style="padding:8px 6px;"><?php echo $ao_auth_linked; ?>/<?php echo $ao_total; ?> posts have authority outbound links (CSSF, Guichet.lu, RCS, ACD, Legilux)
                            <?php if ( $ao_total > 0 && $ao_auth_linked < $ao_total ) : ?>
                                — <span style="color:#c2410c;"><?php echo $ao_total - $ao_auth_linked; ?> missing</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 — activates on first run 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; ?>
                </div>
                <?php endif; ?>

                <?php if ( $ao_orphan_count > 0 && $ao_loaded ) : ?>
                <div style="margin-top:10px;">
                    <button type="button" id="dba-luxstrat-run-audit" class="button button-primary button-small">🛡️ Fix All Orphans (<?php echo $ao_orphan_count; ?>)</button>
                    <span id="dba-luxstrat-audit-status" style="font-size:12px;margin-left:8px;"></span>
                </div>
                <?php endif; ?>
            </div>

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

        <script>
        jQuery(function($) {
            var nonce = '<?php echo wp_create_nonce( 'dba_admin_nonce' ); ?>';
            var A = ajaxurl;

            // ── DRAG-TO-REORDER ──
            if (typeof $.fn.sortable !== 'undefined') {
                $('#lux-theme-tbody').sortable({ handle:'td:first-child', axis:'y', opacity:0.7,
                    update: function(){ $('#lux-theme-save-order').css({background:'#2563eb',color:'#fff'}); }
                });
            }

            $('#lux-theme-save-order').on('click', function(){
                var order = [];
                $('#lux-theme-tbody tr').each(function(){ order.push($(this).data('slug')); });
                var btn = $(this).prop('disabled',1).html('⏳');
                $.post(A, {action:'dba_luxstrat_reorder_themes', nonce:nonce, order:order}, function(r){
                    btn.prop('disabled',0).html('💾 Save Order').css({background:'',color:''});
                    if (r.success) { alert('✅ Theme order saved!'); location.reload(); }
                    else alert('Error: '+(r.data||'Unknown'));
                });
            });

            // ── ADD NEW THEME ──
            $('#lux-theme-add-new').on('click', function(){
                $('#lux-modal-title').text('➕ Add New Theme');
                $('#lux-te-original-slug').val('');
                $('#lux-te-slug').val('').prop('disabled',false);
                $('#lux-te-label,#lux-te-short-label,#lux-te-description,#lux-te-keywords,#lux-te-h2,#lux-te-pillars,#lux-te-cats-en').val('');
                $('#lux-te-color').val('#2563eb');
                $('#lux-theme-modal').fadeIn(200);
            });

            // ── EDIT THEME ──
            $(document).on('click', '.lux-theme-edit', function(){
                var slug = $(this).data('slug');
                $('#lux-modal-title').text('✏️ Editing: '+slug);
                $('#lux-te-slug').val(slug).prop('disabled',true); // Can't change slug of existing
                $('#lux-te-original-slug').val(slug);
                // Fetch full theme data
                $.post(A, {action:'dba_luxstrat_get_theme', nonce:nonce, slug:slug}, function(r){
                    if (r.success && r.data) {
                        var t = r.data;
                        $('#lux-te-label').val(t.label||'');
                        $('#lux-te-short-label').val(t.short_label||'');
                        $('#lux-te-description').val(t.description||'');
                        $('#lux-te-color').val(t.color||'#2563eb');
                        $('#lux-te-color-hex').text(t.color||'#2563eb');
                        $('#lux-te-keywords').val((t.keywords||[]).join('\n'));
                        $('#lux-te-h2').val((t.h2_blueprint||[]).join('\n'));
                        $('#lux-te-pillars').val((t.pillar_urls||[]).join('\n'));
                        $('#lux-te-cats-en').val((t.category_slugs_en||[]).join(', '));
                        $('#lux-theme-modal').fadeIn(200);
                    } else {
                        alert('Error loading theme: '+(r.data||'Unknown'));
                    }
                });
            });

            // ── SAVE THEME (add or edit) ──
            $('#lux-te-save').on('click', function(){
                var slug = $('#lux-te-slug').val().trim().toLowerCase().replace(/[^a-z0-9_]/g,'_');
                var originalSlug = $('#lux-te-original-slug').val();
                if (!slug) { alert('Enter a slug.'); return; }
                if (!$('#lux-te-label').val().trim()) { alert('Enter a label.'); return; }

                var data = {
                    action: 'dba_luxstrat_save_theme', nonce: nonce,
                    slug: slug, original_slug: originalSlug,
                    label: $('#lux-te-label').val().trim(),
                    short_label: $('#lux-te-short-label').val().trim(),
                    description: $('#lux-te-description').val().trim(),
                    color: $('#lux-te-color').val(),
                    keywords: $('#lux-te-keywords').val().trim(),
                    h2_blueprint: $('#lux-te-h2').val().trim(),
                    pillar_urls: $('#lux-te-pillars').val().trim(),
                    category_slugs_en: $('#lux-te-cats-en').val().trim()
                };

                var btn = $(this).prop('disabled',1).html('⏳ Saving...');
                $.post(A, data, function(r){
                    btn.prop('disabled',0).html('💾 Save Theme');
                    if (r.success) {
                        $('#lux-theme-modal').hide();
                        alert('✅ Theme "'+slug+'" saved!');
                        location.reload();
                    } else {
                        alert('Error: '+(r.data||'Unknown'));
                    }
                });
            });

            // ── DELETE custom theme ──
            $(document).on('click', '.lux-theme-delete', function(){
                var slug = $(this).data('slug');
                if (!confirm('Permanently delete custom theme "'+slug+'"?')) return;
                $.post(A, {action:'dba_luxstrat_delete_theme', nonce:nonce, slug:slug, hard:1}, function(r){
                    if (r.success) { alert('🗑️ Theme deleted.'); location.reload(); }
                    else alert('Error: '+(r.data||'Unknown'));
                });
            });

            // ── DISABLE built-in theme ──
            $(document).on('click', '.lux-theme-disable', function(){
                var slug = $(this).data('slug');
                if (!confirm('Disable built-in theme "'+slug+'"? You can restore it later.')) return;
                $.post(A, {action:'dba_luxstrat_delete_theme', nonce:nonce, slug:slug, hard:0}, function(r){
                    if (r.success) { alert('⊘ Theme disabled.'); location.reload(); }
                    else alert('Error: '+(r.data||'Unknown'));
                });
            });

            // ── RESTORE disabled theme ──
            $(document).on('click', '.lux-theme-restore', function(){
                var slug = $(this).data('slug');
                $.post(A, {action:'dba_luxstrat_delete_theme', nonce:nonce, slug:slug, restore:1}, function(r){
                    if (r.success) { location.reload(); }
                });
            });

            // ── Color picker hex display ──
            $('#lux-te-color').on('input change', function(){ $('#lux-te-color-hex').text($(this).val()); });

            // ── SAVE SETTINGS ──
            $('#dba-luxstrat-settings-form').on('submit', function(e) {
                e.preventDefault();
                var $btn = $('#dba-luxstrat-save').prop('disabled',1).text('Saving…');
                var themes = [];
                $('input[name="luxstrat_themes[]"]:checked').each(function(){ themes.push($(this).val()); });
                $.post(A, {
                    action:'dba_luxstrat_save_settings', nonce:nonce,
                    enabled:$('input[name="luxstrat_enabled"]').is(':checked')?1:0,
                    active_themes:themes,
                    post_status:$('select[name="luxstrat_post_status"]').val(),
                    author_id:$('select[name="luxstrat_author_id"]').val(),
                    category_id:$('select[name="luxstrat_category_id"]').val(),
                    word_count_min:$('input[name="luxstrat_word_count_min"]').val(),
                    word_count_max:$('input[name="luxstrat_word_count_max"]').val(),
                    wpml_language:$('input[name="luxstrat_wpml_language"]').val(),
                    cta_text:$('textarea[name="luxstrat_cta_text"]').val(),
                    cta_link_text:$('input[name="luxstrat_cta_link_text"]').val(),
                    cta_link_url:$('input[name="luxstrat_cta_link_url"]').val()
                }, function(res) {
                    $btn.prop('disabled',0).text('💾 Save Settings');
                    $('#dba-luxstrat-save-result').html(res.success
                        ? '<div class="notice notice-success inline"><p>✅ Settings saved.</p></div>'
                        : '<div class="notice notice-error inline"><p>❌ '+(res.data||'Error')+'</p></div>');
                });
            });

            // ── Manual run ──
            $('#dba-luxstrat-run-now').on('click', function() {
                if (!confirm('Generate a LuxStrat post now? This will use the next theme in rotation.')) return;
                var $btn = $(this).prop('disabled',1).text('Generating…');
                $('#dba-luxstrat-action-result').html('<div class="notice notice-info inline"><p>⏳ Generating via OpenAI… 30-60 seconds.</p></div>');
                $.ajax({ url:A, type:'POST', timeout:120000,
                    data:{action:'dba_luxstrat_manual_run', nonce:nonce},
                    success:function(res){
                        $btn.prop('disabled',0).text('▶ Generate Now (Manual Run)');
                        if(res.success){var d=res.data;$('#dba-luxstrat-action-result').html('<div class="notice notice-success inline"><p>✅ <a href="'+d.edit_url+'" target="_blank">#'+d.post_id+' — '+d.title+'</a> ('+d.words+' words, theme: '+d.theme+')</p></div>');}
                        else{$('#dba-luxstrat-action-result').html('<div class="notice notice-error inline"><p>❌ '+(res.data||'Unknown error')+'</p></div>');}
                    },
                    error:function(xhr,s,e){$btn.prop('disabled',0).text('▶ Generate Now (Manual Run)');$('#dba-luxstrat-action-result').html('<div class="notice notice-error inline"><p>❌ '+s+' — '+e+'</p></div>');}
                });
            });

            // ── Reset rotation ──
            $('#dba-luxstrat-reset-rotation').on('click', function() {
                if (!confirm('Reset rotation?')) return;
                $.post(A, {action:'dba_luxstrat_reset_rotation', nonce:nonce}, function(res){
                    if(res.success) $('#dba-luxstrat-action-result').html('<div class="notice notice-success inline"><p>🔄 Rotation reset.</p></div>');
                });
            });

            // ── Kaizen cache flush ──
            $('#dba-luxstrat-flush-kaizen').on('click', function(){
                var btn=$(this).prop('disabled',1).text('⏳ Flushing...');
                $.post(A, {action:'dba_luxstrat_flush_kaizen_cache', nonce:nonce}, function(r){
                    btn.prop('disabled',0).text('Flush Kaizen Cache');
                    $('#dba-luxstrat-kaizen-status').html(r.success ? '<span style="color:#166534;">✓ Cache flushed</span>' : '<span style="color:#991b1b;">✕ '+r.data+'</span>');
                }).fail(function(){ btn.prop('disabled',0).text('Flush Kaizen Cache'); $('#dba-luxstrat-kaizen-status').html('<span style="color:#991b1b;">✕ Request failed</span>'); });
            });

            // ── Anti-Orphan audit ──
            $('#dba-luxstrat-run-audit').on('click', function(){
                var btn=$(this).prop('disabled',1).text('🛡️ Fixing...');
                $.post(A, {action:'dba_luxstrat_run_orphan_audit', nonce:nonce}, function(r){
                    btn.prop('disabled',0).text('🛡️ Done');
                    if (r.success) {
                        var d=r.data;
                        $('#dba-luxstrat-audit-status').html('<span style="color:#166534;">✓ Fixed '+d.fixed+'/'+d.orphaned+' orphans ('+d.total+' total)</span>');
                        if (d.fixed > 0) setTimeout(function(){ location.reload(); }, 2000);
                    } else {
                        $('#dba-luxstrat-audit-status').html('<span style="color:#991b1b;">✕ '+(r.data||'Error')+'</span>');
                    }
                }).fail(function(){ btn.prop('disabled',0).text('🛡️ Fix All Orphans'); $('#dba-luxstrat-audit-status').html('<span style="color:#991b1b;">✕ Request failed</span>'); });
            });
        });
        </script>
        <?php
    }

    /* ══════════════════════════════════════════════════════════════
     *  AJAX: Theme CRUD
     * ══════════════════════════════════════════════════════════════ */

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

        $slug = sanitize_key( $_POST['slug'] ?? '' );
        if ( ! $slug ) wp_send_json_error( 'No slug.' );

        $theme = DBA_LuxStrat_Registry::get_theme( $slug );
        if ( ! $theme ) wp_send_json_error( 'Theme not found.' );

        wp_send_json_success( $theme );
    }

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

        $slug          = sanitize_key( $_POST['slug'] ?? '' );
        $original_slug = sanitize_key( $_POST['original_slug'] ?? '' );
        if ( ! $slug ) wp_send_json_error( 'Slug is required.' );

        // Parse arrays from newline-separated text
        $keywords    = array_filter( array_map( 'trim', explode( "\n", $_POST['keywords'] ?? '' ) ) );
        $h2_blueprint = array_filter( array_map( 'trim', explode( "\n", $_POST['h2_blueprint'] ?? '' ) ) );
        $pillar_urls = array_filter( array_map( 'trim', explode( "\n", $_POST['pillar_urls'] ?? '' ) ) );
        $cats_en     = array_filter( array_map( 'trim', explode( ',', $_POST['category_slugs_en'] ?? '' ) ) );

        $theme_data = array(
            'label'              => sanitize_text_field( $_POST['label'] ?? '' ),
            'short_label'        => sanitize_text_field( $_POST['short_label'] ?? '' ),
            'description'        => sanitize_textarea_field( $_POST['description'] ?? '' ),
            'color'              => sanitize_hex_color( $_POST['color'] ?? '#2563eb' ) ?: '#2563eb',
            'keywords'           => array_map( 'sanitize_text_field', $keywords ),
            'h2_blueprint'       => array_map( 'sanitize_text_field', $h2_blueprint ),
            'pillar_urls'        => array_map( 'esc_url_raw', $pillar_urls ),
            'category_slugs_en'  => array_map( 'sanitize_key', $cats_en ),
        );

        // Is this a new theme or editing existing?
        $is_new = empty( $original_slug );
        $custom  = get_option( 'dba_luxstrat_custom_themes', array() );

        if ( $is_new ) {
            // Check for slug collision
            $existing = DBA_LuxStrat_Registry::get_theme( $slug );
            if ( $existing && ! isset( $custom[ $slug ] ) ) {
                wp_send_json_error( 'Slug "' . $slug . '" already exists as a built-in theme. Choose a different slug.' );
            }
            // Store as custom theme
            $custom[ $slug ] = $theme_data;
            update_option( 'dba_luxstrat_custom_themes', $custom, false );

            // Also add to active themes
            $settings = get_option( 'dba_luxstrat_settings', array() );
            if ( ! isset( $settings['active_themes'] ) ) {
                $settings['active_themes'] = array_keys( DBA_LuxStrat_Registry::get_themes() );
            }
            $settings['active_themes'][] = $slug;
            update_option( 'dba_luxstrat_settings', $settings );

            error_log( 'DBA LuxStrat: Added custom theme "' . $slug . '"' );
        } else {
            // Editing existing theme
            if ( isset( $custom[ $original_slug ] ) ) {
                // It's a custom theme — update directly
                $custom[ $original_slug ] = $theme_data;
                update_option( 'dba_luxstrat_custom_themes', $custom, false );
            } else {
                // It's a built-in theme — store override
                $overrides = get_option( 'dba_luxstrat_theme_overrides', array() );
                $overrides[ $original_slug ] = $theme_data;
                update_option( 'dba_luxstrat_theme_overrides', $overrides, false );
            }
            error_log( 'DBA LuxStrat: Updated theme "' . $original_slug . '"' );
        }

        wp_send_json_success( 'Saved.' );
    }

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

        $slug    = sanitize_key( $_POST['slug'] ?? '' );
        $hard    = ! empty( $_POST['hard'] );
        $restore = ! empty( $_POST['restore'] );

        if ( ! $slug ) wp_send_json_error( 'No slug.' );

        if ( $restore ) {
            // Restore disabled theme
            $deleted = get_option( 'dba_luxstrat_deleted_themes', array() );
            $deleted = array_diff( $deleted, array( $slug ) );
            update_option( 'dba_luxstrat_deleted_themes', array_values( $deleted ), false );
            wp_send_json_success( 'Restored.' );
        }

        if ( $hard ) {
            // Hard delete = remove custom theme entirely
            $custom = get_option( 'dba_luxstrat_custom_themes', array() );
            unset( $custom[ $slug ] );
            update_option( 'dba_luxstrat_custom_themes', $custom, false );

            // Also remove any overrides
            $overrides = get_option( 'dba_luxstrat_theme_overrides', array() );
            unset( $overrides[ $slug ] );
            update_option( 'dba_luxstrat_theme_overrides', $overrides, false );

            error_log( 'DBA LuxStrat: Deleted custom theme "' . $slug . '"' );
        } else {
            // Soft delete = disable built-in theme
            $deleted = get_option( 'dba_luxstrat_deleted_themes', array() );
            if ( ! in_array( $slug, $deleted ) ) {
                $deleted[] = $slug;
                update_option( 'dba_luxstrat_deleted_themes', $deleted, false );
            }
            error_log( 'DBA LuxStrat: Disabled built-in theme "' . $slug . '"' );
        }

        // Remove from active themes
        $settings = get_option( 'dba_luxstrat_settings', array() );
        if ( ! empty( $settings['active_themes'] ) ) {
            $settings['active_themes'] = array_diff( $settings['active_themes'], array( $slug ) );
            update_option( 'dba_luxstrat_settings', $settings );
        }

        wp_send_json_success( 'Done.' );
    }

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

        $order = isset( $_POST['order'] ) && is_array( $_POST['order'] ) ? array_map( 'sanitize_key', $_POST['order'] ) : array();
        if ( empty( $order ) ) wp_send_json_error( 'No order provided.' );

        update_option( 'dba_luxstrat_theme_order', $order, false );
        error_log( 'DBA LuxStrat: Theme order updated — ' . implode( ', ', $order ) );
        wp_send_json_success( 'Order saved.' );
    }

    /* ══════════════════════════════════════════════════════════════
     *  AJAX: Settings + Actions (unchanged)
     * ══════════════════════════════════════════════════════════════ */

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

        $settings = array(
            'enabled'        => ! empty( $_POST['enabled'] ),
            'active_themes'  => isset( $_POST['active_themes'] ) && is_array( $_POST['active_themes'] ) ? array_map( 'sanitize_key', $_POST['active_themes'] ) : array(),
            'post_status'    => sanitize_key( $_POST['post_status'] ?? 'publish' ),
            'author_id'      => absint( $_POST['author_id'] ?? 1 ),
            'category_id'    => absint( $_POST['category_id'] ?? 0 ),
            'word_count_min' => max( 500, absint( $_POST['word_count_min'] ?? 1000 ) ),
            'word_count_max' => max( 800, absint( $_POST['word_count_max'] ?? 1800 ) ),
            'wpml_language'  => sanitize_text_field( $_POST['wpml_language'] ?? 'en' ),
            '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'] ?? '' ),
        );

        update_option( 'dba_luxstrat_settings', $settings );
        if ( $settings['enabled'] ) DBA_LuxStrat_Scheduler::activate();

        wp_send_json_success( 'Saved.' );
    }

    public function ajax_manual_run() {
        check_ajax_referer( 'dba_admin_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( 'Permission denied.' );

        $scheduler = DBA_LuxStrat_Scheduler::get_instance();
        $result    = $scheduler->manual_run();
        if ( is_wp_error( $result ) ) wp_send_json_error( $result->get_error_message() );

        $result['edit_url'] = get_edit_post_link( $result['post_id'], 'raw' );
        wp_send_json_success( $result );
    }

    public function ajax_reset_rotation() {
        check_ajax_referer( 'dba_admin_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( 'Permission denied.' );

        delete_option( 'dba_luxstrat_last_theme' );
        wp_send_json_success( 'Rotation reset.' );
    }
}
