<?php namespace App\Utkarsh;

use App\ConsumerApplication;
use App\ConsumerApplicationFiles;
use App\Mandate;
use App\MerchantWhitelistLender;
use App\Slack;
use App\UtkarshKYCData;
use App\UtkarshMandate;
use App\UtkarshVKYC;
use Carbon\Carbon;
use Hashids\Hashids;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

/**
 * Created by PhpStorm.
 * User: sunil khorwal
 * Date: 6/6/16
 * Time: 1:52 PM
 */
class Utkarsh
{

    public static $lender_id = 13;
    private $PartnerID;
    private $client_id;
    private $x_request_id;
    private $signature;
    private $apiKey;
    private $timestamp;
    private $payload;
    private $method;
    private $url;
    private $response;
    private $service = false;
    /**
     * @var false|mixed
     */
    private $token;
    /**
     * @var Request
     */
    private $request;
    /**
     * @var string
     */
    public $error = false;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    public static function activatedMerchants(){
        $merchantWhitelist = MerchantWhitelistLender::where('lender_id',self::$lender_id)->whereNull('deleted_at')->get(['merchant_id']);
        $merchantWhitelisted =[];
        foreach($merchantWhitelist as $white){
            $merchantWhitelisted[] = $white->merchant_id;
        }
        // return !_env('APP_CONNECTION') ? [1] : [73, 4830, 8, 6659, 6861, 6602, 6654, 5425, 83, 5408, 5453, 6167, 5098, 4182, 6110, 6583, 6948, 1338, 4693, 1286, 6657, 6451, 6873, 5668, 6440, 5861, 6661, 6816, 1731, 6777, 6034];
        return $merchantWhitelisted;
    }

    public function checkEligibility($id){
        $application = ConsumerApplication::where('id', $id)->first(['id','merchant_id']);
        return in_array($application->merchant_id, self::activatedMerchants());
    }

    public function initToken(){
        //$this->token = "eyJ4NXQiOiJaR1prT1daa1pHUTFOelZrWTJVMU5HUXhNV1pqWWpZeE9XWXpaams0WmpBNE1UZG1NRFU0TlEiLCJraWQiOiJOR1ZrT1Rsa09HWTVNRFF5TWpOaFlUTmpNREEyWW1abE16UTBPVFU0WVdaa01EQm1PRFppWWpJM1pERm1aVFl6TkRFNVkyVmtaVEU1T1RFeU9UWXdaZ19SUzI1NiIsInR5cCI6ImF0K2p3dCIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiJ1dGthcnNoYWRtaW4iLCJhdXQiOiJBUFBMSUNBVElPTiIsImF1ZCI6Ik1fZlZkZWU1YnM0UVVmc05pY0x3bElFNkptY2EiLCJuYmYiOjE3NDczOTU3MjcsImF6cCI6Ik1fZlZkZWU1YnM0UVVmc05pY0x3bElFNkptY2EiLCJzY29wZSI6ImRlZmF1bHQiLCJpc3MiOiJodHRwczpcL1wvYXBpbWludGVncmF0ZS51dGthcnNoLmJhbms6OTQ0M1wvb2F1dGgyXC90b2tlbiIsInJlYWxtIjp7InNpZ25pbmdfdGVuYW50IjoiY2FyYm9uLnN1cGVyIn0sImV4cCI6MTc0NzM5NjkyNywiaWF0IjoxNzQ3Mzk1NzI3LCJqdGkiOiI3MTQ2MmI2MS03MDU3LTQxYzMtOGI3OC1jZGZiODhmYmJkMWUifQ.Xfr8hfkG5xN9AVqsLlkPYdxfA1PCoOYIW12NO2JOTuAssKGMAiaxPsPAsE_-y9FunCJwQLMDmLGi1-1rFo-ST3tRI96v2P8ptplr9u2zsOWHDLtbg9kkpsu7DMt_zk-sSihXjR3qTmqPCurXQyuBm7J-e1rEp--qxjLpYtrh6YxJW9sUzaNCl-Hf78xIzMnVoQOFEZtQOFMcw-GLmnnHPn2-uIodCt0emj0-gUxYqGRMpIwrFjcow27O7Gq5Ju9KSuoGABYMsV7ZD4WTciNyDtwgp6L3ha6GzpvpzturMkdwNp4dsZOyuU75sHg18fanDR83qUB6BkWmuX3ANHmezQ";
        //return $this->token;
        if ($this->token){
            return $this->token;
        }
        $this->url = _env('UTKARSH_HOST').'/oauthnew2/v1.0.0/token';
        $this->payload = [
            "grant_type" => "client_credentials",
            "clientInfo" => _env('UTKARSH_CLIENT_INFO')
        ];
        $this->method = 'POST';
        $this->token = $this->saveResponse($this->connect(), __FUNCTION__);
    }

    public function getKYCLink(){
        $this->initToken();
        if (!$this->token){
            return false;
        }
        $this->url = _env('UTKARSH_HOST')._env('UTKARSH_KYC').'/customer-data';
        $this->method = 'PUT';
        if (!$this->dataInitialize(__FUNCTION__)){
            return false;
        }
        $this->getPayload();
        return $this->saveResponse($this->connect(), __FUNCTION__);
    }

    public function pushMandateDetails(){
        $this->initToken();
        $this->url = _env('UTKARSH_HOST').'/nachServiceAPI/v1.0.0/corporate/mr';
        $this->service = __FUNCTION__;
        $this->method = 'POST';
        if (!$this->dataInitialize(__FUNCTION__)){
            if ($this->error == 'Mandate request already created'){
                //Get Mandate Details
                return $this->getMandateDetails();
            }
            return $this->error;
        }
        $this->getPayload();
        $this->saveResponse($this->connect(), __FUNCTION__);

        //Get Mandate Details
        return $this->getMandateDetails();
    }

    public function getMandateDetails(){
        $this->initToken();
        $this->service = __FUNCTION__;
        $this->method = 'GET';
        if (!$this->dataInitialize(__FUNCTION__)){
            return $this->error;
        }

        $this->url = _env('UTKARSH_HOST').'/Corp/v1.0.0/corporate/mr/'.$this->request->get('mandate_reference_number');

        $this->getPayload();
        return $this->saveResponse($this->connect(), __FUNCTION__);
    }

    public function generateOTP(){
        $this->initToken();
        $this->service = __FUNCTION__;
        $this->method = 'POST';
//        if (!$this->dataInitialize(__FUNCTION__)){
//            return $this->error;
//        }

        $this->url = _env('UTKARSH_HOST')._env('UTKARSH_OTP');

        $this->getPayload();
        return $this->saveResponse($this->connect(), __FUNCTION__);
    }

    public function OTPVerification(){
        $this->initToken();
        $this->service = __FUNCTION__;
        $this->method = 'POST';
        if (!$this->dataInitialize(__FUNCTION__)){
            return $this->error;
        }

        $this->url = _env('UTKARSH_HOST')._env('UTKARSH_VERIFICATION_STORING');

        $this->getPayload();
        return $this->saveResponse($this->connect(), __FUNCTION__);
    }

    public function getKYCDetailsLink(){
        $this->url = _env('UTKARSH_HOST')._env('UTKARSH_KYC').'/trackingId/';
        $this->method = 'GET';
        if (!$this->dataInitialize(__FUNCTION__)){
            return false;
        }
        $this->url = $this->url.$this->request->get('trackingId');
        $this->getPayload();
        return $this->saveResponse($this->connect(), __FUNCTION__);
    }

    public function downloadVKYCDocument(){
        $this->url = _env('UTKARSH_HOST')._env('UTKARSH_KYC').'/download/';
        $this->method = 'GET';
        if (!$this->dataInitialize(__FUNCTION__)){
            return false;
        }
        $this->url = $this->url.$this->request->get('docId');
        $this->getPayload();
        return $this->saveResponse($this->connect(), __FUNCTION__);
    }

//    Fetch application details for API call
    private function dataInitialize($service){
        $application = ConsumerApplication::with('proFormaInvoice', 'bank_details', 'emi', 'application_element')->where('id', $this->request->get('application_id'))->first([
            'id',
            'email',
            'name',
            'dob',
            'gender',
            'mobile_number',
            'pan_card',
            'created_at',
            'current_address_line_1',
            'current_address_city',
            'current_address_state',
            'current_address_pincode',
            'permanent_address_line_1',
            'permanent_address_city',
            'permanent_address_state',
            'permanent_address_pincode',
            'applicant_id',
            'monthly_income',
            'marital_status'
        ]);


        if ($service == 'OTPVerification'){

            $UtkarshKYCData = UtkarshKYCData::where('application_id', $application->id)->first(['id', 'request_data', 'response_data']);

            if (isset($UtkarshKYCData->response_data) && $UtkarshKYCData->response_data){
                $this->error = 'Aadhaar already verified';
                return false;
            }

            if (!isset($UtkarshKYCData->request_data)){
                $this->error = 'Please generate the Aadhaar OTP';
                return false;
            }

            $response_decoded = json_decode($UtkarshKYCData->request_data);
            $transaction = $response_decoded->response_data->data;

            $transaction_ref_number = $this->getFromXMLString(base64_decode($transaction), 'txn');

            return $this->request->merge([
                'transaction_ref_number' => $transaction_ref_number ?? '',
                'otp' => $this->request->get('otp')
            ]);
        }

        $mandate_data = Mandate::where('consumer_application_id', $this->request->get('application_id'))->orderBy('created_at', 'desc')->first();

        if (!isset($application->bank_details->bank_name)){
            $this->error = 'Customer bank details not found';
            return false;
        }

        if (!isset($application->emi->emi_date)){
            $this->error = 'EMI is not generated';
            return false;
        }

        $mandate = UtkarshMandate::where('application_id', $application->id)->where('status', 'success')->first(['id', 'message', 'get_mandate_response']);
        $mandate_reference_number = $mandate->message ?? '';
        $get_mandate_response = $mandate->get_mandate_response ?? '';

        if ($service == 'getMandateDetails' && $get_mandate_response){
            $get_mandate_response = json_decode($get_mandate_response);
            $this->error = isset($get_mandate_response->message->surl) && $get_mandate_response->message->surl ? $get_mandate_response : 'Failed to get link';
            return false;
        }

        if ($service == 'pushMandateDetails' && $mandate_reference_number){
            $this->error = 'Mandate request already created';
            return false;
        }

        $application_item = UtkarshKYCData::where('application_id', $this->request->get('id'))->where('applicant_type', $this->request->get('applicant_type'))->first(['response_data']);
        if ($service == 'getKYCLink' && isset($application_item->response_data)){
            $response_data = json_decode($application_item->response_data);
            if (isset($response_data->response_data->data)){
                $response_data_decoded = base64_decode($response_data->response_data->data);
                $aadhaar_user_photo = $this->getFromXMLString($response_data_decoded, 'pht');
            }

            if (!isset($aadhaar_user_photo)){
                $this->error = 'Utkarsh - Aadhaar Photo not found or aadhaar verification failed';
                return false;
            }
        }

        $utkarshVKYC = UtkarshVKYC::where('application_id', $application->id)->where('applicant_type', $this->request->get('applicant_type'))->orderBy('created_at', 'desc')->first(['id', 'trackingId']);
        $trackingId = $utkarshVKYC->trackingId ?? '';

        return $this->request->merge([
            'id' => $application->proFormaInvoice->loan_application_no ?? '',
            'email' => $application->email ?? '',
            'name' => $application->name ?? '',
            'dob' => $application->dob ?? '',
            'gender' => $application->gender ?? '',
            'mobile_number' => $application->mobile_number ?? '',
            'pan_card' => $application->pan_card ?? '',
            'redirect_link' => $this->request->get('redirect_link') ?? '',
            'created_at' => $application->created_at,
            'current_address_line_1' => $application->current_address_line_1,
            'current_address_city' => $application->current_address_city,
            'current_address_state' => $application->current_address_state,
            'current_address_pincode' => $application->current_address_pincode,
            'permanent_address_line_1' => $application->permanent_address_line_1,
            'permanent_address_city' => $application->permanent_address_city,
            'permanent_address_state' => $application->permanent_address_state,
            'permanent_address_pincode' => $application->permanent_address_pincode,
            'applicant_id' => $application->applicant_id,
            'monthly_income' => $application->monthly_income,
            'marital_status' => $application->marital_status,
            'bank_name' => $application->bank_details->bank_name,
            'branch_name' => $application->bank_details->branch_name,
            'account_number' => $application->bank_details->account_number,
            'ifsc_code' => $application->bank_details->ifsc_code,
            'account_holder' => $application->bank_details->account_holder,
            'account_type' => strtoupper($application->bank_details->account_type),
            'mandate_reference_number' => $mandate_reference_number,
            'emi_date' => $application->emi->emi_date,
            'remaining_emi' => $application->emi->remaining_emi,
            'checkmandate' => $mandate_data,
            'trackingId' => $trackingId,
            'father_name' => $application->application_element->father_name ?? '',
            'mother_name' => $application->application_element->mother_name ?? '',
            'aadhaar_user_photo' => $aadhaar_user_photo ?? ''
        ]);
    }

//    Gather information for Payload
     private function getPayload(){
        if ($this->service == 'pushMandateDetails'){
            return $this->payload = [
                    "referenceNumber" => uniqid(),
                    "utilityCode" => _env('UTKARSH_UTILITY_CODE'),
                    "categoryCode" => "L002",
                    "schmNm" => "Loan amount security",
                    "consRefNo" => $this->request->get('id'),
                    "seqTp" => "RCUR",
                    "frqcy" => "MNTH",
                    "frstColltnDt" => date('Y-m-d', strtotime($this->request->get('emi_date'))),
                    "fnlColltnDt" => $this->getLastDateOfRepayment($this->request->get('emi_date'), $this->request->get('remaining_emi')),
                    "amountTp" => "MAXA",
                    "colltnAmt" => $this->request->get('checkmandate')->mandate_amount,
                    "dbtrNm" => $this->request->get('name'),
                    "phone" => "",
                    "mobile" => $this->request->get('mobile_number'),
                    "email" => $this->request->get('email'),
                    "pan" => $this->request->get('pan_card'),
                    "bnkId" => "IDIB",
                    "dbtrAccTp" => strtoupper($this->request->get('account_type')),
                    "dbtrAccNo" => $this->request->get('account_number')
            ];
        }else if($this->service == 'getMandateDetails' || $this->service == 'getKYCDetailsLink'){
            return $this->payload = [];
        }else if($this->service == 'OTPVerification'){

            $consumerApplication = ConsumerApplication::where('id', $this->request->get('id'))->first(['aadhaar_card']);
            return $this->payload = [
                "headers" => [
                    "sub_client_code" => "UTKARSH2206",
                    "actor_type" => "CUSTOMER",
                    "operation_mode" => "SELF",
                    "channel_code" => "MOBILE_APP",
                    "channel_version" => "1.0.1",
                    "function_sub_code" => "DEFAULT",
                    "function_code" => "EKYC",
                    "run_mode" => "REAL",
                    "stan" => $this->unique_reference_key(),
                    "user_handle_value" => "MSISDN",
                    "client_ip" => "",
                    "location" => "",
                    "user_handle_type" => "MSISDN",
                    "client_code" => "UTKARSH2206",
                    "transmission_datetime" => (string)time()
                ],
                "request" => [
                    "purpose" => "DEFAULT",
                    "lr" => "N",
                    "remark" => "",
                    "consent" => "Y",
                    "notification_channel" => "SMS",
                    "client_ref_number" => "171577830199912345",
                    "uid" => $consumerApplication->aadhaar_card ?? '',
                    "environment" => "PREPROD",
                    "pdf" => "Y",
                    "modalities" => [
                        "pa" => "n",
                        "bt" => "FMR",
                        "pi" => "n",
                        "bio" => "n",
                        "pfa" => "n",
                        "otp" => "y"
                    ],
                    "Otp" => (string)$this->request->get('otp'),
                    "Otp_ref_No" => $this->unique_reference_key(),
                    "transaction_ref_number" => $this->request->get('transaction_ref_number')
                ]
            ];
        }else if($this->service == 'generateOTP'){

            $consumerApplication = ConsumerApplication::where('id', $this->request->get('id'))->first(['aadhaar_card']);

            return $this->payload =
                    [
                        "headers" =>
                            [
                                "sub_client_code" => "UTKARSH2206",
                                "actor_type" => "CUSTOMER",
                                "operation_mode" => "SELF",
                                "channel_code" => "MOBILE_APP",
                                "channel_version" => "1.0.1",
                                "function_sub_code" => "GENERATE_OTP",
                                "function_code" => "AUTH",
                                "run_mode" => "REAL",
                                "stan" => $this->unique_reference_key(),
                                "user_handle_value" => "MSISDN",
                                "client_ip" => "",
                                "location" => "",
                                "user_handle_type" => "MSISDN",
                                "client_code" => "UTKARSH2206",
                                "transmission_datetime" => "1726661643058"
                            ],
                        "request" => [
                            "notification_channel" => "SMS",
                            "client_ref_number" => "172171665946312345",
                            "uid" => $consumerApplication->aadhaar_card ?? '', //aadhar number
                            "environment" => "PREPROD",
                            "purpose" => "DEFAULT",
                            "remark" => "",
                            "consent" => "Y"
                        ]
                    ];
        }else {

            $hashids = new Hashids('Creditfair by CS', 20);
            $application_hashed_id = $hashids->encode($this->request->get('application_id'));
            $applicant_type_hashed_id = $hashids->encode($this->request->get('applicant_type'));

            return $this->payload = [
                'trackingId' => 'CF_SOLAR_'.$this->request->get('application_id'),
                'displayName' => $this->request->get('name'),
                'groupId' => _env('UTKARSH_GROUP_ID'),
                'flow' => 'Continuous',
                'priority' => 1,
                'product' => 'Solar Panel Loan',
                'subProduct' => 'Solar Panel Loan',
                'crn' => '',
                'signatureFromRE' => '',
                'redirectUrl' => 'https://creditfair.in/vkyc-process/thank-you/'.$application_hashed_id.'/'.$applicant_type_hashed_id,
                'welcomeMessage' => 'Welcome to Video KYC for SOLAR PANEL LOAN',
                'userPhoto' => $this->request->get('aadhaar_user_photo'),
                'device' => [
                    'deviceType' => 'WebBrowser', 'deviceName' => 'Chrome 80', 'vendor' => 'Web', 'deviceInfo' => 'Operating System= Windows 10|core= 4'
                ],
                "data" => [
                    ["name" => "LatLong", "value" => true],
                    ["name" => "LatLongCity", "value" => true],
                    ["name" => "LatLongState","value" => true],
                    ["name" => "LatLongCountry","value" => true],
                    ["name" => "AadhaarVerificationDate","value" => Carbon::now()->toDateTimeString()],
                    ["name" => "PAN card number","value" => $this->request->get('pan_card'),"verifyWithPanCard" => true],
                    ["name" => "FormSubmissionDate","value" => date('Y-m-d H =>i =>s', strtotime($this->request->get('created_at')))],
                    ["name" => "Sir/Ma'am May we have your name please?","value" => $this->request->get('name'),"verifyWithCustomer" => true],
                    ["name" => "NameAsPerAadharCard","value" => $this->request->get('name')],
                    ["name" => "AadhaarAddressLine1","value" => $this->request->get('permanent_address_line_1')],
                    ["name" => "AadhaarAddressLine2","value" => $this->request->get('permanent_address_city')],
                    ["name" => "AadhaarAddressLine3","value" => $this->request->get('permanent_address_pincode')],
                    ["name" => "What is your address City as per Aadhar card ?","value" => $this->request->get('current_address_city')],
                    ["name" => "AadhaarAddressState","value" => $this->request->get('permanent_address_state')],
                    ["name" => "AadhaarAddressCountry","value" => "INDIA"],
                    ["name" => "CommunicationAddressLine1","value" => $this->request->get('current_address_line_1')],
                    ["name" => "CommunicationAddressLine2","value" => $this->request->get('current_address_city')],
                    ["name" => "CommunicationAddressLine3","value" => ""],
                    ["name" => "CommunicationAddressPinCode","value" => $this->request->get('current_address_pincode')],
                    ["name" => "CommunicationAddressCity","value" => $this->request->get('current_address_city')],
                    ["name" => "CommunicationAddressState","value" => $this->request->get('current_address_state')],
                    ["name" => "CommunicationAddressCountry","value" => "INDIA"],
                    ["name" => "CommunicationAddressFlag","value" => true],
                    ["name" => "Fathers/SpouseName","value" => $this->request->get('father_name')],
                    ["name" => "Sir/Ma'am Please share your date of Birth.","value" => $this->request->get('dob'),"verifyWithCustomer" => true],
                    ["name" => "CustomerMobileNumber","value" => $this->request->get('mobile_number'),"displayOnChatWindow" => true],
                    ["name" => "AadhaarMobileNumber","value" => $this->request->get('mobile_number')],
                    ["name" => "EmailID","value" => $this->request->get('email'),"displayOnChatWindow" => true],
                    ["name" => "MaritalStatus","value" => $this->request->get('marital_status')],
                    ["name" => "NomineeGivenFlag","value" => true],
                    ["name" => "Gender","value" => $this->request->get('gender')],
                    ["name" => "PlaceofBirth","value" => ""],
                    ["name" => "Sir/Ma'am May we have your mother's maiden name please?","value" => $this->request->get('mother_name'),"verifyWithCustomer" => true],
                    ["name" => "AccountNumber","value" => ""],
                    ["name" => "OtherInfo","value" => ""],
                    ["name" => "AccountRegularizationStatusCode","value" => ""],
                    ["name" => "AadhaarNameSameAsNsdlName","value" => $this->request->get('name')],
                    ["name" => "AadhaarNameSameAsPanName","value" => true],
                    ["name" => "Sir/Ma,am What is your name ?","value" => $this->request->get('name')],
                    ["name" => "NameAsPerNSDL","value" => $this->request->get('name'),"verifyWithPanCard" => true],
                    ["name" => "Date Of Birth","value" => $this->request->get('dob'),"verifyWithPanCard" => true],
                    ["name" => "AadhaarPincode","value" => $this->request->get('permanent_address_pincode')]
                ]
            ];
        }
    }

//    Initialise header information
    protected function initialize(){
        $this->PartnerID = _env('UTKARSH_PartnerID');
        $this->client_id = _env('UTKARSH_CLIENT_ID');
        $this->x_request_id = uniqid();
        $this->timestamp = time();
        $this->apiKey = _env('UTKARSH_API_KEY');
        $this->signature = _env('UTKARSH_SIGNATURE');

        if (in_array($this->service, ['pushMandateDetails', 'getMandateDetails'])){
            $this->apiKey = _env('UTKARSH_MANDATE_AUTH_KEY');
        }
    }

//    Define Curl Call for API
    private function connect(){
        $this->initialize();

        if(empty($this->headers)) {
            $this->headers = array(
                'Content-Type: application/json',
                'Accept: application/json',
                'Accept-Encoding:application/json',
                'partnerID: ' . $this->PartnerID,
                'client-id: ' . $this->client_id,
                'apiKey: '. $this->apiKey,
                'x-request-id: ' . $this->x_request_id,
                'timestamp: ' . $this->timestamp,
                'signature: ' . $this->signature
            );
        }
        if ($this->token){
            $this->headers = array_merge($this->headers, ['Authorization: Bearer ' . $this->token]);
        }

        if ($this->service == 'pushMandateDetails' || $this->service == 'getMandateDetails'){
            $this->headers = array_merge($this->headers, ['x-api-key: ' . $this->apiKey]);
            foreach ($this->headers as $header_index => $header) {
                if ($this->strposa($header, ['signature:', 'apiKey', 'client-id', 'x-request-id'])) {
                    unset($this->headers[$header_index]);
                }
            }
        }

        $this->sendRequest($this->url, $this->method, json_encode($this->payload), $this->headers);
        return json_decode($this->response);
    }

//    API Call
    private function sendRequest($url, $method, $payload, $headers = []) {

        $curl = curl_init();
        $body = array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_HTTPHEADER => $headers,
        );

        if($method != 'GET'){
            $body[CURLOPT_POSTFIELDS] = $payload;
        }

        curl_setopt_array($curl, $body);

        $this->response = curl_exec($curl);

        (new Slack(new \Illuminate\Http\Request(['title' => 'Request Error', 'fields' => ['API' => $url, 'req' => $payload,'res' => json_encode($this->response), 'headers' => json_encode($headers)]])))->send();
        curl_close($curl);
    }

//    Save response details
    public function saveResponse($response, $type){
        if ($response){
            try {

                if ($type == 'initToken' && isset($response->access_token)){
                    $this->error = 'Failed to generate utkarsh token';
                    return $response->access_token ?? false;
                }else if($type == 'getKYCLink'){
                    $kyc = UtkarshVKYC::where('application_id', $this->request->get('application_id'))->where('applicant_type', $this->request->get('applicant_type'))->first(['id']);
                    if (!isset($kyc->id) && isset($response->trackingId)){
                        $kyc = new UtkarshVKYC();
                        $kyc->application_id = $this->request->get('application_id');
                        $kyc->trackingId = $response->trackingId;
                        $kyc->response = json_encode($response);
                        $kyc->applicant_type = $this->request->get('applicant_type');
                        $kyc->save();
                        return $response->waitPageUrl;
                    }
                }else if($type == 'pushMandateDetails'){
                    $mandate = new UtkarshMandate();
                    $mandate->reference_number = $response->reference;
                    $mandate->message = $response->message;
                    $mandate->status = $response->status == 200 ? 'success' : 'error';
                    $mandate->response = json_encode($response);
                    $mandate->application_id = $this->request->get('application_id');
                    $mandate->save();
                }else if($type == 'getMandateDetails'){
                    UtkarshMandate::where('application_id', $this->request->get('application_id'))->where('status', 'success')->update(['get_mandate_response' => json_encode($response)]);
                }else if($type == 'getKYCDetailsLink'){
                    UtkarshVKYC::where('application_id', $this->request->get('id'))->where('applicant_type', $this->request->get('applicant_type'))->update(
                        [
                            'get_vkyc_response' => json_encode($response)
                        ]
                    );
                }else if($type == 'generateOTP' && isset($response->response_status->status) && $response->response_status->status == 'SUCCESS'){
                    $UtkarshKYCData = new UtkarshKYCData();
                    $UtkarshKYCData->application_id = $this->request->get('application_id');
                    $UtkarshKYCData->request_data = json_encode($response);
                    $UtkarshKYCData->applicant_type = $this->request->get('applicant_type');
                    $UtkarshKYCData->save();
                }else if($type == 'OTPVerification' && isset($response->response_status->status) && $response->response_status->status == 'SUCCESS'){
                    UtkarshKYCData::where('application_id', $this->request->get('application_id'))->where('applicant_type', $this->request->get('applicant_type'))->update(['response_data' => json_encode($response)]);
                }

            }catch (\Exception $exception){
                (new Slack(new \Illuminate\Http\Request(['title' => 'Request Error', 'fields' => ['response' => $response, 'request' => json_encode($this->request->all()), 'message' => $exception->getMessage(), 'line' => $exception->getLine(), 'trace' => $exception->getTraceAsString()]])))->send();
                return false;
            }
        }

        return $response;
    }

    private function getLastDateOfRepayment($emi_date, $remaining_emi){
        return Carbon::parse($emi_date)->addMonth($remaining_emi)->toDateString();
    }

    private function strposa($haystack, $needles=array(), $offset=0) {
        foreach($needles as $needle) {
            if(strpos($haystack, $needle, $offset) !== false) {
                return true;
            }
        }

        return false;
    }

    private function unique_reference_key() {
        $number = "";
        for($i=0; $i<19; $i++) {
            $min = ($i == 0) ? 1:0;
            $number .= mt_rand($min,9);
        }
        return $number;
    }

    private function getFromXMLString($transaction, $key){
        $xml_string = simplexml_load_string($transaction);
        if ($xml_string === false) {
            $this->error = 'Failed to parse XML string.';
        }

        $pht = (string) $xml_string->attributes()->{$key} ?? '';
        if (!$pht){
            $pht = (string) $xml_string->UidData->Pht ?? '';
        }
        return $pht;
    }
}
