<?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);
	$data_string = json_encode($data, JSON_UNESCAPED_UNICODE);
        
	$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;

	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, $permissions)
{
	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', permissions_status = '$permissions' 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,
						"disableCalling" => $userqueryarray['disable_calling'],
						"otherparty_profileImage" => $party2queryarray['user_profile_image']
					);			
	}else{
		$sessionKey = get_session_key($google_user_key,$time);
		$querystring = "INSERT INTO $mypal_users (google_user_key,pushMessageToken,sessionKey,joined_date,session_last_active_time,status,firebase_uid,email,name,permissions_status) VALUES ('$google_user_key','$device_token','$sessionKey','$time','$time','standby','$firebase_uid','$email','$name','$permissions')";
		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" => mysqli_insert_id($db),
						"chat_history" => [],
						'connection_status' => $connection_status,
						"disableCalling" => "0"
					);	
	}
}

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;
	
	$querystring = "SELECT * FROM $mypal_users WHERE  id = $userID";
	writetolog($querystring,$sqllog);	
	$userquery = mysqli_query($db,$querystring);
	if($userqueryarray = mysqli_fetch_assoc($userquery))
	{

		$user_profile_array = json_decode($userqueryarray["user_profile"],true);
		$profileData['aboutMe'] = $user_profile_array['aboutMe'];
		$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);
	}


	// $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 setAbout($userID, $aboutMe)
{
	global $db,$mypal_users,$sqllog,$time;
	
	$querystring = "SELECT * FROM $mypal_users WHERE  id = $userID";
	writetolog($querystring,$sqllog);	
	$userquery = mysqli_query($db,$querystring);
	if($userqueryarray = mysqli_fetch_assoc($userquery))
	{

		$user_profile_array = json_decode($userqueryarray["user_profile"],true);
		$user_profile_array['aboutMe'] = $aboutMe;
		$profileDataJson = json_encode($user_profile_array, 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://mingle.eft.xyz/profiles/"

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

	$profileImage = $profile_image_path.$userID."/".$userID.".jpg";
	
	$base64_image_string = $encodedProfileImage;
	/*
	$image_parts = explode(";base64,", $encodedProfileImage);
	if (count($image_parts) === 2) {
		$base64_image_string = $image_parts[1];
	}
		*/

	$decodedProfileImageString = base64_decode($base64_image_string);
	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.".jpg?".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 [
			"respCode" => "0059", //"0059" => "Profile photo uploaded successfully.",
			"profileImage" => $user_profile_image
		];
	}
}

/****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" => "00271" //"00271" => "You are connected with <party2details>",
								 );
			}			
		}
		
		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, $mypal_users, $sqllog, $time, $friend_types, $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"])
			{

				if($friendType == 'Approved')
				{
					// $friendList = explode(",",$userqueryarray[$friendTypeData["fieldName"]]);
					$friendList = json_decode($userqueryarray[$friendTypeData["fieldName"]], true);

					foreach($friendList as $friendUserID => $muteStatus)
					{
						$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"],
																									"muteStatus" => $muteStatus
																							);
							}else{
								$friendListData["FriendsData"][$friendType][$friendUserID] = array(
																									"profileData" => FormatProfile($friendqueryarray["user_profile"]),
																									"profileImage" => $friendqueryarray["user_profile_image"],
																									"status" => $friend_status_handling[$friendqueryarray["status"]][false]["displayStatus"],
																									"muteStatus" => $muteStatus
																							);
							}
						}
					}
				}else{
					$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"
				 );				
			}

			if(in_array($userqueryarray["party2_id"],explode(",",$userqueryarray["friends_requests_sent"])))
			{
				return array(
					"respCode" => "0055" //"0055" => "Friend request sent to user",
				 );				
			}

			if(in_array($userqueryarray["party2_id"],explode(",",$userqueryarray["friends_requests_received"])))
			{		 
				 return AcceptFriend($userID, $userqueryarray["party2_id"]);
			}

			$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" => "addFriend",
											"message" => GetProfileToString(FormatProfile($userqueryarray["user_profile"]))." has sent a Friend request",
											"otherPartyDetails" => array(
																			 "userID" => $userqueryarray["id"],
																			 "profileImage" => $party2queryarray["user_profile_image"]
											),
											"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, $mypal_users, $sqllog, $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"]);
		$friendsListArray = json_decode($userqueryarray["friends_approved"], true);
		unset($friendsListArray[$otherPartyID]);

		// if(array_search($otherPartyID,$friendsListArray) <> FALSE)
		// {
		// 	unset($friendsListArray[array_search($otherPartyID,$friendsListArray)]);			
		// }
		// $friendsListString = implode(",",array_unique($friendsListArray));
		$friendsListString = json_encode($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"]);
				$friendsListArray = json_decode($party2queryarray["friends_approved"], true);
				unset($friendsListArray[$userID]);

				// if(array_search($userID,$friendsListArray) <> FALSE)
				// {
				// 	unset($friendsListArray[array_search($userID,$friendsListArray)]);			
				// }
				// $friendsListString = implode(",",array_unique($friendsListArray));
				$friendsListString = json_encode($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, $permissions)
{
	global $db, $mypal_users, $permissions_table, $sqllog, $time, $max_previous_chat_user_buffer, $db_host, $db_username, $db_password, $db_name, $subscription_free_period, $subscription_profiles, $enabled_subscription_package, $subscriptionsEnabled, $check_empty_profile, $callholdtimer;

	$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["joined_date"] < ($time + $subscription_free_period) and $subscriptionsEnabled)
		{
			$subscription_profiles[$enabled_subscription_package]['obfuscatedAccountId'] = $userID;
			$subscription_profiles[$enabled_subscription_package]['obfuscatedProfileId'] = $userqueryarray["email"];
			return array(
				        "trigger_subscription" => $subscription_profiles[$enabled_subscription_package],
						"respCode" => "0085", //"0085" => "Subscription initiation request sent successfully"
						);
		}
		
		if($userqueryarray["user_profile"] == "" and $check_empty_profile)
		{
			return array(
						"respCode" => "0056", //"0056" => "You need to set your profile first before starting to chat.",
						);
		}
		
		
		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);
				$chat_history_party2_user_json = json_encode($chat_history_party2_user, JSON_UNESCAPED_UNICODE);

				$querystring = "UPDATE $mypal_users SET status = 'free', party2_id = 0, chat_history = '$chat_history_party2_user_json', calling_status = 'idle' 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");
				
			}			
		}
		
		//update to searching status
		$querystring = "UPDATE $mypal_users SET status = 'searching', party2_id = 0, calling_status = 'idle', permissions_status = '$permissions' 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"])) or !$chat_history_check)
		  {		
		  	  //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);
			$chat_history_party2_user_json = json_encode($chat_history_party2_user, JSON_UNESCAPED_UNICODE);

			//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', calling_status = 'idle'  WHERE id = $searchFriendqueryArray[id]";
			writetolog($querystring,$sqllog);	
			$userquery = mysqli_query($db,$querystring);
			
				$PushMessage = array(
									 	"type" => "notification",
										"message" => "You are now connected with ".GetProfileToString(FormatProfile($userqueryarray["user_profile"])),
										"otherPartyDetails" => array(
																		 "userID" => $userqueryarray["id"],
																		 "profileData" => FormatProfile($userqueryarray["user_profile"]),
																		 "profileImage" => $userqueryarray["user_profile_image"]
										),
										"callholdtimer" => $callholdtimer,
										"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);
			  $chat_history_party1_user_json = json_encode($chat_history_party1_user, JSON_UNESCAPED_UNICODE);
			

			  //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', calling_status = 'idle' 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, $mypal_users, $sqllog, $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 = json_decode($party2queryarray["friends_approved"], true);
				
				//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
				$party2_friends_approved_array[$userID] = "0"; //save as unmuted
				$party2_friends_approved_str = json_encode($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" => "acceptFriend",
										"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"]);
				$friends_approved_array = json_decode($userqueryarray["friends_approved"], true);
				
				//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
				$friends_approved_array[$friendID] = "0";  //save as unmuted
				$friends_approved_str = json_encode($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, $mypal_users, $sqllog, $time, $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"]
																)
								);
				}
		}

		$friendList = json_decode($userqueryarray["friends_approved"], true);
		if (array_key_exists($friendID, $friendList))
		{
			$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"],
																						 "profileImage" => $userqueryarray["user_profile_image"],
																						 //"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 now connected with ".GetProfileToString(FormatProfile($userqueryarray["user_profile"])),
											"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
					
					$party2friendList = json_decode($party2queryarray["friends_approved"], true);
					if($friend_status_handling[$party2queryarray["status"]][false]["notifyFriend"])
					{//Notify B party
						$PushMessage = array(
												"type" => "chatInvite",
												"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"],
																				 "muteStatus" => $party2friendList[$userID] //XXXXXXXXXXXXXXXXX
												),
												"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 setFriendMute($userID, $setFriendID, $mute)
{
	global $time,$db,$mypal_users,$sqllog,$mingle_report_log_table;

	$querystring = "SELECT * FROM $mypal_users WHERE  id = $userID";
	writetolog($querystring,$sqllog);		
	$userquery = mysqli_query($db,$querystring);
	if($userqueryarray = mysqli_fetch_assoc($userquery))
	{	
		$friends_approved_array = json_decode($userqueryarray['friends_approved'], true);
	}

	$friends_approved_array[$setFriendID] = $mute;
	$friends_approved_json = json_encode($friends_approved_array);

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

	return [
		'respCode' =>  "0086"//"0086" => "Friend mute setting updated successfully"
	];
}

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);
					$chat_history_from_user_json = json_encode($chat_history_from_user, JSON_UNESCAPED_UNICODE);
					$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);
					$chat_history_to_user_json = json_encode($chat_history_to_user, JSON_UNESCAPED_UNICODE);
					$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;
		}

		if($profile['aboutMe'] == '')
		{
			$profile['aboutMe'] = "Hi, Nice to meet you!";
		}
	}else{
		$profile = array(
							// "nickname" =>"Guest",
							"nickname" => $filler,
							"age" =>$filler,
							"gender" => $filler,
							"location" => $filler,
							"lat" => "",
							"lon" => "",
							"aboutMe" => "Hi, Nice to meet you!"
						);
	}
	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, $mypal_users, $sqllog, $time, $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);
		$push_message_queue_json = json_encode($push_message_queue, JSON_UNESCAPED_UNICODE);
		
		$querystring = "UPDATE $mypal_users SET push_message_queue = '$push_message_queue_json' WHERE  id = $userID";
		writetolog($querystring,$sqllog);	
		// $userquery = mysqli_query($db,$querystring);

		// var_dump($otherPartyDetails);
		// exit;
		if(!isset($otherPartyDetails['profileImage']) or $otherPartyDetails['profileImage'] == '')
		{
			$otherPartyDetails['profileImage'] = $PushMessage['otherPartyDetails']['profileImage'];
		}

		$otherPartyDetails['muteStatus'] = $PushMessage['otherPartyDetails']['muteStatus'];

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

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

	$server_key = get_fcm_token();

	if($messageType == null or $messageType == '' or $messageType == 'notification')
	{
		$messageType = 'OPEN_CHAT_WITH_STATUS';
		$type = 'chat';
	}else{
		$type = $messageType;
		if($messageType == 'chatMessage')
		{
			$messageType = 'OPEN_CHAT_WITH_STATUS';
		}
	}

	$json_data = [
		'message' => [
			'token' => $deviceToken,
			'data' => [
				'type' => $type,
				'message' => $body,
				'body' => $body,
				// 'fromUserId' => $otherPartyDetails['userID'],
				'fromUserId' => $fromID,
				'profileImage' => $otherPartyDetails['profileImage'],
				'aboutMe' => $otherPartyDetails['profileData']['aboutMe'],
				'muteStatus' => $otherPartyDetails['muteStatus'],
				'callholdtimer' =>  $callholdtimer
			],
			'notification' => [
				'title' => $pushNotificationTemplate["title"],
				'body' => $body,
				// 'icon'  => 'ic_mingle_push'
			],
			'android' => [
				'priority' => 'high',
				'notification' => [
					// 'click_action' => 'OPEN_CHAT'
					'icon'        => 'ic_mingle_push',
					'click_action' => $messageType
				]
			]
			]
	];
	
	// $data = json_encode($json_data);
	$data = json_encode($json_data, JSON_UNESCAPED_UNICODE);
	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 deleteProfilePhoto($userID)
{
	global $db,$mypal_users,$sqllog,$time;

	$querystring = "UPDATE $mypal_users SET user_profile_image = '' WHERE id = $userID";
	writetolog($querystring,$sqllog);		
	$userquery = mysqli_query($db,$querystring);
	return [
		"respCode" => "0061" //"0061" => "Profile photo deleted 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;
}

function reverseGeoCode($userID, $lat, $lon)
{
	return [
		'respCode' => '0057', //"0057" => "reverse geo coded the location successfully.",
		'location' => 'this is the location'
	];
}

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

	$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))
			{
				$reported_by_id = $userID;
				$reported_by_chat_history = $userqueryarray['chat_history'];

				$reported_for_id = $userqueryarray['party2_id'];
				$reported_for_chat_history = $party2queryarray['chat_history'];

				$querystring = "INSERT INTO $mingle_report_log_table (reported_time,reported_by_id,reported_by_chat_history,reported_for_id,reported_for_chat_history) VALUES ('$time', '$reported_by_id','$reported_by_chat_history','$reported_for_id','$reported_for_chat_history')";
				writetolog($querystring,$sqllog);
				mysqli_query($db,$querystring);

				return [
					'respCode' => '0058', //"0058" => "User reported successfully."
				];

			}else{

				return [
					'respCode' => '0028', //"0028" => "You are not connected with any user",
				];
			}
		}else{
			return [
					'respCode' => '0028', //"0028" => "You are not connected with any user",
				];
		}
	}
}

function setProfilePhoto($image_data,$file_name)
{
	$base64_image_string = $image_data;

	// 2. Remove the "data:image/..." prefix (if present)
	$image_parts = explode(";base64,", $base64_image_string);
	if (count($image_parts) === 2) {
		$base64_image_string = $image_parts[1];
	}

	// 3. Decode the image data
	$binary_image_data = base64_decode($base64_image_string);

	// 4. Set the path and save the file
	$file_path = "profiles/" . $file_name;
	$success = file_put_contents($file_path, $binary_image_data);

	if ($success) {
		return [
			"respCode" => "0059", //"0059" => "Profile photo uploaded successfully.",
			"path" => $file_path
		];
	} else {
		return [
			"respCode" => "0060", //"0060" => "Profile photo upload failure.",
			"message" => "Failed to save file."
		];
	}
}

function disableCalling($userID, $disable)
{
	global $time,$db,$mypal_users,$sqllog,$mingle_report_log_table;

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

	/*
	"00740" => "voice/video calling enabled",
	"00741" => "voice/video calling disabled",
	*/

	return [
			"respCode" =>  ($disable == '1') ? '00741' : '00740',
			"disable" => $disable
		]; 
}

function callInvite($userID, $callType, $sendfcm)
{
	global $time,$db,$mypal_users,$sqllog,$mingle_report_log_table;

	$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))
			{
				if($party2queryarray['disable_calling'] == 1)
				{
					return [
						"respCode" => "0075", //"0075" => "other party has disabled calling"
					];
				}

				if($party2queryarray['calling_status'] == 'calling')
				{
					return [
						"respCode" => "00751", //"00751" => "other party is busy",
					];
				}

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

				$twilio_token = getToken($userID)['token'];
				$twilio_room = $userID . '_' . $userqueryarray['party2_id'] . '_' . $time;

				$uuid = generate_uuid_v4();
				mysqli_query($db,"UPDATE $mypal_users SET call_uuid = '$uuid' WHERE id = $userID");
				mysqli_query($db,"UPDATE $mypal_users SET call_uuid = '$uuid' WHERE id = $userqueryarray[party2_id]");

				if($sendfcm)
				{
					send_fcm_for_call($userID, $userqueryarray['party2_id'], $uuid, 'incoming_call',$twilio_room);
				}

					return [
					"respCode" => "0062", //"0062" => "calling the other party",
					"party2id" => $userqueryarray['party2_id'],
					"twilioToken" => $twilio_token,
					"twilio_room" => $twilio_room,
					"otherPartyDetails" => array(
													"userID" => $party2queryarray["id"],
													"profileData" => FormatProfile($party2queryarray["user_profile"]),
													"profileImage" => $party2queryarray["user_profile_image"],
													"isFriend" => $isFriend
												),
					"own_profileImage" => $userqueryarray["user_profile_image"]
					];

			}else{
				return [
					"respCode" => "0028", //"0028" => "You are not connected with any user",
				];
			}

		}else{
			return [
					"respCode" => "0028", //"0028" => "You are not connected with any user",
				];
		}
	}
}

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

	$querystring = "SELECT * FROM $mypal_users WHERE id = $userID";
	$userquery = mysqli_query($db,$querystring);

	if($userqueryarray = mysqli_fetch_assoc($userquery))
	{
		if($userqueryarray['twilio_token_expiry'] > $time)
		{
			sleep(1);
			return [
				'token' => $userqueryarray['twilio_token']
			];
		}else{
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_URL, $twilio_token_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); 

				curl_close($ch);
    			writetolog("Twillog Token request|response|" . $userID . "|" . $result,$sqllog);

				$result_array = json_decode($result, true);
				$twilio_token = $result_array['twilio_token'];
				$twilio_token_expiry = $result_array['twilio_token_expiry'];

				$querystring = "UPDATE $mypal_users SET twilio_token = '$twilio_token', twilio_token_expiry = '$twilio_token_expiry' WHERE id = $userID";	
				$userquery = mysqli_query($db,$querystring);
				return [
				'token' => $twilio_token
			];
		}
	}
}

function callDecline($party2_id, $sendfcm)
{
	global $time,$db,$mypal_users,$sqllog,$mingle_report_log_table;

	$querystring = "SELECT * FROM $mypal_users WHERE id = $party2_id";
	writetolog($querystring,$sqllog);	
	$userquery = mysqli_query($db,$querystring);
	if($userqueryarray = mysqli_fetch_assoc($userquery))
	{
		$party1_id = $userqueryarray['party2_id'];

		$querystring = "UPDATE $mypal_users SET calling_status = 'idle' WHERE id = $party1_id";
		$userquery = mysqli_query($db,$querystring);

		$querystring = "UPDATE $mypal_users SET calling_status = 'idle' WHERE id = $party2_id";
		$userquery = mysqli_query($db,$querystring);

		if($sendfcm)
		{
			send_fcm_for_call($party2_id, $party1_id, $uuid, 'call_declined', null, 'User declined the call');
		}

		return [
				 "respCode" => "0066", //"0066" => "callDecline successful",
			];
	}
}

function callCancel($party1_id, $sendfcm)
{
	global $time,$db,$mypal_users,$sqllog,$mingle_report_log_table;

	$querystring = "SELECT * FROM $mypal_users WHERE id = $party1_id";
	writetolog($querystring,$sqllog);	
	$userquery = mysqli_query($db,$querystring);
	if($userqueryarray = mysqli_fetch_assoc($userquery))
	{
		$party2_id = $userqueryarray['party2_id'];

		$querystring = "UPDATE $mypal_users SET calling_status = 'idle' WHERE id = $party1_id";
		$userquery = mysqli_query($db,$querystring);

		$querystring = "UPDATE $mypal_users SET calling_status = 'idle' WHERE id = $party2_id";
		$userquery = mysqli_query($db,$querystring);
	
		if($sendfcm)
		{
			send_fcm_for_call($party1_id, $party2_id, $uuid, 'call_cancelled', null, 'User cancelled the call');
		}

		return [
				 "respCode" => "0077", //"0077" => "callCancel successful"
			];
	}
}

function callEnd($party1_id, $sendfcm)
{
	global $time,$db,$mypal_users,$sqllog,$mingle_report_log_table;

	$querystring = "SELECT * FROM $mypal_users WHERE id = $party1_id";
	writetolog($querystring,$sqllog);	
	$userquery = mysqli_query($db,$querystring);
	if($userqueryarray = mysqli_fetch_assoc($userquery))
	{
		$party2_id = $userqueryarray['party2_id'];

		$querystring = "UPDATE $mypal_users SET calling_status = 'idle' WHERE id = $party1_id";
		$userquery = mysqli_query($db,$querystring);

		$querystring = "UPDATE $mypal_users SET calling_status = 'idle' WHERE id = $party2_id";
		$userquery = mysqli_query($db,$querystring);
	
		if($sendfcm)
		{
			send_fcm_for_call($party1_id, $party2_id, $uuid, 'call_ended', null, 'User ended the call');
		}

		return [
				 "respCode" => "0087", //"0087" => "Call ended successfully"
			];
	}
}

function callAnswer($userID, $room, $sendfcm)
{
	global $time,$db,$mypal_users,$sqllog,$mingle_report_log_table;

	$querystring = "SELECT * FROM $mypal_users WHERE id = $userID";
	writetolog($querystring,$sqllog);	
	$userquery = mysqli_query($db,$querystring);

	if($userqueryarray = mysqli_fetch_assoc($userquery))
	{
		$party2_id = $userqueryarray['party2_id'];
		$querystring = "UPDATE $mypal_users SET calling_status = 'idle' WHERE id = $userID";
		$userquery = mysqli_query($db,$querystring);

		$querystring = "UPDATE $mypal_users SET calling_status = 'idle' WHERE id = $party2_id";
		$userquery = mysqli_query($db,$querystring);

		$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))
		{
			$twilio_token = getToken($userID)['token'];
			$twilio_room = $room;

			return [
					"respCode" => "0068", //"0068" => "callAnswer successful",
					// "party2id" => $userqueryarray['party2_id'],
					"twilioToken" => $twilio_token,
					"twilio_room" => $twilio_room,
					"otherPartyDetails" => array(
													"userID" => $party2queryarray["id"],
													"profileData" => FormatProfile($party2queryarray["user_profile"]),
													"profileImage" => $party2queryarray["user_profile_image"],
												),
					"own_profileImage" => $userqueryarray["user_profile_image"]
					];
		}
	}
}	

function send_fcm_for_call($party1id, $party2id, $uuid, $notification_type, $twilio_room = null, $userMessage = null )
{
	global $db,$mypal_users,$sqllog,$pushmessagelog,$time;

	$server_key = get_fcm_token();

	$querystring = "SELECT * FROM $mypal_users WHERE  id = $party2id";
	writetolog($querystring,$sqllog);	
	$userquery = mysqli_query($db,$querystring);
	if($userqueryarray = mysqli_fetch_assoc($userquery))
	{
		$party2_device_token = $userqueryarray['pushMessageToken'];		
	}

	$querystring = "SELECT * FROM $mypal_users WHERE  id = $party1id";
	writetolog($querystring,$sqllog);	
	$userquery = mysqli_query($db,$querystring);
	if($userqueryarray = mysqli_fetch_assoc($userquery))
	{
		$party1_user_profile_image = $userqueryarray['user_profile_image'];
		/*
		{"nickname":"B-user","age":"44","gender":"female","location":"Colombo","lat":"100.00","lon":"50.50","aboutMe":"Hello, ths is about me"}
		*/
		$party1_user_profile_array = json_decode($userqueryarray['user_profile'], true);
		$party1_user_profile_string = $party1_user_profile_array['nickname'].','.$party1_user_profile_array['gender'].','.$party1_user_profile_array['age'].','.$party1_user_profile_array['location'];
	}


	$json_data = [
				'message' => [
					'token' => $party2_device_token,
					'data' => [
						'type' => $notification_type,
						'callId' => $uuid,
						// 'body' => 'this is the body',
						// 'message' => $body,
						// 'body' => $body,
						// 'fromUserId' => $otherPartyDetails['userID'],
						'fromUserId' => $party1id,
						'twilio_room' => $twilio_room,
						'userMessage' =>  $userMessage,
						'profilestring' => $party1_user_profile_string,
						'profileImage' => $party1_user_profile_image

						// "sdp" => $sdp
					],
					// 'notification' => [
					// 	'title' => 'Incoming Mingle Call Title',
					// 	'body' => 'Incoming Mingle Call Body',
					// 	// 'icon'  => 'ic_mingle_push'
					// ],
					'android' => [
						'priority' => 'high',
						// 'notification' => [
						// 	'icon'        => 'ic_mingle_push',
						// 	// 'click_action' => 'OPEN_CHAT'
						// 	// 'click_action' => $messageType
						// ]
						]
					]
			];

	
	$data = json_encode($json_data, JSON_UNESCAPED_UNICODE);

	writetolog("Call Invite PushMessage Request >> " . $notification_type ."|". $party1id ."=>". $party2id ."|".$party2_device_token."|".$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("Call Invite PushMessage Response << ".curl_error($ch),$pushmessagelog);
    }
    curl_close($ch);
    writetolog("Call Invite Push Message Response << " . $notification_type . "|" . $party1id ."=>". $party2id ."|". $result,$pushmessagelog);
    return $result;
}

function generate_uuid_v4(): string
{
    // Generate 16 bytes (128 bits) of random data
    $data = random_bytes(16);

    // Set the version (4) and variant (DCE security) fields
    // The version field is the four most significant bits of the 7th byte
    $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
    // The variant field is the two most significant bits of the 9th byte
    $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set variant to 10

    // Format the bytes into the standard UUID string: 8-4-4-4-12
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
?>
