<?php
/**
 * Name: User Exporter (CSV)
 * Description: Export users to CSV file including usernames, emails, roles, registration dates, and custom metadata for reporting, migration, or external system integration needs
 * Category: User Management
 * Icon: -
  * UseCases: [
 *   {
 *     "title": "Backup User Data",
 *     "description": "Export user lists with their metadata to CSV for backups, migrations, or import into other tools."
 *   },
 *   {
 *     "title": "Marketing Analysis",
 *     "description": "Export user data to analyze demographics, registration trends, or create targeted email campaigns."
 *   }
 * ]
 * Added: 2025-07-08
 * Tags: export, csv, users, backup, migration
 * WhereToFind: {
 *   "location": "Users → Export",
 *   "url": "users.php",
 *   "instructions": "Export users to CSV with metadata",
 *   "newTab": false
 * }
 */

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

class SwitchboardUserExporter {
    
    public function __construct() {
        add_action('wp_ajax_switchboard_export_users', [$this, 'ajax_export_users']);
        
        // 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() {
        // This module exports data but doesn't store its own settings or data
        return [
            'options' => [],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [],
            'term_meta' => [],
            'transients' => []
        ];
    }
    
    /**
     * Render settings panel for User Exporter (CSV)
     * 
     * Displays comprehensive user export interface with:
     * - Role selector dropdown (all roles or specific role with user counts)
     * - Field selector checkboxes (email, registered date, display name, first/last name, website)
     * - Large primary export button that triggers AJAX CSV generation
     * - Inline jQuery for handling export process and triggering CSV download
     * - Real-time button state management (disabled during export, shows "Exporting...")
     * 
     * This is a tool-style module (no persistent settings to save). It provides an
     * on-demand CSV export interface in the module settings panel. Users select which
     * role(s) to export and which fields to include, then click "Export to CSV" to
     * generate and download the file.
     * 
     * Export process:
     * 1. User selects role filter (all or specific role like administrator, editor, etc)
     * 2. User checks/unchecks desired fields (default: email, registered, display_name checked)
     * 3. User clicks "Export to CSV" button
     * 4. jQuery sends AJAX request to switchboard_export_users action
     * 5. PHP handler (ajax_export_users) queries users, builds CSV array
     * 6. CSV returned as JSON with filename and count
     * 7. jQuery creates Blob, triggers browser download via temporary <a> element
     * 8. File named users-export-YYYY-MM-DD-HHmmss.csv automatically downloads
     * 
     * Available fields:
     * - username: Always included (first column)
     * - role: Always included (second column)
     * - email: Email address (default checked)
     * - registered: Registration date (default checked)
     * - display_name: Display name (default checked)
     * - first_last: First name + Last name (optional)
     * - url: Website URL (optional)
     * 
     * The interface displays user counts next to each role using count_users() WordPress
     * function, helping users understand the export size before generating.
     * 
     * Security: Nonce verification in AJAX handler, requires manage_options capability
     * 
     * @param array $settings Current module settings (unused - no persistent settings)
     * @return void Outputs HTML directly with inline jQuery
     */
    public function render_settings($settings = []) {
        global $wp_roles;
        $roles = $wp_roles->get_names();
        $user_count = count_users();
        
        $field_options = [
            'email' => [
                'label' => esc_html__('Email Address', 'wpswitchboard'),
                'description' => esc_html__('User email addresses', 'wpswitchboard'),
                'checked' => true
            ],
            'registered' => [
                'label' => esc_html__('Registration Date', 'wpswitchboard'),
                'description' => esc_html__('Date when user registered', 'wpswitchboard'),
                'checked' => true
            ],
            'display_name' => [
                'label' => esc_html__('Display Name', 'wpswitchboard'),
                'description' => esc_html__('User display name', 'wpswitchboard'),
                'checked' => true
            ],
            'first_last' => [
                'label' => esc_html__('First & Last Name', 'wpswitchboard'),
                'description' => esc_html__('First name and last name fields', 'wpswitchboard'),
                'checked' => false
            ],
            'url' => [
                'label' => esc_html__('Website URL', 'wpswitchboard'),
                'description' => esc_html__('User website URL', 'wpswitchboard'),
                'checked' => false
            ]
        ];
        
        ?>
        <input type="hidden" name="module" value="user-exporter">

        <div class="sb-sp-info-box sb-sp-info-box-info" style="margin-bottom: 24px;">
            <h4 class="sb-sp-heading-sm">How It Works</h4>
            <p class="sb-sp-description" style="margin: 0;">Export your users to CSV format for reporting, backups, or migrations. Select which role to export and which fields to include in the CSV file.</p>
        </div>

        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <h3 class="sb-sp-heading">Export Settings</h3>
            
            <div class="sb-sp-group sb-sp-field-horizontal">
                <div class="sb-sp-field-horizontal-left">
                    <label for="export-role" class="sb-sp-label"><?php esc_html_e('User Role', 'wpswitchboard'); ?></label>
                    <p class="sb-sp-description"><?php esc_html_e('Select which user role to export, or export all users.', 'wpswitchboard'); ?></p>
                </div>
                <select id="export-role" class="sb-sp-select">
                    <option value="all"><?php
                    // translators: %d is the total number of users
                    printf(esc_html__('All Roles (%d)', 'wpswitchboard'), esc_html($user_count['total_users'])); ?></option>
                    <?php foreach ($roles as $role_slug => $role_name):
                        $count = isset($user_count['avail_roles'][$role_slug]) ? $user_count['avail_roles'][$role_slug] : 0;
                    ?>
                    <option value="<?php echo esc_attr($role_slug); ?>">
                        <?php echo esc_html($role_name); ?> (<?php echo esc_html($count); ?>)
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>

        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <h3 class="sb-sp-heading">Include Fields</h3>
            <p class="sb-sp-description"><?php esc_html_e('Select which fields to include in the CSV export. Username and Role are always included.', 'wpswitchboard'); ?></p>
            
            <div style="display: flex; flex-direction: column; gap: 12px; margin-top: 16px;">
                <?php foreach ($field_options as $key => $option): ?>
                <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 echo esc_html($option['label']); ?></strong>
                            <label class="sb-module-toggle">
                                <input type="checkbox"
                                       class="export-field"
                                       value="<?php echo esc_attr($key); ?>"
                                       <?php echo $option['checked'] ? 'checked' : ''; ?>>
                                <span class="sb-module-toggle-slider"></span>
                            </label>
                        </div>
                        <p class="sb-module-option-text"><?php echo esc_html($option['description']); ?></p>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>

        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <button type="button" id="export-btn" class="button button-primary">
                <span class="dashicons dashicons-download" style="vertical-align: middle; margin-right: 4px;"></span>
                <?php esc_html_e('Export to CSV', 'wpswitchboard'); ?>
            </button>
        </div>
        
        <script>
        jQuery(document).ready(function($) {
            $('#export-btn').on('click', function() {
                const role = $('#export-role').val();
                const fields = [];
                $('.export-field:checked').each(function() {
                    fields.push($(this).val());
                });
                
                $(this).prop('disabled', true).text('<?php echo esc_js(__('Exporting...', 'wpswitchboard')); ?>');

                $.post(ajaxurl, {
                    action: 'switchboard_export_users',
                    role: role,
                    fields: fields.join(','),
                    nonce: '<?php echo esc_attr(wp_create_nonce('export_users')); ?>'
                }, function(response) {
                    if (response.success) {
                        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);

                        $('#export-btn').prop('disabled', false).text('<?php echo esc_js(__('Export to CSV', 'wpswitchboard')); ?>');
                    } else {
                        alert('<?php echo esc_js(__('Error:', 'wpswitchboard')); ?> ' + response.data);
                        $('#export-btn').prop('disabled', false).text('<?php echo esc_js(__('Export to CSV', 'wpswitchboard')); ?>');
                    }
                });
            });
        });
        </script>
        <?php
    }
    
    public function ajax_export_users() {
        check_ajax_referer('export_users', 'nonce');

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

        $role = isset($_POST['role']) ? sanitize_key(wp_unslash($_POST['role'])) : 'all';
        $fields = isset($_POST['fields']) ? array_map('sanitize_key', explode(',', sanitize_text_field(wp_unslash($_POST['fields'])))) : [];

        $args = ['orderby' => 'registered', 'order' => 'DESC'];
        if ($role !== 'all') {
            $args['role'] = $role;
        }

        $users = get_users($args);

        // Build CSV
        $csv = [];

        // Header row
        $header = [__('ID', 'wpswitchboard'), __('Username', 'wpswitchboard'), __('Role', 'wpswitchboard')];
        if (in_array('email', $fields)) $header[] = __('Email', 'wpswitchboard');
        if (in_array('display_name', $fields)) $header[] = __('Display Name', 'wpswitchboard');
        if (in_array('first_last', $fields)) {
            $header[] = __('First Name', 'wpswitchboard');
            $header[] = __('Last Name', 'wpswitchboard');
        }
        if (in_array('registered', $fields)) $header[] = __('Registered', 'wpswitchboard');
        if (in_array('url', $fields)) $header[] = __('Website', 'wpswitchboard');
        
        $csv[] = $header;
        
        // Data rows
        foreach ($users as $user) {
            $row = [
                $user->ID,
                $user->user_login,
                implode(', ', $user->roles)
            ];
            
            if (in_array('email', $fields)) {
                $row[] = $user->user_email;
            }
            
            if (in_array('display_name', $fields)) {
                $row[] = $user->display_name;
            }
            
            if (in_array('first_last', $fields)) {
                $row[] = get_user_meta($user->ID, 'first_name', true);
                $row[] = get_user_meta($user->ID, 'last_name', true);
            }
            
            if (in_array('registered', $fields)) {
                $row[] = $user->user_registered;
            }
            
            if (in_array('url', $fields)) {
                $row[] = $user->user_url;
            }
            
            $csv[] = $row;
        }
        
        // Convert to CSV string
        $output = fopen('php://temp', 'r+'); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- CSV export to php://temp stream
        foreach ($csv as $row) {
            fputcsv($output, $row);
        }
        rewind($output);
        $csv_string = stream_get_contents($output);
        fclose($output); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose
        
        $filename = 'users-export-' . gmdate('Y-m-d-His') . '.csv';
        
        wp_send_json_success([
            'csv' => $csv_string,
            'filename' => $filename,
            'count' => count($users)
        ]);
    }
}

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