<?php
session_start();
require('db.php');



	 if(isset($_REQUEST['referenceID']) && isset($_REQUEST['status'])  ){
         //$payref = $_REQUEST['paymentReference'];
	     $ref = $_GET['referenceID'];
	     $state = $_REQUEST['status'];
	
 if($state === 'Completed'){
echo '<script>window.location="buy_credit.php?ref='.$ref.'";</script>';     
 }else{
     
echo '<script>window.location="buy_credit.php?fail='.$ref.'";</script>';     
 }     


}else{
    

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

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

}
	

$response = file_get_contents("GetPaylog.txt");
$res = json_decode($response);

$ref = $res->data->referenceID;
$payref = $res->data->paymentReference;

}



     $ref = filter_var($ref, FILTER_SANITIZE_STRING);
      $payref = filter_var($payref, FILTER_SANITIZE_STRING);
	 


$ref = mysqli_real_escape_string ($conn, $ref);
$payref = mysqli_real_escape_string ($conn, $payref);




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


	
	 //$getpaykey = $apidata['getpaykey']; //email address()
    $getpaysec = $apidata['getpaysec']; 
    $getpayurl = $apidata['getpayurl'];
    $getpaysec = filter_var($getpaysec, FILTER_SANITIZE_STRING);
    
    
     $headers = getallheaders();
	  $Xsignature = $headers['Authorization'];
	  
	  
	  $passcode = "$getpaysec:$payref";
	  $authkey = hash('sha512', $passcode);
      $authkey = strtoupper($authkey);
	


			
    if($Xsignature === $authkey){
	
    $per = $apidata['cardfee'];
    $VAT = $apidata['VAT'];
    $feeBearer = $apidata['feeBearer'];
 

		  
		   $query_rec = mysqli_query($conn,"SELECT * FROM settings");			
        $settings = mysqli_fetch_array($query_rec);
	$sitename = $settings['sitename'];
	$servName = $_SERVER['HTTP_HOST'];

	$check=mysqli_query($conn,"SELECT * FROM deposit WHERE ref='$ref' ");
   
    $num = mysqli_num_rows($check);
    
    
    if ($num == 1){
	
		$ret = mysqli_query($conn,"SELECT * FROM deposit WHERE ref='$ref' ");
		
		$da = mysqli_fetch_array($ret);
		
		$amount = $da['amount'];
		$tid = $da['ref'];
		$token = $da['token'];
		$refer = $da['refer'];
		$status = $da['status'];
		$email = $da['email'];
								
	$ins = mysqli_query($conn,"SELECT * FROM users WHERE email='$email' ");
	$data = mysqli_fetch_array($ins);
								
      $email = $data['email'];
	   $fname = $data['firstname'];
	  $bal  = $data['bal'];
      $fname   = $data['firstname']; 
      $lname   = $data['lastname'];
	
	
	
    if($token === $refer && $status !== 'Completed'){
	
	
	
	
	 $host = "https://$getpayurl/api/v1/merchant-verify/transactions/?secretkey=$getpaysec&referenceID=$ref";


//Initialize cURL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($ch);

//Close the cURL handle.
curl_close($ch);

$result = json_decode($response);

if ($result->transaction->status == "Completed" ) {
    
  $amount = $result->transaction->amount;
  $amount_paid = $result->transaction->amount_paid;
  $payable = $result->transaction->payable;
  $charge = $result->transaction->charge;
  $status = $result->transaction->status;
  $stampDuty = $result->transaction->stampDuty;
  $vat = $result->transaction->VAT;
  $payref =  $result->transaction->paymentReference;
  $method = $result->transaction->paymentMethod;
  $paidon = $result->transaction->date;
  

   $sitecharge = ($per/100)*$amount;
   
   
if($feebearer === "Customer"){
    
 $paid = $amount;
 $fund = $bal + $amount;
  $charge = $charge + $stampDuty + $vat;
    
}elseif($feebearer === "Merchant"){
    
$paid = $amount - $sitecharge - $stampDuty - $vat;
$fund = $bal + $amount - $sitecharge - $stampDuty - $vat;
$charge = $sitecharge + $stampDuty + $vat;
    
}else{

 $paid = $amount;
 $fund = $bal + $amount;    	
 $charge = $charge + $stampDuty + $vat;   
}    
       

  

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

                
 $up = "UPDATE deposit SET token='$ref',refer='N/A',status='$status',charge='$charge',method='$method',balanceA='$fund' WHERE ref='$tid' ";
			$conn->query($up);
				
		
				// send email....
				
				
$from = " ".$sitename."<support@$servName>"; //the email address from which this is sent
$to = "$email"; //the email address you're sending the message to
$subject = "Transaction Notification"; //the subject of the message

// To send HTML mail, the Content-type header must be set
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "X-Priority: 3\r\n";
$headers .= "Return-Path: ".$settings['sitename']."<support@$serName>\r\n";
$headers .= "Organization: ".$settings['sitename']."\r\n";
 
// Create email headers
$headers .= 'From: '.$from."\r\n".
    'Reply-To: '.$from."\r\n" .
    'X-Mailer: PHP/' . phpversion();

$message = "

<html>
<head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
<style>
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 50%;
}

td {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
</style>
</head>

<body>

<img src='https://".$_SERVER['SERVER_NAME']."/portal/assets/images/logo.png'>

<h3>Dear $fname,</h3>

Your account has been credited <br> 

<h2 style='color:#06AF3E'>N$paid</h2> <p>

<strong>Transaction Summary</strong> <p>

<table class='table' >
  
  <tr>
    <td>Description</td>
    <td>Wallet Credit</td>
  </tr>
  <tr>
    <td>Transaction Date</td>
    <td> $dateTime </td>
  </tr>
  
  <tr>
    <td>Transaction Ref</td>
    <td> $ref </td>
  </tr>
  
   <tr>
    <td>Payment Method</td>
    <td> $method</td>
  </tr>
  
  <tr>
    <td>Card Fee</td>
    <td> $charge</td>
  </tr>
  
   <tr>
    <td>Transaction Status</td>
    <td> $status </td>
  </tr>
  
</table> <p>


<a href='https://$serName'>Click here</a> to login and confirm <p>

If you have questions/complaints as regards this transaction, please reply 

the email support@$serName or <strong>Call:</strong> $sitephone
<p>


Thanks for your Patronage. <p>

<strong>$serName</strong>

</body><html>";

//now mail
$DoMail = mail($to,$subject,$message,$headers);
             
               
 ?>
<script>window.location="buy_credit.php?reff='<?php echo $_GET['referenceID']?>' ";</script> <?php 
    

                }else{
                     echo "Payment failed";
                     
                      ?>
<script>window.location="buy_credit.php ";</script> <?php
                }  
				
	}else{
	     echo "Already Funded";
	     
	      ?>
<script>window.location="buy_credit.php?funded='<?php echo $_GET['referenceID']?>'";</script> <?php 
	} 

           }else{
                     echo "Transaction does not exit.";
                     
                      ?>
<script>window.location="buy_credit.php ";</script> <?php
                }	

}else{
    
    echo "Invalid Parameters Supplied";
    
 ?>
<script>window.location="buy_credit.php ";</script> <?php

}
  


?>