<?php
add_action('mepr-event-member-deleted','my_mepr_event_member_deleted');
function my_mepr_event_member_deleted($userObj) {	
	
	// GET USER DATA
	$user = $userObj->get_data();
	
	// DELETE USER TAGGED POSTS
	$data_post_delete = array(
		'tags'   	=> array ( $user->user_nicename ),
	);
	delete_posts_by_tag($data_post_delete);	
	
	// DELETE USER TAGS
	delete_tag_by_slug( $user->user_nicename );
	$filter_tags = get_user_filter_tags($user);
	foreach ($filter_tags as $tag) {
		delete_tag_by_slug( $tag );
	}
	
	// DELETE MEMBERPRESS USER ACCESS RULE VIA RESTAPI
	$post_title = 'Posts Tagged: ' . $user->user_nicename . ' (auto)';
	$data_delete = array(
	  	'post_title'	=> $post_title,
		'post_type' 	=> 'memberpressrule',
	);
	$response = mbpr_restapi_delete_rule_by_title($data_delete);
	
	// RENEW MEMBERPRESS logged_in RULE
	renew_rule_logged_in();
	
	// DELETE USER FROM THE NETWORK AND REMOVE FROM ALL SITES (ALLOWS RE-REGISTRATION)
	require_once( ABSPATH . 'wp-admin/includes/ms.php' );
	wpmu_delete_user( $user->ID );
}

function renew_rule_logged_in() {
	$post_title = "All Content Tagged: logged_in (auto)";
	
	// DELETE RULE VIA RESTAPI
	$data_delete = array(
	  	'post_title'	=> $post_title,
		'post_type' 	=> 'memberpressrule',
	);
	$response = mbpr_restapi_delete_rule_by_title($data_delete);
	
	// ADD RULE VIA RESTAPI
	$logged_in = get_term_by('slug', 'logged_in', 'post_tag');
	$data_add = array(
	  	'post_title'   			=> $post_title,
		'access_type' 			=> 'membership',
	 	'access_operator'   	=> 'is',
		'access_condition' 		=> 172,
		'rule_type'   			=> 'all_tax_post_tag',
		'unauth_excerpt_type' 	=> 'more',
	 	'rule_content'    		=> $logged_in->term_id,
	);
	$response2 = mbpr_restapi_add_rule($data_add);
}

/*
add_action( 'delete_user', 'custom_remove_user', 10 );
function custom_remove_user( $user_id ) {
    $user_meta = get_userdata( $user_id );    // IF you need additional user info before removal
}
*/
