<?php


////////////////////////////////////////////////
////// USER COMPLETE DELETION //////////////////
////////////////////////////////////////////////

function pc_user_del_ajax() {
	global $wpdb, $pc_users;
	
	if(!isset($_POST['type']) || $_POST['type'] != 'pc_del_user_ajax' || !isset($_POST['pc_ud_psw'])) {
		return true;
	}
	
	
	// be sure user is logged
	if(!isset($GLOBALS['pc_user_id'])) {
		echo json_encode(array(
			'resp' => 'error',
			'mess' => __('No user logged', 'pc_ml')
		));	
		die();	
	}
	$user_id = (int)$GLOBALS['pc_user_id'];
	
	
	// get submitted password
	$psw = (string)$_POST['pc_ud_psw'];
	if(trim($psw) === '') {
		
		echo json_encode(array(
			'resp' => 'error',
			'mess' => __('Please insert your password', 'pc_ml')
		));	
		die();	
	}
	
	
	
	// query the database to check password
	$db_psw = $pc_users->get_user_field($user_id, 'psw'); 
	if(!wp_check_password($psw, $db_psw)) {
		echo json_encode(array(
			'resp' => 'error',
			'mess' => __('Wrong password', 'pc_ml')
		));	
		die();		
	}
	
	
	// PC-ACTION - action right before an user is deleted by its own choice
	do_action('pc_pre_self_user_del', $user_id);

	
	// unlog and delete user
	if( $pc_users->delete_user($user_id) ) {
		pc_logout();
		
		// success message	
		echo json_encode(array(
			'resp' => 'success',
			'mess' => __('Account successfully deleted!', 'pc_ml')
		));		
	}
	else {
		
		echo json_encode(array(
			'resp' => 'error',
			'mess' => 'Error deleting user - please contact the admin'
		));	
	}
			
	die(); // security block
}
add_action('init', 'pc_user_del_ajax', 3); // allow sessions setup
