<?php
/**
 * FajaedeSEO AI Settings Admin Page
 * Configure AI service integration
 */

defined('ABSPATH') or exit;

class FajaedeSEO_Admin_AI_Settings {
    
    public static function init() {
        add_action('admin_menu', [__CLASS__, 'add_menu']);
        add_action('admin_init', [__CLASS__, 'register_settings']);
        add_action('admin_enqueue_scripts', [__CLASS__, 'enqueue_scripts']);
    }
    
    /**
     * Add submenu page
     */
    public static function add_menu() {
        add_submenu_page(
            'fajaedeseo-seo',
            __('AI Settings', 'fajaedeseo-ai'),
            __('FajaedeSEO AI', 'fajaedeseo-ai'),
            'manage_options',
            'fajaedeseo-ai-settings',
            [__CLASS__, 'render_page']
        );
    }
    
    /**
     * Register settings
     */
    public static function register_settings() {
        register_setting('fajaedeseo_ai_settings', 'fajaedeseo_ai_enabled', [
            'type' => 'boolean',
            'sanitize_callback' => 'rest_sanitize_boolean',
            'default' => true,
        ]);
        
        register_setting('fajaedeseo_ai_settings', 'fajaedeseo_ai_cache_ttl', [
            'type' => 'integer',
            'sanitize_callback' => fn($val) => max(300, intval($val)),
            'default' => 3600,
        ]);
        
        register_setting('fajaedeseo_ai_settings', 'fajaedeseo_openai_api_key', [
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => '',
        ]);
        
        register_setting('fajaedeseo_ai_settings', 'fajaedeseo_serp_api_key', [
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => '',
        ]);
        
        register_setting('fajaedeseo_ai_settings', 'fajaedeseo_openai_image_model', [
            'type' => 'string',
            'sanitize_callback' => function($val) {
                return strtolower(str_replace(' ', '-', sanitize_text_field((string)$val)));
            },
            'default' => 'gpt-image-2-2026-04-21',
        ]);
    }
    
    /**
     * Enqueue admin scripts
     */
    public static function enqueue_scripts( string $hook ) {
        if (strpos($hook, 'fajaedeseo-ai-settings') === false) {
            return;
        }
        
        wp_enqueue_style(
            'fajaedeseo-admin-ai',
            FAJAEDESEO_URL . 'assets/css/admin-ai-settings.css',
            [],
            FAJAEDESEO_VERSION
        );
        
        wp_enqueue_script(
            'fajaedeseo-admin-ai',
            FAJAEDESEO_URL . 'assets/js/admin-ai-settings.js',
            ['jquery'],
            FAJAEDESEO_VERSION,
            true
        );
        
        wp_localize_script('fajaedeseo-admin-ai', 'fajaedeseAI', [
            'nonce' => wp_create_nonce('fajaedeseo_ai_nonce'),
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'restUrl' => esc_url_raw(get_rest_url(null, 'fajaedeseo/v1/bulk-generate-meta')),
            'restNonce' => wp_create_nonce('wp_rest')
        ]);
    }
    
    /**
     * Render settings page
     */
    public static function render_page() {
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized');
        }
        
        // Haal recente posts op voor de bulk-selector
        $recent_posts = get_posts([
            'numberposts' => 100, // Limiet voor de UI
            'post_status' => 'publish',
            'post_type'   => get_post_types(['public' => true]),
        ]);

        $is_healthy = \FajaedeSEO_AI_Service_Manager::check_health();
        
        ?>
        <div class="wrap">
            <h1><?php echo esc_html(get_admin_page_title()); ?></h1>
            
            <?php settings_errors(); ?>
            
            <!-- Status Card -->
            <div class="fajaedeseo-ai-card status-card">
                <h2><?php esc_html_e('Service Status', 'fajaedeseo-ai'); ?></h2>
                <div class="status-info">
                    <div class="status-item">
                        <span class="status-item-label"><?php esc_html_e('OpenAI API Status', 'fajaedeseo-ai'); ?></span>
                        <span class="status-badge <?php echo $is_healthy ? 'healthy' : 'unhealthy'; ?>">
                            <?php echo $is_healthy ? '✓ ' . esc_html__('Connected', 'fajaedeseo-ai') : '✗ ' . esc_html__('Disconnected', 'fajaedeseo-ai'); ?>
                        </span>
                    </div>
                </div>
                
                <?php if (!$is_healthy): ?>
                <div class="notice notice-warning">
                    <p><strong><?php esc_html_e('⚠️ Warning:', 'fajaedeseo-ai'); ?></strong> <?php esc_html_e('No valid OpenAI API key configured.', 'fajaedeseo-ai'); ?></p>
                    <p><?php esc_html_e('Please enter your OpenAI API key below to enable AI features.', 'fajaedeseo-ai'); ?></p>
                    <?php if ($error = get_option('fajaedeseo_last_ai_error')): ?>
                        <p><strong><?php esc_html_e('Detail:', 'fajaedeseo-ai'); ?></strong> <code><?php echo esc_html($error); ?></code></p>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
            </div>
            
            <!-- Configuration -->
            <form method="post" action="options.php" class="fajaedeseo-ai-form">
                <?php settings_fields('fajaedeseo_ai_settings'); ?>
                
                <div class="fajaedeseo-ai-card">
                    <h2><?php esc_html_e('API Configuration', 'fajaedeseo-ai'); ?></h2>
                    
                    <table class="form-table">
                        <tr>
                            <th scope="row">
                                <label for="fajaedeseo_ai_enabled"><?php esc_html_e('Enable AI Features', 'fajaedeseo-ai'); ?></label>
                            </th>
                            <td>
                                <input 
                                    type="checkbox" 
                                    id="fajaedeseo_ai_enabled" 
                                    name="fajaedeseo_ai_enabled" 
                                    value="1"
                                    <?php checked(get_option('fajaedeseo_ai_enabled'), 1); ?>
                                />
                                <label for="fajaedeseo_ai_enabled">
                                    <?php esc_html_e('Enable AI-powered features', 'fajaedeseo-ai'); ?>
                                </label>
                            </td>
                        </tr>
                        
                            <tr>
                                <th scope="row">
                                    <label for="fajaedeseo_openai_api_key"><?php esc_html_e('OpenAI API Key', 'fajaedeseo-ai'); ?></label>
                                </th>
                                <td>
                                    <input 
                                        type="text" 
                                        id="fajaedeseo_openai_api_key" 
                                        name="fajaedeseo_openai_api_key" 
                                        value="<?php echo esc_attr(get_option('fajaedeseo_openai_api_key')); ?>"
                                        class="large-text"
                                        placeholder="sk-..."
                                        <?php echo \FajaedeSEO_Pro_License::has_feature('openai') ? '' : 'disabled'; ?>
                                    />
                                    <div class="description" style="margin-top: 10px; background: #fff; border-left: 4px solid #0073aa; padding: 10px; box-shadow: 0 1px 1px rgba(0,0,0,.04);">
                                        <p style="margin-top: 0;"><strong><?php esc_html_e('Why do I need my own key?', 'fajaedeseo-ai'); ?></strong> <?php esc_html_e('By using your own API key, you pay the raw cost directly to OpenAI (usually pennies per month). No expensive monthly AI subscriptions or hidden markups!', 'fajaedeseo-ai'); ?></p>
                                        <ol style="margin-bottom: 0; padding-left: 20px;">
                                            <li><?php 
                                                /* translators: %s: Link to OpenAI website */
                                                printf(esc_html__('Create an account at %s', 'fajaedeseo-ai'), '<a href="https://platform.openai.com/" target="_blank" rel="noopener">platform.openai.com</a>'); 
                                            ?></li>
                                            <li><?php esc_html_e('Add at least $5 prepaid credit (required by OpenAI for API usage).', 'fajaedeseo-ai'); ?></li>
                                            <li><?php esc_html_e('Generate an API Key and paste it here.', 'fajaedeseo-ai'); ?></li>
                                        </ol>
                                    </div>
                                    <?php if (!\FajaedeSEO_Pro_License::has_feature('openai')): ?>
                                        <p style="color: #d63638; font-weight: bold; margin-top: 10px;">
                                            <?php esc_html_e('Requires a Pro, Premium or Agency License to activate.', 'fajaedeseo-ai'); ?>
                                        </p>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            
                            <tr>
                                <th scope="row">
                                    <label for="fajaedeseo_serp_api_key"><?php esc_html_e('ValueSERP API Key', 'fajaedeseo-ai'); ?></label>
                                </th>
                                <td>
                                    <input 
                                        type="text" 
                                        id="fajaedeseo_serp_api_key" 
                                        name="fajaedeseo_serp_api_key" 
                                        value="<?php echo esc_attr(get_option('fajaedeseo_serp_api_key')); ?>"
                                        class="large-text"
                                        placeholder="API sleutel..."
                                        <?php echo \FajaedeSEO_Pro_License::has_feature('advanced_serp') ? '' : 'disabled'; ?>
                                    />
                                    <div class="description" style="margin-top: 10px; background: #fff; border-left: 4px solid #0073aa; padding: 10px; box-shadow: 0 1px 1px rgba(0,0,0,.04);">
                                        <p style="margin-top: 0;"><strong><?php esc_html_e('Get 100 free searches per month!', 'fajaedeseo-ai'); ?></strong> <?php esc_html_e('ValueSERP provides real-time Google search data. By connecting your own free account, you avoid paying us any markup fees.', 'fajaedeseo-ai'); ?></p>
                                        <ol style="margin-bottom: 0; padding-left: 20px;">
                                            <li><?php 
                                                /* translators: %s: Link to ValueSERP website */
                                                printf(esc_html__('Create a free account at %s', 'fajaedeseo-ai'), '<a href="https://app.valueserp.com/signup" target="_blank" rel="noopener">ValueSERP.com</a>'); 
                                            ?></li>
                                            <li><?php esc_html_e('Copy the API Key from your dashboard.', 'fajaedeseo-ai'); ?></li>
                                            <li><?php esc_html_e('Paste it here to unlock SERP Competitor Analysis.', 'fajaedeseo-ai'); ?></li>
                                        </ol>
                                    </div>
                                    <?php if (!\FajaedeSEO_Pro_License::has_feature('advanced_serp')): ?>
                                        <p style="color: #d63638; font-weight: bold; margin-top: 10px;">
                                            <?php esc_html_e('Requires a Premium or Agency License to activate.', 'fajaedeseo-ai'); ?>
                                        </p>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            
                            <tr>
                                <th scope="row">
                                    <label for="fajaedeseo_openai_image_model"><?php esc_html_e('OpenAI Image Model', 'fajaedeseo-ai'); ?></label>
                                </th>
                                <td>
                                    <input 
                                        type="text" 
                                        id="fajaedeseo_openai_image_model" 
                                        name="fajaedeseo_openai_image_model" 
                                        value="<?php echo esc_attr(get_option('fajaedeseo_openai_image_model', 'gpt-image-2-2026-04-21')); ?>"
                                        class="regular-text"
                                    />
                                    <p class="description">
                                        <?php 
                                        /* translators: %s: Default image model code */
                                        echo sprintf(esc_html__('The OpenAI image model to use for image generation (default: %s).', 'fajaedeseo-ai'), '<code>gpt-image-2-2026-04-21</code>'); 
                                        ?>
                                    </p>
                                </td>
                            </tr>

                            <tr>
                                <th scope="row">
                                    <label for="fajaedeseo_ai_cache_ttl"><?php esc_html_e('Cache Duration (seconds)', 'fajaedeseo-ai'); ?></label>
                                </th>
                                <td>
                                    <input 
                                        type="number" 
                                        id="fajaedeseo_ai_cache_ttl" 
                                        name="fajaedeseo_ai_cache_ttl" 
                                        value="<?php echo esc_attr(get_option('fajaedeseo_ai_cache_ttl', 3600)); ?>"
                                        min="300"
                                        step="300"
                                    />
                                    <p class="description">
                                        <?php esc_html_e('How long to cache AI responses (minimum 5 minutes). Reduces server load.', 'fajaedeseo-ai'); ?>
                                    </p>
                                </td>
                            </tr>
                        </table>
                    
                    <?php submit_button(__('Save Settings', 'fajaedeseo-ai')); ?>
                </div>
            </form>
            
            <!-- AI Bulk Actions -->
            <div class="fajaedeseo-ai-card">
                <h2><?php esc_html_e('AI Bulk Actions', 'fajaedeseo-ai'); ?></h2>
                <?php if (\FajaedeSEO_Pro_License::has_feature('bulk_actions')) : ?>
                    <p><?php esc_html_e('Generate meta titles and descriptions for multiple posts at once.', 'fajaedeseo-ai'); ?></p>
                <div class="notice notice-info inline" style="margin-left: 0; margin-bottom: 15px;">
                    <p><strong>💡 Tip:</strong> <?php esc_html_e('Select a maximum of 10 to 20 pages at a time to prevent server timeouts and ensure the highest quality AI generation.', 'fajaedeseo-ai'); ?></p>
                </div>
                    <table class="form-table">
                        <tr>
                        <th scope="row"><label for="fajaedeseo_bulk_post_selector"><?php esc_html_e('Select Posts', 'fajaedeseo-ai'); ?></label></th>
                            <td>
                            <div id="fajaedeseo-bulk-post-selector" style="max-height: 250px; overflow-y: auto; border: 1px solid #ddd; padding: 10px; background: #fff;">
                                <?php if (!empty($recent_posts)) : ?>
                                    <?php foreach ($recent_posts as $p) : ?>
                                        <label style="display: block; margin-bottom: 5px; font-size: 13px;">
                                            <input type="checkbox" class="fajaedeseo-bulk-post-id" value="<?php echo esc_attr($p->ID); ?>">
                                            <?php echo esc_html($p->post_title); ?> <span style="color: #888;">(ID: <?php echo esc_html($p->ID); ?>)</span>
                                        </label>
                                    <?php endforeach; ?>
                                <?php else : ?>
                                    <p><?php esc_html_e('No posts found.', 'fajaedeseo-ai'); ?></p>
                                <?php endif; ?>
                            </div>
                            <p class="description"><?php esc_html_e('Select the posts for which you want to generate meta data.', 'fajaedeseo-ai'); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php esc_html_e('Meta Types', 'fajaedeseo-ai'); ?></th>
                            <td>
                                <label>
                                    <input type="checkbox" id="fajaedeseo_bulk_meta_title" value="title" checked> <?php esc_html_e('Generate Title', 'fajaedeseo-ai'); ?>
                                </label><br>
                                <label>
                                    <input type="checkbox" id="fajaedeseo_bulk_meta_description" value="description" checked> <?php esc_html_e('Generate Description', 'fajaedeseo-ai'); ?>
                                </label>
                                <br>
                                <label>
                                    <input type="checkbox" id="fajaedeseo_bulk_meta_keywords" value="keywords" checked> <?php esc_html_e('Generate Keywords', 'fajaedeseo-ai'); ?>
                                </label>
                            </td>
                        </tr>
                    </table>
                    <button class="button button-primary" id="btn-bulk-generate-meta"><?php esc_html_e('Start Bulk Generation', 'fajaedeseo-ai'); ?></button>
                    <div id="bulk-generation-results" style="margin-top: 20px; max-height: 300px; overflow-y: auto; background: #f9f9f9; padding: 10px; border: 1px solid #eee; display: none;"></div>
                <?php else : ?>
                    <div class="notice notice-warning">
                        <p><strong>🔒 <?php esc_html_e('Bulk Actions:', 'fajaedeseo-ai'); ?></strong> <?php esc_html_e('Requires a Premium License to activate.', 'fajaedeseo-ai'); ?></p>
                        <p><?php esc_html_e('Upgrade to Premium to generate meta titles and descriptions for multiple posts at once.', 'fajaedeseo-ai'); ?></p>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Test Tools -->
            <div class="fajaedeseo-ai-card">
                <h2><?php esc_html_e('Test Tools', 'fajaedeseo-ai'); ?></h2>
                <p><?php esc_html_e('Test your AI API connection', 'fajaedeseo-ai'); ?></p>
                
                <div class="test-tools">
                    <button class="button button-primary" id="btn-test-health"><?php esc_html_e('Test Health', 'fajaedeseo-ai'); ?></button>
                    <button class="button" id="btn-test-title"><?php esc_html_e('Test Title Generation', 'fajaedeseo-ai'); ?></button>
                    <button class="button" id="btn-test-keywords"><?php esc_html_e('Test Keywords', 'fajaedeseo-ai'); ?></button>
                    <button class="button" id="btn-clear-cache"><?php esc_html_e('Clear AI Cache', 'fajaedeseo-ai'); ?></button>
                </div>
                
                <div id="test-result" class="test-result" style="display: none;">
                    <pre id="test-result-content"></pre>
                </div>
            </div>
            
            <style>
                .fajaedeseo-ai-card {
                    background: white;
                    border: 1px solid #ccc;
                    border-radius: 5px;
                    padding: 20px;
                    margin: 20px 0;
                    box-shadow: 0 1px 1px rgba(0,0,0,.04);
                }
                
                .status-info {
                    display: grid;
                    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
                    gap: 20px;
                    margin: 15px 0;
                }
                
                .status-item {
                    padding: 10px;
                    background: #f5f5f5;
                    border-radius: 3px;
                }
                
                .status-item .status-item-label {
                    display: block;
                    font-weight: bold;
                    margin-bottom: 5px;
                    color: #333;
                }
                
                .status-badge {
                    display: inline-block;
                    padding: 5px 10px;
                    border-radius: 3px;
                    font-weight: bold;
                    font-size: 12px;
                }
                
                .status-badge.healthy {
                    background: #28a745;
                    color: white;
                }
                
                .status-badge.unhealthy {
                    background: #dc3545;
                    color: white;
                }
                
                .test-tools {
                    margin: 15px 0;
                }
                
                .test-tools button {
                    margin-right: 10px;
                    margin-bottom: 10px;
                }
                
                .test-result {
                    background: #f5f5f5;
                    border: 1px solid #ddd;
                    border-radius: 3px;
                    padding: 10px;
                    margin-top: 10px;
                    max-height: 400px;
                    overflow-y: auto;
                }
                
                .test-result pre {
                    margin: 0;
                    font-size: 12px;
                }
            </style>
        </div>
        <?php
    }
}

// AJAX endpoints for testing
add_action('wp_ajax_fajaedeseo_test_health', function() {
    check_ajax_referer('fajaedeseo_ai_nonce', 'nonce');
    
    if (!current_user_can('manage_options')) {
        wp_send_json_error('Unauthorized');
    }
    
    // Force health check to bypass cache
    $is_healthy = \FajaedeSEO_AI_Service_Manager::check_health(true);
    $error = get_option('fajaedeseo_last_ai_error');

    wp_send_json_success([
        'healthy' => $is_healthy,
        'message' => $is_healthy ? __('✓ Service is healthy', 'fajaedeseo-ai') : __('✗ Service is unreachable: ', 'fajaedeseo-ai') . $error,
    ]);
});

add_action('wp_ajax_fajaedeseo_test_title', function() {
    check_ajax_referer('fajaedeseo_ai_nonce', 'nonce');
    
    if (!current_user_can('manage_options')) {
        wp_send_json_error('Unauthorized');
    }
    
    $result = \FajaedeSEO_Module_SEO::generate_title(
        'This is a test post about WordPress SEO optimization and best practices.',
        'WordPress SEO Guide',
        get_bloginfo('name')
    );
    
    wp_send_json_success([
        'title' => $result,
        'message' => __('Generated title successfully', 'fajaedeseo-ai'),
    ]);
});

add_action('wp_ajax_fajaedeseo_test_keywords', function() {
    check_ajax_referer('fajaedeseo_ai_nonce', 'nonce');
    
    if (!current_user_can('manage_options')) {
        wp_send_json_error('Unauthorized');
    }
    
    $keywords = \FajaedeSEO_Module_Keywords::extract_focus_keywords(
        'This is a test content about WordPress SEO optimization, keywords research, and content strategy.',
        5
    );
    
    wp_send_json_success([
        'keywords' => $keywords,
        'message' => __('Extracted keywords successfully', 'fajaedeseo-ai'),
    ]);
});

add_action('wp_ajax_fajaedeseo_clear_cache', function() {
    check_ajax_referer('fajaedeseo_ai_nonce', 'nonce');
    
    if (!current_user_can('manage_options')) {
        wp_send_json_error('Unauthorized');
    }
    
    \FajaedeSEO_AI_Service_Manager::clear_cache();
    wp_send_json_success([
        'message' => __('AI cache cleared successfully', 'fajaedeseo-ai'),
    ]);
});
