<?php

global $wpdb, $bp;

$raws = array_map( 'str_getcsv', file( $args[0] ) );
//var_dump( $raws );

foreach ( $raws as $index => $raw ) {
	// Skip first row.
	if ( 0 === $index ) {
		continue;
	}

	$course_name = $raw[0];
	$site_url    = $raw[1];
	$group_url   = $raw[2];
	$year        = $raw[5];
	$semester    = $raw[6];

	$instructors_raw = trim( $raw[3] );
	$instructors     = $instructors_raw ? array_map( 'trim', explode( ',', $instructors_raw ) ) : [];

	$campuses_raw = trim( $raw[4] );
	$campuses     = $campuses_raw ? array_map( 'trim', explode( ',', $campuses_raw ) ) : [];

	$group_id = null;
	if ( $group_url ) {
		$group_url  = rtrim( $group_url, '/' );
		$group_slug = substr( $group_url, strrpos( $group_url, '/' ) + 1 );

		$group_id = groups_get_id( $group_slug );
	}

	$site_id = null;
	if ( $site_url ) {
		$site_url_host = parse_url( $site_url, PHP_URL_HOST );
		$site_url_slug = array_shift( explode( '.', $site_url_host ) );

		$site_id = get_id_from_blogname( $site_url_slug );
	}

	// instructor fallback
	if ( empty( $instructors ) ) {
		if ( $group_id ) {
			$group = groups_get_group( $group_id );
			foreach ( $group->admins as $admin ) {
				$instructors[] = $admin->user_login;
			}
		} elseif ( $site_id ) {
			$site_admin = get_blog_option( $site_id, 'admin_email' );
			$admin_user = get_user_by( 'email', $site_admin );
			$instructors[] = $admin_user->user_login;
		}
	}

	$post_arr = [
		'post_type'   => 'cac_course',
		'post_status' => 'publish',
		'post_title'  => $course_name,
	];

	$post_id = wp_insert_post( $post_arr );

	$instructor_ids = array_map(
		function( $instructor_login ) {
			$user = get_user_by( 'login', $instructor_login );
			return $user->ID;
		},
		$instructors
	);
	add_post_meta( $post_id, 'instructor-ids', json_encode( $instructor_ids ) );

	add_post_meta( $post_id, 'campus-slugs', json_encode( $campuses ) );

	if ( $group_id ) {
		add_post_meta( $post_id, 'course-group-ids', json_encode( [ $group_id ] ) );
	}

	if ( $site_id ) {
		add_post_meta( $post_id, 'course-site-ids', json_encode( [ $site_id ] ) );
	}
}
