<?php
session_start();
include "konnection.php";
include "func.php";

if (!isset($_SESSION["user"])) {
    header("location: login.php");
    die(json_encode(array("status" => false, "message" => "Auth Invalid")));
}

$email  = $_SESSION["user"];
require "vends/Verification.php";
$vars = json_decode(file_get_contents("php://input"));
if (!isset($vars->idNumber)) {
    die(json_encode(array("message" => "ID Number Not Found")));
}
if (!isset($vars->idType)) {
    die(json_encode(array("message" => "ID Type Not Found")));
}
if (!isset($vars->slipType)) {
    die(json_encode(array("message" => "Details Not Specified")));
}
if (!isset($vars->consent)) {
    die(json_encode(array("message" => "Consent Not Found")));
}
if ($vars->consent !== true) {
    die(json_encode(array("message" => "You must have consent to verify user data")));
}
if (strlen($vars->idNumber) != 11) {
    die(json_encode(array("message" => strtoupper($vars->idType) . " should be 11 Digits Long")));
}
$imgg = "assets/img/nibss.png";
$now = date("Y-m-d H:i:s");
$bal = getBal($email);
$user = getUserDetails($email);
if ($user["status"] == 0) {
    die(json_encode(array("status" => "caption", "message" => "You've to be verified to use this service")));
}
if ($user["isban"] == 1) {
    die(json_encode(array("status" => "caption", "message" => "You're banned from using our services. Contact admin")));
}
if ($user["canVerifyBVN"] == 0) {
    die(json_encode(array("status" => "caption", "message" => "Service not available for your account. Contact admin")));
}
$service_tag = $vars->idType;
$service = getAvalability($service_tag);
if ($service != "ON") {
    die(json_encode(array("status" => "caption", "message" => strtoupper($vars->idType) . " is not available currently")));
}
$slip = $vars->slipType;
$charges = getCharges();
$charge = $charges["bvn" . ucfirst($slip)];
$getWebConfigs = getWebConfigs();
$auth["app_id"] = $getWebConfigs["id_app_id"];
$auth["api_key"] = $getWebConfigs["id_api_key"];
// if (!filter_var($getWebConfigs["id_url"], FILTER_VALIDATE_URL)) {
//     die(json_encode(array("status" => "caption", "message" => "Unfinished Setup, Contact Admin Support (ERR2)")));
// }
$payload = [
    "url" => $getWebConfigs["id_url"],
    "number" => $vars->idNumber,
    "provider" => $vars->idType,
    "amount" => $charge,
];
$number = $vars->idNumber;
$serv = strtoupper($vars->idType);
if ($bal >= (int)$charge) {
    $verify = new Verification();
    $verif = $verify->$serv($auth, $payload);
    $resp = json_decode($verif);
    if ($resp->status === true) {
        $pure = $resp->response;
        $id = $pure->id;
        $status = $pure->status;
        $plan_amount = $pure->amount;
        $message = $pure->response;
        $slug = strtoupper($vars->idType);
        $profit = (float)$plan_amount;
        if ($status == "success") {
            $values = [
                "type" => strtoupper($vars->idType),
                "value" => $vars->idNumber
            ];
            if ($serv === "BVN") {
                $fistName = $message->firstName;
                $lastName = $message->lastName;
                $otherName = $message->middleName;
                $phone = $message->phoneNumber1;
                $dob = $message->dateOfBirth;
                $img = $message->base64Image;
                $image_name = uniqid() . ".png";
                $image = $image_name;
                foreach ($message as $key => $value) {
                    $message->$key = filter_var($value, FILTER_SANITIZE_STRING);
                    $message->$key = rtrim($value);
                    $message->$key = str_replace("\n", " ", $value);
                    $message->$key = str_replace("'", "", $value);
                    $message->$key = trim(preg_replace('/\s+/', ' ', $value));
                }
                $formm = json_decode(json_encode($message), true);
                unset($formm["photo"]);
                unset($formm["signature"]);
                $form = json_decode(json_encode($formm));
                $placeholder = VERIFICATION_ASSETS . "bvn/" . $image;
                $search_values = json_encode($values);
                $displayName = $fistName . " " . $lastName;
                $report_response = json_encode($form);
                file_put_contents('../avatars/bvn/' . $image_name, base64_decode($img));
            }
            $new = (int)$bal - (int)$charge;
            mysqli_query($conn, "UPDATE balance SET amount = '$new' WHERE user = '$email'");
            mysqli_query($conn, "INSERT INTO transactions (user,transaction_id,type,amount,balance_before,amount_charged,balance_after,profit,beneficiary,whenn,status,serviceImg,message)
                VALUES('$email','$id','ID Verification','$slug','$bal','$charge','$new','$profit','$number','$now','Completed','$imgg','ID Verified Successfull')");

            $add = mysqli_query($conn, "INSERT INTO reports (user, report_id, display_name, placeholder, report_type, search_values, report_response, slip_type, is_found, transaction, date_created) 
                VALUES ('$email', '$id', '$displayName', '$placeholder', '$serv', '$search_values', '$report_response', '$slip', true, '','$now')");
            echo json_encode(array("status" => true, "message" => "Verification Initiated Successful", "transID" => $id));
            $url = "https://webtopdf.com/Controllers/Convert.ashx";
            $curl = curl_init($url);
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            $headers = array(
                "Content-Type: application/json",
            );
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
            $baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'];
            $uslip = "{$baseUrl}/slips/bvn/?reportID=" . $id . "&preview=1";
            $data = '
                {
                    "filepath":"' . $uslip . '",
                    "pagesize":"A4",
                    "width":"",
                    "height":"",
                    "landscape":"false",
                    "leftmargin":"12",
                    "topmargin":"12",
                    "rightmargin":"12",
                    "bottommargin":"14",
                    "htmlzoom":"100",
                    "header":"",
                    "footer":"",
                    "pw":"",
                    "permissions":"011",
                    "type":"PDF",
                    "useprintmedia":"true",
                    "noscript":"false",
                    "nolink":"false",
                    "pagenumber":"false",
                    "grayscale":"false",
                    "bookmark":"false",
                    "minloadwaittime":"8",
                    "wmtext":"",
                    "wmfonttype":"0",
                    "wmfontsize":"14",
                    "wmfontbold":"false",
                    "wmfontitalic":"false",
                    "wmfontcolor":"000000",
                    "wmprefixtype":"0",
                    "wmopacity":"100",
                    "wmrotationtype":"0",
                    "wmbkmode":"0",
                    "curUrl":"/",
                    "zipmode":"0",
                    "convertemode":"00"
                }';
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            $resp = curl_exec($curl);
            //die($resp);
            curl_close($curl);
            $respJ = json_decode($resp);
            $pdfName = $id . '.pdf';
            if ($respJ->convertedFilePath) {
                $ch = curl_init();
                $url = "https://webtopdf.com/RESULT/" . $respJ->convertedFilePath;
                curl_setopt($ch, CURLOPT_URL, $url);
                $fp = fopen("https://ibill.com.ng/slips/bvn/" . $pdfName, 'w+');
                curl_setopt($ch, CURLOPT_FILE, $fp);
                curl_exec($ch);
                curl_close($ch);
                fclose($fp);
                $pdfURL = "https://ibill.com.ng/slips/bvn/" . $pdfName;
                mysqli_query($conn, "UPDATE reports SET pdf = '$pdfURL' WHERE report_id = '$id'");
            }
            die();
        } else {
            $new = (int)$bal - (int)20;
            // mysqli_query($conn, "UPDATE balance SET amount = '$new' WHERE user = '$email'");

            mysqli_query($conn, "INSERT INTO transactions (user,transaction_id,type,amount,balance_before,amount_charged,balance_after,profit,beneficiary,whenn,status,serviceImg,message)
                VALUES('$email','$id','ID Verification','$slug','$bal','$charge','$bal','$profit','$number','$now','$status','$imgg','ID Verification Not Found')");
            die(json_encode(array("status" => true, "message" => $message, "transID" => $id)));
        }
    } else {
        die(json_encode(array("status" => "caption", "message" => $resp->response->response)));
    }
} else {
    die(json_encode(array("status" => "caption", "message" => "InSufficient Fund to perform operation")));
}
