<?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'");
$reserve = mysqli_num_rows(mysqli_query($conn, "SELECT * FROM reservedAccounts WHERE email = '$email'"));
if ($reserve > 0) {
  die(json_encode(array("status" => false, "message" => "You've Nuban Already generated.")));
}
$configs = getPaymentsConfigs();
$secret = $configs["monnify_secret_key"];
$prod = $configs["monnify_api_key"];
$contract = $configs["monnify_contract_code"];
$bvn = $configs["monnify_bvn"];
$wiaxy_api = $configs["wiaxy_api_key"];
$user = mysqli_fetch_array($checkDet);
$bio = array("email" => $email, "firstName" => $user["firstName"], "lastName" => $user["lastName"], "phone" => $user["phone"]);
if ($bio) {
  $legalName = $user["firstName"] . " " . $user["lastName"];
  //Lets Get Things Done
  $login = base64_encode("$prod:$secret");
  $curl = curl_init();
  curl_setopt_array($curl, array(
    CURLOPT_URL => "https://api.monnify.com/api/v1/auth/login",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => '{}',
    CURLOPT_HTTPHEADER => array(
      "Authorization: Basic " . $login,
      "Content-Type: application/json"
    ),
  ));

  $response = curl_exec($curl);
  curl_close($curl);
  //echo $response;
  $resp = json_decode($response);
  $token = $resp->responseBody->accessToken;
  //We get the token, lets recon .... 
  $curl = curl_init();
  curl_setopt_array($curl, array(
    CURLOPT_URL =>  "https://api.monnify.com/api/v2/bank-transfer/reserved-accounts",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS =>
    '{
                "accountReference": "' . $email . '",
                "accountName": "' . $legalName . '",
                "currencyCode": "NGN",
                "contractCode": "' . $contract . '",
                "customerEmail": "' . $email . '",
                "bvn": "' . $bvn . '",
                "customerName": "' . $legalName . '",
                "getAllAvailableBanks": false,
                "preferredBanks": ["035","232","50515","070"]
          }',
    CURLOPT_HTTPHEADER => array(
      "Authorization: Bearer " . $token,
      "Content-Type: application/json"
    ),
  ));
  $response = curl_exec($curl);
  curl_close($curl);
  //echo $response;
  $respN = json_decode($response, true);
  if ($respN["requestSuccessful"] === true && $respN["responseMessage"] === "success") {
    $accs = $respN["responseBody"]["accounts"];
    $status = $respN["responseBody"]["status"];
    //$accounts = json_encode($accs);
    $codeOne = $accs[0]["bankCode"];
    $codeTwo = $accs[1]["bankCode"];
    $codeThree = $accs[2]["bankCode"];
    $codeFour = $accs[3]["bankCode"];
    $accs[0]["accountName"] = $legalName;
    $accs[1]["accountName"] = $legalName;
    $accs[2]["accountName"] = $legalName;
    $accs[3]["accountName"] = $legalName;
    $accs[0]["bankImage"] = getBankImg($codeOne);
    $accs[1]["bankImage"] = getBankImg($codeTwo);
    $accs[2]["bankImage"] = getBankImg($codeThree);
    $accs[3]["bankImage"] = getBankImg($codeFour);
    $wiaxyAccs = getWiaxyNuban();
    $accounts = json_encode($accs);
    $insert = mysqli_query($conn, "INSERT INTO reservedAccounts(email,account,status,raw) VALUES('$email','$accounts','$status','$response')");
    if ($insert) {
      die(json_encode(array("status" => true, "message" => "Account Generated Successfully.", "nubans" => $accs)));
    } else {
      die(json_encode(array("status" => false, "message" => "Whoops! try again later.")));
    }
  } else {
    die(json_encode(array("status" => false, "message" => "We have to Try this sometime.")));
  }
} else {
  die(json_encode(array("status" => false, "message" => "Couldn't resolve Details")));
}
