<?php

global $wpdb;

$cv_ids = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_type = 'cac-cv'" );

foreach ( $cv_ids as $cv_id ) {
	$cv_post = get_post( $cv_id );
	if ( ! $cv_post || ( ! $cv_post instanceof WP_Post ) ) {
		continue;
	}

	$blocks = parse_blocks( $cv_post->post_content );
	if ( empty( $blocks ) ) {
		continue;
	}

	$position_blocks = \CAC\CVEditor\Blocks\CVPositions\find_position_blocks( $blocks );
	if ( ! $position_blocks ) {
		continue;
	}

	$user_id = $cv_post->post_author;

	$existing = xprofile_get_field_data( 2, $user_id, true );

	$all_campuses = cac_get_cuny_campuses();
	$campus_names = array_map(
		function ( $position ) use ( $all_campuses ) {
			if ( empty( $position['campus'] ) ) {
				return '';
			}

			$find = wp_filter_object_list(
				$all_campuses,
				[
					'full_name' => $position['campus'],
				]
			);

			return ! empty( $find ) ? $position['campus'] : '';

		},
		$position_blocks
	);

	$campus_names = array_filter( $campus_names );
	$campus_names = array_unique( $campus_names );

	// Both are empty - nothing to do.
	if ( empty( $existing ) && empty( $campus_names ) ) {
		continue;
	}

	$existing_array = (array) $existing;
	$update_value   = array_filter( array_unique( array_merge( $existing_array, $campus_names ) ) );

	// This mostly covers cases where the user has College value but no Positions in CV.
	if ( $existing_array == $update_value ) {
		continue;
	}

	WP_CLI::log( sprintf(
		'Changing user %d from "%s" to "%s"',
		$user_id,
		print_r( $existing, true ),
		implode( ', ', $update_value )
	) );

	/*
	$field           = new \BP_XProfile_ProfileData();
	$field->field_id = 2;
	$field->user_id  = $user_id
	$field->value    = maybe_serialize( $update_value );
	$field->save();
	*/
}
