<?php
set_time_limit(0);
ini_set('display_errors', 1); 
ini_set('display_startup_errors', 1); 
error_reporting(E_ALL);
require_once("/home/fundbridge/crons.ballng.com/db.php");
require_once("/home/fundbridge/crons.ballng.com/email.php");

const VUSERKEY = "1691135759040";
function verifyvNINData($vnin){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,"https://api.verified.africa/sfx-verify/v3/id-service/");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('userid: '.VUSERKEY,'apiKey: 4NKoVFYVUMenhbHyodpY',"Content-Type:application/json"));
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array("searchParameter"=>$vnin,"countryCode"=>"NG","verificationType"=>"V-NIN")));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $res = curl_exec($ch);
    print_r($res);
    curl_close ($ch);
    if($res != ""){
        $res = json_decode($res, true);
        if($res && isset($res["responseCode"]) && $res["responseCode"] == "00"){
            echo "<br />";
            print_r($res["response"]);
            return $res["response"];
        }
        if(isset($res["responseCode"]) && ($res["responseCode"] == "02" || $res["responseCode"] == "03" || $res["responseCode"] == "15")){
            return true;
        }
    }
    return false;
}
function verifyvDriversData($number,$dob){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,"https://api.verified.africa/sfx-verify/v3/id-service/");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('userid: '.VUSERKEY,'apiKey: vM6MvBckeDHPGY6hO925',"Content-Type:application/json"));
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array("searchParameter"=>$number,"dob"=>$dob,"verificationType"=>"DRIVER-LICENSE-FULL-DETAIL-VERIFICATION")));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $res = curl_exec($ch);
    curl_close ($ch);
    if($res != ""){
        $res = json_decode($res, true);
        if($res && isset($res["responseCode"]) && $res["responseCode"] == "00"){
            return $res["response"];
        }
        if(isset($res["responseCode"]) && ($res["responseCode"] == "02" || $res["responseCode"] == "03" || $res["responseCode"] == "15")){
            return true;
        }
    }
    return false;
}
function verifyvPVCData($number){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,"https://api.verified.africa/sfx-verify/v3/id-service/");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('userid: '.VUSERKEY,'apiKey: dXnETKN5oWqwCg1KQbyZ',"Content-Type:application/json"));
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array("searchParameter"=>$number,"countryCode"=>"NG","verificationType"=>"VIN-FULL-DETAILS-VERIFICATION")));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $res = curl_exec($ch);
    curl_close ($ch);
    if($res != ""){
        $res = json_decode($res, true);
        if($res && isset($res["responseCode"]) && $res["responseCode"] == "00"){
            return $res["response"];
        }
        if(isset($res["responseCode"]) && ($res["responseCode"] == "02" || $res["responseCode"] == "03" || $res["responseCode"] == "15")){
            return true;
        }
    }
    return false;
}
function verifyvPassportData($number,$lname){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,"https://api.verified.africa/sfx-verify/v3/id-service/");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('userid: '.VUSERKEY,'apiKey: PQukAvWsLaa3nnuSbNUy',"Content-Type:application/json"));
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array("searchParameter"=>$number,"lastName"=>$lname,"verificationType"=>"PASSPORT-FULL-DETAILS")));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $res = curl_exec($ch);
    curl_close ($ch);
    print_r($res);
    if($res != ""){
        $res = json_decode($res, true);
        if($res && isset($res["responseCode"]) && $res["responseCode"] == "00"){
            return $res["response"];
        }
        if(isset($res["responseCode"]) && ($res["responseCode"] == "02" || $res["responseCode"] == "03" || $res["responseCode"] == "15")){
            return true;
        }
    }
    return false;
}
$verifications = mysqli_query($conn, "select * from verifications where status = 0 and uid = '145967' order by id desc");
while($verify = mysqli_fetch_assoc($verifications)){
    $uid = $verify['uid'];
    $user = mysqli_fetch_assoc(mysqli_query($conn, "select * from users where uid = '$uid' limit 1"));
    $user["fname"] = trim($user["fname"]);
    $user["lname"] = trim($user["lname"]);
    $document = mysqli_fetch_assoc(mysqli_query($conn, "select id_type,id_number,vnin from documents where uid = '$uid' limit 1")) ?? array();
    print_r($document);
    $status = intval($verify["status"]);
    echo $status;
    
    if($status == 0 && ($document["id_number"] ?? "") != ""){
        $message = "";
        $id_data = false;
        //pending
        switch($document["id_type"]){
            case "national_id":
                $id_data = verifyvNINData($document["vnin"]);
                break;
            case "international_passport":
                $id_data = verifyvPassportData($document["id_number"],$user["lname"]);
                break;
            case "voter_card":
                $id_data = verifyvPVCData($document["id_number"]);
                break;
            case "drive_license":
                $id_data = verifyvDriversData($document["id_number"],$user["dob"]);
                break;
            default:
                $id_data = false;
                break;
        }
        if(is_array($id_data)){
            //success
            $fname = "";
            $lname = "";
            $name = "";
            $dob = "";
            if($document["id_type"] == "national_id"){
                unset($id_data["photo"]);
                if(isset($id_data["firstName"]) && isset($id_data["surname"])){
                    $fname = $id_data["firstName"];
                    $lname = $id_data["surname"];
                    $dob = $id_data["dateOfBirth"];
                }
            }
            if($document["id_type"] == "international_passport"){
                if(isset($id_data["first_name"]) && isset($id_data["last_name"])){
                    $fname = trim($id_data["first_name"]);
                    $lname = trim($id_data["last_name"]);
                    $dob = $id_data["dob"];
                }
            }
            if($document["id_type"] == "voter_card"){
                if(isset($id_data["first_name"]) && isset($id_data["last_name"])){
                    $fname = trim($id_data["first_name"]);
                    $lname = trim($id_data["last_name"]);
                    $dob = $id_data["dob"];
                }
            }
            if($document["id_type"] == "drive_license"){
                if(isset($id_data["first_name"]) && isset($id_data["dob"])){
                    $fname = trim($id_data["first_name"]);
                    $lname = trim($id_data["last_name"]);
                    $dob = $id_data["dob"];
                }
            }
            if( (!empty($fname) && !empty($lname)) || !empty($name)){
                $validateName = empty($name) ? 
                (
                    (
                        (strtolower($fname) == strtolower($user["fname"]))
                        && 
                        (strtolower($lname) == strtolower($user["lname"]))
                    )
                    ||
                    (
                        (strtolower($fname) == strtolower($user["lname"]))
                        && 
                        (strtolower($lname) == strtolower($user["fname"]))
                    )
                ) : 
                ( 
                    str_contains(strtolower($name), strtolower($user["fname"]))
                    && 
                    str_contains(strtolower($name), strtolower($user["lname"])) 
                );
                
                if( $validateName ){
                    //name matches
                    if(strlen($dob) == 4){
                        // year only
                        $status = intval(date("Y", strtotime($verify["dob"]))) == intval($dob) ? 1 : 2;
                    }else{
                        $userDob = strtotime(date("Y-m-d", strtotime($verify["dob"])));
                        $verifyDOB = strtotime(date("Y-m-d", strtotime($dob)));
                        $status = $userDob == $verifyDOB ? 1 : 2;
                    }
                    if($status == 0){
                        //dob failed. send email
                        $message = "The date of birth supplied does not match the date of birth from the ID portal.";
                        $status = 2;
                    }
                }else{
                    //name failed. send email
                    $message = "Your name does not match the name from the ID portal, '".($name ?? "$fname $lname")."'";
                    $status = 2;
                }
            }else{
                //name failed. send email
                $message = "Your name does not match the name from the ID portal, '".($name ?? "$fname $lname")."'";
                $status = 2;
            }
            $id_data = json_encode($id_data);
        }else if(!$id_data){
            //failed. send failed email;
            $status = 2;
            $id_data = "";
            $message = "Invalid ID supplied.";
        }
        if($message != ""){
            echo $message;
            send($user["fname"]." ".$user["lname"],$user["email"], "verification_error",array("name"=>$user["fname"],"reason"=>$message));
        }
        $saveID = $conn->prepare("update verifications set status = ?, id_data = ? where uid = ? limit 1");
        $saveID->bind_param("iss", $status, $id_data,$uid);
        $saveID->execute();
        mysqli_query($conn, "update documents set status = '$status' where uid = '$uid' limit 1");
    }
    
    if($status == 1){
        send($user["fname"]." ".$user["lname"],$user["email"], "verification_pass",array("name"=>$user["fname"]));
    }
}
$conn->close();
?>