<?php
/**
 * Name: Content Exporter (CSV)
 * Description: Export posts and pages to CSV file including titles, content, metadata, and custom fields for backups, audits, migrations, or content analysis spreadsheets
 * Category: Content
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Client Content Delivery",
 *     "description": "Export all blog posts to CSV for client who wants their content for backup or migration to different platform."
 *   },
 *   {
 *     "title": "Data Analysis",
 *     "description": "Export posts with metadata to spreadsheet for content audit analyzing authors, categories, dates, and word counts."
 *   },
 *   {
 *     "title": "Print Publication",
 *     "description": "Extract all articles from digital magazine site to prepare for print version or PDF compilation."
 *   }
 * ]
 * Added: 2025-07-05
 * Tags: export, csv, backup, migration, content
 * WhereToFind: {
 *   "location": "Switchboard Settings",
 *   "url": "",
 *   "instructions": "Select post type, status, and fields to export in module settings. CSV file downloads automatically when ready.",
 *   "newTab": false
 * }
 */

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

class SwitchboardContentExporter {
    
    public function __construct() {
        add_action('wp_ajax_switchboard_export_content', [$this, 'ajax_export_content']);
        
        // Register with data registry
        $this->register_with_data_registry();
    }
    
    private function register_with_data_registry() {
        if (class_exists('Switchboard_Data_Registry')) {
            $registry = Switchboard_Data_Registry::get_instance();
            $registry->auto_register($this, __FILE__);
        }
    }
    
    public function register_data_locations() {
        return [
            'options' => [
                'switchboard_content-exporter_settings'
            ],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [],
            'transients' => []
        ];
    }
    
    public function render_settings() {
        $post_types = get_post_types(['public' => true], 'objects');
        $post_counts = [];

        foreach ($post_types as $type) {
            if (!is_object($type) || !isset($type->name)) {
                continue;
            }
            $count = wp_count_posts($type->name);
            if (is_object($count) && isset($count->publish, $count->draft, $count->pending)) {
                $post_counts[$type->name] = $count->publish + $count->draft + $count->pending;
            } else {
                $post_counts[$type->name] = 0;
            }
        }
        
        ?>
        <div class="sb-sp-group">
            <h4 class="sb-sp-heading-sm"><?php esc_html_e('Content Exporter', 'wpswitchboard'); ?></h4>
            <p class="sb-sp-description"><?php esc_html_e('Export your posts and pages to CSV format for backups or migrations.', 'wpswitchboard'); ?></p>
        </div>

        <div class="sb-sp-group sb-sp-field-horizontal">
            <div class="sb-sp-field-horizontal-left">
                <label class="sb-sp-label"><?php esc_html_e('Post Type', 'wpswitchboard'); ?></label>
                <p class="sb-sp-description"><?php esc_html_e('Select the content type to export', 'wpswitchboard'); ?></p>
            </div>
            <select id="export-post-type" class="sb-sp-select">
                <?php foreach ($post_types as $type): ?>
                <option value="<?php echo esc_attr($type->name); ?>">
                    <?php echo esc_html($type->label); ?> (<?php echo esc_html($post_counts[$type->name]); ?>)
                </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="sb-sp-group sb-sp-field-horizontal">
            <div class="sb-sp-field-horizontal-left">
                <label class="sb-sp-label"><?php esc_html_e('Post Status', 'wpswitchboard'); ?></label>
                <p class="sb-sp-description"><?php esc_html_e('Filter posts by their publish status', 'wpswitchboard'); ?></p>
            </div>
            <select id="export-status" class="sb-sp-select">
                <option value="any"><?php esc_html_e('All Statuses', 'wpswitchboard'); ?></option>
                <option value="publish"><?php esc_html_e('Published', 'wpswitchboard'); ?></option>
                <option value="draft"><?php esc_html_e('Draft', 'wpswitchboard'); ?></option>
                <option value="pending"><?php esc_html_e('Pending', 'wpswitchboard'); ?></option>
                <option value="private"><?php esc_html_e('Private', 'wpswitchboard'); ?></option>
            </select>
        </div>

        <div class="sb-sp-group">
            <div class="sb-module-option-item sb-module-toggle-item">
                <div class="sb-module-option-content">
                    <div class="sb-module-toggle-header">
                        <strong class="sb-module-option-title"><?php esc_html_e('Include post content', 'wpswitchboard'); ?></strong>
                        <label class="sb-module-toggle">
                            <input type="checkbox" id="include-content" checked>
                            <span class="sb-module-toggle-slider"></span>
                        </label>
                    </div>
                </div>
            </div>
        </div>

        <div class="sb-sp-group">
            <div class="sb-module-option-item sb-module-toggle-item">
                <div class="sb-module-option-content">
                    <div class="sb-module-toggle-header">
                        <strong class="sb-module-option-title"><?php esc_html_e('Include excerpt', 'wpswitchboard'); ?></strong>
                        <label class="sb-module-toggle">
                            <input type="checkbox" id="include-excerpt" checked>
                            <span class="sb-module-toggle-slider"></span>
                        </label>
                    </div>
                </div>
            </div>
                        </div>

        <div class="sb-sp-group">
            <div class="sb-module-option-item sb-module-toggle-item">
                <div class="sb-module-option-content">
                    <div class="sb-module-toggle-header">
                        <strong class="sb-module-option-title"><?php esc_html_e('Include custom fields', 'wpswitchboard'); ?></strong>
                        <label class="sb-module-toggle">
                            <input type="checkbox" id="include-meta">
                            <span class="sb-module-toggle-slider"></span>
                        </label>
                    </div>
                </div>
            </div>
        </div>

        <div class="sb-sp-group">
            <div style="display: flex; justify-content: flex-end;">
                <button type="button" id="export-btn" class="button button-primary">
                    <?php esc_html_e('Export to CSV', 'wpswitchboard'); ?>
                </button>
            </div>
        </div>

        <div id="export-progress" style="display: none; margin-top: 16px;">
            <div style="background: #e5e7eb; border-radius: 8px; height: 24px; overflow: hidden;">
                <div id="progress-bar" style="width: 0%; background: var(--primary-500); height: 100%; transition: width 0.3s;"></div>
            </div>
            <p id="progress-text" style="text-align: center; margin: 8px 0 0 0; font-size: 13px; color: #64748b;"></p>
        </div>

        <?php
        $i18n = [
            'exporting' => __('Exporting...', 'wpswitchboard'),
            'exportToCSV' => __('Export to CSV', 'wpswitchboard'),
            'exportComplete' => __('Export complete! Download started.', 'wpswitchboard'),
            'error' => __('Error:', 'wpswitchboard')
        ];
        ?>
        <script>
        jQuery(document).ready(function($) {
            const i18n = <?php echo json_encode($i18n); ?>;

            $('#export-btn').on('click', function() {
                const postType = $('#export-post-type').val();
                const status = $('#export-status').val();
                const includeContent = $('#include-content').is(':checked');
                const includeExcerpt = $('#include-excerpt').is(':checked');
                const includeMeta = $('#include-meta').is(':checked');

                $(this).prop('disabled', true).text(i18n.exporting);
                $('#export-progress').removeClass('hidden');

                $.post(ajaxurl, {
                    action: 'switchboard_export_content',
                    post_type: postType,
                    status: status,
                    include_content: includeContent,
                    include_excerpt: includeExcerpt,
                    include_meta: includeMeta,
                    nonce: '<?php echo esc_js(wp_create_nonce('export_content')); ?>'
                }, function(response) {
                    if (response.success) {
                        // Create download link
                        const blob = new Blob([response.data.csv], { type: 'text/csv' });
                        const url = window.URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = response.data.filename;
                        document.body.appendChild(a);
                        a.click();
                        window.URL.revokeObjectURL(url);
                        document.body.removeChild(a);

                        $('#progress-bar').css('width', '100%');
                        $('#progress-text').text(i18n.exportComplete);

                        setTimeout(function() {
                            $('#export-btn').prop('disabled', false).text(i18n.exportToCSV);
                            $('#export-progress').addClass('hidden');
                            $('#progress-bar').css('width', '0%');
                        }, 2000);
                    } else {
                        alert(i18n.error + ' ' + response.data);
                        $('#export-btn').prop('disabled', false).text(i18n.exportToCSV);
                        $('#export-progress').addClass('hidden');
                    }
                });
            });
        });
        </script>
        <?php
    }
    
    public function ajax_export_content() {
        check_ajax_referer('export_content', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(esc_html__('Unauthorized', 'wpswitchboard'));
        }

        if (!isset($_POST['post_type'], $_POST['status'])) {
            wp_send_json_error(esc_html__('Missing required parameters', 'wpswitchboard'));
        }

        $post_type = sanitize_key($_POST['post_type']);
        $status = sanitize_key($_POST['status']);
        $include_content = isset($_POST['include_content']) && $_POST['include_content'] === 'true';
        $include_excerpt = isset($_POST['include_excerpt']) && $_POST['include_excerpt'] === 'true';
        $include_meta = isset($_POST['include_meta']) && $_POST['include_meta'] === 'true';
        
        $args = [
            'post_type' => $post_type,
            'post_status' => $status === 'any' ? ['publish', 'draft', 'pending', 'private'] : $status,
            'posts_per_page' => -1,
            'orderby' => 'date',
            'order' => 'DESC'
        ];
        
        $posts = get_posts($args);
        
        // Build CSV
        $csv = [];
        
        // Header row
        $header = ['ID', 'Title', 'Slug', 'Status', 'Author', 'Date', 'Modified', 'URL'];
        if ($include_excerpt) $header[] = 'Excerpt';
        if ($include_content) $header[] = 'Content';
        if ($include_meta) $header[] = 'Custom Fields';
        
        $csv[] = $header;
        
        // Data rows
        foreach ($posts as $post) {
            $row = [
                $post->ID,
                $post->post_title,
                $post->post_name,
                $post->post_status,
                get_the_author_meta('display_name', $post->post_author),
                $post->post_date,
                $post->post_modified,
                get_permalink($post->ID)
            ];
            
            if ($include_excerpt) {
                $row[] = $post->post_excerpt;
            }
            
            if ($include_content) {
                $row[] = wp_strip_all_tags($post->post_content);
            }
            
            if ($include_meta) {
                $meta = get_post_meta($post->ID);
                $meta_str = '';
                foreach ($meta as $key => $value) {
                    if (strpos($key, '_') !== 0) { // Skip private meta
                        $meta_str .= $key . ': ' . (is_array($value) ? implode(', ', $value) : $value) . '; ';
                    }
                }
                $row[] = trim($meta_str);
            }
            
            $csv[] = $row;
        }
        
        // Convert to CSV string
        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- Generating CSV for download
        $output = fopen('php://temp', 'r+');
        foreach ($csv as $row) {
            fputcsv($output, $row);
        }
        rewind($output);
        $csv_string = stream_get_contents($output);
        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- Closing CSV temp stream
        fclose($output);
        
        $filename = $post_type . '-export-' . gmdate('Y-m-d-His') . '.csv';
        
        wp_send_json_success([
            'csv' => $csv_string,
            'filename' => $filename,
            'count' => count($posts)
        ]);
    }
}

// Initialize and register with data system
$switchboard_instance = new SwitchboardContentExporter();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
