<?php

namespace App;

use App\Events\V1\EventVkycWebhook;
use App\Events\V1\EventVkycApproved;
use App\Http\Controllers\Admin\ConsumerApplicationController;
use App\ConsumerApplication;
use App\Http\Controllers\Admin\ConsumerDocument;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use App\Slack;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use League\Flysystem\AwsS3v3\AwsS3Adapter;
use App\Logging\CloudWatchLoggerFactory;
use Hashids\Hashids;
use App\Http\Controllers\WebhookController;

class KarzaVideo
{
    private $KARZA_DOMAIN = null;
    private $payload;
    private $request;
    private $APP_KEY;
    private $KARZA_JWT_URL;
    private $API_TYPE;
    private $CUSTOMER_TYPE;
    private $CUSTOMER_TRANSACTION_ID = null;

    public function __construct(Request $request){
        $this->request = $request;
        $this->KARZA_DOMAIN = (_env('KARZA_DOMAIN'));
        $this->APP_KEY = (_env('KARZA_APP_KEY'));
        $this->KARZA_JWT_URL = (_env('KARZA_JWT_URL'));
    }

    public function getVideoKYCURL($applicant_type = null){
        $videoURL = "";
        $applicationId = $this->request->get('application')->id;
        $hash = new Hashids('Creditfair by CS', 20);
        $hashedApplicationId = $hash->encode($applicationId);
        $applicationLoanId = $this->request->get('application')->proFormaInvoice->loan_application_no;
        // https://test10.creditfair.in/admin/consumer-application/get-documents/701/vkyc_aadhar_match_701_1_72.jpeg
        if($this->request->get('application')->co_applicant_name && $applicant_type == 2){
            $applicant_type = 2;
            $this->CUSTOMER_TYPE = $applicant_type;
            $customerId = $applicationId.$applicant_type;
            $dob = date('d/m/Y',strtotime($this->request->get('application')->co_applicant_dob));
            $name = $this->request->get('application')->co_applicant_name;
            $email = $this->request->get('application')->co_applicant_email;
            $gender = $this->request->get('application')->co_applicant_gender;
            $fatherName = $this->request->get('application')->application_element->co_applicant_father_name;
            $currentAddress = $this->request->get('application')->co_applicant_currentAddress;
            $permanentAddress = $this->request->get('application')->co_applicant_permanentAddress;
            $isSameAddress = false;
            if($currentAddress == $permanentAddress) {
                $isSameAddress = true;
            }
            $applicantType = "CO-APPLICANT";
            $panNumber = $this->request->get('application')->co_applicant_pan_card;
            $fileType = "co_applicant_aadhar_card";
        }elseif($this->request->get('application')->name && !$applicant_type){
            $applicant_type = 1;
            $this->CUSTOMER_TYPE = $applicant_type;
            $customerId = $applicationId.$applicant_type;
            $dob = date('d/m/Y',strtotime($this->request->get('application')->dob));
            $name = $this->request->get('application')->name;
            $email = $this->request->get('application')->email;
            $gender = $this->request->get('application')->gender;
            $fatherName = $this->request->get('application')->application_element->father_name;
            $currentAddress = $this->request->get('application')->currentAddress;
            $permanentAddress = $this->request->get('application')->permanentAddress;
            $isSameAddress = false;
            if($currentAddress == $permanentAddress) {
                $isSameAddress = true;
            }
            $applicantType = "APPLICANT";
            $panNumber = $this->request->get('application')->pan_card;
            $fileType = "aadhar_card";
        }

        $aadharFile = ConsumerApplicationFiles::where(['consumer_application_id' => $applicationId, 'is_masked' => 1, 'file_type' => $fileType, 'applicant_type' => $applicant_type])->orderBy('created_at', 'DESC')->first();


        $applicationFormData = [
            'applicationId' => $applicationLoanId,
            'applicationType' => 'INDIVIDUAL',
            'applicantType' => $applicantType,
            'firstName' => $name,
            'fatherName' => $fatherName,
            'dob' => $dob,
            'gender' => strtolower($gender),
            'currentAddress' => $currentAddress,
            'permanentAddress' => $permanentAddress,
            'isCurrentAndPermanentAddressSame' => $isSameAddress,
            "productType" => "vkyc",
            "customerStatus" => "new"
        ];

        if (isset($email) && $email){
            $applicationFormData['email'] = $email;
        }

        $requestBody = [
            'customerId' => $customerId,
            'applicationFormData' => $applicationFormData,
        ];

        if (!Auth::check()) { // No redirect link for internal link generation
            $requestBody['redirectLink'] = _env('APP_URL')."/esign/".$hashedApplicationId.'?kyc=complete&type='.$applicant_type;
        }
        $docsAddar = [];

        /*if($aadharFile) {
            $short_path = isset($aadharFile->file_path) && !empty($aadharFile->file_path) ? $aadharFile->file_path : $this->request->get('application')->id.'/'.$aadharFile->file_type.'.pdf';
            $imagePath = Storage::disk('s3')->get($short_path);
            // get file extension
            $fileExtension = explode(".", $short_path);
            $fileExtension = $fileExtension[count($fileExtension) - 1];

            $docsAddar["aadhaar"] = [
                  "name" => $name,
                  "genDate" => Carbon::now()->format('YmdHis00'),
                  "address" => $permanentAddress,
                  "dob" => $dob,
                  "gender" => strtolower($gender),
                  "source"=> "UIDAI",
                  "type"=> "XML",
                  "verified" => true,
                  "isAadhaarMasked" => true,
                  "documentCategory" => 'POA',
                  "faceOnDocument" => [
                    "fileBase64" => base64_encode($imagePath),
                    "fileType" => $fileExtension,
                    "metaData" => ""
                  ]
              ];
        }

        if($panNumber) {
            $docsAddar["pan"] = [
                    "firstName" => $name,
                    "printedName" => $name,
                    "panNo" => $panNumber,
                    "type" => "API",
                    "source" => "NSDL",
                    "verified" => true,
                    "documentCategory" => "POI"
                ];
            
        }

        if(!empty($docsAddar)){
            $requestBody['docs'] = ["individualDocs" => $docsAddar];
        }*/

        $this->payload = json_encode($requestBody);
        $resp = $this->getResponse();

        if(false !== $resp) {
            $videoURL = $this->setKarzaVideoAttribute($resp, 'url_data', $applicant_type);
        }

        return $videoURL;
    }
    
    public function setKarzaVideoAttribute($response, $type, $applicant_type = null){
        if($this->request->has('application') && isset($this->request->get('application')->id)) {

            $karzaVideoAttribute = KarzaVideoAttribute::where('application_id', $this->request->get('application')->id)->where('applicant_type', $applicant_type)->first(['id']);

            if (!isset($karzaVideoAttribute->id)) {
                KarzaVideoAttribute::insert(
                    [
                        'application_id' => $this->request->get('application')->id,
                        $type => json_encode($response),
                        'applicant_type' => $applicant_type,
                        'created_at' => Carbon::now()->toDateTimeString()
                    ]
                );
            } else {
                KarzaVideoAttribute::where('id', $karzaVideoAttribute->id)->where('applicant_type', $applicant_type)->update(
                    [
                        $type => json_encode($response),
                    ]
                );
            }
            return (!empty($response['statusCode']) && $response['statusCode'] == 101) ? $response['result']['data']['webLink'] : '';
        } elseif($type == 'webhook') {
            event(new EventVkycWebhook(json_encode($response)));
        }
    }

    public function karzaWebhookProcess($response) {
        // no limit of execution time and memory limit
        ini_set('max_execution_time', -1);
        set_time_limit(0);
        ini_set('memory_limit', '-1');

        $consumerApplicationController = new ConsumerApplicationController();
        $customerId = !empty($response->customerId) ? $response->customerId : '';
        $application_id = substr($customerId, 0, -1);
        $applicant_type = substr($customerId, -1);
        unset($customerId);
        if($application_id) {
            $karzaVideoAttribute = KarzaVideoAttribute::where('application_id', $application_id)->where('applicant_type', $applicant_type)->first(['id', 'deleted_at']);
            if (isset($karzaVideoAttribute->id)) {
                $karzaObj = new KarzaVideoWebhook();
                $karzaObj->karza_id = $karzaVideoAttribute->id;
                $karzaObj->application_id = $application_id;
                $karzaObj->applicant_type = $applicant_type;
                $karzaObj->data = json_encode($response);
                $karzaObj->save();

                // for release memory
                unset($karzaObj);
      
                $isApprovalResponse = false;
                $approval_status = false;
                if (isset($response->approvedByAgent) && $response->approvedByAgent == "ACCEPTED") {
                    $consumerApplicationController->webhook($application_id, ['type' => 'VKYC-Webhook','status' => 'completed', 'data' => ['vendor'=> 'Karza', 'applicantType' => $applicant_type]]);
                }

                if (isset($response->approvedByAuditor) && $response->approvedByAuditor == "REJECTED") {
                    $karzaVideoAttribute->deleted_at = Carbon::now();
                    $karzaVideoAttribute->update();
                    $consumerApplicationController->webhook($application_id, ['type' => 'VKYC-Webhook','status' => 'rejected', 'data' => ['vendor'=> 'Karza', 'applicantType' => $applicant_type]]);
                }
                unset($karzaVideoAttribute);
                if(isset($response->approvedByAuditor) && $response->approvedByAuditor == "ACCEPTED") {
                    $isApprovalResponse = true;
                    $approval_status = true;
                    $consumerApplicationController->webhook($application_id, ['type' => 'VKYC-Webhook','status' => 'approved', 'data' => ['vendor'=> 'Karza', 'applicantType' => $applicant_type]]);
                    $sendDAWebhook = (new WebhookController())->pushDAWebhook($application_id, 'vkyc');
                    if ($sendDAWebhook) {
                        $consumerApplicationController->webhook($application_id, ['type' => 'DA-Confirmation-Webhook','status' => 'pending', 'data' => $consumerApplicationController->getMConnectPayload($application_id, 'DA-Confirmation-Webhook')]);
                    }
                }elseif(isset($response->approvedByAuditor) && $response->approvedByAuditor != "ACCEPTED") {
                    $isApprovalResponse = true;
                    $approval_status = false;
                }

                if ($isApprovalResponse && !$approval_status) {

                    $data = ConsumerApplication::with([
                        'merchant' => function ($query) {
                            $query->select('id', 'merchant_name');  // Select necessary fields from Merchant
                        },
                        'advisor' => function ($query) {
                            $query->select('id', 'name', 'email');  // Select necessary fields from Advisor
                        }
                    ])
                    ->where('id', $application_id)
                    ->whereNull('deleted_at')
                    ->first(['id', 'name', 'merchant_id', 'created_by','co_applicant_name']);  // Include foreign keys
                    // Ensure data exists to avoid errors
                    if ($data) {
                        $name = $applicant_type == '2' ? $data->co_applicant_name : $data->name;

                        $commentText = "Dear " . $data->advisor->name . ",<br><br>The VKYC has been rejected for partner loan id " . $application_id . ". Kindly generate a new VKYC link on Credit Fair Admin portal and complete the 2 way VKYC.<br> Customer Name : " . $name . "<br> Merchant Name: " . $data->merchant->merchant_name;
                    
                        $comment = new Comments();
                        $comment->application_id = $application_id;
                        $comment->user_id = 107;
                        $comment->comment = $commentText;
                        $comment->show_merchant = 0;
                        $comment->show_consumer = 0;
                        $comment->save();

                        $email = $data->advisor->email ?? "" ;

                        if ($email != "") {
                            $body = '
                            <div style="font-size:13px;font-family:verdana,arial;line-height:1.5">
                            Dear ' . $data->advisor->name . ',
                            The VKYC has been rejected for partner loan id ' . $application_id .'<br><br>
                            Kindly generate a new VKYC link on Credit Fair Admin portal and complete the 2 way VKYC. .<br> Customer Name : ' . $name . '<br> Merchant Name: ' . $data->merchant->merchant_name.'<br>Commented By: System Generated<br><br>
                            </div>';
            
                            \Mail::send('emails.reminders.basic_reminder',
                                ['body' => $body]
                                , function ($message) use ($email) {
                                    $message->to([$email])->subject('VKYC Rejected');
                            });
                        }
                    }
                }

                $consumerDocument = new ConsumerDocument(new Request());
                // Upload Customer Photo to s3
                if(!empty($response->customerImage)) {
                    $consumerDocument->uploadToS3('CUSTPHOTO_'.$application_id.'_'.$applicant_type, $application_id, base64_decode($response->customerImage, '.jpeg'));
                }

                // Upload Customer Signature Photo to s3
                if (!empty($response->signatureImage)) {
                    $consumerDocument->uploadToS3('signature_'.$application_id.'_'.$applicant_type, $application_id, base64_decode($response->signatureImage, '.jpeg'));
                }

                // Upload Pan 
                if (isset($response->panMatchResults->image) && !empty($response->panMatchResults->image->value)) {
                    $consumerDocument->uploadToS3('vkyc_pan_match_'.$application_id.'_'.$applicant_type, $application_id, base64_decode($response->panMatchResults->image->value),'.jpeg');
                }

                // Upload Aadhar 
                if (isset($response->aadhaarMatchResults->image) && !empty($response->aadhaarMatchResults->image->value)) {
                    $consumerDocument->uploadToS3('vkyc_aadhar_match_'.$application_id.'_'.$applicant_type, $application_id, base64_decode($response->aadhaarMatchResults->image->value),'.jpeg');
                }

                // Upload video to s3
                if (!empty($response->customerKycVideo)) {
                    $consumerDocument->uploadToS3('vkyc_video_'.$application_id.'_'.$applicant_type, $application_id, file_get_contents($response->customerKycVideo),'.webm');
                }

                $response->user_id = $application_id;

                if(isset($response->applicationDetails)){
                    $applicant_type = ($applicant_type == 1) ? 'applicant' : 'co_applicant';
                    $view = view('front.karzaV-report', ['data' => $response]);
                    $pdf = App::make('snappy.pdf.wrapper');
                    $report = $pdf->loadHTML($view)->setOption('encoding', 'UTF-8')->setPaper('a4')->setOrientation('portrait');
                    $consumerDocument->uploadToS3('karzaV_report_'.$applicant_type, $application_id, $report->output());
                    $appObj = ConsumerApplication::find($application_id);
                    if (!empty($appObj->lender_id) && $appObj->lender_id == ConsumerApplication::AVANSE_LENDER_ID) {
                        event(new EventVkycApproved($application_id));
                        (new ConsumerApplicationController())->rabbitMQQueue();
                    }
                    unset($appObj);
                }
                $job_id = JobProvider::where('application_id', $application_id)->where('from', 'karzaPurge')->first(['id']);
                if (empty($job_id)) {
                $payload = [
                    'payload' => json_encode(array_merge(['id' => $application_id, 'applicant_type' => ($applicant_type == 'applicant') ? 1 : 2, 'transaction_id' => $response->transactionId])),
                    'from' => 'karzaPurge',
                    'application_id' => $application_id,
                    'available_at' => Carbon::now()->toDateTimeString(),
                    'created_at' => Carbon::now()->toDateTimeString(),
                    'is_available' => '2'
                ];
                JobProvider::insert($payload);
            }
            }
        }
    }

    public function karzaPurge ($job, $payload) {
        $this->API_TYPE = "jwt-auth";
        $_app = new \StdClass();
        $_app->id = $payload->id;
        $this->CUSTOMER_TYPE = ($payload->applicant_type == 'applicant') ? 1 : 2;
        $this->request = new Request(["application" => $_app]);
        $jwt_response = $this->apiCall();
        if($jwt_response) {
            $this->transactionId = $payload->transaction_id;
            $karzaToken = $jwt_response['result']['data']['karzaToken'];
            $this->API_TYPE = "purge-data";
            $purgeResponse = $this->apiCall($karzaToken);
        }
    }

    public function getRequestedAttributes(){
        if($this->request->has('application') && isset($this->request->get('application')->id)) {
            $data = [
                'customer_link' => '',
                'co_customer_link' => ''
            ];
            $karzaVideoAttribute = KarzaVideoAttribute::with('webhook')->where('application_id', $this->request->get('application')->id)->where('applicant_type',1)->whereNull('deleted_at')->first(['id','url_data']);
            if (isset($karzaVideoAttribute->id) && !$karzaVideoAttribute->webhook){
                $url_data = json_decode($karzaVideoAttribute->url_data);
                $videoURL = isset($url_data->statusCode) && $url_data->statusCode == 101 ? $url_data->result->data->webLink : '';
                if($videoURL) {
                    $data['customer_link'] = Shortio::getUrl($videoURL);
                }
            }else {
                $videoURL = $this->getVideoKYCURL();
                $data['customer_link'] = Shortio::getUrl($videoURL);
            }

            if($this->request->has('application') && isset($this->request->get('application')->co_applicant_name)) {
                $karzaVideoAttribute = KarzaVideoAttribute::with('webhook')->where('application_id', $this->request->get('application')->id)->where('applicant_type',2)->whereNull('deleted_at')->first(['id','url_data']);
                if (isset($karzaVideoAttribute->id) && !$karzaVideoAttribute->webhook) {
                    $url_data = json_decode($karzaVideoAttribute->url_data);
                    $videoURL = isset($url_data->statusCode) && $url_data->statusCode == 101 ? $url_data->result->data->webLink : '';
                    $data['co_customer_link'] = Shortio::getUrl($videoURL);
                }else {
                    $videoURL = $this->getVideoKYCURL(2);
                    $data['co_customer_link'] = Shortio::getUrl($videoURL);
                }
            }
            $data['agent_link'] = $this->KARZA_DOMAIN.'login';
            
            return !empty($data) ? $data : false;
        }

        return false;
    }

    private function apiCall($token = null) {
        $apiUrl = "";
        switch ($this->API_TYPE) {
            case 'jwt-auth':
                $apiUrl = $this->KARZA_JWT_URL;
                $payload = json_encode(["productId" => ["video_kyc"]]);
                $curlBody = array(
                    CURLOPT_URL => $apiUrl,
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_ENCODING => "",
                    CURLOPT_MAXREDIRS => 10,
                    CURLOPT_TIMEOUT => 30,
                    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                    CURLOPT_CUSTOMREQUEST => 'POST',
                    CURLOPT_POSTFIELDS => $payload,
                    CURLOPT_HTTPHEADER => array(
                        "Content-Type: application/json",
                        "x-karza-key: ".$this->APP_KEY,
                        "cache-control: no-cache"
                    )
                );
                break;

            case 'create-customer':
                $payload = $this->payload;
                $apiUrl = $this->KARZA_DOMAIN.'api/v3/customers';
                $curlBody = array(
                    CURLOPT_URL => $apiUrl,
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_ENCODING => "",
                    CURLOPT_MAXREDIRS => 10,
                    CURLOPT_TIMEOUT => 30,
                    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                    CURLOPT_CUSTOMREQUEST => 'POST',
                    CURLOPT_POSTFIELDS => $payload,
                    CURLOPT_HTTPHEADER => array(
                        "Content-Type: application/json",
                        "karzatoken: ".$token,
                        "cache-control: no-cache"
                    )
                );
                break;

            case 'customer-token':
                $apiUrl = $this->KARZA_DOMAIN.'api/v2/generate-usertoken/'.$this->CUSTOMER_TRANSACTION_ID;
                $curlBody = array(
                    CURLOPT_URL => $apiUrl,
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_ENCODING => "",
                    CURLOPT_MAXREDIRS => 10,
                    CURLOPT_TIMEOUT => 30,
                    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                    CURLOPT_CUSTOMREQUEST => 'GET',
                    CURLOPT_HTTPHEADER => array(
                        "Content-Type: application/json",
                        "karzatoken: ".$token,
                        "cache-control: no-cache"
                    )
                );
                break;

            case 'customer-link':
                $apiUrl = $this->KARZA_DOMAIN.'api/v2/link';
                $curlBody = array(
                    CURLOPT_URL => $apiUrl,
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_ENCODING => "",
                    CURLOPT_MAXREDIRS => 10,
                    CURLOPT_TIMEOUT => 30,
                    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                    CURLOPT_CUSTOMREQUEST => 'GET',
                    CURLOPT_HTTPHEADER => array(
                        "Content-Type: application/json",
                        "karzatoken: ".$token,
                        "cache-control: no-cache"
                    )
                );
                break;
            
            case 'purge-data':
                $apiUrl = $this->KARZA_DOMAIN.'api/v2/purge/vkyc';
                $payload = json_encode(["transactionId" => $this->transactionId, "forcePurge" => true]);
                $curlBody = array(
                    CURLOPT_URL => $apiUrl,
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_ENCODING => "",
                    CURLOPT_MAXREDIRS => 10,
                    CURLOPT_TIMEOUT => 30,
                    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                    CURLOPT_CUSTOMREQUEST => 'POST',
                    CURLOPT_POSTFIELDS => $payload,
                    CURLOPT_HTTPHEADER => array(
                        "Content-Type: application/json",
                        "karzatoken: ".$token,
                        "cache-control: no-cache"
                    )
                );
                default:
                # code...
                break;
        }
        $curl = curl_init();

        curl_setopt_array($curl, $curlBody);

        $response = curl_exec($curl);
        // $response = '{"requestId": "05a5198f-e3fa-4e03-a1d2-bb4afaabb897","result": {"data": {"karzaToken":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyZXF1ZXN0X2lkIjoiMDVhNTE5OGYtZTNmYS00ZTAzLWExZDItYmI0YWZhYWJiODk3IiwidXNlcl9pZCI6MzI3MjEwLCJzY29wZSI6WyJ2aWRlb19reWMiXSwiZW52IjoidGVzdCIsImNsaWVudF9pZCI6IkNyZWRpdF9GYWlfYU03TENyIiwic3RhZ2UiOiJ0ZXN0IiwidXNlcl90eXBlIjoib3BlbiIsImV4cGlyeV90aW1lIjoiMjQtMDUtMjAyMlQxMjowMDozNSJ9.5qsq3zNxwa8dstg40Plpy2ZkhhhqZYLinNh1ZvdT8P8"},"success": true,"reason": null},"statusCode": 101}';
        $err = curl_error($curl);
        curl_close($curl);
        
        $applicationId = $this->request->get('application')->id;
        $this->dbLog($applicationId, $apiUrl, $curlBody, $response);

        $response = json_decode($response, 1);

        $cwFactory = new CloudWatchLoggerFactory();
        $data = array('application_id'=>$applicationId, 'applicant_type' => $this->CUSTOMER_TYPE ?? '', 'user_id'=> isset(Auth::user()->id) ? Auth::user()->id : 0, 'vendor'=> 'Karza VKYC', 'api_name'=> $this->API_TYPE, 'api_url' => $apiUrl,'Request'=> $payload ?? '{}', 'Response'=>$response, 'error_msg' => $err ?? '');
        $cwFactory->logger(json_encode($data));

        if(!isset($response['statusCode'])) {
            (new Slack(new Request(['title'=>"Issue in Karza API", 'fields'=>['Message' => $response['error']]])))->send();
            return false;
        }

        if($this->API_TYPE == 'purge-data') {
            if (isset($response['result']['success']) && !$response['result']['success']){
                (new Slack(new Request(['title'=>"Karza VKYC Purge Faliure", 'fields'=>['Application ID' => $applicationId]])))->send();
            }
        }

        if ($err) {
            (new Slack(new Request(['title'=>"Issue in Karza API", 'fields'=>['Message' => $err]])))->send();
            return false;
        } else {
            return $response;
        }
    }

    private function getResponse(){
        $this->API_TYPE = "jwt-auth";
        $response = $this->apiCall();
        if($response) {
            $karzaToken = $response['result']['data']['karzaToken'];
            $this->API_TYPE = "create-customer";
            $response = $this->apiCall($karzaToken);
            if($response) {
                $this->CUSTOMER_TRANSACTION_ID = $response['result']['data']['transactionId'];
                $this->API_TYPE = "customer-token";
                $response = $this->apiCall($karzaToken);
                if($response) {
                    $userToken = $response['result']['data']['userToken'];
                    $this->API_TYPE = "customer-link";
                    $response = $this->apiCall($userToken);
                }
            }
        }
        return $response;
    }

    private function dbLog($appId, $url, $curlBody=[], $response=[]) {
        $karzaApiLog = new KarzaVkycApiLog();
        $karzaApiLog->application_id = $appId;
        $karzaApiLog->applicant_type = $this->CUSTOMER_TYPE;
        $karzaApiLog->api_link = $url;
        $karzaApiLog->request = json_encode($curlBody);
        $karzaApiLog->response = json_encode($response);
        $karzaApiLog->save();
    }
}
