<?php

include("../../includes/init.php");

require_once "../../vendor/autoload.php";

use Matscode\Paystack\Transaction;
use Matscode\Paystack\Utility\Debug;


// creating the transaction object
$Transaction = new Transaction(SECRET_KEY);

// transaction can be verified by doing manual check on the response Obj
// Debug::print_r($response);
/*


// OR

/*
Debug::print_r( $result);
*/

// To check if verified amount is the expected amount before giving value to customer

// $result = $Transaction->isSuccessful();
$response = $Transaction->verify($_GET['reference']);

$isSuccessful = false;
$amount = 0;

if (
	isset($response->data) && is_object($response->data) &&
	$response->status == true &&
	$response->data->status == 'success'
) {
	$amount = $response->data->amount;
	$isSuccessful = true;
}

// echo "<pre>";
// print_r($response);
// echo "</pre>";
// return false;

if ($isSuccessful) {

	$my_transaction = MyTransaction::find_by_query("SELECT * FROM transaction WHERE user_id=$_GET[sasd] AND reference='$_GET[reference]' LIMIT 1");
	$my_transaction = array_shift($my_transaction);
	$my_transaction->status = "Varified";
	if ($my_transaction->save()) {

		$payment = new Payment;

		$payment->user_id = $my_transaction->user_id;
		$payment->amount = $my_transaction->amount;
		$payment->reference = $my_transaction->reference;
		$payment->status = $my_transaction->status;
		$payment->date_created = $date;
		$payment->date_updated = $date;

		if ($payment->save()) {
			$wallet = Wallet::find_by_query("SELECT * FROM wallet WHERE user_id=$payment->user_id LIMIT 1");
			$wallet = array_shift($wallet);
			$wallet->balance += (intval($amount) / 100);
			$wallet->date_updated = $date;

			if ($wallet->save()) {
				redirect("../../?page=fund_wallet&" . md5($wallet->user_id) . "=" . base64_encode($amount / 100));
			} else {

				echo "Error Contact System Administrator";
			}
		} else {
			echo "Error Contact System Administrator";
		}
	} else {
		echo "Error Contact System Administrator";
	}
} else {

	echo "Error Contact System Administrator";
}
// $result = $Transaction->amountEquals(5000); // amount in kobo
// Debug::printStr($result);



	// Getting AuthorizationCode
	/*
	$authorizationCode = $Transaction->getAuthorizationCode();

	Debug::print_r( $authorizationCode);
	*/