<?php

require('../db.php');

?>




<?php

  if($json = file_get_contents("php://input")) {

file_put_contents('vtuafrica.txt', $json);

}

?>






<?php 



	

$response = file_get_contents("vtuafrica.txt");

$res = json_decode($response);


if (!empty($res)) {
    
    
    $status =  $res->status;
    $apikey = $res->apikey;
	$service = $res->service;
	$network = $res->network;
	$amount = $res->amount;
	$debit = $res->debit;
	$charge = $res->charge;
	$comm = $res->comi;
	$token = $res->token;
	$ref = $res->ref;
	$messageA = $res->message;
	$accesscode = $res->accesscode;
    $baseurl = $res->baseurl;
	$sender = $res->sender;

        
	
$apikey = filter_var($apikey, FILTER_SANITIZE_STRING);
$status = filter_var($status, FILTER_SANITIZE_STRING);
$service = filter_var($service, FILTER_SANITIZE_STRING);
$network = filter_var($network, FILTER_SANITIZE_STRING);
$token = filter_var($token, FILTER_SANITIZE_STRING);
$amount = filter_var($amount, FILTER_SANITIZE_STRING);
$debit = filter_var($debit, FILTER_SANITIZE_STRING);
$charge = filter_var($charge, FILTER_SANITIZE_STRING);
$comm = filter_var($comm, FILTER_SANITIZE_STRING);
$ref = filter_var($ref, FILTER_SANITIZE_STRING);
$messageA = filter_var($messageA, FILTER_SANITIZE_STRING);
$accesscode = filter_var($accesscode, FILTER_SANITIZE_STRING);
$baseurl = filter_var($baseurl, FILTER_SANITIZE_STRING);
$sender = filter_var($user, FILTER_SANITIZE_STRING);


$apikey = mysqli_real_escape_string ($conn, $apikey);
$status = mysqli_real_escape_string ($conn, $status);
$service = mysqli_real_escape_string ($conn, $service);
$network = mysqli_real_escape_string ($conn, $network);
$token = mysqli_real_escape_string ($conn, $token);
$debit = mysqli_real_escape_string ($conn, $debit);
$ref = mysqli_real_escape_string ($conn, $ref);
$amount = mysqli_real_escape_string ($conn, $amount);
$charge = mysqli_real_escape_string ($conn, $charge);
$comm = mysqli_real_escape_string ($conn, $comm);
$messageA = mysqli_real_escape_string ($conn, $messageA);
$accesscode = mysqli_real_escape_string ($conn, $accesscode);
$baseurl = mysqli_real_escape_string ($conn, $baseurl);
$sender = mysqli_real_escape_string ($conn, $user);



	
	
	
	$channel = "API";
	$view = "View";
	
	
$qryApi = mysqli_query($conn,"SELECT * FROM settings");
$apidata = mysqli_fetch_array($qryApi);

$sitename = $apidata['sitename'];
$admin = $apidata['email'];
$sitephone = $apidata['mobile'];
$siturl = $_SERVER['SERVER_NAME'];
$sitlogo = $apidata['sitelogo'];
$request_dir = $_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']);
date_default_timezone_set('Africa/Lagos'); 
$dateTime = date('Y-m-d h:i A');

$del = substr(str_shuffle("0123456789678901"), 0, 6);
$action = substr(str_shuffle("0123456789678901"), 0, 7);
	
	// check if the account is valid
	



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

        $key = $apidata['APIkey'];
			
	 $authlock = hash('SHA512', $key);
      $authkey = strtoupper($authlock);
	
      $headers = getallheaders();
$Xsignature = $headers['Authorization'];
$Xsignature = strtoupper($Xsignature); 	


	
	if($Xsignature === $authkey){
	    
	
	    
	    // check if the user have balance
	

	
$gbs = mysqli_query($conn,"SElECT * FROM transactions WHERE ref = '$ref' ") or die(mysqli_error());	
	$rec = mysqli_fetch_array($gbs);
	
	$reseller = $rec['email'];
    $user = $rec['email'];
	$id = $rec['ref'];
	$stat = $rec['status'];
	$channel = $rec['channel'];
	$sender = $rec['sender'];
	$type = $rec['serviceid'];
	$balanceB2 = $rec['balanceB'];
	$balanceA2 = $rec['balanceA'];
	$debit = $rec['debit'];

      $req = mysqli_query($conn,"SElECT * FROM transactions WHERE ref = '$ref' ") or die(mysqli_error());	
	
     $nu = mysqli_num_rows($req);

	if($nu == 1){
		
		
	if($stat == 'Completed' || $stat == 'Processing' || $stat === 'Requested' ){
		
		
$gb = mysqli_query($conn,"SElECT * FROM users WHERE email = '$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'];
        $webhook = $reco['webhook'];
        $apikeys = $reco['apikey'];
        $auth = md5($apikeys);
  
		
		






//ACTIONS START HERE

  if($status == 'Completed'){

$sql = mysqli_query($conn,"UPDATE transactions SET status='$status',token='$token' WHERE ref='$id' ");
 
$text = "Please be informed that your $type Transaction on $sitename is <b>Successful.</b> ";
$loginID = $email;
$oldbal =  $balanceB2;
$newbal = $balanceA2;

$txt = "Dear $fname Please be informed that your $type Transaction on $sitename is <b>Successful. www.$siturl";

$message = "Transaction Updated To Completed Successfully";

$state = "Completed";
$code ="101";



//AIRTIMME TO CASH START HERE



if($service == 'Airtime2Cash'){

$gb = mysqli_query($conn,"SElECT * FROM users WHERE email = '$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'];
	
	$qrypinBil = mysqli_query($conn,"SELECT * FROM acash_billing");
 $pin = mysqli_fetch_array($qrypinBil);


$mtn = $pin['mtn'];
$airtel = $pin['airtel'];
$glo = $pin['glo'];
$etisalat = $pin['9mobile'];


if($network === 'mtn'){
$pnt = "MTN Airtime2Cash";
$per = $mtn;
}elseif($network === '9mobile'){
$pnt = "9mobile Airtime2Cash";
$per = $etisalat;
}elseif($network === 'airtel'){
$pnt = "Airtel Airtime2Cash";
$per = $airtel;
}elseif($network === 'glo'){
$pnt = "Glo Airtime2Cash";
$per = $glo;
}else{
$pnt = "Invalid Network";
$per = 0;
}

$charge = ($per/100)*$amount;
	$credit = $amount-$charge;
						
	$amountpaid = $credit;
	
	
$gbs = mysqli_query($conn,"SElECT * FROM transactions WHERE ref = '$ref' ") or die(mysqli_error());	
	$rec = mysqli_fetch_array($gbs);
	
	$reseller = $rec['email'];

	if($reseller == $user ){
	    
	    // check if ref number exist
	    
	  $req = mysqli_query($conn,"SElECT * FROM deposit WHERE ref = '$ref' ") or die(mysqli_error());	
	
	$nu = mysqli_num_rows($req);

	if($nu == 0){
	    
$balA = $blc+$credit;

$add = mysqli_query($conn,"INSERT INTO deposit (ref,amount,charge,email,user,status,method,process,del,balanceB,balanceA) VALUES('$ref','$credit','$charge','$email','$fname $lname','Completed','$amount Airtime2Cash','$service','Delete','$blc','$balA')") or die(mysqli_error());	    
	    
       // credit account
	  
$doupt = mysqli_query($conn,"UPDATE users set bal=$blc+$credit WHERE email ='$user' ") or die(mysqli_error());
	  

$qsel = "UPDATE transactions SET status='Completed',balanceA='$balA'refer='N/A',token='0',date='$dateTime' WHERE ref='$ref' ";


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

$state = "Completed";
$code ="101";

include('alert-airtime2cash.php'); 

$message = "Airtime2Cash Performed Successfully";



}else{ 
 
$message = "AIRTIME2CASH TRANSACTION ID ALREADY EXIST"; 

$state = "Failed";
$code ="204";
    
}


}else{ 
 
$message = "INVALID SENDER EMAIL SUPPLIED"; 

$state = "Failed";
$code ="204";
    
}

	}
	
	
//AIRTIME TO CASH STOPS HERE


}elseif($status == 'Reversed'){

if ($stat === 'Processing' || $stat === 'Completed' || $stat === 'Requested' ){

$text= "Please be informed that your $type Transaction on $sitename Was <b>NOT Successful.</b> and Your Account has been <b>REFUNDED</b>."; 
$loginID = $email;
$oldbal =  $blc;
$newbal = $blc+$debit; 
$balA = $blc+$debit; 



$sql = mysqli_query($conn,"UPDATE transactions SET status='$status',balanceA='$balA' WHERE ref='$id' ") or die(mysqli_error());


$doupt = mysqli_query($conn,"UPDATE users SET bal='$newbal' WHERE email ='$email' ") or die(mysqli_error());

$message = "Transaction Updated To Reversed Successfully";

$state = "Completed";
$code ="101";
    
}else{

$message = "Note: This Transaction Was Not Debited";

$state = "Failed";
$code ="203";


 }





}elseif($status == 'Processing'){ 

$sql = mysqli_query($conn,"UPDATE transactions SET status='$status' WHERE ref='$id' ");

$text= "Please be informed that your Transaction on $sitename is still in <b>PROGRESS</b>. <br>
Please Be Patient with Us.";
$loginID = $email;
$newpassword = "";
$newstatus = $status;


$message = "Transaction Updated To Processing Successfully";


$state = "Completed";
$code ="101";


}elseif($status == 'Debit'){



$oldbal =  $blc;
$newbal = $blc-$debit; 
$balA = $blc-$debit; 



$sql = mysqli_query($conn,"UPDATE transactions SET status='Completed' WHERE ref='$id' ") or die(mysqli_error());


$doupt = mysqli_query($conn,"UPDATE users SET bal='$newbal' WHERE email ='$email' ") or die(mysqli_error());

$message = "User Account Debited Successfully";

$state = "Completed";
$code ="101";


}elseif($status == 'Delete'){ 
    

$del = mysqli_query($conn,"DELETE FROM transactions WHERE serial='$id' ");


$message = "Transaction Deleted Successfully";


$state = "Completed";
$code ="101";

}



//ACTIONS STOP HERE

   
  


	}else{ 
    

    
    $message = "TRANSACTION ALREADY COMPLETED";

$state = "Failed";
$code ="205";
    
} 



}else{ 
    
   // response(404,"INVALID TRANSACTION REFERENCE");
    
    $message = "INVALID TRANSACTION REFERENCE";

$state = "Failed";
$code ="403";
    
}




} else{  


$message = "INVALID ACCOUNT (INVALID AUTHENTICATION CODE SUPPLIED).";

$state = "Failed";
$code ="402";

    }



}else{ 
    
$message = "INVALID PARAMETERS";

$state = "Failed";
$code ="404";
    
}




 if($service == 'Access' || $status == 'Access'){ 

$sql = mysqli_query($conn, "UPDATE api_setting SET accesscode='$accesscode',baseurl='$baseurl'");

$text= "Please be informed that your VTU Portal Creator Has been <b>ACTIVATED</b>.";
$loginID = $email;
$newpassword = "";
$newstatus = "Active";
$message = "Access Code Updated Successfully";

$state = "Completed";
$code ="101";


 }
 

//webhook here

if($channel === 'API'){
    
  
 // Data to send as JSON
 $data = array(
    "apikey"=>$auth,
    "accesscode" => $code,
    "ref" => $ref,
    "status" => $status,
	"service" => $service,
	"network" => $network,
	"token" =>$token,
    "amount"=>$amount,
    "debit "=>$fund,
    "charge"=>$charge,
    "comi"=>$comi,
    "message"=>$message,
     "sender"=>$sender
); 		


// Encode the data as JSON
$jsonData = json_encode($data);
     


include('webhook.php');

}

//Webhook Ends here




response(array("code"=>$code,"status"=>$state,"message"=>$message,"Action"=>$status));


function response($status_message){
	
	
	$response['status']=$status;
$response=$status_message;
	
	
	$json_response = json_encode($response);
	echo $json_response;
	
}

?>