<?php
// Add Feed Source UI Component
if ( ! defined( 'ABSPATH' ) ) exit;

// Check if we're in edit mode
$edit_mode = false;
$feed_data = null;
$edit_feed_id = isset($_GET['edit_feed_id']) ? intval($_GET['edit_feed_id']) : 0;

// Debug comment
echo "<!-- Debug: edit_feed_id = $edit_feed_id -->";

if ($edit_feed_id > 0) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'blogibot_feed_sources';
    echo "<!-- Debug: table_name = $table_name -->";
    $feed_data = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $edit_feed_id), ARRAY_A);
    echo "<!-- Debug: feed_data = " . print_r($feed_data, true) . " -->";
    
    if ($feed_data) {
        $edit_mode = true;
        echo "<!-- Debug: edit_mode SET TO TRUE -->";
    } else {
        echo "<!-- Debug: feed_data is NULL or empty -->";
    }
}
echo "<!-- Debug: Final edit_mode = " . ($edit_mode ? 'TRUE' : 'FALSE') . " -->";
?>
<div class="blog82ai-add-feed-source">
    <div class="blog82ai-page-header">
        <h2><?php echo $edit_mode ? 'Edit Feed Source' : 'Add New Feed Source'; ?></h2>
        <p><?php echo $edit_mode ? 'Update your RSS/Atom feed settings' : 'Add RSS/Atom feeds to automatically import content from other websites'; ?></p>
    </div>

    <form class="blog82ai-feed-source-form" id="feedSourceForm">
        <?php if ($edit_mode): ?>
            <input type="hidden" name="feed_id" value="<?php echo esc_attr($edit_feed_id); ?>">
        <?php endif; ?>
        <!-- Basic Feed Information -->
        <div class="blog82ai-form-section">
            <h3>Feed Information</h3>
            
            <div class="blog82ai-form-group">
                <label for="feed-name">Feed Name</label>
                <input type="text" id="feed-name" name="feed_name" required placeholder="e.g., TechCrunch Technology News" value="<?php echo $edit_mode ? esc_attr($feed_data['feed_name']) : ''; ?>">
                <small>A descriptive name to identify this feed</small>
            </div>

            <div class="blog82ai-form-group">
                <label for="feed-url">Feed URL</label>
                <div class="blog82ai-url-input-group">
                    <input type="url" id="feed-url" name="feed_url" required placeholder="https://example.com/feed.xml" value="<?php echo $edit_mode ? esc_attr($feed_data['feed_url']) : ''; ?>">
                    <button type="button" class="button" onclick="validateFeed()">Validate Feed</button>
                </div>
                <small>RSS or Atom feed URL (usually ends with .xml, .rss, or /feed)</small>
                <div id="feed-validation-result" class="blog82ai-validation-result" style="display: none;"></div>
            </div>

            <div class="blog82ai-form-row">
                <div class="blog82ai-form-group">
                    <label for="feed-category">Category</label>
                    <select id="feed-category" name="category">
                        <option value="">Select Category</option>
                        <?php
                        // Get all WordPress categories
                        $categories = get_categories(array(
                            'hide_empty' => false,
                            'orderby' => 'name',
                            'order' => 'ASC',
                        ));
                        
                        // Get the selected category value for edit mode
                        $selected_category = $edit_mode && isset($feed_data['category']) ? $feed_data['category'] : '';
                        
                        // Function to display categories hierarchically
                        if (!function_exists('blogibot_display_category_options')) {
                            function blogibot_display_category_options($categories, $parent = 0, $level = 0, $selected = '') {
                                foreach ($categories as $category) {
                                    if ($category->parent == $parent) {
                                        $indent = str_repeat('&nbsp;&nbsp;&nbsp;', $level);
                                        $selected_attr = ($selected == $category->term_id) ? 'selected' : '';
                                        echo '<option value="' . esc_attr($category->term_id) . '" ' . $selected_attr . '>' . $indent . esc_html($category->name) . '</option>';
                                        blogibot_display_category_options($categories, $category->term_id, $level + 1, $selected);
                                    }
                                }
                            }
                        }
                        
                        blogibot_display_category_options($categories, 0, 0, $selected_category);
                        ?>
                    </select>
                    <small>Posts imported from this feed will be assigned to the selected WordPress category</small>
                </div>
            </div>
        </div>

        <!-- Import Settings -->
        <div class="blog82ai-form-section">
            <h3>Import Settings</h3>
            
            <div class="blog82ai-form-row">
                <div class="blog82ai-form-group">
                    <label for="import-frequency">Fetch Frequency</label>
                    <select id="import-frequency" name="import_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>
                        <option value="manual">Manual Only</option>
                    </select>
                </div>
                <div class="blog82ai-form-group">
                    <label for="import-type">Import Type</label>
                    <select id="import-type" name="import_type">
                        <option value="draft">As Draft</option>
                        <option value="publish">Publish Immediately</option>
                        <option value="external">External Link Only</option>
                    </select>
                </div>
            </div>

            <div class="blog82ai-form-group">
                <label for="max-posts">Maximum Posts per Fetch</label>
                <input type="number" id="max-posts" name="max_posts" value="50" min="1" max="100">
                <small>Limit the number of posts imported in each fetch (1-100). Recommended: 50</small>
            </div>

            <div class="blog82ai-form-row">
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="auto_fetch" checked>
                        Enable Auto Fetch
                    </label>
                    <small>Automatically fetch new posts based on frequency</small>
                </div>
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="fetch_full_content">
                        Fetch Full Content
                    </label>
                    <small>Try to fetch complete article content (when supported)</small>
                </div>
            </div>
        </div>

        <!-- Content Processing -->
        <div class="blog82ai-form-section">
            <h3>Content Processing</h3>
            
            <div class="blog82ai-form-row">
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="auto_featured_image" checked>
                        Auto Set Featured Image
                    </label>
                    <small>Automatically import and set featured images</small>
                </div>
            </div>

            <div class="blog82ai-form-group">
                <label for="fallback-image">Fallback Featured Image URL</label>
                <input type="url" id="fallback-image" name="fallback_image" placeholder="https://example.com/default-image.jpg">
                <small>Image to use when no featured image is available</small>
            </div>

            <div class="blog82ai-form-group">
                <label for="content-filter">Content Filtering</label>
                <select id="content-filter" name="content_filter">
                    <option value="none">No Filtering</option>
                    <option value="keyword">Keyword Based</option>
                    <option value="length">Minimum Length</option>
                    <option value="both">Both Keyword and Length</option>
                </select>
            </div>

            <div class="blog82ai-filter-options" id="keywordFilter" style="display: none;">
                <div class="blog82ai-form-group">
                    <label for="include-keywords">Include Keywords (comma separated)</label>
                    <input type="text" id="include-keywords" name="include_keywords" placeholder="wordpress, php, development">
                    <small>Only import posts containing these keywords</small>
                </div>
                <div class="blog82ai-form-group">
                    <label for="exclude-keywords">Exclude Keywords (comma separated)</label>
                    <input type="text" id="exclude-keywords" name="exclude_keywords" placeholder="spam, advertisement">
                    <small>Skip posts containing these keywords</small>
                </div>
            </div>

            <div class="blog82ai-filter-options" id="lengthFilter" style="display: none;">
                <div class="blog82ai-form-group">
                    <label for="min-content-length">Minimum Content Length (words)</label>
                    <input type="number" id="min-content-length" name="min_content_length" value="100" min="50">
                    <small>Skip posts shorter than this word count</small>
                </div>
            </div>
        </div>

        <!-- Attribution & SEO -->
        <div class="blog82ai-form-section">
            <h3>Attribution & SEO</h3>
            
            <div class="blog82ai-form-row">
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="add_attribution" checked>
                        Add Source Attribution
                    </label>
                    <small>Add source credit to imported posts</small>
                </div>
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="canonical_tags" checked>
                        Add Canonical Tags
                    </label>
                    <small>Add canonical reference for SEO</small>
                </div>
            </div>

            <div class="blog82ai-form-group">
                <label for="attribution-format">Attribution Format</label>
                <select id="attribution-format" name="attribution_format">
                    <option value="simple">Source: {source_name}</option>
                    <option value="detailed">Originally published on {source_name} at {source_url}</option>
                    <option value="custom">Custom Format</option>
                </select>
            </div>

            <div class="blog82ai-form-group" id="customAttribution" style="display: none;">
                <label for="custom-attribution">Custom Attribution Text</label>
                <textarea id="custom-attribution" name="custom_attribution" rows="3" placeholder="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-group">
                <label for="author-handling">Author Handling</label>
                <select id="author-handling" name="author_handling">
                    <option value="preserve">Preserve Original Author</option>
                    <option value="current">Use Current User</option>
                    <option value="specific">Assign to Specific User</option>
                    <option value="guest">Create as Guest Author</option>
                </select>
            </div>

            <div class="blog82ai-form-group" id="specificAuthor" style="display: none;">
                <label for="assigned-author">Assigned Author</label>
                <select id="assigned-author" name="assigned_author">
                    <option value="1">Admin</option>
                    <option value="2">Editor</option>
                    <option value="3">Content Manager</option>
                </select>
            </div>
        </div>

        <!-- Advanced Options -->
        <div class="blog82ai-form-section">
            <h3>Advanced Options</h3>
            
            <div class="blog82ai-form-row">
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="duplicate_prevention" checked>
                        Duplicate Prevention
                    </label>
                    <small>Prevent importing the same post multiple times</small>
                </div>
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="update_existing">
                        Update Existing Posts
                    </label>
                    <small>Update posts if they already exist</small>
                </div>
            </div>

            <div class="blog82ai-form-group">
                <label for="duplicate-check">Duplicate Check Method</label>
                <select id="duplicate-check" name="duplicate_check">
                    <option value="url">By Source URL</option>
                    <option value="title">By Title</option>
                    <option value="guid">By GUID</option>
                    <option value="content">By Content Hash</option>
                </select>
            </div>

            <div class="blog82ai-form-group">
                <label for="import-limit">Import History Limit</label>
                <input type="number" id="import-limit" name="import_limit" value="1000" min="100">
                <small>Maximum number of imported posts to keep in history</small>
            </div>

            <div class="blog82ai-form-group">
                <label for="custom-fields">Custom Fields Mapping</label>
                <textarea id="custom-fields" name="custom_fields" rows="4" placeholder="source_url = {source_url}&#10;original_author = {author}&#10;import_date = {import_date}"></textarea>
                <small>Map feed data to custom fields (one per line, format: field_name = {variable})</small>
            </div>
        </div>

        <div class="blog82ai-form-actions">
            <button type="button" class="button" onclick="window.location.href='<?php echo esc_url(admin_url('admin.php?page=blogibot&tab=feed&subtab=manage_feeds')); ?>'">Cancel</button>
            <button type="button" class="button button-secondary" onclick="testFeed()">Test Feed</button>
            <button type="submit" class="button button-primary">Add Feed Source</button>
        </div>
    </form>

    <!-- Feed Preview -->
    <div class="blog82ai-feed-preview" id="feedPreview" style="display: none;">
        <h3>Feed Preview</h3>
        <div class="blog82ai-preview-content">
            <!-- Preview content will be loaded here -->
        </div>
    </div>
</div>

<script>
// Localize data for JavaScript
var blogibotFeed = {
    ajax_url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
    nonce: '<?php echo wp_create_nonce('blogibot_feed_nonce'); ?>',
    manage_feeds_url: '<?php echo esc_url(admin_url('admin.php?page=blogibot&tab=feed&subtab=manage_feeds')); ?>'
};

<?php if ($edit_mode && $feed_data): ?>
var blogibotFeedData = {
    edit_mode: true,
    feed_data: <?php echo json_encode($feed_data); ?>
};
<?php endif; ?>
</script>
