<?php
require_once('../../vendor/autoload.php');
require_once('../init.php');
$client = new \GuzzleHttp\Client();

// define('API_BASE', 'https://api.myidentitypass.com');
// define('API_BASE', 'https://sandbox.myidentitypass.com');

function generate_reference()
 {
  $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  $charactersLength = strlen($characters);
  $nums = '0123456789';
  $nums_length = strlen($nums);
  $reference = '';
  for ($i = 0; $i < 12; $i++) {

   $reference .= $nums[rand(0, $nums_length - 1)];
  }
  for ($i = 0; $i < 2; $i++) {

   $reference .= $characters[rand(0, $charactersLength - 1)];
  }
  for ($i = 0; $i < 3; $i++) {

   $reference .= $nums[rand(0, $nums_length - 1)];
  }
  return $reference;
 }
 
 
function error_res($status, $response_code, $message)
{
    $response = new stdClass;
    $response->status = $status;
    $response->response_code = $response_code;
    $response->message = $message;
    return json_encode($response);
}

if (isset($_SESSION['user_id'])) {
    extract($_POST);
    if (isset($phone) && !empty($service_type)) {

        $user = User::find_by_id($_SESSION['user_id']);
        if ($user) {

            $service_type = Service::find_by_id($service_type);

            // print_r($service_type);
            // return false;

            if (!$service_type) {
                echo error_res(false, "03", "Service Not Avilable, Contact Administrator!");
                exit;
            }

            $service = $service_type->service_name;
            $service_fee = intval($service_type->service_fee);
            $status = 0;

            $my_wallet = Wallet::find_by_query("SELECT * FROM wallet WHERE user_id =" . $user->id . " LIMIT 1");
            $my_wallet = array_shift($my_wallet);
            $my_wallet_balance = intval($my_wallet->balance);

            if ($my_wallet_balance >= $service_fee) {

                try {

                    $headers = [
                        'userid' => '1662732332645',
                        'apiKey' => 'nDYWizheJo9s8IHUciXe',
                        'Content-Type' => 'application/json'
                    ];
                    $body = json_encode([
                        'verificationType' => 'NIN-VERIFY',
                        'countryCode' => 'NG',
                        "transactionReference" => generate_reference() . "_AVERIFY",
                        'searchParameter' => $phone
                    ]);

                    $response = $client->request('POST', 'https://api.verified.africa/sfx-verify/v3/id-service/', [
                        'headers' => $headers,
                        'body' => $body
                    ]);

                    $responses = $response->getBody(); 

                    // print_r($responses);
                } catch (\Throwable $th) {

                    // print_r($th->getMessage());
                    echo error_res(false, "04", "Network Error! try using VNIN Search.");
                    exit;
                }

                // print_r();

                $response_std = json_decode($responses);
                // print_r($response_std);

                // return false;

                $service_record = new ServiceRecord;
                $in_transaction = new InTransaction;

                // print_r($response_std->data->image);

                // return false;

                if (isset($response_std->responseCode) && $response_std->responseCode == "00" && !empty($response_std->response[0]->firstname)) {
                    $status = 1;

                    $new_response_std = new stdClass;
                    $new_response_std->response_code = "00";
                    $new_response_std->detail = "Verification Successful";
                    $new_response_std->nin_data = new stdClass;

                    $new_response_std->nin_data->birthdate = $response_std->response[0]->birthdate;
                    $new_response_std->nin_data->birthlga = $response_std->response[0]->birthlga;
                    $new_response_std->nin_data->birthstate = $response_std->response[0]->birthstate;
                    $new_response_std->nin_data->centralID = $response_std->response[0]->centralID ?? '';
                    $new_response_std->nin_data->educationallevel = $response_std->response[0]->educationallevel ?? '';
                    $new_response_std->nin_data->email = $response_std->response[0]->email ?? '';
                    $new_response_std->nin_data->emplymentstatus = $response_std->response[0]->emplymentstatus ?? '';
                    $new_response_std->nin_data->firstname = $response_std->response[0]->firstname;
                    $new_response_std->nin_data->middlename = $response_std->response[0]->middlename ?? '';
                    $new_response_std->nin_data->gender = strtoupper($response_std->response[0]->gender);
                    $new_response_std->nin_data->heigth = $response_std->response[0]->heigth ?? '';
                    $new_response_std->nin_data->maritalstatus = $response_std->response[0]->maritalstatus ?? '';
                    $new_response_std->nin_data->nin = $response_std->response[0]->nin;
                    $new_response_std->nin_data->trackingId = $response_std->response[0]->trackingId ?? '';
                    $new_response_std->nin_data->nok_address1 = $response_std->response[0]->nok_address1 ?? '';
                    $new_response_std->nin_data->nok_address2 = $response_std->response[0]->nok_address2 ?? '';
                    $new_response_std->nin_data->nok_firstname = $response_std->response[0]->nok_firstname ?? '';
                    $new_response_std->nin_data->nok_lga = $response_std->response[0]->nok_lga ?? '';
                    $new_response_std->nin_data->nok_middlename = $response_std->response[0]->nok_middlename ?? '';
                    $new_response_std->nin_data->nok_postalcode = $response_std->response[0]->nok_postalcode ?? '';
                    $new_response_std->nin_data->nok_state = $response_std->response[0]->nok_state ?? '';
                    $new_response_std->nin_data->nok_surname = $response_std->response[0]->nok_surname ?? '';
                    $new_response_std->nin_data->nok_town = $response_std->response[0]->nok_town ?? '';
                    $new_response_std->nin_data->nspokenlang = $response_std->response[0]->nspokenlang ?? '';
                    $new_response_std->nin_data->ospokenlang = $response_std->response[0]->ospokenlang ?? '';
                    $new_response_std->nin_data->pfirstname = $response_std->response[0]->pfirstname ?? '';
                    $new_response_std->nin_data->photo = $response_std->response[0]->photo ?? '';
                    $new_response_std->nin_data->signature = $response_std->response[0]->signature ?? '';
                    $new_response_std->nin_data->pmiddlename = $response_std->response[0]->pmiddlename ?? '';
                    $new_response_std->nin_data->profession = $response_std->response[0]->profession ?? '';
                    $new_response_std->nin_data->psurname = $response_std->response[0]->psurname ?? '';
                    $new_response_std->nin_data->religion = $response_std->response[0]->religion ?? '';
                    $new_response_std->nin_data->residence_address  = $response_std->response[0]->residence_AdressLine1 ?? '';
                    $new_response_std->nin_data->residence_town = $response_std->response[0]->residence_Town ?? '';
                    $new_response_std->nin_data->residence_lga = $response_std->response[0]->residence_lga ?? '';
                    $new_response_std->nin_data->residence_state = $response_std->response[0]->residence_state ?? '';
                    $new_response_std->nin_data->residencestatus = $response_std->response[0]->residencestatus ?? '';
                    $new_response_std->nin_data->self_origin_lga = $response_std->response[0]->self_origin_lga ?? '';
                    $new_response_std->nin_data->self_origin_place = $response_std->response[0]->self_origin_place ?? '';
                    $new_response_std->nin_data->self_origin_state = $response_std->response[0]->self_origin_state ?? '';
                    $new_response_std->nin_data->surname = $response_std->response[0]->surname;
                    $new_response_std->nin_data->telephoneno = $response_std->response[0]->telephoneno;
                    $new_response_std->nin_data->title = $response_std->response[0]->title ?? '';
                    $new_response_std->nin_data->vnin = $response_std->response[0]->vnin ?? '';
                    $new_response_std->nin_data->userid = $response_std->response[0]->userid ?? '';

                    $new_response_std->verification = new stdClass;
                    $new_response_std->verification->status = $response_std->verificationStatus;
                    $new_response_std->verification->reference = $response_std->transactionReference;

                    $new_wallet_balance = $my_wallet_balance - $service_fee;
                    $my_wallet->balance = $new_wallet_balance;
                    $my_wallet->date_updated = $date;
                    $my_wallet->save();
                    
                } else if (isset($response_std->responseCode) && $response_std->responseCode = "00" && (empty($response_std->response[0]->surname) && empty($response_std->response[0]->middlename) && empty($response_std->response[0]->firstname))) {
                    echo error_res(false, "01", 'Sorry no record found');
                    $new_wallet_balance = $my_wallet_balance  - 50;
                    $my_wallet->balance = $new_wallet_balance;
                    $my_wallet->date_updated = $date;
                    $my_wallet->save();
                    
                    $in_transaction->user_id = $user->id;
                    $in_transaction->wallet_id = $my_wallet->id;
                    $in_transaction->search_query = $phone;
                    $in_transaction->amount = 50;
                    $in_transaction->remaining_balance = $new_wallet_balance;
                    $in_transaction->service = $service_type->service_name;
                    $in_transaction->status = $status;
                    $in_transaction->date = $date;
                    $in_transaction->save();
                    exit;
                } else {
                    $new_wallet_balance = $my_wallet->balance;
                    $service_fee = 0;
                }

                
                $in_transaction->user_id = $user->id;
                $in_transaction->wallet_id = $my_wallet->id;
                $in_transaction->search_query = $phone;
                $in_transaction->amount = $service_fee;
                $in_transaction->remaining_balance = $new_wallet_balance;
                $in_transaction->service = $service_type->service_name;
                $in_transaction->status = $status;
                $in_transaction->date = $date;
                $in_transaction->save();

                $service_record->user_id = $user->id;
                $service_record->in_transaction_id = $in_transaction->id;
                $service_record->service = $service_type->service_name;
                $service_record->search_query = $phone;
                $service_record->response = json_encode($new_response_std);
                $service_record->save();
                
                $new_response_std->record_id = $service_record->id;

                echo json_encode($new_response_std);
            } else {
                echo error_res(false, "02", "Insufficient balance, please fund your wallet!");
                exit;
            }
        } else {
            echo error_res(false, "02", "User not found!");
            exit;
        }
    } else {
        echo error_res(false, "02", "Service type is not selected or NIN is empty");
        exit;
    }
} else {
    echo error_res(false, "02", "You must login first");
    exit;
}
?>
