<?php
/**
 * User
 *
 * @package Nisje
 */

namespace Dekode\Nisje\Resets;

/**
 * Setup user details.
 */
function user() {
	add_action( 'user_register', __NAMESPACE__ . '\map_user_profile' );
	add_action( 'personal_options_update', __NAMESPACE__ . '\map_user_profile' );
	add_action( 'edit_user_profile_update', __NAMESPACE__ . '\map_user_profile' );

	add_action( 'bp_make_spam_user', __NAMESPACE__ . '\ham_to_spam', 1 );
	add_action( 'bp_make_ham_user', __NAMESPACE__ . '\spam_to_ham', 1 );
}
add_action( 'init', __NAMESPACE__ . '\user' );

/**
 * Setup default user states
 *
 * @param int $user_id User ID.
 */
function map_user_profile( $user_id ) {
	if ( ! is_admin() ) {
		return;
	}

	// Update not saved profile and last activity.
	if ( 'user_register' === current_action() ) {
		if ( function_exists( 'bp_update_user_last_activity' ) ) {
			bp_update_user_last_activity( $user_id );
		}
	}
}

/**
 * Ham to spam/inactive user.
 *
 * @param int $user_id The ID of the inactivated user.
 */
function ham_to_spam( $user_id ) {
	$profile_data = \BP_XProfile_ProfileData::get_all_for_user( $user_id );

	update_user_meta( $user_id, 'nisje_xprofile_backup', $profile_data );

	// Fallback name.
	$user         = get_userdata( $user_id );
	$display_name = $user->display_name;
	$anon_name    = apply_filters( 'nisje_deactivate_user_anonymous_name', $display_name, $user );

	update_user_meta( $user_id, 'nisje_display_name_backup', $display_name );

	wp_update_user( [
		'ID'           => $user_id,
		'display_name' => $anon_name,
	] );
}

/**
 * Spam to ham/reactivated user.
 *
 * @param int $user_id The ID of the rectivated user.
 */
function spam_to_ham( $user_id ) {
	$old_display_name = get_user_meta( $user_id, 'nisje_display_name_backup', true );

	// Fallback name.
	$user         = get_userdata( $user_id );
	$display_name = $user->display_name;

	if ( $old_display_name && ( $old_display_name !== $display_name ) ) {

		wp_update_user( [
			'ID'           => $user_id,
			'display_name' => $old_display_name,
		] );
	}
}
