<?php
/**
 * ==========================
 * 🔐 IGNY8 FILE RULE HEADER
 * ==========================
 * @file         : integration.php
 * @location     : /modules/settings/integration.php
 * @type         : Admin Page
 * @scope        : Module Only
 * @allowed      : API integration, connection management, external service settings
 * @reusability  : Single Use
 * @notes        : API integration settings page for settings module
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Start output buffering
ob_start();

?>
<!-- API Integration Section -->
<div class="igny8-dashboard-section">
    <div class="igny8-standard-header">
        <div class="igny8-card-header-content">
            <div class="igny8-card-title-text">
                <h3>API Integration</h3>
                <p class="igny8-card-subtitle">Configure external API connections and integrations</p>
            </div>
            <div class="igny8-card-icon">
                <span class="dashicons dashicons-admin-site igny8-dashboard-icon-lg igny8-dashboard-icon-blue"></span>
            </div>
        </div>
    </div>
    
    <!-- API Services Grid -->
    <div class="igny8-grid-2 igny8-dashboard-section" style="display: flex; flex-direction: row;">
        
        <!-- OpenAI API Card -->
        <div class="igny8-card">
            <div class="igny8-standard-header">
                <div class="igny8-card-header-content">
                    <div class="igny8-card-title-text">
                        <h3>OpenAI API</h3>
                        <p class="igny8-card-subtitle">AI-powered content generation and analysis</p>
                    </div>
                    <div class="igny8-card-icon">
                        <span class="dashicons dashicons-admin-site igny8-dashboard-icon-lg igny8-dashboard-icon-green"></span>
                    </div>
                </div>
            </div>
            <div class="igny8-card-body">
        <form method="post" action="options.php">
            <?php settings_fields('igny8_api_settings'); ?>
            <table class="form-table">
                <tr>
                    <th scope="row">
                        <label for="igny8_api_key">OpenAI API Key</label>
                    </th>
                    <td>
                        <input type="password" name="igny8_api_key" id="igny8_api_key" value="<?php echo esc_attr(get_option('igny8_api_key', '')); ?>" class="regular-text" />
                        <p class="description">Your OpenAI API key for DALL-E 3 image generation and text AI features.</p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="igny8_runware_api_key">Runware API Key</label>
                    </th>
                    <td>
                        <input type="password" name="igny8_runware_api_key" id="igny8_runware_api_key" value="<?php echo esc_attr(get_option('igny8_runware_api_key', '')); ?>" class="regular-text" />
                        <p class="description">Your Runware API key for high-quality image generation. <a href="https://runware.com" target="_blank">Get your API key here</a>.</p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label>AI Model</label>
                    </th>
                    <td>
                        <fieldset>
                            <label style="display: block; margin-bottom: 10px;">
                                <input type="radio" name="igny8_model" value="gpt-4.1" <?php checked(get_option('igny8_model', 'gpt-4.1'), 'gpt-4.1'); ?> />
                                <strong>GPT-4.1</strong> — $2.00 / $8.00 per 1M tokens<br>
                                <span style="color: #666; font-size: 12px;">Content creation, coding, analysis, high-quality content generation</span>
                            </label>
                            <label style="display: block; margin-bottom: 10px;">
                                <input type="radio" name="igny8_model" value="gpt-4o-mini" <?php checked(get_option('igny8_model', 'gpt-4.1'), 'gpt-4o-mini'); ?> />
                                <strong>GPT-4o mini</strong> — $0.15 / $0.60 per 1M tokens<br>
                                <span style="color: #666; font-size: 12px;">Bulk tasks, lightweight AI, cost-effective for high-volume operations</span>
                            </label>
                            <label style="display: block;">
                                <input type="radio" name="igny8_model" value="gpt-4o" <?php checked(get_option('igny8_model', 'gpt-4.1'), 'gpt-4o'); ?> />
                                <strong>GPT-4o</strong> — $2.50 / $10.00 per 1M tokens<br>
                                <span style="color: #666; font-size: 12px;">Advanced AI for general and multimodal tasks, faster than GPT-4.1</span>
                            </label>
                        </fieldset>
                        <p class="description">Select the AI model to use for content generation. Pricing shown per 1M tokens.</p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">Image Generation Service</th>
                    <td>
                        <fieldset>
                            <label style="display: block; margin-bottom: 10px;">
                                <input type="radio" name="igny8_image_service" value="openai" <?php checked(get_option('igny8_image_service', 'openai'), 'openai'); ?> />
                                <strong>OpenAI</strong> — Multiple models available<br>
                                <span style="color: #666; font-size: 12px;">High-quality image generation with OpenAI's models</span>
                            </label>
                            <label style="display: block;">
                                <input type="radio" name="igny8_image_service" value="runware" <?php checked(get_option('igny8_image_service', 'openai'), 'runware'); ?> />
                                <strong>Runware</strong> — $0.009 per image<br>
                                <span style="color: #666; font-size: 12px;">High-quality AI image generation with Runware's models</span>
                            </label>
                        </fieldset>
                        <p class="description">Select the image generation service to use. Each service requires its own API key.</p>
                    </td>
                </tr>
                <tr id="igny8-openai-models-row" style="display: none;">
                    <th scope="row">OpenAI Image Model</th>
                    <td>
                        <fieldset>
                            <label style="display: block; margin-bottom: 10px;">
                                <input type="radio" name="igny8_image_model" value="dall-e-3" <?php checked(get_option('igny8_image_model', 'dall-e-3'), 'dall-e-3'); ?> />
                                <strong>DALL·E 3</strong> — $0.040 per image<br>
                                <span style="color: #666; font-size: 12px;">High-quality image generation with advanced AI capabilities</span>
                            </label>
                            <label style="display: block; margin-bottom: 10px;">
                                <input type="radio" name="igny8_image_model" value="dall-e-2" <?php checked(get_option('igny8_image_model', 'dall-e-3'), 'dall-e-2'); ?> />
                                <strong>DALL·E 2</strong> — $0.020 per image<br>
                                <span style="color: #666; font-size: 12px;">Cost-effective image generation with good quality</span>
                            </label>
                            <label style="display: block; margin-bottom: 10px;">
                                <input type="radio" name="igny8_image_model" value="gpt-image-1" <?php checked(get_option('igny8_image_model', 'dall-e-3'), 'gpt-image-1'); ?> />
                                <strong>GPT Image 1 (Full)</strong> — $0.042 per image<br>
                                <span style="color: #666; font-size: 12px;">Full-featured image generation with comprehensive capabilities</span>
                            </label>
                            <label style="display: block;">
                                <input type="radio" name="igny8_image_model" value="gpt-image-1-mini" <?php checked(get_option('igny8_image_model', 'dall-e-3'), 'gpt-image-1-mini'); ?> />
                                <strong>GPT Image 1 Mini</strong> — $0.011 per image<br>
                                <span style="color: #666; font-size: 12px;">Lightweight, cost-effective image generation for bulk operations</span>
                            </label>
                        </fieldset>
                        <p class="description">Select the OpenAI image model to use. Pricing shown per image.</p>
                    </td>
                </tr>
                <tr id="igny8-runware-models-row" style="display: none;">
                    <th scope="row">Runware Image Model</th>
                    <td>
                        <fieldset>
                            <label style="display: block;">
                                <input type="radio" name="igny8_runware_model" value="runware:97@1" <?php checked(get_option('igny8_runware_model', 'runware:97@1'), 'runware:97@1'); ?> />
                                <strong>HiDream-I1 Full</strong> — $0.009 per image<br>
                                <span style="color: #666; font-size: 12px;">High-quality AI image generation with Runware's HiDream model</span>
                            </label>
                        </fieldset>
                        <p class="description">Select the Runware image model to use. Pricing shown per image.</p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">API Validation</th>
                    <td>
                        <div id="igny8-openai-validation" style="display: none;">
                            <button type="button" id="igny8-test-api" class="button">Test OpenAI Connection</button>
                            <button type="button" id="igny8-test-response" class="button">Test OpenAI Response (Ping)</button>
                        </div>
                        <div id="igny8-runware-validation" style="display: none;">
                            <button type="button" id="igny8-test-runware-btn" class="button">Test Runware Connection</button>
                            <div id="igny8-runware-test-result" style="margin-top: 10px;"></div>
                        </div>
                        <div id="igny8-api-test-result" style="margin-top: 10px;"></div>
                    </td>
                </tr>
            </table>
            <?php submit_button('Save API Settings'); ?>
        </form>
            </div>
        </div>

        <!-- Google Search Console API Card -->
        <div class="igny8-card">
            <div class="igny8-standard-header">
                <div class="igny8-card-header-content">
                    <div class="igny8-card-title-text">
                        <h3>Google Search Console API</h3>
                        <p class="igny8-card-subtitle">Search performance and ranking data integration</p>
                    </div>
                    <div class="igny8-card-icon">
                        <span class="dashicons dashicons-chart-bar igny8-dashboard-icon-lg igny8-dashboard-icon-orange"></span>
                    </div>
                </div>
            </div>
            <div class="igny8-card-body">
                <div style="background: rgba(255, 193, 7, 0.1); border: 1px solid var(--amber); border-radius: var(--radius); padding: 16px; margin-bottom: 20px;">
                    <div style="display: flex; align-items: center; gap: 12px;">
                        <span style="font-size: 24px;">⚠️</span>
                        <div>
                            <strong style="color: var(--amber-dark);">Coming Soon</strong><br>
                            <span style="color: var(--text-dim); font-size: 14px;">
                                Google Search Console API integration is currently in development. 
                                This will provide search performance data and ranking insights.
                            </span>
                        </div>
                    </div>
                </div>
                
                <div style="color: var(--text-dim); margin-bottom: 16px;">
                    <strong>Planned Features:</strong>
                    <ul style="margin: 8px 0; padding-left: 20px;">
                        <li>Search performance metrics</li>
                        <li>Keyword ranking data</li>
                        <li>Click-through rate analysis</li>
                        <li>Search appearance insights</li>
                    </ul>
                </div>
                
                <div style="text-align: center; padding: 20px; background: var(--bg-light); border-radius: var(--radius);">
                    <span style="color: var(--text-dim); font-size: 14px;">
                        Integration will be available in a future update
                    </span>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- API Request Logs Section -->
<div class="igny8-dashboard-section">
    <div class="igny8-standard-header">
        <div class="igny8-card-header-content">
            <div class="igny8-card-title-text">
                <h3>API Request Logs</h3>
                <p class="igny8-card-subtitle">Monitor API usage and performance metrics</p>
            </div>
            <div class="igny8-card-icon">
                <span class="dashicons dashicons-chart-line igny8-dashboard-icon-lg igny8-dashboard-icon-purple"></span>
            </div>
        </div>
    </div>
    
    <div class="igny8-card">
        <div class="igny8-card-body">
            <div id="igny8-api-logs-container">
            <div class="tablenav top">
                <div class="alignleft actions">
                    <button type="button" id="igny8-refresh-logs" class="button">Refresh Logs</button>
                    <button type="button" id="igny8-clear-logs" class="button">Clear Logs</button>
                </div>
                <div class="alignright actions">
                    <span class="displaying-num">
                        <span id="igny8-logs-count">0</span> API calls
                    </span>
                </div>
            </div>
            
            <table class="widefat fixed striped" id="igny8-api-logs">
                <thead>
                    <tr>
                        <th>Timestamp</th>
                        <th>Status</th>
                        <th>Model</th>
                        <th>Tokens (In/Out)</th>
                        <th>Cost</th>
                        <th>API ID</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    global $wpdb;
                    $logs = $wpdb->get_results("
                        SELECT * FROM {$wpdb->prefix}igny8_logs 
                        WHERE source = 'openai_api' 
                        ORDER BY created_at DESC 
                        LIMIT 20
                    ");
                    
                    if ($logs) {
                        foreach ($logs as $log) {
                            $context = json_decode($log->context, true);
                            $status_class = $log->status === 'success' ? 'success' : 'error';
                            $status_icon = $log->status === 'success' ? '✅' : '❌';
                            
                            // Debug logging for cost display
                            error_log("Igny8 Display Debug: Log ID=" . $log->id . ", total_cost=" . ($context['total_cost'] ?? 'null') . ", formatted=" . igny8_format_cost($context['total_cost'] ?? 0));
                            
                            echo "<tr>
                                <td>" . esc_html($log->created_at) . "</td>
                                <td><span class='igny8-status {$status_class}'>{$status_icon} " . esc_html($log->status) . "</span></td>
                                <td>" . esc_html($context['model'] ?? 'Unknown') . "</td>
                                <td>" . intval($context['input_tokens'] ?? 0) . " / " . intval($context['output_tokens'] ?? 0) . "</td>
                                <td>" . igny8_format_cost($context['total_cost'] ?? 0) . "</td>
                                <td>" . esc_html($log->api_id ? substr($log->api_id, 0, 12) . '...' : 'N/A') . "</td>
                            </tr>";
                        }
                    } else {
                        echo '<tr><td colspan="6">No API logs found.</td></tr>';
                    }
                    ?>
                </tbody>
            </table>
        </div>
    </div>
    </div>

<!-- Image Request Logs Section -->
<div class="igny8-dashboard-section">
    <div class="igny8-standard-header">
        <div class="igny8-card-header-content">
            <div class="igny8-card-title-text">
                <h3>Image Request Logs</h3>
                <p class="igny8-card-subtitle">Monitor AI image generation requests and performance</p>
            </div>
            <div class="igny8-card-icon">
                <span class="dashicons dashicons-format-image igny8-dashboard-icon-lg igny8-dashboard-icon-teal"></span>
            </div>
        </div>
    </div>
    
    <div class="igny8-card">
        <div class="igny8-card-body">
            <div id="igny8-image-logs-container">
            <div class="tablenav top">
                <div class="alignleft actions">
                    <button type="button" id="igny8-refresh-image-logs" class="button">Refresh Logs</button>
                    <button type="button" id="igny8-clear-image-logs" class="button">Clear Logs</button>
                </div>
                <div class="alignright actions">
                    <span class="displaying-num">
                        <span id="igny8-image-logs-count">0</span> image requests
                    </span>
                </div>
            </div>
            
            <table class="widefat fixed striped" id="igny8-image-logs">
                <thead>
                    <tr>
                        <th>Timestamp</th>
                        <th>Status</th>
                        <th>Model</th>
                        <th>Prompt Length</th>
                        <th>Cost</th>
                        <th>Image Size</th>
                        <th>API ID</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $image_logs = $wpdb->get_results("
                        SELECT * FROM {$wpdb->prefix}igny8_logs 
                        WHERE source = 'openai_image' 
                        ORDER BY created_at DESC 
                        LIMIT 20
                    ");
                    
                    if ($image_logs) {
                        foreach ($image_logs as $log) {
                            $context = json_decode($log->context, true);
                            $status_class = $log->status === 'success' ? 'success' : 'error';
                            $status_icon = $log->status === 'success' ? '✅' : '❌';
                            
                            echo "<tr>
                                <td>" . esc_html($log->created_at) . "</td>
                                <td><span class='igny8-status {$status_class}'>{$status_icon} " . esc_html($log->status) . "</span></td>
                                <td>" . esc_html($context['model'] ?? 'dall-e-3') . "</td>
                                <td>" . intval($context['prompt_length'] ?? 0) . " chars</td>
                                <td>" . igny8_format_cost($context['total_cost'] ?? 0) . "</td>
                                <td>" . esc_html($context['image_size'] ?? '1024x1024') . "</td>
                                <td>" . esc_html($log->api_id ? substr($log->api_id, 0, 12) . '...' : 'N/A') . "</td>
                            </tr>";
                        }
                    } else {
                        echo '<tr><td colspan="7">No image request logs found.</td></tr>';
                    }
                    ?>
                </tbody>
            </table>
        </div>
    </div>
    </div>

<!-- Content Engine Settings Section -->
<div class="igny8-dashboard-section">
    <div class="igny8-standard-header">
        <div class="igny8-card-header-content">
            <div class="igny8-card-title-text">
                <h3>Content Engine Settings</h3>
                <p class="igny8-card-subtitle">Personalization and content generation configuration</p>
            </div>
            <div class="igny8-card-icon">
                <span class="dashicons dashicons-admin-generic igny8-dashboard-icon-lg igny8-dashboard-icon-amber"></span>
            </div>
        </div>
    </div>
    
    <div class="igny8-card">
        <div class="igny8-card-body">
            <div style="background: rgba(59, 130, 246, 0.1); border: 1px solid var(--blue); border-radius: var(--radius); padding: 16px; margin-bottom: 20px;">
                <div style="display: flex; align-items: center; gap: 12px;">
                    <span style="font-size: 24px;">ℹ️</span>
                    <div>
                        <strong style="color: var(--blue-dark);">Settings Moved</strong><br>
                        <span style="color: var(--text-dim); font-size: 14px;">
                            Content Engine settings have been moved to the Personalize module for better organization.
                        </span>
                    </div>
                </div>
            </div>
            
            <p><strong>Note:</strong> Content Engine settings have been moved to the <a href="<?php echo admin_url('admin.php?page=igny8-personalize&sm=settings'); ?>">Personalize module</a> for better organization.</p>
            <p>Please configure personalization settings in the Personalize → Settings section.</p>
        </div>
    </div>
</div>

<!-- Third-party Integrations Section -->
<div class="igny8-dashboard-section">
    <div class="igny8-standard-header">
        <div class="igny8-card-header-content">
            <div class="igny8-card-title-text">
                <h3>Third-party Integrations</h3>
                <p class="igny8-card-subtitle">Additional SEO tools and data sources</p>
            </div>
            <div class="igny8-card-icon">
                <span class="dashicons dashicons-admin-tools igny8-dashboard-icon-lg igny8-dashboard-icon-red"></span>
            </div>
        </div>
    </div>
    
    <div class="igny8-card">
        <div class="igny8-card-body">
            <div style="background: rgba(255, 193, 7, 0.1); border: 1px solid var(--amber); border-radius: var(--radius); padding: 16px; margin-bottom: 20px;">
                <div style="display: flex; align-items: center; gap: 12px;">
                    <span style="font-size: 24px;">⚠️</span>
                    <div>
                        <strong style="color: var(--amber-dark);">Coming Soon</strong><br>
                        <span style="color: var(--text-dim); font-size: 14px;">
                            Additional third-party integrations are currently in development.
                        </span>
                    </div>
                </div>
            </div>
            
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                <div style="padding: 16px; background: var(--bg-light); border-radius: var(--radius);">
                    <h4 style="margin: 0 0 8px 0; color: var(--text-primary);">Ahrefs API</h4>
                    <p style="margin: 0; color: var(--text-dim); font-size: 14px;">Integration with Ahrefs for keyword and backlink data.</p>
                </div>
                <div style="padding: 16px; background: var(--bg-light); border-radius: var(--radius);">
                    <h4 style="margin: 0 0 8px 0; color: var(--text-primary);">SEMrush API</h4>
                    <p style="margin: 0; color: var(--text-dim); font-size: 14px;">Integration with SEMrush for competitive analysis.</p>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Handle conditional display of image model options and API validation
    const imageServiceRadios = document.querySelectorAll('input[name="igny8_image_service"]');
    const openaiModelsRow = document.getElementById('igny8-openai-models-row');
    const runwareModelsRow = document.getElementById('igny8-runware-models-row');
    const openaiValidation = document.getElementById('igny8-openai-validation');
    const runwareValidation = document.getElementById('igny8-runware-validation');
    
    function toggleServiceOptions() {
        const selectedService = document.querySelector('input[name="igny8_image_service"]:checked');
        if (selectedService) {
            if (selectedService.value === 'openai') {
                openaiModelsRow.style.display = 'table-row';
                runwareModelsRow.style.display = 'none';
                openaiValidation.style.display = 'block';
                runwareValidation.style.display = 'none';
            } else if (selectedService.value === 'runware') {
                openaiModelsRow.style.display = 'none';
                runwareModelsRow.style.display = 'table-row';
                openaiValidation.style.display = 'none';
                runwareValidation.style.display = 'block';
            }
        }
    }
    
    // Add event listeners to image service radio buttons
    imageServiceRadios.forEach(radio => {
        radio.addEventListener('change', toggleServiceOptions);
    });
    
    // Initialize display on page load
    toggleServiceOptions();
    
    const testApiButton = document.getElementById('igny8-test-api');
    const testResponseButton = document.getElementById('igny8-test-response');
    const refreshLogsButton = document.getElementById('igny8-refresh-logs');
    const clearLogsButton = document.getElementById('igny8-clear-logs');
    const refreshImageLogsButton = document.getElementById('igny8-refresh-image-logs');
    const clearImageLogsButton = document.getElementById('igny8-clear-image-logs');
    const resultDiv = document.getElementById('igny8-api-test-result');
    
    // Test API Connection (without I/O messages)
    if (testApiButton) {
        testApiButton.addEventListener('click', function() {
            testApiConnection(false);
        });
    }
    
    // Test API Response (with "test ping")
    if (testResponseButton) {
        testResponseButton.addEventListener('click', function() {
            testApiConnection(true);
        });
    }
    
    // Refresh Logs
    if (refreshLogsButton) {
        refreshLogsButton.addEventListener('click', function() {
            loadApiLogs();
        });
    }
    
    // Clear Logs
    if (clearLogsButton) {
        clearLogsButton.addEventListener('click', function() {
            clearApiLogs();
        });
    }
    
    // Refresh Image Logs
    if (refreshImageLogsButton) {
        refreshImageLogsButton.addEventListener('click', function() {
            loadImageLogs();
        });
    }
    
    // Clear Image Logs
    if (clearImageLogsButton) {
        clearImageLogsButton.addEventListener('click', function() {
            clearImageLogs();
        });
    }
    
    function testApiConnection(withResponse = false) {
        resultDiv.innerHTML = '<span style="color: blue;">Testing API connection...</span>';
        
        const formData = new FormData();
        formData.append('action', 'igny8_test_api');
        formData.append('nonce', '<?php echo wp_create_nonce('igny8_ajax_nonce'); ?>');
        formData.append('with_response', withResponse ? '1' : '0');
        
        fetch('<?php echo admin_url('admin-ajax.php'); ?>', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const modelUsed = data.data?.model_used || 'Unknown';
                const response = data.data?.response || 'No response';
                const cost = data.data?.cost || 'N/A';
                const tokens = data.data?.tokens || 'N/A';
                const tokensSent = data.data?.tokens_sent || 'N/A';
                const tokensUsed = data.data?.tokens_used || 'N/A';
                const totalTokens = data.data?.total_tokens || 'N/A';
                
                resultDiv.innerHTML = `
                    <div style="color: green; margin-bottom: 10px;">
                        ✓ API connection successful!
                    </div>
                    <div style="background: #f0f8ff; padding: 10px; border-radius: 4px; border-left: 4px solid #0073aa;">
                        <strong>Model Used:</strong> ${modelUsed}<br>
                        ${withResponse ? `<strong>Expected:</strong> "OK! Ping Received"<br><strong>Actual Response:</strong> "${response}"<br>` : ''}
                        <strong>Token Limit Sent:</strong> ${tokensSent} (from your settings)<br>
                        <strong>Tokens Used:</strong> ${tokensUsed} (input/output)<br>
                        <strong>Total Tokens:</strong> ${totalTokens}<br>
                        <strong>Cost:</strong> ${cost}
                    </div>
                `;
                
                // Refresh logs to show new entry
                setTimeout(() => loadApiLogs(), 1000);
            } else {
                const errorMessage = data.data?.message || 'Unknown error';
                const errorDetails = data.data?.details || '';
                resultDiv.innerHTML = `
                    <div style="color: red; margin-bottom: 10px;">
                        ✗ API connection failed: ${errorMessage}
                    </div>
                    ${errorDetails ? `<div style="background: #fff2f2; padding: 10px; border-radius: 4px; border-left: 4px solid #dc3232; font-size: 12px; color: #666;">
                        <strong>Details:</strong> ${errorDetails}
                    </div>` : ''}
                `;
            }
        })
        .catch(error => {
            resultDiv.innerHTML = '<span style="color: red;">✗ API connection failed: ' + error.message + '</span>';
        });
    }
    
    function loadApiLogs() {
        fetch('<?php echo admin_url('admin-ajax.php'); ?>', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                action: 'igny8_get_api_logs',
                nonce: '<?php echo wp_create_nonce('igny8_ajax_nonce'); ?>'
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const logsTable = document.querySelector('#igny8-api-logs tbody');
                const logsCount = document.getElementById('igny8-logs-count');
                
                if (logsTable) {
                    logsTable.innerHTML = data.data.html;
                }
                if (logsCount) {
                    logsCount.textContent = data.data.total;
                }
            }
        })
        .catch(error => {
            console.error('Error loading logs:', error);
        });
    }
    
    function clearApiLogs() {
        if (!confirm('Are you sure you want to clear all API logs? This action cannot be undone.')) {
            return;
        }
        
        fetch('<?php echo admin_url('admin-ajax.php'); ?>', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                action: 'igny8_clear_api_logs',
                nonce: '<?php echo wp_create_nonce('igny8_ajax_nonce'); ?>'
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                loadApiLogs();
                alert('API logs cleared successfully!');
            } else {
                alert('Error clearing logs: ' + (data.data?.message || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error clearing logs:', error);
            alert('Error clearing logs: ' + error.message);
        });
    }
    
    function loadImageLogs() {
        fetch('<?php echo admin_url('admin-ajax.php'); ?>', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                action: 'igny8_get_image_logs',
                nonce: '<?php echo wp_create_nonce('igny8_ajax_nonce'); ?>'
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const logsTable = document.querySelector('#igny8-image-logs tbody');
                const logsCount = document.getElementById('igny8-image-logs-count');
                
                if (logsTable) {
                    logsTable.innerHTML = data.data.html;
                }
                if (logsCount) {
                    logsCount.textContent = data.data.total;
                }
            }
        })
        .catch(error => {
            console.error('Error loading image logs:', error);
        });
    }
    
    function clearImageLogs() {
        if (!confirm('Are you sure you want to clear all image request logs? This action cannot be undone.')) {
            return;
        }
        
        fetch('<?php echo admin_url('admin-ajax.php'); ?>', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                action: 'igny8_clear_image_logs',
                nonce: '<?php echo wp_create_nonce('igny8_ajax_nonce'); ?>'
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                loadImageLogs();
                alert('Image request logs cleared successfully!');
            } else {
                alert('Error clearing image logs: ' + (data.data?.message || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error clearing image logs:', error);
            alert('Error clearing image logs: ' + error.message);
        });
    }
    
    // Load logs on page load
    loadApiLogs();
    loadImageLogs();
});
</script>

<style>
.igny8-status.success {
    color: #46b450;
    font-weight: bold;
}
.igny8-status.error {
    color: #dc3232;
    font-weight: bold;
}
#igny8-api-logs {
    margin-top: 15px;
}
#igny8-api-logs th {
    background: #f1f1f1;
    font-weight: bold;
}
#igny8-api-logs td {
    padding: 8px 10px;
}
</style>

