<?php

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

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

// print_r($_GET);
// return false;

$curl = curl_init();

curl_setopt_array($curl, array(
	CURLOPT_URL => "https://api-d.squadco.com/transaction/verify/" . $_GET['reference'],
	// CURLOPT_URL => "https://sandbox-api-d.squadco.com/transaction/verify/" . $_GET['reference'],
	CURLOPT_RETURNTRANSFER => true,
	CURLOPT_ENCODING => "",
	CURLOPT_MAXREDIRS => 10,
	CURLOPT_TIMEOUT => 30,
	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
	CURLOPT_CUSTOMREQUEST => "GET",
		"Authorization: Bearer sk_6756a57bce8ce3a8c9fd697b9af4dac1e6114a16",
	CURLOPT_HTTPHEADER => array(
    	"Authorization: Bearer sk_b53fc8bab69731a0c22a2e18437d2de50c3ccadf",
		"Cache-Control: no-cache",
	),
));

$response = curl_exec($curl);
$response = json_decode($response);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
	echo "Payment Verification failed:" . $err;
} else {


	$isSuccessful = false;
	$amount = 0;


	if (
		isset($response->data) && is_object($response->data) &&
		$response->status == 200 &&
		$response->message == 'Success'
	) {

		$amount = $response->data->transaction_amount;
		$isSuccessful = true;
	}
	if ($isSuccessful) {
		$my_transaction = MyTransaction::find_by_query("SELECT  * FROM transaction WHERE user_id='$_GET[sasd]' AND reference='$_GET[tx_ref]' AND status='Not Varified' LIMIT 1");
        // print_r($_GET);
        // print_r($my_transaction);
		// return false;
        $my_transaction = array_shift($my_transaction);
        if(!$my_transaction){
            redirect("../");
        }
		if ($my_transaction->save()) {

			$payment = new Payment;

			$payment->user_id = $my_transaction->user_id;
// 			$payment->amount = 0;
			$payment->amount = $my_transaction->amount;
			$payment->reference = $my_transaction->reference;
			$payment->status = $my_transaction->status;
			$payment->method = "Payment Gateway";


			$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("../");
				} else {

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

		echo "Error Contact System Administrator";
	}
}
// return false;


// $result = $Transaction->amountEquals(5000); // amount in kobo
// Debug::printStr($result);



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

	Debug::print_r( $authorizationCode);
	*/