<?php
 
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET, PUT, POST, DELETE");
  
   // require_once('../Connections/db.php');
   
    require_once('../../db.php');


	// API parameter
    
	if(isset($_REQUEST['apikey']) && isset($_REQUEST['message']) && isset($_REQUEST['sendto']) &&  isset($_REQUEST['sender']) && isset($_REQUEST['ref'])){
	
	
         
$apikey = $_REQUEST['apikey'];

$from = $_REQUEST['sender'];
$sendto = $_REQUEST['sendto'];

$txt = $_REQUEST['message'];

$schedule = $_REQUEST['sendlater'];

$ref = $_REQUEST['ref'];

$uid = mt_rand(784755,998937);

$auth = "paid";


	$apikey = str_replace( array( '+', '-', '/', '(', ')',   '_',  'drop',  '//', 'delete', 'update', 'insert', '$', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $apikey);
	$from = str_replace( array( '+', '-', '/', '(', ')',   '_',  'drop',  '//', 'delete', 'update', 'insert', '$', '{',   '}',   '<',  '>',  '='), '', $from);
	$sendto = str_replace( array( '+', '-', '/', '(', ')',   '_',  'drop',  '//', 'delete', 'update', 'insert', '$', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $sendto);

	$ref = str_replace( array( '/', '(', ')',   'drop',  '//', 'delete', 'update', 'insert', '$', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $ref);
	$schedule = str_replace( array( '+', '-', '/', '(', ')',   '_',  'drop',  '//', 'delete', 'update', 'insert', '$', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $schedule);
	$name = str_replace( array( '+', '-', '--', '/', '(', ')',   '_',  'drop',  '//', 'delete', 'update', 'insert', '$', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $name);


$apikey = filter_var($apikey, FILTER_SANITIZE_STRING);

$from = filter_var($from, FILTER_SANITIZE_STRING);

$sendto = filter_var($sendto, FILTER_SANITIZE_STRING);


$schedule = filter_var($schedule, FILTER_SANITIZE_STRING);

$ref = filter_var($ref, FILTER_SANITIZE_STRING);

$auth = filter_var($auth, FILTER_SANITIZE_STRING);

	
//$ref = substr(str_shuffle("0123456789678901"), 0, 10);
	
	
	
	
	$channel = "API";
	$productName = "Bulk SMS";
    $action = substr(str_shuffle("0123456789678901"), 0, 8);
	$del = substr(str_shuffle("0123456789678901"), 0, 7);
        date_default_timezone_set('Africa/Lagos');    
        $dateTime = date('Y-m-d h:i A');
	
	// check if the account is valid
	
	if($param){
	    
	    response(107,"BAD REQUEST");
         } else{
	
	$retr = mysqli_query($conn,"SELECT * FROM users WHERE apikey='$apikey' ");

	$rob = mysqli_fetch_array($retr);
	
	
	$user = $rob['apikey'];
	$aut = $rob['level'];
	
	$arr = array("$apikey","$auth");
	
	$pair = array("$user","$aut");		
	
	if($arr === $pair){
	    
	    // check if the user have balance
	
		$gb = mysqli_query($conn,"SElECT * FROM users WHERE apikey = '$user' ") or die(mysqli_error());	
	$reco = mysqli_fetch_array($gb);
	
	$blc = $reco['bal'];
	$level = $reco['level'];
	$email = $reco['email'];
    $fname = $reco['firstname'];        
    $lname = $reco['lastname']; 
									

	
	$query_rec = mysqli_query($conn,"SELECT * FROM billing");
$bil = mysqli_fetch_array($query_rec);
 	
									
								
										
										
										
										
										
				$Charlen = strlen($txt);
			
			 $sms_array = explode("," , $sendto);
			  
			  $no = count($sms_array);
			  
			  if($Charlen <='160'){
				  
				 $bi = $bil['sms']; 
				  }elseif($Charlen <='320'){
					  
					$bi = $bil['sms']*2;  
					  }elseif($Charlen <= '480'){
						  
						$bi = $bil['sms']*3;  
						  }elseif($Charlen <= '640'){
							
							$bi = $bil['sms']*4;  
							  
						  }else{
							  
							$bi = $bil['sms']*10;  
							  }

				$tot = $bi * $no;
				
				$tot = str_replace( array( '+', '-', '--', '/', '(', ')',   '_',  'drop',  '//', 'delete', 'update', 'insert', '$', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $tot);
				
			if(!empty($from) &&!empty($sendto) && !empty($txt) ){
											
									
										if($blc >= $tot){
											
											// debit ACCOUNT
					
$qryApi = mysqli_query($conn,"SELECT * FROM api_setting");
$apidata = mysqli_fetch_array($qryApi);

$key = $apidata['APIkey'];

$message = utf8_encode($txt);
$sms = urlencode($message);
$sender = utf8_encode($from);
$senderid = urlencode($sender);


$baseurl ="https://vtuafrica.com.ng/portal/api/sms/?apikey=$key&sendto=$sendto&message=$sms&sender=$senderid&ref=$ref";


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $baseurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

$content1 =curl_exec($ch);
                                    
      //  $deco = json_decode($content);
                                   
        curl_close($ch);
	//$content2 = str_replace( ' ', '', $content1);

 $content =json_decode($content1); 
  $response = $content->description->message;
		
if($content->code =='101') {


	
	
    	$ddebit = "UPDATE users SET bal=bal-$tot WHERE email='$email'";
			$doDebit = $conn->query($ddebit);	

$Completed = 'Completed';

$stat = "Completed";

$balanceA = $blc - $tot;

$balA = $blc - $tot;


 $add = mysqli_query($conn,"INSERT INTO transactions (serviceid,channel,amount,debit,ref,status,email,customer,balanceB,balanceA,del,date) VALUES('$productName','$channel','$tot','$tot','$ref',' $stat','$email','$fname $lname','$blc','$balA','$del','$dateTime')") or die(mysqli_error());
 
 
$qsel = "INSERT INTO message_history(mobile,sender,message,username,email,refid,status,senttime,charge,channel,user,balanceB,balanceA)VALUES('$sendto','$from','$txt','$email','$email','$ref','$stat','$dateTime','$tot','$channel','$fname $lname','$blc','$balanceA')";	

$sav = $conn->query($qsel);




response(100,array("status"=>$stat,"message"=>$response,"Amount_Charged"=>$tot,"Available_Balance"=>$balanceA));



}else{ 

 $stat = "Failed";


response(204,array("status"=>$stat,"message"=>$response,"Amount_Charged"=>'0',"Available_Balance"=>$blc));





}


}

else{ 
    
    response(102,"LOW BALANCE"); 


    
} // echo low balance

}
//}

// close account not found
} else{  
    
    response(103,"INVALID ACCOUNT"); 


    }


} // close wrong parameter



	}   else{ 
	   
	   response(400,"INVALID PARAMETER"); 
	       
	       
	   }
	    

function response($status,$status_message)
{
	
	
	$response['code']=$status;
	$response['description']=$status_message;
	
	
	$json_response = json_encode($response);
	echo $json_response;
}
    
    ?>
    
  
   	

