<?php

include("../main_includes/init.php");
// $secret_key = 'FLWSECK-2ade3da9213bc244d50dca7eb604f191-189f60815f1vt-X';
// $secretKey = 'FLWSECK_TEST-8d2b3d8d7dd3e172d8a2e044e1edf15d-X'; // Replace with your Flutterwave secret key
$secret_key = ENVIRONMENT == 'prod'? 'FLWSECK-2ade3da9213bc244d50dca7eb604f191-189f60815f1vt-X': "FLWSECK_TEST-8d2b3d8d7dd3e172d8a2e044e1edf15d-X";



extract($_GET);
$date = Date('c');



$url = 'https://api.flutterwave.com/v3/transactions/' . $transaction_id . '/verify';
$headers = array(
	'Content-Type: application/json',
	'Authorization: Bearer ' . $secret_key,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Send the HTTP request
$response = curl_exec($ch);

curl_close($ch);


if ($response === false) {
    // Request failed, handle accordingly
	echo 'Failed to confirm payment. Error: ' . curl_error($ch);
} else {
    
    $response = json_decode($response);

	$isSuccessful = false;
	$amount = 0;


	$paymentStatus = $response->status;
        // echo "<pre>";
// print_r($response);

// return false;
	if ($paymentStatus == 'success') {
		$amount = $response->data->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='unverify' LIMIT 1");
        // print_r($_GET);
        // print_r($my_transaction);
		// return false;
        $my_transaction = array_shift($my_transaction);
        if(!$my_transaction){
            redirect("../");
        }
		$my_transaction->status = "varified";
		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);
				$wallet->date_updated = $date;
				
				// print_r($payment);
				// print_r($wallet);
			// return false;
				if ($wallet->save()) {
					redirect(ROOT_URL);
				} else {

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

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


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



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

	Debug::print_r( $authorizationCode);
	*/