<?php
global $czpf_plugin;

require_once(RHCCZPF_PATH.'inc/class.object_controler.php');
function send_error_die($msg){
	die(json_encode(array('R'=>'ERR','MSG'=>$msg)));
}

if(!is_user_logged_in()){
	send_error_die(__('You are not logged in.','rhc'));
}

$current_user = wp_get_current_user();
$object = new czpf_class_object_controler( RHCCZPF_URL );
$tmp_list = $object->all_objects();
$tmp_no_referenace = false;

foreach($tmp_list as $tmp){
	if(!empty($_REQUEST['tmp_savepos']) && !empty($_REQUEST['tmp_save']) && $_REQUEST['tmp_savepos'] == $tmp['savepoint'] && $_REQUEST['tmp_save'] == $tmp['save']){
		$tmp_no_referenace = true;
		break;
	}
}
	
if(!$tmp_no_referenace && $_REQUEST['tmp_object'] != 'custom'){
	send_error_die(__('No correct data','rhc'));
}



if(!empty($_REQUEST['tmp_savepos']) && $_REQUEST['tmp_savepos'] == 'users'){

	if($_REQUEST['tmp_save'] = 'user_email'){
		if($current_user->user_email == $_REQUEST['tmp_value']){
			die(json_encode(array('R'=>'OK','MSG'=>__('Save done','rhc'))));
		}

		if( email_exists( $_REQUEST['tmp_value'] )) {
			send_error_die(__('Email exists','rhc'));
		}
		
		if(!filter_var( $_REQUEST['tmp_value'], FILTER_VALIDATE_EMAIL )){
			send_error_die(__('Is not a valid email','rhc'));
		}
		
		wp_update_user( array ( 'ID' => $current_user->ID, 'user_email' => $_REQUEST['tmp_value'] ) ) ;
	}
} else if(!empty($_REQUEST['tmp_savepos']) && $_REQUEST['tmp_savepos'] == 'usermeta'){

	if($_REQUEST['tmp_save'] == 'full_name'){
	 
	 	$tmpvar = explode(' ',$_REQUEST['tmp_value']);
	 	
	 	if(!empty($tmpvar[0])){
		 	update_user_meta( $current_user->ID, 'first_name', $tmpvar[0] );
	 	}
	 	
	 	if(count($tmpvar) > 1){
		 	if(!empty($tmpvar[1])){
		 		$_REQUEST['tmp_value'] = $tmpvar[1];
		 	}
		 	if(!empty($tmpvar[2])){
		 		$_REQUEST['tmp_value'] .= ' '. $tmpvar[2];
		 	}
		 	if(!empty($tmpvar[3])){
		 		$_REQUEST['tmp_value'] .= ' '. $tmpvar[3];
		 	} 	
		 	if(!empty($tmpvar[4])){
		 		$_REQUEST['tmp_value'] .= ' '. $tmpvar[4];
		 	}
		 	if(!empty($tmpvar[5])){
		 		$_REQUEST['tmp_value'] .= ' '. $tmpvar[5];
		 	}
		 	if(!empty($tmpvar[6])){
		 		$_REQUEST['tmp_value'] .= ' '. $tmpvar[6];
		 	}
		 	
		 	update_user_meta( $current_user->ID, 'last_name', $_REQUEST['tmp_value'] );
	 	}
	} else {
	 	update_user_meta( $current_user->ID, $_REQUEST['tmp_save'], $_REQUEST['tmp_value'] );
	}



}

update_user_meta( $current_user->ID, 'editdate', date('Y-m-d H:i:s'));


die(json_encode(array('R'=>'OK','MSG'=>__('Save done','rhc'))));
?>