<?php
if (!defined('WPINC')) die;


/* ========== Admin: Export subscribers to CSV ========== */

add_action('admin_menu', function() {
    add_users_page(
        'Export Subscribers CSV',      // Page title
        'Export Subscribers CSV',      // Menu title
        'manage_options',              // Capability
        'custom-auth-suite-export-subscribers-csv', // Menu slug
        'custausu_export_subscribers_csv_page' // Callback
    );
});

if (!function_exists('custausu_export_subscribers_csv_url')) {
    function custausu_export_subscribers_csv_url(): string {
        return wp_nonce_url(
            admin_url('admin-post.php?action=custom_auth_suite_export_subscribers_csv'),
            'custom_auth_suite_export_subscribers_csv_action',
            'custom_auth_suite_export_subscribers_csv_nonce'
        );
    }
}

// Callback for the Users > Export Subscribers CSV page.
function custausu_export_subscribers_csv_page(): void {
    if (!current_user_can('manage_options')) {
        wp_die('Unauthorized');
    }

    echo '<div class="wrap">';
    echo '<h1>Export Subscribers CSV</h1>';
    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Export subscribers box renderer returns controlled escaped admin HTML.
    echo custausu_export_subscribers_csv_box(true);
    echo '</div>';
}

if (!function_exists('custausu_export_subscribers_csv_box')) {
    function custausu_export_subscribers_csv_box(bool $use_form = true): string {
        if (!current_user_can('manage_options')) {
            return '';
        }

        $export_url = $use_form
            ? admin_url('admin-post.php?action=custom_auth_suite_export_subscribers_csv')
            : custausu_export_subscribers_csv_url();

        ob_start();

        echo '<div class="custausu-export-subscribers-box">';
        echo '<h2 class="custausu-export-subscribers-box__title">Export Subscribers CSV</h2>';
        echo '<p class="custausu-export-subscribers-box__desc">';
        echo esc_html__('Download a CSV file containing all WordPress users with the Subscriber role.', 'custom-auth-suite');
        echo '</p>';

        echo '<p class="custausu-export-subscribers-box__actions">';

        if ($use_form) {
            echo '<form method="post" action="' . esc_url($export_url) . '">';
            wp_nonce_field('custom_auth_suite_export_subscribers_csv_action', 'custom_auth_suite_export_subscribers_csv_nonce');
            echo '<input type="submit" class="button button-primary" value="' . esc_attr__('Download CSV', 'custom-auth-suite') . '">';
            echo '</form>';
        } else {
            echo '<a class="button button-primary" href="' . esc_url($export_url) . '">';
            echo esc_html__('Download CSV', 'custom-auth-suite');
            echo '</a>';
        }

        echo '</p>';
        echo '</div>';

        return (string) ob_get_clean();
    }
}

// Hook for the CSV export action.
add_action('admin_post_custom_auth_suite_export_subscribers_csv', 'custausu_handle_export_subscribers_csv');

function custausu_handle_export_subscribers_csv(): void {
    if (!current_user_can('manage_options')) {
        wp_die('Unauthorized');
    }

    check_admin_referer('custom_auth_suite_export_subscribers_csv_action', 'custom_auth_suite_export_subscribers_csv_nonce');

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=subscribers.csv');
    $output = fopen('php://output', 'w');

    // Headers.
    fputcsv($output, ['User ID','First Name','Second Name','Last Name','Email','Username','Registered'], ',', '"', '');

    // Query subscriber users.
    $subscribers = get_users([
        'role' => 'subscriber',
        'orderby' => 'ID',
        'order' => 'ASC',
    ]);

    foreach ($subscribers as $user) {
        $first_name = get_user_meta($user->ID, 'first_name', true);
        $last_name  = get_user_meta($user->ID, 'last_name', true);

        // Split second name when present.
        $first_word  = '';
        $second_word = '';
        if (!empty($first_name)) {
            $parts = explode(' ', trim($first_name));
            $first_word  = $parts[0];
            $second_word = isset($parts[1]) ? $parts[1] : '';
        }

        fputcsv($output, [
            $user->ID,
            $first_word,
            $second_word,
            $last_name,
            $user->user_email,
            $user->user_login,
            $user->user_registered,
        ], ',', '"', '');
    }

    exit; // Essenziale: blocca WordPress e invia solo il CSV
}