<?php
/**
 * Smart Segments / Save Filter Templates functionality for Clicks User Manager.
 *
 * @package WP_User_Management
 */

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

/**
 * Register AJAX handlers for segments.
 */
add_action( 'wp_ajax_wpum_save_segment', 'wpum_handle_save_segment' );
add_action( 'wp_ajax_wpum_delete_segment', 'wpum_handle_delete_segment' );

/**
 * Retrieve saved segments.
 *
 * @return array Array of saved segments.
 */
function wpum_get_saved_segments() {
	$segments = get_option( '_wpum_saved_segments', array() );
	return is_array( $segments ) ? $segments : array();
}

/**
 * Handle AJAX request to save a filter segment.
 */
function wpum_handle_save_segment() {
	check_ajax_referer( 'wpum_nonce', 'nonce' );

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

	$segment_name = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '';
	$params_raw   = isset( $_POST['params'] ) ? (array) $_POST['params'] : array();

	if ( empty( $segment_name ) ) {
		wp_send_json_error( array( 'message' => __( 'Segment name cannot be empty.', 'clicks-user-manager' ) ) );
	}

	$segments = wpum_get_saved_segments();

	// Enforce Free limit of 1 saved segment
	if ( ! wpum_is_pro() && count( $segments ) >= 1 ) {
		wp_send_json_error( array(
			'message' => __( 'Free version limit reached: Upgrade to Pro to save unlimited filter templates.', 'clicks-user-manager' ),
			'is_limit_reached' => true
		) );
	}

	// Clean params
	$clean_params = array();
	$allowed_keys = array( 'role', 's', 'date_from', 'date_to', 'last_login', 'inactive', 'post_count', 'orders' );
	foreach ( $allowed_keys as $key ) {
		if ( isset( $params_raw[ $key ] ) ) {
			$clean_params[ $key ] = sanitize_text_field( $params_raw[ $key ] );
		}
	}

	$new_segment = array(
		'id'     => uniqid( 'seg_', true ),
		'name'   => $segment_name,
		'params' => $clean_params,
	);

	$segments[] = $new_segment;
	update_option( '_wpum_saved_segments', $segments );

	wp_send_json_success( array(
		'message'  => __( 'Segment saved successfully.', 'clicks-user-manager' ),
		'segment'  => $new_segment,
		'segments' => $segments,
	) );
}

/**
 * Handle AJAX request to delete a filter segment.
 */
function wpum_handle_delete_segment() {
	check_ajax_referer( 'wpum_nonce', 'nonce' );

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

	$segment_id = isset( $_POST['segment_id'] ) ? sanitize_key( $_POST['segment_id'] ) : '';

	if ( empty( $segment_id ) ) {
		wp_send_json_error( array( 'message' => __( 'Invalid parameters.', 'clicks-user-manager' ) ) );
	}

	$segments = wpum_get_saved_segments();
	$updated_segments = array();
	$found = false;

	foreach ( $segments as $seg ) {
		if ( $seg['id'] === $segment_id ) {
			$found = true;
			continue;
		}
		$updated_segments[] = $seg;
	}

	if ( $found ) {
		update_option( '_wpum_saved_segments', $updated_segments );
		wp_send_json_success( array(
			'message'  => __( 'Segment deleted successfully.', 'clicks-user-manager' ),
			'segments' => $updated_segments,
		) );
	} else {
		wp_send_json_error( array( 'message' => __( 'Segment not found.', 'clicks-user-manager' ) ) );
	}
}

/**
 * Render Segment Selector Dropdown on the admin filter bar.
 */
function wpum_render_segments_selector() {
	$segments = wpum_get_saved_segments();
	?>
	<div class="wpum-segment-wrap" style="display: inline-block; margin-right: 10px; vertical-align: middle;">
		<select id="wpum-segment-select" style="max-width: 200px;">
			<option value=""><?php esc_html_e( '— Load Saved Segment —', 'clicks-user-manager' ); ?></option>
			<?php foreach ( $segments as $seg ) : ?>
				<option value="<?php echo esc_attr( $seg['id'] ); ?>" data-params="<?php echo esc_attr( wp_json_encode( $seg['params'] ) ); ?>">
					<?php echo esc_html( $seg['name'] ); ?>
				</option>
			<?php endforeach; ?>
		</select>
		<button type="button" id="wpum-delete-segment-btn" class="button button-secondary" style="display:none;" title="<?php esc_attr_e( 'Delete this segment', 'clicks-user-manager' ); ?>">
			<span class="dashicons dashicons-trash" style="margin-top: 4px;"></span>
		</button>
		<button type="button" id="wpum-save-segment-trigger" class="button button-secondary" title="<?php esc_attr_e( 'Save current filters as segment', 'clicks-user-manager' ); ?>">
			<span class="dashicons dashicons-star-filled" style="margin-top: 4px; color: #ffb900;"></span>
			<?php esc_html_e( 'Save Segment', 'clicks-user-manager' ); ?>
		</button>
	</div>
	<?php
}
