<?php
// IP Whitelist - Verify IP address against monnify IP  35.242.133.146
$ip = ($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:$_SERVER['REMOTE_HOST'];
if( $ip != "35.242.133.146") {

    die("Invalid IP");
}
 
// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

// class CustomTransactionHashUtil {
//     public static function computeSHA512TransactionHash($stringifiedData, $clientSecret) {
//       $computedHash = hash_hmac('sha512', $stringifiedData, $clientSecret);
//       return $computedHash;
//     }
// }

// Retrieve the raw POST data from the webhook
$requestBody = file_get_contents('php://input');
$CLIENT_SECRET = "FKQEEF5WPUZZ4C4VNSVXJSL6B7NNEQ2Z";

$payload = json_decode($requestBody);

if (!empty($payload)) {
    // Payload based on the event type
    $eventType = $payload->eventType;
    $eventData = $payload->eventData;
    
    if ($eventType === 'SUCCESSFUL_TRANSACTION') {
        // Handle successful transaction event
        if ($eventData->product->type == "RESERVED_ACCOUNT") {
            // Handle payment success event
            $paymentReference = $eventData->paymentReference;

            $existed_payment = Payment::find_by_query("SELECT * FROM payment WHERE reference='$paymentReference'");

            if (empty($existed_payment)) {
                $amountPaid = $eventData->amountPaid;
                $user_email = $eventData->customer->email;

                $user = User::find_by_query("SELECT * FROM user WHERE email='$user_email' LIMIT 1");
                $user = array_shift($user);

                $payment = new Payment;

                $payment->user_id = $user->id;
                $payment->amount = $amountPaid;
                $payment->reference = $paymentReference;
                $payment->status = 'Verified';
                $payment->date_created = $date;
                $payment->date_updated = $date;
                $payment->response = $requestBody;
                $payment->method = "RESERVED_ACCOUNT - " . $eventData->destinationAccountInformation->bankName . " (" . $eventData->destinationAccountInformation->accountNumber . ")";

                $payment->save();

                $wallet = Wallet::find_by_query("SELECT * FROM wallet WHERE user_id=$user->id LIMIT 1");
                $wallet = array_shift($wallet);
                $wallet->balance += (intval($amountPaid));
                $wallet->date_updated = $date;

                $wallet->save();
            }
        }
    } else {
        // Handle other webhook event types
    }
} else {
    // Handle empty or invalid webhook payload
}

http_response_code(200);
?>
