<?php
// Import Settings UI Component
if ( ! defined( 'ABSPATH' ) ) exit;
?>
<div class="blog82ai-import-settings">
    <div class="blog82ai-page-header">
        <h2>Import Settings</h2>
        <p>Configure global settings for feed imports and content processing</p>
    </div>

    <form class="blog82ai-import-settings-form" id="importSettingsForm">
        <!-- Default Import Behavior -->
        <div class="blog82ai-settings-section">
            <h3>Default Import Behavior</h3>
            
            <div class="blog82ai-form-row">
                <div class="blog82ai-form-group">
                    <label for="default-post-status">Default Post Status</label>
                    <select id="default-post-status" name="default_post_status">
                        <option value="draft" selected>Draft</option>
                        <option value="publish">Published</option>
                        <option value="pending">Pending Review</option>
                        <option value="private">Private</option>
                    </select>
                    <small>Default status for newly imported posts</small>
                </div>
                <div class="blog82ai-form-group">
                    <label for="default-author">Default Author</label>
                    <select id="default-author" name="default_author">
                        <option value="preserve">Preserve Original Author</option>
                        <option value="current" selected>Current User</option>
                        <option value="admin">Admin</option>
                        <option value="feed-manager">Feed Manager</option>
                    </select>
                    <small>How to handle post authorship</small>
                </div>
            </div>

            <div class="blog82ai-form-row">
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="auto_set_featured_image" checked>
                        Auto Set Featured Images
                    </label>
                    <small>Automatically import and set featured images from feeds</small>
                </div>
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="preserve_formatting" checked>
                        Preserve Original Formatting
                    </label>
                    <small>Keep original HTML formatting when possible</small>
                </div>
            </div>

            <div class="blog82ai-form-group">
                <label for="default-category">Default Category for Uncategorized Posts</label>
                <select id="default-category" name="default_category">
                    <option value="">Select Category</option>
                    <option value="1">Uncategorized</option>
                    <option value="2">Technology</option>
                    <option value="3">Programming</option>
                    <option value="4">Web Development</option>
                    <option value="5">News</option>
                </select>
                <small>Category to assign when no category is specified in feed</small>
            </div>
        </div>

        <!-- Content Processing -->
        <div class="blog82ai-settings-section">
            <h3>Content Processing</h3>
            
            <div class="blog82ai-form-row">
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="enable_ai_rewriting">
                        Enable AI Content Rewriting
                    </label>
                    <small>Use Blogibot AI to rewrite imported content</small>
                </div>
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="extract_images" checked>
                        Extract and Import Images
                    </label>
                    <small>Download and host images locally</small>
                </div>
            </div>

            <div class="blog82ai-form-group">
                <label for="content-length-limit">Minimum Content Length (words)</label>
                <input type="number" id="content-length-limit" name="content_length_limit" value="50" min="10" max="1000">
                <small>Skip posts shorter than this word count</small>
            </div>

            <div class="blog82ai-form-group">
                <label for="excerpt-length">Auto-Generated Excerpt Length (words)</label>
                <input type="number" id="excerpt-length" name="excerpt_length" value="30" min="10" max="100">
                <small>Length of automatically generated excerpts</small>
            </div>

            <div class="blog82ai-form-group">
                <label for="content-cleanup">Content Cleanup Options</label>
                <div class="blog82ai-checkbox-group">
                    <label><input type="checkbox" name="remove_scripts" checked> Remove JavaScript</label>
                    <label><input type="checkbox" name="remove_styles" checked> Remove Inline Styles</label>
                    <label><input type="checkbox" name="sanitize_html" checked> Sanitize HTML</label>
                    <label><input type="checkbox" name="remove_empty_paragraphs" checked> Remove Empty Paragraphs</label>
                </div>
                <small>Automatically clean imported content</small>
            </div>
        </div>

        <!-- Duplicate Prevention -->
        <div class="blog82ai-settings-section">
            <h3>Duplicate Prevention</h3>
            
            <div class="blog82ai-form-row">
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="enable_duplicate_detection" checked>
                        Enable Duplicate Detection
                    </label>
                    <small>Prevent importing duplicate posts</small>
                </div>
                <div class="blog82ai-form-group">
                    <label for="duplicate-check-method">Detection Method</label>
                    <select id="duplicate-check-method" name="duplicate_check_method">
                        <option value="url">By Source URL</option>
                        <option value="title" selected>By Title</option>
                        <option value="content">By Content Hash</option>
                        <option value="guid">By GUID</option>
                    </select>
                    <small>How to identify duplicate posts</small>
                </div>
            </div>

            <div class="blog82ai-form-group">
                <label for="update-existing">Update Existing Posts</label>
                <select id="update-existing" name="update_existing">
                    <option value="never">Never Update</option>
                    <option value="if_newer" selected>Update if Source is Newer</option>
                    <option value="always">Always Update</option>
                </select>
                <small>What to do when duplicate is found</small>
            </div>
        </div>

        <!-- Attribution and SEO -->
        <div class="blog82ai-settings-section">
            <h3>Attribution & SEO</h3>
            
            <div class="blog82ai-form-row">
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="add_source_attribution" checked>
                        Add Source Attribution
                    </label>
                    <small>Add attribution to the original source</small>
                </div>
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="add_canonical_tags" checked>
                        Add Canonical Tags
                    </label>
                    <small>Add canonical URL for SEO</small>
                </div>
            </div>

            <div class="blog82ai-form-group">
                <label for="attribution-template">Attribution Template</label>
                <textarea id="attribution-template" name="attribution_template" rows="3">This article was originally published on {source_name}. Read the original at {source_url}</textarea>
                <small>Available variables: {source_name}, {source_url}, {author}, {publish_date}</small>
            </div>

            <div class="blog82ai-form-row">
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="nofollow_source_links" checked>
                        Add nofollow to Source Links
                    </label>
                    <small>Add rel="nofollow" to external links</small>
                </div>
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="open_links_new_tab" checked>
                        Open External Links in New Tab
                    </label>
                    <small>Add target="_blank" to external links</small>
                </div>
            </div>
        </div>

        <!-- Scheduling and Automation -->
        <div class="blog82ai-settings-section">
            <h3>Scheduling & Automation</h3>
            
            <div class="blog82ai-form-row">
                <div class="blog82ai-form-group">
                    <label for="global-fetch-frequency">Global Fetch Frequency</label>
                    <select id="global-fetch-frequency" name="global_fetch_frequency">
                        <option value="hourly">Every Hour</option>
                        <option value="6hours">Every 6 Hours</option>
                        <option value="daily" selected>Daily</option>
                        <option value="weekly">Weekly</option>
                    </select>
                    <small>Default frequency for new feeds</small>
                </div>
                <div class="blog82ai-form-group">
                    <label for="max-posts-per-fetch">Max Posts per Fetch</label>
                    <input type="number" id="max-posts-per-fetch" name="max_posts_per_fetch" value="10" min="1" max="100">
                    <small>Maximum posts to import in single fetch</small>
                </div>
            </div>

            <div class="blog82ai-form-row">
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="auto_publish_after_review">
                        Auto-Publish After Manual Review
                    </label>
                    <small>Automatically publish posts marked for review</small>
                </div>
                <div class="blog82ai-form-group">
                    <label for="review-delay">Review Delay (hours)</label>
                    <input type="number" id="review-delay" name="review_delay" value="24" min="1" max="168">
                    <small>Hours to wait before auto-publishing reviewed posts</small>
                </div>
            </div>
        </div>

        <!-- Error Handling -->
        <div class="blog82ai-settings-section">
            <h3>Error Handling & Notifications</h3>
            
            <div class="blog82ai-form-row">
                <div class="blog82ai-form-group">
                    <label for="retry-attempts">Retry Failed Imports</label>
                    <input type="number" id="retry-attempts" name="retry_attempts" value="3" min="0" max="10">
                    <small>Number of retry attempts for failed imports</small>
                </div>
                <div class="blog82ai-form-group">
                    <label for="retry-delay">Retry Delay (minutes)</label>
                    <input type="number" id="retry-delay" name="retry_delay" value="30" min="5" max="1440">
                    <small>Minutes to wait between retry attempts</small>
                </div>
            </div>

            <div class="blog82ai-form-group">
                <label for="notification-settings">Email Notifications</label>
                <div class="blog82ai-checkbox-group">
                    <label><input type="checkbox" name="notify_import_errors" checked> Import Errors</label>
                    <label><input type="checkbox" name="notify_feed_failures"> Feed Connection Failures</label>
                    <label><input type="checkbox" name="notify_daily_summary"> Daily Import Summary</label>
                    <label><input type="checkbox" name="notify_weekly_report"> Weekly Performance Report</label>
                </div>
                <small>Choose when to receive email notifications</small>
            </div>

            <div class="blog82ai-form-group">
                <label for="notification-email">Notification Email Address</label>
                <input type="email" id="notification-email" name="notification_email" value="<?php echo esc_attr(get_option('admin_email')); ?>">
                <small>Email address for notifications (defaults to admin email)</small>
            </div>
        </div>

        <!-- Performance Settings -->
        <div class="blog82ai-settings-section">
            <h3>Performance & Storage</h3>
            
            <div class="blog82ai-form-row">
                <div class="blog82ai-form-group">
                    <label for="log-retention">Log Retention Period (days)</label>
                    <input type="number" id="log-retention" name="log_retention" value="30" min="7" max="365">
                    <small>How long to keep import logs</small>
                </div>
                <div class="blog82ai-form-group">
                    <label for="image-quality">Image Quality</label>
                    <select id="image-quality" name="image_quality">
                        <option value="low">Low (60%)</option>
                        <option value="medium" selected>Medium (80%)</option>
                        <option value="high">High (95%)</option>
                        <option value="original">Original</option>
                    </select>
                    <small>Quality for imported images</small>
                </div>
            </div>

            <div class="blog82ai-form-row">
                <div class="blog82ai-form-group">
                    <label for="max-image-size">Max Image Size (KB)</label>
                    <input type="number" id="max-image-size" name="max_image_size" value="500" min="50" max="5000">
                    <small>Maximum size for imported images</small>
                </div>
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="cleanup_temp_files" checked>
                        Auto-Cleanup Temporary Files
                    </label>
                    <small>Automatically delete temporary import files</small>
                </div>
            </div>
        </div>

        <!-- Save Settings -->
        <div class="blog82ai-form-actions">
            <button type="button" class="button" onclick="resetToDefaults()">Reset to Defaults</button>
            <button type="button" class="button" onclick="exportSettings()">Export Settings</button>
            <button type="button" class="button" onclick="importSettings()">Import Settings</button>
            <button type="submit" class="button button-primary">Save Settings</button>
        </div>
    </form>

    <!-- Settings Import/Export -->
    <div class="blog82ai-settings-io" style="display: none;">
        <div class="blog82ai-io-section">
            <h4>Import Settings</h4>
            <textarea id="settings-import" rows="6" placeholder="Paste exported settings JSON here..."></textarea>
            <button class="button" onclick="processSettingsImport()">Import</button>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    initializeSettingsForm();
});

function initializeSettingsForm() {
    // Form submission
    document.getElementById('importSettingsForm').addEventListener('submit', function(e) {
        e.preventDefault();
        saveSettings();
    });

    // Conditional field visibility
    setupConditionalFields();
}

function setupConditionalFields() {
    // Show/hide review delay based on auto-publish checkbox
    const autoPublishCheckbox = document.querySelector('input[name="auto_publish_after_review"]');
    const reviewDelayGroup = document.getElementById('review-delay').closest('.blog82ai-form-group');
    
    function toggleReviewDelay() {
        if (autoPublishCheckbox.checked) {
            reviewDelayGroup.style.display = 'block';
        } else {
            reviewDelayGroup.style.display = 'none';
        }
    }
    
    autoPublishCheckbox.addEventListener('change', toggleReviewDelay);
    toggleReviewDelay(); // Initial state

    // Show/hide notification email based on notification checkboxes
    const notificationCheckboxes = document.querySelectorAll('input[name^="notify_"]');
    const notificationEmailGroup = document.getElementById('notification-email').closest('.blog82ai-form-group');
    
    function toggleNotificationEmail() {
        const anyChecked = Array.from(notificationCheckboxes).some(cb => cb.checked);
        if (anyChecked) {
            notificationEmailGroup.style.display = 'block';
        } else {
            notificationEmailGroup.style.display = 'none';
        }
    }
    
    notificationCheckboxes.forEach(cb => {
        cb.addEventListener('change', toggleNotificationEmail);
    });
    toggleNotificationEmail(); // Initial state
}

function saveSettings() {
    const submitBtn = document.querySelector('button[type="submit"]');
    const originalText = submitBtn.textContent;
    
    // Show loading state
    submitBtn.textContent = 'Saving...';
    submitBtn.disabled = true;
    
    // Collect form data
    const formData = new FormData(document.getElementById('importSettingsForm'));
    const settings = {};
    
    for (let [key, value] of formData.entries()) {
        if (settings[key]) {
            // Handle multiple values (checkboxes)
            if (Array.isArray(settings[key])) {
                settings[key].push(value);
            } else {
                settings[key] = [settings[key], value];
            }
        } else {
            settings[key] = value;
        }
    }
    
    // Add unchecked checkboxes as false
    const checkboxes = document.querySelectorAll('input[type="checkbox"]');
    checkboxes.forEach(cb => {
        if (!cb.checked && !settings[cb.name]) {
            settings[cb.name] = false;
        }
    });
    
    // Simulate API call
    setTimeout(() => {
        submitBtn.textContent = originalText;
        submitBtn.disabled = false;
        
        // Show success message
        showNotification('Settings saved successfully!', 'success');
        
        console.log('Settings saved:', settings);
    }, 2000);
}

function resetToDefaults() {
    if (confirm('Reset all settings to default values? This action cannot be undone.')) {
        // Reset form to defaults
        document.getElementById('importSettingsForm').reset();
        
        // Reset specific checkboxes to their default states
        document.querySelector('input[name="auto_set_featured_image"]').checked = true;
        document.querySelector('input[name="preserve_formatting"]').checked = true;
        document.querySelector('input[name="extract_images"]').checked = true;
        document.querySelector('input[name="enable_duplicate_detection"]').checked = true;
        document.querySelector('input[name="add_source_attribution"]').checked = true;
        document.querySelector('input[name="add_canonical_tags"]').checked = true;
        document.querySelector('input[name="nofollow_source_links"]').checked = true;
        document.querySelector('input[name="open_links_new_tab"]').checked = true;
        
        showNotification('Settings reset to defaults', 'info');
    }
}

function exportSettings() {
    // Collect current settings
    const formData = new FormData(document.getElementById('importSettingsForm'));
    const settings = {};
    
    for (let [key, value] of formData.entries()) {
        settings[key] = value;
    }
    
    // Create download
    const dataStr = JSON.stringify(settings, null, 2);
    const dataBlob = new Blob([dataStr], {type: 'application/json'});
    const url = URL.createObjectURL(dataBlob);
    
    const link = document.createElement('a');
    link.href = url;
    link.download = 'blogibot-import-settings.json';
    link.click();
    
    URL.revokeObjectURL(url);
    showNotification('Settings exported successfully', 'success');
}

function importSettings() {
    const ioSection = document.querySelector('.blog82ai-settings-io');
    if (ioSection.style.display === 'none') {
        ioSection.style.display = 'block';
        ioSection.scrollIntoView({ behavior: 'smooth' });
    } else {
        ioSection.style.display = 'none';
    }
}

function processSettingsImport() {
    const importText = document.getElementById('settings-import').value.trim();
    
    if (!importText) {
        showNotification('Please paste settings JSON to import', 'error');
        return;
    }
    
    try {
        const settings = JSON.parse(importText);
        
        // Apply settings to form
        Object.keys(settings).forEach(key => {
            const element = document.querySelector(`[name="${key}"]`);
            if (element) {
                if (element.type === 'checkbox') {
                    element.checked = settings[key] === true || settings[key] === 'on';
                } else {
                    element.value = settings[key];
                }
            }
        });
        
        document.querySelector('.blog82ai-settings-io').style.display = 'none';
        showNotification('Settings imported successfully! Don\'t forget to save.', 'success');
        
    } catch (error) {
        showNotification('Invalid JSON format. Please check your settings data.', 'error');
    }
}

function showNotification(message, type = 'info') {
    // Create notification element
    const notification = document.createElement('div');
    notification.className = `blog82ai-notification blog82ai-notification-${type}`;
    notification.innerHTML = `
        <span class="blog82ai-notification-message">${message}</span>
        <button class="blog82ai-notification-close" onclick="this.parentElement.remove()">×</button>
    `;
    
    // Add styles
    notification.style.cssText = `
        position: fixed;
        top: 32px;
        right: 20px;
        background: ${type === 'success' ? '#d1e7dd' : type === 'error' ? '#f8d7da' : '#d1ecf1'};
        color: ${type === 'success' ? '#0a3622' : type === 'error' ? '#58151c' : '#055160'};
        border: 1px solid ${type === 'success' ? '#badbcc' : type === 'error' ? '#f5c6cb' : '#b6effb'};
        border-radius: 6px;
        padding: 12px 16px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.15);
        z-index: 10000;
        max-width: 400px;
        display: flex;
        align-items: center;
        gap: 8px;
    `;
    
    notification.querySelector('.blog82ai-notification-close').style.cssText = `
        background: none;
        border: none;
        font-size: 18px;
        font-weight: bold;
        cursor: pointer;
        padding: 0;
        margin-left: auto;
    `;
    
    document.body.appendChild(notification);
    
    // Auto-remove after 5 seconds
    setTimeout(() => {
        if (notification.parentElement) {
            notification.remove();
        }
    }, 5000);
}
</script>
