<?php
//session_start();
require('db.php');
//if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
//header("location: index.php");
//  exit; }
	//include('inc/func.php');							

		
// confirm Rave payment 
//https://vtuafrica.com.ng/portal/flutterwavecheck.php?flwref=FLW-6036c60df5f04b28a6e142287b892f26&txref=978788

//if (isset($_GET['txref'])) {
       // $cref = $_GET['txref'];  
       
    
       
 
 if(isset($_REQUEST['flwref']) && isset($_REQUEST['txref']) ){
$flwref = $_REQUEST['flwref'];
	$cref = $_REQUEST['txref'];

$flwref = filter_var($flwref, FILTER_SANITIZE_STRING);
$flwref = mysqli_real_escape_string ($conn, $flwref);

$cref = filter_var($cref, FILTER_SANITIZE_STRING);
$cref = mysqli_real_escape_string ($conn, $cref);

$flwref = str_replace( array( '+', ',', '-', '/', '(', ')',   '_',  '//', 'drop', 'update', 'delete', 'insert', 'add', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $flwref);
$cref = str_replace( array( '+', ',', '-', '/', '(', ')',   '_',  '//', 'drop', 'update', 'delete', 'insert', 'add', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $cref);
	
        $amount = ""; //Correct Amount from Server
        $currency = ""; //Correct Currency from Server
        
    
date_default_timezone_set('Africa/Lagos');

$dateTime = date(' Y-m-d h:i A');
$dat = date(' Y-m-d h:i A');
  
        		$ret = mysqli_query($conn,"SELECT * FROM deposit WHERE ref='$cref' ");
		
		$da = mysqli_fetch_array($ret);
		
		$amount = $da['amount'];
		$tid = $da['ref'];
		$token = $da['token'];
		$refer = $da['refer'];
		$TXstatus = $da['status'];							
	        $UserEmail = $da['email'];
	        $user = $da['email'];
                $serName = $_SERVER['HTTP_HOST'];
                $sitephone = $settings['mobile'];
			



$ins = mysqli_query($conn,"SELECT * FROM users WHERE email='$user' ");
	$data = mysqli_fetch_array($ins);
								
	$email = $data['email'];
	$rowpas = $data['pass'];
	$fname = $data['firstname'];
        $lname = $data['lastname'];
        $bal2 = $data['bal'];
        $phone = $data['phone'];
	

$query_rec = mysqli_query($conn,"SELECT * FROM payment");
			
$apib = mysqli_fetch_array($query_rec);
			
$paykey = $apib['flutterSecret'];
$paykey = filter_var($paykey, FILTER_SANITIZE_STRING);
$paykey= mysqli_real_escape_string ($conn, $paykey);

     $query = array(
            "SECKEY" => $paykey,
            "txref" => $cref );

        $data_string = json_encode($query);
                
        $ch = curl_init('https://api.ravepay.co/flwv3-pug/getpaidx/api/v2/verify');                                                                      
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                              
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

      $response = curl_exec($ch);
        

        $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $header = substr($response, 0, $header_size);
        $body = substr($response, $header_size);
        
        
        curl_close($ch);

       // $resp = json_decode($response, true);
        $resp = json_decode($response,true);
        
        
      	$paymentStatus = $resp['data']['status'];
        $chargeResponsecode = $resp['data']['chargecode'];
        $chargeAmount = $resp['data']['amount'];
        $chargeCurrency = $resp['data']['currency'];
        $vbMessage = $resp['data']['vbvmessage'];
        $sender = $resp['data']['custemail']; 
        $ref = $resp['data']['txref'];
        
        $card = $resp['data']['card']['brand'];
        
        $digit4 =   $resp['data']['card']['last4digits'];
        
      
      
     
if($paymentStatus === 'successful' ) {
    
    
    $payamt = $chargeAmount;
    $charge = 0; 
    $blockpro = '2';	


$bal3 = $bal2 + $payamt;


if($TXstatus === 'Pending'){
                    
$Qryadd = "UPDATE users SET bal=bal+$chargeAmount,blockpro='$blockpro' WHERE email='$UserEmail'";
               $AdFun = $conn->query($Qryadd);
                // update
                $tk = md5(uniqid());
				$statu = "Completed";
                $r = $flwref;
                

$up = "UPDATE deposit SET token='$tk',refer='$r',status='$statu',currency='$bal3',charge='$charge',method='Fluterwave',date='$dateTime' WHERE ref='$tid' ";
				$conn->query($up);

				// send email....

$from = " ".$settings['sitename']."<info@$serName>"; //the email address from which this is sent
$to = "$UserEmail"; //the email address you're sending the message to
$subject = "Wallet funding 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']."<info@$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/sitelogo/logo.png'>

<h3>Dear $fname $lname,</h3>

Your account has been credited <br> 

<h2 style='color:#06AF3E'>N$chargeAmount</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> ATM Card</td>
  </tr>
  
  <tr>
    <td>Card Fee</td>
    <td> $charge</td>
  </tr>
  
   <tr>
    <td>Transaction Status</td>
    <td> $statu </td>
  </tr>

<tr>
    <td>Previous Balance</td>
    <td> $bal2 </td>
  </tr>

<tr>
    <td>Current Balance</td>
    <td> $bal3 </td>
  </tr>
  
</table> <p>


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

If you have questions or 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);

		
$qryApi = mysqli_query($conn,"SELECT * FROM api_setting");
$apidata = mysqli_fetch_array($qryApi);
$apikey = $apidata['APIkey'];

$query_rec = mysqli_query($conn,"SELECT * FROM billing");
$bil = mysqli_fetch_array($query_rec);
$bi = $bil['sms'];
$new = number_format($bal3,2,'.',',');
$old = number_format($bal2,2,'.',',');

$txt = "Dear $fname
Credit Notification
Amount: N$paidamt
Charge: N$charge
Prev Bal: N$old
New Bal: N$new
Thank you for choosing Us.
www.$serName";
	  
$message = utf8_encode($txt);
$senderid = urlencode($from);
$aa = urlencode($message);
	   


//$baseurl ='https://vtuafrica.com.ng/portal/api/sms/?apikey='.$apikey.'&sendto='.$sendto.'&message='.urlencode($message).'&sender='.$senderid;
$baseurl ="https://vtuafrica.com.ng/portal/api/sms/?apikey=$apikey&sendto=$phone&message=$aa&sender=Wallet";


$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);
        
echo '<script> 
window.location.href="buy_credit.php?credit='.$r.' "; </script>';    
			    
                
                
}else{ 
            
  echo'<div class="alert alert-danger">
<strong>Wallet Already Funded Thank you!</strong>.  
		</div>'; 
		
            
            
        }
    
    
    
    }else {
      die('No or Invalid reference supplied');
      
     
    }
        
        


            
            
        }
    
    



  

         

?>