<?php
/**
 * DBA Admin - Settings page, dashboard, and log viewer
 */
class DBA_Admin {

    private static $instance = null;

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

    private function __construct() {
        add_action('admin_menu', array($this, 'add_menu'));
        add_action('admin_init', array($this, 'register_settings'));

        // Auto-refresh sitemap AFTER content settings are saved (safe — runs after DB write)
        add_action('update_option_dba_content_settings', array($this, 'on_content_settings_saved'), 10, 2);

        // Quick Unpublish — row action in Posts list
        add_filter('post_row_actions', array($this, 'add_unpublish_row_action'), 10, 2);

        // Quick Unpublish — handle the action
        add_action('admin_init', array($this, 'handle_quick_unpublish'));

        // DBA metabox on Edit Post screen
        add_action('add_meta_boxes', array($this, 'add_dba_metabox'));
    }

    /**
     * After content settings saved — refresh sitemap in background
     */
    public function on_content_settings_saved($old, $new) {
        if (!empty($new['sitemap_url'])) {
            // Schedule a one-time refresh (non-blocking)
            wp_schedule_single_event(time() + 5, 'dba_daily_sitemap_refresh');
        }
    }

    /**
     * Add "⚡ Unpublish" link to post row actions for DBA-created posts
     */
    public function add_unpublish_row_action($actions, $post) {
        if ($post->post_status !== 'publish') return $actions;
        if (!get_post_meta($post->ID, '_dba_auto_created', true)) return $actions;

        $url = wp_nonce_url(
            admin_url('admin.php?action=dba_unpublish&post_id=' . $post->ID),
            'dba_unpublish_' . $post->ID
        );

        $actions['dba_unpublish'] = sprintf(
            '<a href="%s" style="color:#d63638;font-weight:bold;" onclick="return confirm(\'Unpublish this post immediately?\')">⚡ Unpublish</a>',
            esc_url($url)
        );

        return $actions;
    }

    /**
     * Handle quick unpublish action
     */
    public function handle_quick_unpublish() {
        if (!isset($_GET['action']) || $_GET['action'] !== 'dba_unpublish') return;
        if (!isset($_GET['post_id'])) return;

        $post_id = intval($_GET['post_id']);
        check_admin_referer('dba_unpublish_' . $post_id);

        if (!current_user_can('edit_post', $post_id)) {
            wp_die('Permission denied');
        }

        wp_update_post(array(
            'ID'          => $post_id,
            'post_status' => 'draft',
        ));

        wp_redirect(admin_url('edit.php?dba_unpublished=1'));
        exit;
    }

    /**
     * Add DBA info metabox on Edit Post screen
     */
    public function add_dba_metabox() {
        add_meta_box(
            'dba_post_info',
            '🏛️ Damalion Blog AI',
            array($this, 'render_dba_metabox'),
            'post',
            'side',
            'high'
        );
    }

    /**
     * Render DBA metabox — shows quick actions and post info
     */
    public function render_dba_metabox($post) {
        $is_dba = get_post_meta($post->ID, '_dba_auto_created', true);

        if (!$is_dba) {
            echo '<p style="color:#666;">Not a DBA-generated post.</p>';
            return;
        }

        $theme = get_post_meta($post->ID, '_dba_theme', true);
        $subject = get_post_meta($post->ID, '_dba_subject', true);
        $plag_score = get_post_meta($post->ID, '_dba_plagiarism_score', true);
        $created = get_post_meta($post->ID, '_dba_auto_created', true);

        echo '<div style="margin-bottom:12px;">';
        echo '<strong>Created:</strong> ' . esc_html($created) . '<br>';
        if ($theme) echo '<strong>Theme:</strong> ' . esc_html($theme) . '<br>';
        if ($subject) echo '<strong>Subject:</strong> ' . esc_html($subject) . '<br>';
        if ($plag_score) echo '<strong>Uniqueness:</strong> ' . intval($plag_score) . '%<br>';
        echo '</div>';

        // Unpublish button
        if ($post->post_status === 'publish') {
            $url = wp_nonce_url(
                admin_url('admin.php?action=dba_unpublish&post_id=' . $post->ID),
                'dba_unpublish_' . $post->ID
            );
            echo '<a href="' . esc_url($url) . '" class="button" style="color:#d63638;border-color:#d63638;" onclick="return confirm(\'Unpublish this post?\')">⚡ Unpublish Now</a>';
        }

        // Edit tip
        echo '<p style="color:#666;margin-top:10px;font-size:12px;">To edit content: click <strong>Code</strong> tab (top-right of editor area). Visual tab may appear blank due to Divi.</p>';
    }

    public function add_menu() {
        add_menu_page(
            'Damalion Blog AI',
            'Damalion Blog AI',
            'manage_options',
            'dba-settings',
            array($this, 'render_settings_page'),
            'dashicons-edit-page',
            30
        );

        add_submenu_page(
            'dba-settings',
            'Generation Logs',
            'Logs',
            'manage_options',
            'dba-logs',
            array($this, 'render_logs_page')
        );
    }

    public function register_settings() {
        register_setting('dba_settings_group', 'dba_settings', array($this, 'sanitize_settings'));
        register_setting('dba_settings_group', 'dba_schedule_settings', array($this, 'sanitize_schedule'));
        register_setting('dba_settings_group', 'dba_content_settings', array($this, 'sanitize_content'));
    }

    public function sanitize_settings($input) {
        $clean = array();
        $clean['openai_api_key'] = sanitize_text_field($input['openai_api_key'] ?? '');
        $model_val = sanitize_text_field($input['openai_model'] ?? 'gpt-4.1');
        if ($model_val === 'custom' && !empty($input['openai_model_custom'])) {
            $model_val = sanitize_text_field($input['openai_model_custom']);
        }
        $clean['openai_model'] = $model_val;
        $clean['image_model'] = sanitize_text_field($input['image_model'] ?? 'dall-e-3');
        $clean['posts_per_run'] = max(1, min(10, intval($input['posts_per_run'] ?? 5)));
        $clean['post_status'] = in_array($input['post_status'] ?? '', array('draft','publish','future')) ? $input['post_status'] : 'publish';
        $clean['image_size'] = sanitize_text_field($input['image_size'] ?? '950x762');
        $clean['copyscape_user'] = sanitize_text_field($input['copyscape_user'] ?? '');
        $clean['copyscape_key'] = sanitize_text_field($input['copyscape_key'] ?? '');
        $clean['google_search_key'] = sanitize_text_field($input['google_search_key'] ?? '');
        $clean['google_search_cx'] = sanitize_text_field($input['google_search_cx'] ?? '');
        $clean['bing_search_key'] = sanitize_text_field($input['bing_search_key'] ?? '');
        return $clean;
    }

    public function sanitize_schedule($input) {
        $clean = array();
        $clean['enabled'] = !empty($input['enabled']);

        $valid_days = array('monday','tuesday','wednesday','thursday','friday','saturday','sunday');
        $clean['posting_days'] = array();
        if (isset($input['posting_days']) && is_array($input['posting_days'])) {
            foreach ($input['posting_days'] as $day) {
                if (in_array(strtolower($day), $valid_days)) {
                    $clean['posting_days'][] = strtolower($day);
                }
            }
        }

        $clean['posting_times'] = array();
        if (isset($input['posting_times']) && is_string($input['posting_times'])) {
            $times = array_map('trim', explode(',', $input['posting_times']));
            foreach ($times as $t) {
                if (preg_match('/^\d{2}:\d{2}$/', $t)) {
                    $clean['posting_times'][] = $t;
                }
            }
        }

        $clean['timezone'] = sanitize_text_field($input['timezone'] ?? 'Europe/Luxembourg');

        // Reschedule cron if enabled
        if ($clean['enabled']) {
            DBA_Scheduler::deactivate();
            DBA_Scheduler::activate();
        }

        return $clean;
    }

    public function sanitize_content($input) {
        $clean = array();

        // Subjects schedule: "Subject | Mon,Wed,Fri" per line
        $clean['subjects_schedule'] = sanitize_textarea_field($input['subjects_schedule'] ?? '');
        $clean['subjects'] = array();
        $clean['subject_days'] = array(); // maps subject => array of day abbreviations

        if (!empty($clean['subjects_schedule'])) {
            $lines = explode("\n", $clean['subjects_schedule']);
            foreach ($lines as $line) {
                $line = trim($line);
                if (empty($line)) continue;

                $parts = array_map('trim', explode('|', $line, 2));
                $subject_name = sanitize_text_field($parts[0]);
                if (empty($subject_name)) continue;

                $clean['subjects'][] = $subject_name;

                // Parse days
                $days = array();
                if (isset($parts[1]) && !empty($parts[1])) {
                    $day_parts = array_map('trim', explode(',', strtolower($parts[1])));
                    $valid_days = array('mon','tue','wed','thu','fri','sat','sun');
                    foreach ($day_parts as $d) {
                        if (in_array($d, $valid_days)) {
                            $days[] = $d;
                        }
                    }
                }
                // Empty days = post every day
                $clean['subject_days'][$subject_name] = $days;
            }
        }
        if (empty($clean['subjects'])) $clean['subjects'] = array('Luxembourg holding company');

        // Keep old fields for backward compat
        $clean['subjects_text'] = implode("\n", $clean['subjects']);

        $clean['languages'] = array();
        if (isset($input['languages']) && is_array($input['languages'])) {
            foreach ($input['languages'] as $l) {
                $clean['languages'][] = sanitize_text_field($l);
            }
        }
        if (empty($clean['languages'])) $clean['languages'] = array('en');

        $clean['pillar_url'] = esc_url_raw($input['pillar_url'] ?? 'https://www.damalion.com/blog/');
        $clean['cta_html'] = wp_kses_post($input['cta_html'] ?? '');
        $clean['sitemap_url'] = esc_url_raw($input['sitemap_url'] ?? 'https://www.damalion.com/sitemap.xml');

        // News fields — preserve on save
        $clean['news_url']          = esc_url_raw($input['news_url'] ?? '');
        $clean['news_headline']     = sanitize_text_field($input['news_headline'] ?? '');
        $clean['news_mode']         = in_array(($input['news_mode'] ?? 'next_only'), array('next_only', 'persistent')) ? ($input['news_mode'] ?? 'next_only') : 'next_only';
        $clean['news_cta_override'] = wp_kses_post($input['news_cta_override'] ?? '');

        // Image dimensions
        $clean['image_width'] = max(200, min(2048, intval($input['image_width'] ?? 950)));
        $clean['image_height'] = max(200, min(2048, intval($input['image_height'] ?? 762)));

        // Banned words
        $clean['banned_words'] = array();
        if (!empty($input['banned_words_raw'])) {
            $lines = explode("\n", $input['banned_words_raw']);
            foreach ($lines as $line) {
                $word = strtolower(trim(sanitize_text_field($line)));
                if (!empty($word)) {
                    $clean['banned_words'][] = $word;
                }
            }
            $clean['banned_words'] = array_unique($clean['banned_words']);
        }

        return $clean;
    }

    /**
     * Render main settings page
     */
    public function render_settings_page() {
        if (!current_user_can('manage_options')) return;

        $settings = get_option('dba_settings', array());
        $schedule = get_option('dba_schedule_settings', array());
        $content = get_option('dba_content_settings', array());
        $last_run = get_option('dba_last_run', array());
        $registry = get_option('dba_link_registry', array());
        $sitemap_instance = DBA_Sitemap::get_instance();
        $scan_meta_full = $sitemap_instance->get_scan_meta();
        // For sidebar preview: only load primary language, not all 35k pages
        $primary_lang = ($content['languages'] ?? array('en'))[0] ?? 'en';
        $full_registry = $sitemap_instance->get_full_registry($primary_lang);

        $logger = DBA_Logger::get_instance();
        $today_count = $logger->get_today_count();

        ?>
        <div class="wrap">
            <h1>🏛️ Damalion Blog AI</h1>

            <!-- Status Banner -->
            <div class="dba-banner">
                <h2>Automated Blog Post Generation</h2>
                <p>
                    📝 <strong>Posts today:</strong> <?php echo $today_count; ?>/<?php echo $settings['posts_per_run'] ?? 5; ?> &nbsp;|&nbsp;
                    📅 <strong>Posting days:</strong> <?php echo DBA_Scheduler::get_posting_days_string(); ?> &nbsp;|&nbsp;
                    ⏰ <strong>Next run:</strong> <?php echo DBA_Scheduler::get_next_run_info(); ?> &nbsp;|&nbsp;
                    🔗 <strong>Registry:</strong> <?php echo intval($scan_meta_full['total_pages'] ?? 0); ?> pages (<?php echo count($scan_meta_full['languages'] ?? array()); ?> languages)
                    <?php
                    $scan_meta_info = DBA_Sitemap::get_instance()->get_scan_meta();
                    if (!empty($scan_meta_full['last_scan'])):
                    ?> (<?php echo esc_html(human_time_diff(strtotime($scan_meta_full['last_scan']), current_time('timestamp'))); ?> ago)<?php
                    else:
                    ?> — <span style="color:#d32f2f;">needs initial scan</span><?php
                    endif;
                    ?>
                </p>
            </div>

            <?php if (!empty($last_run)): ?>
            <div class="dba-notice dba-notice-info">
                <strong>Last run:</strong> <?php echo esc_html($last_run['time'] ?? 'Unknown'); ?>
                <?php if (isset($last_run['results'])): ?>
                — Created: <?php echo intval($last_run['results']['created'] ?? 0); ?>,
                Failed: <?php echo intval($last_run['results']['failed'] ?? 0); ?>
                <?php endif; ?>
            </div>
            <?php endif; ?>

            <!-- Quick Actions -->
            <div class="dba-actions">
                <h3>⚡ Quick Actions</h3>
                <button id="dba-test-openai" class="button button-secondary">🔌 Test OpenAI</button>
                <button id="dba-scan-pages" class="button button-secondary" style="background:#1e88e5;border-color:#1565c0;color:#fff;">🔍 Scan Internal Pages</button>
                <button id="dba-refresh-sitemap" class="button button-secondary">🔄 Refresh Sitemap</button>
                <button id="dba-check-plagiarism" class="button button-secondary">🔍 Check Plagiarism</button>
                <button id="dba-generate-single" class="button button-primary">📝 Generate 1 Post</button>
                <button id="dba-generate-batch" class="button button-primary" style="background:#28a745;border-color:#28a745;">🚀 Run Daily Batch</button>
                <div id="dba-action-result" class="dba-result" style="display:none;"></div>

                <!-- Scan Progress Bar -->
                <div id="dba-scan-progress" style="display:none; margin-top:12px; padding:15px; background:#f0f7ff; border:1px solid #c2dbf4; border-radius:6px;">
                    <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:8px;">
                        <strong id="dba-scan-label" style="color:#1565c0;">🔍 Scanning internal pages…</strong>
                        <span id="dba-scan-count" style="font-size:13px; color:#555;">0 / 0</span>
                    </div>
                    <div style="width:100%; height:22px; background:#e3edf7; border-radius:11px; overflow:hidden; position:relative;">
                        <div id="dba-scan-bar" style="height:100%; width:0%; background:linear-gradient(90deg, #1e88e5, #42a5f5); border-radius:11px; transition:width 0.3s ease;"></div>
                    </div>
                    <div id="dba-scan-details" style="margin-top:8px; font-size:12px; color:#666;"></div>
                </div>
            </div>

            <script>
            (function(){
                var btn = document.getElementById('dba-scan-pages');
                if (!btn) return;

                btn.addEventListener('click', function(){
                    btn.disabled = true;
                    btn.textContent = '⏳ Starting scan…';

                    var progressBox = document.getElementById('dba-scan-progress');
                    var scanBar     = document.getElementById('dba-scan-bar');
                    var scanCount   = document.getElementById('dba-scan-count');
                    var scanLabel   = document.getElementById('dba-scan-label');
                    var scanDetails = document.getElementById('dba-scan-details');

                    progressBox.style.display = 'block';
                    scanBar.style.width = '0%';
                    scanCount.textContent = '0 / 0';
                    scanLabel.textContent = '🔍 Scanning internal pages…';
                    scanDetails.textContent = 'Starting scan…';

                    // Step 1: Start scan
                    jQuery.post(dba_admin.ajaxurl, {
                        action: 'dba_scan_pages_start',
                        nonce: dba_admin.nonce
                    }, function(res) {
                        if (!res.success) {
                            scanLabel.textContent = '❌ Scan failed to start';
                            btn.disabled = false;
                            btn.textContent = '🔍 Scan Internal Pages';
                            return;
                        }

                        var total = res.data.total;
                        scanCount.textContent = '0 / ' + total;
                        scanDetails.textContent = 'Scanning posts and pages: reading titles, categories, tags, Yoast keyphrases…';

                        // Step 2: Process batches with auto-retry
                        var retries = 0;
                        var maxRetries = 3;

                        function processBatch() {
                            jQuery.ajax({
                                url: dba_admin.ajaxurl,
                                type: 'POST',
                                timeout: 60000,
                                data: {
                                    action: 'dba_scan_pages_batch',
                                    nonce: dba_admin.nonce
                                },
                                success: function(batchRes) {
                                retries = 0; // reset on success

                                if (!batchRes.success) {
                                    scanLabel.textContent = '❌ Scan error';
                                    btn.disabled = false;
                                    btn.textContent = '🔍 Scan Internal Pages';
                                    return;
                                }

                                var d = batchRes.data;
                                var pct = total > 0 ? Math.min(100, Math.round((d.processed / total) * 100)) : 100;
                                scanBar.style.width = pct + '%';
                                scanCount.textContent = d.processed + ' / ' + total;

                                if (d.done) {
                                    scanBar.style.background = 'linear-gradient(90deg, #2e7d32, #66bb6a)';
                                    scanLabel.textContent = '✅ Scan complete!';
                                    scanCount.textContent = d.processed + ' pages scanned';
                                    scanDetails.textContent = 'Registry updated with real titles, categories, tags, and Yoast keyphrases. Links will now use accurate data.';
                                    btn.disabled = false;
                                    btn.textContent = '🔍 Scan Internal Pages';

                                    var regCount = document.getElementById('dba-registry-count');
                                    if (regCount) regCount.textContent = d.processed;
                                } else {
                                    if (d.phase === 'finalizing') {
                                        scanLabel.textContent = '⚙️ Merging results by language…';
                                        scanBar.style.background = 'linear-gradient(90deg, #f57c00, #ffb74d)';
                                        scanBar.style.width = '100%';
                                    }
                                    setTimeout(processBatch, 50);
                                }
                                },
                                error: function(){
                                retries++;
                                if (retries <= maxRetries) {
                                    scanDetails.textContent = 'Network hiccup — retrying (' + retries + '/' + maxRetries + ')…';
                                    setTimeout(processBatch, 2000 * retries);
                                } else {
                                    scanLabel.textContent = '❌ Network error after ' + maxRetries + ' retries';
                                    scanDetails.textContent = 'Click "Scan Internal Pages" to resume from where it stopped.';
                                    btn.disabled = false;
                                    btn.textContent = '🔍 Scan Internal Pages';
                                }
                                }
                            });
                        }

                        processBatch();
                    }).fail(function(){
                        scanLabel.textContent = '❌ Network error';
                        btn.disabled = false;
                        btn.textContent = '🔍 Scan Internal Pages';
                    });
                });
            })();
            </script>

            <div class="dba-settings-grid">
                <div class="dba-settings-main">
                    <form method="post" action="options.php">
                        <?php settings_fields('dba_settings_group'); ?>

                        <!-- OpenAI Settings -->
                        <div class="dba-section">
                            <h3>🤖 OpenAI Configuration</h3>
                            <table class="form-table">
                                <tr>
                                    <th>API Key</th>
                                    <td><input type="password" name="dba_settings[openai_api_key]" value="<?php echo esc_attr($settings['openai_api_key'] ?? ''); ?>" class="regular-text" autocomplete="off" /></td>
                                </tr>
                                <tr>
                                    <th>Text Model</th>
                                    <td>
                                        <select name="dba_settings[openai_model]" id="dba-model-select">
                                            <?php
                                            $models = array(
                                                'gpt-4.1' => 'GPT-4.1 (recommended)',
                                                'gpt-4.1-mini' => 'GPT-4.1 Mini (fast/cheap)',
                                                'gpt-4.1-nano' => 'GPT-4.1 Nano (fastest)',
                                                'gpt-4o' => 'GPT-4o',
                                                'gpt-4o-mini' => 'GPT-4o Mini',
                                                'o3' => 'o3 (reasoning)',
                                                'o3-mini' => 'o3-mini (reasoning/cheap)',
                                                'o4-mini' => 'o4-mini (reasoning)',
                                                'gpt-5' => 'GPT-5 (when available)',
                                                'custom' => '— Custom model ID —',
                                            );
                                            $current = $settings['openai_model'] ?? 'gpt-4.1';
                                            $is_custom = !array_key_exists($current, $models) || $current === 'custom';
                                            foreach ($models as $val => $label): ?>
                                            <option value="<?php echo esc_attr($val); ?>" <?php selected($is_custom && $val === 'custom' ? 'custom' : $current, $val); ?>><?php echo esc_html($label); ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                        <input type="text" name="dba_settings[openai_model_custom]" id="dba-model-custom"
                                            value="<?php echo esc_attr($is_custom ? $current : ''); ?>"
                                            placeholder="e.g. gpt-5-turbo, ft:gpt-4o:my-org:custom"
                                            style="margin-top:6px;<?php echo $is_custom ? '' : 'display:none;'; ?>" />
                                        <script>
                                        document.getElementById('dba-model-select').addEventListener('change', function() {
                                            document.getElementById('dba-model-custom').style.display = this.value === 'custom' ? '' : 'none';
                                        });
                                        </script>
                                    </td>
                                </tr>
                                <tr>
                                    <th>Image Model</th>
                                    <td>
                                        <select name="dba_settings[image_model]">
                                            <option value="gpt-image-1" <?php selected($settings['image_model'] ?? 'dall-e-3', 'gpt-image-1'); ?>>GPT Image 1 (newest)</option>
                                            <option value="dall-e-3" <?php selected($settings['image_model'] ?? 'dall-e-3', 'dall-e-3'); ?>>DALL-E 3</option>
                                            <option value="dall-e-2" <?php selected($settings['image_model'] ?? '', 'dall-e-2'); ?>>DALL-E 2</option>
                                        </select>
                                    </td>
                                </tr>
                                <tr>
                                    <th>Posts per Run</th>
                                    <td><input type="number" name="dba_settings[posts_per_run]" value="<?php echo intval($settings['posts_per_run'] ?? 5); ?>" min="1" max="10" /></td>
                                </tr>
                                <tr>
                                    <th>Default Status</th>
                                    <td>
                                        <select name="dba_settings[post_status]">
                                            <option value="draft" <?php selected($settings['post_status'] ?? 'publish', 'draft'); ?>>Draft</option>
                                            <option value="publish" <?php selected($settings['post_status'] ?? 'publish', 'publish'); ?>>Publish</option>
                                            <option value="future" <?php selected($settings['post_status'] ?? '', 'future'); ?>>Scheduled (Future)</option>
                                        </select>
                                    </td>
                                </tr>
                                <tr>
                                    <th>Image Size</th>
                                    <td><input type="text" name="dba_settings[image_size]" value="<?php echo esc_attr($settings['image_size'] ?? '950x762'); ?>" class="small-text" /> (width×height px)</td>
                                </tr>
                            </table>
                        </div>

                        <!-- Schedule Settings -->
                        <div class="dba-section">
                            <h3>🛡️ Plagiarism Detection</h3>
                            <p class="description" style="margin-bottom:12px;">Content is always checked against your existing posts (free, built-in). For external web checking, configure one of the optional APIs below.</p>
                            <table class="form-table">
                                <tr>
                                    <th>Copyscape Username</th>
                                    <td><input type="text" name="dba_settings[copyscape_user]" value="<?php echo esc_attr($settings['copyscape_user'] ?? ''); ?>" class="regular-text" placeholder="Optional — premium API" /></td>
                                </tr>
                                <tr>
                                    <th>Copyscape API Key</th>
                                    <td><input type="password" name="dba_settings[copyscape_key]" value="<?php echo esc_attr($settings['copyscape_key'] ?? ''); ?>" class="regular-text" autocomplete="off" /></td>
                                </tr>
                                <tr>
                                    <th>Google Search API Key</th>
                                    <td><input type="password" name="dba_settings[google_search_key]" value="<?php echo esc_attr($settings['google_search_key'] ?? ''); ?>" class="regular-text" autocomplete="off" placeholder="Optional — free tier: 100 queries/day" /></td>
                                </tr>
                                <tr>
                                    <th>Google Search CX ID</th>
                                    <td><input type="text" name="dba_settings[google_search_cx]" value="<?php echo esc_attr($settings['google_search_cx'] ?? ''); ?>" class="regular-text" placeholder="Custom Search Engine ID" /></td>
                                </tr>
                                <tr>
                                    <th>Minimum Uniqueness</th>
                                    <td><code>85%</code> — Posts below this score are rejected and regenerated.</td>
                                </tr>
                            </table>
                        </div>

                        <!-- Schedule Settings -->
                        <div class="dba-section">
                            <h3>📅 Scheduling</h3>
                            <table class="form-table">
                                <tr>
                                    <th>Enable Auto-Generation</th>
                                    <td><label><input type="checkbox" name="dba_schedule_settings[enabled]" value="1" <?php checked($schedule['enabled'] ?? false); ?> /> Run automatically on posting days</label></td>
                                </tr>
                                <tr>
                                    <th>Posting Days</th>
                                    <td>
                                        <?php
                                        $all_days = array('monday','tuesday','wednesday','thursday','friday','saturday','sunday');
                                        $active_days = $schedule['posting_days'] ?? array('monday','wednesday','saturday');
                                        foreach ($all_days as $day): ?>
                                        <label style="display:inline-block;margin-right:12px;">
                                            <input type="checkbox" name="dba_schedule_settings[posting_days][]" value="<?php echo $day; ?>" <?php checked(in_array($day, $active_days)); ?> />
                                            <?php echo ucfirst($day); ?>
                                        </label>
                                        <?php endforeach; ?>
                                    </td>
                                </tr>
                                <tr>
                                    <th>Posting Times</th>
                                    <td>
                                        <input type="text" name="dba_schedule_settings[posting_times]" value="<?php echo esc_attr(implode(', ', $schedule['posting_times'] ?? array('09:10','11:20','13:30','15:40','17:50'))); ?>" class="regular-text" />
                                        <p class="description">Comma-separated, 24h format (HH:MM). One time per post.</p>
                                    </td>
                                </tr>
                                <tr>
                                    <th>Timezone</th>
                                    <td><input type="text" name="dba_schedule_settings[timezone]" value="<?php echo esc_attr($schedule['timezone'] ?? 'Europe/Luxembourg'); ?>" class="regular-text" /></td>
                                </tr>
                            </table>
                        </div>

                        <!-- Content Settings -->
                        <div class="dba-section">
                            <h3>📄 Content Configuration</h3>
                            <table class="form-table">
                                <tr>
                                    <th>📰 News Source URL</th>
                                    <td>
                                        <div style="display:flex; gap:8px; align-items:flex-start;">
                                            <input type="url" name="dba_content_settings[news_url]" id="dba-news-url" value="<?php echo esc_url($content['news_url'] ?? ''); ?>" class="large-text" placeholder="https://www.reuters.com/business/finance/..." style="flex:1;" />
                                            <button type="button" id="dba-extract-headline" class="button button-secondary" title="Fetch headline from URL and auto-fill fields below" style="white-space:nowrap;">🔍 Extract</button>
                                        </div>
                                        <p class="description">Paste a news article URL. Click <strong>Extract</strong> to auto-fill headline & subject from the page.<br>
                                        <strong>Tip:</strong> Works best with standard news sites (Reuters, Bloomberg, Financial Times, etc.).</p>
                                    </td>
                                </tr>
                                <tr>
                                    <th>📰 News Headline</th>
                                    <td>
                                        <input type="text" name="dba_content_settings[news_headline]" id="dba-news-headline" value="<?php echo esc_attr($content['news_headline'] ?? ''); ?>" class="large-text" placeholder="EU approves new ELTIF 2.0 regulation for cross-border fund distribution" />
                                        <p class="description">Enter a news headline or topic. <span style="color:green;">🔍 The plugin uses <strong>OpenAI web search</strong> (Responses API) to research live web sources — no Bing API needed.</span><br>
                                        You can use <strong>URL only</strong>, <strong>headline only</strong>, or <strong>both</strong> (URL = primary source, headline = supplementary search).</p>
                                    </td>
                                </tr>
                                <tr>
                                    <th>📰 News Mode</th>
                                    <td>
                                        <select name="dba_content_settings[news_mode]">
                                            <option value="next_only" <?php selected($content['news_mode'] ?? 'next_only', 'next_only'); ?>>Use for next post only (auto-clear after generation)</option>
                                            <option value="persistent" <?php selected($content['news_mode'] ?? 'next_only', 'persistent'); ?>>Keep for all posts until manually cleared</option>
                                        </select>
                                        <p class="description"><strong>Next only:</strong> After 1 post is generated, the news fields are automatically cleared.<br>
                                        <strong>Persistent:</strong> Every post uses this news source until you manually clear the fields.</p>
                                    </td>
                                </tr>
                                <tr>
                                    <th>📰 News CTA Override</th>
                                    <td>
                                        <textarea name="dba_content_settings[news_cta_override]" id="dba-news-cta-override" rows="4" class="large-text code" placeholder="<p>Damalion helps investors navigate data center investments across Europe. <a href=&quot;https://www.damalion.com/lets-connect&quot;>Contact our experts</a>.</p>"><?php echo esc_textarea($content['news_cta_override'] ?? ''); ?></textarea>
                                        <p class="description"><strong>Optional.</strong> When filled, this CTA replaces the global CTA for the news-generated post only.<br>
                                        Use this to tailor the call-to-action to the specific news topic (e.g. link to a relevant Damalion service page).<br>
                                        <strong>Important:</strong> Promote Damalion's <em>services</em> (advisory, structuring, fund setup), not "the blog".<br>
                                        Auto-cleared after generation if News Mode is "next only".</p>
                                    </td>
                                </tr>
                                <tr>
                                    <th>Subjects & Schedule</th>
                                    <td>
                                        <textarea name="dba_content_settings[subjects_schedule]" id="dba-subjects-schedule" rows="10" class="large-text" placeholder="One subject per line. Format: Subject | Days&#10;&#10;Examples:&#10;Luxembourg SOPARFI | Mon,Wed,Fri&#10;Private equity fund setup | Tue,Thu,Sat&#10;Crypto custody in Europe | Mon,Tue,Wed,Thu,Fri&#10;Czech company formation | Sat&#10;&#10;Days: Mon,Tue,Wed,Thu,Fri,Sat,Sun&#10;Leave out the | days part to post that subject every posting day."><?php echo esc_textarea($content['subjects_schedule'] ?? ''); ?></textarea>
                                        <p class="description"><strong>Format:</strong> <code>Subject name | Mon,Wed,Fri</code> — one per line. Each subject only posts on its assigned days.<br>
                                        Leave out <code>| days</code> to post that subject on all posting days.<br>
                                        <strong>Example:</strong> If today is Monday, only subjects with <code>Mon</code> will be picked.</p>
                                    </td>
                                </tr>
                                <tr>
                                    <th>Languages</th>
                                    <td>
                                        <?php
                                        $all_langs = array(
                                            'en' => 'English', 'fr' => 'French', 'de' => 'German',
                                            'es' => 'Spanish', 'it' => 'Italian', 'nl' => 'Dutch',
                                            'pt-br' => 'Portuguese (BR)', 'ar' => 'Arabic',
                                            'ru' => 'Russian', 'zh-hans' => 'Chinese (Simplified)',
                                            'ja' => 'Japanese', 'ko' => 'Korean',
                                            'pl' => 'Polish', 'cs' => 'Czech',
                                            'tr' => 'Turkish', 'sv' => 'Swedish',
                                        );
                                        $active_langs = $content['languages'] ?? array('en');
                                        foreach ($all_langs as $code => $name): ?>
                                        <label style="display:inline-block;min-width:180px;margin-bottom:4px;">
                                            <input type="checkbox" name="dba_content_settings[languages][]" value="<?php echo esc_attr($code); ?>" <?php checked(in_array($code, $active_langs)); ?> />
                                            <?php echo esc_html($name); ?>
                                        </label>
                                        <?php endforeach; ?>
                                        <p class="description">Select up to 5 languages. WPML must be installed for multi-language support.</p>
                                    </td>
                                </tr>
                                <tr>
                                    <th>Featured Image Size</th>
                                    <td>
                                        <input type="number" name="dba_content_settings[image_width]" value="<?php echo esc_attr($content['image_width'] ?? 950); ?>" min="200" max="2048" style="width:80px;" /> × 
                                        <input type="number" name="dba_content_settings[image_height]" value="<?php echo esc_attr($content['image_height'] ?? 762); ?>" min="200" max="2048" style="width:80px;" /> px
                                        <p class="description">Target dimensions for featured images. Generated images are automatically resized and cropped to fit. Default: 950 × 762.</p>
                                    </td>
                                </tr>
                                <tr>
                                    <th>Pillar URL</th>
                                    <td><input type="url" name="dba_content_settings[pillar_url]" value="<?php echo esc_url($content['pillar_url'] ?? ''); ?>" class="large-text" /></td>
                                </tr>
                                <tr>
                                    <th>Sitemap URL</th>
                                    <td><input type="url" name="dba_content_settings[sitemap_url]" value="<?php echo esc_url($content['sitemap_url'] ?? ''); ?>" class="large-text" /></td>
                                </tr>
                                <tr>
                                    <th>CTA HTML</th>
                                    <td>
                                        <textarea name="dba_content_settings[cta_html]" rows="5" class="large-text code"><?php echo esc_textarea($content['cta_html'] ?? ''); ?></textarea>
                                        <p class="description">Exact CTA HTML appended to every post. Must match exactly for validation.</p>
                                    </td>
                                </tr>
                                <tr>
                                    <th>Banned Words</th>
                                    <td>
                                        <?php
                                        $default_banned = array(
                                            'unlocking','unveiling','navigating','harnessing','demystifying',
                                            'mastering','empowering','transformative','recoupment','paradigm',
                                            'ecosystem','synergies','leveraging','optimization','optimisation',
                                            'framework','utilize','utilise','facilitate','comprehensive',
                                            'robust','streamline','cutting-edge','landscape','holistic',
                                            'pivot','scalable','actionable','delve','game-changer',
                                            'innovative','seamless','deep dive','unleash','elevate',
                                            'spearhead','foster','bolster','underpin','underscores',
                                            'realm','beacon','tapestry','multifaceted','intricate',
                                            'nuanced','commencing','aforementioned','pertaining',
                                            'therein','thereby','henceforth','notwithstanding',
                                            'stakeholder','synergy','disruption','disruptive',
                                            'best-in-class','world-class','next-gen','bleeding-edge',
                                            'turnkey','end-to-end','one-stop','full-spectrum',
                                            'value-added','mission-critical','results-driven',
                                            'proactive','futureproof','future-proof',
                                            'core structuring tool','structuring vehicle',
                                            'key instrument','instrumental in',
                                        );
                                        $banned = isset($content['banned_words']) ? $content['banned_words'] : $default_banned;
                                        if (!is_array($banned)) $banned = $default_banned;
                                        ?>
                                        <div id="dba-banned-words-container" style="display:flex;flex-wrap:wrap;gap:6px;margin-bottom:10px;">
                                            <?php foreach ($banned as $word): ?>
                                            <span class="dba-banned-tag" style="display:inline-flex;align-items:center;background:#fce4e4;border:1px solid #e57373;border-radius:4px;padding:4px 8px;font-size:13px;">
                                                <?php echo esc_html($word); ?>
                                                <button type="button" class="dba-remove-banned" data-word="<?php echo esc_attr($word); ?>" style="background:none;border:none;color:#c62828;font-size:16px;cursor:pointer;margin-left:4px;padding:0;line-height:1;" title="Remove">&times;</button>
                                            </span>
                                            <?php endforeach; ?>
                                        </div>
                                        <textarea name="dba_content_settings[banned_words_raw]" id="dba-banned-words-raw" style="display:none;"><?php echo esc_textarea(implode("\n", $banned)); ?></textarea>
                                        <div style="display:flex;gap:8px;align-items:center;margin-top:6px;">
                                            <input type="text" id="dba-add-banned-input" placeholder="Type a word or phrase…" class="regular-text" />
                                            <button type="button" id="dba-add-banned-btn" class="button">+ Add</button>
                                            <button type="button" id="dba-reset-banned-btn" class="button" title="Reset to default list">↻ Reset defaults</button>
                                        </div>
                                        <p class="description">Words and phrases that will <strong>never</strong> appear in generated articles. Click × to remove, type below to add.</p>
                                        <script>
                                        (function(){
                                            var container = document.getElementById('dba-banned-words-container');
                                            var raw = document.getElementById('dba-banned-words-raw');
                                            var addInput = document.getElementById('dba-add-banned-input');
                                            var addBtn = document.getElementById('dba-add-banned-btn');
                                            var resetBtn = document.getElementById('dba-reset-banned-btn');
                                            var defaults = <?php echo json_encode(array_values($default_banned)); ?>;

                                            function getWords() {
                                                return raw.value.split('\n').map(function(w){return w.trim();}).filter(function(w){return w.length>0;});
                                            }

                                            function setWords(words) {
                                                raw.value = words.join('\n');
                                            }

                                            function renderTags(words) {
                                                container.innerHTML = '';
                                                words.forEach(function(w) {
                                                    var span = document.createElement('span');
                                                    span.className = 'dba-banned-tag';
                                                    span.style.cssText = 'display:inline-flex;align-items:center;background:#fce4e4;border:1px solid #e57373;border-radius:4px;padding:4px 8px;font-size:13px;';
                                                    span.textContent = w;
                                                    var btn = document.createElement('button');
                                                    btn.type = 'button';
                                                    btn.innerHTML = '&times;';
                                                    btn.style.cssText = 'background:none;border:none;color:#c62828;font-size:16px;cursor:pointer;margin-left:4px;padding:0;line-height:1;';
                                                    btn.title = 'Remove';
                                                    btn.setAttribute('data-word', w);
                                                    btn.addEventListener('click', function(){
                                                        var words = getWords().filter(function(x){return x !== w;});
                                                        setWords(words);
                                                        renderTags(words);
                                                    });
                                                    span.appendChild(btn);
                                                    container.appendChild(span);
                                                });
                                            }

                                            container.addEventListener('click', function(e) {
                                                if (e.target.classList.contains('dba-remove-banned')) {
                                                    var w = e.target.getAttribute('data-word');
                                                    var words = getWords().filter(function(x){return x !== w;});
                                                    setWords(words);
                                                    renderTags(words);
                                                }
                                            });

                                            addBtn.addEventListener('click', function(){
                                                var newWord = addInput.value.trim().toLowerCase();
                                                if (!newWord) return;
                                                var words = getWords();
                                                if (words.indexOf(newWord) === -1) {
                                                    words.push(newWord);
                                                    setWords(words);
                                                    renderTags(words);
                                                }
                                                addInput.value = '';
                                                addInput.focus();
                                            });

                                            addInput.addEventListener('keydown', function(e){
                                                if (e.key === 'Enter') { e.preventDefault(); addBtn.click(); }
                                            });

                                            resetBtn.addEventListener('click', function(){
                                                if (confirm('Reset banned words to the default list? Your custom words will be lost.')) {
                                                    setWords(defaults);
                                                    renderTags(defaults);
                                                }
                                            });
                                        })();
                                        </script>
                                    </td>
                                </tr>
                            </table>
                        </div>

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

                <!-- Sidebar -->
                <div class="dba-settings-sidebar">
                    <div class="dba-section">
                        <h3>📊 Themes Available</h3>
                        <ul class="dba-theme-list">
                            <?php
                            $openai = DBA_OpenAI::get_instance();
                            $used = $logger->get_today_themes();
                            foreach ($openai->get_themes() as $t):
                                $is_used = in_array($t, $used);
                            ?>
                            <li class="<?php echo $is_used ? 'used' : ''; ?>"><?php echo esc_html($t); ?> <?php echo $is_used ? '✅' : ''; ?></li>
                            <?php endforeach; ?>
                        </ul>
                    </div>

                    <div class="dba-section">
                        <h3>🔗 Page Registry (<span id="dba-registry-count"><?php echo intval($scan_meta_full['total_pages'] ?? count($full_registry)); ?></span>)</h3>
                        <?php
                        $scan_meta = DBA_Sitemap::get_instance()->get_scan_meta();
                        $last_scan = $scan_meta['last_scan'] ?? null;
                        $lang_counts = $scan_meta['lang_counts'] ?? array();
                        $with_yoast = 0;
                        foreach ($full_registry as $p) {
                            if (!empty($p['yoast_keyphrase'])) $with_yoast++;
                        }
                        ?>
                        <div style="font-size:12px; line-height:1.8; margin-bottom:10px;">
                            <?php if ($last_scan): ?>
                            <div>📅 <strong>Last scan:</strong> <?php echo esc_html($last_scan); ?></div>
                            <div>⏱️ <strong>Duration:</strong> <?php echo esc_html($scan_meta['scan_duration'] ?? '—'); ?>s</div>
                            <?php endif; ?>
                            <div>📊 <strong>Total:</strong> <?php echo intval($scan_meta['total_pages'] ?? 0); ?> pages</div>
                            <div>🎯 <strong>Yoast keyphrases:</strong> <?php echo $with_yoast; ?></div>
                            <div>📊 <strong>IDF terms:</strong> <?php echo $scan_meta['idf_terms'] ?? 0; ?></div>
                            <?php if (!empty($lang_counts)): ?>
                            <div style="margin-top:6px;"><strong>🌐 Languages:</strong></div>
                            <div style="max-height:120px;overflow-y:auto;padding-left:8px;margin-top:2px;">
                            <?php
                            arsort($lang_counts);
                            foreach ($lang_counts as $lc_lang => $lc_count):
                            ?>
                                <div><code><?php echo esc_html(strtoupper($lc_lang)); ?></code> — <?php echo intval($lc_count); ?> pages</div>
                            <?php endforeach; ?>
                            </div>
                            <?php endif; ?>
                            <?php if (!$last_scan): ?>
                            <div style="margin-top:8px;padding:8px;background:#fff3cd;border-radius:4px;color:#856404;">
                                ⚠️ <strong>No scan yet.</strong> Click "Scan Internal Pages" to build the registry.
                            </div>
                            <?php endif; ?>
                        </div>
                        <div style="max-height:200px;overflow-y:auto;font-size:11px;">
                            <?php if (empty($full_registry)): ?>
                                <p>No pages scanned yet.</p>
                            <?php else: ?>
                                <p style="color:#888;margin:0 0 4px;font-size:10px;">Preview: <?php echo strtoupper(esc_html($primary_lang)); ?> pages (<?php echo count($full_registry); ?>)</p>
                                <?php foreach (array_slice($full_registry, 0, 15) as $entry): ?>
                                <div style="padding:3px 0;border-bottom:1px solid #eee;">
                                    <a href="<?php echo esc_url($entry['url']); ?>" target="_blank" style="word-break:break-all;"><?php echo esc_html($entry['title'] ?? $entry['slug']); ?></a>
                                    <?php if (!empty($entry['yoast_keyphrase'])): ?>
                                    <span style="color:#1565c0;font-size:10px;"> [<?php echo esc_html($entry['yoast_keyphrase']); ?>]</span>
                                    <?php endif; ?>
                                </div>
                                <?php endforeach; ?>
                                <?php if (count($full_registry) > 15): ?>
                                <p><em>… and <?php echo count($full_registry) - 15; ?> more</em></p>
                                <?php endif; ?>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="dba-section">
                        <h3>ℹ️ Shortcode</h3>
                        <p>Display blog posts on any page:</p>
                        <code>[damalion_blog limit="10"]</code>
                        <p style="margin-top:8px;">Filter by subject:</p>
                        <code>[damalion_blog subject="Private equity fund setup" limit="5"]</code>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Render logs page
     */
    public function render_logs_page() {
        if (!current_user_can('manage_options')) return;

        $logger = DBA_Logger::get_instance();
        $logs = $logger->get_logs(100);
        ?>
        <div class="wrap">
            <h1>📋 Damalion Blog AI — Generation Logs</h1>

            <div style="margin-bottom:15px;">
                <button id="dba-clear-logs" class="button button-secondary">🗑️ Clear All Logs</button>
                <button id="dba-refresh-logs" class="button button-secondary">🔄 Refresh</button>
            </div>

            <table class="widefat striped" id="dba-logs-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Date</th>
                        <th>Theme</th>
                        <th>Title</th>
                        <th>Lang</th>
                        <th>Post</th>
                        <th>Status</th>
                        <th>Retries</th>
                        <th>Validation</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($logs)): ?>
                    <tr><td colspan="9" style="text-align:center;">No logs yet. Generate some posts!</td></tr>
                    <?php else: ?>
                    <?php foreach ($logs as $log): ?>
                    <tr>
                        <td><?php echo intval($log['id']); ?></td>
                        <td><?php echo esc_html($log['run_time']); ?></td>
                        <td><?php echo esc_html($log['theme']); ?></td>
                        <td>
                            <?php if (!empty($log['post_id']) && $log['post_id'] > 0): ?>
                            <a href="<?php echo get_edit_post_link($log['post_id']); ?>"><?php echo esc_html(wp_trim_words($log['title'], 8)); ?></a>
                            <?php else: ?>
                            <?php echo esc_html(wp_trim_words($log['title'], 8)); ?>
                            <?php endif; ?>
                        </td>
                        <td><?php echo esc_html($log['language']); ?></td>
                        <td><?php echo $log['post_id'] ? '#' . intval($log['post_id']) : '—'; ?></td>
                        <td>
                            <span class="dba-status-<?php echo esc_attr($log['status']); ?>">
                                <?php echo esc_html(ucfirst($log['status'])); ?>
                            </span>
                        </td>
                        <td><?php echo intval($log['retry_attempts']); ?></td>
                        <td title="<?php echo esc_attr($log['validation_result']); ?>"><?php echo esc_html(wp_trim_words($log['validation_result'], 5)); ?></td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        <?php
    }
}
