<?php

$course_ids = get_posts(
	[
		'post_type'      => 'cac_course',
		'fields'         => 'ids',
		'posts_per_page' => -1,
	]
);

$progress_bar = \WP_CLI\Utils\make_progress_bar( 'Backfilling instructors for courses', count( $course_ids ) );

foreach ( $course_ids as $course_id ) {
	$course = new \CAC\Courses\Course( $course_id );

	$instructor_ids = $course->get_instructor_ids();

	$site_ids = $course->get_site_ids();
	if ( $site_ids ) {
		foreach ( $site_ids as $site_id ) {
			// Don't overwrite existing.
			$saved = bp_blogs_get_blogmeta( $site_id, 'cac_instructors' );
			if ( ! $saved ) {
				cac_set_site_instructors( $site_id, $instructor_ids );
				WP_CLI::log( 'Setting instructors for site ' . $site_id );
			}
		}
	}

	$group_ids = $course->get_group_ids();
	if ( $group_ids ) {
		foreach ( $group_ids as $group_id ) {
			// Don't overwrite existing.
			$saved = groups_get_groupmeta( $group_id, 'cac_instructors' );
			if ( ! $saved ) {
				groups_update_groupmeta( $group_id, 'cac_instructors', $instructor_ids );
				WP_CLI::log( 'Setting instructors for group ' . $group_id );
			}
		}
	}
//	print_r( $instructor_ids );

	$progress_bar->tick();
}

$progress_bar->finish();
