<?php
header('Content-Type: application/json');
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    include "../../ajax/konnection.php";
    include "../../ajax/func.php";
    $configs = getPaymentsConfigs();
    $psb9_config = $configs["payvessel_api_key"];
    $psb = json_decode($psb9_config);
    if (isset($psb->secret) && !empty($psb->secret)) {
        $payload = file_get_contents('php://input');
        $signature = $_SERVER['HTTP_PAYVESSEL_HTTP_SIGNATURE'];
        $ip = $_SERVER['REMOTE_ADDR'];
        $hashkey = hash_hmac('sha512', $payload, $psb->secret ?? null);
        //file_put_contents('pvs.json', $payload);
        if ($signature == $hashkey && $ip == "162.246.254.36") {
            $data = json_decode($payload, true);
            $amount = floatval($data['order']['amount']);
            $fee = floatval($data['order']['fee']);
            $paidon = $data['transaction']['date'];
            $amount_paid = floatval($data['order']['settlement_amount']);
            $reference = "9PSB|" . $data['transaction']['reference'];
            $description = $data['order']['description'];
            $email = $data['customer']['email'];
            $verify = mysqli_num_rows(mysqli_query($conn, "SELECT * FROM transactions WHERE transaction_id='$reference'"));
            // $verify = mysqli_query($conn, "SELECT * FROM transactions WHERE transaction_id = '$reference'");
            if ($verify > 0) {
                die(json_encode(array("status" => false, "message" => "Transaction Already Proccessed")));
            }
            if ($verify == 0) {
                $r_bal = mysqli_query($conn, "SELECT * FROM balance where user='$email'");
                while ($r = mysqli_fetch_array($r_bal)) {
                    $bal = $r["amount"];
                }
                $credit_balance = $bal + $amount_paid;
                $mess = "Wallet Funding Using 9Payment Service Bank";
                $credit = mysqli_query($conn, "UPDATE balance SET amount='$credit_balance' WHERE user='$email'");
                $img = "assets/img/banks/psb9.png";
                $now = date("Y-m-d H:i:s");
                mysqli_query($conn, "INSERT INTO transactions (user,transaction_id,type,amount,amount_charged,balance_before, balance_after, profit, beneficiary,whenn,status,serviceImg,message) VALUES('$email','$reference','Wallet TopUp','N$amount','$amount', '$bal','$credit_balance','0', '$email','$now','Completed','$img', '$mess')");
                //die(json_encode(array("status" => true, "amount" => "")));
                http_response_code(200);
                exit();
            } else {
                http_response_code(200);
            }
        } else {
            http_response_code(400);
        }
    }
} else {
    http_response_code(405);
}
