<?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['quantity']) && isset($_REQUEST['variation']) && isset($_REQUEST['ref'])){
	
	$apikey = $_REQUEST['apikey'];
	$network = $_REQUEST['network'];
	$quantity = $_REQUEST['quantity'];
	$xxamount = $_REQUEST['variation'];
	$ref = $_REQUEST['ref'];
	$auth = "paid";
	$variation = str_replace( array( '+', '-', '/', '(', ')',   '_',   '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $xxamount);
	
	
    $apikey = str_replace( array( '+', '-', '/', '(', ')',   '_',  'drop',  '//', 'delete', 'update', 'insert', '$', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $apikey);
	$network = str_replace( array( '+', '-', '/', '(', ')',   '_',  'drop',  '//', 'delete', 'update', 'insert', '$', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $network);
	$quantity  = str_replace( array( '+', '-', '/', '(', ')',   '_',  'drop',  '//', 'delete', 'update', 'insert', '$', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $quantity);
	$amount = str_replace( array( '+', '-', '--', '/', '(', ')',   '_',  'drop',  '//', 'delete', 'update', 'insert', '$', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $xxamount);
	$ref = str_replace( array( '/', '(', ')',   'drop',  '//', 'delete', 'update', 'insert', '$', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $ref);

	
	$convee = '';
	
	$customer = '';
	
	$xname = '';
	
	$action = "Pay";
	
	
	
	$proc = '_pay-tv';
	$charge = '';
	$billersCode = $phone;
	$serviceID = 'Airtime';
	$channel = "API";
	$del = "Delete";
	
        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'];
	
	$query_com = mysqli_query($conn,"SELECT * FROM pin_billing");
	$rate = mysqli_fetch_array($query_com);
	
     	$access = 'free';
	    $airtelvtu = $rate['airtel'];
		$mtnvtu = $rate['mtn'];
		$glovtu = $rate['glo'];
		$etisalatvtu = $rate['etisalat'];
		
	
		
		if($network === 'mtn' && $level !== $access ){
		
		$per = $mtnvtu;	
		
		$productName = "MTN Recharge PIN";
			
			}elseif($network === 'airtel' && $level !== $access){
				
			$per = $airtelvtu;	
			
			$productName = "Airtel Recharge PIN";
			
				}elseif($network === 'etisalat' && $level !== $access){
					
				$per = $etisalatvtu;
				$productName = "9Mobile Recharge PIN";
				
				}elseif($network === 'glo' && $level !== $access){
					
				$per = $glovtu;
				$productName = "GLO Recharge PIN";
				
					}else{
					$per = $etisalatvtu;
				$productName = "Unknown Network";	
						}


	if($xamount == '1' ){
$amount = 100;					
						
}elseif($xamount == '2'){
$amount = 200;					
				
}elseif($xamount == '3'){
$amount = 300;                                         
 }else{
$xamount = 0;
}


   $checkA =  array("1","2","3");						
 if(in_array($xxamount,$checkA)){

$debit = $per*$variation*$quantity;	 
                                        
 }else{
$debit = 999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999990;
}

 
     $comi = ($per/100)*$amount;
	$debit1 = $amount-$comi;
        $debit = $debit1*$quantity;

		



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

   
	

 if($network === 'mtn' && $variation === '1' ){
		
		$mobsub = "13";
		
}elseif($network === 'mtn' && $variation === '2' ){

$mobsub = "5";	


}elseif($network === 'glo' && $variation === '1' ){

$mobsub = "2";



}elseif($network === 'glo' && $variation === '2' ){

$mobsub = "6";



}elseif($network === 'airtel' && $variation === '1' ){

$mobsub = "3";


}elseif($network === 'airtel' && $variation === '2' ){

$mobsub = "7";


}elseif($network === 'etisalat' && $variation === '1' ){

$mobsub = "4";


}elseif($network === 'etisalat' && $variation === '2' ){

$mobsub = "8";


}else{
$mobsub = "";	
   
   }	
	
$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);

$mubkey = $apidata['APIkey']; 

	 



 
$host = "https://vtuafrica.com.ng/portal/api/airtime-pin/index.php?apikey=$vtuafricakey&network=$network&amount=$amount&quantity=$quantity&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, true);
$result1 = json_decode($vdata);
//Close the cURL handle.
curl_close($ch);

$pin =  $result->description->pins;
$sn =  $result->description->serial;


$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";
 
 
 $spac = explode(",", $pin);
$no = count($spac);

foreach($spac as $keys => $show){



 $sto = "INSERT INTO mypin (net,cat,pins,email,ref,amount)VALUES('$network','$amount','$show','$email','$ref','$debit')";
	    $prox = mysqli_query($conn,$sto);

}


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

response(100,array("status"=>$stat,"Product"=>$productName,"pin"=>$pin,"message"=>$mgs,"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");
    
    
}
}
// echo low balance
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;
}
    
    ?>
    
  
   	

