<?php

function register_tapor_schema() {
	register_post_type(
		'tapor_tool',
		[
			'label'  => __( 'TAPoR Tools', 'tapor-client' ),
			'public' => true,
			'has_archive' => true,
			'rewrite' => array(
				'slug' => _x( 'tool', 'Tool rewrite slug', 'tapor-client' ),
				'with_front' => false,
			),
		]
	);

	register_taxonomy(
		'tapor_used_by_user',
		'tapor_tool',
		[
			'label'  => __( 'TAPoR Tool Users', 'tapor-client' ),
			'public' => false,
		]
	);

	register_taxonomy(
		'tapor_category',
		'tapor_tool',
		[
			'label'  => __( 'TAPoR Tool Category', 'tapor-client' ),
			'public' => true,
		]
	);
}

global $wpdb;

$dry_run = true;
if ( ! empty( $args[0] ) && 'no-dry-run' === $args[0] ) {
	$dry_run = false;
}

if ( $dry_run ) {
	WP_CLI::log( 'No "no-dry-run" argument found. This will be a dry run.' );
}

register_tapor_schema();

$tool_ids   = $wpdb->get_col( "SELECT ID FROM {$wpdb->posts} WHERE post_type = 'ddc_tool'" );
$no_matches = [];
$migrated   = [];
foreach ( $tool_ids as $tool_id ) {
	$post = get_post( $tool_id );

	// Fetch matching TAPoR tools by keyword, then narrow down to one with the same title.
	$keyword_match_query   = wp_remote_get( 'http://tapor.ca/api/tools?query=' . $post->post_title );
	$keyword_match_results = json_decode( wp_remote_retrieve_body( $keyword_match_query ) );

	$match = null;
	foreach ( $keyword_match_results->tools as $keyword_match ) {
		if ( $keyword_match->name === $post->post_title ) {
			$match = $keyword_match;
			break;
		}
	}

	if ( ! $match ) {
		$no_matches[ $tool_id ] = $post->post_title;
		continue;
	}

	$postarr = [
		'post_type'    => 'tapor_tool',
		'post_title'   => $match->name,
		'post_status'  => 'publish',
		'post_content' => $match->detail,
	];

	if ( $dry_run ) {
		continue;
	}

	$post_id = wp_insert_post( $postarr );

	if ( ! $post_id || is_wp_error( $post_id ) ) {
		var_dump( $postarr ); die;
	}

	update_post_meta( $post_id, 'tapor_id', $match->id );
	update_post_meta( $post_id, 'tapor_link', 'http://tapor.ca/tools/' . $match->id );
	update_post_meta( $post_id, 'tapor_image', 'http://tapor.ca/' . $match->image_url );

	// Separate request for tool attributes.
	$attributes_query   = wp_remote_get( 'http://tapor.ca/api/tools/' . $match->id . '/attributes' );
	$attributes_results = json_decode( wp_remote_retrieve_body( $attributes_query ) );

	$categories         = [];
	if ( $attributes_results ) {
		foreach ( $attributes_results as $attribute_type ) {
			if ( 'Type of analysis' === $attribute_type->name ) {
				foreach ( $attribute_type->selected as $selected ) {
					foreach ( $attribute_type->attribute_values as $attribute_value ) {
						if ( $attribute_value->id === $selected->id ) {
							$categories[] = $attribute_value->name;
							break;
						}
					}
				}

				break;
			}
		}
	}

	wp_set_object_terms( $post_id, $categories, 'tapor_category' );

	$retval = [
		'title'     => $match->name,
		'tapor_id'  => $match->id,
		'new_wp_id' => $post_id,
		'old_wp_id' => $post->ID,
		'users'     => [],
	];

	// Now we migrate 'use' data.
	$users = ddc_get_users_of_tool( $post->ID );
	foreach ( $users as $user_id ) {
		wp_set_object_terms( $post_id, 'tapor_tool_is_used_by_user_' . $user_id, 'tapor_used_by_user' );

		$retval['users'][] = $user_id;
	}

	$migrated[] = $retval;
}

if ( $no_matches ) {
	WP_CLI::log( "\n" );
	WP_CLI::log( 'The following sites have no correlates in TAPoR:' );
	print_r( $no_matches );
}

if ( ! $dry_run ) {
	WP_CLI::log( "\n" );
	WP_CLI::log( "Migrated the following tools:" );
	print_r( $migrated );
}

