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

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

/**
 * Register AJAX handlers.
 */
add_action( 'wp_ajax_wpum_save_export_schedule', 'wpum_handle_save_export_schedule' );

/**
 * Add custom cron schedules (weekly and monthly).
 */
add_filter( 'cron_schedules', 'wpum_add_custom_cron_schedules' );
function wpum_add_custom_cron_schedules( $schedules ) {
	$schedules['weekly'] = array(
		'interval' => WEEK_IN_SECONDS,
		'display'  => __( 'Once Weekly', 'clicks-user-manager' ),
	);
	$schedules['monthly'] = array(
		'interval' => 30 * DAY_IN_SECONDS,
		'display'  => __( 'Once Monthly', 'clicks-user-manager' ),
	);
	return $schedules;
}

/**
 * Hook the cron event.
 */
add_action( 'wpum_run_scheduled_export', 'wpum_execute_scheduled_export' );

/**
 * Save schedule configuration.
 */
function wpum_handle_save_export_schedule() {
	check_ajax_referer( 'wpum_export_nonce', 'nonce' );

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( array( 'message' => __( 'Permission denied.', 'clicks-user-manager' ) ) );
	}

	if ( ! wpum_is_pro() ) {
		wp_send_json_error( array( 'message' => __( 'Scheduled Exports is a Premium feature. Please upgrade to Pro.', 'clicks-user-manager' ) ) );
	}

	$enabled   = isset( $_POST['enabled'] ) ? '1' === $_POST['enabled'] : false;
	$frequency = isset( $_POST['frequency'] ) ? sanitize_key( $_POST['frequency'] ) : 'daily';
	$segment   = isset( $_POST['segment'] ) ? sanitize_key( $_POST['segment'] ) : '';
	$dest      = isset( $_POST['dest'] ) ? sanitize_key( $_POST['dest'] ) : 'email';
	$email     = isset( $_POST['email'] ) ? sanitize_email( $_POST['email'] ) : '';
	$webhook   = isset( $_POST['webhook'] ) ? esc_url_raw( $_POST['webhook'] ) : '';
	$cols      = isset( $_POST['cols'] ) ? array_map( 'sanitize_key', (array) $_POST['cols'] ) : array();

	if ( $enabled ) {
		if ( 'email' === $dest && empty( $email ) ) {
			wp_send_json_error( array( 'message' => __( 'Please enter a valid email address.', 'clicks-user-manager' ) ) );
		}
		if ( 'webhook' === $dest && empty( $webhook ) ) {
			wp_send_json_error( array( 'message' => __( 'Please enter a valid webhook URL.', 'clicks-user-manager' ) ) );
		}
		if ( empty( $cols ) ) {
			wp_send_json_error( array( 'message' => __( 'Please select at least one column to export.', 'clicks-user-manager' ) ) );
		}
	}

	$config = array(
		'enabled'   => $enabled,
		'frequency' => $frequency,
		'segment'   => $segment,
		'dest'      => $dest,
		'email'     => $email,
		'webhook'   => $webhook,
		'cols'      => $cols,
	);

	update_option( '_wpum_scheduled_exports_config', $config );

	// Reschedule cron
	wp_clear_scheduled_hook( 'wpum_run_scheduled_export' );
	if ( $enabled ) {
		wp_schedule_event( time() + HOUR_IN_SECONDS, $frequency, 'wpum_run_scheduled_export' );
	}

	wp_send_json_success( array( 'message' => __( 'Export schedule updated successfully.', 'clicks-user-manager' ) ) );
}

/**
 * Execute cron-triggered scheduled export.
 */
function wpum_execute_scheduled_export() {
	$config = get_option( '_wpum_scheduled_exports_config' );
	if ( ! $config || empty( $config['enabled'] ) ) {
		return;
	}

	// 1. Gather users matching the saved segment filters
	$params = array( 'no_pagination' => true );
	if ( ! empty( $config['segment'] ) ) {
		$segments = wpum_get_saved_segments();
		foreach ( $segments as $seg ) {
			if ( $seg['id'] === $config['segment'] ) {
				$params = array_merge( $params, $seg['params'] );
				break;
			}
		}
	}

	$query_args = wpum_build_query_args( $params );
	$user_query = new WP_User_Query( $query_args );
	$users      = $user_query->get_results();

	if ( empty( $users ) ) {
		return; // Nothing to export
	}

	// 2. Generate CSV contents
	$temp_file = wp_tempnam( 'wpum_export_' );
	$fp = fopen( $temp_file, 'w' );
	if ( ! $fp ) {
		return;
	}

	// BOM for Excel
	fwrite( $fp, "\xEF\xBB\xBF" );

	// Headers
	$all_headers = wpum_get_export_columns();
	$cols = $config['cols'];
	$header_row = array();
	foreach ( $cols as $c ) {
		if ( isset( $all_headers[ $c ] ) ) {
			$header_row[] = $all_headers[ $c ];
		}
	}
	fputcsv( $fp, $header_row );

	// Rows
	$wc_active = wpum_is_woocommerce_active();
	$order_counts = $wc_active ? wpum_get_customer_order_counts() : array();

	foreach ( $users as $user ) {
		$row = array();
		foreach ( $cols as $c ) {
			switch ( $c ) {
				case 'id':
					$row[] = $user->ID;
					break;
				case 'username':
					$row[] = $user->user_login;
					break;
				case 'email':
					$row[] = $user->user_email;
					break;
				case 'name':
					$row[] = trim( $user->first_name . ' ' . $user->last_name );
					break;
				case 'role':
					$row[] = implode( ', ', $user->roles );
					break;
				case 'registered':
					$row[] = $user->user_registered;
					break;
				case 'last_login':
					$last_login = get_user_meta( $user->ID, '_wpum_last_login', true );
					$row[] = $last_login ? $last_login : '';
					break;
				case 'post_count':
					$row[] = wpum_count_user_published_posts( $user->ID );
					break;
				case 'orders':
					$row[] = isset( $order_counts[ $user->ID ] ) ? $order_counts[ $user->ID ] : 0;
					break;
				default:
					// Treat as user meta
					$row[] = get_user_meta( $user->ID, $c, true );
					break;
			}
		}
		fputcsv( $fp, $row );
	}

	fclose( $fp );

	// 3. Deliver
	if ( 'email' === $config['dest'] ) {
		$to      = $config['email'];
		$subject = sprintf( __( 'Scheduled Users Export - %s', 'clicks-user-manager' ), gmdate( 'Y-m-d' ) );
		$body    = __( 'Please find attached the scheduled users export CSV file generated by Clicks User Manager.', 'clicks-user-manager' );
		$headers = array( 'Content-Type: text/html; charset=UTF-8' );
		
		// Create attachment rename
		$final_filename = 'users-scheduled-export-' . gmdate( 'Y-m-d' ) . '.csv';
		$renamed_temp   = dirname( $temp_file ) . '/' . $final_filename;
		copy( $temp_file, $renamed_temp );

		wp_mail( $to, $subject, $body, $headers, array( $renamed_temp ) );

		unlink( $temp_file );
		unlink( $renamed_temp );
	} elseif ( 'webhook' === $config['dest'] ) {
		$csv_data = file_get_contents( $temp_file );
		unlink( $temp_file );

		wp_remote_post( $config['webhook'], array(
			'method'    => 'POST',
			'body'      => array(
				'filename' => 'users-scheduled-export-' . gmdate( 'Y-m-d' ) . '.csv',
				'date'     => gmdate( 'Y-m-d H:i:s' ),
				'csv_raw'  => $csv_data,
			),
			'timeout'   => 15,
		) );
	}
}
