<?php
session_start();

include("../config.php");
//check if request was made with the right data
if(isset($_GET['reference'])){
    echo '
        <script>
            alert("Thief")
        </script>
    ';
    
    echo '
        <script>
            window.location = "./"
        </script>
    ';
}
if(!$_SERVER['REQUEST_METHOD'] == 'POST' || !isset($_POST['reference'])){  
  die("Transaction reference not found");
}else{

//set reference to a variable @ref
$reference = $_POST['reference'];
$email = $_POST['email'];

//The parameter after verify/ is the transaction reference to be verified
$url = 'https://api.paystack.co/transaction/verify/'.$reference;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt(
  $ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer sk_live_d3ab9a7f934cb3c400ca40ac602f72255f8655eb']
);

//send request
$request = curl_exec($ch);
//close connection
curl_close($ch);
//declare an array that will contain the result 
$result = array();

if ($request) {
  $result = json_decode($request, true);
}

if (array_key_exists('data', $result) && array_key_exists('status', $result['data']) && ($result['data']['status'] === 'success')) {
    $sql = $conn->query("SELECT * FROM `main_reg` WHERE `email`='$email'");
    $query = mysqli_fetch_array($sql);
    $myrefs = $query['ref'];
    $code = $query['hash_p'];
    $cd = $query['cd'];
    if($myrefs != ''){
        $sql2 = $conn->query("SELECT * FROM `main_reg` WHERE `cd`='$myrefs'");
        $query2 = mysqli_fetch_array($sql2);
        $refcode = $query2['hash_p'];
        
                $query4 = $conn->query("SELECT * FROM `referral` WHERE `code`='$refcode'");
	            if(mysqli_num_rows($query4) >= 1){
	                $row4 = mysqli_fetch_array($query4);
	                $amount = 5000;
	                $earn = 3000;
	                $bal = $row4['amount'];
	                $total = $bal + $earn;
	                $cm = $conn->query("UPDATE `referral` SET `amount`='$total' WHERE `code`='$refcode'");
	                $conn->query("INSERT INTO `ref_history`(`id`, `refcode`, `code`, `amount`,`amount_inv`) VALUES (NULL,'$refcode','$code','$earn', '$amount')");
	            }else{
	                $amount = 5000;
	                $earn = 3000;
	                $cm = $conn->query("INSERT INTO `referral`(`id`, `code`, `amount`, `status`) VALUES (NULL,'$refcode','$earn','1')");
	                $conn->query("INSERT INTO `ref_history`(`id`, `refcode`, `code`, `amount`,`amount_inv`) VALUES (NULL,'$refcode','$code','$earn', '$amount')");
	            }
        
    }
    $qc = $conn->query("UPDATE `main_reg` SET `active`='3',`status`='3' WHERE `email`='$email'");
    if($qc == true){
        echo 'success';
    }else{
        echo 'contact support@eaglewinks.com';
    }
	//Perform necessary action
}else{
  echo "Transaction was unsuccessful";
}

}

?>