<?php header('Access-Control-Allow-Origin: *'); ?>
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
error_reporting(0);
global $LANG;
global $configverssion_id;
global $configapp_version;
global $server;
$userID = getUser();
$resellerID = userData($userID,'reseller');
global $userID;
global $resellerID;

define('TIMEOUT_MINUTES', 60);
$timeout = (TIMEOUT_MINUTES == 0 ? 0 : time() + TIMEOUT_MINUTES * 1200);
global $timeout;	

$ip = getUserIP();
if(forbiddenIP($ip,0)) {
	echo '{"request": "auth","status": "error","message": "API Access Denied"}'; die();
}

global $hooks; 
$hooks->do_action('OnAPICall');

if(isset($_REQUEST['apikey'])) {
  	$apikey = mysqli_real_escape_string($server,$_REQUEST['apikey']);
  	$apitoken = mysqli_real_escape_string($server,$_REQUEST['apitoken']);
	if(empty($apikey) || empty($apitoken)) {
		echo '{"request": "auth","status": "error","message": "Invalid API Authentication"}'; die();
	}
	$query="SELECT * FROM users WHERE api_key = '$apikey' AND api_token = '$apitoken'"; 
	$result = mysqli_query($server,$query);  
	$row = mysqli_fetch_assoc($result); 
	$num = mysqli_num_rows($result);
	if($num < 1) {
		echo '{"request": "auth","status": "error","message": "Invalid API Credentails"}'; die();
	}
	$email_verified = $row['email_verified'];
	$status = $row['status'];
	if($status < 1) {
		echo '{"request": "auth","status": "error","message": "Account Currently Suspended"}'; die();
	}	
	if($email_verified != 0) {
		echo '{"request": "auth","status": "error","message": "Email Not Verified"}'; die();
	}	
	$userID = $user = $row['id'];
	$whitelistedip = v3updates20200401_GETLISTIP($userID);
	if(!empty($whitelistedip)) {
		$whitelistedipArr = explode(',',$whitelistedip);
		if (!in_array($ip, $whitelistedipArr)) {
		  echo '{"request": "auth","status": "error","message": "IP Address Not White-Listed"}'; die();
		} 
	}
}

if(isset($_REQUEST['adminapikey'])) {
  	$adminapikey = mysqli_real_escape_string($server,$_REQUEST['adminapikey']);
  	$adminapitoken = mysqli_real_escape_string($server,$_REQUEST['adminapitoken']);
	if(empty($adminapikey) || empty($adminapitoken)) {
		echo '{"request": "auth","status": "error","message": "Invalid Admin API Authentication"}'; die();
	}
	$query="SELECT * FROM users WHERE role_id = 1 AND api_key = '$adminapikey' AND api_token = '$adminapitoken'"; 
	$result = mysqli_query($server,$query);  
	$row = mysqli_fetch_assoc($result); 
	$num = mysqli_num_rows($result);
	if($num < 1) {
		echo '{"request": "auth","status": "error","message": "Invalid Admin API Credentails"}'; die();
	}
	$userID = $row['id'];
	$whitelistedip = v3updates20200401_GETLISTIP($userID);
	if(!empty($whitelistedip)) {
		$whitelistedipArr = explode(',',$whitelistedip);
		if (!in_array($ip, $whitelistedipArr)) {
		  echo '{"request": "auth","status": "error","message": "IP Address Not White-Listed"}'; die();
		} 
	}
}

if(isset($_REQUEST['sendsms']) ||isset($_REQUEST['balance']) || isset($_REQUEST['getinbox']) || isset($_REQUEST['groupstatus'])) {
	if(!isset($_REQUEST['apikey'])) {
		echo '{"request": "auth","status": "error","message": "Invalid API Authentication"}'; die();
	}
}
	
//User authentication API
if(isset($_REQUEST['auth'])) {
	if(empty($_REQUEST['adminapikey'])) {
		echo '{"request": "auth","status": "error","message": "Invalid Admin API Credentails"}'; die();
	}
	if(empty($_REQUEST['adminapitoken'])) {
		echo '{"request": "auth","status": "error","message": "Invalid Admin API Credentails"}'; die();
	}
  	$adminapikey = mysqli_real_escape_string($server,$_REQUEST['adminapikey']);
  	$adminapitoken = mysqli_real_escape_string($server,$_REQUEST['adminapitoken']);
	$query="SELECT * FROM users WHERE role_id = 1 AND api_key = '$adminapikey' AND api_token = '$adminapitoken'"; 
	$result = mysqli_query($server,$query);  
	$row = mysqli_fetch_assoc($result); 
	$num = mysqli_num_rows($result);
	if($num < 1) {
		echo '{"request": "auth","status": "error","message": "Invalid Admin API Credentails"}'; die();
	}
	
	$login = mysqli_real_escape_string($server,$_REQUEST['username']);
  	$password = mysqli_real_escape_string($server,$_REQUEST['password']);
  	$query="SELECT * FROM users WHERE email = '$login'"; 
	$result = mysqli_query($server,$query);  
	$row = mysqli_fetch_assoc($result); 
	$num = mysqli_num_rows($result);
	if($num < 1) {
    	echo '{"request": "auth","status": "error","message": "User Not Found"}'; die();
	} else {
		$pwsalt = explode( ":",$row["password"]);	
		$pass2 = $row["password"];
		$tracking = $row['tracking'];
		$status = $row['status'];
		if($status < 1) {
			echo '{"request": "auth","status": "error","message": "User Account Is Suspended"}'; die();
		}	
		if(md5($password . $pwsalt[1]) != $pwsalt[0] && md5($password) != $row["password"]) {	
		  echo '{"request": "auth","status": "error","message": "Password Is Incorrect"}'; die();
		} else {
			$query="SELECT * FROM users WHERE email = '$login'"; 
			$result = mysqli_query($server,$query);  
			$row = mysqli_fetch_assoc($result); 
			$user_id = $row['id'];
			$role = $row['role_id'];
			$last_login = $row['last_login'];
			$_SESSION['last_login'] = $last_login;
			$_SESSION['SendroidUltimateUser'] = $user_id;
			setcookie("SendroidUltimateUser", $user_id, $timeout, '/'); 
			
			$day = time();
			logEvent($user_id,'Logged into '.getSetting('businessName').' via API');
			mysqli_query($server, "UPDATE  `users` SET  `last_login` =  '$day' WHERE `id` ='$user_id'");
			$ip = getUserIP();
			mysqli_query($server, "UPDATE  `users` SET  `last_ip` =  '$ip' WHERE `id` ='$user_id'");
			echo '{"request": "auth","status": "success","first_name": "'.$row['first_name'].'","last_name": "'.$row['last_name'].'","email": "'.$row['email'].'","phone": "'.$row['phone'].'","apikey": "'.$row['api_key'].'","apitoken": "'.$row['api_token'].'"}'; die();
	  }
  }	
  die();
}

//=============== Register new user
if(isset($_REQUEST['createcustomer'])) { 
	foreach ($_REQUEST as $key => $value ){
		${$key} = $value = mysqli_real_escape_string($server,$value);
	}
	if(empty($_REQUEST['adminapikey'])) {
		echo '{"request": "auth","status": "error","message": "Invalid Admin API Credentails"}'; die();
	}
	if(empty($_REQUEST['adminapitoken'])) {
		echo '{"request": "auth","status": "error","message": "Invalid Admin API Credentails"}'; die();
	}
	$query="SELECT * FROM users WHERE role_id = 1 AND api_key = '$adminapikey' AND api_token = '$adminapitoken'"; 
	$result = mysqli_query($server,$query);  
	$row = mysqli_fetch_assoc($result); 
	$num = mysqli_num_rows($result);
	if($num < 1) {
		echo '{"request": "createcustomer","status": "error","message": "Invalid Admin API Credentails"}'; die();
	}
	$passwordStrong = checkPassword($password);
	if(forbiddenEmail($email,0)) {
		echo '{"request": "createcustomer","status": "error","message": "Email Address Not Allowed"}'; die();
	}
	if(empty($fisrt_name)) {
		echo '{"request": "createcustomer","status": "error","message": "First Name Not Supplied"}'; die();
	}
	if(empty($last_name)) {
		echo '{"request": "createcustomer","status": "error","message": "Last Name Not Supplied"}'; die();
	}
	if(empty($phone)) {
		echo '{"request": "createcustomer","status": "error","message": "Phone Not Supplied"}'; die();
	}
	if(!checkEmailAddress($email)) {
		echo '{"request": "createcustomer","status": "error","message": "Invalid Email Address"}'; die();
	} elseif(!empty($passwordStrong)) {
		echo '{"request": "createcustomer","status": "error","message": "'.$passwordStrong.'"}'; die();
	} else 	{
		$query = "SELECT * FROM users WHERE email = '$email'";
		$result = mysqli_query($server, $query) or die(mysqli_error($server));
		$num = mysqli_num_rows($result);	
		if($num < 1) {
		  //save info as temp user
			$_SESSION['username'] = $email;
			$salt = genRandomPassword(32);
			$crypt = getCryptedPassword($password, $salt);
			$password2 = $crypt.':'.$salt;	
			$emIl_track = time().$salt;
			$phone_track = time();
			if(getSetting('email_verify',0) < 1) { $emIl_track = 0;	}
			if(getSetting('phone_verify',0) < 1) { $phone_track = 0;	}		
			$email_track = 	$emIl_track;	
			$currency_id = getSetting('defaultCurrency'); 			
			$country_id = getSetting('defaultCountry'); 
			$reseller = 0;

			$timezone = countryTimeZone($country_id);
			$affliliate = genRandomPassword(16);
			
			 mysqli_query($server, "INSERT INTO users (`first_name`, `last_name`, `email`, `uservar`, `password`, `currency_id`, `country_id`,`phone`, `phone_verified`,`email_verified`,`timezone_id`,`role_id`,`referrer`,`affiliate_id`,`reseller`) 
				VALUES ('$first_name', '$last_name', '$email', '$password', '$password2', '$currency_id', '$country_id', '$phone','$phone_track','$email_track','$timezone','4','0','$affliliate','$reseller');") or die (mysqli_error($server));
			$user_id = mysqli_insert_id($server);	
			logEvent( mysqli_insert_id($server),"Joined ".getSetting('businessName'));		
			
			//create hook variables
			$vars = array(
						 "id"=>$user_id, 
						 "email"=>$email,
						 "password"=>$password, 
						 "phone"=>$phone,
						 "first_name"=>$first_name, 
						 "last_name"=>$last_name
						 );
			$_SESSION['EventVals'] = $vars;
			
			if($phone_track !=0) {
				sendPhoneVerify($user_id,$phone_track);	
			}
			if(getSetting('email_verify',0) > 0) { 
				$link_domain = home_base_url();
				if(!empty(getSetting('resellerDomain')))	{
					$link_domain = 'http://'.getSetting('resellerDomain');
				}
				//send verification code
				$mail = "<h2 align='center'>Verify your email address</h2>";
				$mail .= "<hr>";
				$mail .= "<p align='center'>In order to start using your ".getSetting('businessName')." account, you need to confirm your email address.</p>";
				$mail .= '<p align="center"><a href="'.home_base_url().'?vf='.$email_track.'"><button style="margin: 5px auto; border: 0; color: white; padding: 10px; background: #036" >Very Email Address</button></a></p>';
				$mail .= "<hr><p align='center'>If you did not sign up for this account, you can ignore this email and the account will be deleted.</p>";
					
				$sender = getSetting('businessName');
				$subject = "Please Verify Your Email Address";
				$verify_link = home_base_url().'?vf='.$email_track;
				//try ciustom 
				if(!empty(getSetting('newAccountVerifyEmailSubject'))) {
					$subject = getSetting('newAccountVerifyEmailSubject');
					$subject = strtr($subject, array("{name}" => $first_name.' '.$last_name, 
								"{email}" => $email,
								"{verify_link}" => $verify_link,
								"{password}" => $password,
								"{company}" => getSetting('businessName'),
								"{brand_name}" => getSetting('businessName'),
								"{url}" => $link_domain,
								"{phone}" => $phone,
								"{amount}" => 0,
								"{balance}" => 0
							));	
				}
				if(!empty(getSetting('newAccountVerifyEmail'))) {
					$mail = getSetting('newAccountVerifyEmail');
					$mail = strtr($mail, array("{name}" => $first_name.' '.$last_name, 
								"{email}" => $email,
								"{verify_link}" => $verify_link,
								"{password}" => $password,
								"{company}" => getSetting('businessName'),
								"{brand_name}" => getSetting('businessName'),
								"{url}" => $link_domain,
								"{phone}" => $phone,
								"{amount}" => 0,
								"{balance}" => 0
							));	
				}
				
				$from = getSetting('smtpUsername');
				sendEmail($from,$sender,$subject,$email,$mail);
			} else {			 
				//Just Send Welcome Email
				$link_domain = home_base_url();
				if(!empty(getSetting('resellerDomain')))	{
					$link_domain = 'http://'.getSetting('resellerDomain');
				}
				//send verification code
				$mail = "<h2 align='center'>Welcome to ".getSetting('businessName')."</h2>";
				$mail .= "<hr>";
				$mail .= "<p align='center'>Your ".getSetting('businessName')." account is ready. Here are your login account details;</p>";
				$mail .= "<p align='left'><strong>Username:</strong> ".$email."<br><strong>Password:</strong> ".$password."</p>";
				$mail .= '<p align="center"><a href="'.home_base_url().'"><button style="margin: 5px auto; border: 0; color: white; padding: 10px; background: #036" >Login to your account</button></a></p>';
				$mail .= "<hr><p align='center'>Do let us know if you did not authorize this new account creation.</p>";
				$subject = "Welcome to ".getSetting('businessName');
				
				if(!empty(getSetting('newAccountEmail'))) {
					$mail = getSetting('newAccountEmail');
					$mail = strtr($mail, array("{name}" => $first_name.' '.$last_name, 
									"{email}" => $email,
									"{password}" => $password,
									"{company}" => getSetting('businessName'),
									"{brand_name}" => getSetting('businessName'),
									"{url}" => $link_domain,
									"{phone}" => $phone,
									"{amount}" => 0,
									"{balance}" => 0
									));	
					$subject = 	getSetting('newAccountEmailSubject');				
					$subject = strtr($subject, array("{name}" => $first_name.' '.$last_name, 
									"{email}" => $email,
									"{password}" => $password,
									"{company}" => getSetting('businessName'),
									"{brand_name}" => getSetting('businessName'),
									"{url}" => $link_domain,
									"{phone}" => $phone,
									"{amount}" => 0,
									"{balance}" => 0
									));	
				}
				$sender = getSetting('businessName');
				$from = getSetting('smtpUsername');						
				sendEmail($from,$sender,$subject,$email,$mail);	
				sendWelcomeSMS($user_id);
			}
			echo '{"request": "createcustomer","status": "success","first_name": "'.$first_name.'","last_name": "'.$last_name.'","email": "'.$email.'","phone": "'.$phone.'","id": "'.$user_id.'"}'; die();
		} else {
			echo '{"request": "createcustomer","status": "error","message": "Email Already Exist"}'; die();
		}	
	}
	die();
}

function CanUseSenderIDAPI($user,$senderID,$type="") {		
	global $server;		
	$query="SELECT * FROM sender_id where sender_id = '$senderID' AND (customer_id = '$user' or resold = '$user') and status = 'approved'";
	if(!empty($type)) {
		$query="SELECT * FROM sender_id where sender_id = '' (customer_id = '$user' or resold = '$user') and status = 'approved' and type LIKE '%$type%'";
	}
    $result = mysqli_query($server,$query);
    $funbd = mysqli_num_rows($result);
	if($funbd > 0) {
		return true;
	}
	return false;
}

if(isset($_REQUEST['sendsms'])) {
	$type = 'sms';
	if(!isset($_REQUEST['apikey'])) {
		echo '{"request": "auth","status": "error","message": "Invalid API Authentication"}'; die();
	}
	if($userID < 1) {
		echo '{"request": "auth","status": "error","message": "Invalid User Credentails"}'; die();
	}
	foreach ($_REQUEST as $key => $value ){
		${$key} = $value = mysqli_real_escape_string($server,$value);
	}
	$to = correctRecipient($to);
	
	$type = strtolower($type);
	
	//check recipients
	$tempTo = $to;
	$tempTo = correctRecipient($tempTo);
	
	$chars = countCharacters($text);
	$numbers = $to_count = $numbers = countRecipient($tempTo);
	$pages = countPage($text,$type,$duration);
	$cost = smsCost($tempTo,$type,$country,$pages,$userID);
	
	$now = date('Y-m-d H:i:s', time());
	$sent_from = 'API';
	$gateway_id = 0;
	if(isset($_REQUEST['route']) && $_REQUEST['route']>0) {
		$gateway_id = $route;
		$gateway_mtype = smsGatewayData($gateway_id,'type'); 
		if($gateway_mtype != $type)	{
			echo '{"request": "sendsms","status": "error","message": "Invalid Route Selected"}'; die();		
		}
	}
	$ip = getUserIP();
	$notice = '';
	
	if(empty($text) && ($type=='sms' || $type=='unicode')) { echo '{"request": "sendsms","status": "error","message": "Message Field Is Empty"}'; die();	}
	if(empty($from) && $type != 'whatsapp') { echo '{"request": "sendsms","status": "error","message": "No Valid Sender ID Supplied"}'; die();	}
	if(getSetting('senderIDLimit',0)>0 && strlen($from) > getSetting('senderIDLimit',0)) { echo '{"request": "sendsms","status": "error","message": "Sender ID Can Not Be Above '.getSetting('senderIDLimit',0).' Characters"}'; die();	}
	$forbiden_id = forbiddenSenderID($from,$userID);
	if($forbiden_id && (!isAdmin($userID))) { echo '{"request": "sendsms","status": "error","message": "Sender ID Not Allowed"}'; die();}
	$forbiden_word = forbiddenWord($text,$userID);
	if($forbiden_word && (!isAdmin($userID))) { echo '{"request": "sendsms","status": "error","message": "Message Contains Forbidden Words"}'; die();}
	if($numbers < 1) { echo '{"request": "sendsms","status": "error","message": "No Valid Recipients Supplied"}'; die(); }
	if((userWalletBalance($userID) <= 0) && (!isAdmin($userID)) ) { echo '{"request": "sendsms","status": "error","message": "Insufficient Balance"}'; die();}
	//set admin user
	if(isAdmin($userID)) { 
	$userID = 0;
	$user_time = date('Y-m-d H:i:s',time());
	} else {
		if(getSetting('dynamicSenderEnabled',0)<1){
			if(!CanUseSenderIDAPI($userID,$from)) {
				echo '{"request": "sendsms","status": "error","message": "Sender ID Not Approved"}'; die();
			}
		}
		$user_time = getUserTime($userID);
	}
	$vars = array(
					 "sender_id"=>$sender_id, 
					 "to"=>$tempTo,
					 "message"=>$text, 
					 "customer_id"=>$userID,
					 "type"=>$type, 
					 "media"=>$media_file
					 );
	$_SESSION['EventVals'] = $vars;
		
	global $hooks; $hooks->do_action('BeforeSendMessage');
	if(strtotime($scheduledate) > strtotime($user_time)) {
		$schedule_date = date('Y-m-d H:i:s',strtotime($scheduledate));
		//save to DB for scheduling
		mysqli_query($server, "INSERT INTO scheduledmessages (`message`,`recipients`, `customer_id`, `type`, `media`, `date`, `sender_id`, `phonebook_id`, `marketinglist_id`, `duration`, `file`,`country`,`status`,`schedule_date`, `gateway_id`, `to_count`, `language`) VALUES ('$text','$tempTo', '$userID', '$type', '$file','$now','$from','0','0', '$duration', '','0','queued', '$schedule_date', '0', '$to_count', '$language');") or die(mysqli_error($server));
		logEvent($userID,'Scheduled a message for '.$schedule_date);
		global $hooks; $hooks->do_action('AfterSendMessage');
		echo '{"request": "sendsms","status": "queued","group_id": "0","date": "'.date('Y-m-d H:i:s').'"}'; die();	
	}
	//save to DB for queuing
	mysqli_query($server, "INSERT INTO sentmessages (`message`,`recipients`, `customer_id`, `type`, `media`, `date`, `sender_id`, `phonebook_id`, `marketinglist_id`, `duration`, `file`,`country`,`status`,`sent_from`, `gateway_id`, `ip`, `notice`, `to_count`, `language`) VALUES ('$text','$tempTo', '$userID', '$type', '$file', '$now', '$from', '0','0', '$duration', '','0','queued', '$sent_from', '0', '$ip', '', '$to_count', '$language');") or die(mysqli_error($server));
	$group_id = mysqli_insert_id($server);	
	
	$sendRealTime = getSetting('sendRealTime',0);
	if($to_count <= $sendRealTime) {
		$query="SELECT * FROM sentmessages WHERE status LIKE '%queued%' AND id = '$group_id'";
		$result = mysqli_query($server,$query) or die(mysqli_error($server));
		while($rows = mysqli_fetch_assoc($result)) { 
			mysqli_query($server, "UPDATE sentmessages SET `status` = 'processing' WHERE `id` = '".$rows['id']."'");
			mysqli_query($server, "UPDATE sentmessages SET `sent_on` = '".date('Y-m-d H:i:s')."' WHERE `id` = '".$rows['id']."'");
			$to = $rows['recipients'];
			$countryCode = countryPhoneCode($rows['country']);
			if(!empty($rows['file'])) {
				$to .= ','.getFileContacts($rows['file']);
			}
			if(!empty($rows['phonebook_id'])) {
				$addressbook = explode(',', $rows['phonebook_id']);
				foreach ($addressbook as $list){
					$to .= ','.getContacts($list,'phonebook');	
				}
			}
			$tos = explode(',', $to);
			foreach($tos as $recipient){
				if(!empty($recipient)) {
					$recipient = str_replace('+', '', $recipient);
					$recipient = alterPhone($recipient,$countryCode);
					$datetime = date('Y-m-d H:i:s');
					$now = time();
					$country = getDestinationCountry($recipient);
					$gateway_id = getDestinationRoute($rows['type'],$recipient,$rows['customer_id'],$rows['gateway_id']);
					//just incase...
					$checksum = $rows['id'].$rows['type'].$rows['customer_id'];				
					$integrity_checksum = 	$rows['id'].$recipient;			
					mysqli_query($server, "INSERT INTO messagedetails (`message_id`, `message`,`recipient`, `customer_id`, `type`, `media`, `date`, `sender_id`, `marketinglist_id`, `duration`, `datetime`,`country_id`, `operator`, `status`, `gateway_id`, `notice`, `cost`, `language`, `integrity_checksum`)  VALUES ('$rows[id]', '".mysqli_real_escape_string($server,$rows['message'])."','$recipient', '$rows[customer_id]', '$rows[type]', '$rows[media]', '$now', '".mysqli_real_escape_string($server,$rows['sender_id'])."', '0', '$rows[duration]', '$datetime','$country', 'Unknown', 'queued',  '$gateway_id', '', '0', '$rows[language]', '$integrity_checksum');"); $error = mysqli_error($server);
				}
			}
			if(!empty($rows['marketinglist_id'])) {
				$to='';
				$marketinglist_id = explode(',', $rows['marketinglist_id']);
				foreach ($marketinglist_id as $list){
					$to .= ','.getContacts($list,'marketing');	
				}
				$tos = explode(',', $to);
				foreach($tos as $recipient){
					if(!empty($recipient)) {
						$recipient = str_replace('+', '', $recipient);
						$recipient = alterPhone($recipient,$countryCode);
						$datetime = date('Y-m-d H:i:s');
						$now = time();
						$country = getDestinationCountry($recipient);
						$gateway_id = getDestinationRoute($rows['type'],$recipient,$rows['customer_id'],$rows['gateway_id']);
						//just incase...
						$checksum = $rows['id'].$rows['type'].$rows['customer_id'];							
						$integrity_checksum = 	$rows['id'].$recipient;			
						mysqli_query($server, "INSERT INTO messagedetails (`message_id`, `message`,`recipient`, `customer_id`, `type`, `media`, `date`, `sender_id`, `marketinglist_id`, `duration`, `datetime`,`country_id`, `operator`, `status`, `gateway_id`, `notice`, `cost`, `language`, `integrity_checksum`) VALUES ('$rows[id]', '".mysqli_real_escape_string($server,$rows['message'])."','$recipient', '$rows[customer_id]', '$rows[type]', '$rows[media]', '$now', '".mysqli_real_escape_string($server,$rows['sender_id'])."', '$list', '$rows[idduration]', '$datetime','$country', 'Unknown', 'queued',  '$gateway_id', '', '0', '$rows[language]', '$integrity_checksum');"); $error = mysqli_error($server);
					}
				}
			} 
			mysqli_query($server, "UPDATE sentmessages SET `status` = 'completed' WHERE `id` = '".$rows['id']."'");
		} //end of this message 
		
		$query="SELECT * FROM messagedetails WHERE status LIKE '%queued%' AND message_id = '".$group_id."'";
		$result = mysqli_query($server,$query) or die(mysqli_error($server));
		while($rows = mysqli_fetch_assoc($result)) { 
			//create hook variables
				$vars = array(
							 "id"=>$rows['id'], 
							 "sender_id"=>$rows['sender_id'], 
							 "to"=>$rows['recipient'],
							 "gateway_id"=>$rows['gateway_id'],
							 "message"=>$rows['message'], 
							 "customer_id"=>$rows['customer_id'],
							 "type"=>$rows['type'], 
							 "media"=>$rows['media']
							 );
				$_SESSION['EventVals'] = $vars;
			global $hooks; $hooks->do_action('BeforeProcessMessage');
			sendSMS($rows['id']);
			$hooks->do_action('AfterMessageProcess');
		} //end actuall process
	} // End of real-tieme stuffs
	logEvent($userID,'Initiated an '.$type.' message to '.$numbers.' recipients');
	global $hooks; $hooks->do_action('AfterSendMessage');	
	echo '{"request": "sendsms","status": "queued","group_id": "'.$group_id.'","date": "'.date('Y-m-d H:i:s').'"}'; die();	
}

if(isset($_REQUEST['balance'])) {
	if(!isset($_REQUEST['apikey'])) {
		echo '{"request": "auth","status": "error","message": "Invalid API Authentication"}'; die();
	}
	$balance = userWalletBalance($userID);
	echo '{"balance":"'.$balance.'"}'; die();
}

if(isset($_REQUEST['getinbox'])) {
	if(!isset($_REQUEST['apikey'])) {
		echo '{"request": "auth","status": "error","message": "Invalid API Authentication"}'; die();
	}
	$list = 'unread';
	if(isset($_REQUEST['list']))
	$list = mysqli_real_escape_string($server,$_REQUEST['list']);
	$added = " AND is_read = 0";
	if($list=='all') $added = "";
	$query="SELECT * FROM inbox WHERE customer_id = '$userID' $added";
	if(isAdmin($userID)) { 
		$query="SELECT * FROM inbox WHERE 1 $added";
	}
	$result = mysqli_query($server,$query);
	$xyz = mysqli_num_rows($result);
	$i = 1;
	if($xyz < 1) {
		echo '{"request":"getinbox","status":"error","message":"No Messages Found"}'; die();	
	}
	echo '{"request": "getinbox","status":"success","inbox":[';
	while ($rows = mysqli_fetch_assoc($result)) {
		echo '{"id": "'.$rows['id'].'","from": "'.$rows['sender'].'","to": "'.$rows['recipient'].'","message": "'.$rows['message'].'","date": "'.$rows['date'].'"}';
		if ($i < $xyz) echo ',';
		$i++;
	}
	echo ']}'; die();
}

if(isset($_REQUEST['groupstatus'])) {
	if(!isset($_REQUEST['apikey'])) {
		echo '{"request": "auth","status": "error","message": "Invalid API Authentication"}'; die();
	}
	$groupid = mysqli_real_escape_string($server,$_REQUEST['groupid']);
	$query="SELECT * FROM sentmessages WHERE id = '$groupid' AND customer_id = '$userID' ";

	if(isAdmin($userID)) { 
		$query="SELECT * FROM sentmessages WHERE id = '$groupid'";
	}
	$result = mysqli_query($server,$query);
	$xyz = mysqli_num_rows($result);
	if($xyz < 1) {
		echo '{"request":"groupstatus","status":"error","message":"Message Not Found"}'; die();	
	}
	$row = mysqli_fetch_assoc($result); 
	echo '{"request": "groupstatus","status":"success","group_id":"'.$row['id'].'","group_status": "'.$row['status'].'","recipients":[';
	$query2="SELECT * FROM messagedetails WHERE message_id = '$groupid'";
	$result2 = mysqli_query($server,$query2);
	$number = mysqli_num_rows($result2);
	$i = 1;
	while ($rows = mysqli_fetch_assoc($result2)) {
		$to = $rows['recipient'];
		$status_1 = ucfirst($rows['status']);
		if(	strtolower($rows['status'])=='sent' && strtolower($rows['dlr'])!='sent') {
			$status_1 = ucfirst($rows['dlr']);
		}

		if( ($rows['marketinglist_id']>0) && (marketinglistData($rows['marketinglist_id'],'customer_id') != $userID) ) {
			if(!isAdmin($userID)) $to = substr($rows['recipient'],0,-5) . '*****'; 
		}
		echo '{"id": "'.$rows['id'].'","to": "'.$to.'","status": "'.$status_1.'"}';
		if ($i < $number) echo ',';
		$i++;
	}
	echo '],"date":"'.$row['date'].'"}'; die();
}

echo '{"request": "unknown","status":"error","message":"Invalid API Request"}'; die();

global $hooks; 
$hooks->do_action('AfterAPICall');