<?php
/**
 * Admin Interface
 * 
 * Settings page for controlling plugin features
 * and viewing statistics.
 */

namespace BlockAI;

class Admin {
    
    /**
     * Initialize admin interface
     */
    public function init() {
        add_action('admin_menu', [$this, 'add_admin_menu']);
        add_action('admin_init', [$this, 'register_settings']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_assets']);
        add_action('admin_notices', [$this, 'display_compatibility_notices']);
    }
    
    /**
     * Add admin menu (top-level menu item)
     */
    public function add_admin_menu() {
        add_menu_page(
            'HumanGate',
            'HumanGate',
            'manage_options',
            'block-ai-plugin',
            [$this, 'render_settings_page'],
            'dashicons-shield-alt', // Shield icon to represent protection/security
            30 // Position in menu (after Comments, before Appearance)
        );
        
        // Add submenu item with same name (removes duplicate, makes "HumanGate" parent)
        add_submenu_page(
            'block-ai-plugin',
            'HumanGate Settings',
            'Settings',
            'manage_options',
            'block-ai-plugin',
            [$this, 'render_settings_page']
        );
    }
    
    /**
     * Register settings
     */
    public function register_settings() {
        // Block Search Engines
        register_setting('block_ai_settings', 'block_ai_block_search_engines', [
            'type' => 'boolean',
            'default' => true,
            'sanitize_callback' => function($value) {
                return filter_var($value, FILTER_VALIDATE_BOOLEAN);
            },
        ]);
        
        // Global Refusal
        register_setting('block_ai_settings', 'block_ai_global_refusal', [
            'type' => 'boolean',
            'default' => true,
            'sanitize_callback' => function($value) {
                return filter_var($value, FILTER_VALIDATE_BOOLEAN);
            },
        ]);
        
        // Enforcement Mode
        register_setting('block_ai_settings', 'block_ai_enforcement_mode', [
            'type' => 'string',
            'default' => 'signals_only',
            'sanitize_callback' => function($value) {
                $allowed = ['signals_only', 'challenge', 'block'];
                return in_array($value, $allowed) ? $value : 'signals_only';
            },
        ]);
        
        // Verify Search Engine Bots (expensive DNS lookup)
        register_setting('block_ai_settings', 'block_ai_verify_search_engine_bots', [
            'type' => 'boolean',
            'default' => false,
            'sanitize_callback' => function($value) {
                return filter_var($value, FILTER_VALIDATE_BOOLEAN);
            },
        ]);
        
        // Emergency Lockdown
        register_setting('block_ai_settings', 'block_ai_lockdown_mode', [
            'type' => 'boolean',
            'default' => false,
            'sanitize_callback' => function($value) {
                return filter_var($value, FILTER_VALIDATE_BOOLEAN);
            },
        ]);
        
        register_setting('block_ai_settings', 'block_ai_lockdown_require_login', [
            'type' => 'boolean',
            'default' => false,
            'sanitize_callback' => function($value) {
                return filter_var($value, FILTER_VALIDATE_BOOLEAN);
            },
        ]);
        
        // Friction Settings
        register_setting('block_ai_settings', 'block_ai_friction_enabled', [
            'type' => 'boolean',
            'default' => true,
            'sanitize_callback' => function($value) {
                return filter_var($value, FILTER_VALIDATE_BOOLEAN);
            },
        ]);
        
        register_setting('block_ai_settings', 'block_ai_friction_burst_pages', [
            'type' => 'integer',
            'default' => 12,
            'sanitize_callback' => 'absint',
        ]);
        
        register_setting('block_ai_settings', 'block_ai_friction_burst_seconds', [
            'type' => 'integer',
            'default' => 5,
            'sanitize_callback' => 'absint',
        ]);
        
        register_setting('block_ai_settings', 'block_ai_friction_rate_pages', [
            'type' => 'integer',
            'default' => 40,
            'sanitize_callback' => 'absint',
        ]);
        
        register_setting('block_ai_settings', 'block_ai_friction_rate_seconds', [
            'type' => 'integer',
            'default' => 60,
            'sanitize_callback' => 'absint',
        ]);
        
        // Disable robots.txt management
        register_setting('block_ai_settings', 'block_ai_disable_robots_txt', [
            'type' => 'boolean',
            'default' => false,
            'sanitize_callback' => function($value) {
                return filter_var($value, FILTER_VALIDATE_BOOLEAN);
            },
        ]);
        
        // Register post type settings (for granular control)
        $post_types = get_post_types(['public' => true], 'names');
        foreach ($post_types as $post_type) {
            $setting_name = 'block_ai_refusal_post_types_' . $post_type;
            register_setting('block_ai_settings', $setting_name, [
                'type' => 'boolean',
                'default' => true,
                'sanitize_callback' => function($value) {
                    return filter_var($value, FILTER_VALIDATE_BOOLEAN);
                },
            ]);
        }
        
        // Statistics retention period
        register_setting('block_ai_settings', 'block_ai_stats_retention', [
            'type' => 'string',
            'default' => 'weekly',
            'sanitize_callback' => function($value) {
                $allowed = ['daily', 'weekly', 'monthly', 'ongoing'];
                return in_array($value, $allowed) ? $value : 'weekly';
            },
        ]);
    }
    
    /**
     * Display compatibility notices
     */
    public function display_compatibility_notices() {
        $screen = get_current_screen();
        if (!$screen || $screen->id !== 'toplevel_page_block-ai-plugin') {
            return;
        }
        
        // Check for robots.txt managing plugins
        $robots_plugins = \BlockAI\RefusalLayer::detect_robots_txt_plugins();
        $disable_robots = get_option('block_ai_disable_robots_txt', false);
        
        // Always show robots.txt information, but adapt based on detected plugins
        if ($disable_robots) {
            // robots.txt management is disabled
            if (!empty($robots_plugins)) {
                $plugins_list = implode(', ', $robots_plugins);
                ?>
                <div class="notice notice-warning">
                    <p><strong>robots.txt Management Disabled:</strong></p>
                    <p>
                        HumanGate's robots.txt management is disabled. You'll need to manually add AI crawler blocks to your robots.txt file in <?php echo esc_html($plugins_list); ?> if you want to block AI crawlers via robots.txt.
                    </p>
                    <p>
                        Note: Even with robots.txt management disabled, HumanGate still provides:
                    </p>
                    <ul style="list-style: disc; margin-left: 2em;">
                        <li>Meta tags (noindex, noai, etc.)</li>
                        <li>HTTP headers (X-Robots-Tag, X-AI-Training)</li>
                        <li>Active enforcement (if enabled) via HTTP-level blocking</li>
                    </ul>
                </div>
                <?php
            }
        } else {
            // robots.txt management is enabled
            if (!empty($robots_plugins)) {
                // SEO plugins detected - show compatibility info
                $plugins_list = implode(', ', $robots_plugins);
                ?>
                <div class="notice notice-info is-dismissible">
                    <p><strong>HumanGate & <?php echo esc_html($plugins_list); ?> Compatibility:</strong></p>
                    <p>
                        HumanGate automatically appends AI crawler blocks to your robots.txt file managed by <?php echo esc_html($plugins_list); ?>. 
                        Both plugins work together - HumanGate adds its rules after <?php echo esc_html($plugins_list); ?> generates the base robots.txt file.
                    </p>
                    <p>
                        <strong>Recommendation:</strong> Let HumanGate manage the AI crawler blocks automatically. 
                        If you prefer to manage robots.txt entirely through <?php echo esc_html($plugins_list); ?>, you can disable HumanGate's robots.txt management below.
                    </p>
                </div>
                <?php
            } else {
                // No SEO plugins detected - explain HumanGate manages robots.txt directly
                ?>
                <div class="notice notice-info is-dismissible">
                    <p><strong>robots.txt Management:</strong></p>
                    <p>
                        HumanGate automatically manages your robots.txt file, adding AI crawler blocks to prevent AI training crawlers from accessing your site.
                    </p>
                    <p>
                        If you install an SEO plugin (like Yoast SEO, Rank Math, or All in One SEO), HumanGate will automatically work with it by appending its rules to the SEO plugin's robots.txt configuration.
                    </p>
                    <p>
                        If you prefer to manage robots.txt manually, you can disable HumanGate's robots.txt management below.
                    </p>
                </div>
                <?php
            }
        }
    }
    
    /**
     * Enqueue admin assets
     */
    public function enqueue_admin_assets($hook) {
        if ($hook !== 'toplevel_page_block-ai-plugin') {
            return;
        }
        
        wp_enqueue_style(
            'block-ai-admin',
            BLOCK_AI_PLUGIN_URL . 'assets/admin.css',
            [],
            BLOCK_AI_PLUGIN_VERSION
        );
        
        // Ensure jQuery is loaded for tab functionality
        wp_enqueue_script('jquery');
    }
    
    /**
     * Get logo URL
     */
    private function get_logo_url() {
        $logo_path = BLOCK_AI_PLUGIN_DIR . 'assets/HumanGateLogo.png';
        if (file_exists($logo_path)) {
            return BLOCK_AI_PLUGIN_URL . 'assets/HumanGateLogo.png';
        }
        return false;
    }
    
    /**
     * Render settings page
     */
    public function render_settings_page() {
        // Security check: verify user capabilities
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'humangate'));
        }
        
        // Handle retention settings save separately
        if (isset($_POST['save_retention']) && isset($_POST['block_ai_stats_retention'])) {
            check_admin_referer('block_ai_settings-options');
            $retention = sanitize_text_field(wp_unslash($_POST['block_ai_stats_retention']));
            $allowed = ['daily', 'weekly', 'monthly', 'ongoing'];
            if (in_array($retention, $allowed)) {
                update_option('block_ai_stats_retention', $retention);
                // Redirect to refresh the page and show updated setting
                wp_safe_redirect(add_query_arg(['page' => 'block-ai-plugin', 'tab' => 'telemetry', 'settings-updated' => 'retention'], admin_url('admin.php')));
                exit;
            }
        }
        
        // Show success notice if redirected after save
        if (isset($_GET['settings-updated']) && $_GET['settings-updated'] === 'retention') {
            echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('Retention settings saved.', 'humangate') . '</p></div>';
        }
        
        // Verify nonce on form submission (handled by settings_fields, but double-check)
        if (isset($_POST['submit']) && !check_admin_referer('block_ai_settings-options')) {
            wp_die(esc_html__('Security check failed.', 'humangate'));
        }
        
        // Get telemetry stats
        $telemetry = new Telemetry();
        $stats = $telemetry->get_formatted_stats();
        
        ?>
        <div class="wrap">
            <div class="block-ai-admin">
                <div class="plugin-header">
                    <div class="plugin-header-text">
                        <h1>HumanGate</h1>
                        <p class="description">
                            Lightweight but enforceable AI & Indexing Refusal + Selective Friction layer for WordPress.
                        </p>
                    </div>
                </div>
            
            <form method="post" action="options.php">
                <?php
                settings_fields('block_ai_settings');
                ?>
                
                <?php 
                // Determine which tab to show (check URL parameter or default to settings)
                $active_tab = isset($_GET['tab']) && $_GET['tab'] === 'telemetry' ? 'telemetry' : 'settings';
                ?>
                <h2 class="nav-tab-wrapper">
                    <a href="#settings" class="nav-tab <?php echo $active_tab === 'settings' ? 'nav-tab-active' : ''; ?>">Settings</a>
                    <a href="#telemetry" class="nav-tab <?php echo $active_tab === 'telemetry' ? 'nav-tab-active' : ''; ?>">Stats</a>
                </h2>
                
                <div id="settings-tab" class="tab-content" style="display: <?php echo $active_tab === 'settings' ? 'block' : 'none'; ?>;">
                    
                    <!-- SECTION 1: AI CRAWLER BLOCKING -->
                    <div class="collapsible-section">
                        <h2 class="collapsible-header active">
                            <span>AI Crawler Blocking</span>
                            <span class="toggle-icon">▼</span>
                        </h2>
                        <div class="collapsible-content" style="display: block;">
                            <div class="global-refusal-toggle-section" style="margin-bottom: 2rem;">
                                <label for="block_ai_global_refusal" style="display: flex; align-items: flex-start; gap: 12px; cursor: pointer; padding: 1rem; background: rgba(255, 255, 255, 0.02); border-radius: 8px; border: 1px solid rgba(255, 255, 255, 0.05); transition: all 0.2s ease;">
                                    <input type="checkbox" 
                                           id="block_ai_global_refusal" 
                                           name="block_ai_global_refusal" 
                                           value="1" 
                                           <?php checked(get_option('block_ai_global_refusal', true)); ?>
                                           class="global-refusal-toggle"
                                           style="margin-top: 2px; width: 18px; height: 18px; cursor: pointer; flex-shrink: 0;">
                                    <div style="flex: 1;">
                                        <div style="font-weight: 500; color: var(--text-main); margin-bottom: 0.5em;">
                                            Enable AI crawler blocking (meta tags, HTTP headers, robots.txt)
                                        </div>
                                        <p class="description" style="margin: 0 0 0.5em 0; font-size: 0.9em; color: var(--text-soft);">
                                            Sends refusal signals (meta tags, HTTP headers, robots.txt) to block known AI training crawlers (GPTBot, ClaudeBot, PerplexityBot, etc.). Optionally can actively block/challenge AI crawlers based on enforcement mode below.
                                        </p>
                                        <div style="margin-top: 0.75em; padding: 0.75em; background: rgba(255, 107, 107, 0.1); border-left: 3px solid #ff6b6b; border-radius: 4px;">
                                            <p style="margin: 0; font-size: 0.85em; color: var(--text-soft); line-height: 1.5;">
                                                <strong style="color: var(--text-main);">Targets:</strong> Known AI training crawlers (GPTBot, ClaudeBot, PerplexityBot, CCBot, Google-Extended, etc.) by user agent detection. 
                                                Search engine blocking is configured separately below.
                                            </p>
                                        </div>
                                    </div>
                                </label>
                            </div>
                            
                            <div class="enforcement-options" style="<?php echo get_option('block_ai_global_refusal', true) ? '' : 'display: none;'; ?>">
                                <h4 style="margin-top: 0; margin-bottom: 1.5rem; font-size: 1.1em; font-weight: 600; color: var(--text-main);">Enforcement Mode</h4>
                                    
                                    <?php $current_mode = get_option('block_ai_enforcement_mode', 'signals_only'); ?>
                                    
                                    <div class="enforcement-modes">
                                        <div class="enforcement-mode-card <?php echo $current_mode === 'signals_only' ? 'active' : ''; ?>">
                                            <label class="enforcement-mode-label">
                                                <input type="radio" 
                                                       name="block_ai_enforcement_mode" 
                                                       value="signals_only" 
                                                       <?php checked($current_mode, 'signals_only'); ?>>
                                                <div class="mode-header">
                                                    <div class="mode-title">
                                                        <strong>Signals Only</strong>
                                                        <span class="mode-badge mode-badge-default">Recommended</span>
                                                    </div>
                                                </div>
                                                <p class="mode-description">
                                                    Send meta tags and headers, no active blocking. Best for most sites.
                                                </p>
                                                <ul class="mode-features">
                                                    <li>• AI-specific meta tags (noai, noimageai)</li>
                                                    <li>• HTTP headers (X-AI-Training, X-Content-Usage)</li>
                                                    <li>• robots.txt rules for AI crawlers</li>
                                                    <li>• No performance impact</li>
                                                </ul>
                                            </label>
                                        </div>
                                        
                                        <div class="enforcement-mode-card <?php echo $current_mode === 'challenge' ? 'active' : ''; ?>">
                                            <label class="enforcement-mode-label">
                                                <input type="radio" 
                                                       name="block_ai_enforcement_mode" 
                                                       value="challenge" 
                                                       <?php checked($current_mode, 'challenge'); ?>>
                                                <div class="mode-header">
                                                    <div class="mode-title">
                                                        <strong>Challenge Mode</strong>
                                                        <span class="mode-badge mode-badge-balanced">Balanced</span>
                                                    </div>
                                                </div>
                                                <p class="mode-description">
                                                    Send signals + require JavaScript challenge for known AI crawlers.
                                                </p>
                                                <ul class="mode-features">
                                                    <li>• All signals from "Signals Only"</li>
                                                    <li>• JavaScript challenge for AI crawlers</li>
                                                    <li>• Stops simple scrapers automatically</li>
                                                    <li>• Challenges headless browsers</li>
                                                </ul>
                                            </label>
                                        </div>
                                        
                                        <div class="enforcement-mode-card <?php echo $current_mode === 'block' ? 'active' : ''; ?>">
                                            <label class="enforcement-mode-label">
                                                <input type="radio" 
                                                       name="block_ai_enforcement_mode" 
                                                       value="block" 
                                                       <?php checked($current_mode, 'block'); ?>
                                                       class="enforcement-mode-radio"
                                                       data-mode="block">
                                                <div class="mode-header">
                                                    <div class="mode-title">
                                                        <strong>Block Mode</strong>
                                                        <span class="mode-badge mode-badge-maximum">Maximum Protection</span>
                                                    </div>
                                                </div>
                                                <p class="mode-description">
                                                    Send signals + return 403 Forbidden to known AI crawlers.
                                                </p>
                                                <ul class="mode-features">
                                                    <li>• All signals from "Signals Only"</li>
                                                    <li>• Active HTTP-level blocking</li>
                                                    <li>• Returns 403 Forbidden to AI crawlers</li>
                                                    <li>• Maximum enforcement</li>
                                                </ul>
                                            </label>
                                        </div>
                                    </div>
                                    
                                    <p class="description" style="margin-top: 1.5em; font-size: 0.85em; color: var(--text-soft);">
                                        <strong>Note:</strong> These enforcement modes target specific AI crawlers by user agent. 
                                        The "Bot Challenge Level" section below targets <strong>all suspicious bots</strong> (including scrapers) based on behavior patterns.
                                        Search engine blocking is configured separately in the "Search Engine Blocking" section below.
                                    </p>
                                    
                                    <div style="margin-top: 1.5em; padding-top: 1em; border-top: 1px solid rgba(255, 255, 255, 0.08);">
                                        <h4>robots.txt Management
                                            <span class="tooltip-trigger" 
                                                  data-tooltip="robots.txt is a file that tells search engines and crawlers which pages they can or cannot access on your site. It's located at yoursite.com/robots.txt. HumanGate automatically adds rules to block AI training crawlers while still allowing search engine bots if you've enabled that option."
                                                  style="display: inline-block; width: 14px; height: 14px; border-radius: 50%; background: #ff6b6b; color: #ffffff; font-size: 10px; line-height: 14px; text-align: center; margin-left: 6px; cursor: help; font-weight: bold; vertical-align: middle;">i</span>
                                        </h4>
                                        <?php 
                                        $robots_plugins = \BlockAI\RefusalLayer::detect_robots_txt_plugins();
                                        if (!empty($robots_plugins)): 
                                        ?>
                                            <p class="description">
                                                <strong>Detected SEO Plugin:</strong> <?php echo esc_html(implode(', ', $robots_plugins)); ?>
                                            </p>
                                            <p class="description">
                                                HumanGate automatically appends AI crawler blocks to your robots.txt file. 
                                                Both plugins work together - HumanGate adds its rules after your SEO plugin generates the base file.
                                            </p>
                                        <?php else: ?>
                                            <p class="description">
                                                HumanGate automatically manages your robots.txt file, adding AI crawler blocks. 
                                                If you install an SEO plugin (Yoast SEO, Rank Math, All in One SEO, etc.), HumanGate will automatically work with it by appending its rules.
                                            </p>
                                        <?php endif; ?>
                                        
                                        <input type="checkbox" 
                                               id="block_ai_disable_robots_txt" 
                                               name="block_ai_disable_robots_txt" 
                                               value="1" 
                                               <?php checked(get_option('block_ai_disable_robots_txt', false)); ?>>
                                        <label for="block_ai_disable_robots_txt">
                                            <strong>Disable robots.txt management</strong>
                                        </label>
                                        <p class="description">
                                            If disabled, you'll need to manually add AI crawler blocks to robots.txt<?php echo !empty($robots_plugins) ? ' through your SEO plugin' : ''; ?>. 
                                            HumanGate will still provide meta tags and HTTP headers for refusal signals.
                                        </p>
                                    </div>
                                </div>
                            </table>
                        </div>
                    </div>
                    
                    <!-- SECTION 2: SEARCH ENGINE BLOCKING -->
                    <div class="collapsible-section">
                        <h2 class="collapsible-header active">
                            <span>Search Engine Blocking</span>
                            <span class="toggle-icon">▼</span>
                        </h2>
                        <div class="collapsible-content" style="display: block;">
                            <table class="form-table">
                                <tr>
                                    <th scope="row">
                                        <label for="block_ai_block_search_engines">Block Search Engines</label>
                                    </th>
                                    <td>
                                        <label for="block_ai_block_search_engines" style="display: flex; align-items: flex-start; gap: 12px; cursor: pointer;">
                                            <input type="checkbox" 
                                                   id="block_ai_block_search_engines" 
                                                   name="block_ai_block_search_engines" 
                                                   value="1" 
                                                   <?php checked(get_option('block_ai_block_search_engines', true)); ?>
                                                   style="margin-top: 3px; width: 18px; height: 18px; cursor: pointer; flex-shrink: 0;">
                                            <div style="flex: 1;">
                                                <strong style="color: var(--text-main);">Block Search Engines (Google, Bing, DuckDuckGo, etc.)</strong>
                                                <p class="description" style="margin: 0.5em 0 0 0; font-size: 0.9em; color: var(--text-soft); line-height: 1.6;">
                                                    When enabled, adds <code style="background: rgba(0,0,0,0.3); padding: 2px 6px; border-radius: 3px; font-weight: 600;">noindex, nofollow</code> meta tags that tell <strong>all search engines</strong> NOT to index your site. 
                                                    Your site will <strong>NOT appear in Google search results</strong> or any other search engine when this is enabled.
                                                </p>
                                                <div style="margin-top: 1em; padding: 0.75em; background: rgba(255, 107, 107, 0.1); border-left: 3px solid #ff6b6b; border-radius: 4px;">
                                                    <p style="margin: 0; font-size: 0.85em; color: var(--text-soft); line-height: 1.5;">
                                                        <strong style="color: var(--text-main);">Targets:</strong> All search engines (Google, Bing, DuckDuckGo, Yandex, Baidu, etc.) via <code style="background: rgba(0,0,0,0.3); padding: 2px 4px; border-radius: 3px;">noindex, nofollow</code> meta tags. 
                                                        This is separate from AI crawler blocking configured above.
                                                    </p>
                                                </div>
                                            </div>
                                        </label>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </div>
                    
                    <div class="collapsible-section">
                        <h2 class="collapsible-header">
                            <span>Content Type Control</span>
                            <span class="toggle-icon">▶</span>
                        </h2>
                        <div class="collapsible-content" style="display: none;">
                            <table class="form-table">
                        <tr>
                            <th scope="row">
                                <label>Post Types</label>
                            </th>
                            <td>
                                <?php 
                                $content_control = new ContentControl();
                                $post_types = $content_control->get_post_types_with_settings();
                                ?>
                                
                                <p class="description" style="margin-bottom: 1em;">
                                    Select which post types should have AI refusal signals applied. You can also control this per-post in the post editor.
                                    <strong>Note:</strong> This allows you to selectively apply refusal to specific content types, even if global refusal is disabled.
                                </p>
                                
                                <div style="background: #1d2327; padding: 1.5em; border-radius: 8px; border: 1px solid rgba(255, 107, 107, 0.2);">
                                    <?php foreach ($post_types as $post_type): ?>
                                        <p style="margin: 0.75em 0;">
                                            <label style="display: flex; align-items: center;">
                                                <input type="checkbox" 
                                                       name="block_ai_refusal_post_types_<?php echo esc_attr($post_type['name']); ?>" 
                                                       value="1" 
                                                       <?php checked($post_type['enabled'], true); ?>
                                                       style="margin-right: 0.5em;">
                                                <strong><?php echo esc_html($post_type['label']); ?></strong>
                                                <span style="color: #999; margin-left: 0.5em; font-size: 0.9em;">
                                                    (<?php echo esc_html($post_type['name']); ?>)
                                                </span>
                                            </label>
                                        </p>
                                    <?php endforeach; ?>
                                </div>
                                
                                <p class="description" style="margin-top: 1em;">
                                    <strong>Per-Post Control:</strong> When editing a post or page, you'll see a "HumanGate AI Refusal" meta box 
                                    in the sidebar where you can enable/disable refusal for that specific content, or inherit from the post type setting.
                                </p>
                                
                                <div style="margin-top: 1em; padding: 1em; background: rgba(255, 107, 107, 0.1); border-radius: 6px; border-left: 3px solid #ff6b6b;">
                                    <p style="margin: 0; font-size: 0.9em;">
                                        <strong>💡 Tip:</strong> You might want to disable refusal for certain content types (e.g., product pages) 
                                        if you want them indexed in search engines or accessible to AI tools.
                                    </p>
                                </div>
                            </td>
                        </tr>
                            </table>
                        </div>
                    </div>
                    
                    <div class="collapsible-section">
                        <h2 class="collapsible-header">
                            <span>Emergency Lockdown Mode</span>
                            <span class="toggle-icon">▶</span>
                        </h2>
                        <div class="collapsible-content" style="display: none;">
                            <table class="form-table">
                        <tr>
                            <th scope="row">
                                <label for="block_ai_lockdown_mode">Enable Lockdown</label>
                            </th>
                            <td>
                                <input type="checkbox" 
                                       id="block_ai_lockdown_mode" 
                                       name="block_ai_lockdown_mode" 
                                       value="1" 
                                       <?php checked(get_option('block_ai_lockdown_mode', false)); ?>
                                       class="lockdown-toggle">
                                <label for="block_ai_lockdown_mode">
                                    <strong>Enable emergency lockdown</strong> (451 responses to unknown agents)
                                </label>
                                <p class="description" style="color: #d63638;">
                                    <strong>Warning:</strong> This will block most visitors. Use only in emergencies.
                                </p>
                                
                                <div class="lockdown-options" style="margin-top: 1em; <?php echo get_option('block_ai_lockdown_mode') ? '' : 'display: none;'; ?>">
                                    <input type="checkbox" 
                                           id="block_ai_lockdown_require_login" 
                                           name="block_ai_lockdown_require_login" 
                                           value="1" 
                                           <?php checked(get_option('block_ai_lockdown_require_login', false)); ?>>
                                    <label for="block_ai_lockdown_require_login">
                                        Allow logged-in users (recommended for testing)
                                    </label>
                                </div>
                            </td>
                        </tr>
                            </table>
                        </div>
                    </div>
                    
                    <div class="collapsible-section">
                        <h2 class="collapsible-header">
                            <span>Bot Challenge Level</span>
                            <span class="toggle-icon">▶</span>
                        </h2>
                        <div class="collapsible-content" style="display: none;">
                            <table class="form-table">
                        <tr>
                            <th scope="row">
                                <label for="block_ai_friction_enabled">Enable Bot Challenges</label>
                            </th>
                            <td>
                                <input type="checkbox" 
                                       id="block_ai_friction_enabled" 
                                       name="block_ai_friction_enabled" 
                                       value="1" 
                                       <?php checked(get_option('block_ai_friction_enabled', true)); ?>
                                       class="friction-toggle">
                                <label for="block_ai_friction_enabled">
                                    Enable bot challenges (JS challenge for suspicious patterns)
                                </label>
                                <p class="description">
                                    Applies lightweight challenges to detected bot and scraping patterns.
                                </p>
                                <div style="margin-top: 0.75em; padding: 0.75em; background: rgba(255, 107, 107, 0.1); border-left: 3px solid #ff6b6b; border-radius: 4px;">
                                    <p style="margin: 0; font-size: 0.85em; color: var(--text-soft); line-height: 1.5;">
                                        <strong style="color: var(--text-main);">Targets:</strong> <strong>ALL suspicious bots</strong> (AI crawlers, scrapers, data harvesters, etc.) based on traffic patterns, not user agent. 
                                        This catches bots regardless of what they claim to be in their user agent string.
                                    </p>
                                </div>
                                
                                <div class="friction-options" style="margin-top: 1em; <?php echo get_option('block_ai_friction_enabled') ? '' : 'display: none;'; ?>">
                                    <h4>Burst Traffic Detection</h4>
                                    <p>
                                        <label>
                                            Pages: <input type="number" 
                                                          name="block_ai_friction_burst_pages" 
                                                          value="<?php echo esc_attr(get_option('block_ai_friction_burst_pages', 12)); ?>" 
                                                          min="1" 
                                                          style="width: 80px;">
                                        </label>
                                        in
                                        <label>
                                            <input type="number" 
                                                   name="block_ai_friction_burst_seconds" 
                                                   value="<?php echo esc_attr(get_option('block_ai_friction_burst_seconds', 5)); ?>" 
                                                   min="1" 
                                                   style="width: 80px;">
                                            seconds
                                        </label>
                                    </p>
                                    
                                    <h4>Rate Limit Detection</h4>
                                    <p>
                                        <label>
                                            Pages: <input type="number" 
                                                          name="block_ai_friction_rate_pages" 
                                                          value="<?php echo esc_attr(get_option('block_ai_friction_rate_pages', 40)); ?>" 
                                                          min="1" 
                                                          style="width: 80px;">
                                        </label>
                                        in
                                        <label>
                                            <input type="number" 
                                                   name="block_ai_friction_rate_seconds" 
                                                   value="<?php echo esc_attr(get_option('block_ai_friction_rate_seconds', 60)); ?>" 
                                                   min="1" 
                                                   style="width: 80px;">
                                            seconds
                                        </label>
                                    </p>
                                </div>
                            </td>
                        </tr>
                            </table>
                        </div>
                    </div>
                    
                    <?php submit_button(); ?>
                    
                    <div style="margin-top: 3rem; padding: 2rem; background: #1d2327; border: 1px solid rgba(255, 107, 107, 0.3); border-radius: 12px; border-left: 4px solid #ff6b6b;">
                        <h3 style="margin-top: 0; color: #ff6b6b; font-size: 1.25em; margin-bottom: 1rem;">
                            Learn More About AI Harms
                        </h3>
                        <p style="color: #e5e7eb; margin-bottom: 1em; line-height: 1.6;">
                            HumanGate helps protect your content from AI training and unauthorized scraping. 
                            To learn more about the broader issues surrounding AI development, content rights, and digital consent, visit <a href="https://darkai.ca/" target="_blank" rel="noopener noreferrer" style="color: #ff6b6b; text-decoration: underline;">darkai.ca</a>.
                        </p>
                        <p style="color: #d1d5db; margin: 0; font-size: 0.9em; line-height: 1.6;">
                            <strong>AI harms DarkAI investigates:</strong> Synthetic identity fraud ($20B+ annually), deepfake exploitation (8M+ projected in 2025), 
                            AI-generated sexual abuse material, impersonation attempts (3.8M+ globally), and AI-scaled fraud networks ($40B projected by 2027).
                        </p>
                    </div>
                </div>
            </form>
            
            <div id="telemetry-tab" class="tab-content" style="display: <?php echo $active_tab === 'telemetry' ? 'block' : 'none'; ?>;">
                <h2>Statistics</h2>
                
                <div style="background: #1d2327; border: 1px solid rgba(255, 107, 107, 0.3); border-left: 4px solid #ff6b6b; border-radius: 8px; padding: 1.5rem; margin-bottom: 2.5rem;">
                    <h3 style="margin-top: 0; color: #ff6b6b; font-size: 1.1em; margin-bottom: 1rem;">
                        Privacy & Data Storage
                    </h3>
                    <p style="color: #e5e7eb; margin-bottom: 0.75em; line-height: 1.6;">
                        <strong>All data is stored locally on your WordPress site.</strong> The plugin developer (DarkAI) does not collect, store, or transmit any data. 
                        Everything stays in your WordPress database and is under your complete control.
                    </p>
                    <p style="color: #d1d5db; margin: 0; font-size: 0.9em; line-height: 1.6;">
                        <strong>What is tracked:</strong> Aggregated counters (numbers only), user agent categories, and block reasons. 
                        <strong>What is not tracked:</strong> IP addresses, personal information, or any identifying data. 
                        You can clear all statistics at any time or disable statistics entirely.
                    </p>
                </div>
                
                <div style="margin-bottom: 2.5rem; padding: 1.5rem; background: #1d2327; border: 1px solid rgba(255, 255, 255, 0.1); border-radius: 8px;">
                    <h3 style="margin-top: 0; margin-bottom: 1rem; font-size: 1.1em;">Data Retention Settings</h3>
                    <table class="form-table" style="margin: 0;">
                        <tr>
                            <th scope="row" style="width: 200px;">
                                <label for="block_ai_stats_retention">Retention Period</label>
                            </th>
                            <td>
                                <div class="select-wrapper">
                                    <select name="block_ai_stats_retention" id="block_ai_stats_retention" style="background: #1d2327; border: 1px solid rgba(255, 255, 255, 0.2); color: #ffffff; padding: 8px 12px; padding-right: 35px; border-radius: 6px; min-width: 200px; appearance: none; -webkit-appearance: none; -moz-appearance: none;">
                                        <option value="daily" <?php selected(get_option('block_ai_stats_retention', 'weekly'), 'daily'); ?>>Daily (1 day)</option>
                                        <option value="weekly" <?php selected(get_option('block_ai_stats_retention', 'weekly'), 'weekly'); ?>>Weekly (7 days)</option>
                                        <option value="monthly" <?php selected(get_option('block_ai_stats_retention', 'weekly'), 'monthly'); ?>>Monthly (30 days)</option>
                                        <option value="ongoing" <?php selected(get_option('block_ai_stats_retention', 'weekly'), 'ongoing'); ?>>Ongoing (no automatic deletion)</option>
                                    </select>
                                    <span class="select-caret">▼</span>
                                </div>
                                <p class="description" style="margin-top: 0.5em; color: #d1d5db;">
                                    Choose how long to keep statistics. Data older than the selected period will be automatically deleted. 
                                    <strong>Current setting:</strong> 
                                    <span id="current-retention-text">
                                    <?php 
                                    $retention = get_option('block_ai_stats_retention', 'weekly');
                                    $retention_text = [
                                        'daily' => 'Data resets daily at midnight',
                                        'weekly' => 'Rolling 7-day window (data older than 7 days is deleted)',
                                        'monthly' => 'Rolling 30-day window (data older than 30 days is deleted)',
                                        'ongoing' => 'No automatic deletion (you control when to clear)'
                                    ];
                                    echo esc_html($retention_text[$retention]);
                                    ?>
                                    </span>
                                </p>
                            </td>
                        </tr>
                    </table>
                    <?php 
                    wp_nonce_field('block_ai_settings-options');
                    submit_button('Save Retention Settings', 'secondary', 'save_retention', false, ['style' => 'margin-top: 1rem;']); 
                    ?>
                </div>
                
                <div class="telemetry-stats">
                    <div class="stat-box">
                        <h3><?php echo number_format($stats['total_blocked']); ?></h3>
                        <p>Blocked crawler requests today</p>
                        <small><?php echo esc_html($stats['date']); ?></small>
                    </div>
                    
                    <div class="stat-box">
                        <h3<?php echo ($stats['top_user_agent'] === 'None') ? ' class="stat-none"' : ''; ?>><?php echo esc_html(strlen($stats['top_user_agent']) > 30 ? substr($stats['top_user_agent'], 0, 30) . '...' : $stats['top_user_agent']); ?></h3>
                        <p>Top blocked user agent
                            <span class="tooltip-trigger" 
                                  data-tooltip="The user agent string that appeared most frequently in blocked requests. User agents identify the software making the request (browser, bot, etc.)"
                                  style="display: inline-block; width: 14px; height: 14px; border-radius: 50%; background: #ff6b6b; color: #ffffff; font-size: 10px; line-height: 14px; text-align: center; margin-left: 6px; cursor: help; font-weight: bold; vertical-align: middle;">i</span>
                        </p>
                        <?php if ($stats['top_user_agent'] !== 'None'): ?>
                        <small><?php echo esc_html($stats['top_user_agent']); ?></small>
                        <?php endif; ?>
                    </div>
                    
                    <div class="stat-box">
                        <h3<?php echo ($stats['top_category'] === 'None') ? ' class="stat-none"' : ''; ?>><?php echo esc_html(ucwords(str_replace('_', ' ', $stats['top_category']))); ?></h3>
                        <p>Top blocked category 
                            <span class="tooltip-trigger" 
                                  data-tooltip="Categories: Browser (Chrome, Firefox, Safari, etc.), Cloud Hosting (AWS, Azure, Cloudflare, etc.), Bot Crawler (known bots/spiders), Unknown (doesn't match patterns)"
                                  style="display: inline-block; width: 14px; height: 14px; border-radius: 50%; background: #ff6b6b; color: #ffffff; font-size: 10px; line-height: 14px; text-align: center; margin-left: 6px; cursor: help; font-weight: bold; vertical-align: middle;">i</span>
                        </p>
                    </div>
                </div>
                
                <?php if (!empty($stats['by_reason'])): ?>
                <h3>Blocked by Reason</h3>
                <table class="wp-list-table widefat fixed striped" style="background: var(--bg-panel) !important;">
                    <thead>
                        <tr>
                            <th>Reason</th>
                            <th>Count</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        // Define tooltip explanations for each reason
                        $reason_tooltips = [
                            'burst' => 'Burst traffic detected: Too many pages accessed too quickly (default: 12+ pages in 5 seconds, or 40+ pages in 60 seconds). This catches bots scraping at high speed.',
                            'deep_link' => 'Deep link access: Direct access to old content, date archives, or media files with no referrer or session cookie. Suggests automated scraping.',
                            'sequential' => 'Sequential traversal: Machine-like pagination pattern (e.g., /page/1, /page/2, /page/3). Real users rarely browse this way.',
                            'ai_crawler_blocked' => 'AI crawler blocked: Known AI training crawler (GPTBot, ClaudeBot, etc.) detected by user agent and blocked by enforcement mode.',
                            'unknown' => 'Unknown reason: Blocked for an unspecified reason. Check your logs for more details.',
                        ];
                        
                        foreach ($stats['by_reason'] as $reason => $count): 
                            $reason_display = ucwords(str_replace('_', ' ', $reason));
                            $tooltip_text = isset($reason_tooltips[$reason]) ? $reason_tooltips[$reason] : 'Blocked for this reason.';
                        ?>
                        <tr style="background: transparent !important;">
                            <td style="color: #f3f4f7 !important; background: transparent !important;">
                                <?php echo esc_html($reason_display); ?>
                                <span class="tooltip-trigger" 
                                      data-tooltip="<?php echo esc_attr($tooltip_text); ?>"
                                      style="display: inline-block; width: 14px; height: 14px; border-radius: 50%; background: #ff6b6b; color: #ffffff; font-size: 10px; line-height: 14px; text-align: center; margin-left: 8px; cursor: help; font-weight: bold; vertical-align: middle;">i</span>
                            </td>
                            <td style="color: #f3f4f7 !important; background: transparent !important;"><?php echo number_format($count); ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php endif; ?>
            </div>
            </div>
        </div>
        
        <script>
        jQuery(document).ready(function($) {
            // Check URL parameter on page load to show correct tab
            var urlParams = new URLSearchParams(window.location.search);
            var tabParam = urlParams.get('tab');
            if (tabParam === 'telemetry') {
                $('.nav-tab[href="#telemetry"]').addClass('nav-tab-active').siblings().removeClass('nav-tab-active');
                $('#telemetry-tab').show().siblings('.tab-content').hide();
            }
            
            // Collapsible sections
            $('.collapsible-header').on('click', function() {
                var $header = $(this);
                var $content = $header.next('.collapsible-content');
                var $icon = $header.find('.toggle-icon');
                
                if ($header.hasClass('active')) {
                    $header.removeClass('active');
                    $content.slideUp(300);
                    $icon.text('▶');
                } else {
                    $header.addClass('active');
                    $content.slideDown(300);
                    $icon.text('▼');
                }
            });
            
            // Tab switching
            $('.nav-tab').on('click', function(e) {
                e.preventDefault();
                var target = $(this).attr('href');
                $('.nav-tab').removeClass('nav-tab-active');
                $(this).addClass('nav-tab-active');
                $('.tab-content').hide();
                $(target + '-tab').show();
            });
            
            // Toggle lockdown options
            $('.lockdown-toggle').on('change', function() {
                if ($(this).is(':checked')) {
                    $('.lockdown-options').slideDown();
                } else {
                    $('.lockdown-options').slideUp();
                }
            });
            
            // Toggle friction options
            $('.friction-toggle').on('change', function() {
                if ($(this).is(':checked')) {
                    $('.friction-options').slideDown();
                } else {
                    $('.friction-options').slideUp();
                }
            });
            
            // Toggle enforcement options based on global refusal checkbox
            function toggleEnforcementOptions() {
                if ($('.global-refusal-toggle').is(':checked')) {
                    $('.enforcement-options').slideDown(300);
                } else {
                    $('.enforcement-options').slideUp(300);
                }
            }
            
            // Run on page load
            toggleEnforcementOptions();
            
            // Run on checkbox change
            $('.global-refusal-toggle').on('change', toggleEnforcementOptions);
            
            // Make enforcement mode cards clickable
            $('.enforcement-mode-card').on('click', function(e) {
                // Don't trigger if clicking directly on the radio button
                if ($(e.target).is('input[type="radio"]')) {
                    return;
                }
                
                var $card = $(this);
                var $radio = $card.find('input[type="radio"]');
                
                // Uncheck all radios and remove active class
                $('.enforcement-mode-card').removeClass('active');
                $('.enforcement-mode-card input[type="radio"]').prop('checked', false);
                
                // Check this card's radio and add active class
                $radio.prop('checked', true);
                $card.addClass('active');
                
                // Trigger change event for search engine verification
                updateSearchEngineVerification();
            });
            
            // Also handle direct radio button clicks
            $('.enforcement-mode-card input[type="radio"]').on('change', function() {
                $('.enforcement-mode-card').removeClass('active');
                $(this).closest('.enforcement-mode-card').addClass('active');
                updateSearchEngineVerification();
            });
            
            // Show/hide search engine verification based on enforcement mode
            function updateSearchEngineVerification() {
                var mode = $('.enforcement-mode-radio:checked').val();
                if (mode === 'block') {
                    $('.search-engine-verification').slideDown();
                } else {
                    $('.search-engine-verification').slideUp();
                }
            }
            
            $('.enforcement-mode-radio').on('change', updateSearchEngineVerification);
            updateSearchEngineVerification(); // Run on page load
            
            // Tooltip functionality - using position:fixed to escape containers
            $(document).on('mouseenter', '.tooltip-trigger', function() {
                var trigger = this;
                var tooltipText = $(trigger).attr('data-tooltip');
                
                if (!tooltipText) {
                    return;
                }
                
                // Remove any existing tooltips
                $('.tooltip-popup').remove();
                
                // Create tooltip with fixed positioning
                var tooltip = document.createElement('div');
                tooltip.className = 'tooltip-popup';
                tooltip.textContent = tooltipText;
                tooltip.style.cssText = 'position:fixed;background:#1d2327;color:#ffffff;padding:12px 16px;border-radius:8px;font-size:14px;line-height:1.6;white-space:normal;width:300px;max-width:calc(100vw - 40px);z-index:99999999;text-align:left;box-shadow:0 8px 32px rgba(0,0,0,0.9),0 4px 16px rgba(255,107,107,0.3);border:1px solid rgba(255,107,107,0.4);word-wrap:break-word;pointer-events:none;opacity:0;transition:opacity 0.2s ease;';
                
                document.body.appendChild(tooltip);
                
                // Get trigger position (using getBoundingClientRect for viewport coordinates)
                var triggerRect = trigger.getBoundingClientRect();
                var tooltipRect = tooltip.getBoundingClientRect();
                
                // Position above by default (using viewport coordinates since tooltip is fixed)
                var top = triggerRect.top - tooltipRect.height - 10;
                var left = triggerRect.left + (triggerRect.width / 2) - (tooltipRect.width / 2);
                
                // Adjust if off screen
                if (top < 10) {
                    top = triggerRect.bottom + 10; // Show below instead
                }
                if (left < 10) {
                    left = 10;
                }
                if (left + tooltipRect.width > window.innerWidth - 10) {
                    left = window.innerWidth - tooltipRect.width - 10;
                }
                
                tooltip.style.top = top + 'px';
                tooltip.style.left = left + 'px';
                
                // Fade in
                setTimeout(function() {
                    tooltip.style.opacity = '1';
                }, 10);
                
                $(trigger).data('tooltip-element', tooltip);
            });
            
            $(document).on('mouseleave', '.tooltip-trigger', function() {
                var tooltip = $(this).data('tooltip-element');
                if (tooltip && tooltip.parentNode) {
                    tooltip.style.opacity = '0';
                    setTimeout(function() {
                        if (tooltip.parentNode) {
                            tooltip.parentNode.removeChild(tooltip);
                        }
                    }, 200);
                    $(this).removeData('tooltip-element');
                }
            });
            
            // Update retention text when dropdown changes
            $('#block_ai_stats_retention').on('change', function() {
                var retentionTexts = {
                    'daily': 'Data resets daily at midnight',
                    'weekly': 'Rolling 7-day window (data older than 7 days is deleted)',
                    'monthly': 'Rolling 30-day window (data older than 30 days is deleted)',
                    'ongoing': 'No automatic deletion (you control when to clear)'
                };
                var selectedValue = $(this).val();
                $('#current-retention-text').text(retentionTexts[selectedValue]);
            });
        });
        </script>
        <?php
    }
}

