<?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;	
//====== Default response
$errors         = array();     
$data           = array();     
$data['errors']  = $LANG['Invalid API request'];
$data['success'] = false;
$data['message'] = '';

if(!isset($_SESSION['request_token'])) {
	buildJSONResponse($data['errors'],$data['success'],$data['message']);
}

$ip = getUserIP();
if(forbiddenIP($ip,0)) {
	buildJSONResponse('Your IP address has been banned',false,'');
}

//============ Check if user exist
if(isset($_REQUEST['checkUser'])) { 
	$email = mysqli_real_escape_string($server,$_REQUEST['checkUser']);	
	$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) {
		buildJSONResponse('',true,0); die();
	} else {
		buildJSONResponse($LANG['Email already registered by another user'],false,''); die();
	}
	die();
}

//========User authentication API
if(isset($_REQUEST['access_login'])) {
  	$login = mysqli_real_escape_string($server,$_REQUEST['access_login']);
  	$password = mysqli_real_escape_string($server,$_REQUEST['access_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) {
    	$message = $LANG['Your login detail is not associated with any user here. Please check your details']; 
		buildJSONResponse($message,false,0); die();
	} else {
		$pwsalt = explode( ":",$row["password"]);	
		$pass2 = $row["password"];
		$tracking = $row['tracking'];
		$status = $row['status'];
		if($status < 1) {
			$message = $LANG['Your account is currently suspended. Please contact us for more information and for assistance.']; 
			buildJSONResponse($message,false,0);  die();
		}	
		if(md5($password . $pwsalt[1]) != $pwsalt[0] && md5($password) != $row["password"]) {	
		   $message = $LANG['Your email or password is incorrect.']; $color = "red";
		   buildJSONResponse($message,false,0); 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, '/'); 
			
			//create hook variables
			$vars = array(
						 "id"=>$row['id'], 
						 "email"=>$row['email'],
						 "first_name"=>$row['first_name'], 
						 "last_name"=>$row['last_name']
						 );
			$_SESSION['EventVals'] = $vars;
			$day = time();
			logEvent($user_id,'Logged into '.getSetting('businessName'));
			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'");
			global $hooks; $hooks->do_action('UserLogin');
			buildJSONResponse('',true,$user_id); die();
	  }
  }	
  die();
}


//=======Reset password
if(isset($_REQUEST['userEmail'])) {
	$email2 = mysqli_real_escape_string($server,$_REQUEST['userEmail']);	
	$query = "SELECT * FROM users WHERE email = '$email2'";
	$result = mysqli_query($server, $query);
	$num = mysqli_num_rows($result);	
	if($num < 1) {
		buildJSONResponse($LANG['This email is not associated with any user here. Please check your email'],false,'');
	} else {
		$password = rand(199999, 999999);
		if(DEMO_MODE) {
			$password = 12345678;
		}
		$salt = genRandomPassword(32);
		$crypt = getCryptedPassword($password, $salt);
		$password2 = $crypt.':'.$salt;
		mysqli_query($server,"UPDATE  `users` SET `password` =  '$password2'	WHERE  `email` = '$email2';");
							
		$query="SELECT * FROM users WHERE email = '$email2'"; 
		$result = mysqli_query($server, $query);  
		$row = mysqli_fetch_assoc($result); 
		$name = $row['first_name'].' '.$row['last_name'];
		$email = $row['email'];
		$phone = $row['phone'];
			//create hook variables
			$vars = array(
						 "id"=>$row['id'], 
						 "email"=>$row['email'],
						 "password"=>$password, 
						 "first_name"=>$row['first_name'], 
						 "last_name"=>$row['last_name']
						 );
			$_SESSION['EventVals'] = $vars;
			
		$mail = 'Dear '.$name.'<br><br>Your '.getSetting('businessName').' account password has been recovered.<br>Your new password is '.$password.'.<br>Do let us know at once if you have not authorized or initiated this password change.<br><hr><br>Message sent from '.getSetting('businessName').'';
		$subject = 'Your New Account Password';
		if(!empty(getSetting('newPasswordEmail'))) {
				$mail = getSetting('newPasswordEmail');
				$mail = strtr($mail, array("{name}" => $name, 
								"{email}" => $email,
								"{password}" => $password,
								"{company}" => getSetting('businessName'),
								"{brand_name}" => getSetting('businessName'),
								"{url}" => $link_domain,
								"{phone}" => $phone,
								"{amount}" => 0,
								"{balance}" => 0
								));	
				$subject = 	getSetting('newPasswordEmailSubject');				
				$subject = strtr($subject, array("{name}" => $name, 
								"{email}" => $email,
								"{password}" => $password,
								"{company}" => getSetting('businessName'),
								"{brand_name}" => getSetting('businessName'),
								"{url}" => $link_domain,
								"{phone}" => $phone,
								"{amount}" => 0,
								"{balance}" => 0
								));	
		}
		
		sendEmail(getSetting('smtpUsername'),getSetting('businessName').'',$subject,$email,$mail);
		
		$user_id = $row['id'];
		sendNewpasswordSMS($user_id,$password);
		logEvent($user_id,'Requested a password reset');	
		global $hooks; $hooks->do_action('PasswordChange');
		buildJSONResponse('',true,$LANG['A new password has been sent to your registered email address']); die();
	}
	die();
}

//=============== Register new user
if(isset($_REQUEST['join'])) { 
	foreach ($_REQUEST as $key => $value ){
		${$key} = $value = mysqli_real_escape_string($server,$value);
	}
	$passwordStrong = checkPassword($password);
	if(isset($_SESSION['referrer']) && !empty($_SESSION['referrer'])) {
		$referer_id = mysqli_real_escape_string($server,$_SESSION['referrer']);	
		$referal = getRefererUserID($referer_id);
	}
	if(forbiddenEmail($email,0)) {
		buildJSONResponse('Your email address is not allowed on our website',false,'');
	}
	if(!checkEmailAddress($email)) {
		$message = $LANG['Invalid email address format'];
		buildJSONResponse($message,false,0); die();
	}else if($password != $password2) {
		$message = $LANG['Your two password fields didn\'t match'];
		buildJSONResponse($message,false,0); die();
	} elseif(!empty($passwordStrong)) {
		$message = $LANG[$passwordStrong];
		buildJSONResponse($message,false,0); 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;	
			$email_track = time().$salt;
			$phone_track = time();
			if(getSetting('email_verify',0) < 1) { $email_track = 0;	}
			if(getSetting('phone_verify',0) < 1) { $phone_track = 0;	}			
			$currency_id = getSetting('defaultCurrency'); 
			
			$reseller = resellerByDomain();
			if(!isAdmin($reseller) || ($reseller > 0)) {
				$currency_id = userData($user,'currency_id'); 
			} 
			$timezone = countryTimeZone($country_id);
			$affliliate = genRandomPassword(16);
			
			 mysqli_query($server, "INSERT INTO users (`first_name`, `last_name`, `email`, `password`, `currency_id`, `country_id`,`phone`, `phone_verified`,`email_verified`,`timezone_id`,`role_id`,`referrer`,`affiliate_id`,`reseller`) 
				VALUES ('$first_name', '$last_name', '$email', '$password2', '$currency_id', '$country_id', '$phone','$phone_track','$email_track','$timezone','4','$referal','$affliliate','$reseller');") or die (mysqli_error($server));
			$user_id = mysqli_insert_id($server);	
			logEvent( mysqli_insert_id($server),"Joined ".getSetting('businessName'));		
			mysqli_query($server, "UPDATE  `users` SET  `last_login` =  '".time()."' WHERE `id` ='$user_id'");
			
			//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) {
				//send verify sms 
				sendPhoneVerify($user_id,$phone_track);	
			}
			if(getSetting('email_verify',0) > 0) { 
				//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";
				$from = getSetting('smtpUsername');
				sendEmail($from,$sender,$subject,$email,$mail);
			}
			 
			$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',$userID);
			$from = getSetting('smtpUsername',$userID);						
			sendEmail($from,$sender,$subject,$email,$mail);	
			sendWelcomeSMS($user_id);
			buildJSONResponse('',true,$user_id); die();
			global $hooks; $hooks->do_action('CustomerCreate');
		} else {
			buildJSONResponse($LANG['A user already exisit with the email address you entered'],false,0); die();
		}	
	}
	die();
}


//============ Login with Facebook
if(isset($_REQUEST['facebook_auth'])) {
	if($_REQUEST['facebook_auth'] != '011') {
		buildJSONResponse($LANG['Invalid request method'],false,0);	die();
	} else {
		$userData = json_decode($_POST['userData']);
		if(!empty($userData)){
			$query = "SELECT * FROM users WHERE facebook_id = '".$userData->id."'";
			$result = mysqli_query($server, $query) or die(mysqli_error($server));
			$num = mysqli_num_rows($result);
			if($num > 0) {
				$row = mysqli_fetch_assoc($result); 
				mysqli_query($server,"UPDATE users SET first_name = '".$userData->first_name."', last_name = '".$userData->last_name."', email = '".$userData->email."' WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$userData->id."'");	
				$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, '/'); 
				
				//create hook variables
				$vars = array(
							 "id"=>$user_id, 
							 "email"=>$row['email'],
							 "password"=>'', 
							 "phone"=>$row['phone'],
							 "first_name"=>$row['first_name'], 
							 "last_name"=>$row['last_name']
							 );
				$_SESSION['EventVals'] = $vars;
				
				$day = time();
				logEvent($user_id,'Logged into '.getSetting('businessName'));
				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'");
				global $hooks; $hooks->do_action('UserLogin');
				buildJSONResponse('',true,$user_id); die();
			} else {
				if(isset($_SESSION['referrer']) && !empty($_SESSION['referrer'])) {
					$referer_id = mysqli_real_escape_string($server,$_SESSION['referrer']);	
					$referal = getRefererUserID($referer_id);
				}
				$_SESSION['username'] = $email;
				$password = genRandomPassword(8);
				$salt = genRandomPassword(32);
				$crypt = getCryptedPassword($password, $salt);
				$password2 = $crypt.':'.$salt;	
				$emIl_track = 0;
				$phone_track = time().$salt;
				if(getSetting('phone_verify') < 1) { $phone_track = 0;	}			
				$country_id = getSetting('defaultCountry');
				$currency_id = getSetting('defaultCurrency'); 
				$timezone = countryTimeZone($country_id);
				$affliliate = genRandomPassword(16);
				
				$reseller = resellerByDomain();
				if(!isAdmin($reseller) || ($reseller > 0)) {
					$currency_id = userData($user,'currency_id'); 
					$country_id = userData($user,'country_id'); 
				} 
				
				mysqli_query($server, "INSERT INTO users (`first_name`, `last_name`, `email`, `password`, `currency_id`, `country_id`,`phone`,  `phone_verified`, `email_verified`, `timezone_id`, `role_id`,`facebook_id`,`last_login`,`referrer`,`affiliate_id`, `reseller`) 
					VALUES ('".$userData->first_name."', '".$userData->last_name."', '".$userData->email."', '$password2', '$currency_id', '$country_id', '','$phone_track','$email_track','$timezone','4','".$userData->id."','".time()."','$referal','$affliliate', '$reseller');") or die (mysqli_error($server));
				$user_id = mysqli_insert_id($server);	
				logEvent( mysqli_insert_id($server),"Joined ".getSetting('businessName').' via facebook');		
				
				$mail = "<h2 align='center'>Welcome to ".getSetting('businessName')."!</h2>";
				$mail .= "<hr>";
				$mail .= "<p align='center'>You have just signed-up at ".getSetting('businessName')." with your facebook account.</p>";
				$mail .= "<p align='center'>You can now login to your account any time by simply clicking on the <b>Sign-in With Facebook</b> button at our login page.</p>";
				$mail .= "<p align='center'>We have also created a username and password for you just incase you prefer to use it. Below are the details;</p>";
				$mail .= "<p align='center'>Username: <b>".$userData->email."</b><br>Password: <b>".$password."</b></p>";
				$mail .= "<hr><p align='center'>Do let us know at once if you did not sign up for this account.</p>";
				$subject = "Welcome to ".getSetting('businessName');

				if(!empty(getSetting('newAccountEmail'))) {
					$mail = getSetting('newAccountEmail');
					$mail = strtr($mail, array("{name}" => $userData->first_name.' '.$userData->last_name, 
									"{email}" => $userData->email,
									"{password}" => $password,
									"{company}" => getSetting('businessName'),
									"{brand_name}" => getSetting('businessName'),
									"{url}" => $link_domain,
									"{phone}" => '',
									"{amount}" => 0,
									"{balance}" => 0
									));	
					$subject = 	getSetting('newAccountEmailSubject',$userID);				
					$subject = strtr($subject, array("{name}" => $userData->first_name.' '.$userData->last_name, 
									"{email}" => $userData->email,
									"{password}" => $password,
									"{company}" => getSetting('businessName'),
									"{brand_name}" => getSetting('businessName'),
									"{url}" => $link_domain,
									"{phone}" => '',
									"{amount}" => 0,
									"{balance}" => 0
									));	
				}	
				
				$sender = getSetting('businessName');
				$from = getSetting('smtpUsername');	
				sendEmail($from,$sender,$subject,$userData->email,$mail);
				
				$query = "SELECT * FROM users WHERE facebook_id = '".$userData->id."'";
				$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, '/'); 
				
				//create hook variables
				$vars = array(
							 "id"=>$user_id, 
							 "email"=>$row['email'],
							 "password"=>$password, 
							 "phone"=>$row['phone'],
							 "first_name"=>$row['first_name'], 
							 "last_name"=>$row['last_name']
							 );
				$_SESSION['EventVals'] = $vars;
				
				$day = time();
				logEvent($user_id,'Logged into via facebook');
				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'");
				global $hooks; $hooks->do_action('CustomerCreate');
				buildJSONResponse('',true,$user_id); die();
			}
		}
	}
	die();
}

if(isset($_REQUEST['cancel_inv'])) {
	$invoice = mysqli_real_escape_string($server,$_REQUEST['cancel_inv']);
	$userID = mysqli_real_escape_string($server,$_REQUEST['user']);
	$query = "SELECT * FROM transactions WHERE customer_id = '$userID' AND `transaction_reference` = '$invoice'";
	$result = mysqli_query($server, $query) or die(mysqli_error($server));
	$num = mysqli_num_rows($result);
	if($num < 1) {
		echo $LANG['Invalid Transaction Reference'].':0'; die();
	}
	mysqli_query($server, "UPDATE `transactions` SET `status` =  'canceled' WHERE `transaction_reference` = '$invoice'");
		echo 'success:0'; die();
}

if(isset($_REQUEST['voucher_pin'])) {
	$pin = mysqli_real_escape_string($server,$_REQUEST['voucher_pin']);
	$query = "SELECT * FROM vouchers WHERE customer_id = '".userData($userID,'reseller')."' AND `pin` = '$pin'";
	$result = mysqli_query($server, $query) or die(mysqli_error($server));
	$num = mysqli_num_rows($result);
	if($num < 1) {
		echo $LANG['Invalid Voucher PIN'].':0:0'; die();
	}
	$row = mysqli_fetch_assoc($result); 
	if($row['used'] > 0) {
		echo $LANG['This Voucher PIN has already been used'].':0:0'; die();
	}
	echo 'success:'.$row['credits']*userExchangeRate(getUser()).':'.$row['cost']*userExchangeRate(getUser()); die();
}
if(isset($_REQUEST['voucher_load'])) {
	$pin = mysqli_real_escape_string($server,$_REQUEST['voucher_load']);
	$query = "SELECT * FROM vouchers WHERE customer_id = '".userData($userID,'reseller')."' AND `pin` = '$pin'";
	$result = mysqli_query($server, $query) or die(mysqli_error($server));
	$num = mysqli_num_rows($result);
	if($num < 1) {
		echo $LANG['Invalid Voucher PIN'].':0:0'; die();
	}
	$row = mysqli_fetch_assoc($result); 
	if($row['used'] > 0) {
		echo $LANG['This Voucher PIN has already been used'].':0:0'; die();
	}
	$cost = $row['cost'];
	$credits = $row['credits'];

	$date = date('Y-m-d H:i:s', time());		$user_id = getUser();
	$description = 'SMS Recharge';				$credits = $credits*userExchangeRate($user_id);
	$description = mysqli_real_escape_string($server,$description);
	$method = 'voucher';						$cost = $cost*userExchangeRate($user_id);
	$reference = genRandomPassword(6).time();	$gateway_response = 'ok';
	$approved_by = 'System';					$is_earned = '0';
	$status = 'completed';						$validity = '0';
	
	//create hook variables
	$vars = array(
				 "reference"=>$reference, 
				 "credits"=>$credits,
				 "amount"=>$cost, 
				 "customer_id"=>$user_id,
				 "method"=>$method, 
				 "description"=>$description
				 );
	$_SESSION['EventVals'] = $vars;
				
	mysqli_query($server, "INSERT INTO transactions (`date`,`customer_id`, `description`, `credits`, `cost`,`method`,`transaction_reference`,`approved_by`,`status`, `gateway_response`, `is_earned`, `validity`)	VALUES ('$date','$user_id', '$description', '$credits', '$cost','$method','$reference','$approved_by','$status', '$gateway_response', '$is_earned', '$validity');") or die (mysqli_error($server));
	mysqli_query($server, "UPDATE `vouchers` SET `used` =  '1' WHERE `pin` = '$pin' LIMIT 1");
	processTransaction($reference);
	logEvent(getUser(),'Recharged with a voucher PIN: '.$pin);
	global $hooks; $hooks->do_action('OrderCreate');
	echo 'success:'.$row['credits'].':'.$row['cost']; die();
}

if(isset($_REQUEST['buy_credit'])) {
	$amount = correctNumber(mysqli_real_escape_string($server,$_REQUEST['buy_credit']));
	$gateway = mysqli_real_escape_string($server,$_REQUEST['gateway']);
	$userID = mysqli_real_escape_string($server,$_REQUEST['user']);
	if($userID<1) {
		echo $LANG['User account validation failed'].':0'; die();	
	}
	if($gateway<1) {
		echo $LANG['Invalide payment method selected'].':0'; die();	
	}
	if($amount<1) {
		echo $LANG['Please enter a valid amount'].':0'; die();	
	}
	$min_order = userData($userID,'min_order')*userExchangeRate($userID);
	if($min_order == 0) {
		$min_order = paymentGatewayData($gateway,'minimum_order')*userExchangeRate($userID);
		if($amount < $min_order) {
			echo $LANG['The payment method you selected requires a minimum order of '].$min_order.':0'; die();	
		}
	} else {
		if($amount < $min_order) {
			echo $LANG['Your account has a minimum order of '].$min_order.':0'; die();	
		}
	}
	
	$cost = 1*$credits;
	//check resellers balance for resold transactions 
	$reseller = userData(getUser(),'reseller');
	if($reseller > 0) {
		//convert cost to users curr and check 
		/* Please note that this is disabled to prevent unneccesary restrictions
		if($amount > $reseller_balance) {
			echo $LANG['Unable to complete transaction for this amount. Please contact your admin'].':0:0'; die();
		}
		*/
	}

	$date = date('Y-m-d H:i:s', time());					$user_id = $userID;
	$description = 'SMS Recharge';							$credits = $amount;
	$description = mysqli_real_escape_string($server,$description);
	$method = $gateway;										$cost = 1*$credits;
	$reference = genRandomPassword(6).time();				$gateway_response = '';
	$approved_by = 'System';								$is_earned = '0';
	$status = 'pending';									$validity = '0';
	
	//create hook variables
	$vars = array(
				 "reference"=>$reference, 
				 "credits"=>$credits,
				 "amount"=>$cost, 
				 "customer_id"=>$user_id,
				 "method"=>$method, 
				 "description"=>$description
				 );
	$_SESSION['EventVals'] = $vars;
	
	mysqli_query($server, "INSERT INTO transactions (`date`,`customer_id`, `description`, `credits`, `cost`,`method`,`transaction_reference`,`approved_by`,`status`, `gateway_response`, `is_earned`, `validity`)	VALUES ('$date','$user_id', '$description', '$credits', '$cost','$method','$reference','$approved_by','$status', '$gateway_response', '$is_earned', '$validity');") or die (mysqli_error($server));
	
	$_SESSION['reference'] = $reference;		$_SESSION['gateway'] = $gateway;		$_SESSION['tx_user'] = $user_id;
	global $hooks; $hooks->do_action('OrderCreate');
	echo 'success:'.$reference; die();
}

if(isset($_REQUEST['buy_plan'])) {
	$plan = correctNumber(mysqli_real_escape_string($server,$_REQUEST['buy_plan']));
	$gateway = mysqli_real_escape_string($server,$_REQUEST['gateway']);
	$userID = mysqli_real_escape_string($server,$_REQUEST['user']);
	if($userID<1) {
		echo $LANG['User account validation failed'].':0'; die();	
	}
	if($gateway<1) {
		echo $LANG['Invalide payment method selected'].':0'; die();	
	}
	$query = "SELECT * FROM sms_plans WHERE customer_id = '".userData($userID,'reseller')."' AND `id` = '$plan'";
	$result = mysqli_query($server, $query) or die(mysqli_error($server));
	$num = mysqli_num_rows($result);
	if($num < 1) {
		echo $LANG['Invalid SMS Package'].':0'; die();
	}
	$row = mysqli_fetch_assoc($result); 
	$amount = $row['credits']*userExchangeRate($userID);
	$price = $row['price']*userExchangeRate($userID);
	$min_order = userData($userID,'min_order')*userExchangeRate($userID);

	//check resellers balance for resold transactions 
	$reseller = userData(getUser(),'reseller');
	if($reseller > 0) {
		/* Please note that this is disabled to prevent unneccesary restrictions		
		if($required > $reseller_balance) {
			echo $LANG['Unable to complete transaction for this amount. Please contact your admin'].':0:0'; die();
		}
		*/
	} else {
		//check order limits
		if($min_order == 0) {
			$min_order = paymentGatewayData($gateway,'minimum_order')*userExchangeRate($userID);
			if($amount < $min_order) {
				echo $LANG['The payment method you selected requires a minimum order of '].$min_order.':0'; die();	
			}
		} else {
			if($amount < $min_order) {
				echo $LANG['Your account has a minimum order of '].$min_order.':0'; die();	
			}
		}
	}
	
	$date = date('Y-m-d H:i:s', time());		$user_id = $userID;
	$description = $row['title'];				$credits = $amount;
	$description = mysqli_real_escape_string($server,$description);
	$method = $gateway;							$cost = $price;
	$reference = genRandomPassword(6).time();	$gateway_response = '';
	$approved_by = 'System';					$is_earned = '0';
	$status = 'pending';						$validity = $row['validity'];
	
	//create hook variables
	$vars = array(
				 "reference"=>$reference, 
				 "credits"=>$credits,
				 "amount"=>$cost, 
				 "customer_id"=>$user_id,
				 "method"=>$method, 
				 "description"=>$description
				 );
	$_SESSION['EventVals'] = $vars;
	
	mysqli_query($server, "INSERT INTO transactions (`date`,`customer_id`, `description`, `credits`, `cost`,`method`,`transaction_reference`,`approved_by`,`status`, `gateway_response`, `is_earned`, `validity`)	VALUES ('$date','$user_id', '$description', '$credits', '$cost','$method','$reference','$approved_by','$status', '$gateway_response', '$is_earned', '$validity');") or die (mysqli_error($server));
	
	$_SESSION['reference'] = $reference;		$_SESSION['gateway'] = $gateway;		$_SESSION['tx_user'] = $user_id;
	global $hooks; $hooks->do_action('OrderCreate');
	echo 'success:'.$reference; die();
}

if(isset($_REQUEST['message_stats'])) { 
	$message = mysqli_real_escape_string($server,$_REQUEST['message']);
	$to = mysqli_real_escape_string($server,$_REQUEST['to']);
	$addressbook = json_decode($_REQUEST['addressbook'],true);
	$marketing_list = json_decode($_REQUEST['marketing_list'],true);
	$files = mysqli_real_escape_string($server,$_REQUEST['files']);
	//consider phonebooks
	foreach ($addressbook as $list){
		$to .= ','.getContacts($list,'phonebook');	
	}
	//consider marketing lists
	foreach ($marketing_list as $list){
		$to .= ','.getContacts($list,'marketing');	
	}
	//consider uploaded files
	if(!empty($files)) {
		$to .= ','.getFileContacts($files);
	}
	
	if(!empty($to)) $to = correctRecipient($to);
	$country = mysqli_real_escape_string($server,$_REQUEST['country']);
	$type = mysqli_real_escape_string($server,$_REQUEST['message_type']);
	$duration = mysqli_real_escape_string($server,$_REQUEST['duration']);
	$userID = mysqli_real_escape_string($server,$_REQUEST['user']);

	$chars = countCharacters($message);
	$numbers = countRecipient($to);
	$pages = countPage($message,$type,$duration);
	if(empty($message)) $page = 1;
	$cost = smsCost($to,$type,$country,$pages,$userID);
	echo 'success:'.$chars.':'.$numbers.':'.$pages.':'.$cost; die();
}

if(isset($_REQUEST['uploadfileCon'])) {
	$fileName = $_FILES['file']['name'];
	$fileType = strtolower(end(explode(".", $_FILES['file']['name'])));
	if($fileType != 'csv' && $fileType != 'xls' && $fileType != 'xlsx') {
		echo $LANG['Unsupported file format'].':0'; die();	
	}
	$newfilename = microtime(true) . '.' . $fileType;
	if(move_uploaded_file($_FILES["file"]["tmp_name"], "files/temp/" . $newfilename)) {
		echo 'success:'.$newfilename; die();
	} 
	echo $LANG['Unable to upload file'].' '.$fileName.':'.'0'; die();
}

if(isset($_REQUEST['uploadfileZIP'])) {
	$fileName = $_FILES['file']['name'];
	$fileType = strtolower(end(explode(".", $_FILES['file']['name'])));
	if($fileType != 'zip') {
		echo $LANG['Unsupported module file'].':0'; die();	
	}
	$newfilename = rand(1111,8888).time() . '.' . $fileType;
	if(move_uploaded_file($_FILES["file"]["tmp_name"], "files/temporally_files/" . $newfilename)) {
		echo 'success:'.$newfilename; die();
	} 
	echo $LANG['Unable to upload file'].' '.$fileName.':'.'0'; die();
}
if(isset($_REQUEST['uploadfileMM'])) {
	$fileName = $_FILES['file']['name'];
	$fileType = strtolower(end(explode(".", $_FILES['file']['name'])));
	if($fileType != 'jpg' && $fileType != 'gif' && $fileType != 'png' && $fileType != 'mp4' && $fileType != 'amr' && $fileType != 'mpeg' && $fileType != 'wav' && $fileType != '3gp' && $fileType != 'mpg' && $fileType != 'mp3' && $fileType != 'txt') {
		echo $LANG['Unsupported file format'].':0'; die();	
	}
	$newfilename = rand(1111,8888).time() . '.' . $fileType;
	if(move_uploaded_file($_FILES["file"]["tmp_name"], "files/temp/" . $newfilename)) {
		echo 'success:'.$newfilename; die();
	} 
	echo $LANG['Unable to upload file'].' '.$fileName.':'.'0'; die();
}
if(isset($_REQUEST['uploadfileAud'])) {
	$fileName = $_FILES['file']['name'];
	$fileType = strtolower(end(explode(".", $_FILES['file']['name'])));
	if($fileType != 'mp3' && $fileType != 'wav' && $fileType != 'wma') {
		echo $LANG['Unsupported file format'].':0'; die();	
	}
	$newfilename = rand(1111,8888).time() . '.' . $fileType;
	if(move_uploaded_file($_FILES["file"]["tmp_name"], "files/temp/" . $newfilename)) {
		echo 'success:'.$newfilename; die();
	} 
	echo $LANG['Unable to upload file'].' '.$fileName.':'.'0'; die();
}

if(isset($_REQUEST['save_message'])) {
	$message = mysqli_real_escape_string($server,$_REQUEST['message']);
	$to = mysqli_real_escape_string($server,$_REQUEST['to']);
	$addressbook = json_decode($_REQUEST['addressbook'],true);
	$marketing_list = json_decode($_REQUEST['marketing_list'],true);
	$files = mysqli_real_escape_string($server,$_REQUEST['files']);
	//consider phonebooks
	$phonebook_id = '';
	foreach ($addressbook as $list){
		$phonebook_id .= $list.',';	
	} $phonebook_id = rtrim($phonebook_id,',');
	//consider marketing lists
	$marketinglist_id = '';
	foreach ($marketing_list as $list){
		$marketinglist_id .= $list.',';	
	} $marketinglist_id = rtrim($marketinglist_id,',');
	if(!empty($to)) $to = correctRecipient($to);
	$time = mysqli_real_escape_string($server,$_REQUEST['time']);
	$date = mysqli_real_escape_string($server,$_REQUEST['date']);

	$media_file = $voice_file = '';
	if(!empty($_REQUEST['media_file']))
	$media_file = home_base_url().'files/temp/'.mysqli_real_escape_string($server,$_REQUEST['media_file']);
	if(!empty($_REQUEST['voice_file']))
	$voice_file = home_base_url().'files/temp/'.mysqli_real_escape_string($server,$_REQUEST['voice_file']);
	$type = mysqli_real_escape_string($server,$_REQUEST['message_type']);

	if(strtolower($type)=='voice') {
		$media_file = $voice_file;
	}

	$sender_id = mysqli_real_escape_string($server,$_REQUEST['sender_id']);
	$country = mysqli_real_escape_string($server,$_REQUEST['country']);
	$duration = mysqli_real_escape_string($server,$_REQUEST['duration']);
	$userID = mysqli_real_escape_string($server,$_REQUEST['user']);
	$now = date('Y-m-d H:i:s', time());
	if(empty($message)) { echo $LANG['You cannot save a blank message'].':0'; die();	}
	if($userID < 1) { echo $LANG['Invalid API request!'].':0'; die(); }
	$forbiden_word = forbiddenWord($message,$userID);
	if($forbiden_word && (!isAdmin($userID))) { echo $LANG['Your message contains some forbidden words. Please remove those and try again'].':0'; die();}
	//set admin user
	if(isAdmin(getUser())) { $userID = 0;}
	//save to DB
	mysqli_query($server, "INSERT INTO draftmessages (`message`,`recipients`, `customer_id`, `type`, `media`, `date`, `sender_id`, `phonebook_id`, `marketinglist_id`, `duration`, `file`,`country`) VALUES ('$message','$to', '$userID', '$type', '$media_file','$now','$sender_id','$phonebook_id','$marketinglist_id', '$duration', '$files','$country');") or die(mysqli_error($server));
	echo 'success:'.'0'; die();	
}

if(isset($_REQUEST['send_message'])) {
	$message = mysqli_real_escape_string($server,$_REQUEST['message']);
	$to = mysqli_real_escape_string($server,$_REQUEST['to']);
	$to = correctRecipient($to);
	$addressbook = json_decode($_REQUEST['addressbook'],true);
	$marketing_list = json_decode($_REQUEST['marketing_list'],true);
	$files = mysqli_real_escape_string($server,$_REQUEST['files']);
	//consider phonebooks
	$phonebook_id = '';
	foreach ($addressbook as $list){
		$phonebook_id .= $list.',';	
	} $phonebook_id = rtrim($phonebook_id,',');
	//consider marketing lists
	$marketinglist_id = '';
	foreach ($marketing_list as $list){
		$marketinglist_id .= $list.',';	
	} $marketinglist_id = rtrim($marketinglist_id,',');

	//check recipients
	$tempTo = $to;
	foreach ($addressbook as $list){
		$tempTo .= ','.getContacts($list,'phonebook');	
	}
	//consider marketing lists
	foreach ($marketing_list as $list){
		$tempTo .= ','.getContacts($list,'marketing');	
	}
	//consider uploaded files
	if(!empty($files)) {
		$tempTo .= ','.getFileContacts($files);
	}
	$tempTo = correctRecipient($tempTo);
	
	$time = mysqli_real_escape_string($server,$_REQUEST['time']);
	$date = mysqli_real_escape_string($server,$_REQUEST['date']);
	$repeats = mysqli_real_escape_string($server,$_REQUEST['repeats']);
	$media_file = $voice_file = '';
	if(!empty($_REQUEST['media_file']))
	$media_file = home_base_url().'files/temp/'.mysqli_real_escape_string($server,$_REQUEST['media_file']);
	if(!empty($_REQUEST['voice_file']))
	$voice_file = home_base_url().'files/temp/'.mysqli_real_escape_string($server,$_REQUEST['voice_file']);
	$type = mysqli_real_escape_string($server,$_REQUEST['message_type']);

	if(strtolower($type)=='voice') {
		$media_file = $voice_file;
	}
	$sender_id = mysqli_real_escape_string($server,$_REQUEST['sender_id']);	
	$country = mysqli_real_escape_string($server,$_REQUEST['country']);
	$duration = mysqli_real_escape_string($server,$_REQUEST['duration']);
	$userID = mysqli_real_escape_string($server,$_REQUEST['user']);
	$date = mysqli_real_escape_string($server,$_REQUEST['date']);
	$date = strtotime($date);
	$date = date('Y-m-d',$date);
	$time = mysqli_real_escape_string($server,$_REQUEST['time']);
	$schedule_date = $date.' '.$time.':00';
	$chars = countCharacters($message);
	$numbers = $to_count = $numbers = countRecipient($tempTo);
	$pages = countPage($message,$type,$duration);
	$cost = smsCost($tempTo,$type,$country,$pages,$userID);
	
	$now = date('Y-m-d H:i:s', time());
	$sent_from = 'web';
	$gateway_id = 0;
	$ip = getUserIP();
	$notice = '';
	
	if(empty($message) && $type=='sms') { echo $LANG['You cannot send a blank message'].':0'; die();	}
	if(empty($sender_id)) { echo $LANG['You have not supplied any valid Sender ID'].':0'; die();	}
	$forbiden_id = forbiddenSenderID($sender_id,$userID);
	if($forbiden_id && (!isAdmin($userID))) { echo $LANG['You are not allowed to use this sender ID on our platform'].':0'; die();}
	$forbiden_word = forbiddenWord($message,$userID);
	if($forbiden_word && (!isAdmin($userID))) { echo $LANG['Your message contains some forbidden words. Please remove those and try again'].':0'; die();}
	if($numbers < 1) { echo $LANG['You have not supplied any valid recipient'].':0'; die(); }
	if((userWalletBalance($userID) <=0) && (!isAdmin($userID)) ) { echo $LANG['You do not have enough credit to send this message. Please recharge your account'].':0'; die(); }
	if($userID < 1) { echo $LANG['Invalid API request'].':0'; die(); }
	//set admin user
	if(isAdmin(getUser())) { 
	$userID = 0;
	$user_time = date('Y-m-d H:i:s',time());
	} else {
	$user_time = getUserTime($userID);
	}
	//create hook variables
		$vars = array(
					 "sender_id"=>$sender_id, 
					 "to"=>$tempTo,
					 "message"=>$message, 
					 "customer_id"=>$userID,
					 "type"=>$type, 
					 "media"=>$media_file
					 );
		$_SESSION['EventVals'] = $vars;
		
	global $hooks; $hooks->do_action('BeforeSendMessage');
	if(strtotime($schedule_date) > strtotime($user_time)) {
		//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`, `repeats`) VALUES ('$message','$to', '$userID', '$type', '$media_file','$now','$sender_id','$phonebook_id','$marketinglist_id', '$duration', '$files','$country','queued', '$schedule_date', '$gateway_id', '$to_count', '$repeats');") or die(mysqli_error($server));
		logEvent($userID,'Scheduled a message for '.$schedule_date);
		global $hooks; $hooks->do_action('AfterSendMessage');
		echo 'success:'.'1:'.$cost; 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`) VALUES ('$message','$to', '$userID', '$type', '$media_file','$now','$sender_id','$phonebook_id','$marketinglist_id', '$duration', '$files','$country','queued', '$sent_from', '$gateway_id', '$ip', '$notice', '$to_count');") or die(mysqli_error($server));
	logEvent($userID,'Initiated an '.$type.' message to '.$numbers.' recipients');
	global $hooks; $hooks->do_action('AfterSendMessage');
	echo 'success:'.'0:'.$cost; die();	
}

if(isset($_REQUEST['save_phonebook'])) {
	$message = mysqli_real_escape_string($server,$_REQUEST['message']);
	$title = mysqli_real_escape_string($server,$_REQUEST['title']);
	$phonebook_id = mysqli_real_escape_string($server,$_REQUEST['phonebook_id']);
	$description = mysqli_real_escape_string($server,$_REQUEST['description']);
	$userID = mysqli_real_escape_string($server,$_REQUEST['user']);
	
	if(empty($title)) { echo $LANG['Please provide a title for this phonebook'].':0'; die();}
	if($phonebook_id > 0) {
		if(!isAdmin($userID) && addressbookData($phonebook_id,'customer_id')!=$userID) {
			echo $LANG['You do not have permission to update this phonebook.'].':0'; die();
		}
		mysqli_query($server, "UPDATE `phonebooks` SET `title` =  '$title' WHERE `id` = '$phonebook_id'");
		mysqli_query($server, "UPDATE `phonebooks` SET `description` =  '$description' WHERE `id` = '$phonebook_id'");
		mysqli_query($server, "UPDATE `phonebooks` SET `birthday_sms` =  '$message' WHERE `id` = '$phonebook_id'");
		echo 'success:'.'0'; die();	
	} else {
		if($userID < 1) { echo $LANG['Invalid API request!'].':0'; die(); }
		//set admin user
		if(isAdmin(getUser())) { $userID = 0;}
		//save to DB
		mysqli_query($server, "INSERT INTO phonebooks (`title`,`description`, `birthday_sms`, `customer_id`) VALUES ('$title','$description', '$message', '$userID');") or die(mysqli_error($server));
		$phonebook_id = mysqli_insert_id($server);	
		mysqli_query($server, "INSERT INTO phonebook_owners (`phonebook_id`,`is_owner`, `customer_id`) VALUES ('$phonebook_id', '1', '$userID');") or die(mysqli_error($server));
		logEvent($userID,'Created a phonebook with ID '.$phonebook_id);
		echo 'success:'.'0'; die();	
	}
	die();
}
if(isset($_REQUEST['save_marketinglist'])) {
	$is_public = 0;
	$cost = 0;
	$title = mysqli_real_escape_string($server,$_REQUEST['title']);
	$phonebook_id = mysqli_real_escape_string($server,$_REQUEST['phonebook_id']);
	$description = mysqli_real_escape_string($server,$_REQUEST['description']);
	$optout_sms = mysqli_real_escape_string($server,$_REQUEST['optout_sms']);
	$optout_key = mysqli_real_escape_string($server,$_REQUEST['optout_key']);
	$optin_sms = mysqli_real_escape_string($server,$_REQUEST['optin_sms']);
	$optin_key = mysqli_real_escape_string($server,$_REQUEST['optin_key']);
	$shortcode = mysqli_real_escape_string($server,$_REQUEST['shortcode']);
	$default_sender_id = mysqli_real_escape_string($server,$_REQUEST['default_sender_id']);
	$user = $userID = mysqli_real_escape_string($server,$_REQUEST['user']);
	
	if(isAdmin($userID)) {
		$is_public = mysqli_real_escape_string($server,$_REQUEST['is_public']);
		$cost = mysqli_real_escape_string($server,$_REQUEST['cost']);
	}
	if(empty($title)) { echo $LANG['Please provide a title for this list'].':0'; die();}
	if(empty($optin_key)) { echo $LANG['Please provide an opt-in for this list'].':0'; die();}
	if(empty($optout_key)) { echo $LANG['Please provide an opt-out for this list'].':0'; die();}
	if($phonebook_id > 0) {
		if(!isAdmin($userID) &&  marketinglistData($phonebook_id,'customer_id')!=$userID) {
			echo $LANG['You do not have permission to update this list.'].':0'; die();
		}
		if(keywordExist($optin_key,$phonebook_id,$shortcode)) { 
			echo $LANG['Your opt-in keyword is already in use'].':0'; die(); 
		}
		if(keywordExist($optout_key,$phonebook_id,$shortcode)) { 
			echo $LANG['Your opt-out keyword is already in use'].':0'; die(); 
		}
		mysqli_query($server, "UPDATE `marketinglist` SET `is_public` =  '$is_public' WHERE `id` = '$phonebook_id'");
		mysqli_query($server, "UPDATE `marketinglist` SET `cost` =  '$cost' WHERE `id` = '$phonebook_id'");
		mysqli_query($server, "UPDATE `marketinglist` SET `title` =  '$title' WHERE `id` = '$phonebook_id'");
		mysqli_query($server, "UPDATE `marketinglist` SET `description` =  '$description' WHERE `id` = '$phonebook_id'");
		mysqli_query($server, "UPDATE `marketinglist` SET `shortcode` =  '$shortcode' WHERE `id` = '$phonebook_id'");
		mysqli_query($server, "UPDATE `marketinglist` SET `default_sender_id` =  '$default_sender_id' WHERE `id` = '$phonebook_id'");
		mysqli_query($server, "UPDATE `marketinglist` SET `optin_keyword` =  '$optin_key' WHERE `id` = '$phonebook_id'");
		mysqli_query($server, "UPDATE `marketinglist` SET `optin_message` =  '$optin_sms' WHERE `id` = '$phonebook_id'");
		mysqli_query($server, "UPDATE `marketinglist` SET `optout_keyword` =  '$optout_key' WHERE `id` = '$phonebook_id'");
		mysqli_query($server, "UPDATE `marketinglist` SET `optout_message` =  '$optout_sms' WHERE `id` = '$phonebook_id'");
		echo 'success:'.'0'; die();	
	} else {
		if($userID < 1) { echo $LANG['Invalid API request!'].':0'; die(); }
		if(keywordExist($optin_key,0,$shortcode)) { 
			echo $LANG['Your opt-in keyword is already in use'].':0'; die(); 
		}
		if(keywordExist($optout_key,0,$shortcode)) { 
			echo $LANG['Your opt-out keyword is already in use'].':0'; die(); 
		}
		//set admin user
		if(isAdmin(getUser())) { $userID = 0;}
		//save to DB
		mysqli_query($server, "INSERT INTO marketinglist (`is_public`, `cost`, `title`,`description`, `customer_id`, `shortcode`, `optin_keyword`, `optin_message`, `optout_keyword`, `optout_message`, `default_sender_id`) VALUES ('$is_public', '$cost', '$title', '$description', '$userID', '$shortcode', '$optin_key', '$optin_sms', '$optout_key', '$optout_sms', '$default_sender_id');") or die(mysqli_error($server));
		$phonebook_id = mysqli_insert_id($server);	
		mysqli_query($server, "INSERT INTO marketinglist_owners (`marketinglist_id`,`is_owner`, `customer_id`) VALUES ('$phonebook_id', '1', '$userID');") or die(mysqli_error($server));
		logEvent($userID,'Created a marketing list with ID '.$phonebook_id);
		echo 'success:'.'0'; die();	
	}
	die();
}
if(isset($_REQUEST['share_marketinglist'])) {
	$phonebook_id = mysqli_real_escape_string($server,$_REQUEST['phonebook_id']);
	$member = mysqli_real_escape_string($server,$_REQUEST['member']);
	$userID = mysqli_real_escape_string($server,$_REQUEST['user']);
	
	if(empty($member)) { echo $LANG['Please provide a member\'s email address'].':0'; die();}
	if(!isAdmin($userID) && marketinglistData($phonebook_id,'customer_id')!=$userID) {
		echo $LANG['You do not have permission to share this list.'].':0'; die();
	}
	$customer_id = memberByEmail($member,$userID);
	if($customer_id < 1) { echo $LANG['This email address is not valid'].':0'; die();}
	if(!canAccessList($phonebook_id,$customer_id)) {
		mysqli_query($server, "INSERT INTO marketinglist_owners (`marketinglist_id`,`is_owner`, `customer_id`) VALUES ('$phonebook_id', '0', '$customer_id');") or die(mysqli_error($server));
		logEvent($userID,'shared marketing list ID '.$phonebook_id.' with '.$member);
		createNotice($customer_id,userData($userID,'first_name')." shared a marketing list with you!");
	}
	echo 'success:'.'0'; die();	
}
if(isset($_REQUEST['share_phonebook'])) {
	$phonebook_id = mysqli_real_escape_string($server,$_REQUEST['phonebook_id']);
	$member = mysqli_real_escape_string($server,$_REQUEST['member']);
	$userID = mysqli_real_escape_string($server,$_REQUEST['user']);
	
	if(empty($member)) { echo $LANG['Please provide a member\'s email address'].':0'; die();}
	if(!isAdmin($userID) &&  addressbookData($phonebook_id,'customer_id')!=$userID) {
		echo $LANG['You do not have permission to share this addressbook.'].':0'; die();
	}
	$customer_id = memberByEmail($member,$userID);
	if($customer_id < 1) { echo $LANG['This email address is not valid'].':0'; die();}
	if(!canAccessPhonebook($phonebook_id,$customer_id)) {
		mysqli_query($server, "INSERT INTO phonebook_owners (`phonebook_id`,`is_owner`, `customer_id`) VALUES ('$phonebook_id', '0', '$customer_id');") or die(mysqli_error($server));
		logEvent($userID,'shared phonebook ID '.$phonebook_id.' with '.$member);
		createNotice($customer_id,userData($userID,'first_name')." shared an addressbook with you!");
	}
	echo 'success:'.'0'; die();	
}

if(isset($_REQUEST['save_contact'])) {
	$phone = correctNumber(mysqli_real_escape_string($server,$_REQUEST['phone']));
	$fname = mysqli_real_escape_string($server,$_REQUEST['fname']);
	$phonebook_id = mysqli_real_escape_string($server,$_REQUEST['phonebook_id']);
	$id = mysqli_real_escape_string($server,$_REQUEST['updateCon']);
	$birthday = mysqli_real_escape_string($server,$_REQUEST['dob']);
	$birthday = strtotime($birthday);
	$birthday = date('Y-m-d',$birthday);
	$lname = mysqli_real_escape_string($server,$_REQUEST['lname']);
	$files = mysqli_real_escape_string($server,$_REQUEST['files']);
	$userID = mysqli_real_escape_string($server,$_REQUEST['user']);
	
	if($id > 0) {
		if(!isAdmin($userID) &&  addressbookData($phonebook_id,'customer_id')!=$userID) {
			echo $LANG['You do not have permission perform this action.'].':0'; die();
		}
		if(empty($phone)) { echo $LANG['Please provide a valide phone number for this contact'].':0'; die();}		
		mysqli_query($server, "UPDATE `contacts` SET `first_name` =  '$fname' WHERE `id` = '$id'");
		mysqli_query($server, "UPDATE `contacts` SET `last_name` =  '$lname' WHERE `id` = '$id'");
		mysqli_query($server, "UPDATE `contacts` SET `phone` =  '$phone' WHERE `id` = '$id'");
		mysqli_query($server, "UPDATE `contacts` SET `birthday` =  '$birthday' WHERE `id` = '$id'");
		echo 'success:'.'0'; die();	
	} else {
		if($userID < 1) { echo $LANG['Invalid API request!'].':0'; die(); }
		//set admin user
		if(isAdmin(getUser())) { $userID = 0;}
		//save to DB
		if(!empty($files)) {
			$done = importCSV($files,'contact',$phonebook_id);
			if($done=='ok') {
				echo 'success:'.'0'; die();	
			} else {
				echo $LANG['Unable to read contacts from file'].':0'; die(); 
			}
		} else {
			if(empty($phone)) { echo $LANG['Please provide a valide phone number for this contact'].':0'; die();}
			if(contactExist($phone,$phonebook_id,'contact') < 1) {
				mysqli_query($server, "INSERT INTO contacts (`first_name`, `last_name`,`phone`, `birthday`, `phonebook_id`) VALUES ('$fname', '$lname','$phone', '$birthday', '$phonebook_id');") or die(mysqli_error($server));
				logEvent($userID,'Created a new contact in phonebook ID '.$phonebook_id);
			}
			echo 'success:'.'0'; die();	
		}
	}
	die();
}

if(isset($_REQUEST['save_marketinglistcontact'])) {
	$phone = correctNumber(mysqli_real_escape_string($server,$_REQUEST['phone']));
	$fname = mysqli_real_escape_string($server,$_REQUEST['fname']);
	$phonebook_id = mysqli_real_escape_string($server,$_REQUEST['phonebook_id']);
	$id = mysqli_real_escape_string($server,$_REQUEST['updateCon']);
	$files = mysqli_real_escape_string($server,$_REQUEST['files']);
	$userID = mysqli_real_escape_string($server,$_REQUEST['user']);
	
	if($id > 0) {
		if(!isAdmin($userID) &&  marketinglistData($phonebook_id,'customer_id')!=$userID) {
			echo $LANG['You do not have permission perform this action.'].':0'; die();
		}
		if(empty($phone)) { echo $LANG['Please provide a valide phone number for this contact'].':0'; die();}		
		mysqli_query($server, "UPDATE `marketingcontacts` SET `name` =  '$fname' WHERE `id` = '$id'");
		mysqli_query($server, "UPDATE `marketingcontacts` SET `phone` =  '$phone' WHERE `id` = '$id'");
		echo 'success:'.'0'; die();	
	} else {
		if($userID < 1) { echo $LANG['Invalid API request!'].':0'; die(); }
		//set admin user
		if(isAdmin(getUser())) { $userID = 0;}
		//save to DB
		if(!empty($files)) {
			$done = importCSV($files,'marketing',$phonebook_id);
			if($done=='ok') {
				echo 'success:'.'0'; die();	
			} else {
				echo $LANG['Unable to read contacts from file'].':0'; die(); 
			}
		} else {
			if(empty($phone)) { echo $LANG['Please provide a valide phone number for this contact'].':0'; die();}
			if(contactExist($phone,$phonebook_id,'marketing') < 1) {
				mysqli_query($server, "INSERT INTO marketingcontacts (`name`,`phone`, `marketinglist`) VALUES ('$fname', '$phone', '$phonebook_id');") or die(mysqli_error($server));
				logEvent($userID,'Created a new contact in markeing list ID '.$phonebook_id);
			}
			echo 'success:'.'0'; die();	
		}
	}
	die();
}
if(isset($_REQUEST['save_blacklist'])) {
	$phone = correctNumber(mysqli_real_escape_string($server,$_REQUEST['phone']));
	$phone = str_replace('+','',$phone);
	$userID = mysqli_real_escape_string($server,$_REQUEST['user']);
	if($userID < 1) { echo $LANG['Invalid API request!'].':0'; die(); }
	if(empty($phone)) { echo $LANG['Please provide a valide phone number for this contact'].':0'; die();}
	if(isAdmin(getUser())) { $userID = 0;}
	if(!numberBlacklisted($phone))
	mysqli_query($server, "INSERT INTO blacklist (`phone`, `customer_id`) VALUES ('$phone', '$userID');") or die(mysqli_error($server));
	logEvent($userID,'added a new contact to blacklist: '.$phone);
	echo 'success:'.'0'; die();	
}

if(isset($_REQUEST['buy_shortcode'])) {
	$phone = mysqli_real_escape_string($server,$_REQUEST['phone']);
	$data = mysqli_real_escape_string($server,$_REQUEST['data']);
	$datas = explode(':',$data);
	$cost = $datas[1]*userExchangeRate($userID);
	$cycle = $datas[2];
	$due = date('Y-m-d H:i:s', time()+(30*24*60*60*$cycle));
	$userID = mysqli_real_escape_string($server,$_REQUEST['user']);
	
	if($userID < 1) { echo $LANG['Invalid API request!'].':0'; die(); }
	if(empty($phone)) { echo $LANG['You have not selected any shortcode'].':0'; die();}
	$userbalance = userWalletBalance($userID);
	if($cost > $userbalance) { 	echo $LANG['You do not have sufficient credits to buy this short-code. Please fund your account'].':0'; die();}
	mysqli_query($server,"UPDATE `shortcodes` SET customer_id = '$userID' WHERE `shortcode` = '$phone'") or die(mysqli_error($server));
	mysqli_query($server,"UPDATE `shortcodes` SET date = '$due' WHERE `shortcode` = '$phone' AND customer_id = '$userID'") or die(mysqli_error($server));
	
	//create hook variables
				$vars = array(
							 "customer_id"=>$userID, 
							 "shortcode"=>$phone,
							 "duration"=>$cycle
							 );
				$_SESSION['EventVals'] = $vars;
				
	//transact
	$date = date('Y-m-d H:i:s', time());										$user_id = $userID;
	$description = 'Shortcode purchase: '.$phone;								$credits = 0-$cost;
	$description = mysqli_real_escape_string($server,$description);
	$method = 'system';															$cost = 0;
	$reference = genRandomPassword(6).time();			$gateway_response = '';
	$approved_by = 'System';							$is_earned = '0';
	$status = 'completed';								$validity = 0;
	
	mysqli_query($server, "INSERT INTO transactions (`date`,`customer_id`, `description`, `credits`, `cost`,`method`,`transaction_reference`,`approved_by`,`status`, `gateway_response`, `is_earned`, `validity`)	VALUES ('$date','$user_id', '$description', '$credits', '$cost','$method','$reference','$approved_by','$status', '$gateway_response', '$is_earned', '$validity');") or die (mysqli_error($server));
	mysqli_query($server, "UPDATE `transactions` SET `paid_on` =  '".date('Y-m-d H:i:s')."' WHERE `transaction_reference` = '$reference'");
	logEvent($userID,'Purchased a new shortcode: '.$phone);
	global $hooks; $hooks->do_action('ShortcodePurchase');
	echo 'success:'.'0'; die();	
}

if(isset($_REQUEST['share_shortcode'])) {
	$shortcode = mysqli_real_escape_string($server,$_REQUEST['shortcode']);
	$customer = mysqli_real_escape_string($server,$_REQUEST['customer']);
	$userID = mysqli_real_escape_string($server,$_REQUEST['user']);
	
	if($userID < 1) { echo $LANG['Invalid API request!'].':0'; die(); }
	if($customer<1) { echo $LANG['You have not selected any customer'].':0'; die();}
	mysqli_query($server,"UPDATE `shortcodes` SET resold = '$customer' WHERE `id` = '$shortcode' AND `customer_id` = '$userID'") or die(mysqli_error($server));
	logEvent($userID,'shared a shortcode with ID: '.$shortcode);
	echo 'success:'.'0'; die();	
}

if(isset($_REQUEST['share_senderid'])) {
	$sender_id = mysqli_real_escape_string($server,$_REQUEST['senderid']);
	$customer = mysqli_real_escape_string($server,$_REQUEST['customer']);
	$userID = mysqli_real_escape_string($server,$_REQUEST['user']);
	
	if($userID < 1) { echo $LANG['Invalid API request!'].':0'; die(); }
	if($customer<1) { echo $LANG['You have not selected any customer'].':0'; die();}
	mysqli_query($server,"UPDATE `sender_id` SET resold = '$customer' WHERE `id` = '$sender_id' AND `customer_id` = '$userID'") or die(mysqli_error($server));
	logEvent($userID,'shared a sender ID: '.$sender_id);
	echo 'success:'.'0'; die();	
}

if(isset($_REQUEST['add_senderid'])) {
	$sender_id = mysqli_real_escape_string($server,$_REQUEST['senderid']);
	$type = mysqli_real_escape_string($server,$_REQUEST['type']);
	$customer_id = mysqli_real_escape_string($server,$_REQUEST['customer']);
	$user = $userID = mysqli_real_escape_string($server,$_REQUEST['user']);
	//create hook variables
				$vars = array(
							 "sender_id"=>$sender_id, 
							 "customer_id"=>$user,
							 "type"=>$type
							 );
				$_SESSION['EventVals'] = $vars;
	if($userID==$customer_id) {
		echo $LANG['Invalid API request!'].':0'; die();
	}
	$status = 'pending';
	if(isAdmin($userID)) {
		$userID = $customer_id;
		$status = 'approved';
	}
	//check if sender is ok
	if(empty($sender_id)) {
		echo $LANG['You have not supplied any Sender ID'].':0'; die();
	}
	mysqli_query($server, "INSERT INTO sender_id (`customer_id`, `type`,`sender_id`, `status`) VALUES ('$userID', '$type','$sender_id', '$status');") or die(mysqli_error($server));
	logEvent($user,'Created a new sender ID');
	global $hooks; $hooks->do_action('SenderIDCreate');
	echo 'success:'.'0'; die();	
}

if(isset($_REQUEST['share_credit'])) {
	$amount = $cost = correctNumber(mysqli_real_escape_string($server,$_REQUEST['credit']));
	$member = mysqli_real_escape_string($server,$_REQUEST['member']);
	$password = mysqli_real_escape_string($server,$_REQUEST['pass']);
	$userID = mysqli_real_escape_string($server,$_REQUEST['user']);
	$user_email = userData($userID,'email');
	
	if($userID < 1) { echo $LANG['Invalid API request!'].':0'; die(); }
	if(empty($cost)) { echo $LANG['You have not supplied a valid amount of credit to share'].':0'; die();}
	$userbalance = userWalletBalance($userID);
	if($cost > $userbalance) { 	echo $LANG['You cannot transfer above your current balance'].':0'; die();}
	$customer_id = memberByEmail($member,$userID);
	if($customer_id < 1) { echo $LANG['This email address is not valid'].':0'; die();}
	
	$query="SELECT * FROM users WHERE id = '$userID'"; 
	$result = mysqli_query($server,$query);  
	$row = mysqli_fetch_assoc($result); 
	$pwsalt = explode( ":",$row["password"]);	
	$pass2 = $row["password"];		
	if(md5($password . $pwsalt[1]) != $pwsalt[0] && md5($password) != $row["password"]) { echo $LANG['The password you entered is not valid'].':0'; die();}
		   
	//transact for sender
	$date = date('Y-m-d H:i:s', time());										$user_id = $userID;
	$description = 'Credit transfer to: '.$member;								$credits = 0-$cost;
	$description = mysqli_real_escape_string($server,$description);
	$method = 'system';															$cost = 0;
	$reference = genRandomPassword(6).time();			$gateway_response = '';
	$approved_by = 'System';							$is_earned = '0';
	$status = 'completed';								$validity = 0;
	
	mysqli_query($server, "INSERT INTO transactions (`date`,`customer_id`, `description`, `credits`, `cost`,`method`,`transaction_reference`,`approved_by`,`status`, `gateway_response`, `is_earned`, `validity`,`is_shared`,`receiver`)	VALUES ('$date','$user_id', '$description', '$credits', '$cost','$method','$reference','$approved_by','$status', '$gateway_response', '$is_earned', '$validity','1','$customer_id');") or die (mysqli_error($server));
	logEvent($userID,'Transfered credits to '.$member);
	
	//transact for receiver
	$amount = round($amount/userExchangeRate($userID),4);
	$amount = $amount*userExchangeRate($customer_id); //amount in recivers currency
	
	$date = date('Y-m-d H:i:s', time());										$user_id = $customer_id;
	$description = 'Credit transfer from: '.$user_email;						$credits = 0+$amount;
	$description = mysqli_real_escape_string($server,$description);
	$method = 'system';															$cost = 0;
	$reference = $reference;							$gateway_response = '';
	$approved_by = 'System';							$is_earned = '0';
	$status = 'completed';								$validity = 0;
	
	mysqli_query($server, "INSERT INTO transactions (`date`,`customer_id`, `description`, `credits`, `cost`,`method`,`transaction_reference`,`approved_by`,`status`, `gateway_response`, `is_earned`, `validity`)	VALUES ('$date','$user_id', '$description', '$credits', '$cost','$method','$reference','$approved_by','$status', '$gateway_response', '$is_earned', '$validity');") or die (mysqli_error($server));
	createNotice($customer_id,userData($userID,'email')." transfered ".$amount." SMS credits to you!");
	echo 'success:'.'0'; die();	
}

if(isset($_REQUEST['enable_api'])) {
	$userID = mysqli_real_escape_string($server,$_REQUEST['user']);
	if($userID < 1) { echo $LANG['Invalid API request!'].':0'; die(); }
	$key = genRandomPassword(32);			$token = genRandomPassword(4).time();
	mysqli_query($server, "UPDATE users SET api_key = '$key' WHERE id = '$userID'") or die(mysqli_error($server));
	mysqli_query($server, "UPDATE users SET api_token = '$token' WHERE id = '$userID'") or die(mysqli_error($server));
	logEvent($userID,'enabled API access');
	echo 'success:'.'0'; die();	
}

if(isset($_REQUEST['post_ticket'])) {
	$customer = mysqli_real_escape_string($server,$_REQUEST['customer']);
	$subject = mysqli_real_escape_string($server,$_REQUEST['subject']);
	$ticket = mysqli_real_escape_string($server,$_REQUEST['ticket']);
	$message = mysqli_real_escape_string($server,$_REQUEST['message']);
	$userID = mysqli_real_escape_string($server,$_REQUEST['user']);
	$admin_reply = 0;
	$customer_reply = 1;
	$date = date('Y-m-d H:i:s');
	$status = 'open';
	if($ticket > 0) {
		$status = 'customer-reply';	
	}
	if($customer != $userID) {
		$admin_reply = 1;
		$customer_reply = 0;
		$status = 'answered';
		if($ticket < 1) {
			$status = 'open';	
		}
	}

	if($userID < 1) { echo $LANG['Invalid API request!'].':0'; die(); }
	if(empty($subject)) { echo $LANG['Please give your ticket a subject'].':0'; die();}
	if(empty($message)) { echo $LANG['Please type some message to submit with your ticket'].':0'; die();}
	
	mysqli_query($server, "INSERT INTO tickets (`customer_id`,`admin_reply`, `customer_reply`, `subject`, `date`, `status`, `parent_id`, `last_updated`, `message`) VALUES ('$customer','$admin_reply', '$customer_reply', '$subject', '$date', '$status', '$ticket', '$date', '$message');") or die(mysqli_error($server));
	if($ticket > 0) {
		mysqli_query($server, "UPDATE tickets SET admin_reply = '$admin_reply' WHERE id = '$ticket'") or die(mysqli_error($server));
		mysqli_query($server, "UPDATE tickets SET customer_reply = '$customer_reply' WHERE id = '$ticket'") or die(mysqli_error($server));
		mysqli_query($server, "UPDATE tickets SET status = '$status' WHERE id = '$ticket'") or die(mysqli_error($server));
		mysqli_query($server, "UPDATE tickets SET last_updated = '$date' WHERE id = '$ticket'") or die(mysqli_error($server));
	}
	if($customer != $userID) {
		$email = userData($customer,'email');
		sendEmail(getSetting('smtpUsername'),getSetting('businessName').'','Re: '.$subject,$email,$mail);
	}
	echo 'success:'.'0'; die();	
}

//Create or update customer
if(isset($_REQUEST['add_customer'])) { 
	$role_id = '3';
	foreach ($_REQUEST as $key => $value ){
		${$key} = $value = mysqli_real_escape_string($server,$value);
	}
	$userID = $user;
	$min_order = round($min_order/userExchangeRate($userID),2);
	if(!isReseller($userID) && !isAdmin($userID)) {
		$message = $LANG['API feature not allowed'];
		buildJSONResponse($message,false,0);  die();
	}
	if(empty($first_name) || empty($last_name) || empty($email) || empty($phone)) {
		$message = $LANG['One or more required fields were not supplied'];
		buildJSONResponse($message,false,0);  die();
	}
	if(isAdmin($userID)) {
		$role_id = $role_id;	
	}
	if($customer_id > 0) {
		//update customer		
		$old_rate = userExchangeRate($customer_id);
		$new_rate = currencyRate($currency_id);
		$old_currency = userData('currency_id',$customer_id);
		if(!empty($password)) {
			$passwordStrong = checkPassword($password);
			if(!empty($passwordStrong)) {
				$message = $LANG[$passwordStrong];
				buildJSONResponse($message,false,0); die();
			} else {
				$timezone = countryTimeZone($country_id);
				mysqli_query($server, "UPDATE users SET 
									`first_name` = '$first_name' ,
									`last_name` = '$last_name' ,
									`country_id` = '$country_id' ,
									`currency_id` = '$currency_id' ,
									`timezone_id` = '$timezone' ,
									`min_order` = '$min_order' ,
									`no_tax` = '$no_tax' ,
									`email` = '$email' ,
									`phone` = '$phone' ,
									`role_id` = '$role_id',
									`address` = '$address' ,
									`city` = '$city' ,
									`email_verified` = '0' ,
									`default_sender_ID` = '$default_sender_ID',
									`phone_verified` = '0' ,
									`state` = '$state' 
				WHERE id = '$customer_id'") or die(mysqli_error($server));
				//change password
				$salt = genRandomPassword(32);
				$crypt = getCryptedPassword($password, $salt);
				$password2 = $crypt.':'.$salt;	
				mysqli_query($server, "UPDATE users SET password = '$password2' WHERE id = '$customer_id'");
				if($country_id != $old_currency) {
					//update all transactions
					mysqli_query($server, "UPDATE `transactions` SET `credits` =  `credits`/'$old_rate' WHERE `credits` != 0 AND `customer_id` = '$customer_id'");
					mysqli_query($server, "UPDATE `transactions` SET `cost` =  `cost`/'$old_rate' WHERE `cost` != 0 AND `customer_id` = '$customer_id'");
					//---
					mysqli_query($server, "UPDATE `transactions` SET `credits` =  `credits`*'$new_rate' WHERE `credits` != 0 AND `customer_id` = '$customer_id'");
					mysqli_query($server, "UPDATE `transactions` SET `cost` =  `cost`*'$new_rate' WHERE `cost` != 0 AND `customer_id` = '$customer_id'");
					//Update all message cost
					mysqli_query($server, "UPDATE `messagedetails` SET `cost` =  `cost`/'$old_rate' WHERE `cost` != 0 AND `customer_id` = '$customer_id'");
					//---
					mysqli_query($server, "UPDATE `messagedetails` SET `cost` =  `cost`*'$new_rate' WHERE `cost` != 0 AND `customer_id` = '$customer_id'");
				}
				$name = $first_name.' '.$last_name;
				$link_domain = home_base_url();
				if(!empty(getSetting('resellerDomain',$userID)))	{
					$link_domain = 'http://'.getSetting('resellerDomain',$userID);
				}
				$mail = 'Dear '.$name.'<br><br>Your '.getSetting('businessName',$userID).' account password has been recovered.<br>Your new password is '.$password.'.<br>Do let us know at once if you have not authorized or initiated this password change.<br><hr><br>Message sent from '.getSetting('businessName',$userID).'';
				$subject = 'Your New Account Password';
				if(!empty(getSetting('newPasswordEmail',$userID))) {
						$mail = getSetting('newPasswordEmail',$userID);
						$mail = strtr($mail, array("{name}" => $name, 
										"{email}" => $email,
										"{password}" => $password,
										"{company}" => getSetting('businessName',$userID),
										"{brand_name}" => getSetting('businessName',$userID),
										"{url}" => $link_domain,
										"{phone}" => $phone,
										"{amount}" => 0,
										"{balance}" => 0
										));	
						$subject = 	getSetting('newPasswordEmailSubject',$userID);				
						$subject = strtr($subject, array("{name}" => $name, 
										"{email}" => $email,
										"{password}" => $password,
										"{company}" => getSetting('businessName',$userID),
										"{brand_name}" => getSetting('businessName',$userID),
										"{url}" => $link_domain,
										"{phone}" => $phone,
										"{amount}" => 0,
										"{balance}" => 0
										));	
				}
				//create hook variables
				$vars = array(
							 "id"=>$customer_id, 
							 "email"=>$email,
							 "password"=>$password, 
							 "phone"=>$phone,
							 "first_name"=>$first_name, 
							 "last_name"=>$last_name
							 );
				$_SESSION['EventVals'] = $vars;
				sendEmail(getSetting('smtpUsername',$userID),getSetting('businessName',$userID).'',$subject,$email,$mail);
				global $hooks; $hooks->do_action('PasswordChange');
			}
		} else {
			$timezone = countryTimeZone($country_id);
			mysqli_query($server, "UPDATE users SET 
									`first_name` = '$first_name' ,
									`last_name` = '$last_name' ,
									`country_id` = '$country_id' ,
									`currency_id` = '$currency_id' ,
									`timezone_id` = '$timezone' ,
									`min_order` = '$min_order' ,
									`no_tax` = '$no_tax' ,
									`email` = '$email' ,
									`phone` = '$phone' ,
									`role_id` = '$role_id',
									`address` = '$address' ,
									`default_sender_ID` = '$default_sender_ID',
									`city` = '$city' ,
									`email_verified` = '0' ,
									`phone_verified` = '0' ,
									`state` = '$state' 
			WHERE id = '$customer_id'") or die(mysqli_error($server));
			
			if($country_id != $old_currency) {
					//update all transactions
					mysqli_query($server, "UPDATE `transactions` SET `credits` =  `credits`/'$old_rate' WHERE `credits` != 0 AND `customer_id` = '$customer_id'");
					mysqli_query($server, "UPDATE `transactions` SET `cost` =  `cost`/'$old_rate' WHERE `cost` != 0 AND `customer_id` = '$customer_id'");
					//---
					mysqli_query($server, "UPDATE `transactions` SET `credits` =  `credits`*'$new_rate' WHERE `credits` != 0 AND `customer_id` = '$customer_id'");
					mysqli_query($server, "UPDATE `transactions` SET `cost` =  `cost`*'$new_rate' WHERE `cost` != 0 AND `customer_id` = '$customer_id'");
					//Update all message cost
					mysqli_query($server, "UPDATE `messagedetails` SET `cost` =  `cost`/'$old_rate' WHERE `cost` != 0 AND `customer_id` = '$customer_id'");
					//---
					mysqli_query($server, "UPDATE `messagedetails` SET `cost` =  `cost`*'$new_rate' WHERE `cost` != 0 AND `customer_id` = '$customer_id'");
				}
		}
		buildJSONResponse('',true,$user_id); die();	
	} else {
		//create new
		$passwordStrong = checkPassword($password);
		if(!empty($passwordStrong)) {
			$message = $LANG[$passwordStrong];
			buildJSONResponse($message,false,0);  die();
		} 
		if(!checkEmailAddress($email)) {
			$message = $LANG['Invalid email address format'];
			buildJSONResponse($message,false,0); die();
		}
		$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) {
			$salt = genRandomPassword(32);
			$crypt = getCryptedPassword($password, $salt);
			$password2 = $crypt.':'.$salt;	
			$emIl_track = 0;	
			$phone_track = 0;	
			$referal = 0;
			$reseller = $userID;
			if(isAdmin($userID)) $reseller = 0;
			$currency_id = $currency_id; 
			$country_id = $country_id;
			
			$timezone = countryTimeZone($country_id);
			$affliliate = genRandomPassword(16);
			$date = date('Y-m-d H:i:s');
			if(isAdmin($userID)) {
				$role_id = $role_id;	
			}
			 mysqli_query($server, "INSERT INTO users (`first_name`, `last_name`, `email`, `password`, `currency_id`, `country_id`,`phone`, `phone_verified`,`email_verified`,`timezone_id`,`role_id`,`referrer`,`affiliate_id`, `date`,`reseller`, `min_order`, `no_tax`, `address`, `city`, `state`, `default_sender_ID`) 
			VALUES ('$first_name', '$last_name', '$email', '$password2', '$currency_id', '$country_id', '$phone','$phone_track','$email_track','$timezone','$role_id','$referal','$affliliate', '$date','$reseller', '$min_order', '$no_tax', '$address', '$city', '$state', '$default_sender_ID');") or die (mysqli_error($server));
			$user_id = mysqli_insert_id($server);	
			logEvent( $userID,"created a new customer with ID ".$user_id);		
			mysqli_query($server, "UPDATE  `users` SET  `last_login` =  '".time()."' WHERE `id` ='$user_id'");
			
			$link_domain = home_base_url();
			if(!empty(getSetting('resellerDomain',$userID)))	{
				$link_domain = 'http://'.getSetting('resellerDomain',$userID);
			}
			//send verification code
			$mail = "<h2 align='center'>Welcome to ".getSetting('businessName',$userID)."</h2>";
			$mail .= "<hr>";
			$mail .= "<p align='center'>Your ".getSetting('businessName',$userID)." 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="'.$link_domain.'"><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',$userID);
			
			if(!empty(getSetting('newAccountEmail',$userID))) {
				$mail = getSetting('newAccountEmail',$userID);
				$mail = strtr($mail, array("{name}" => $first_name.' '.$last_name, 
								"{email}" => $email,
								"{password}" => $password,
								"{company}" => getSetting('businessName',$userID),
								"{brand_name}" => getSetting('businessName',$userID),
								"{url}" => $link_domain,
								"{phone}" => $phone,
								"{amount}" => 0,
								"{balance}" => 0
								));	
				$subject = 	getSetting('newAccountEmailSubject',$userID);				
				$subject = strtr($subject, array("{name}" => $first_name.' '.$last_name, 
								"{email}" => $email,
								"{password}" => $password,
								"{company}" => getSetting('businessName',$userID),
								"{brand_name}" => getSetting('businessName',$userID),
								"{url}" => $link_domain,
								"{phone}" => $phone,
								"{amount}" => 0,
								"{balance}" => 0
								));	
			}
			//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;
									
			$sender = getSetting('businessName',$userID);
			$from = getSetting('smtpUsername',$userID);
					
			sendEmail($from,$sender,$subject,$email,$mail);
			sendWelcomeSMS($user_id);
			global $hooks; $hooks->do_action('CustomerCreate');
			buildJSONResponse('',true,$user_id); die();
		} else {
			buildJSONResponse($LANG['A user already exisit with the email address you entered'],false,0); die();
		}				
	}
	die();
}

//update or create custom rate
if(isset($_REQUEST['add_rate'])) {
	$rate = correctNumber(mysqli_real_escape_string($server,$_REQUEST['rate']));
	$customer = mysqli_real_escape_string($server,$_REQUEST['customer']);
	$country = mysqli_real_escape_string($server,$_REQUEST['country']);
	$country_code = countryPhoneCode($country);
	$operator = correctNumber(mysqli_real_escape_string($server,$_REQUEST['operator']));
	$operator_code = ltrim($operator, '0');
	$gateway = mysqli_real_escape_string($server,$_REQUEST['gateway']);
	$type = mysqli_real_escape_string($server,$_REQUEST['type']);
	$userID = mysqli_real_escape_string($server,$_REQUEST['user']);
	
	if(!isReseller($userID) && !isAdmin($userID)) {
		echo $LANG['API feature not allowed'].':0'; die();
	}
	if($userID==$customer) {
		echo $LANG['Invalid API request!'].':0'; die();
	}
	if(isAdmin($userID)) {
		$userID = 0;
	} else {
		$rate = round($rate/userExchangeRate($userID),4);
	}
	//check if operator is ok
	if($operator_code < 0) {
		echo $LANG['Please provide a valid operator prefix'].':0'; die();
	}
	//check if rate exits
	$id = rateExist($customer,$country_code,$operator_code,$type,$userID);
	if($id > 0) {	
		mysqli_query($server, "UPDATE `rates` SET `rate` =  '$rate' WHERE `id` = '$id'");
		logEvent($userID,'updated sms rate #').$id;
		echo 'success:'.'0'; die();	
	} else {
		mysqli_query($server, "INSERT INTO rates (`customer_id`, `country_code`,`operator_code`, `rate`, `gateway_id`, `type`, `reseller_id`) VALUES ('$customer', '$country_code','$operator_code', '$rate', '$gateway', '$type', '$userID');") or die(mysqli_error($server));
		logEvent($userID,'Created a new sms rate');
		echo 'success:'.'0'; die();	
	}
	die();
}

if(isset($_REQUEST['add_route'])) {
	$customer_id = mysqli_real_escape_string($server,$_REQUEST['customer_id']);
	$country = mysqli_real_escape_string($server,$_REQUEST['country']);
	$country_code = countryPhoneCode($country);
	$operator = correctNumber(mysqli_real_escape_string($server,$_REQUEST['operator']));
	$operator_code = ltrim($operator, '0');
	$gateway_id = mysqli_real_escape_string($server,$_REQUEST['gateway_id']);
	$type = smsGatewayData(mysqli_real_escape_string($server,$_REQUEST['gateway_id']),'type');
	$group_id = mysqli_real_escape_string($server,$_REQUEST['group_id']);
	$userID = mysqli_real_escape_string($server,$_REQUEST['user']);
	
	
	if(!isAdmin($userID)) {
		echo $LANG['API feature not allowed'].':0'; die();
	}
	
	//check if operator is ok
	if($operator_code < 0) {
		echo $LANG['Please provide a valid operator prefix'].':0'; die();
	}
	if($gateway_id < 1) {
		echo $LANG['Please select a gateway'].':0'; die();
	}
	//check if rate exits
	$id = routeExist($customer_id,$country_code,$operator_code,$type,$group_id);
	if($id > 0) {	
		mysqli_query($server, "UPDATE `routes` SET `gateway_id` =  '$gateway_id' WHERE `id` = '$id'");
		logEvent($userID,'updated sms rate #').$id;
		echo 'success:'.'0'; die();	
	} else {
		mysqli_query($server, "INSERT INTO routes (`customer_id`, `country_code`,`operator_code`, `gateway_id`, `type`, `group_id`) VALUES ('$customer_id', '$country_code','$operator_code', '$gateway_id', '$type', '$group_id');") or die(mysqli_error($server));
		logEvent($userID,'Created a new routing rule');
		echo 'success:'.'0'; die();	
	}
	die();
}


if(isset($_REQUEST['upload_customer'])) {
	$files = mysqli_real_escape_string($server,$_REQUEST['files']);
	$userID = mysqli_real_escape_string($server,$_REQUEST['user']);
	if(!isReseller($userID) && !isAdmin($userID)) {
		echo $LANG['API feature not allowed'].':0'; die();
	}
	if($userID < 1) { echo $LANG['Invalid API request!'].':0'; die(); }
	if(isAdmin($userID)) {
		$userID = 0;
	}
	if(!empty($files)) {
		$done = importCustomers($files,$userID);
		if($done=='ok') {
			echo 'success:'.'0'; die();	
			logEvent($userID,'imported customer records from file');
		} else {
			echo $LANG['Unable to load customers from file'].':0'; die(); 
		}
	} 
	echo $LANG['Unable to load customers from file'].':0'; die(); 
}

//Save settings
if(isset($_REQUEST['save_settings'])) {
	foreach ($_REQUEST as $key => $value ){
		${$key} = $value = mysqli_real_escape_string($server,$value);
	}
	$userID = $user;
	if(!isReseller($userID) && !isAdmin($userID)) {
		$message = $LANG['API feature not allowed'].':0'; 
		buildJSONResponse($message,false,0); die();
	}
	if($userID < 1) { $message = $LANG['Invalid API request!'].':0'; buildJSONResponse($message,false,0);  die();}
	if(isAdmin($userID)) {
		$userID = 0;
		$timeZone = countryTimeZone($defaultCountry);
		mysqli_query($server, "UPDATE settings SET `value` = '$timeZone' WHERE `field` = 'timeZone' AND customer_id = 0");
		mysqli_query($server, "UPDATE currencies SET `rate` = '1' WHERE `id` = '$defaultCurrency'");
	}
	foreach ($_REQUEST as $field => $value ){
		if($field !='save_settings' && $field !='user' && $field !='url') {
			$value = mysqli_real_escape_string($server,$value);
			saveSettings($field,$value,$userID);
		}
	}
	logEvent($userID,'Updated system settings');
	systemInformation();	
	buildJSONResponse('',true,$user_id); die();
}

if(isset($_REQUEST['update_push'])) {
	foreach ($_REQUEST as $key => $value ){
		${$key} = $value = mysqli_real_escape_string($server,$value);
	}
	$userID = $user;
	if(!isReseller($userID) && !isAdmin($userID)) {
		$message = $LANG['API feature not allowed']; 
		echo $message; die();
	}
	if(strlen($pushTitle)>30) {
		$message = $LANG['Your Headings should not be more than 30 characters']; 
		echo $message; die();
	}
	if(isAdmin($userID)) {
		$userID = 0;
	}
	saveSettings('pushTitle',$pushTitle,$userID);
	saveSettings('pushFor',$pushFor,$userID);
	saveSettings('pushPages',$pushPages,$userID);
	saveSettings('pushMessage',$pushMessage,$userID);
	
	logEvent($userID,'Updated puch notification settings');
	echo 'success'; die();
}


//Create vouchers
if(isset($_REQUEST['add_voucher'])) {
	foreach ($_REQUEST as $key => $value ){
		${$key} = $value = mysqli_real_escape_string($server,$value);
	}
	$userID = $user;
	if(!isReseller($userID) && !isAdmin($userID)) {
		echo $LANG['API feature not allowed'].':0'; die();
	}
	if($userID < 1) { echo $LANG['Invalid API request!'].':0'; die(); }
	if(isAdmin($userID)) {
		$userID = 0;
	} else {
		$cost = round($cost/userExchangeRate($userID),4);
		$credit = round($credit/userExchangeRate($userID),4);	
	}
	$x = 1; 
	while($x <= $quantity) {
		$pin = rand(100000,999999).rand(100000,999999).rand(100000,999999);
		mysqli_query($server, "INSERT INTO vouchers (`customer_id`, `pin`,`cost`, `credits`, `validity`, `used`) VALUES ('$userID', '$pin','$cost', '$credit', '$validity', '0');") or die(mysqli_error($server));
		$x++;
	} 	
	logEvent($userID,'Created new sms vouchers');
	echo 'success:'.'0'; die();	
}

//Create sms plans
if(isset($_REQUEST['add_plan'])) {
	foreach ($_REQUEST as $key => $value ){
		${$key} = $value = mysqli_real_escape_string($server,$value);
	}
	$userID = $user;
	if(!isReseller($userID) && !isAdmin($userID)) {
		echo $LANG['API feature not allowed'].':0'; die();
	}
	if($userID < 1) { echo $LANG['Invalid API request!'].':0'; die(); }
	if(isAdmin($userID)) {
		$userID = 0;
	} else {
		$cost = round($cost/userExchangeRate($userID),4);
		$credit = round($credit/userExchangeRate($userID),4);	
	}
		mysqli_query($server, "INSERT INTO sms_plans (`customer_id`, `title`,`price`, `credits`, `validity`, `recommend`) VALUES ('$userID', '$name','$cost', '$credit', '$validity', '0');") or die(mysqli_error($server));
	logEvent($userID,'Created new sms plan');
	echo 'success:'.'0'; die();	
}

if(isset($_REQUEST['load_sms_gateways'])) {
	foreach ($_REQUEST as $key => $value ){
		${$key} = $value = mysqli_real_escape_string($server,$value);
	}
	$userID = getUser();
	if(!isAdmin($userID)) {
		echo $LANG['API feature not allowed'].':0'; die();
	}
	echo loadSMSGatewayParams($id); die();
}

//load sms gateway templates
if(isset($_REQUEST['load_sms_gateway_temp'])) {
	foreach ($_REQUEST as $key => $value ){
		${$key} = $value = mysqli_real_escape_string($server,$value);
	}
	$userID = getUser();
	if(!isAdmin($userID)) {
		echo $LANG['API feature not allowed'].':0'; die();
	}
	$query="SELECT * FROM api_templates WHERE id = '$load_sms_gateway_temp'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	echo json_encode(mysqli_fetch_assoc($result));
	die();
}
//add sms gateway
if(isset($_REQUEST['add_sms_gateway'])) {
	foreach ($_REQUEST as $key => $value ){
		${$key} = $value = mysqli_real_escape_string($server,$value);
	}
	$userID = $user;
	if(!isAdmin($userID)) {
		echo $LANG['API feature not allowed'].':0'; die();
	}
	if($userID < 1) { echo $LANG['Invalid API request!'].':0'; die(); }
	if(empty($title)) { echo $LANG['Please type a display name for your new gateway!'].':0'; die(); }
	
	if(empty($message_field)) { echo $LANG['Message Parameter Name is required!'].':0'; die(); }
	if(empty($recipient_field)) { echo $LANG['To Parameter Name is required!'].':0'; die(); }
	
	$tempName = smsGatewayTemplateData($alias,'title');
	if(empty($tempName)) { echo $LANG['Please select a valid gateway template!'].':0'; die(); }
	
	$alias = smsGatewayTemplateData($alias,'alias') ;	
	if($alias=='custom' && !empty($cusType)) $type = $cusType;
	
	if($gateway_id < 1) {
		mysqli_query($server, "INSERT INTO sms_gateways (`param1_value`, `param2_value`,`param3_value`,`param4_value`, `param1_field`,`param2_field`, `param3_field`, `param4_field`, `request_type`, `base_url`, `success_word`, `success_logic`, `authentication`, `username`, `password`, `sender_field`, `recipient_field`,`message_field`, `audio_field`, `timeout_field`, `json_encode`, `type`, `alias`, `cutting_limit`, `cutting_percent`, `hour_limit`, `title`, `balance_url`, `base64_encode`) 
							 					 VALUES ('$param1_value', '$param2_value','$param3_value', '$param4_value', '$param1_field', '$param2_field', '$param3_field', '$param4_field', '$request_type', '$base_url', '$success_word', '$success_logic', '$authentication', '$username', '$password', '$sender_field','$recipient_field', '$message_field', '$audio_field', '$timeout_field', '$json_encode', '$type', '$alias', '$cutting_limit', '$cutting_percent', '$hour_limit', '$title', '$balance_url', '$base64_encode');") or die(mysqli_error($server));
							  
		logEvent($userID,'Created new SMS gateway');
		echo 'success:'.'0'; die();		
	} else {
		mysqli_query($server, "UPDATE sms_gateways SET 
									`param1_value` = '$param1_value' ,
									`param2_value` = '$param2_value' ,
									`param3_value` = '$param3_value' ,
									`param4_value` = '$param4_value' ,
									`param1_field` = '$param1_field' ,
									`param2_field` = '$param2_field' ,
									`param3_field` = '$param3_field' ,
									`param4_field` = '$param4_field' ,
									`request_type` = '$request_type' ,
									`base_url` = '$base_url' ,
									`balance_url` = '$balance_url',
									`success_word` = '$success_word' ,
									`success_logic` = '$success_logic' ,
									`authentication` = '$authentication' ,
									`username` = '$username' ,
									`password` = '$password' ,
									`sender_field` = '$sender_field' ,
									`recipient_field` = '$recipient_field' ,
									`message_field` = '$message_field' ,
									`audio_field` = '$audio_field' ,
									`timeout_field` = '$timeout_field' ,
									`json_encode` = '$json_encode' ,
									`type` = '$type' ,
									`alias` = '$alias' ,
									`cutting_limit` = '$cutting_limit' ,
									`cutting_percent` = '$cutting_percent' ,
									`hour_limit` = '$hour_limit' ,
									`base64_encode` = '$base64_encode',
									`title` = '$title' 
			WHERE id = '$gateway_id'") or die(mysqli_error($server));
		echo 'success:'.'0'; die();			
	}
	die();
}
//do upgrades
if(isset($_REQUEST['do_upgrade'])) {
	$userID = getUser();
	if(!isAdmin($userID)) {
		echo $LANG['API feature not allowed'].':0'; die();
	}	
	 echo upgradeToLatest(); die();
}

if(isset($_REQUEST['do_update'])) {
	$userID = getUser();
	if(!isAdmin($userID)) {
		echo $LANG['API feature not allowed'].':0'; die();
	}	
	echo updateToLatest(); die();
}
if(isset($_REQUEST['update_license'])) {
	foreach ($_REQUEST as $key => $value ){
		${$key} = $value = mysqli_real_escape_string($server,$value);
	}
	$userID = getUser();
	if(!isAdmin($userID)) {
		echo $LANG['API feature not allowed'].':0'; die();
	}	
	echo updateMyLicense($license); die();
}

//load gateway templates
if(isset($_REQUEST['load_pay_gateway_temp'])) {
	foreach ($_REQUEST as $key => $value ){
		${$key} = $value = mysqli_real_escape_string($server,$value);
	}
	$userID = getUser();
	if(!isReseller($userID) && !isAdmin($userID)) {
		echo $LANG['API feature not allowed'].':0'; die();
	}
	$query="SELECT * FROM paymentgateway_templates WHERE alias = '$load_pay_gateway_temp'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	echo $row['param1_label'].':'.$row['param2_label'].':'.$row['param3_label'];	die();
}

//Create payment gateway
if(isset($_REQUEST['add_gateway'])) {
	foreach ($_REQUEST as $key => $value ){
		${$key} = $value = mysqli_real_escape_string($server,$value);
	}
	$userID = $user;
	if(!isReseller($userID) && !isAdmin($userID)) {
		echo $LANG['API feature not allowed'].':0'; die();
	}
	if($userID < 1) { echo $LANG['Invalid API request!'].':0'; die(); }
	if(empty($gtitle)) { echo $LANG['Please type a display name for your new gateway!'].':0'; die(); }
	$tempName = paymentGatewayTemplateData($gtype,'title');
	if(empty($tempName)) { echo $LANG['Please select a valid gateway template!'].':0'; die(); }
	if(isAdmin($userID)) {
		$userID = 0;
	} else {
		if($minimum_order>0) $minimum_order = round($minimum_order/userExchangeRate($userID),4);
		if($charges_fix>0) $charges_fix = round($charges_fix/userExchangeRate($userID),4);	
	}
	if($charge_type=='fixed') $charges_perc = 0.00;
	if($charge_type=='percent') $charges_fix = 0.00;
	$currency_id = paymentGatewayTemplateData($gtype,'currency_id');
	if($currency_id<1) {
		$currency_id = currencyCode(getSetting('defaultCurrency',$userID));
	}
	if($gateway_id < 1) {
		mysqli_query($server, "INSERT INTO paymentgateways (`customer_id`, `title`,`type`, `enabled`, `text`, `param1`, `param2`, `param3`, `currency_id`, `minimum_order`, `charges_perc`, `charges_fix`) VALUES ('$userID', '$gtitle','$gtype', '$genabled', '$text', '$param1', '$param2', '$param3', '$currency_id', '$minimum_order', '$charges_perc', '$charges_fix');") or die(mysqli_error($server));
		logEvent($userID,'Created new payment gateway');
		echo 'success:'.'0'; die();		
	} else {
		if(paymentGatewayData($gateway_id,'customer_id')!= $userID) { echo $LANG['Invalid API request!'].':0'; die(); }
		mysqli_query($server, "UPDATE paymentgateways SET 
									`title` = '$gtitle' ,
									`type` = '$gtype' ,
									`enabled` = '$genabled' ,
									`text` = '$text' ,
									`param1` = '$param1' ,
									`param2` = '$param2' ,
									`param3` = '$param3' ,
									`currency_id` = '$currency_id' ,
									`minimum_order` = '$minimum_order' ,
									`charges_perc` = '$charges_perc' ,
									`charges_fix` = '$charges_fix' 
			WHERE id = '$gateway_id'") or die(mysqli_error($server));
		echo 'success:'.'0'; die();			
	}
	die();
}

//add currency
if(isset($_REQUEST['add_currency'])) {
	foreach ($_REQUEST as $key => $value ){
		${$key} = $value = mysqli_real_escape_string($server,$value);
	}
	$userID = $user;
	if(!isAdmin($userID)) {
		echo $LANG['API feature not allowed'].':0'; die();
	}
	if($userID < 1) { echo $LANG['Invalid API request!'].':0'; die(); }
	if(empty($title) || empty($rate) || empty($code) || empty($symbul)) { echo $LANG['All fields must have a value'].':0'; die(); }
	$rate = correctNumber($rate);
	if($currency_id < 1) {
		mysqli_query($server, "INSERT INTO currencies (`title`, `code`,`rate`, `symbul`) VALUES ('$title', '$code','$rate', '$symbul');") or die(mysqli_error($server));
		logEvent($userID,'Created new currency');
		echo 'success:'.'0'; die();		
	} else {
		mysqli_query($server, "UPDATE currencies SET 
									`title` = '$title' ,
									`code` = '$code' ,
									`rate` = '$rate' ,
									`symbul` = '$symbul' 
			WHERE id = '$currency_id'") or die(mysqli_error($server));
		echo 'success:'.'0'; die();			
	}
	die();
}


//Update Profile
if(isset($_REQUEST['update_profile'])) { 
	foreach ($_REQUEST as $key => $value ){
		${$key} = $value = mysqli_real_escape_string($server,$value);
	}
	$userID = $user;

	if(empty($first_name) || empty($last_name) || empty($email) || empty($phone)) {
		$message = $LANG['One or more required fields were not supplied'];
		buildJSONResponse($message,false,0);  die();
	}

	if($customer_id > 0) {
		//update customer		
		$old_rate = userExchangeRate($customer_id);
		$new_rate = currencyRate($currency_id);
		$old_currency = userData('currency_id',$customer_id);
						
		if(!empty($password)) {
			$passwordStrong = checkPassword($password);
			if(!empty($passwordStrong)) {
				$message = $LANG[$passwordStrong];
				buildJSONResponse($message,false,0); die();
			} else {
				$timezone = countryTimeZone($country_id);
				mysqli_query($server, "UPDATE users SET 
									`first_name` = '$first_name' ,
									`last_name` = '$last_name' ,
									`country_id` = '$country_id' ,
									`currency_id` = '$currency_id' ,
									`timezone_id` = '$timezone' ,
									`email` = '$email' ,
									`phone` = '$phone' ,
									`photo` = '$photo' ,
									`address` = '$address' ,
									`city` = '$city' ,
									`state` = '$state' 
				WHERE id = '$customer_id'") or die(mysqli_error($server));
				//change password
				$salt = genRandomPassword(32);
				$crypt = getCryptedPassword($password, $salt);
				$password2 = $crypt.':'.$salt;	
				mysqli_query($server, "UPDATE users SET password = '$password2' WHERE id = '$customer_id'");
				
				
				if($country_id != $old_currency) {
					//update all transactions
					mysqli_query($server, "UPDATE `transactions` SET `credits` =  `credits`/'$old_rate' WHERE `credits` != 0 AND `customer_id` = '$customer_id'");
					mysqli_query($server, "UPDATE `transactions` SET `cost` =  `cost`/'$old_rate' WHERE `cost` != 0 AND `customer_id` = '$customer_id'");
					//---
					mysqli_query($server, "UPDATE `transactions` SET `credits` =  `credits`*'$new_rate' WHERE `credits` != 0 AND `customer_id` = '$customer_id'");
					mysqli_query($server, "UPDATE `transactions` SET `cost` =  `cost`*'$new_rate' WHERE `cost` != 0 AND `customer_id` = '$customer_id'");
					//Update all message cost
					mysqli_query($server, "UPDATE `messagedetails` SET `cost` =  `cost`/'$old_rate' WHERE `cost` != 0 AND `customer_id` = '$customer_id'");
					//---
					mysqli_query($server, "UPDATE `messagedetails` SET `cost` =  `cost`*'$new_rate' WHERE `cost` != 0 AND `customer_id` = '$customer_id'");
				}
				$name = $first_name.' '.$last_name;
				$link_domain = home_base_url();
				if(!empty(getSetting('resellerDomain')))	{
					$link_domain = 'http://'.getSetting('resellerDomain');
				}
				$mail = 'Dear '.$name.'<br><br>Your '.getSetting('businessName').' account password has been recovered.<br>Your new password is '.$password.'.<br>Do let us know at once if you have not authorized or initiated this password change.<br><hr><br>Message sent from '.getSetting('businessName').'';
				$subject = 'Your New Account Password';
				if(!empty(getSetting('newPasswordEmail'))) {
						$mail = getSetting('newPasswordEmail');
						$mail = strtr($mail, array("{name}" => $name, 
										"{email}" => $email,
										"{password}" => $password,
										"{company}" => getSetting('businessName'),
										"{url}" => $link_domain,
										"{phone}" => $phone,
										"{amount}" => 0,
										"{balance}" => 0
										));	
						$subject = 	getSetting('newPasswordEmailSubject');				
						$subject = strtr($subject, array("{name}" => $name, 
										"{email}" => $email,
										"{password}" => $password,
										"{company}" => getSetting('businessName'),
										"{url}" => $link_domain,
										"{phone}" => $phone,
										"{amount}" => 0,
										"{balance}" => 0
										));	
				}
				//create hook variables
				$vars = array(
							 "id"=>$customer_id, 
							 "email"=>$email,
							 "password"=>$password, 
							 "phone"=>$phone,
							 "first_name"=>$first_name, 
							 "last_name"=>$last_name
							 );
				$_SESSION['EventVals'] = $vars;
				sendEmail(getSetting('smtpUsername'),getSetting('businessName').'',$subject,$email,$mail);
				sendNewpasswordSMS($customer_id,$password);
				global $hooks; $hooks->do_action('PasswordChange');
			}
		} else {
			$timezone = countryTimeZone($country_id);
			mysqli_query($server, "UPDATE users SET 
									`first_name` = '$first_name' ,
									`last_name` = '$last_name' ,
									`country_id` = '$country_id' ,
									`currency_id` = '$currency_id' ,
									`timezone_id` = '$timezone' ,
									`phone` = '$phone' ,
									`photo` = '$photo' ,
									`address` = '$address' ,
									`city` = '$city' ,
									`state` = '$state' 
			WHERE id = '$customer_id'") or die(mysqli_error($server));
		}

		if($country_id != $old_currency) {
			//update all transactions
			mysqli_query($server, "UPDATE `transactions` SET `credits` =  `credits`/'$old_rate' WHERE `credits` != 0 AND `customer_id` = '$customer_id'");
			mysqli_query($server, "UPDATE `transactions` SET `cost` =  `cost`/'$old_rate' WHERE `cost` != 0 AND `customer_id` = '$customer_id'");
			//---
			mysqli_query($server, "UPDATE `transactions` SET `credits` =  `credits`*'$new_rate' WHERE `credits` != 0 AND `customer_id` = '$customer_id'");
			mysqli_query($server, "UPDATE `transactions` SET `cost` =  `cost`*'$new_rate' WHERE `cost` != 0 AND `customer_id` = '$customer_id'");
			//Update all message cost
			mysqli_query($server, "UPDATE `messagedetails` SET `cost` =  `cost`/'$old_rate' WHERE `cost` != 0 AND `customer_id` = '$customer_id'");
			//---
			mysqli_query($server, "UPDATE `messagedetails` SET `cost` =  `cost`*'$new_rate' WHERE `cost` != 0 AND `customer_id` = '$customer_id'");
		}
		logEvent($userID,'Updated account profile');
		buildJSONResponse('',true,$user_id); die();	
	}
	die();
}

//credit customers account
if(isset($_REQUEST['credit_customer'])) {
	$cost = correctNumber(mysqli_real_escape_string($server,$_REQUEST['credits']));
	if(mysqli_real_escape_string($server,$_REQUEST['credits'])<1) {
	    $cost = mysqli_real_escape_string($server,$_REQUEST['credits']);
	}
	$customer_id = mysqli_real_escape_string($server,$_REQUEST['customer_id']);
	$userID = mysqli_real_escape_string($server,$_REQUEST['user']);
	$password = mysqli_real_escape_string($server,$_REQUEST['password']);
	
	if($userID < 1) { echo $LANG['Invalid API request!'].':0'; die(); }
	if(empty($cost)) { echo $LANG['You have not supplied a valid amount of credit to add'].':0'; die();}
	if(!isReseller($userID) && !isAdmin($userID)) {
		echo $LANG['API feature not allowed'].':0'; die();
	}
	
	$query="SELECT * FROM users WHERE id = '$userID'"; 
	$result = mysqli_query($server,$query);  
	$row = mysqli_fetch_assoc($result); 
	$pwsalt = explode( ":",$row["password"]);	
	$pass2 = $row["password"];		
	if(md5($password . $pwsalt[1]) != $pwsalt[0] && md5($password) != $row["password"]) { echo $LANG['The password you entered is not valid'].':0'; die();}
	
	$date = date('Y-m-d H:i:s', time());										$user_id = $customer_id;
	$description = 'Credits added by admin';									$credits = 0+$cost;
	$description = mysqli_real_escape_string($server,$description);
	$method = 'admin';															$cost = 0;
	$reference = genRandomPassword(6).time();							$gateway_response = '';
	$approved_by = 'Admin';								$is_earned = '0';
	$status = 'completed';								$validity = 0;
	
	mysqli_query($server, "INSERT INTO transactions (`date`,`customer_id`, `description`, `credits`, `cost`,`method`,`transaction_reference`,`approved_by`,`status`, `gateway_response`, `is_earned`, `validity`)	VALUES ('$date','$user_id', '$description', '$credits', '$cost','$method','$reference','$approved_by','$status', '$gateway_response', '$is_earned', '$validity');") or die (mysqli_error($server));
	createNotice($customer_id,"Admin added ".$credits." SMS credits to you!");
	logEvent($userID,'Added '.$credits.' credits to user ID '.$customer_id);
	echo 'success:'.'0'; die();	
}

//save shortcofde
if(isset($_REQUEST['add_shortcode'])) {
	$is_public = 0;
	$date = date('Y-m-d H:i:s', time());
	$billing = 1;
	foreach ($_REQUEST as $key => $value ){
		${$key} = $value = mysqli_real_escape_string($server,$value);
	}
	$userID = $user;
	$shortcode = alterPhone($shortcode);
	if(!isAdmin($userID)) {
		echo $LANG['API feature not allowed'].':0'; die();
	}
	if($userID < 1) { echo $LANG['Invalid API request!'].':0'; die(); }
	if(empty($shortcode)) { echo $LANG['Please provide a valid shortcode'].':0'; die(); }
	
	if($customer_id < 1 && $price == 0) {
		$is_public = 1;
	}
	
	if($shortcode_id < 1) {
		mysqli_query($server, "INSERT INTO shortcodes (`customer_id`, `shortcode`,`cost`, `billing`, `is_public`, `date`) VALUES ('$customer_id', '$shortcode','$price', '$billing', '$is_public', '$date');") or die(mysqli_error($server));
		logEvent($userID,'Created new shortcode');
		echo 'success:'.'0'; die();		
	} else {
		mysqli_query($server, "UPDATE shortcodes SET 
									`customer_id` = '$customer_id' ,
									`shortcode` = '$shortcode' ,
									`cost` = '$price' ,
									`billing` = '$billing' ,
									`is_public` = '$is_public' 
			WHERE id = '$shortcode_id'") or die(mysqli_error($server));
		echo 'success:'.'0'; die();			
	}
	die();
}

//save banned stuffs
if(isset($_REQUEST['add_banned'])) {	
	foreach ($_REQUEST as $key => $value ){
		${$key} = $value = mysqli_real_escape_string($server,$value);
	}
	$userID = $user;
	if(!isAdmin($userID)) {
		echo $LANG['API feature not allowed'].':0'; die();
	} else {
		$userID = 0;	
	}
	if(empty($ip) && empty($email) && empty($country) && empty($sender) && empty($word)) { echo $LANG['You have not supplied any thing to ban'].':0'; die(); }
	
	if($reason == '') {
		$reason = 'Not specified';
	}
	
	if(!empty($ip)) {
		mysqli_query($server, "INSERT INTO fobidden_ip (`customer_id`, `ip`,`reason`) VALUES ('$userID', '$ip','$reason')") or die(mysqli_error($server));
		logEvent($userID,'Created a banned IP: '.$ip);
		echo 'success:'.'0'; die();		
	}
	if(!empty($email)) {
		mysqli_query($server, "INSERT INTO fobidden_email (`customer_id`, `email`,`reason`) VALUES ('$userID', '$email','$reason')") or die(mysqli_error($server));
		logEvent($userID,'Created a banned email: '.$email);
		echo 'success:'.'0'; die();		
	}
	if(!empty($sender)) {
		mysqli_query($server, "INSERT INTO fobidden_sender (`customer_id`, `sender_id`,`reason`) VALUES ('$userID', '$sender','$reason')") or die(mysqli_error($server));
		logEvent($userID,'Created a banned sender ID: '.$sender);
		echo 'success:'.'0'; die();		
	}
	if(!empty($country)) {
		mysqli_query($server, "INSERT INTO forbidden_country (`customer_id`, `country_id`,`reason`) VALUES ('$userID', '$country','$reason')") or die(mysqli_error($server));
		logEvent($userID,'Created a banned country: '.$country);
		echo 'success:'.'0'; die();		
	}
	if(!empty($word)) {
		mysqli_query($server, "INSERT INTO forbidden_words (`customer_id`, `word`,`reason`) VALUES ('$userID', '$word','$reason')") or die(mysqli_error($server));
		logEvent($userID,'Created a banned IP: '.$word);
		echo 'success:'.'0'; die();		
	}	
	die();
}

//install mule
if(isset($_REQUEST['install_module'])) {	
	foreach ($_REQUEST as $key => $value ){
		${$key} = $value = mysqli_real_escape_string($server,$value);
	}
	$userID = $user;
	if(!isAdmin($userID)) {
		echo $LANG['API feature not allowed'].':0'; die();
	}
	if(empty($module)) {
		echo $LANG['You have not uploaded any module'].':0'; die();
	}
	$local_file = 'files/temporally_files/'.$module;
	if(!is_readable($local_file)) {
		echo $LANG['Unable to read module file'].':0'; die();
	}
	$tempF = time();
	unzip($local_file,'files/temporally_files/'.$tempF.'/', true, true);
	$manifest = file_get_contents('files/temporally_files/'.$tempF.'/Manifest.txt'); 
	deleteDir('files/temporally_files/'.$tempF);
	if(empty($manifest)) {
		echo $LANG['Invalid module manifest file'].':0'; die();
	} 
	$data = simplexml_load_string($manifest);
	$name = $data->name;
	$author = $data->author;
	$type = $data->type;
	$type = strtolower($type);
	$privileges = $data->privileges;
	if(empty($name) || empty($type)) { 
		echo $LANG['Invalid module'].':0'; die(); 
	}
	if($type != 'sms' && $type != 'system' && $type != 'payment' && $type != 'language') {
		echo $LANG['Unknown module type. Please contact the author'].':0'; die();
	}
	if(moduleExist($name,$author,$type)) {
		echo $LANG['The uploaded module is already installed on your system'].':0'; die();
	}
	$module_id = $alias = preg_replace("/[^A-Za-z0-9 ]/", '', $name);
	$module_id = $alias = strtolower(str_replace(' ','',$module_id));
	if($type=='sms') {
		$dir = "smsapi/";
		$table = 'api_templates';
	} else if($type=='payment') {
		$dir = "gateway/";
		$table = 'paymentgateway_templates';
	} else if($type=='language') {
		$dir = "system/lang/";
		$table = 'language';
	} else {
		$dir = "system/modules/";
		$table = 'modules';
	}

	if(file_exists($dir.$module_id)) {
		$module_id = $alias = time().$alias;
	}
	if($type=='language') {
		$tempF = time();
		unzip($local_file,'files/temporally_files/'.$tempF.'/', true, true);
		if (!copy('files/temporally_files/'.$tempF.'/index.php', 'system/lang/'.$alias.'.php')) {
			deleteDir('files/temporally_files/'.$tempF);
			echo $LANG['Something went wrong while installing the module'].':0'; die();
		}
		deleteDir('files/temporally_files/'.$tempF);
	} else {
		mkdir($dir.$alias, 0777, true);
		if(!unzip($local_file, $dir.$alias.'/', true, true)) {
			echo $LANG['Something went wrong while installing the module'].':0'; die();
		}
	}
	$lastID = getLastID($table);
	if(file_exists($dir.$alias.'/'.'sql.php')) { include($dir.$alias.'/'.'sql.php'); } 
	mysqli_query($server, "INSERT INTO modules (`title`, `url`,`privileges`, `status`, `author`, `type`, `module_id`) VALUES ('$name', '$alias','$privileges','0', '$author', '$type', '$module_id')") or die(mysqli_error($server));
	$nowID = getLastID($table);
	if(($lastID < $nowID) && $type != 'system') {
		mysqli_query($server,"UPDATE `".$table."` SET module_id = '$module_id' WHERE `id` = '$nowID'") or die(mysqli_error($server));
		mysqli_query($server,"UPDATE `".$table."` SET alias = '$module_id' WHERE `id` = '$nowID'") or die(mysqli_error($server));
	}
	if(file_exists($dir.$alias.'/'.'eventhook.php')) {
		copy('files/temporally_files/'.$tempF.'/eventhooks.php', 'system/eventhooks/'.$alias.'.php');
	}
	
	logEvent($userID,'Installed a new module: '.$name);
	echo 'success:'.'0'; die();	
}

if(isset($_REQUEST['send_email'])) {
	$userID = getUser();
	foreach ($_POST as $key => $value ){
		${$key} = $value = mysqli_real_escape_string($server,$value);
	} 
	if(!isReseller($userID) && !isAdmin($userID)) {
		echo $LANG['API feature not allowed'].':0'; die();
	}	
	if(!isAdmin($userID)) {
		$user = $userID;
	} else {
		$user = 0;
	}
	$to = '';
	if($recipients > 0) {
		$result = mysqli_query($server,"SELECT * FROM users WHERE id = '$recipients' AND reseller = '$user'") or die(mysqli_error($server));
		while ($rows = mysqli_fetch_assoc($result)) {	
			$to .= $rows['email'].',';
		}
	} elseif($recipients == 3) {
		$result = mysqli_query($server,"SELECT * FROM users WHERE role_id = '3' AND reseller = '$user'") or die(mysqli_error($server));
		while ($rows = mysqli_fetch_assoc($result)) {	
			$to .= $rows['email'].',';
		}
	} else {
		$result = mysqli_query($server,"SELECT * FROM users WHERE role_id > '2' AND reseller = '$user'") or die(mysqli_error($server));
		while ($rows = mysqli_fetch_assoc($result)) {	
			$to .= $rows['email'].',';
		}
	}
	$to = rtrim($to,',');
	mysqli_query($server, "INSERT INTO emails (`customer_id`, `subject`, `message`, `recipient`, `status`)  VALUES ('$user', '$subject', '$message',  '$to','queued');") or die (mysqli_error($server));
	logEvent( $userID,"Created a new email with subject ".$subject);		
	echo 'success:'.'0'; die();	
}


if(isset($_REQUEST['verify_phone'])) {	
	foreach ($_REQUEST as $key => $value ){
		${$key} = $value = mysqli_real_escape_string($server,$value);
	}
	if(empty($code)) {
		echo $LANG['You have not supplied any code to verify'].':0'; die();	
	}
	$query="SELECT * FROM users WHERE id = '$user'"; 
	$result = mysqli_query($server,$query);  
	$row = mysqli_fetch_assoc($result); 
	$phone_verified = $row['phone_verified'];
	if($phone_verified == 0) {
		echo 'success:'.'0'; die();	
	}
	if($phone_verified == $code) {
		mysqli_query($server, "UPDATE  `users` SET  `phone_verified` =  '0' WHERE `id` ='$user'");
		echo 'success:'.'0'; die();	
	} else {
		echo $LANG['Your verification code is incorrect'].':0'; die();	
	}
}


if(isset($_REQUEST['post_sms_chat'])) {
	$userID = getUser();
	foreach ($_POST as $key => $value ){
		${$key} = $value = mysqli_real_escape_string($server,$value);
	} 
	$date = time();
	$receiver = str_replace('+', '', $receiver);
	$sender = str_replace('+', '', $sender);
	if(isAdmin(getUser())) { 
		$userID = 0;
	}
	mysqli_query($server, "INSERT INTO smschat (`customer_id`, `sender`, `number`, `receiver`, `message`, `date`, `seen`, `sent`)  VALUES ('$userID', '$sender', '$receiver', '$receiver',  '$message','$date', '1', '0');") or die (mysqli_error($server));
	$chat_id = mysqli_insert_id($server);
	$now = date('Y-m-d H:i:s', time());
	$sent_from = 'web';
	$ip = getUserIP();
	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`) VALUES ('$message','$receiver', '$userID', 'sms', '', '$now', '$sender', '', '', '', '', '0', 'completed', '$sent_from', '0', '$ip', '', '1');") or die(mysqli_error($server));
	$message_id = mysqli_insert_id($server);
	$datetime = date('Y-m-d H:i:s');
	$now = time();
	$country = getDestinationCountry($receiver);
	$gateway_id = getDestinationRoute('sms',$receiver,$userID,'0');
	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`) VALUES ('$message_id', '$message','$receiver', '$userID', 'sms', '', '$now', '$sender', '0', '', '$datetime','$country', 'Unknown', 'sending',  '$gateway_id', '', '0');"); 	
	$single_message_id = mysqli_insert_id($server);
	sendSMS($single_message_id);
	$status = singleMessageData($single_message_id,'status');
	if(strtolower($status)=='sent') {
		mysqli_query($server, "UPDATE smschat SET `sent` = '1' WHERE `id` = '$chat_id'");	
	}
	echo 'success:'.'0'; die();	
}

if(isset($_REQUEST['fetch_chats'])) {
	$userID = getUser();
	foreach ($_POST as $key => $value ){
		${$key} = $value = mysqli_real_escape_string($server,$value);
	} 
	$results = '';
	$sender = '';
	$query = "SELECT * FROM smschat WHERE `customer_id` = '$userID' AND number = '$number' ORDER BY id ASC";
	if(isAdmin(getUser()))$query = "SELECT * FROM smschat WHERE `customer_id` = '0' AND number = '$number' ORDER BY id ASC";
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	while ($rows = mysqli_fetch_assoc($result)) { 
		if($rows['number']==$rows['sender']) {
			$sender = $rows['receiver'];	
			$results .=	'<div class="row"><div class="col s11 m10 lime lighten-5 chts"><strong class="black-text">'.$rows['number'].' <small>'.timeElapsed($rows['date']).'</small></strong><br>'.$rows['message'].'</div></div>';
		} else {
			$sender = $rows['sender'];
			$results .= '<div class="row"><div class="col s11 m10 grey lighten-4 chts right"><strong class="black-text">'.$LANG['Me'].' <small>'.timeElapsed($rows['date']).'</small></strong><br>'.$rows['message'].'</div></div>';
		}
		mysqli_query($server, "UPDATE smschat SET `seen` = '1' WHERE `id` = '$rows[id]'");	
	}
	echo $sender.':<<:'.$results; die();
}
buildJSONResponse($data['errors'],$data['success'],$data['message']);