<?php 
/* template name: reactrequest */

include_once('../../../wp-config.php');
include_once('../../../wp-load.php');
include_once('../../../wp-includes/wp-db.php');
global $wpdb;

$request_data = json_decode(file_get_contents('php://input'), true);

if(!isset($_SESSION['client_token_key'])){
	$data  =array();
	$data['client_id'] =  'QojjBgcvYKuRciNLarQZEMXwI4j2Jk24';
	$data['client_secret'] =  'vERpwa1YHMpZnuovQ7z-shPb1GQc-naIl1rj2AJEgt-9j1cD-a9Er5-kEHjFKXKL';
	$data['audience']= 'https://familyone.auth0.com/api/v2/';
	$data['grant_type'] ='client_credentials';

	$url = 'https://familyone.auth0.com/oauth/token';
    $ch=curl_init($url);
    $data_string = json_encode($data);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
	curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    $result = curl_exec($ch);
    curl_close($ch);
	$response = json_decode($result);
	
	if($response->expires_in && $response->access_token){
		session_start();
		$_SESSION['expires_in'] = time()+$response->expires_in;
		$_SESSION['client_token_key'] = $response->access_token;
	}
}

$token_id = $_SESSION['client_token_key'];
$auth_authorization = $authorization = 'Bearer '.$token_id;

header('Access-Control-Allow-Origin: *');
//header("Access-Control-Allow-Headers", "X-PINGOTHER, Content-Type");
//header("Access-Control-Allow-Methods", "GET,POST");




if($request_data['action']=='signup'){
		unset($request_data['action']);
		$url = 'https://familyone.auth0.com/api/v2/users';
		$ch=curl_init($url);
		$data_string = json_encode($request_data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
		curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json','Authorization: '.$authorization));
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
		$result = curl_exec($ch);
		curl_close($ch);
		print_r($result);
}
elseif($request_data['action']=='login'){
		unset($request_data['action']);
		$url = 'https://familyone.auth0.com/passwordless/start';
		$ch=curl_init($url);
		$data_string = json_encode($request_data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
		curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json','Authorization: '.$authorization));
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
		$result = curl_exec($ch);
		curl_close($ch);
		print_r($result);

}elseif($request_data['action']=='addchild'){
					unset($request_data['action']);
					$member_id = getMemberId(9);
					$child_data = array();
					$child_data['connection'] = 'childdb';
					$child_data['email'] = $member_id.'@familyone.in';
					$child_data['password'] = 'bewnexus(123)';
					$child_data['user_metadata'] = $request_data;
					$url = 'https://familyone.auth0.com/api/v2/users';
					$authorization = 'Bearer '.$token_id;
					$ch=curl_init($url);
					$child_data_string = json_encode($child_data);
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
					curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json','Authorization: '.$authorization));
					curl_setopt($ch, CURLOPT_POSTFIELDS, $child_data_string);
					$child_reg_rspnse = curl_exec($ch);
					curl_close($ch);
					print_r($child_reg_rspnse);
}elseif($request_data['action']=='update'){
				$user_id = $request_data['user_id'];
				unset($request_data['user_id']);
				unset($request_data['action']);
				$url = 'https://familyone.auth0.com/api/v2/users/'.$user_id;
				$update_data_string = json_encode($request_data);
				$ch=curl_init($url);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
				curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PATCH');
				curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json','Authorization: '.$authorization));
				curl_setopt($ch, CURLOPT_POSTFIELDS, $update_data_string);
				$update_result = curl_exec($ch);
				curl_close($ch);
				print_r($update_result);
}elseif($request_data['action']=='get_information'){
	$user_id = $request_data['user_id'];
	$url = 'https://familyone.auth0.com/api/v2/users/'.$user_id;
	$ch=curl_init($url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
	curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json','Authorization: '.$authorization));
	$result = curl_exec($ch);
	curl_close($ch);
	print_r($result);
}elseif($request_data['action']=='getcontest'){
	global $wpdb;
	$contest_id = $request_data['contest_id'];
	$user_id = $request_data['user_id'];
	$current_date = date(Y-m-d);
	if($contest_id){
		$query = "select * from `family_contest` where _id=$contest_id AND expiry_date >= $current_date";
	}
	else{
		$contest_visible = check_contest_visible($user_id,$auth_authorization);
		
		$list_of_contestId = implode(',', $contest_visible);
		// direct member
		if(!empty($contest_visible)){
			$query = "select * from `family_contest` where expiry_date >= $current_date AND _id IN (".$list_of_contestId.")";
		}
	}
	$contest_result = $wpdb->get_results($query , ARRAY_A);
	echo json_encode($contest_result);
}
elseif($request_data['action']=='join_contest'){
	global $wpdb;
	$contest_id = $request_data['contest_id'];
	$user_id = $request_data['user_id'];
	$referer_user_id = $request_data['refered_user_id'];
	$is_social = $request_data['is_social'];
	
		// Function to get whether the user is direct participant or not
	
		$direct_member_relation = check_direct_participant($user_id,$contest_id,$auth_authorization);
		if($direct_member_relation){
			//Function to add entry point to referer user and user
			$user_entry_point = add_point_db($user_id,$contest_id,$referer_user_id,$is_social);
			  //if($user_entry_point){
					if($referer_user_id){
						// Function to get whether the referer user is direct participant or not
						$referer_user_type_direct = check_direct_participant($referer_user_id,$contest_id,$auth_authorization);
						if($referer_user_type_direct){
							addRefererpoint($referer_user_id,$contest_id,$user_id);
							//Function to add sharing point in direct referer member
							$direct_user_family_point = direct_user_family_point($user_id,$contest_id,$auth_authorization,$referer_user_id);
							if(!empty($direct_user_family_point)){
								echo json_encode(array('status'=>'OK'));
							}
							else{
								echo json_encode(array('error'=>'Not done'));
							}
						}
						else{
							//Function to add sharing point in direct referer member
							$indirect_user_family_point = indirect_user_family_point($user_id,$contest_id,$auth_authorization);
							if(!empty($indirect_user_family_point)){
								echo json_encode(array('status'=>'OK'));
							}
							else{
								echo json_encode(array('error'=>'Not done'));
							}
						}
					}
					else{
						$direct_user_family_point = direct_user_family_point($user_id,$contest_id,$auth_authorization,$referer_user_id);
							if(!empty($direct_user_family_point)){
								echo json_encode(array('status'=>'OK'));
							}
							else{
								echo json_encode(array('error'=>'Not done'));
							}
					}
			 // }
			 // else{
			 // 	echo json_encode(array('error'=>'User already entered in the contest'));
			 // }
		}
		else{

				// Function to get whether the referer user is direct participant or not
			if($referer_user_id){
				$referer_user_type_direct = check_direct_participant($referer_user_id,$contest_id);
				if($referer_user_type_direct){

					//Function to add entry point to referer user and user
					$user_and_referer_user_earn_point = addRefererpoint($referer_user_id,$contest_id);
				
					if(!empty($user_and_referer_user_earn_point)){
						echo json_encode(array('status'=>'OK'));
					}
					else{
						echo json_encode(array('error'=>'Not done'));
					}
				}
				else{
					$indirect_user_family_point = indirect_user_family_point($user_id,$contest_id,$auth_authorization);
						if(!empty($indirect_user_family_point)){
							echo json_encode(array('status'=>'OK'));
						}
						else{
							echo json_encode(array('error'=>'Not done'));
						}
				}
			}
			else{
				//Nothing right now
			}
				
			}
}
elseif($request_data['action']=='user_refer_user'){
	
			// set the data to store in the referer table
			$referer_user_id = $request_data['referer_user_id'];
			$reference_user_id = $request_data['reference_user_id'];
			$current_date = date('Y-m-d');
			$contest_id = $request_data['contest_id'];
			
			//Save data in the referer table

			$insert_in_referer_table = $wpdb->insert("referer_table", array('referer_user_id'=>$referer_user_id,'reference_user_id'=>$reference_user_id,'date'=>$current_date ,'contest_id'=>$contest_id));
			if(!empty($insert_in_referer_table)){
				echo json_encode(array('status'=>'OK'));
			}
			else{
				echo json_encode(array('error'=>'Not done'));
			}
		}
else{
	echo json_encode(array('error'=>'Please enter a valid action'));
}


// Function starts ......

function add_point_db($user_id,$contest_id,$referer_user_id,$is_social){
	global $wpdb;
	//Check whether the user already exist in the contest
	$is_user_existed = $wpdb->get_results("select `point` from `user_contest_point` where `contest_id`= $contest_id AND `player_user_id` = '".$user_id."'",ARRAY_A);
	if(!empty($is_user_existed)){
		return 0;
	}
	else{
		$user_existing_points = 0;
   		$entry_points = $wpdb->get_results("select `entry_point` from `family_contest` where `_id`=$contest_id",ARRAY_A);
   		
   		foreach ($entry_points as $value) {
   			$user_entry_points = $user_existing_points + $value['entry_point'];
   		}
   		
		$insert_user_contest_entry_point = $wpdb->insert('user_contest_point', array("player_user_id"=>$user_id,"contest_id"=>$contest_id,"point"=>$user_entry_points ,"point_type"=>"entry"));
		return 1;
	}
}

//To check whether the relation of direct member exist in the contest or not
function direct_user_family_point($user_id,$contest_id,$auth_authorization,$referer_user_id) {
	global $wpdb;
    $temp_relation_array=array();
	// Auth0 api call to get user data
	$url = 'https://familyone.auth0.com/api/v2/users/'.$user_id;
	$ch=curl_init($url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
	curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json','Authorization: '.$auth_authorization));
	$temp_result = curl_exec($ch);
	curl_close($ch);
	$result = json_decode($temp_result);
	// Making array of the child relation with the user
	foreach( $result->user_metadata->relation as $value ) {
		$temp_relation_array[] = "'".$value->user_id."'";
    }
	$relation_array = rtrim(implode(',', $temp_relation_array),',');
	// Check all relation user id which are related to user and are in the contest  
   	$direct_member_relation_in_contest = $wpdb->get_results("select * from `user_contest_point` where player_user_id IN ($relation_array) AND contest_id= $contest_id",ARRAY_A);
   	
	$family_sharing_points = $wpdb->get_results("select `family_share_point` from `family_contest` where `_id`= $contest_id",ARRAY_A);
		foreach ($family_sharing_points as $value) {
	   		$fam_share_point = $value['family_share_point'];
	   	}

	
	
	$count_participent = count($direct_member_relation_in_contest);
	   	if(!empty($direct_member_relation_in_contest)){
		   	foreach ($direct_member_relation_in_contest as $share_value) {
		   		$insert_share_point = $wpdb->insert('user_contest_point', array('point'=>$fam_share_point ,'point_type'=>"family_share_point",'reference_user_id'=>$share_value['player_user_id'],'player_user_id'=>$user_id,'contest_id'=>$contest_id));
			
			}
	   	}

	return 1;
}

//To check whether the relation of indirect member exist in the contest or not
function indirect_user_family_point($user_id,$contest_id,$auth_authorization) {
	global $wpdb;
    $temp_relation_array=array();
 	// Auth0 api call to get user data
 	$url = 'https://familyone.auth0.com/api/v2/users/'.$user_id;
 	$ch=curl_init($url);
 	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
 	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
 	curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json','Authorization: '.$auth_authorization));
 	$temp_result = curl_exec($ch);
 	curl_close($ch);
 	$result = json_decode($temp_result);

 	// Making array of the child relation with the user
 	foreach( $result->user_metadata->relation as $key=>$value ) {
 		//Get social share point
    		$social_sharing_points = $wpdb->get_results("select `social_share_point` from `family_contest` where `_id`= $contest_id",ARRAY_A);
    		foreach ($social_sharing_points as $value_social) {
    			$social_share_point = $value_social['social_share_point'];
    		}

	   		$insert_social_share_point = $wpdb->insert('user_contest_point', array('point'=>$social_share_point ,'point_type'=>"social_share_point",'player_user_id'=>$value->user_id,'reference_user_id'=>$user_id,'contest_id'=>$contest_id));
    }
    return 1;
}

// To check whether the user entered in the contest is direct participant or not
function check_direct_participant($user_id,$contest_id,$auth_authorization){
	global $wpdb;
	$user_id = $user_id;
	$contest_id = $contest_id;
	$temp_child_relation_array= array();
	// Auth0 api call to get user data
	$url = 'https://familyone.auth0.com/api/v2/users/'.$user_id;
	$ch=curl_init($url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
	curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json','Authorization: '.$auth_authorization));
	$temp_result = curl_exec($ch);
	curl_close($ch);
	$result = json_decode($temp_result);
	// Making array of the child relation with the user
	foreach( $result->user_metadata->child_data as $key=>$value ) {
			$temp_child_relation_array[] = "'".$value->relation."'";
        }
        $temp_child_relation_array[] = "'all'";

		$child_relations = rtrim(implode(',', $temp_child_relation_array),',');
    // Check all relation with contest direct member 
	$direct_member_relation = $wpdb->get_results("select * from `contest_member` WHERE `direct_member_relation` IN ($child_relations) AND `contest_id` = $contest_id",ARRAY_A);
	if(!empty($direct_member_relation)){
		return 1;
	}
	else{
		return 0;
	}
}

function addRefererpoint($referer_id, $contest_id,$user_id){
	global $wpdb;
	$user_entry_points = 0;
   		$family_share_point = $wpdb->get_results("select `family_share_point` from `family_contest` where `_id`=$contest_id",ARRAY_A);
   		
   		foreach ($family_share_point as $value) {
   			$user_entry_points = $user_entry_points + $value['family_share_point'];
   		}
    	
		$check_contest_point_exist = $wpdb->get_results("select * from `user_contest_point` where player_user_id = '".$referer_id."' AND contest_id=$contest_id",ARRAY_A);
		
		if(!empty($check_contest_point_exist)){
			
			
			$insert_user_contest_point = $wpdb->insert('user_contest_point', array("reference_user_id"=>$user_id,"player_user_id"=>$referer_id,"contest_id"=>$contest_id,"point"=>$user_entry_points ,"point_type"=>"family_share_point"));
		}
	return 1;
}

// To show contest only to the direct memmber 
function check_contest_visible($user_id,$auth_authorization){
	global $wpdb;
	$temp_child_relation_array= array();
	// Auth0 api call to get user data
	$url = 'https://familyone.auth0.com/api/v2/users/'.$user_id;
	$ch=curl_init($url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
	curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json','Authorization: '.$auth_authorization));
	$temp_result = curl_exec($ch);
	curl_close($ch);
	$result = json_decode($temp_result);

	// Making array of the child relation with the user
	foreach( $result->user_metadata->child_data as $value ) {
		    if($value->relation){
			 $temp_child_relation_array[] = "'".$value->relation."'";
		    }
        }
        $temp_child_relation_array[] = "'all'";

		$child_relations = rtrim(implode(',', $temp_child_relation_array),',');
		

	$existed_contest = $wpdb->get_results("select DISTINCT `contest_id` FROM `user_contest_point` WHERE `player_user_id`= '".$user_id."'",ARRAY_A);
	
		$list_of_visible_id = array();
		if(!empty($existed_contest)){
			foreach ($existed_contest as $id) {
				$list_of_visible_id[] = "'".$id['contest_id']."'";
			}
		}
		$contest_visible_id = rtrim(implode(',', $list_of_visible_id),',');
		// Check all relation with contest direct member 
		if(!empty($existed_contest)){
		$contest_visible = $wpdb->get_results("select * from `contest_member` WHERE `direct_member_relation` IN ($child_relations) AND `contest_id` NOT IN($contest_visible_id)",ARRAY_A);
		}
		else{
			$contest_visible = $wpdb->get_results("select * from `contest_member` WHERE `direct_member_relation` IN ($child_relations)",ARRAY_A);
		}

	$list_of_ids = array();
	if(!empty($contest_visible)){

		foreach ($contest_visible as $visitor) {

			$list_of_ids[] = $visitor['contest_id'];
		}
	}
	return $list_of_ids;
}

 ?>