<?php


require_once('../vendor/autoload.php');
// require_once('../init.php');
$client = new \GuzzleHttp\Client();
$date = Date("c");

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

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);
}


extract($_POST);

if (isset($nin) && !empty($nin)) {

    $user = User::find_by_id($user_id);
    if ($user) {
        $service_type_id = 21;
        $service_type = Service::find_by_id($service_type_id);

        if($service_type->status == 0){
            echo response(res(500, 'Sorry! Service temporary not available.', ''));
            exit;
        }
        // $service_type = Service::find_by_id($service_type);

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

        $service = "NIN Verification (API) v1";
        $service_fee = intval(110);
        $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 {
                $curl = curl_init();

                curl_setopt_array($curl, array(
                    CURLOPT_URL => 'https://api.prembly.com/identitypass/verification/vnin',
                    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 => '{
                            "number": "' . $nin . '"
                            }',
                    CURLOPT_HTTPHEADER => array(
                        'app-id: 1a4393bc-8135-4263-8c1b-d2e376cc464b',
                        'x-api-key: sandbox_sk_78fQCZsQOGBEAXyxk58h9XDBK9cEAI0OrywNAJV',
                        'Accept: application/json',
                        'content-type: application/json'
                    ),
                )
                );

                $responses = curl_exec($curl);
            } catch (\Throwable $th) {
                try {

                    $responses_er = explode('response:', $th->getMessage());
                    // echo error_res(false, "03", 'this values does not match the required pattern.');
                    // echo error_res(false, "03", $responses_er);
                    echo response(res(400, 'Bad Request', 'This values does not match the required pattern'));
                    exit;
                } catch (\Throwable $th2) {

                    echo response(res(405, 'Method Not Allowed', ''));
                    // echo error_res(false, "03", "Invalid Request detail!");
                    exit;
                }
            }
            $response_std = json_decode($responses);


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

            // if ($response_std->response_code == "00") {
            //     $status = 1;
            //     $new_wallet_balance = $my_wallet_balance  - $service_fee;
            //     $my_wallet->balance = $new_wallet_balance;
            //     $my_wallet->date_updated = $date;
            //     $my_wallet->save();
            // } else {
            //     $new_wallet_balance = $my_wallet->balance;
            //     $service_fee = 0;
            // }

            if ($response_std->response_code == "00") {
                $status = 1;
                $new_wallet_balance = $my_wallet_balance - $service_fee;
                $my_wallet->balance = $new_wallet_balance;
                $my_wallet->date_updated = $date;
                $my_wallet->save();
            } else if ($response_std->response_code == "01") {
                $service_fee = 0;
                // $service_fee = 50;
                $new_wallet_balance = $my_wallet_balance - $service_fee;
                $my_wallet->balance = $new_wallet_balance;
                $my_wallet->date_updated = $date;
                $my_wallet->save();
            } 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 = $nin;
            $in_transaction->amount = $service_fee;
            $in_transaction->remaining_balance = $new_wallet_balance;
            $in_transaction->service = $service;
            $in_transaction->date = $date;
            $in_transaction->status = $status;

            if ($in_transaction->save()) {

                $service_record->user_id = $user->id;
                $service_record->service = $service;
                $service_record->search_query = $nin;
                $service_record->response = $responses;
                $service_record->in_transaction_id = $in_transaction->id;
                if ($service_record->save()) {
                    // $response_std->record_id = $service_record->id;
                    $response_std->search_query = $nin;


                    if ($response_std->response_code == '00') {

                        $data = new stdClass;
                        $data->nin_data = $response_std->nin_data;
                        $data->verification = $response_std->verification;

                        echo response(res(200, $response_std->detail, $data));
                    } else {
                        $data = new stdClass;
                        // $data->nin_data = $response_std->nin_data;
                        $data->verification = $response_std->verification;

                        echo response(res(400, $response_std->message, $data));
                        // echo (json_encode($response_std));
                    }


                    exit;
                } else {
                    // echo error_res(false, "03", "Contact Administrator!");
                    echo response(res(500, 'Internal Server Error', ''));
                    exit;
                }
            } else {
                // echo error_res(false, "03", "Contact Administrator!");
                echo response(res(500, 'Internal Server Error', ''));
                exit;
            }
        } else {
            // echo error_res(false, "03", "Insufficient wallet balance");
            echo response(res(402, 'Insufficient wallet balance', ''));
            exit;
        }
    } else {
        echo response(res(401, 'Unauthorized', ''));
        // echo error_res(false, "404", "Contact Administrator!");
        exit;
    }
} else {
    // echo $_POST;
    echo response(res(400, 'Bad Request', ''));
    // echo error_res(false, "033", "Contact Administrator!");
    exit;
}