<?php
  

 header('Content-Type : application/json');
  
   // require_once('../Connections/db.php');
   
    require_once('../../db.php');


	// API parameter
    
	if(isset($_REQUEST['apikey']) && isset($_REQUEST['network']) && isset($_REQUEST['MobileNumber']) && isset($_REQUEST['amount']) && isset($_REQUEST['ref'])){
	
	$apikey = $_REQUEST['apikey'];
	$network = $_REQUEST['network'];
	$phone = $_REQUEST['phone'];
	$xamount = $_REQUEST['amount'];
	$ref = $_REQUEST['ref'];
	$auth = "paid";
	$apikey = str_replace( array( '+', '-', '/', '(', ')',   '_',  'drop',  '//', 'delete', 'update', 'insert', '$', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $apikey);
	$network = str_replace( array( '+', '-', '/', '(', ')',   '_',  'drop',  '//', 'delete', 'update', 'insert', '$', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $network);
	$phone  = str_replace( array( '+', '-', '/', '(', ')',   '_',  'drop',  '//', 'delete', 'update', 'insert', '$', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $phone );
	$amount = str_replace( array( '+', '-', '--', '/', '(', ')',   '_',  'drop',  '//', 'delete', 'update', 'insert', '$', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $xamount);
	$ref = str_replace( array( '/', '(', ')',   'drop',  '//', 'delete', 'update', 'insert', '$', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $ref);

	

	

	$serviceID = 'Airtime';
	$channel = "API";
	$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_com = mysqli_query($conn,"SELECT * FROM billing");
	$rate = mysqli_fetch_array($query_com);
	
	$access = 'free';
	        $airtelvtu = $rate['airtelvtu'];
		$mtnvtu = $rate['mtnvtu'];
		$glovtu = $rate['glovtu'];
		$etisalatvtu = $rate['9mobilevtu'];
		
		if($network === 'mtn' && $level !== $access ){
		
		$per = $mtnvtu;	
		
		$productName = "MTN Airtime VTU";
			
			}elseif($network === 'airtel' && $level !== $access){
				
			$per = $airtelvtu;	
			
			$productName = "Airtel Airtime VTU";
				}elseif($network === 'etisalat' && $level !== $access){
					
				$per = $etisalatvtu;
				$productName = "9Mobile Airtime VTU";
				
					}else{
						
					if($level !== $access){	
					$per = $glovtu;	
					$productName = "Glo Airtime VTU";
					}
						}


  if($network === 'mtn'){
	$gladNet = "1";
	
	}elseif($network === 'glo'){
		
		$gladNet = "3";
		}elseif($network === 'etisalat'){
		
		$gladNet = "4";	
			
			}elseif($network === 'airtel'){
				
				$gladNet = "2";
				}


	
	$comi = ($per/100)*$amount;
	$debit = $amount-$comi;
	$charge = 0;
	
	$debit = str_replace( array( '+', '-', '--', '/', '(', ')',   '_',  'drop',  '//', 'delete', 'update', 'insert', '$', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $debit);
	
	
	if($debit < $blc ){ 
	    
	    // check if ref number exist
	    
	  $req = mysqli_query($conn,"SElECT * FROM transactions WHERE ref = '$ref' ") or die(mysqli_error());	
	
	$nu = mysqli_num_rows($req);

	if($nu == 0){
	    
       // debit account




$qryApi = mysqli_query($conn,"SELECT * FROM api_setting");
$apidata = mysqli_fetch_array($qryApi);

$key = $apidata['APIkey']; 

	 
		
		

$host = "https://vtuafrica.com.ng/portal/api/airtime/index.php?apikey=$key&network=$network&phone=$phone&amount=$amount&ref=$ref";




//Initialize cURL.

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $host);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

$vdata = curl_exec($ch);

$result = json_decode($vdata);



//Close the cURL handle.

curl_close($ch);



$mgs = $result->description->message;

if($result->code =='101'){

 $doupt = mysqli_query($conn,"UPDATE users SET bal=$blc-$debit WHERE apikey='$apikey' ") or die(mysqli_error());
    
    $stat = "Completed";

$balA = $blc - $debit;

 $message = "TRANSACTION SUCCESSFUL";


 $add = mysqli_query($conn,"INSERT INTO transactions (network,serviceid,channel,phone,amount,debit,charge,comi,ref,status,email,customer,balanceB,balanceA,del,date) VALUES('$network','$productName','$channel','$phone','$amount','$debit','$charge','$comi','$ref',' $stat','$email','$fname $lname','$blc','$balA','$del','$dateTime')") or die(mysqli_error());
 

response(100,array("status"=>$stat,"service"=>$productName,"message"=>$message,"ref"=>$ref,"amount"=>$amount,"Amount_Charged"=>$debit,"Available_Balance"=>$balA,"transaction_date"=>$dateTime));


}else{ 

$stat = "Failed";

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


}else{ 

response(104,"TRANSACTION ID ALREADY EXIST");
    
    
}

}else{ 
    
    response(102,"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;
}
    
    ?>
    
  
   	

