<?php

// PAYVESSEL API WEBHOOK NOTIFICATION


include_once("../ajax/konnection.php");

$funding_type = "Automatic Funding";
$fullname = "From 9PSB Bank";

// Verify if the request is a POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405); // Method Not Allowed
    exit(json_encode(["message" => "Method not allowed"]));
}

// Retrieve the raw POST data
$payload = file_get_contents('php://input');

// Ensure the payload is not empty
if (empty($payload)) {
    http_response_code(400); // Bad Request
    exit(json_encode(["message" => "Empty payload received"]));
} 
$apiQuery = "SELECT payvessel_api_key FROM paymentconfigs LIMIT 1";
    $apiResult = $conn->query($apiQuery);
    
    if ($apiResult->num_rows > 0) {
        $apiData = $apiResult->fetch_assoc();

        $secretKey = $apiData['payvessel_api_key'];
    } else {
        echo json_encode(array("success" => false, "message" => "API credentials not found."));
        exit();
    }

// Retrieve Payvessel signature and IP address
$payvessel_signature = $_SERVER['HTTP_PAYVESSEL_HTTP_SIGNATURE'];
$ip_address = $_SERVER['REMOTE_ADDR']; // Use 'HTTP_X_FORWARDED_FOR' if needed
$trusted_ips = ["3.255.23.38", "162.246.254.36"];
$secret = $secretKey;

// Calculate HMAC hash
$hashkey = hash_hmac('sha512', $payload, $secret);

// Verify signature and IP address
if ($payvessel_signature !== $hashkey || !in_array($ip_address, $trusted_ips)) {
    http_response_code(403); // Forbidden
    exit(json_encode(["message" => "Permission denied, invalid hash or IP address"]));
}

// Decode JSON payload
$data = json_decode($payload, true);

// Check JSON decoding errors
if ($data === null && json_last_error() !== JSON_ERROR_NONE) {
    http_response_code(400); // Bad Request
    exit(json_encode(["message" => "Invalid JSON format"]));
}




            $email = $res->customer->email;
            $amount = $res->order->amount;
            $transactionReference = $res->transaction->reference;

            // Verify The Transaction
            $check = $controller->verifyPayvesselRef($email, $payvessel_signature, $input);

            if ($check->status == "success") {
                $userid = $check->userid;
                    $userbalance = $check->balance;
                        $email = $check->useremail;
                            $charges = (float) $check->charges;
                                $chargestype = $check->chargestype;
                                    $amount = (float) $amount;

                                        if ($chargestype == "flat") { 
                                                $amounttosave = $amount - $charges;
                                                        $chargesText = "N".$charges;
                                                            } else { 
                                                                    $amounttosave = $amount - ($amount * ($charges/100)); 
                                                                            $chargesText = $charges."%";
                                                                                }

                                                                                    $servicename = "Wallet Topup";
                                                                                        $servicedesc = "Wallet funding of N{$amount} via Payvessel transfer with a service charge of $chargesText.";
                                                                                            $servicedesc .= " Your wallet has been credited with N{$amounttosave}.";
                                                                                                $transactionReference = "PAYVESSEL_".$transactionReference;
                                                                                                    $result = $controller->recordPayvesselTransaction($userid, $servicename, $servicedesc, $amounttosave, $userbalance, $transactionReference, "0");
                                                                                                        $message = $servicedesc . " Your transaction reference is $transactionReference.";
                                                                                                            
                                                                                                                // Send Email Notification
                                                                                                                    $controller->sendEmailNotification($servicename, $message, $email);

                                                                                                                        echo "Success";
                                                                                                                            http_response_code(200);
                                                                                                                                exit();

                                                                                                                                } else {
                                                                                                                                    echo "UnAuthorized"; 
                                                                                                                                        http_response_code(401); 
                                                                                                                                            exit();
                                                                                                                                            }

                                                                                                                                            ?>