<?php
/*
Local:	C:\Dropbox\htdocs\RND\AnonymousChatApp\apiServer\Apiserver\includes
Remote:	/var/www/mingle.eft.xyz/html/includes
*/


function sync_users($party1msisdn)
{	
	global $db;
	global $time;
	global $mypal_users;
	
	//log files
	global $inputlogfile;
	global $outputlogfile;
	global $errorlog;
	global $sqllog;
	
	//db parameters
	global $db_host;
	global $db_username;
	global $db_password;
	global $db_name;
	
	if (!mysqli_ping($db)) {

			  mysqli_close($db);
	 			  
			  $db = mysqli_connect($db_host, $db_username ,$db_password, $db_name);
			  mysqli_set_charset($db,"utf8");
             }
		
		$querystring = "SELECT * FROM $mypal_users WHERE  msisdn = '$party1msisdn'";
		writetolog($querystring,$sqllog);
		
		$userquery = mysqli_query($db,$querystring);	
		if($userqueryarray = mysqli_fetch_assoc($userquery))
		{
			return $userqueryarray["id"];
			
		} else {
			
			$querystring = "INSERT INTO $mypal_users (msisdn,status) VALUES ('$party1msisdn', 'standby')";
			writetolog($querystring,$sqllog);
			
			// Perform a query, check for error
			if (!mysqli_query($db,$querystring)) {
				writetolog(mysqli_error($db),$sqllog);
			}
			
			return mysqli_insert_id($db);
		}	
}

////////////////////-Message sender-////////////////////////
function sendmessage($destinationUserId,$content)
{
    global $db;
	global $messageSenderSecret;
	global $sendMessageEndPoint;
	
	//log files
	global $inputlogfile;
	global $outputlogfile;
	global $errorlog;
	global $sqllog;
		
	$data = array("message" => $content, "destinationUserId" => $destinationUserId,"secret" => $messageSenderSecret);

	$data_string = json_encode($data);
        
	$ch = curl_init($sendMessageEndPoint);  
	
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                   
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);              
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                    
	curl_setopt($ch, CURLOPT_HTTPHEADER, array(                          
		'Content-Type: application/json',                                    
		'Content-Length: ' . strlen($data_string))                       
	);
	$result = curl_exec($ch);
	
	return $result;
}


//Signup, Login, Forgot password, Charging, Subscription Operators

function createUser($msisdn)
{
	global $db;
	global $mypal_users;
	global $sqllog;

	$msisdn = validateMobile($msisdn,"validate");
	if(!$msisdn)
	{
		return  array( 
					  	"respCode" => "0004"//"Invalid Number <mobile>. Need to be 'Dialog' or 'Mobitel' numbers in 7xx xxxxxx format"
					 );
	}

	$querystring = "SELECT * FROM $mypal_users WHERE  msisdn = '$msisdn'";
	writetolog($querystring,$sqllog);		
	$userquery = mysqli_query($db,$querystring);
	
	if($userqueryarray = mysqli_fetch_assoc($userquery))
	{//user exists
		return array(
					 "respCode" => "0026",//"Mobile <mobile> already registered. Please login with <mobile> and password"
					 "userID" => $userqueryarray["id"],
					 "mobile" => $userqueryarray["msisdn"],
					 "sendSMS" => false
					 );
	}else{//create user and sms password
	
	$password = rand(1000,9999);
	$querystring = "INSERT INTO $mypal_users (msisdn,password,status) VALUES ('$msisdn','$password','standby')";
	writetolog($querystring,$sqllog);
	$userquery = mysqli_query($db,$querystring);
	
	return array(
		"respCode" => "0021",//"Password Sent to Mobile <mobile>"
		"userID" => mysqli_insert_id($db),
		"mobile" => $msisdn,
		"password" => $password,
		"sendSMS" => true
		);
	}	
}


function createAndSendPassword($msisdn)
{
	global $db;
	global $mypal_users;
	global $sqllog;
	
	$msisdn = validateMobile($msisdn,"validate");
	if(!$msisdn)
	{
		return  array( 
					  	"respCode" => "0004"//"Invalid Number <mobile>. Need to be 'Dialog' or 'Mobitel' numbers in 7xx xxxxxx format"
					 );
	}
	
	$querystring = "SELECT * FROM $mypal_users WHERE  msisdn = '$msisdn'";
	writetolog($querystring,$sqllog);		
	$userquery = mysqli_query($db,$querystring);
	
	if($userqueryarray = mysqli_fetch_assoc($userquery))
	{//user exists
		return array(
					 "respCode" => "0026",//"Mobile <mobile> already registered. Please login with <mobile> and password"
					 "userID" => $userqueryarray["id"],
					 "msisdn" => $userqueryarray["msisdn"]
					 );
	}else{//create user and sms password
	
	$password = rand(1000,9999);
	$querystring = "INSERT INTO $mypal_users (msisdn,password,status) VALUES ('$msisdn','$password','standby')";
	writetolog($querystring,$sqllog);
	$userquery = mysqli_query($db,$querystring);
	
	//sms password
	$sendSMSresponseJson = send_sms($msisdn,"Login to site with $password");
	$sendSMSresponse = json_decode($sendSMSresponseJson,true)["messages"][0]["resultCode"];
		
		if($sendSMSresponse == 0)
		{
			return array(
					 "respCode" => "0021",//"Password Sent to Mobile <mobile>"
					 "userID" => mysqli_insert_id($db)
					 );
		}else{
			return array(
					 "respCode" => "0022"//"Error sending password to <mobile>. Please try again later"
					 );
		}	
	}	
}

function validateMobile($msisdn,$action)
{
	global $number_validations;
	
	if($action == "validate")
	{
		if(in_array(substr($msisdn,0,$number_validations[strlen($msisdn)]["length"]),$number_validations[strlen($msisdn)]["prefixes"]))
		{
			return substr($msisdn, $number_validations[strlen($msisdn)]["trim_lengh"]);
		}else{
			return false;		
		}
	}
	
	if($action == "trim")
	{
		return substr($msisdn, $number_validations[strlen($msisdn)]["trim_lengh"]);		
	}
}

function send_sms($destination,$content)
{
	global $testingMode;

	/*
			$sendSMSresponseJson = send_sms($msisdn,"Login to site with $password");
			$sendSMSresponse = json_decode($sendSMSresponseJson,true)["messages"][0]["resultCode"];			
			if($sendSMSresponse == 0)
	*/
	if($testingMode)
	{
			$output["messages"][0]["resultCode"] = 0;
			return json_encode($output);
	}

        $now = date("Y-m-d\TH:i:s"); 
        $username = "efuture"; 
        $password = "@q123456"; 
        $digest=md5($password); 

        $body_array = array();
        $body_array["messages"][0] =  array(
												"clientRef" => "0934345",
												"number" => "94$destination",
												"mask" => "MyPal.lk",
												"text" => "$content",
												"campaignName" => "For MyPal.lk" 
											);


        $body = json_encode($body_array);
        ////////////////Live Code///////////////
        $ch_live = curl_init(); 
        curl_setopt($ch_live, CURLOPT_URL,"https://richcommunication.dialog.lk/api/sms/send"); 
        curl_setopt($ch_live, CURLOPT_POST, 1); 
        curl_setopt($ch_live, CURLOPT_POSTFIELDS,$body); //Post Fields 
        curl_setopt($ch_live, CURLOPT_RETURNTRANSFER, true);

        $headers = [ 'Content-Type: application/json', 'USER: '.$username,'DIGEST: '.$digest, 'CREATED: '.$now ];
        curl_setopt($ch_live, CURLOPT_HTTPHEADER, $headers); 

        $server_output = curl_exec($ch_live); 
        curl_close ($ch_live); 

        return $server_output;

}

function generateAndSetSessionKey($userID)
{
	global $db;
	global $mypal_users;
	global $sqllog;
	global $time;

	if($userID <>"")
	{//generate and return session key
		$querystring = "SELECT * FROM $mypal_users WHERE  id = $userID";
		writetolog($querystring,$sqllog);	
		$userquery = mysqli_query($db,$querystring);
		if($userqueryarray = mysqli_fetch_assoc($userquery))
		{
			//generate and save session key
			//return session key
			$sessionKey = get_session_key($userqueryarray["msisdn"],$time);
			$querystring = "UPDATE $mypal_users SET sessionKey = '$sessionKey', session_last_active_time = '$time' WHERE id = $userqueryarray[id]";
			writetolog($querystring,$sqllog);		
			$userquery = mysqli_query($db,$querystring);
			
			return array(
							"respCode" 	=> "0023", //"User logged in successfully"
							"sessionKey" => $sessionKey,
							"mobile"	=> $userqueryarray["msisdn"],
							"userID" => $userqueryarray["id"],
							"subscriptionStatus" => $userqueryarray["subscriptionStatus"]
						);
			
		}else{
			//incorrect login credentials
			return array(
						 	"respCode" 	=> "0011", //"Invalid Transaction Reference"
							"sessionKey" => NULL
						);
		}		
		
	}else{
		//incorrect login credentials
		return array(
			"respCode" 	=> "0011", //"Invalid Transaction Reference"
		    "sessionKey" => NULL
	   );		
	}

}

function login_user($google_user_key, $device_token, $firebase_uid, $email, $name)
{
	global $db;
	global $mypal_users;
	global $sqllog;
	global $time;
	
	$querystring = "SELECT * FROM $mypal_users WHERE pushMessageToken = '$device_token'";
	writetolog($querystring,$sqllog);		
	$userquery = mysqli_query($db,$querystring);
	if($userqueryarray = mysqli_fetch_assoc($userquery))
	{
		//generate and save session key
		//return session key
		$sessionKey = get_session_key($google_user_key,$time);
		$querystring = "UPDATE $mypal_users SET google_user_key = '$google_user_key', sessionKey = '$sessionKey', session_last_active_time = '$time', firebase_uid = '$firebase_uid', email = '$email', name = '$name' WHERE id = $userqueryarray[id]";
		writetolog($querystring,$sqllog);		
		$userquery = mysqli_query($db,$querystring);

		if($userqueryarray["status"] == 'connected')
		{
			$party2query = mysqli_query($db,"SELECT * FROM $mypal_users WHERE id = '$userqueryarray[party2_id]'");
			$party2queryarray = mysqli_fetch_assoc($party2query);
			$profile_string =  get_profile_string($party2queryarray['user_profile']);
			$connection_status = 'You are connected with ' . $profile_string;
		}else{
			$connection_status = 'You are not connected with any user. Click search to find a user';
		}

		return array(
						"respCode" 	=> "0023", //"User logged in successfully"
						"sessionKey" => $sessionKey,
						"userID" => $userqueryarray["id"],
						"chat_history" => $userqueryarray["chat_history"],
						'connection_status' => $connection_status
					);			
	}else{
		$sessionKey = get_session_key($google_user_key,$time);
		$querystring = "INSERT INTO $mypal_users (google_user_key,pushMessageToken,sessionKey,session_last_active_time,status,firebase_uid,email,name) VALUES ('$google_user_key','$device_token','$sessionKey','$time','standby','$firebase_uid','$email','$name')";
		writetolog($querystring,$sqllog);
		$userquery = mysqli_query($db,$querystring);
		$connection_status = 'You are not connected with any user. Click search to find a user';

		return array(
						"respCode" 	=> "0023", //"User logged in successfully"
						"sessionKey" => $sessionKey,
						"userID" => $userqueryarray["id"],
						"chat_history" => [],
						'connection_status' => $connection_status
					);	
	}
}

function mapSubscriptionStatus($subscriptionStatus)
{
	global $subscriptionStatusValues;
	/*
	$subscriptionStatusValues = array(
	"SUBSCRIBED" => array("SUBSCRIBED"),
	"UNSUBSCRIBED" => array("UNSUBSCRIBED","NOT_SUBSCRIBED","PENDING_AUTH")
	)
	*/
	foreach($subscriptionStatusValues as $subscriptionStatusKey => $subscriptionStatusValueSet)
	{
		if(in_array($subscriptionStatus,$subscriptionStatusValueSet))
		{
			return $subscriptionStatusKey;
		}
	}
}

function resetPassword($msisdn)
{
	
	global $db;
	global $mypal_users;
	global $sqllog;
	global $time;
	

		$querystring = "SELECT * FROM $mypal_users WHERE  msisdn = '$msisdn'";
		writetolog($querystring,$sqllog);		
		$userquery = mysqli_query($db,$querystring);
		if($userqueryarray = mysqli_fetch_assoc($userquery))
		{
			//generate temporary password
			
			$password = rand(1000,9999);
			$querystring = "UPDATE $mypal_users SET temp_password = '$password' WHERE id = $userqueryarray[id]";
			writetolog($querystring,$sqllog);		
			$userquery = mysqli_query($db,$querystring);
	
	
			//sms password
			$sendSMSresponseJson = send_sms($msisdn,"Login to site with $password");
			$sendSMSresponse = json_decode($sendSMSresponseJson,true)["messages"][0]["resultCode"];
			
			if($sendSMSresponse == 0)
			{
				return array(
						 "respCode" => "0021",//"Password Sent to Mobile <mobile>"
						 "mobile"	=> $userqueryarray["msisdn"]
						 );
			}else{
				return array(
						 "respCode" => "0022"//"Error sending password to <mobile>. Please try again later"
						 );
			}			
		
		}else{
			//account does not exist
			return array(
						 	"respCode" 	=> "0031", //"Mobile <mobile> not signup up. Please signup 1st to login"
							"sessionKey" => NULL
						);
		}
}

function changePassword($userID, $oldPassword, $newPassword)
{
	
	global $db;
	global $mypal_users;
	global $sqllog;
	global $time;	

		$querystring = "SELECT * FROM $mypal_users WHERE  id = $userID AND password = '$oldPassword'";
		writetolog($querystring,$sqllog);		
		$userquery = mysqli_query($db,$querystring);
		if($userqueryarray = mysqli_fetch_assoc($userquery))
		{
			$querystring = "UPDATE $mypal_users SET password = '$newPassword' WHERE id = $userqueryarray[id]";
			writetolog($querystring,$sqllog);		
			$userquery = mysqli_query($db,$querystring);
	
			return array(
						 "respCode" => "0033"//"Password updated successfully"
						 );
		
		}else{
			//account does not exist
			return array(
						 	"respCode" 	=> "0032"//"Incorrect Old password. Please retry"
						);
		}
}

function get_session_key($google_user_key,$time)
{
	global $messageSenderSecret;
	$random_num = rand(10000,99999);
	
	// return base64_encode("$google_user_key:$time:$random_num:$messageSenderSecret");
	// return 'mytestsessionkey';
	return 'mytestsessionkey'.$random_num;
}

/**** Profile operators ****/
function GetProfile($userID)
{
	global $db;
	global $mypal_users;
	global $sqllog;
	global $time;
	
	$querystring = "SELECT * FROM $mypal_users WHERE  id = $userID";
	writetolog($querystring,$sqllog);	
	$userquery = mysqli_query($db,$querystring);
	if($userqueryarray = mysqli_fetch_assoc($userquery))
	{
		return array(
					"profile" => FormatProfile($userqueryarray["user_profile"]),
					"profileImage" => $userqueryarray["user_profile_image"],
					"respCode" => "0030" //"Profile data sent successfully"
					);
	}
}

function SetProfile($userID, $profileData)
{
	global $db;
	global $mypal_users;
	global $sqllog;
	global $time;
	
	// $profileDataJson = json_encode($profileData);
	$profileDataJson = json_encode($profileData, JSON_UNESCAPED_UNICODE);
	
	$querystring = "UPDATE $mypal_users SET user_profile = '$profileDataJson' WHERE  id = $userID";
	writetolog($querystring,$sqllog);	
	$userquery = mysqli_query($db,$querystring);
	
	return GetProfile($userID);
}

function SetImage($userID, $encodedProfileImage)
{
	global $db;
	global $mypal_users;
	global $sqllog;
	global $time;
	global $profile_image_path; // "/var/www/mypal.lk/html/profiles/"
	global $profile_image_link_path; // "https://mypal.lk/profiles/"

	if (!file_exists($profile_image_path.$userID)) {
		mkdir($profile_image_path.$userID, 0777, true);
	}

	$profileImage = $profile_image_path.$userID."/".$userID;
	
	$decodedProfileImageString = base64_decode($encodedProfileImage);
	if(!$decodedProfileImageString)
	{
		return array(				
						"respCode" => "0046" //"Invalid Profile photo format. Please upload in jpg, jpeg, gif, png or bmp formats"
					);
	}else{
		$profileImagePointer = fopen( $profileImage, 'wb' ); 
		fwrite($profileImagePointer, $decodedProfileImageString);
		$user_profile_image = $profile_image_link_path.$userID."/".$userID."?".rand(10000,99999);

		$querystring = "UPDATE $mypal_users SET user_profile_image = '$user_profile_image' WHERE  id = $userID";
		writetolog($querystring,$sqllog);
		$userquery = mysqli_query($db,$querystring);
		
		fclose( $profileImagePointer ); 

		return;
	}
}

/****Chat Operators****/

function GetWho($userID)
{
	global $db;
	global $mypal_users;
	global $sqllog;
	global $time;
	
	$querystring = "SELECT * FROM $mypal_users WHERE  id = $userID";
	writetolog($querystring,$sqllog);	
	$userquery = mysqli_query($db,$querystring);
	if($userqueryarray = mysqli_fetch_assoc($userquery))
	{
		if($userqueryarray["status"] == "connected")
		{
			$party2querystring = "SELECT * FROM $mypal_users WHERE  id = $userqueryarray[party2_id] AND party2_id = $userID AND status = 'connected'";
			writetolog($party2querystring,$sqllog);	
			$party2query = mysqli_query($db,$party2querystring);

			
			if($party2queryarray = mysqli_fetch_assoc($party2query))
			{			
				//check if B-party is a friend
			   $isFriend = (in_array($party2queryarray["id"],explode(",",$userqueryarray["friends_approved"]))) ? "1":"0";
			
					return array(
									"otherPartyDetails" => array(
																 "userID" => $party2queryarray["id"],
																 "profileData" => FormatProfile($party2queryarray["user_profile"]),
																 "profileImage" => $party2queryarray["user_profile_image"],
																 "isFriend" => $isFriend
															 ),
									"respCode" => "0027" //"You are connected with a user"
								 );
			}			
		}
		
		return array(
						"respCode" => "0028" //"You are not connecte with any user"
					 );
	}
	return array(
					"respCode" => "0012"//"Cannot Process due to System Error. Please Try again soon"
				 );	
}

function GetFriends($userID)
{
	global $db;
	global $mypal_users;
	global $sqllog;
	global $time;
	global $friend_types;
	global $friend_status_handling;
	
	$friendListData = array();
	
	$querystring = "SELECT * FROM $mypal_users WHERE  id = $userID";
	writetolog($querystring,$sqllog);	
	$userquery = mysqli_query($db,$querystring);
	if($userqueryarray = mysqli_fetch_assoc($userquery))
	{
		
		foreach($friend_types as $friendType => $friendTypeData)
		{
			if($friendTypeData["enabled"])
			{
				$friendList = explode(",",$userqueryarray[$friendTypeData["fieldName"]]);
				foreach($friendList as $friendUserID)
				{
					$friendquerystring = "SELECT * FROM $mypal_users WHERE  id = $friendUserID";
					writetolog($friendquerystring,$sqllog);	
					$friendquery = mysqli_query($db,$friendquerystring);
					if($friendqueryarray = mysqli_fetch_assoc($friendquery))
					{
						if($userqueryarray["status"] == "connected" and $userqueryarray["party2_id"] == $friendqueryarray["id"] and $friendqueryarray["status"] == "connected" and $friendqueryarray["party2_id"] == $userqueryarray["id"]){
							$friendListData["FriendsData"][$friendType][$friendUserID] = array(
																								"profileData" => FormatProfile($friendqueryarray["user_profile"]),
																								"profileImage" => $friendqueryarray["user_profile_image"],
																								"status" => $friend_status_handling[$friendqueryarray["status"]][true]["displayStatus"]
																						   );
						}else{
							$friendListData["FriendsData"][$friendType][$friendUserID] = array(
																								"profileData" => FormatProfile($friendqueryarray["user_profile"]),
																								"profileImage" => $friendqueryarray["user_profile_image"],
																								"status" => $friend_status_handling[$friendqueryarray["status"]][false]["displayStatus"]
																						   );
						}
					}
				}
			}
		}
	}
			
		$friendListData["respCode"] = "1000";		
		return $friendListData;
}

function SendFriendRequest($userID)
{
	global $db;
	global $mypal_users;
	global $sqllog;
	global $time;
	
	$querystring = "SELECT * FROM $mypal_users WHERE  id = $userID";
	writetolog($querystring,$sqllog);	
	$userquery = mysqli_query($db,$querystring);
	if($userqueryarray = mysqli_fetch_assoc($userquery))
	{		
		if($userqueryarray["status"] == "connected")
		{
			//check if party2_id already in friends users list
			if(in_array($userqueryarray["party2_id"],explode(",",$userqueryarray["friends_approved"])))
			{
				return array(
					"respCode" => "0049" //"User is already in your friends list"
				 );				
			}

			$party2querystring = "SELECT * FROM $mypal_users WHERE  id = $userqueryarray[party2_id] AND party2_id = $userID AND status = 'connected'";
			writetolog($party2querystring,$sqllog);	
			$party2query = mysqli_query($db,$party2querystring);
			if($party2queryarray = mysqli_fetch_assoc($party2query))
			{	
				//Update Request sent for user A
				$requestSentArray = explode(",",$userqueryarray["friends_requests_sent"]);
				array_push($requestSentArray, $party2queryarray["id"]);
				$requestSentString = implode(",",array_unique($requestSentArray));
				
				$querystring = "UPDATE $mypal_users SET friends_requests_sent = '$requestSentString' WHERE id = $userID";
				writetolog($querystring,$sqllog);	
				$userquery = mysqli_query($db,$querystring);
					
				//Update Request received for user B
				$requestReceivedArray = explode(",",$party2queryarray["friends_requests_received"]);
				array_push($requestReceivedArray, $userID);
				$requestReceivedString = implode(",",array_unique($requestReceivedArray));
				
				$querystring = "UPDATE $mypal_users SET friends_requests_received = '$requestReceivedString' WHERE id = $party2queryarray[id]";
				writetolog($querystring,$sqllog);	
				$userquery = mysqli_query($db,$querystring);
			
					$PushMessage = array(
										 	"type" => "notification",
											"message" => GetProfileToString(FormatProfile($userqueryarray["user_profile"]))." has sent a Friend request",
											"otherPartyDetails" => array(
																			 "userID" => $userqueryarray["id"],
																			 //"ProfileData" => json_decode($userqueryarray["user_profile"],true)
											),
											"notificationCode" => "0003"
										);
				
					if(AddToPushMessageQueue($party2queryarray["id"], $PushMessage))
					{
						return array(
										"otherPartyDetails" => array(
																	 "userID" => $party2queryarray["id"],
																	 "profileData" => FormatProfile($party2queryarray["user_profile"]),
																	 "profileImage" => $party2queryarray["user_profile_image"]
																 ),
										"respCode" => "0035" //"Friend request sent to user"
									);
					}else{					
							return array(
											"respCode" => "0012" //"Cannot Process due to System Error. Please Try again soon"
										 );
					}
			}			
		}
	}
	
	return array(
					"respCode" => "0028" //"You are not connected with any user"
				 );
}

function RemoveFriend($userID, $otherPartyID)
{
	global $db;
	global $mypal_users;
	global $sqllog;
	global $time;
	
	$querystring = "SELECT * FROM $mypal_users WHERE  id = $userID";
	writetolog($querystring,$sqllog);	
	$userquery = mysqli_query($db,$querystring);
	if($userqueryarray = mysqli_fetch_assoc($userquery))
	{				
		//Update Friends list for user A
		$friendsListArray = explode(",",$userqueryarray["friends_approved"]);
		if(array_search($otherPartyID,$friendsListArray) <> FALSE)
		{
			unset($friendsListArray[array_search($otherPartyID,$friendsListArray)]);			
		}
		$friendsListString = implode(",",array_unique($friendsListArray));
			
		$querystring = "UPDATE $mypal_users SET friends_approved = '$friendsListString' WHERE id = $userID";
		writetolog($querystring,$sqllog);	
		$userquery = mysqli_query($db,$querystring);		
				
			$party2querystring = "SELECT * FROM $mypal_users WHERE  id = $otherPartyID";
			writetolog($party2querystring,$sqllog);	
			$party2query = mysqli_query($db,$party2querystring);
			if($party2queryarray = mysqli_fetch_assoc($party2query))
			{		
				//Update Friends list for user B
				$friendsListArray = explode(",",$party2queryarray["friends_approved"]);
				if(array_search($userID,$friendsListArray) <> FALSE)
				{
					unset($friendsListArray[array_search($userID,$friendsListArray)]);			
				}
				$friendsListString = implode(",",array_unique($friendsListArray));
					
				$querystring = "UPDATE $mypal_users SET friends_approved = '$friendsListString' WHERE id = $party2queryarray[id]";
				writetolog($querystring,$sqllog);	
				$userquery = mysqli_query($db,$querystring);
			
					$PushMessage = array(
										 	"type" => "notification",
											"message" => GetProfileToString(FormatProfile($userqueryarray["user_profile"]))." has removed you as a friend",
											"otherPartyDetails" => array(
																			 "userID" => $userqueryarray["id"],
																			 //"ProfileData" => json_decode($userqueryarray["user_profile"],true)
											),
											"notificationCode" => "0006"
										);
				
					if(AddToPushMessageQueue($party2queryarray["id"], $PushMessage))
					{
						return array(
										"otherPartyDetails" => array(
																	 "userID" => $party2queryarray["id"],
																	 //"ProfileData" => json_decode($party2queryarray["user_profile"],true)
																 ),
										"respCode" => "0036" //"Friend removed successfully"
									);
					}else{					
							return array(
											"respCode" => "0012" //"Cannot Process due to System Error. Please Try again soon"
										 );
					}
			}		
	}
	
	return array(
					"respCode" => "0012" //"Cannot Process due to System Error. Please Try again soon"
				 );
}

function FindFriend($userID)
{
	global $db;
	global $mypal_users;
	global $permissions_table;
	global $sqllog;
	global $time;
	global $max_previous_chat_user_buffer;
	
	global $db_host;
	global $db_username;
	global $db_password;
	global $db_name;

	$permission_granted = false;
	
	$querystring = "SELECT * FROM $mypal_users WHERE  id = $userID";
	writetolog($querystring,$sqllog);	
	$userquery = mysqli_query($db,$querystring);
	if($userqueryarray = mysqli_fetch_assoc($userquery))
	{		
		
		if($userqueryarray["status"] == "connected")
		{
			$party2querystring = "SELECT * FROM $mypal_users WHERE  id = $userqueryarray[party2_id] AND party2_id = $userID AND status = 'connected'";
			writetolog($party2querystring,$sqllog);	
			$party2query = mysqli_query($db,$party2querystring);
			if($party2queryarray = mysqli_fetch_assoc($party2query))
			{					

				//chat_history_from_user - Updating
				$chat_history_party2_user = json_decode($party2queryarray["chat_history"], true);
				$chat_history_party2_user[$time] = [
						'status' => get_profile_string($userqueryarray["user_profile"]) . ' has left',
					];
				$chat_history_party2_user = set_chat_history_window($chat_history_party2_user);
				$chat_history_party2_user_json = json_encode($chat_history_party2_user, true);

				$querystring = "UPDATE $mypal_users SET status = 'free', party2_id = 0, chat_history = '$chat_history_party2_user_json' WHERE id = $party2queryarray[id]";
				writetolog($querystring,$sqllog);	
				$userquery = mysqli_query($db,$querystring);
			
					$PushMessage = array(
										 	"type" => "notification",
											"message" => GetProfileToString(FormatProfile($userqueryarray["user_profile"]))." has left. Click \"Find\" to find a new friend!",
											"otherPartyDetails" => array(
																			 "userID" => $userqueryarray["id"],
																			 //"ProfileData" => json_decode($userqueryarray["user_profile"],true)
											),
											"notificationCode" => "0001"
										);
				
					AddToPushMessageQueue($party2queryarray["id"], $PushMessage, "c");
				
					/*
					if(AddToPushMessageQueue($party2queryarray["id"], $PushMessage))
					{
						return array(
										"otherPartyDetails" => array(
																	 "userID" => $party2queryarray["id"],
																	 "ProfileData" => $party2queryarray["user_profile"]
																 ),
										"respCode" => "0035" //"Friend request sent to user"
									);
					}else{					
							return array(
											"respCode" => "0012" //"Cannot Process due to System Error. Please Try again soon"
										 );
					}
					*/
			}			
		}
		
		//update to searching status
		$querystring = "UPDATE $mypal_users SET status = 'searching', party2_id = 0 WHERE id = $userID";
		writetolog($querystring,$sqllog);	
		$userquery = mysqli_query($db,$querystring);
	
		
		do{
			//check if still searching
			$CheckSearchStatusquerystring = "SELECT * FROM $mypal_users WHERE  id = $userID";
			writetolog($CheckSearchStatusquerystring,$sqllog);	
			$CheckSearchStatusquery = mysqli_query($db,$CheckSearchStatusquerystring);
			if($CheckSearchStatusqueryArray = mysqli_fetch_assoc($CheckSearchStatusquery))
			{
				if($CheckSearchStatusqueryArray["status"] <> "searching")
				{
						
					return array(
								"respCode" => "0027", //"You are connected with a user"
								/*
								"otherPartyDetails" => array(
																 "userID" => $searchFriendqueryArray["id"],
																 "ProfileData" => json_decode($searchFriendqueryArray["user_profile"],true)
															)
								*/
						   		);
				}
			}
	
				$currenttime=time();
				$permission_query = mysqli_query($db,"SELECT * FROM $permissions_table WHERE permission = 'newfriendsearch'");
				 if (!$permission_query) {
						   $mysql_error_msg_0=mysqli_error($db);
						   writetolog("sql_error_0_0->{$mysql_error_msg_0}", $sqllog);
						   
							mysqli_free_result($permission_query);
							
							mysqli_close($db);
						   $db = mysqli_connect($db_host, $db_username ,$db_password, $db_name);
						   mysqli_set_charset($db,"utf8");			  
	  
							$permission_query = mysqli_query($db,"SELECT * FROM $permissions_table WHERE permission = 'newfriendsearch'" );
							if (!$permission_query) {
							 $mysql_error_msg_0_1=mysqli_error($db);
								  writetolog("sql_error_0_1->{$mysql_error_msg_0_1}", $sqllog);
								  break;
							   }
						   }
						   
				$permission_queryarray = mysqli_fetch_assoc($permission_query);
				if($permission_queryarray['userID'] == $userID)
				{
					$permission_granted = true;
					} else if($permission_queryarray['userID'] == '' or ($currenttime-$permission_queryarray['updatetime'])>30){
				
				$querystring = "UPDATE $permissions_table SET userID = $userID, updatetime='$currenttime' WHERE permission = 'newfriendsearch'";
				writetolog("1->" . $querystring,$sqllog);	
				$query_result = mysqli_query($db,$querystring);		
				
				if (!$query_result) {
					  $mysql_error_msg_1=mysqli_error($db);
								  writetofile_io("sql_error_1->{$mysql_error_msg_1}", $sqllog);
								  break;
								}
				}
			
			
		}while(!$permission_granted);
	}
	
	if($permission_granted)
	{
		//search and match a new friend
		$searchFriendquerystring = "SELECT * FROM $mypal_users WHERE  status = 'searching' AND id <> $userID ORDER BY session_last_active_time DESC";
		writetolog($searchFriendquerystring,$sqllog);	
		$searchFriendquery = mysqli_query($db,$searchFriendquerystring);
		while($searchFriendqueryArray = mysqli_fetch_assoc($searchFriendquery))
		{
		  if(!in_array($searchFriendqueryArray["id"], explode(",",$userqueryarray["previous_party2_ids"])))
		  {		
		  	  //B-party previous users
			  $previous_party2_ids_array = explode(",",$searchFriendqueryArray["previous_party2_ids"]);
			  if(!is_array($previous_party2_ids_array))
			  {
				  $previous_party2_ids_array = array();
			  }
			  array_push($previous_party2_ids_array,$userID);
			  if(sizeof($previous_party2_ids_array) > $max_previous_chat_user_buffer)
			  {
				  array_shift($previous_party2_ids_array);
			  }			  
			  $previous_party2_ids_string = implode(",",$previous_party2_ids_array);
			  
			//chat_history - party2 - Updating
			$chat_history_party2_user = json_decode($searchFriendqueryArray["chat_history"], true);
			$chat_history_party2_user[$time] = [
					'status' => 'You are connected with ' . get_profile_string($userqueryarray["user_profile"]),
				];
			$chat_history_party2_user = set_chat_history_window($chat_history_party2_user);
			$chat_history_party2_user_json = json_encode($chat_history_party2_user, true);

			//Update and Push message to B-party
			$querystring = "UPDATE $mypal_users SET status = 'connected', party2_id = $userID, previous_party2_ids = '$previous_party2_ids_string', chat_history = '$chat_history_party2_user_json'  WHERE id = $searchFriendqueryArray[id]";
			writetolog($querystring,$sqllog);	
			$userquery = mysqli_query($db,$querystring);
			
				$PushMessage = array(
									 	"type" => "notification",
										"message" => "You are connected with ".GetProfileToString(FormatProfile($userqueryarray["user_profile"])).". Type a message to chat.",
										"otherPartyDetails" => array(
																		 "userID" => $userqueryarray["id"],
																		 "profileData" => FormatProfile($userqueryarray["user_profile"]),
																		 "profileImage" => $userqueryarray["user_profile_image"]
										),
										"notificationCode" => "0002"
									);
				AddToPushMessageQueue($searchFriendqueryArray["id"], $PushMessage, "a", $PushMessage["otherPartyDetails"]);
			  
			  //A-party previous users
			  $previous_party2_ids_array = explode(",",$userqueryarray["previous_party2_ids"]);
			  if(!is_array($previous_party2_ids_array))
			  {
				  $previous_party2_ids_array = array();
			  }
			  array_push($previous_party2_ids_array,$searchFriendqueryArray["id"]);
			  if(sizeof($previous_party2_ids_array) > $max_previous_chat_user_buffer)
			  {
				  array_shift($previous_party2_ids_array);
			  }
			  $previous_party2_ids_string = implode(",",$previous_party2_ids_array);
			  
			  //chat_history - party1 - Updating
			  $chat_history_party1_user = json_decode($userqueryarray["chat_history"], true);
			  $chat_history_party1_user[$time] = [
					'status' => 'You are connected with ' . get_profile_string($searchFriendqueryArray["user_profile"]),
				];
			  $chat_history_party1_user = set_chat_history_window($chat_history_party1_user);
			  $chat_history_party1_user_json = json_encode($chat_history_party1_user, true);
			

			  //Update A-party
			  $querystring = "UPDATE $mypal_users SET status = 'connected', party2_id = $searchFriendqueryArray[id], previous_party2_ids = '$previous_party2_ids_string', chat_history = '$chat_history_party1_user_json' WHERE id = $userID";
			  writetolog($querystring,$sqllog);	
			  $userquery = mysqli_query($db,$querystring);
			  
			  //release permisson
			  $querystring = "UPDATE $permissions_table SET userID = NULL, updatetime='' WHERE permission = 'newfriendsearch'";
			  writetolog("2->" . $querystring,$sqllog);	
			  $userquery = mysqli_query($db,$querystring);
			  $permission_granted = false;
	
			  return array(
						   	"respCode" => "0027", //"You are connected with a user"
							"otherPartyDetails" => array(
															 "userID" => $searchFriendqueryArray["id"],
															 "profileData" => FormatProfile($searchFriendqueryArray["user_profile"]),
															 "profileImage" => $searchFriendqueryArray["user_profile_image"]
														)
						   );				  
		  }
		}	
		
		 //release permisson
		  $querystring = "UPDATE $permissions_table SET userID = NULL, updatetime='' WHERE permission = 'newfriendsearch'";
		  writetolog("3->" . $querystring,$sqllog);	
		  $userquery = mysqli_query($db,$querystring);
		  $permission_granted = false;
			  
		return array(
						"respCode" => "0037", //"Wait till we find a friend to chat"
			 	    );			
	}
	
	return array(
					"respCode" => "0012" //"Cannot Process due to System Error. Please Try again soon"
				 );	
}

function AcceptFriend($userID, $friendID)
{
	global $db;
	global $mypal_users;
	global $sqllog;
	global $time;
	
	$querystring = "SELECT * FROM $mypal_users WHERE  id = $userID";
	writetolog($querystring,$sqllog);	
	$userquery = mysqli_query($db,$querystring);
	if($userqueryarray = mysqli_fetch_assoc($userquery))
	{
		//"0044" => "You have no friend requests from the user"
		//"0045" => "user added to your friends list"
		$friends_requests_received_array = explode(",",$userqueryarray["friends_requests_received"]);
		if(in_array($friendID,$friends_requests_received_array))
		{//pending friend request have
			
			$party2querystring = "SELECT * FROM $mypal_users WHERE  id = $friendID";
			writetolog($party2querystring,$sqllog);	
			$party2query = mysqli_query($db,$party2querystring);
			if($party2queryarray = mysqli_fetch_assoc($party2query))
			{
				//B-party handling
				$party2_friends_requests_sent_array = explode(",",$party2queryarray["friends_requests_sent"]);
				$party2_friends_approved_array = explode(",",$party2queryarray["friends_approved"]);
				
				//B-Party - remove from sent friend requests
				$key = array_search($userID,$party2_friends_requests_sent_array);
				unset($party2_friends_requests_sent_array[$key]);
				$party2_friends_requests_sent_str = implode(",",$party2_friends_requests_sent_array);				
				
				//B-Party - add to approved friends list
				array_push($party2_friends_approved_array,$userID);
				$party2_friends_approved_array = array_unique($party2_friends_approved_array);
				$party2_friends_approved_str = implode(",",$party2_friends_approved_array);
				
				$querystring = "UPDATE $mypal_users SET friends_requests_sent = '$party2_friends_requests_sent_str', friends_approved = '$party2_friends_approved_str' WHERE id = $party2queryarray[id]";
				writetolog($querystring,$sqllog);	
				$userquery = mysqli_query($db,$querystring);
				
				//Notify B-party
				$PushMessage = array(
										"type" => "notification",
										"message" => GetProfileToString(FormatProfile($userqueryarray["user_profile"]))." has accepted your friend request!",
										"otherPartyDetails" => array(
																		 "userID" => $userqueryarray["id"],
																		 "profileData" => FormatProfile($userqueryarray["user_profile"]),
																		 "profileImage" => $userqueryarray["user_profile_image"]
										),
										"notificationCode" => "0004"
									);
			
				AddToPushMessageQueue($party2queryarray["id"], $PushMessage);
								
				//A-party handling
				$friends_requests_received_array = explode(",",$userqueryarray["friends_requests_received"]);
				$friends_approved_array = explode(",",$userqueryarray["friends_approved"]);
				
				//A-Party - remove from sent friend requests
				$key = array_search($friendID,$friends_requests_received_array);
				unset($friends_requests_received_array[$key]);
				$friends_requests_received_str = implode(",",$friends_requests_received_array);				
				
				//A-Party - add to approved friends list
				array_push($friends_approved_array,$friendID);
				$friends_approved_array = array_unique($friends_approved_array);
				$friends_approved_str = implode(",",$friends_approved_array);
				
				$querystring = "UPDATE $mypal_users SET friends_requests_received = '$friends_requests_received_str', friends_approved = '$friends_approved_str' WHERE id = $userID";
				writetolog($querystring,$sqllog);	
				$userquery = mysqli_query($db,$querystring);
				
				return array(
						"respCode" => "0045", //"user added to your friends list"
						"otherPartyDetails" => array(
														 "userID" => $friendID,
														 "profileData" => FormatProfile($party2queryarray["user_profile"]),
														 "profileImage" => $party2queryarray["user_profile_image"]
													)
					);
					
			}else{
				
					
				//B-party not found
				
				//A-party handling
				$friends_requests_received_array = explode(",",$userqueryarray["friends_requests_received"]);
						
				//A-Party - remove from sent friend requests
				$key = array_search($friendID,$friends_requests_received_array);
				unset($friends_requests_received_array[$key]);
				$friends_requests_received_str = implode(",",$friends_requests_received_array);				
				
				$querystring = "UPDATE $mypal_users SET friends_requests_received = '$friends_requests_received_str' WHERE id = $userID";
				writetolog($querystring,$sqllog);	
				$userquery = mysqli_query($db,$querystring);
							
				return array(
								"respCode" => "0044", //"You have no friend requests from the user"
								"otherPartyDetails" => array(
																 "userID" => $friendID,
																 //"ProfileData" => json_decode($party2queryarray["user_profile"],true)
															)
							);
			
			}
		
		
		}else{			
			
				//no pending friend request
				
				//A-party handling
				$friends_requests_received_array = explode(",",$userqueryarray["friends_requests_received"]);
						
				//A-Party - remove from sent friend requests
				$key = array_search($friendID,$friends_requests_received_array);
				unset($friends_requests_received_array[$key]);
				$friends_requests_received_str = implode(",",$friends_requests_received_array);				
				
				$querystring = "UPDATE $mypal_users SET friends_requests_received = '$friends_requests_received_str' WHERE id = $userID";
				writetolog($querystring,$sqllog);	
				$userquery = mysqli_query($db,$querystring);
				
		
				return array(
								"respCode" => "0044", //"You have no friend requests from the user"
								"otherPartyDetails" => array(
																 "userID" => $friendID,
																 //"ProfileData" => json_decode($party2queryarray["user_profile"],true)
															)
							);
		}
	}
	
	return array(
					"respCode" => "0012"//"Cannot Process due to System Error. Please Try again soon"
				 );
	
}

function RejectFriend($userID, $friendID)
{
	global $db;
	global $mypal_users;
	global $sqllog;
	global $time;
	
	$querystring = "SELECT * FROM $mypal_users WHERE  id = $userID";
	writetolog($querystring,$sqllog);	
	$userquery = mysqli_query($db,$querystring);
	if($userqueryarray = mysqli_fetch_assoc($userquery))
	{
		//"0044" => "You have no friend requests from the user"
		//"0047" => "Friend request rejected",
		$friends_requests_received_array = explode(",",$userqueryarray["friends_requests_received"]);
		if(in_array($friendID,$friends_requests_received_array))
		{//pending friend request have
			
			$party2querystring = "SELECT * FROM $mypal_users WHERE  id = $friendID";
			writetolog($party2querystring,$sqllog);	
			$party2query = mysqli_query($db,$party2querystring);
			if($party2queryarray = mysqli_fetch_assoc($party2query))
			{
				//B-Party - remove from sent friend requests
				$party2_friends_requests_sent_array = explode(",",$party2queryarray["friends_requests_sent"]);
				$key = array_search($userID,$party2_friends_requests_sent_array);
				unset($party2_friends_requests_sent_array[$key]);
				$party2_friends_requests_sent_str = implode(",",$party2_friends_requests_sent_array);		
				
				$querystring = "UPDATE $mypal_users SET friends_requests_sent = '$party2_friends_requests_sent_str' WHERE id = $party2queryarray[id]";
				writetolog($querystring,$sqllog);	
				$userquery = mysqli_query($db,$querystring);
				
				//Notify B-party
				$PushMessage = array(
										"type" => "notification",
										"message" => GetProfileToString(FormatProfile($userqueryarray["user_profile"]))." has rejected your friend request!",
										"otherPartyDetails" => array(
																		 "userID" => $userqueryarray["id"],
																		 "profileData" => FormatProfile($userqueryarray["user_profile"]),
																		 "profileImage" => $userqueryarray["user_profile_image"]
										),
										"notificationCode" => "0005"
									);
			
				AddToPushMessageQueue($party2queryarray["id"], $PushMessage);
								
				//A-Party - remove from sent friend requests
				$friends_requests_received_array = explode(",",$userqueryarray["friends_requests_received"]);
				$key = array_search($friendID,$friends_requests_received_array);
				unset($friends_requests_received_array[$key]);
				$friends_requests_received_str = implode(",",$friends_requests_received_array);				
				
				$querystring = "UPDATE $mypal_users SET friends_requests_received = '$friends_requests_received_str' WHERE id = $userID";
				writetolog($querystring,$sqllog);	
				$userquery = mysqli_query($db,$querystring);
				
				return array(
						"respCode" => "0047", //"Friend request rejected"
						"otherPartyDetails" => array(
														 "userID" => $friendID,
														 "profileData" => FormatProfile($party2queryarray["user_profile"]),
														 "profileImage" => $party2queryarray["user_profile_image"]
													)
					);
					
			}else{				
					
				//B-party not found
				
				//A-party handling
				$friends_requests_received_array = explode(",",$userqueryarray["friends_requests_received"]);
						
				//A-Party - remove from sent friend requests
				$key = array_search($friendID,$friends_requests_received_array);
				unset($friends_requests_received_array[$key]);
				$friends_requests_received_str = implode(",",$friends_requests_received_array);				
				
				$querystring = "UPDATE $mypal_users SET friends_requests_received = '$friends_requests_received_str' WHERE id = $userID";
				writetolog($querystring,$sqllog);	
				$userquery = mysqli_query($db,$querystring);
							
				return array(
								"respCode" => "0044", //"You have no friend requests from the user"
								"otherPartyDetails" => array(
																 "userID" => $friendID,
																 //"ProfileData" => json_decode($party2queryarray["user_profile"],true)
															)
							);			
			}		
		
		}else{			
			
				//no pending friend request
				
				//A-party handling
				$friends_requests_received_array = explode(",",$userqueryarray["friends_requests_received"]);
						
				//A-Party - remove from sent friend requests
				$key = array_search($friendID,$friends_requests_received_array);
				unset($friends_requests_received_array[$key]);
				$friends_requests_received_str = implode(",",$friends_requests_received_array);				
				
				$querystring = "UPDATE $mypal_users SET friends_requests_received = '$friends_requests_received_str' WHERE id = $userID";
				writetolog($querystring,$sqllog);	
				$userquery = mysqli_query($db,$querystring);
				
		
				return array(
								"respCode" => "0044", //"You have no friend requests from the user"
								"otherPartyDetails" => array(
																 "userID" => $friendID,
																 //"ProfileData" => json_decode($party2queryarray["user_profile"],true)
															)
							);
		}
	}
	
	return array(
					"respCode" => "0012"//"Cannot Process due to System Error. Please Try again soon"
				 );
	
}

function withdrawRequest($userID, $friendID)
{
	global $db;
	global $mypal_users;
	global $sqllog;
	global $time;
	
	$querystring = "SELECT * FROM $mypal_users WHERE  id = $userID";
	writetolog($querystring,$sqllog);	
	$userquery = mysqli_query($db,$querystring);
	if($userqueryarray = mysqli_fetch_assoc($userquery))
	{
		//"0053" => "You have no freidn requests sent to this user",
		//"0052" => "Friend request withdrawn"
		$friends_requests_sent_array = explode(",",$userqueryarray["friends_requests_sent"]);
		if(in_array($friendID,$friends_requests_sent_array))
		{//pending friend request have
			
			$party2querystring = "SELECT * FROM $mypal_users WHERE  id = $friendID";
			writetolog($party2querystring,$sqllog);	
			$party2query = mysqli_query($db,$party2querystring);
			if($party2queryarray = mysqli_fetch_assoc($party2query))
			{
				//B-Party - remove from sent friend requests
				$party2_friends_requests_received_array = explode(",",$party2queryarray["friends_requests_received"]);
				$key = array_search($userID,$party2_friends_requests_received_array);
				unset($party2_friends_requests_received_array[$key]);
				$party2_friends_requests_received_str = implode(",",$party2_friends_requests_received_array);		
				
				$querystring = "UPDATE $mypal_users SET friends_requests_received = '$party2_friends_requests_received_str' WHERE id = $party2queryarray[id]";
				writetolog($querystring,$sqllog);	
				$userquery = mysqli_query($db,$querystring);
				
				/*
				//Notify B-party
				$PushMessage = array(
										"type" => "notification",
										"message" => GetProfileToString(FormatProfile($userqueryarray["user_profile"]))." has rejected your friend request!",
										"otherPartyDetails" => array(
																		 "userID" => $userqueryarray["id"],
																		 "profileData" => FormatProfile($userqueryarray["user_profile"]),
																		 "profileImage" => $userqueryarray["user_profile_image"]
										),
										"notificationCode" => "0005"
									);
			
				AddToPushMessageQueue($party2queryarray["id"], $PushMessage);
				*/

				//A-Party - remove from sent friend requests
				$friends_requests_sent_array = explode(",",$userqueryarray["friends_requests_sent"]);
				$key = array_search($friendID,$friends_requests_sent_array);
				unset($friends_requests_sent_array[$key]);
				$friends_requests_sent_str = implode(",",$friends_requests_sent_array);				
				
				$querystring = "UPDATE $mypal_users SET friends_requests_sent = '$friends_requests_sent_str' WHERE id = $userID";
				writetolog($querystring,$sqllog);	
				$userquery = mysqli_query($db,$querystring);
				
				return array(
						"respCode" => "0052", //"0052" => "Friend request withdrawn",
						"otherPartyDetails" => array(
														 "userID" => $friendID,
														 "profileData" => FormatProfile($party2queryarray["user_profile"]),
														 "profileImage" => $party2queryarray["user_profile_image"]
													)
					);
					
			}else{				
					
				//B-party not found
				
				//A-party handling
				$friends_requests_sent_array = explode(",",$userqueryarray["friends_requests_sent"]);
						
				//A-Party - remove from sent friend requests
				$key = array_search($friendID,$friends_requests_sent_array);
				unset($friends_requests_sent_array[$key]);
				$friends_requests_sent_str = implode(",",$friends_requests_sent_array);				
				
				$querystring = "UPDATE $mypal_users SET friends_requests_sent = '$friends_requests_sent_str' WHERE id = $userID";
				writetolog($querystring,$sqllog);	
				$userquery = mysqli_query($db,$querystring);
							
				return array(
								"respCode" => "0052", //"0052" => "Friend request withdrawn",
								"otherPartyDetails" => array(
																 "userID" => $friendID,
																 //"ProfileData" => json_decode($party2queryarray["user_profile"],true)
															)
							);			
			}		
		
		}else{			
			
				//no pending friend request
				
				//A-party handling
				$friends_requests_sent_array = explode(",",$userqueryarray["friends_requests_sent"]);
						
				//A-Party - remove from sent friend requests
				$key = array_search($friendID,$friends_requests_sent_array);
				unset($friends_requests_sent_array[$key]);
				$friends_requests_sent_str = implode(",",$friends_requests_sent_array);				
				
				$querystring = "UPDATE $mypal_users SET friends_requests_sent = '$friends_requests_sent_str' WHERE id = $userID";
				writetolog($querystring,$sqllog);	
				$userquery = mysqli_query($db,$querystring);
				
		
				return array(
								"respCode" => "0053", //"0053" => "You have no freidn requests sent to this user",
								"otherPartyDetails" => array(
																 "userID" => $friendID,
																 //"ProfileData" => json_decode($party2queryarray["user_profile"],true)
															)
							);
		}
	}
	
	return array(
					"respCode" => "0012"//"Cannot Process due to System Error. Please Try again soon"
				 );
	
}
	
function ConnectFriend($userID, $friendID)
{
	global $db;
	global $mypal_users;
	global $sqllog;
	global $time;
	global $friend_status_handling;
	
	$querystring = "SELECT * FROM $mypal_users WHERE  id = $userID";
	writetolog($querystring,$sqllog);	
	$userquery = mysqli_query($db,$querystring);
	if($userqueryarray = mysqli_fetch_assoc($userquery))
	{
		//"0027" => "You are connected with a user"
		//"0038" => "Chat request sent to user"
		//"0039" => "User is not in your friend list"
		//"0040" => "User is currently unavailable"
		//"0041" => "You are already connected with the friend",
		
		//Check if already connected
		$party2querystring = "SELECT * FROM $mypal_users WHERE  id = $friendID";
		writetolog($party2querystring,$sqllog);	
		$party2query = mysqli_query($db,$party2querystring);
		if($party2queryarray = mysqli_fetch_assoc($party2query))
		{
			if($userqueryarray["status"] == "connected" and $userqueryarray["party2_id"] == $party2queryarray["id"] and $party2queryarray["status"] == "connected" and $party2queryarray["party2_id"] == $userqueryarray["id"])						
				{					
					return array(
									"respCode" => "0041", //"You are already connected with the friend"
									"otherPartyDetails" => array(
																	 "userID" => $party2queryarray["id"],
																	 "profileData" => FormatProfile($party2queryarray["user_profile"]),
																	 "profileImage" => $party2queryarray["user_profile_image"]
																)
								);
				}
		}

		
		if(in_array($friendID,explode(",",$userqueryarray["friends_approved"])))
		{
			$party2querystring = "SELECT * FROM $mypal_users WHERE  id = $friendID";
			writetolog($party2querystring,$sqllog);	
			$party2query = mysqli_query($db,$party2querystring);
			if($party2queryarray = mysqli_fetch_assoc($party2query))
			{
				
				if($friend_status_handling[$party2queryarray["status"]][false]["chatConnect"])
				{//connect instantly					
				
					//notify currently connected party 2
					if($userqueryarray["status"] == "connected")
					{
						$Currentparty2querystring = "SELECT * FROM $mypal_users WHERE  id = $userqueryarray[party2_id] AND party2_id = $userID AND status = 'connected'";
						writetolog($Currentparty2querystring,$sqllog);	
						$Currentparty2query = mysqli_query($db,$Currentparty2querystring);
						if($Currentparty2queryArray = mysqli_fetch_assoc($Currentparty2query))
						{					
							$querystring = "UPDATE $mypal_users SET status = 'free', party2_id = 0 WHERE id = $Currentparty2queryArray[id]";
							writetolog($querystring,$sqllog);	
							$userquery = mysqli_query($db,$querystring);
						
								$PushMessage = array(
													 	"type" => "notification",
														"message" => GetProfileToString(FormatProfile($userqueryarray["user_profile"]))." has left. Click \"Find\" to find a new friend!",
														"otherPartyDetails" => array(
																						 "userID" => $userqueryarray["id"],
																						 //"ProfileData" => json_decode($userqueryarray["user_profile"],true)
														),
														"respCode" => "0001"
													);
							
								AddToPushMessageQueue($Currentparty2queryArray["id"], $PushMessage, "b");
						}			
					}					
				
				  //Update and Push message to new party 2
				  $querystring = "UPDATE $mypal_users SET status = 'connected', party2_id = $userID WHERE id = $party2queryarray[id]";
				  writetolog($querystring,$sqllog);	
				  $userquery = mysqli_query($db,$querystring);
				
					$PushMessage = array(
										 	"type" => "notification",
											"message" => "You are connected with ".GetProfileToString(FormatProfile($userqueryarray["user_profile"])).". Type a message to chat.",
											"otherPartyDetails" => array(
																			 "userID" => $userqueryarray["id"],
																			 "profileData" => FormatProfile($userqueryarray["user_profile"]),
																			 "profileImage" => $userqueryarray["user_profile_image"]
											),
											"notificationCode" => "0002"
										);
					AddToPushMessageQueue($party2queryarray["id"], $PushMessage, "a", $PushMessage["otherPartyDetails"]);
				
				
				  //Update A-party
				  $querystring = "UPDATE $mypal_users SET status = 'connected', party2_id = $party2queryarray[id] WHERE id = $userID";
				  writetolog($querystring,$sqllog);	
				  $userquery = mysqli_query($db,$querystring);
		
				  return array(
								"respCode" => "0027", //"You are connected with a user"
								"otherPartyDetails" => array(
																 "userID" => $party2queryarray["id"],
																 "profileData" => FormatProfile($party2queryarray["user_profile"]),
																 "profileImage" => $party2queryarray["user_profile_image"]
															)
							   );				  
					
				}else{//send notification only
					
					if($friend_status_handling[$party2queryarray["status"]][false]["notifyFriend"])
					{//Notify B party
						$PushMessage = array(
												"type" => "notification",
												"message" => GetProfileToString(FormatProfile($userqueryarray["user_profile"]))." wants to chat with you. Connect with friend to chat.",
												"otherPartyDetails" => array(
																				 "userID" => $userqueryarray["id"],
																				 "profileData" => FormatProfile($userqueryarray["user_profile"]),
																				 "profileImage" => $userqueryarray["user_profile_image"]
												),
												"notificationCode" => "0007"
										);
						AddToPushMessageQueue($party2queryarray["id"], $PushMessage, "b");
					}
					
					
					return array(
								"respCode" => $friend_status_handling[$party2queryarray["status"]][false]["respCode"], //0038,0040
								"otherPartyDetails" => array(
																 "userID" => $party2queryarray["id"],
																 "profileData" => FormatProfile($party2queryarray["user_profile"]),
																 "profileImage" => $party2queryarray["user_profile_image"]
																 
															)
							   );
				}			
			
			}

		  }else{
				  return array(
								"respCode" => "0039",//"User is not in your friend list"
								"otherPartyDetails" => array(
																 "userID" => $party2queryarray["id"],
																 "profileData" => FormatProfile($party2queryarray["user_profile"]),
																 "profileImage" => $party2queryarray["user_profile_image"]
															)
							  );
		  }		  
	}
			return array(
							"respCode" => "0012"//"Cannot Process due to System Error. Please Try again soon"
						 );	
}

function SendChatMessage($userID, $message)
{
	global $db;
	global $mypal_users;
	global $sqllog;
	global $time;
	
	$querystring = "SELECT * FROM $mypal_users WHERE  id = $userID";
	writetolog($querystring,$sqllog);	
	$userquery = mysqli_query($db,$querystring);
	if($userqueryarray = mysqli_fetch_assoc($userquery))
	{
		if($userqueryarray["status"] == "connected")
		{
			$party2_id = $userqueryarray['party2_id'];
			$party2querystring = "SELECT * FROM $mypal_users WHERE  id = $party2_id AND party2_id = $userID AND status = 'connected'";
			writetolog($party2querystring,$sqllog);	
			$party2query = mysqli_query($db,$party2querystring);
			if($party2queryarray = mysqli_fetch_assoc($party2query))
			{	//send the message to B-party			
			
					//chat_history_from_user - Updating
				    $chat_history_from_user = json_decode($userqueryarray["chat_history"], true);
					$chat_history_from_user[$time] = [
							'from' => $userID,
							'to' => $party2_id,
							'message' => $message
						];
					$chat_history_from_user = set_chat_history_window($chat_history_from_user);
					$chat_history_from_user_json = json_encode($chat_history_from_user, true);
					$chat_history_from_user_querystring = "UPDATE $mypal_users SET chat_history = '$chat_history_from_user_json' WHERE  id = $userID";
					writetolog('chat_history_from_user_UPDATE:' . $chat_history_from_user_querystring,$sqllog);	
					mysqli_query($db,$chat_history_from_user_querystring);

					//chat_history_to_user - Updating
				    $chat_history_to_user = json_decode($party2queryarray["chat_history"], true);
					$chat_history_to_user[$time] = [
							'from' => $userID,
							'to' => $party2_id,
							'message' => $message
						];
					$chat_history_from_user = set_chat_history_window($chat_history_from_user);
					$chat_history_to_user_json = json_encode($chat_history_to_user, true);
					$chat_history_to_user_querystring = "UPDATE $mypal_users SET chat_history = '$chat_history_to_user_json' WHERE  id = $party2_id";
					writetolog('chat_history_to_user_UPDATE:' . $chat_history_to_user_querystring,$sqllog);	
					mysqli_query($db,$chat_history_to_user_querystring);

					$PushMessage = array(
										 	"type" => "chatMessage",
											"message" => $message,
											"otherPartyDetails" => array(
																			 "userID" => $userqueryarray["id"],
																			 "profileData" => FormatProfile($userqueryarray["user_profile"]),
																			 "profileImage" => $userqueryarray["user_profile_image"]
											),
											"notificationCode" => "0008"
										);
			
					AddToPushMessageQueue($party2queryarray["id"], $PushMessage, $PushMessage["otherPartyDetails"], null, $userID, $party2_id, 'OPEN_CHAT');
			
					return array(
									"otherPartyDetails" => array(
																	 "userID" => $party2queryarray["id"],
																	 "profileData" => FormatProfile($party2queryarray["user_profile"]),
																	 "profileImage" => $party2queryarray["user_profile_image"]
																 ),
									"respCode" => "0042" //"Chat message sent successfully"
								 );
			}			
		}
		
		return array(
						"respCode" => "0028" //"You are not connecte with any user"
					 );
	}
	return array(
					"respCode" => "0012"//"Cannot Process due to System Error. Please Try again soon"
				 );		
}

function StopChat($userID)
{
	global $db;
	global $mypal_users;
	global $sqllog;
	global $time;
	
	//"0043" => "You have stopped chatting"	
	//"0028" => "You are not connected with any user",
	
	$querystring = "SELECT * FROM $mypal_users WHERE  id = $userID";
	writetolog($querystring,$sqllog);	
	$userquery = mysqli_query($db,$querystring);
	if($userqueryarray = mysqli_fetch_assoc($userquery))
	{
		if($userqueryarray["status"] == "connected")
		{
			$party2querystring = "SELECT * FROM $mypal_users WHERE  id = $userqueryarray[party2_id] AND party2_id = $userID AND status = 'connected'";
			writetolog($party2querystring,$sqllog);	
			$party2query = mysqli_query($db,$party2querystring);
			if($party2queryarray = mysqli_fetch_assoc($party2query))
			{					
				  //Update A-party
				  $querystring = "UPDATE $mypal_users SET status = 'free', party2_id = 0 WHERE id = $userID";
				  writetolog($querystring,$sqllog);	
				  $userquery = mysqli_query($db,$querystring);
				  
				  //Update and Push message to party 2
				  $querystring = "UPDATE $mypal_users SET status = 'free', party2_id = 0 WHERE id = $party2queryarray[id]";
				  writetolog($querystring,$sqllog);	
				  $userquery = mysqli_query($db,$querystring);
			
					$PushMessage = array(
										 	"type" => "notification",
											"message" => GetProfileToString(FormatProfile($userqueryarray["user_profile"]))." has left. Click \"Find\" to find a new friend!",
											"otherPartyDetails" => array(
																			 "userID" => $userqueryarray["id"],
																			 //"ProfileData" => json_decode($userqueryarray["user_profile"],true)
											),
											"notificationCode" => "0001"
										);
				
					AddToPushMessageQueue($party2queryarray["id"], $PushMessage);
						
		
				  	return array(
								"respCode" => "0043", //"You have stopped chatting"	
								/*
								"otherPartyDetails" => array(
																 "userID" => $party2queryarray["id"],
																 "ProfileData" => json_decode($party2queryarray["user_profile"],true)
															)
								*/
							   );
			}	
		}
		
		  //Update A-party
		  $querystring = "UPDATE $mypal_users SET status = 'free', party2_id = 0 WHERE id = $userID";
		  writetolog($querystring,$sqllog);	
		  $userquery = mysqli_query($db,$querystring);
		
		return array(
						"respCode" => "0028" //"You are not connecte with any user"
					 );
	}
	return array(
					"respCode" => "0012"//"Cannot Process due to System Error. Please Try again soon"
				 );	
}

function FormatProfile($profileData)
{
	$filler = "";
	$profileDataArray = json_decode($profileData,true);
	
	if(is_array($profileDataArray))
	{
		foreach($profileDataArray as $key => $value)
		{
			$profile[$key] = ($value<>"") ? $value : $filler;
		}

	}else{
		$profile = array(
							"nickname" =>"Guest",
							"age" =>$filler,
							"gender" => $filler,
							"location" => $filler,
							"lat" => "",
							"lon" => ""
						);
	}
	return $profile;	// Array
}

function GetPushMessage($userID)
{
	global $db;
	global $mypal_users;
	global $sqllog;
	global $time;
	
	$querystring = "SELECT * FROM $mypal_users WHERE  id = $userID";
	writetolog($querystring,$sqllog);	
	$userquery = mysqli_query($db,$querystring);
	if($userqueryarray = mysqli_fetch_assoc($userquery))
	{	
		//clear push message queue
		$querystring = "UPDATE $mypal_users SET push_message_queue = '' WHERE id = $userID";
		writetolog($querystring,$sqllog);		
		$userquery = mysqli_query($db,$querystring);
		
		return array(
						"respCode" => "1000",//"Operation processed successfully"
						//"messageQueue" => json_decode($userqueryarray["push_message_queue"],true)
						"messageQueue" => $userqueryarray["push_message_queue"]
					 ); 
	}
	
	return array(
					"respCode" => "0012"//"Cannot Process due to System Error. Please Try again soon"
				 );		
}


function AddToPushMessageQueue($userID, $PushMessage, $urlPointer = null, $otherPartyDetails = null, $fromID = null, $toID = null, $messageType = null)
{
	global $db;
	global $mypal_users;
	global $sqllog;
	global $time;
	global $debuglog;
	
	$party2querystring = "SELECT * FROM $mypal_users WHERE  id = $userID";
	writetolog($party2querystring,$sqllog);	
	$party2query = mysqli_query($db,$party2querystring);
	if($party2queryarray = mysqli_fetch_assoc($party2query))
	{	
		writetolog($party2queryarray["push_message_queue"],$debuglog);
		
		$push_message_queue = json_decode($party2queryarray["push_message_queue"],true);
		
		writetolog(json_encode($push_message_queue),$debuglog);
		/*
		{"1601831827":{"type":"chatMessage","message":"YYYYYYYYYY","otherPartyDetails":{"userID":"23","ProfileData":"{"nickname":"B-user","age":"44","gender":"female","location":"Colombo","lat":"100.00","lon":"50.50"}"}}}
		
		*/
		$push_message_queue[$time] = $PushMessage;
		
		writetolog(json_encode($push_message_queue),$debuglog);
		
		$push_message_queue_json = json_encode($push_message_queue);
		
		$querystring = "UPDATE $mypal_users SET push_message_queue = '$push_message_queue_json' WHERE  id = $userID";
		writetolog($querystring,$sqllog);	
		// $userquery = mysqli_query($db,$querystring);

		sendPushMessage($userID,$party2queryarray["pushMessageToken"],$PushMessage["message"],$PushMessage["notificationCode"], $urlPointer, $otherPartyDetails, $fromID, $toID, $messageType);
	}
	
	return true;
}

/*
function sendPushMessage_Original($userID, $deviceToken, $body, $notificationCode, $urlPointer = null, $otherPartyDetails = null)
{
	global $db;
	global $mypal_users;
	global $sqllog;
	global $time;
	global $debuglog;
	global $pushmessagelog;
	global $pushNotificationTemplate;
	global $operator;

	 //FCM-161220	
    // $server_key = 'AAAADUvUaQg:APA91bEkieuBtQhJLOzCGqX1JA3Ycru7Ot-Dmmad7MpkBltO1ETSn9nffuL8H2LNnYK5fnchkFATajb6kkg_KBA10MTc3zcr4ns6lk8NRbdPkhNZEiQXb53ABqyksD6xg9uzi7WjHAmc';
    
    //MyPal-Beta
    $server_key = 'AAAANJWaqv0:APA91bH03cd5KnmXKp0MIKq0CwSiX5nSmMrl4Umc5wQMzcYh1TRen-ssVqVH2j5LWqYYaLTXFF-WuDNmGe0NHY-HtksvhmHYFyT282tPjlez_nBYpyXu9QUoCPcfaoOC7h9e6_sIY7nX';
    
    //Dev test
    // $server_key = 'AAAAQfl8a5c:APA91bHKOTOi3Um6fmpL4-Xd_YjtY0Zw43t0BKrLS1KiM9ADTcqv7st1_NfzO8pXS-EYHYKadTRyydDlxt63AaqwXfiNTEHbr1666KDlhd3UczHp40RAjGGRstdX4_mxJeYjVhD6ObvT';

	// $title = $pushMessageTemplates[$operator]["title"];
	// $body = $pushMessageTemplates[$operator]["body"];
	// $icon = $pushMessageTemplates[$operator]["icon"];
	// $message = $pushMessageTemplates[$operator]["message"];

	if(is_null($urlPointer))
	{
		$json_data = array(
							"to" => $deviceToken,
							"notification" => array(
														"title"=> $pushNotificationTemplate["title"],
														"icon" => $pushNotificationTemplate["icon"],
														"body" => $body
													),
							"data" =>  $pushNotificationTemplate["message"][$operator]
						);   
	}else{
		$json_data = array(
							"to" => $deviceToken,
							"notification" => array(
														"title"=> $pushNotificationTemplate["title"],
														"icon" => $pushNotificationTemplate["icon"],
														"body" => $body
													),
							"data" =>  $pushNotificationTemplate["message"][$operator][$urlPointer]
						);  
	}

	//set other party details
	if(!is_null($otherPartyDetails))
	{
		// $json_data["data"]["user"]["userID"] = $otherPartyDetails["userID"];
		// $json_data["data"]["user"]["nickname"] = $otherPartyDetails["profileData"]["nickname"];
		// $json_data["data"]["user"]["profileImage"] = $otherPartyDetails["profileImage"];
		
		$json_data["data"]["userID"] = $otherPartyDetails["userID"];
		$json_data["data"]["nickname"] = $otherPartyDetails["profileData"]["nickname"];
		$json_data["data"]["profileImage"] = $otherPartyDetails["profileImage"];
	}
	
	//set other parameters prioriy
	$json_data["data"]["action"] = $operator;
	$json_data["data"]["notificationCode"] = $notificationCode;
	$json_data["android"]["priority"] = "high";
	
	
	$data = json_encode($json_data);
	writetolog("PushMessage Request >> ".$userID."|".$deviceToken."|".$data,$pushmessagelog);
      
    //FCM API end-point
    $url = 'https://fcm.googleapis.com/fcm/send';
    //api_key in Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key
    //header with content_type api key
    $headers = array(
        'Content-Type:application/json',
        'Authorization:key='.$server_key
    );
    //CURL request to route notification to FCM connection server (provided by Google)
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $result = curl_exec($ch);
    if ($result === FALSE) {
		// die('Oops! FCM Send Error: ' . curl_error($ch));
		writetolog("PushMessage Response << ".curl_error($ch),$pushmessagelog);
    }
    curl_close($ch);
    writetolog("PushMessage Response << ".$result,$pushmessagelog);
    return $result;
}
*/

function sendPushMessage($userID, $deviceToken, $body, $notificationCode, $urlPointer = null, $otherPartyDetails = null, $fromID, $toID, $messageType)
{
	global $db;
	global $mypal_users;
	global $sqllog;
	global $time;
	global $debuglog;
	global $pushmessagelog;
	global $pushNotificationTemplate;
	global $operator;
	// global  $server_key;

	$server_key = get_fcm_token();

	if($messageType == null)
	{
		$messageType = 'OPEN_CHAT_WITH_STATUS';
	}

	$json_data = [
		'message' => [
			'token' => $deviceToken,
			'data' => [
				'type' => 'chat',
				'message' => $body,
				'body' => $body,
				// 'fromUserId' => $otherPartyDetails['userID'],
				'fromUserId' => $fromID
			],
			'notification' => [
				'title' => $pushNotificationTemplate["title"],
				'body' => $body
			],
			'android' => [
				'priority' => 'high',
				'notification' => [
					// 'click_action' => 'OPEN_CHAT'
					'click_action' => $messageType
				]
			]
			]
	];



// 		var_dump($pushNotificationTemplate);
// exit;


/*
	if(is_null($urlPointer))
	{
		$json_data = array(
							"to" => $deviceToken,
							"notification" => array(
														"title"=> $pushNotificationTemplate["title"],
														"icon" => $pushNotificationTemplate["icon"],
														"body" => $body
													),
							"data" =>  $pushNotificationTemplate["message"][$operator]
						);   
	}else{
		$json_data = array(
							"to" => $deviceToken,
							"notification" => array(
														"title"=> $pushNotificationTemplate["title"],
														"icon" => $pushNotificationTemplate["icon"],
														"body" => $body
													),
							"data" =>  $pushNotificationTemplate["message"][$operator][$urlPointer]
						);  
	}
*/

/*
	//set other party details
	if(!is_null($otherPartyDetails))
	{
		// $json_data["data"]["user"]["userID"] = $otherPartyDetails["userID"];
		// $json_data["data"]["user"]["nickname"] = $otherPartyDetails["profileData"]["nickname"];
		// $json_data["data"]["user"]["profileImage"] = $otherPartyDetails["profileImage"];
		
		$json_data["data"]["userID"] = $otherPartyDetails["userID"];
		$json_data["data"]["nickname"] = $otherPartyDetails["profileData"]["nickname"];
		$json_data["data"]["profileImage"] = $otherPartyDetails["profileImage"];
	}
	
	//set other parameters prioriy
	$json_data["data"]["action"] = $operator;
	$json_data["data"]["notificationCode"] = $notificationCode;
	$json_data["android"]["priority"] = "high";
*/
	
	$data = json_encode($json_data);
	writetolog("PushMessage Request >> ".$userID."|".$deviceToken."|".$data,$pushmessagelog);
      
    //FCM API end-point
    $url = 'https://fcm.googleapis.com/v1/projects/mingle-ed148/messages:send';
    //api_key in Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key
    //header with content_type api key
    $headers = array(
        'Content-Type:application/json',
        'Authorization:Bearer '.$server_key
    );
    //CURL request to route notification to FCM connection server (provided by Google)
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $result = curl_exec($ch);
    if ($result === FALSE) {
		// die('Oops! FCM Send Error: ' . curl_error($ch));
		writetolog("PushMessage Response << ".curl_error($ch),$pushmessagelog);
    }
    curl_close($ch);
    writetolog("PushMessage Response << ".$result,$pushmessagelog);
    return $result;
}

function GetProfileToString($profileData)
{
	global $profile_data_variables;
	
	foreach($profileData as $profileField => $profileValue)
	{
		if(!$profile_data_variables[$profileField])
		{
			unset($profileData[$profileField]);
		}
	}
	
	return implode(",",$profileData);
}


function isJson($string) {
 json_decode($string);
 return (json_last_error() == JSON_ERROR_NONE);
}

function writetolog($content,$logfile)
{
	global $sequencecode;
		
	$fp = fopen($logfile, 'a');
	fwrite($fp, $sequencecode."|(".date("g:i A dmy").")".$content."\n");
	fclose($fp);
}


function set_chat_history_window($chat_list)
{
	global $chat_history_limit;

    if (count($chat_list) <= $chat_history_limit) {
        return $chat_list;
    }
    krsort($chat_list);

    $trimmed_array = array_slice($chat_list, 0, $chat_history_limit, true);

    return $trimmed_array;
}

function clearHistory($userID)
{
	global $db,$mypal_users,$sqllog,$time;

	$querystring = "UPDATE $mypal_users SET chat_history = '' WHERE id = $userID";
	writetolog($querystring,$sqllog);		
	$userquery = mysqli_query($db,$querystring);
	return [
		"respCode" => "0054" //"0054" => "Chat history cleared successfully",
	];
}

function get_profile_string($profile_json)
{
	global $profile_string_parameters;
	$profile_array = [];

    $data_array = json_decode($profile_json, true);

    if (!is_array($data_array)) {
        return ""; // Return empty string if invalid JSON
    }

	foreach($profile_string_parameters as $field)
	{
		if($data_array[$field] <> '')
		{
			array_push($profile_array,$data_array[$field]);
		}
	}

	return implode(',', $profile_array);
}

function get_fcm_token()
{
	global $db,$serviceJsonPath,$mingle_fcm_token_table,$time;

	$token_query = mysqli_query($db,"SELECT * FROM $mingle_fcm_token_table WHERE  id = 1");
	if($token_query_array = mysqli_fetch_assoc($token_query))
	{
		if($token_query_array['expiry_time'] > $time)
		{
			return $token_query_array['token'];
		}else{

			if (!file_exists($serviceJsonPath)) {
        	throw new RuntimeException("Service account JSON not found: $serviceJsonPath");
			}

			$json = json_decode(file_get_contents($serviceJsonPath), true);
			if (!$json || empty($json['client_email']) || empty($json['private_key'])) {
				throw new RuntimeException("Invalid service account JSON.");
			}
			$clientEmail = $json['client_email'];
			$privateKey  = $json['private_key'];
			// Replace literal \n with real newlines if needed
			if (strpos($privateKey, "\\n") !== false) $privateKey = str_replace("\\n", "\n", $privateKey);

			$now = time();
			$header = ['alg' => 'RS256', 'typ' => 'JWT'];
			$claims = [
				'iss'   => $clientEmail,
				'scope' => 'https://www.googleapis.com/auth/firebase.messaging',
				'aud'   => 'https://oauth2.googleapis.com/token',
				'iat'   => $now,
				'exp'   => $now + 3600, // max 1h
			];

			$encodedHeader  = b64url(json_encode($header));
			$encodedClaims  = b64url(json_encode($claims));
			$signingInput   = $encodedHeader . '.' . $encodedClaims;

			$pkey = openssl_pkey_get_private($privateKey);
			if (!$pkey) throw new RuntimeException("Failed to load private key (openssl).");

			$signature = '';
			if (!openssl_sign($signingInput, $signature, $pkey, OPENSSL_ALGO_SHA256)) {
				throw new RuntimeException("openssl_sign failed.");
			}
			openssl_pkey_free($pkey);
			$jwt = $signingInput . '.' . b64url($signature);

			// Exchange JWT for access token
			$resp = http_post_form('https://oauth2.googleapis.com/token', [
				'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
				'assertion'  => $jwt,
			]);
			$tok = json_decode($resp, true);
			if (empty($tok['access_token']) || empty($tok['expires_in'])) {
				throw new RuntimeException("Failed to obtain access token: $resp");
			}

			$token = $tok['access_token'];
			$expiry_time = $time + 60*60;
			$querystring = "UPDATE $mingle_fcm_token_table SET token = '$token', created_time = '$time', expiry_time = '$expiry_time'  WHERE id = 1";
			writetolog($querystring,$sqllog);		
			$userquery = mysqli_query($db,$querystring);

			return $token;
		}
	}
}

function b64url($s) {
    return rtrim(strtr(base64_encode($s), '+/', '-_'), '=');
}

function http_post_form($url, array $fields, $timeout = 20) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST            => true,
        CURLOPT_POSTFIELDS      => http_build_query($fields, '', '&'),
        CURLOPT_RETURNTRANSFER  => true,
        CURLOPT_TIMEOUT         => $timeout,
        CURLOPT_HEADER          => false,
    ]);
    $body = curl_exec($ch);
    $http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err  = curl_error($ch);
    curl_close($ch);
    if ($body === false || $http >= 400) {
        throw new RuntimeException("HTTP $http: $err $body");
    }
    return $body;
}

?>
