<?php
/**
 * AI Provider Settings UI
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Thoát nếu truy cập trực tiếp

// AJAX handler for saving AI provider settings
add_action('wp_ajax_save_ai_provider_settings', function() {
    check_ajax_referer('ai_provider_settings', 'nonce');
    
    if (!current_user_can('manage_options')) {
        wp_send_json_error(array('message' => 'Permission denied'));
    }
    
    $provider_id = isset($_POST['provider_id']) ? sanitize_text_field($_POST['provider_id']) : '';
    $model = isset($_POST['model']) ? sanitize_text_field($_POST['model']) : '';
    $routing_mode = isset($_POST['routing_mode']) ? sanitize_text_field($_POST['routing_mode']) : 'single';
    $routing_mode = in_array($routing_mode, array('single', 'rotate'), true) ? $routing_mode : 'single';
    
    if ($routing_mode === 'single' && empty($provider_id)) {
        wp_send_json_error(array('message' => 'Provider ID is required'));
    }
    
    $manager = AIAutotool_AI_Provider_Manager::get_instance();
    if (method_exists($manager, 'set_provider_routing_mode')) {
        $manager->set_provider_routing_mode($routing_mode);
    }
    
    if (!empty($provider_id) && !$manager->set_active_provider($provider_id)) {
        wp_send_json_error(array('message' => 'Invalid provider'));
    }
    
    if (!empty($model)) {
        $manager->set_active_model($model);
    }
    
    
    wp_send_json_success(array(
        'message' => $routing_mode === 'rotate' ? 'AI Provider routing set to rotate available providers.' : 'AI Provider settings saved successfully!',
        'provider_id' => $provider_id,
        'model' => $model,
        'routing_mode' => $routing_mode
    ));
});

// AJAX handler for testing AI provider
// NOTE: This handler has been moved to AIAutotool_AI_Provider_Settings_UI class (aiautotool_ai_provider_settings_ui.php)
// The new handler includes full response with model info, usage stats, and AI response content
// Commenting out to avoid conflicts
/*
add_action('wp_ajax_test_ai_provider', function() {
    check_ajax_referer('ai_provider_settings', 'nonce');
    
    if (!current_user_can('manage_options')) {
        wp_send_json_error(array('message' => 'Permission denied'));
    }
    
    $provider_id = isset($_POST['provider_id']) ? sanitize_text_field($_POST['provider_id']) : '';
    
    if (empty($provider_id)) {
        wp_send_json_error(array('message' => 'Provider ID is required'));
    }
    
    $manager = AIAutotool_AI_Provider_Manager::get_instance();
    $provider = $manager->get_provider($provider_id);
    
    if (!$provider) {
        wp_send_json_error(array('message' => 'Provider not found'));
    }
    
    if (!$provider->is_configured()) {
        wp_send_json_error(array('message' => 'Provider not configured. Please set API key first.'));
    }
    
    $result = $provider->test_connection();
    
    if ($result['success']) {
        wp_send_json_success(array('message' => $result['message']));
    } else {
        wp_send_json_error(array('message' => $result['message']));
    }
});
*/

// Render settings section
if (!function_exists('render_ai_provider_settings_section')) {
    function render_ai_provider_settings_section() {
        $manager = AIAutotool_AI_Provider_Manager::get_instance();
        $providers_info = $manager->get_providers_info();
        $active_provider = $manager->get_active_provider();
        $active_provider_id = $active_provider ? $active_provider->get_id() : '';
        $active_model = $manager->get_active_model();
        
        ?>
        <div class="aiautotool-ai-provider-settings" style="margin-top: 30px; border-top: 2px solid #e0e0e0; padding-top: 30px;">
            <h3>🤖 <?php _e('AI Provider & Model Selection', 'ai-auto-tool'); ?></h3>
            <p class="description">
                <?php _e('Choose which AI provider and model to use across the entire plugin. This ensures consistent AI responses throughout all features.', 'ai-auto-tool'); ?>
            </p>
            
            <table class="form-table">
                <tr>
                    <th scope="row">
                        <?php _e('AI Provider', 'ai-auto-tool'); ?>
                    </th>
                    <td>
                        <select id="aiautotool_ai_provider" name="aiautotool_ai_provider" class="regular-text" style="min-width: 300px;">
                            <option value=""><?php _e('-- Select Provider --', 'ai-auto-tool'); ?></option>
                            <?php foreach ($providers_info as $id => $info): ?>
                                <option value="<?php echo esc_attr($id); ?>" 
                                        <?php selected($active_provider_id, $id); ?>
                                        <?php echo $info['configured'] ? '' : 'disabled'; ?>>
                                    <?php echo esc_html($info['name']); ?>
                                    <?php if (!$info['configured']): ?>
                                        (<?php _e('Not Configured', 'ai-auto-tool'); ?>)
                                    <?php else: ?>
                                        ✓
                                    <?php endif; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        
                        <button type="button" id="test_ai_provider" class="button button-secondary" style="margin-left: 10px;">
                            🔌 <?php _e('Test Connection', 'ai-auto-tool'); ?>
                        </button>
                        
                        <p class="description">
                            <?php _e('Select the AI provider to use. Make sure to configure API keys in the "API Keys Manager" tab first.', 'ai-auto-tool'); ?>
                            <br>
                            <strong><?php _e('Recommendation:', 'ai-auto-tool'); ?></strong>
                            <?php _e('Pollinations.ai is FREE and offers excellent models. Perfect for getting started!', 'ai-auto-tool'); ?>
                        </p>
                        
                        <!-- Provider Status -->
                        <div id="provider_status" style="margin-top: 10px;">
                            <?php if ($active_provider): ?>
                                <span style="color: green;">
                                    ✓ <?php echo sprintf(__('Active: %s', 'ai-auto-tool'), $active_provider->get_name()); ?>
                                </span>
                            <?php else: ?>
                                <span style="color: orange;">
                                    ⚠️ <?php _e('No active provider. Please select and configure one.', 'ai-auto-tool'); ?>
                                </span>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                
                <tr>
                    <th scope="row">
                        <?php _e('AI Model', 'ai-auto-tool'); ?>
                    </th>
                    <td>
                        <select id="aiautotool_ai_model" name="aiautotool_ai_model" class="regular-text" style="min-width: 300px;">
                            <option value=""><?php _e('-- Select Model --', 'ai-auto-tool'); ?></option>
                        </select>
                        
                        <p class="description" id="model_description">
                            <?php _e('Select the AI model to use. Different models have different capabilities and speeds.', 'ai-auto-tool'); ?>
                        </p>
                        
                        <!-- Model recommendations -->
                        <div id="model_recommendations" style="margin-top: 10px; padding: 10px; background: #f0f8ff; border-left: 3px solid #2196F3; display: none;">
                            <p style="margin: 0; font-size: 13px;"></p>
                        </div>
                    </td>
                </tr>
            </table>
            
            <p class="submit">
                <button type="button" id="save_ai_provider_settings" class="button button-primary">
                    💾 <?php _e('Save AI Provider Settings', 'ai-auto-tool'); ?>
                </button>
                <span class="spinner" style="float: none; margin: 0 10px;"></span>
                <span class="save-message-provider"></span>
            </p>
            
            <!-- Provider Comparison Table -->
            <div style="margin-top: 30px;">
                <h4><?php _e('Provider Comparison', 'ai-auto-tool'); ?></h4>
                <table class="wp-list-table widefat fixed striped" style="margin-top: 10px;">
                    <thead>
                        <tr>
                            <th><?php _e('Provider', 'ai-auto-tool'); ?></th>
                            <th><?php _e('Status', 'ai-auto-tool'); ?></th>
                            <th><?php _e('Cost', 'ai-auto-tool'); ?></th>
                            <th><?php _e('Models', 'ai-auto-tool'); ?></th>
                            <th><?php _e('Best For', 'ai-auto-tool'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($providers_info as $id => $info): ?>
                            <tr>
                                <td><strong><?php echo esc_html($info['name']); ?></strong></td>
                                <td>
                                    <?php if ($info['configured']): ?>
                                        <span style="color: green;">✓ <?php _e('Configured', 'ai-auto-tool'); ?></span>
                                    <?php else: ?>
                                        <span style="color: red;">✗ <?php _e('Not Configured', 'ai-auto-tool'); ?></span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php 
                                    if ($id === 'llm7') {
                                        echo '<span style="color: green; font-weight: bold;">FREE</span>';
                                    } elseif ($id === 'gemini') {
                                        echo __('Free tier + Paid', 'ai-auto-tool');
                                    } else {
                                        echo __('Paid', 'ai-auto-tool');
                                    }
                                    ?>
                                </td>
                                <td><?php echo count($info['models']); ?>+ models</td>
                                <td>
                                    <?php 
                                    if ($id === 'llm7') {
                                        echo __('Cost-free testing & production', 'ai-auto-tool');
                                    } elseif ($id === 'gemini') {
                                        echo __('Fast responses & multimodal', 'ai-auto-tool');
                                    } else {
                                        echo __('Most advanced capabilities', 'ai-auto-tool');
                                    }
                                    ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        
        <script>
        jQuery(document).ready(function($) {
            var providersData = <?php echo json_encode($providers_info); ?>;
            var currentProvider = '<?php echo esc_js($active_provider_id); ?>';
            var currentModel = '<?php echo esc_js($active_model); ?>';
            
            // Model recommendations
            var modelRecommendations = {
                'openai': '💡 GPT-4o-mini is recommended for most tasks - fast and cost-effective.',
                'gemini': '💡 Gemini 1.5 Flash is recommended for speed. Use Pro for complex tasks.',
                'llm7': '💡 DeepSeek v3.1 is recommended for reasoning tasks. Use Codestral for coding.'
            };
            
            // Update models dropdown when provider changes
            function updateModelsDropdown(providerId) {
                var $modelSelect = $('#aiautotool_ai_model');
                $modelSelect.html('<option value="">-- Select Model --</option>');
                
                if (!providerId || !providersData[providerId]) {
                    return;
                }
                
                var provider = providersData[providerId];
                var models = provider.models;
                
                $.each(models, function(modelId, modelName) {
                    var selected = (modelId === currentModel || modelId === provider.default_model);
                    $modelSelect.append(
                        $('<option></option>')
                            .val(modelId)
                            .text(modelName)
                            .prop('selected', selected)
                    );
                });
                
                // Show recommendations
                if (modelRecommendations[providerId]) {
                    $('#model_recommendations p').text(modelRecommendations[providerId]);
                    $('#model_recommendations').show();
                } else {
                    $('#model_recommendations').hide();
                }
            }
            
            // Initialize
            if (currentProvider) {
                updateModelsDropdown(currentProvider);
            }
            
            // Provider change event
            $('#aiautotool_ai_provider').on('change', function() {
                var providerId = $(this).val();
                updateModelsDropdown(providerId);
                currentProvider = providerId;
            });
            
            // Save settings
            $('#save_ai_provider_settings').on('click', function() {
                var $button = $(this);
                var $spinner = $button.next('.spinner');
                var $message = $('.save-message-provider');
                
                var providerId = $('#aiautotool_ai_provider').val();
                var model = $('#aiautotool_ai_model').val();
                
                if (!providerId) {
                    alert('Please select a provider');
                    return;
                }
                
                $button.prop('disabled', true);
                $spinner.addClass('is-active');
                $message.html('');
                
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'save_ai_provider_settings',
                        nonce: '<?php echo wp_create_nonce('ai_provider_settings'); ?>',
                        provider_id: providerId,
                        model: model
                    },
                    success: function(response) {
                        $spinner.removeClass('is-active');
                        $button.prop('disabled', false);
                        
                        if (response.success) {
                            $message.html('<span style="color: green;">✓ ' + response.data.message + '</span>');
                            
                            // Update provider status
                            var providerName = providersData[providerId].name;
                            $('#provider_status').html('<span style="color: green;">✓ Active: ' + providerName + '</span>');
                        } else {
                            $message.html('<span style="color: red;">✗ ' + response.data.message + '</span>');
                        }
                        
                        setTimeout(function() { $message.html(''); }, 5000);
                    },
                    error: function() {
                        $spinner.removeClass('is-active');
                        $button.prop('disabled', false);
                        $message.html('<span style="color: red;">✗ Error saving settings</span>');
                    }
                });
            });
            
            // Test connection
            $('#test_ai_provider').on('click', function() {
                var $button = $(this);
                var providerId = $('#aiautotool_ai_provider').val();
                
                if (!providerId) {
                    alert('Please select a provider first');
                    return;
                }
                
                $button.prop('disabled', true).text('⏳ Testing...');
                
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'test_ai_provider',
                        nonce: '<?php echo wp_create_nonce('ai_provider_settings'); ?>',
                        provider_id: providerId
                    },
                    success: function(response) {
                        $button.prop('disabled', false).text('🔌 Test Connection');
                        
                        if (response.success) {
                            alert('✅ ' + response.data.message);
                        } else {
                            alert('❌ ' + response.data.message);
                        }
                    },
                    error: function() {
                        $button.prop('disabled', false).text('🔌 Test Connection');
                        alert('❌ Connection test failed');
                    }
                });
            });
        });
        </script>
        
        <style>
        .aiautotool-ai-provider-settings select {
            font-size: 14px;
        }
        .aiautotool-ai-provider-settings .wp-list-table th {
            font-weight: 600;
        }
        </style>
        <?php
    }
}
