<?php

declare(strict_types=1);
header('Access-Control-Allow-Origin: *');

use Firebase\JWT\JWT;

require_once('vendor/autoload.php');
$head =  json_encode(getallheaders());
$unhead = json_decode($head, true);
if (!isset($unhead["Authorization"])) {
    http_response_code(400);
    die(json_encode(array("message" => "NO_AUTH_HEADER_FOUND")));
}
$head = $unhead["Authorization"];
$matches = explode(' ', $head);
if (!isset($matches[0]) && $matches[0] != "Bearer") {
    http_response_code(400);
    die(json_encode(array("message" => "PATTERN_NOT_SET")));
}
if (!isset($matches[1])) {
    http_response_code(400);
    die(json_encode(array("message" => "TOKEN_NOT_FOUND")));
}
$jwt = $matches[1];
if (empty($jwt)) {
    http_response_code(400);
    die(json_encode(array("message" => "TOKEN_EMPTY")));
}
$secretKey  = 'wt4es0cj6BIN1pokBJEVLvOGdqa3q8dBYbvzpf9MKlvllqNBdQhYbmHt8Q0TNDDzfCWAynTcKtwk50WJsi8vVOpexkMP6uqIjRLd92eWqaJupsAc9qbZ3rLZIV8qIeps';
$token = JWT::decode($jwt, $secretKey, ['HS512']);
$now = new DateTimeImmutable();
$serverName = "ksbdata.com";
//echo $token;
include "konnection.php";
include "func.php";
$email = $token->data->wxt;
$checkDet = mysqli_query($conn, "SELECT * FROM users WHERE email = '$email'");
$user = mysqli_fetch_array($checkDet);
$checkBal = mysqli_query($conn, "SELECT amount FROM balance WHERE user = '$email'");
$r = mysqli_fetch_array($checkBal);
$bal = (float)$r['amount'];
$charges = getCharges();
$site = getSite();
$bio = array("email" => $email, "firstName" => $user["firstName"], "lastName" => $user["lastName"], "phone" => $user["phone"], "role" => $user["role"]);
if (isset($bal) && $bio) {
    $out = array();
    $checkTrans = mysqli_query($conn, "SELECT * FROM transactions WHERE user = '$email' ORDER by id DESC LIMIT 4");
    if (mysqli_num_rows($checkTrans) > 0) {

        while ($row = mysqli_fetch_assoc($checkTrans)) {
            $out[] = $row;
        }
    }
    $bal = (int)$bal;
    $formatted_bal = number_format($bal, 2);
    $reserve = mysqli_query($conn, "SELECT * FROM reservedAccounts WHERE email = '$email'");
    $reserveRows = mysqli_num_rows($reserve);
    if ($reserveRows > 0) {
        $parts = mysqli_fetch_array($reserve);
        if ($site["monnify_payment"] == "ON") {
            $nubans = json_decode($parts["account"], true);
            $nubC = 0;
            foreach ($nubans as $nuba) {
                if ($nuba["bankCode"] == "232") {
                    $evicted = $nubans[$nubC];
                    unset($nubans[$nubC]);
                }
                $nubC++;
            }
            array_push($nubans, $evicted);
        } else {
            $nubans = [];
        }
    } else {
        $nubans = [];
    }
    $reserveWiaxy = mysqli_query($conn, "SELECT * FROM wiaxyAccounts WHERE email = '$email'");
    $reserveWiaxyRows = mysqli_num_rows($reserveWiaxy);
    if ($reserveWiaxyRows > 0) {
        $parts = mysqli_fetch_array($reserveWiaxy);
        if ($site["wiaxy_payment"] == "ON") {
            $nubs = json_decode($parts["account"]);
        } else {
            $nubs = [];
        }
    } else {
        $nubs = [];
    }
    /*
        $reserveVFD = mysqli_query($conn, "SELECT * FROM vpayAccounts WHERE email = '$email'");
        $reserveVFDRows = mysqli_num_rows($reserveVFD);
        if($reserveVFDRows > 0){
           $partsy = mysqli_fetch_array($reserveVFD);
           if($site["wiaxy_payment"] == "ON"){
            $nubsy = json_decode($partsy["account"]);
           }else{
            $nubsy = [];   
           }
        }else{
           $nubsy = [];
        }
        
        */

    $nubsy = [];
    $accounts = array_merge($nubs, $nubans);

    $notif = mysqli_query($conn, "SELECT * FROM notifications");
    $notifRows = mysqli_num_rows($notif);
    if ($notifRows > 0) {
        $parts = mysqli_fetch_array($notif);
        $notify = (bool)$parts["showMessage"];
        $message = $parts["message"];
    } else {
        $notify = false;
        $message = null;
    }

    if ($reserveWiaxyRows == 0) {
        $configs = getPaymentsConfigs();
        $wiaxy_api = $configs["wiaxy_api_key"];
        $webhook = "https://app.ksbdata.com/callback/wiaxy/resp.php";
        $wiaxyAccs = getWiaxyNuban2($wiaxy_api, $email, $email, $user["firstName"], $user["lastName"], $user["phone"], $webhook);
        if (is_array($wiaxyAccs)) {
            $accs[0]["bankCode"] = "KUDA";
            $accs[0]["accountNumber"] = $wiaxyAccs["account_number"];
            $accs[0]["accountName"] = $wiaxyAccs["account_name"];
            $accs[0]["bankName"] = $wiaxyAccs["bank_name"];
            $accs[0]["bankImage"] = "img/assets/kuda.png";
            $wAccounts = json_encode($accs);
            $insert = mysqli_query($conn, "INSERT INTO wiaxyAccounts(email,account,status,raw) VALUES('$email','$wAccounts','ACTIVE','')");
        }
    }
    /*
       if($reserveVFDRows == 0){
            $vfdAccs = getVFD($wiaxy_api,$email,$email,$user["firstName"],$user["lastName"],$user["phone"]);
            if(!is_bool($vfdAccs)){
                $accsy[0]["bankCode"] = "VFD";
                $accsy[0]["accountNumber"] = $vfdAccs;
                $accsy[0]["accountName"] = $user["firstName"] . " " .$user["lastName"];
                $accsy[0]["bankName"] = "VFD Microfinance Bank";
                $accsy[0]["bankImage"] = "img/assets/vfd.png";
                $vAccounts = json_encode($accsy);
                $insert = mysqli_query($conn, "INSERT INTO vpayAccounts(email,account,status,raw) VALUES('$email','$vAccounts','ACTIVE','$vfdAccs')");
            }  
       }
       */



    die(json_encode(
        array(
            "status" => true,
            "bal" => $formatted_bal,
            "notif" => $notify,
            "notification" => $message,
            "user" => $bio,
            "commission" => 50,
            "transactions" => $out,
            "reserve" => $reserveRows,
            "cont" => count($out),
            "nubans" => $accounts,
            "charges" => "₦" . $charges["monnifyDeposit"],
            "token" => ""
        )
    ));
} else {
    die(json_encode(array("status" => false, "message" => "Couldn't resolve balance")));
}
