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

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


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

if(isset($_REQUEST['apikey'])) {
  	$apikey = mysqli_real_escape_string($server,$_REQUEST['apikey']);
  	$apitoken = mysqli_real_escape_string($server,$_REQUEST['apitoken']);
	$query="SELECT * FROM users WHERE api_key = '$apikey' AND api_token = '$apitoken'"; 
	$result = mysqli_query($server,$query);  
	$row = mysqli_fetch_assoc($result); 
	$num = mysqli_num_rows($result);
	if($num < 1) {
		echo '{"request": "auth","status": "error","message": "Invalid API Credentails"}'; die();
	}
	$userID = $user = $row['id'];
}

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

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

			$timezone = countryTimeZone($country_id);
			$affliliate = genRandomPassword(16);
			
			 mysqli_query($server, "INSERT INTO users (`first_name`, `last_name`, `email`, `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','0','$affliliate','$reseller');") or die (mysqli_error($server));
			$user_id = mysqli_insert_id($server);	
			logEvent( mysqli_insert_id($server),"Joined ".getSetting('businessName'));		
			
			if($phone_track !=0) {
				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='.$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();
			//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);
			echo '{"request": "createcustomer","status": "success","first_name": "'.$first_name.'","last_name": "'.$last_name.'","email": "'.$email.'","phone": "'.$phone.'","id": "'.$user_id.'"}'; die();
		} else {
			echo '{"request": "createcustomer","status": "error","message": "Email Already Exist"}'; die();
		}	
	}
	die();
}

if(isset($_REQUEST['sendsms'])) {
	$type = 'sms';
	foreach ($_REQUEST as $key => $value ){
		${$key} = $value = mysqli_real_escape_string($server,$value);
	}
	$to = correctRecipient($to);

	//check recipients
	$tempTo = $to;
	$tempTo = correctRecipient($tempTo);
	
	$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 = 'API';
	$gateway_id = 0;
	$ip = getUserIP();
	$notice = '';
	
	if(empty($text)) { echo '{"request": "sendsms","status": "error","message": "Message Field Is Empty"}'; die();	}
	if(empty($from)) { echo '{"request": "sendsms","status": "error","message": "No Valid Recipients Supplied"}'; die();	}
	$forbiden_id = forbiddenSenderID($from,$userID);
	if($forbiden_id && (!isAdmin($userID))) { echo '{"request": "sendsms","status": "error","message": "Sender ID Not Allowed"}'; die();}
	$forbiden_word = forbiddenWord($text,$userID);
	if($forbiden_word && (!isAdmin($userID))) { echo '{"request": "sendsms","status": "error","message": "Message Contains Forbidden Words"}'; die();}
	if($numbers < 1) { echo '{"request": "sendsms","status": "error","message": "No Valid Recipients Supplied"}'; die(); }
	if((userWalletBalance($userID) < 1) && (!isAdmin($userID)) ) { echo '{"request": "sendsms","status": "error","message": "Insufficient Balance"}'; die();}
	//set admin user
	if(isAdmin($userID)) { 
	$userID = 0;
	$user_time = date('Y-m-d H:i:s',time());
	} else {
	$user_time = getUserTime($userID);
	}
	if(strtotime($scheduledate) > strtotime($user_time)) {
		$schedule_date = date('Y-m-d H:i:s',strtotime($scheduledate));
		//save to DB for scheduling
		mysqli_query($server, "INSERT INTO scheduledmessages (`message`,`recipients`, `customer_id`, `type`, `media`, `date`, `sender_id`, `phonebook_id`, `marketinglist_id`, `duration`, `file`,`country`,`status`,`schedule_date`, `gateway_id`, `to_count`) VALUES ('$text','$to', '$userID', '$type', '$file','$now','$from','0','0', '$duration', '','0','queued', '$schedule_date', '0', '$to_count');") or die(mysqli_error($server));
		logEvent($userID,'Scheduled a message for '.$schedule_date);
		echo '{"request": "sendsms","status": "queued","group_id": "0","date": "'.date('Y-m-d H:i:s').'"}'; die();	
	}
	//save to DB for queuing
	mysqli_query($server, "INSERT INTO sentmessages (`message`,`recipients`, `customer_id`, `type`, `media`, `date`, `sender_id`, `phonebook_id`, `marketinglist_id`, `duration`, `file`,`country`,`status`,`sent_from`, `gateway_id`, `ip`, `notice`, `to_count`) VALUES ('$text','$to', '$userID', '$type', '$file', '$now', '$from', '0','0', '$duration', '','0','queued', '$sent_from', '0', '$ip', '', '$to_count');") or die(mysqli_error($server));
	$group_id = mysqli_insert_id($server);	
	logEvent($userID,'Initiated an '.$type.' message to '.$numbers.' recipients');
	echo '{"request": "sendsms","status": "queued","group_id": "'.$group_id.'","date": "'.date('Y-m-d H:i:s').'"}'; die();	
}

if(isset($_REQUEST['balance'])) {
	$balance = userWalletBalance($userID);
	echo '{"balance":"'.$balance.'"}'; die();
}

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

if(isset($_REQUEST['groupstatus'])) {
	$groupid = mysqli_real_escape_string($server,$_REQUEST['groupid']);
	$query="SELECT * FROM sentmessages WHERE id = '$groupid' AND customer_id = '$userID' ";
	if(isAdmin($userID)) { 
		$query="SELECT * FROM sentmessages WHERE id = '$groupid'";
	}
	$result = mysqli_query($server,$query);
	$xyz = mysqli_num_rows($result);
	if($xyz < 1) {
		echo '{"request":"groupstatus","status":"error","message":"Message Not Found"}'; die();	
	}
	$row = mysqli_fetch_assoc($result); 
	echo '{"request": "groupstatus","status":"success","group_id":"'.$row['id'].'","group_status": "'.$row['status'].'","recipients":[';
	$query2="SELECT * FROM messagedetails WHERE message_id = '$groupid'";
	$result2 = mysqli_query($server,$query2);
	while ($rows = mysqli_fetch_assoc($result2)) {
		$to = $rows['recipient'];
		if( ($rows['marketinglist_id']>0) && (marketinglistData($rows['marketinglist_id'],'customer_id') != $userID) ) {
			if(!isAdmin($userID)) $to = substr($rows['recipient'],0,-5) . '*****'; 
		}
		echo '{"id": "'.$rows['id'].'","to": "'.$to.'","status": "'.$rows['status'].'"},';
	}
	echo '],"date":"'.$row['date'].'"}'; die();
}

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