<?php
/**
 * Export functionality for Clicks User Manager.
 *
 * @package WP_User_Management
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Render the Export Users admin page.
 */
function wpum_render_export_page() {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'Permission denied.', 'clicks-user-manager' ) );
	}

	$all_columns = wpum_get_export_columns();

	?>
	<div class="wrap wpum-wrap">
		<?php wpum_upsell_banner(); ?>
		<h1><?php esc_html_e( 'Export Users', 'clicks-user-manager' ); ?></h1>
		<p class="description"><?php esc_html_e( 'Export all or filtered users to a CSV file. Customise which columns to include.', 'clicks-user-manager' ); ?></p>

		<div class="wpum-card">
			<h2><?php esc_html_e( 'Export Options', 'clicks-user-manager' ); ?></h2>

			<form id="wpum-export-form">
				<?php wp_nonce_field( 'wpum_export_nonce', 'wpum_export_nonce' ); ?>

				<!-- Filters -->
				<div class="wpum-form-section">
					<h3><?php esc_html_e( 'Filter Users', 'clicks-user-manager' ); ?></h3>
					<table class="form-table wpum-form-table">
						<tr>
							<th><label for="exp_role"><?php esc_html_e( 'Role', 'clicks-user-manager' ); ?></label></th>
							<td>
								<select id="exp_role" name="role">
									<?php wpum_role_dropdown_options(); ?>
								</select>
							</td>
						</tr>
						<tr>
							<th><label for="exp_date_from"><?php esc_html_e( 'Registered From', 'clicks-user-manager' ); ?></label></th>
							<td>
								<input type="date" id="exp_date_from" name="date_from" />
							</td>
						</tr>
						<tr>
							<th><label for="exp_date_to"><?php esc_html_e( 'Registered To', 'clicks-user-manager' ); ?></label></th>
							<td>
								<input type="date" id="exp_date_to" name="date_to" />
							</td>
						</tr>
						<tr>
							<th><label for="exp_last_login"><?php esc_html_e( 'Last Login', 'clicks-user-manager' ); ?></label></th>
							<td>
								<select id="exp_last_login" name="last_login">
									<option value=""><?php esc_html_e( 'Any', 'clicks-user-manager' ); ?></option>
									<option value="today"><?php esc_html_e( 'Today', 'clicks-user-manager' ); ?></option>
									<option value="this_week"><?php esc_html_e( 'This Week', 'clicks-user-manager' ); ?></option>
									<option value="this_month"><?php esc_html_e( 'This Month', 'clicks-user-manager' ); ?></option>
									<option value="never"><?php esc_html_e( 'Never Logged In', 'clicks-user-manager' ); ?></option>
								</select>
							</td>
						</tr>
						<tr>
							<th><label for="exp_inactive"><?php esc_html_e( 'Inactive For', 'clicks-user-manager' ); ?></label></th>
							<td>
								<select id="exp_inactive" name="inactive">
									<option value=""><?php esc_html_e( 'Any', 'clicks-user-manager' ); ?></option>
									<option value="30"><?php esc_html_e( 'Last 30 days', 'clicks-user-manager' ); ?></option>
									<option value="60"><?php esc_html_e( 'Last 60 days', 'clicks-user-manager' ); ?></option>
									<option value="90"><?php esc_html_e( 'Last 90 days', 'clicks-user-manager' ); ?></option>
								</select>
							</td>
						</tr>
						<?php if ( wpum_is_woocommerce_active() ) : ?>
						<tr>
							<th><label for="exp_orders"><?php esc_html_e( 'WooCommerce Orders', 'clicks-user-manager' ); ?></label></th>
							<td>
								<select id="exp_orders" name="orders">
									<option value=""><?php esc_html_e( 'Any', 'clicks-user-manager' ); ?></option>
									<option value="has_orders"><?php esc_html_e( 'Has Ordered', 'clicks-user-manager' ); ?></option>
									<option value="no_orders"><?php esc_html_e( 'No Orders', 'clicks-user-manager' ); ?></option>
									<option value="1"><?php esc_html_e( '1 Order', 'clicks-user-manager' ); ?></option>
									<option value="2_5"><?php esc_html_e( '2–5 Orders', 'clicks-user-manager' ); ?></option>
									<option value="6_plus"><?php esc_html_e( '6+ Orders', 'clicks-user-manager' ); ?></option>
								</select>
							</td>
						</tr>
						<?php endif; ?>
					</table>
				</div>

				<!-- Column selector -->
				<div class="wpum-form-section">
					<h3><?php esc_html_e( 'Columns to Export', 'clicks-user-manager' ); ?></h3>
					<p class="description">
						<a href="#" id="wpum-check-all-cols"><?php esc_html_e( 'Select All', 'clicks-user-manager' ); ?></a>
						&nbsp;|&nbsp;
						<a href="#" id="wpum-uncheck-all-cols"><?php esc_html_e( 'Deselect All', 'clicks-user-manager' ); ?></a>
					</p>
					<div class="wpum-column-checkboxes">
						<?php foreach ( $all_columns as $col_key => $col_label ) : ?>
							<label class="wpum-col-check">
								<input type="checkbox" name="export_cols[]" value="<?php echo esc_attr( $col_key ); ?>" checked />
								<?php echo esc_html( $col_label ); ?>
							</label>
						<?php endforeach; ?>
					</div>
				</div>

				<div class="wpum-form-actions">
					<button type="button" id="wpum-do-export" class="button button-primary button-large">
						<span class="dashicons dashicons-download"></span>
						<?php esc_html_e( 'Export to CSV', 'clicks-user-manager' ); ?>
					</button>
					<span class="wpum-spinner" id="wpum-export-spinner" style="display:none;"></span>
					<span class="wpum-action-status" id="wpum-export-status"></span>
				</div>
			</form>
		</div>

		<!-- Scheduled Exports Card -->
		<div class="wpum-card" style="margin-top: 20px; position:relative;">
			<h2>
				<span class="dashicons dashicons-calendar-alt" style="vertical-align: middle; margin-right: 5px;"></span>
				<?php esc_html_e( 'Scheduled Exports', 'clicks-user-manager' ); ?>
				<?php if ( ! wpum_is_pro() ) : ?>
					<span class="wpum-pro-badge-inline" style="background:#ffb900; color:#000; font-size:10px; padding:2px 6px; border-radius:3px; margin-left:5px; font-weight:bold; vertical-align:middle; text-transform:uppercase;">PRO</span>
				<?php endif; ?>
			</h2>
			
			<?php
			$sched_config = get_option( '_wpum_scheduled_exports_config', array(
				'enabled'   => false,
				'frequency' => 'daily',
				'segment'   => '',
				'dest'      => 'email',
				'email'     => get_option( 'admin_email' ),
				'webhook'   => '',
				'cols'      => array_keys( $all_columns ),
			) );
			
			$segments = wpum_get_saved_segments();
			?>

			<form id="wpum-schedule-form">
				<?php if ( ! wpum_is_pro() ) : ?>
					<div class="wpum-pro-overlay" style="position:absolute; inset:0; background:rgba(255, 255, 255, 0.8); display:flex; align-items:center; justify-content:center; flex-direction:column; z-index:10; border-radius:4px;">
						<span style="font-size:32px; display:block; margin-bottom:10px;">🔒</span>
						<h3><?php esc_html_e( 'Scheduled Exports is a Pro Feature', 'clicks-user-manager' ); ?></h3>
						<p><?php esc_html_e( 'Upgrade to the Premium version to run automated exports sent directly to your Email or Webhook.', 'clicks-user-manager' ); ?></p>
						<p style="margin-top:15px;"><a href="<?php echo esc_url( admin_url( 'admin.php?page=clicks-user-manager-about' ) ); ?>" class="button button-primary"><?php esc_html_e( 'Upgrade to Pro', 'clicks-user-manager' ); ?></a></p>
					</div>
				<?php endif; ?>

				<table class="form-table wpum-form-table">
					<tr>
						<th><label for="wpum-sched-enabled"><?php esc_html_e( 'Enable Scheduled Export', 'clicks-user-manager' ); ?></label></th>
						<td>
							<input type="checkbox" id="wpum-sched-enabled" name="enabled" value="1" <?php checked( ! empty( $sched_config['enabled'] ) ); ?> />
							<span class="description"><?php esc_html_e( 'Run this export automatically on a background schedule.', 'clicks-user-manager' ); ?></span>
						</td>
					</tr>
					<tr class="wpum-sched-field">
						<th><label for="wpum-sched-freq"><?php esc_html_e( 'Frequency', 'clicks-user-manager' ); ?></label></th>
						<td>
							<select id="wpum-sched-freq" name="frequency">
								<option value="daily" <?php selected( $sched_config['frequency'], 'daily' ); ?>><?php esc_html_e( 'Daily', 'clicks-user-manager' ); ?></option>
								<option value="weekly" <?php selected( $sched_config['frequency'], 'weekly' ); ?>><?php esc_html_e( 'Weekly', 'clicks-user-manager' ); ?></option>
								<option value="monthly" <?php selected( $sched_config['frequency'], 'monthly' ); ?>><?php esc_html_e( 'Monthly', 'clicks-user-manager' ); ?></option>
							</select>
						</td>
					</tr>
					<tr class="wpum-sched-field">
						<th><label for="wpum-sched-segment"><?php esc_html_e( 'Filter Segment to Export', 'clicks-user-manager' ); ?></label></th>
						<td>
							<select id="wpum-sched-segment" name="segment">
								<option value=""><?php esc_html_e( 'Export all users (No filters)', 'clicks-user-manager' ); ?></option>
								<?php foreach ( $segments as $seg ) : ?>
									<option value="<?php echo esc_attr( $seg['id'] ); ?>" <?php selected( $sched_config['segment'], $seg['id'] ); ?>>
										<?php echo esc_html( $seg['name'] ); ?>
									</option>
								<?php endforeach; ?>
							</select>
						</td>
					</tr>
					<tr class="wpum-sched-field">
						<th><label for="wpum-sched-dest"><?php esc_html_e( 'Delivery Destination', 'clicks-user-manager' ); ?></label></th>
						<td>
							<select id="wpum-sched-dest" name="dest">
								<option value="email" <?php selected( $sched_config['dest'], 'email' ); ?>><?php esc_html_e( 'Email Attachment', 'clicks-user-manager' ); ?></option>
								<option value="webhook" <?php selected( $sched_config['dest'], 'webhook' ); ?>><?php esc_html_e( 'Webhook (POST request)', 'clicks-user-manager' ); ?></option>
							</select>
						</td>
					</tr>
					<tr class="wpum-sched-field wpum-sched-dest-email">
						<th><label for="wpum-sched-email"><?php esc_html_e( 'Recipient Email', 'clicks-user-manager' ); ?></label></th>
						<td>
							<input type="email" id="wpum-sched-email" name="email" value="<?php echo esc_attr( $sched_config['email'] ); ?>" class="regular-text" />
						</td>
					</tr>
					<tr class="wpum-sched-field wpum-sched-dest-webhook" style="display:none;">
						<th><label for="wpum-sched-webhook"><?php esc_html_e( 'Webhook URL', 'clicks-user-manager' ); ?></label></th>
						<td>
							<input type="url" id="wpum-sched-webhook" name="webhook" value="<?php echo esc_attr( $sched_config['webhook'] ); ?>" class="regular-text" />
						</td>
					</tr>
					<tr class="wpum-sched-field">
						<th><?php esc_html_e( 'Columns to include', 'clicks-user-manager' ); ?></th>
						<td>
							<div class="wpum-column-checkboxes">
								<?php foreach ( $all_columns as $col_key => $col_label ) : ?>
									<label class="wpum-col-check">
										<input type="checkbox" name="sched_cols[]" value="<?php echo esc_attr( $col_key ); ?>" <?php checked( in_array( $col_key, (array) $sched_config['cols'], true ) ); ?> />
										<?php echo esc_html( $col_label ); ?>
									</label>
								<?php endforeach; ?>
							</div>
						</td>
					</tr>
				</table>

				<div class="wpum-form-actions">
					<button type="button" id="wpum-save-schedule" class="button button-primary button-large">
						<?php esc_html_e( 'Save Schedule Settings', 'clicks-user-manager' ); ?>
					</button>
					<span class="wpum-spinner" id="wpum-sched-spinner" style="display:none;"></span>
					<span class="wpum-action-status" id="wpum-sched-status"></span>
				</div>
			</form>
		</div>
	</div>
	<?php
}

/**
 * Get the list of exportable column keys and labels.
 *
 * @return array
 */
function wpum_get_export_columns() {
	$columns = array(
		'ID'            => __( 'ID', 'clicks-user-manager' ),
		'user_login'    => __( 'Username', 'clicks-user-manager' ),
		'first_name'    => __( 'First Name', 'clicks-user-manager' ),
		'last_name'     => __( 'Last Name', 'clicks-user-manager' ),
		'user_email'    => __( 'Email', 'clicks-user-manager' ),
		'role'          => __( 'Role', 'clicks-user-manager' ),
		'user_registered' => __( 'Registration Date', 'clicks-user-manager' ),
		'last_login'    => __( 'Last Login', 'clicks-user-manager' ),
		'post_count'    => __( 'Post Count', 'clicks-user-manager' ),
	);

	if ( wpum_is_woocommerce_active() ) {
		$columns['order_count'] = __( 'Order Count', 'clicks-user-manager' );
	}

	return $columns;
}

/**
 * Stream a CSV export based on query params.
 * Called from both the AJAX handler and direct form POST.
 */
function wpum_export_csv() {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'Permission denied.', 'clicks-user-manager' ) );
	}

	// Retrieve columns to export.
	$all_cols     = wpum_get_export_columns();
	$selected_cols = isset( $_POST['export_cols'] ) // phpcs:ignore WordPress.Security.NonceVerification
		? array_map( 'sanitize_key', (array) wp_unslash( $_POST['export_cols'] ) ) // phpcs:ignore WordPress.Security.NonceVerification
		: array_keys( $all_cols );

	$selected_cols = array_intersect( $selected_cols, array_keys( $all_cols ) );
	if ( empty( $selected_cols ) ) {
		$selected_cols = array_keys( $all_cols );
	}

	// Build query args (no pagination — export everything).
	$params                   = isset( $_POST ) ? wp_unslash( $_POST ) : array(); // phpcs:ignore WordPress.Security.NonceVerification
	$params['no_pagination']  = true;
	$args                     = wpum_build_query_args( $params );
	$args['count_total']      = false;
	$args['fields']      = 'all';

	$user_query = new WP_User_Query( $args );
	$users      = $user_query->get_results();

	$order_counts = in_array( 'order_count', $selected_cols, true ) ? wpum_get_customer_order_counts() : array();

	// Filename.
	$filename = 'users-export-' . gmdate( 'Y-m-d' ) . '.csv';

	// Headers.
	header( 'Content-Type: text/csv; charset=UTF-8' );
	header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
	header( 'Pragma: no-cache' );
	header( 'Expires: 0' );

	// BOM for Excel compatibility.
	echo "\xEF\xBB\xBF";

	$out = fopen( 'php://output', 'w' );

	// Header row.
	$header_row = array();
	foreach ( $selected_cols as $col ) {
		$header_row[] = isset( $all_cols[ $col ] ) ? $all_cols[ $col ] : $col;
	}
	fputcsv( $out, $header_row );

	// Data rows.
	foreach ( $users as $user ) {
		$row = array();
		foreach ( $selected_cols as $col ) {
			switch ( $col ) {
				case 'ID':
					$row[] = $user->ID;
					break;
				case 'user_login':
					$row[] = $user->user_login;
					break;
				case 'first_name':
					$row[] = get_user_meta( $user->ID, 'first_name', true );
					break;
				case 'last_name':
					$row[] = get_user_meta( $user->ID, 'last_name', true );
					break;
				case 'user_email':
					$row[] = $user->user_email;
					break;
				case 'role':
					$roles = $user->roles;
					$row[] = ! empty( $roles ) ? implode( ', ', $roles ) : '';
					break;
				case 'user_registered':
					$row[] = $user->user_registered;
					break;
				case 'last_login':
					$ll    = get_user_meta( $user->ID, '_wpum_last_login', true );
					$row[] = $ll ? $ll : '';
					break;
				case 'post_count':
					$row[] = wpum_count_user_published_posts( $user->ID );
					break;
				case 'order_count':
					$row[] = isset( $order_counts[ $user->ID ] ) ? $order_counts[ $user->ID ] : 0;
					break;
				default:
					$row[] = '';
			}
		}
		fputcsv( $out, $row );
	}

	fclose( $out ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose
	exit;
}
