<?php

if ( empty( $args[0] ) || empty( $args[1] ) ) {
	WP_CLI::error( 'Too few arguments. Usage: wp eval-file /path/to/user-login-change.php from_username to_username' );
}

$from_username = $args[0];
$to_username   = $args[1];

global $wpdb;

// sanity checks

// user_login
$q = $wpdb->prepare( "UPDATE $wpdb->users SET user_login = %s WHERE user_login = %s", $to, $from );
if ( false === $wpdb->query( $q ) ) {
	WP_CLI::error( 'Could not change the user_login value' );
}

// user_nicename
$q = $wpdb->prepare( "UPDATE $wpdb->users SET user_nicename = %s WHERE user_nicename = %s", $to, $from );
if ( false === $wpdb->query( $q ) ) {
	WP_CLI::error( 'Could not change the user_nicename value' );
}

$replace_tables = [
	buddypress()->activity->table_name,
	$wpdb->posts,
	$wpdb->comments
];

// URL swap.
$members_base = bp_get_root_domain() . '/' . bp_get_members_root_slug() . '/';
$from_url     = $members_base . $from_username . '/';
$to_url       = $members_base . $to_username . '/';

$url_sr_command = "search-replace --all-tables $from_url $to_url " . implode( ' ', $replace_tables );
WP_CLI::runcommand(
	$url_sr_command,
	[ 'exit_error' => true ]
);

// Mentions. Use regex to avoid replacing partials.
$from_mention = '@' . $from_username . '\\b';
$to_mention   = '@' . $to_username;
$mention_sr_command = "search-replace --regex --all-tables $from_username $to_username " . implode( ' ', $replace_tables );
WP_CLI::runcommand(
	$mention_sr_command,
	[ 'exit_error' => true ]
);
