<?php
global $czpf_plugin;

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.');
}

if(empty($_REQUEST['tmp_post']) || !is_numeric($_REQUEST['tmp_post'])){
	send_error_die('Error contact support');
}

if(empty($_REQUEST['tmp_user_id']) || !is_numeric($_REQUEST['tmp_user_id'])){
	send_error_die('Error contact support');
}

add_action( 'init', 'create_post_typess' );	

function create_post_typess(){
    global $czpf_plugin,$wpdb,$wp_version;
    
   
    
    $tmp_check = $wpdb->get_var("SELECT userID FROM {$wpdb->prefix}rhc_groups_teams WHERE postID = ".$_REQUEST['tmp_post']." and userID = ".$_REQUEST['tmp_user_id'] . " LIMIT 1");
    
    if(empty($tmp_check)){
		$allow_all = get_post_meta($_REQUEST['tmp_post'], 'allow_all_users' , true);
	    $allow_all_sql = 1;
	    $allow_all_text = __('Pending','rhc');
	
	    if($allow_all == 'true'){
	    	$allow_all_text = __('Thank you<br>for joining','rhc');
		    $allow_all_sql = 2;
	    }
	    
	    
	    $wpdb->insert( 
			$wpdb->prefix.'rhc_groups_teams',
			array( 
				'status' => $allow_all_sql, 
				'postID' => $_REQUEST['tmp_post'],
				'userID' => $_REQUEST['tmp_user_id']
			), 
			array( 
				'%d',
				'%d',
				'%d' 
			) 
		);  
		
		die(json_encode(array('R'=>'OK','STATUS'=>$allow_all_text)));
    } else {
	    send_error_die('User has already been join');
    }
    


}
?>