<?php

namespace App\Method\ABFL\Payload;

use App\ABFLBreDecision;
use App\ABFLSanctionWrapper;
use App\ApplicationEMICalculation;
use App\ConsumerApplication;
use App\ConsumerApplicationFiles;
use App\CreditReport;
use App\FOIR;
use App\Http\Controllers\Admin\ConsumerApplicationController;
use App\Http\Controllers\Admin\LenderServices;
use App\Http\Controllers\Grade\GradeController;
use App\KYCDetails;
use App\Method\ABFL\Helpers\ABFLHelper;
use App\PaymentTransaction;
use App\Slack;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use function GuzzleHttp\Psr7\str;

class Payload implements ABFLHelper
{

    public $request;
    public $error = null;

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

    public function decisionEngine($wrapper = null){

        $application = ConsumerApplication::with(['emi' => function($query){
            return $query->select(['application_id', 'tenure', 'interest_rate', 'emi']);
        }])->where('id', $this->request->get('id'))->first(['id', 'merchant_id', 'name', 'mobile_number', 'email', 'pan_card', 'gender', 'dob', 'permanent_address_line_1', 'permanent_address_city', 'permanent_address_state', 'permanent_address_pincode', 'approved_amount', 'purpose', 'employee_status', 'monthly_income']);

        $name = explode(' ', $application->name);

        $lender = new LenderServices($this->request);

        if (!$application->emi){
            $error = new \stdClass();
            $error->description = 'EMI is not generated';
            $this->error = $error;
            return $this;
        }

        if (!$application->email){
            $error = new \stdClass();
            $error->description = 'EMAIL is required';
            $this->error = $error;
            return $this;
        }

        if (!$application->pan_card){
            $error = new \stdClass();
            $error->description = 'panNumber is required';
            $this->error = $error;
            return $this;
        }

        if (!$application->dob){
            $error = new \stdClass();
            $error->description = 'DOB is required';
            $this->error = $error;
            return $this;
        }

        if (!$application->permanent_address_line_1){
            $error = new \stdClass();
            $error->description = 'Address is required';
            $this->error = $error;
            return $this;
        }

        if (!$application->permanent_address_city){
            $error = new \stdClass();
            $error->description = 'City is required';
            $this->error = $error;
            return $this;
        }

        if (!$application->permanent_address_state){
            $error = new \stdClass();
            $error->description = 'State is required';
            $this->error = $error;
            return $this;
        }

        if (!$application->permanent_address_pincode){
            $error = new \stdClass();
            $error->description = 'Pincode is required';
            $this->error = $error;
            return $this;
        }

        if (!$application->gender){
            $error = new \stdClass();
            $error->description = 'Gender is required';
            $this->error = $error;
            return $this;
        }

        $roi = $lender->getPayloadValueByID($this->request->get('id'), 'roi');

        $grade = new GradeController($this->request);
        $foir = $grade->getFOIRByID($application->id);

        $EMIWithoutCF = (($grade->credit_limit * 5) / 100) + $grade->total_existing_emi;

        $segments = ["25" => 'Healthcare', "16" => 'Healthcare', "20" => 'Healthcare', "21" => 'Healthcare', "19" => 'Healthcare', "4" => 'Education', "14" => 'Home-Decor', "22" => 'Home-Decor', "40" => 'Home-Decor', "42" => 'Home-Decor', "46" => 'Home-Decor', "7" => 'EV', "24" => 'Solar Rooftop Panel'];


        //$EMIWithoutCF = FOIR::where('application_id', $application->id)->where('AccountType', '!=', 'Credit Fair EMI')->where('InstallmentAmount', '>', 0)->sum('InstallmentAmount');

        if (!$foir){
            $error = new \stdClass();
            $error->description = 'FOIR is required';
            $this->error = $error;
            return $this;
        }

        $purpose = $application->purpose;

        if (!isset($segments[$application->purpose])){

            if(in_array($application->purpose, [34, 35])){
                $purpose = 4;
            }else if(in_array($application->merchant_id, [7040, 7225, 7472, 6875, 7540, 7449, 7542])){
                $purpose = 42;
            }else {
                $error = new \stdClass();
                $error->description = 'Category is required. Possible categories: Healthcare, Education, Home-Decor, EV and Solar ';
                $this->error = $error;
                return $this;
            }
        }

        if(in_array($application->merchant_id, [
            3630,
            3637,
            3810,
            3888,
            4038,
            4269,
            4478,
            4661,
            5239,
            5371,
            5434,
            5526,
            6209,
            6573,
            6607,
            6604,
            6679,
            6731,
            6739,
            6802,
            6824,
            6847,
            6875,
            6886,
            6918,
            6926,
            6957,
            6996,
            7028,
            7030,
            7033,
            7036,
            7037,
            7039,
            7040,
            7044,
            7050,
            7058,
            7078,
            7107,
            7122,
            7136,
            7139,
            7151,
            7161,
            7176,
            7182,
            7183,
            7197,
            7208,
            7225,
            7238,
            7246,
            7253,
            7264,
            7275,
            7277,
            7281,
            7288,
            7313,
            7340,
            7371,
            7409,
            7411,
            7415,
            7418,
            7421,
            7432,
            7455,
            7461,
            7449,
            7462,
            7469,
            7472,
            7470,
            7474,
            7481,
            7485,
            7490,
            7493,
            7495,
            7504,
            7505,
            7510,
            7511,
            7519,
            7520,
            7518,
            7515,
            7522,
            7527,
            7531,
            7532,
            7533,
            7538,
            7540,
            7541,
            7542,
            7543,
            7547,
            7549,
            7551,
            7552,
            7554,
            7558,
            7561,
            7563,
            7564,
            7566,
            7567,
            7568,
            7570,
            7571,
            7573,
            7575,
            7577,
            7582,
            7586,
            7581,
            7592,
            7594,
            7597,
            7601,
            7603,
            7587,
            7604,
            7602,
            7606,
            7607,
            7614,
            7615,
            7620,
            7626,
            7628,
            7633,
            7634,
            7635,
            7636,
            7638,
            7639,
            7642,
            7643,
            7644,
            7645,
            7646,
            7652,
            7654,
            7655,
            7657,
            7658,
            7660,
            7664,
            7666,
            7668,
            7670,
            7676,
            7680,
            7687,
            7691,
            7692,
            7697,
            7698,
            7700,
            7688,
            7701,
            7702,
            7703,
            7713,
            7717,
            7719,
            7721,
            7725,
            7726,
            7722,
            7728,
            7731,
            7733,
            7736,
            7739,
            7740,
            7741,
            7742,
            7746,
            7749,
            7751,
            7754,
            7755,
            7758,
            7756,
            7759,
            7762,
            7767,
            7769,
            7760,
            7775])){
            $purpose = 14;
        }

        $addressArray = explode(" ", $application->permanent_address_line_1);
        $arrayLength = count($addressArray);

        // Set the maximum number of words for each line
        $wordsPerLine = 14;

        $address_line_1 = implode(" ", array_slice($addressArray, 0, $wordsPerLine));
        $address_line_2 = implode(" ", array_slice($addressArray, $wordsPerLine, $wordsPerLine));
        $address_line_3 = implode(" ", array_slice($addressArray, $wordsPerLine * 2, $arrayLength - $wordsPerLine * 2));
        if(strlen($address_line_1) >= 100){
            $wordsPerLine1 = $wordsPerLine - 1;
            $address_line_1 = implode(" ", array_slice($addressArray, 0, $wordsPerLine1));
            $address_line_2 = implode(" ", array_slice($addressArray, $wordsPerLine1, $wordsPerLine1));
            $address_line_3 = implode(" ", array_slice($addressArray, $wordsPerLine1 * 2, $arrayLength - $wordsPerLine1 * 2));
        }
        if(strlen($address_line_1) >= 100){
            $wordsPerLine1 = $wordsPerLine - 2;
            $address_line_1 = implode(" ", array_slice($addressArray, 0, $wordsPerLine1));
            $address_line_2 = implode(" ", array_slice($addressArray, $wordsPerLine1, $wordsPerLine1));
            $address_line_3 = implode(" ", array_slice($addressArray, $wordsPerLine1 * 2, $arrayLength - $wordsPerLine1 * 2));
        }

        $state = null;
        if($application->permanent_address_state == "Pondicherry/Puducherry"){
            $state = "PUDUCHERRY";
        }elseif($application->permanent_address_state == "Uttaranchal/Uttarakhand"){
            $state = "UTTARAKHAND";
        }elseif($application->permanent_address_state == "Orissa"){
            $state = "ODISHA";
        }

        return [
            "source" => "CreditFair",
            "accountId" => 'CF'.$this->request->get('id'),
            "productCode" => "CreditFair",
            "customerReport" => [
                "kycInfo" => [
                    "firstName" => $name[0],
                    "middleName" => count($name) > 2 ? $name[2] : ($name[1] ?? ''),
                    "lastName" => $name[count($name) - 1] ?? $name,
                    "mobile" => $application->mobile_number,
                    "email" => $application->email,
                    "panNumber" => $application->pan_card,
                    "gender" => $application->gender == 'Male' ? 'M' : 'F',
                    "dob" => $application->dob,
                    "addressLine1" => $address_line_1,
                    "addressLine2" => $address_line_2,
                    "addressLine3" => $address_line_3,
                    "city" => $application->permanent_address_city,
                    "state" => $state ?? $application->permanent_address_state,
                    "pincode" => (int)$application->permanent_address_pincode
                ],
                "loanApplicationRequest" => [
                    "requestedLoanAmount" => $lender->getPayloadValueByID($this->request->get('id'), 'actual_sanction_amt'),
                    "roi" => $roi == 0 ? "0.0" : (string)(float)$roi,
                    "tenure" => (string)$lender->getPayloadValueByID($this->request->get('id'), 'effective_tenure'),
                ]
            ],
            "fixed_obligations" => (string)$EMIWithoutCF ?? "0",
            "foir" => (string)$foir,
            "income" => $application->monthly_income,
            "proposedEMI" => (string)$application->emi->emi,
            "employment_type" => (isset($application->employee_status) && strtolower($application->employee_status) == 'salaried') ? 'Salaried' : 'Self-Employed',
            "segmentType" => $segments[$purpose] ?? '-'
        ];
    }

    public function createAccountv2($wrapper = null){

        $application = ConsumerApplication::with(['emi' => function($query){
            return $query->select(['application_id', 'tenure', 'interest_rate']);
        }, 'merchant' => function($query){
            return $query/*->with(['bank_details' => function($query){
                return $query->select(['merchant_id','account_number', 'ifsc_code', 'karza_response']);
            }])*/->select(['id', 'merchant_name']);
        }, 'category' => function($query){
            return $query->select(['id', 'name']);
        }, 'bank_details' => function($query){
            return $query->select(['application_id','account_number', 'ifsc_code', 'karza_response']);
        }])->where('id', $this->request->get('id'))->first(['id', 'merchant_id', 'purpose']);

        $lender = new LenderServices($this->request);

        if(!$application->merchant){
            $error = new \stdClass();
            $error->description = 'Merchant not selected';
            $this->error = $error;
            return $this;
        }

        if(!$application->bank_details || !$application->bank_details->account_number || !$application->bank_details->ifsc_code){
            $error = new \stdClass();
            $error->description = 'Bank Details not added';
            $this->error = $error;
            return $this;
        }

        if(!$application->category){
            $error = new \stdClass();
            $error->description = 'Category not selected';
            $this->error = $error;
            return $this;
        }

        return [
            "accountId" => 'CF'.$this->request->get('id'),
            "loanAmount" => (int)$lender->getPayloadValueByID($this->request->get('id'), 'actual_disbursement_amt'),
            "productDetailsSanction" => [
                "merchantName" =>  $application->merchant->merchant_name,
                "category" => $application->category->name,
                "subCategory" => "Others",
                "productDesc" => "Class V"
        ],
        "kyc" => [
            "operationsFlowType" => 13,
            "creditFlowType" => 1
        ],
        "bankDetails" => [
            "accountNumber" =>  $application->bank_details->account_number,
            "IFSCCode"=> $application->bank_details->ifsc_code
            ]
        ];
    }

    public function captureChargev2($wrapper = null){

        $application = ConsumerApplication::with('merchant','emi.offer', 'proFormaInvoice', 'application_element.merchant_center', 'merchant_bank_details')->where('id', $this->request->get('id'))->first(['id', 'name', 'merchant_id', 'tenure', 'offer_id']);
        $ABFLSanctionWrapper = ABFLSanctionWrapper::where('application_id', $this->request->get('id'))->first();

        $dates = $this->getLoanDates();

        $lender = new LenderServices($this->request);
        $uniqid = uniqid().time();

        $subvention_amount_gst = $lender->getPayloadValueByID($this->request->get('id'), 'subvention_amount_gst');


        $merchant_processing_collected = isset($application->merchant->is_collected) && $application->merchant->is_collected == 1 ? $application->merchant->is_collected : (isset($application->proFormaInvoice) && $application->proFormaInvoice->processing_fee_by_merchant == 1 ? $application->proFormaInvoice->processing_fee_by_merchant : 0);

        $processingFee = $application->emi->processing_fee;
        $merchantCollectedPF = 0;
        //PF collected by merchant
        if($merchant_processing_collected == 1){
            if($application->emi && $application->emi->offer && (!isset($application->emi->offer->processing_fee_first_emi) || (isset($application->emi->offer->processing_fee_first_emi) && !$application->emi->offer->processing_fee_first_emi))){
                $merchantCollectedPF = 1;
            }
        }


        //Bank Details
        $merchantBank = (new ConsumerApplicationController())->getBankAccountDetails($application);


        if (!$merchantBank){
            $error = new \stdClass();
            $error->description = 'Bank is required for disbursement';
            $this->error = $error;
            return $this;
        }


        $fees[] = [
                "chargeType" => "R",
                "businessPartnerType" => "CS",
                "chargeAmount" => (string)$subvention_amount_gst,
                "taxRate1" => "9",
                "taxInclusive" => "Y",
                "taxApplicable" => "Y",
                "taxRate2" => "9",
                "businessPartnerName" => "CreditFair",
                "finalAmount" => (string) $subvention_amount_gst,
                "chargeCode" => "617", //106
                "chargeMethod" => "F",
                "chargeCalculatedOn" => "2"
        ];
        if ($processingFee){
            $fees = array_merge($fees, array([
                "chargeType" => "R",
                "businessPartnerType" => "CS",
                "chargeAmount" => (string) $processingFee,
                "taxRate1" => "9",
                "taxInclusive" => "Y",
                "taxApplicable" => "Y",
                "taxRate2" => "9",
                "businessPartnerName" => "",
                "finalAmount" => (string) $processingFee,
                "chargeCode" => "106", // -> PF Charges
                "charge_applicable" => $merchantCollectedPF ? "Y" : "N",
                "chargeMethod" => "F",
                "chargeCalculatedOn" => "2"
            ]));
        }

//        if($application->merchant->state != 'Maharashtra'){
//            $tax1 = 18;
//            $tax2 = 0;
//        }else{
//            $tax1 = 9;
//            $tax2 = 9;
//        }


        $merchant_collected_advance_amount = $lender->getPayloadValueByID($this->request->get('id'), 'merchant_collected_advance_amount');


        $noOfAdvanceInstallments = 0;

        if($merchant_collected_advance_amount) {
            $tenure = $application->emi && $application->emi->tenure ? $application->emi->tenure : 0;
            $noOfAdvanceInstallments = $application->emi && $application->emi->advance_emi ? $application->emi->advance_emi : 0;
        }else{
            $tenure = $lender->getPayloadValueByID($this->request->get('id'), 'effective_tenure');
        }

        $paymentTransaction = PaymentTransaction::where('application_id', $this->request->get('id'))->where('payment_for', 'advance_amount')->first(['trasanction_id']);

        $data = [
            "accountId" => 'CF'.$this->request->get('id'),
            "disbursalAmount" => $lender->getPayloadValueByID($this->request->get('id'), 'actual_disbursement_amt'),
            "dealNo" => $ABFLSanctionWrapper->deal_no,
            "dealId" => $ABFLSanctionWrapper->deal_id,
            //"disbursal_date" => date('Y-m-d', strtotime("2028-07-21")), //$dates['disbursal_date'],
            "repayment_date" => $dates['repay_date'],
            "due_date" => date('Y-m-d', strtotime($application->emi->emi_date)),//date('Y-m-d', strtotime("2029-04-05")),
            "chargeDetails" => [
                "numberOfInstallments" => $tenure,
                "interestRate" => (float)$lender->getPayloadValueByID($this->request->get('id'), 'roi'),
                "noOfAdvanceInstallments" => $noOfAdvanceInstallments
            ],
            "pTxnId" => $uniqid,
            "zeroRef" => strtolower(str_replace(' ', '', $application->name)),//"sddfsf",
            "payTo" => "CS",
            "charges" => $fees,
            "merchantDetails" => [
                "merchantName" => $application->merchant->merchant_name,
                "bankAccountNo" => $merchantBank['beneficiaryAccount'],
                "ifscCode" => $merchantBank['beneficiaryIFSC'],
                "beneName" => $merchantBank['beneficiaryName'],
                "micrCode" => "",
                "bankName" => "",
                "branchName" => ""
            ]
        ];

        if($merchant_collected_advance_amount) {
            $data['chargeDetails']['advEmiApplicable'] = "Y";
            $data['chargeDetails']['transactionRefNumber'] = $paymentTransaction->trasanction_id ?? "";
        }

        return $data;
    }

    public function uploadDocumentBase64($wrapper = null){

        $application = ConsumerApplicationFiles::where('id', $this->request->get('file_id'))->orderBy('created_at','desc')->first(['file_type', 'file_path']);

        if (!isset($application->file_type)){
            $error = new \stdClass();
            $error->description = 'File is missing';
            $this->error = $error;
            return $this;
        }

        $ABFLBreDecision = ABFLBreDecision::where('account_id', $this->request->get('id'))->first();

        if (!isset($ABFLBreDecision->id)){
            $error = new \stdClass();
            $error->description = 'BRE is not initiated yet';
            $this->error = $error;
            return $this;
        }

        $file = Storage::disk('s3')->get($application->file_path);

        if (!$file){
            $error = new \stdClass();
            $error->description = 'File is missing';
            $this->error = $error;
            return $this;
        }
        $uniqid = uniqid();

        $extension = '';
        $fileArray = explode("/", $application->file_path);
        $fileWithExtension = $fileArray[count($fileArray) - 1];
        if ($fileWithExtension){
            $fileWithExtension = explode('.', $fileWithExtension);
            $extension = $fileWithExtension[1] ?? '';
        }

        if (empty($extension)){
            $error = new \stdClass();
            $error->description = 'File extension is missing';
            $this->error = $error;
            return $this;
        }

        return [
            "cccId" => $ABFLBreDecision->ccc_id,
            "fileUpload" => base64_encode($file),
            "fileName" => $application->file_type.'.'.$extension,
            "accountId" => 'CF'.$this->request->get('id'),
            "customerId" => $ABFLBreDecision->ccc_id,
            "docType" => $application->file_type,
            "requestId" => $uniqid.$this->request->get('id'),
        ];
    }

    public function createToken($wrapper = null){
        return [
            'id' => $this->request->get('id')
        ];
    }

    public function getPayload($func){
        if(method_exists($this, $func)){
            return ['payload' => $this->$func()];
        }
        return ['payload' => []];
    }

    public function DKYC($wrapper = null)
    {

        $consumer = ConsumerApplication::where('id', $this->request->get('id'))->first(['id','pan_card', 'dob', 'name', 'permanent_address_line_1', 'permanent_address_landmark', 'permanent_address_state', 'permanent_address_city', 'permanent_address_pincode']);

        $ABFLBreDecision = ABFLBreDecision::where('account_id', $this->request->get('id'))->first();

        if (!isset($ABFLBreDecision->id)){
            $error = new \stdClass();
            $error->description = 'BRE is not initiated yet';
            $this->error = $error;
            return $this;
        }

        $creditReport = CreditReport::where('application_id', $this->request->get('id'))->where('applicant_type', 1)->first(['id','panValidation', 'panVendor']);

        if (isset($creditReport->id) && $creditReport->panValidation){
            $panValidation = json_decode($creditReport->panValidation, 1);
            if($creditReport->panVendor == "decentro"){
                $kycResult = json_decode($creditReport->panValidation);
                if(isset($kycResult->kycResult)){
                    $panVerification = $kycResult->kycResult;
                    $nsdl_name = "";
                    if (isset($panVerification->firstName)) {
                        $nsdl_name .= $panVerification->firstName . " ";
                    }
                    if (isset($panVerification->middleName)) {
                        $nsdl_name .= $panVerification->middleName . " ";
                    }
                    if (isset($panVerification->lastName)) {
                        $nsdl_name .= $panVerification->lastName . " ";
                    }
                }else{
                    $panError = true;
                }
            }else if(!isset($panValidation['sch:percentMatch'])){
                $panError = true;
            }

            if(isset($panError) || (isset($nsdl_name) && empty($nsdl_name))){
                $error = new \stdClass();
                $error->description = 'Please validate the PAN';
                $this->error = $error;
                return $this;
            }

            if ((isset($nsdl_name) && empty($nsdl_name)) || !isset($nsdl_name)){
                $nsdl_name = ($panValidation['sch:firstName'] ?? '').' '.($panValidation['sch:middleName'] ?? '').' '.($panValidation['sch:lastName'] ?? '');
            }
        }

        /*if (!isset($nsdl_name) || (!$nsdl_name)){
            $error = new \stdClass();
            $error->description = 'PAN Validation not found';
            $this->error = $error;
            return $this;
        }*/
        $docType = 1;
        $applications = ConsumerApplicationFiles::where('consumer_application_id', $this->request->get('id'))->orderBy('created_at','desc')->whereIn('file_type', ['aadhar_card_masked', 'aadhar_card_back_masked', 'customer_photo', 'CUSTPHOTO_'.$this->request->get('id').'_1', 'votar_id_front_masked', 'votar_id_back_masked', 'driving_license_masked','passport_front_masked', 'passport_back_masked'])->get(['file_type', 'file_path']);

        if (count($applications)){
            $s3Main = Storage::disk('s3');
            foreach($applications as $application) {
                if (isset($application->file_type)) {
                    if($application->file_type == 'aadhar_card_masked'){
                        //$s3 = Storage::disk('s3_temp');
                        $front = $this->getPNGFile($s3Main->get($application->file_path), $application->file_type);
                        //$front = base64_encode($s3Main->get($application->file_path));
                    }else if ($application->file_type == 'aadhar_card_back_masked'){
                        //$s3 = Storage::disk('s3_temp');
                        $back = $this->getPNGFile($s3Main->get($application->file_path), $application->file_type);
                    }else if($application->file_type == 'customer_photo' || $application->file_type == 'CUSTPHOTO_'.$this->request->get('id').'_1'){
                        $selfie = base64_encode($s3Main->get($application->file_path));
                    }else if ($application->file_type == 'votar_id_front_masked'){
                        $votar_id = $this->getPNGFile($s3Main->get($application->file_path), $application->file_type);
                    }else if ($application->file_type == 'votar_id_back_masked'){
                        $votar_id_back = $this->getPNGFile($s3Main->get($application->file_path), $application->file_type);
                    }else if ($application->file_type == 'driving_license_masked'){
                        $driving_license = $this->getPNGFile($s3Main->get($application->file_path), $application->file_type);
                    }else if ($application->file_type == 'passport_front_masked'){
                        $passport = $this->getPNGFile($s3Main->get($application->file_path), $application->file_type);
                    }else if ($application->file_type == 'passport_back_masked'){
                        $passport_back = $this->getPNGFile($s3Main->get($application->file_path), $application->file_type);
                    }
                }

                if (isset($front) && isset($back) && isset($selfie)){
                    break;
                }
            }
        }

        if (!isset($front)){
            if (!isset($votar_id) && !isset($driving_license) && !isset($passport)) {
                $error = new \stdClass();
                $error->description = 'Front Aadhaar/VotarID/DL/Passport masked is Missing';
                $this->error = $error;
                return $this;
            }
        }

        if (!isset($selfie)){
            $error = new \stdClass();
            $error->description = 'Selfie is Missing';
            $this->error = $error;
            return $this;
        }

        if (!isset($consumer->pan_card)){
            $error = new \stdClass();
            $error->description = 'PAN Number Missing';
            $this->error = $error;
            return $this;
        }

        if (!isset($back)){
            if (!isset($votar_id) && !isset($driving_license) && !isset($passport)) {
                $error = new \stdClass();
                $error->description = 'Back Aadhaar/VotarID/DL/Passport masked is Missing';
                $this->error = $error;
                return $this;
            }
        }

        if ((isset($votar_id) || isset($driving_license) || isset($passport)) || (isset($front) && isset($back))) {
            if (!isset($front) || !isset($back)){
                if (isset($votar_id)){
                    $front = $votar_id;
                    $back = $votar_id_back ?? '';
                    $docType = 2;
                }
                if (isset($driving_license)){
                    $front = $driving_license;
                    $docType = 4;
                }
                if (isset($passport)){
                    $front = $passport;
                    $back = $passport_back ?? '';
                    $docType = 3;
                }
            }
        }


        /*$KYCDetails = KYCDetails::where('application_id', $this->request->get('id'))->where('applicant_type', 1)->where('response', 'like', '%"document_type":"aadhaar"%')->whereNotNull('response')->first(['id', 'request_id']);

        if(isset($KYCDetails->id) && $xmlDoc = $this->getDigioAadharXML($KYCDetails->request_id)){
            //OKYC - Digio Aadhaar XML
            return [
                "Customer Id" => $ABFLBreDecision->ccc_id,
                "Loan Application Id" => 'CF'.$ABFLBreDecision->account_id,
                "Transaction Id" => $ABFLBreDecision->id.$ABFLBreDecision->account_id,
                "XML Doc" => base64_encode($xmlDoc),
                "Doc Type" => "8",
                "Declared DoB" => date('d/m/Y', strtotime($consumer->dob)),
                "Declared PAN" => $consumer->pan_card,
                "NSDL Name" => trim($nsdl_name ?? $consumer->name),
                "Declared Name" => trim($consumer->name),
                "Declared Address" => trim($consumer->permanent_address_line_1.' '.$consumer->permanent_address_landmark.' '.$consumer->permanent_address_city.' '.$consumer->permanent_address_state.' '.$consumer->permanent_address_pincode),
                "Selfie" => $selfie
            ];
        }*/

        // TODO: Implement DKYC() method.
        // IKYC - OSV

        $kyc = [
            "Customer Id" => $ABFLBreDecision->ccc_id,
            "Loan Application Id" => 'CF'.$ABFLBreDecision->account_id,
            "Transaction Id" => $ABFLBreDecision->id.$ABFLBreDecision->account_id,
            "Doc Front Photo" => $front,
            "Declared DoB" => date('d/m/Y', strtotime($consumer->dob)),
            "Doc Type" => (string)$docType, //1 - Aaddhar, 2 - Voter ID, 3 - Passport, 4 - DRIVING_LICENSE
            "Declared PAN" => $consumer->pan_card,
            "NSDL Name" => trim($nsdl_name ?? $consumer->name),
            "Selfie" => $selfie,
            "Declared Name" => trim($consumer->name),
            "Declared Address" => trim($consumer->permanent_address_line_1.' '.$consumer->permanent_address_landmark.' '.$consumer->permanent_address_city.' '.$consumer->permanent_address_state.' '.$consumer->permanent_address_pincode)
        ];

        if (isset($back) && $back){
            $kyc["Doc Back Photo"] = $back;
        }

        return $kyc;

        $kyc = [
            "Customer Id" => "123",
            "Loan Application Id" => "123",
            "Transaction Id" =>"123",
            "XML Zip" => "",
            "XML Zip Pass" =>"1234",
            "Doc Type" => "7",
            "Declared DoB" => "20/01/1990",
            "Declared PAN" => "ACEE123434",
            "NSDL Name" => "John Doe",
            "Declared Name" => "John Doe",
            "Declared Address" =>"",
            "Selfie" => ""
        ];
    }

    private function getPNGFile($data, $fileName){
        $curl = curl_init();
        $path = storage_path(time().rand('100000', '999999').'.pdf');
        $file = fopen($path, "w");
        fwrite($file, $data);
        fclose($file);

        $data = base64_encode(file_get_contents($path));
        /*if (function_exists('curl_file_create')) {
            (new Slack(new Request(['title' => 'ABFL GetPNG - curl_file_create', 'fields' => ['File' => $fileName], 'group' => Slack::$STAGE_TESTING])))->send();
            $cFile = curl_file_create($path, '', $fileName);
            //$cFile = new \CURLFile($path, '', $fileName);
        } else { //
            (new Slack(new Request(['title' => 'ABFL GetPNG - realpath', 'fields' => ['File' => $fileName], 'group' => Slack::$STAGE_TESTING])))->send();
            $cFile = '@' . realpath($path);
        }*/

        curl_setopt_array($curl, array(
            CURLOPT_URL => _env('PY_SERVER_PDF_TO_IMAGE'),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_POSTFIELDS => json_encode(['file'=> "", 'base64' => $data, 'vfileName' => $fileName]),
            CURLOPT_HTTPHEADER => ['Content-Type:application/json'],
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        unlink($path);
        $dataRes = json_decode($response, 1);
        if($dataRes) {
            return stripslashes(array_values($dataRes)[0]);
        }
        return '';
    }

    private function getDigioAadharXML($request_id){

        return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Certificate><CertificateData><KycRes code="0821b21363444734941d33306fce9d84" ret="Y" ts="2022-07-31T19:16:00.758+05:30" ttl="2023-07-31T19:16:00" txn="UKC:4cb965845ecf72a6bcad2d2f3400362620220731191517"><UidData tkn="01002274ehLdeHJ5drdyfrH5SMflk4P5a8DtYxWfbM0wv7Sg7SZaT1jkENxoJ/eadE4gSKgx" uid="xxxxxxxx2564"><Poi dob="06-06-2000" gender="M" name="Suryateja Veeresh Gujjula"/><Poa co="C/O: Veeresh Gujjula" country="India" dist="Mumbai City" house="Grd Floor Vijay Nagar Sangh" lm="Near Markanday Mandir" loc="Antop Hill" pc="400037" state="Maharashtra" street="Shaikh Mistri Road" vtc="Mumbai"/><LData co="द्वारा: वीरेश गुज्जुला" country=" " dist="मुंबई नगर" house="ग्र्ड फ्लोर विजय नगर संघ" lang="06" lm="मर्कंडय मंदिर के पास" loc="अंटॉप पहाड़ी" name="सुर्यतेज विरेष गूजला" pc="400037" state="महाराष्ट्र" street="शेख मिस्त्री रोड" vtc="मुंबई"/><Pht>/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCADIAKADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6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Qtw0ZKy4bHRhwT9RTjKWIONq+p61zexnfY6vbQte4zydxpRDg+/tS+dGBjcXPcAZNOBkbjZ5a/rWscP3ZjKv2DhF2jlj1FKibAWwSfXNKu0HYoOOp96kdgEwPpXSlZHO3cjjQmEE8ZHpUiA7QCOlOUkAYA6d6apBJ3HFMRHEpXfg8biQPrzUoBDYbqR2oUlZOuNwoLcgn6UANCEensKUKSM8/SkJB7ihT8gOR+FADjGDgY7VIxEUfUEnjFFFADokAQ5PJ5pxQA/eyPeiimIAp25wRz1xUbKc52/nRRQAjKT1FNKDHYUUUhjDGpHzYI9MU1rVMjCJ9cUUUAS+UAMZx+VRlctgEHHeiigBwXBx1pGHzj0oooAdtPXn8aYFPm9OCOlFFADipBAI79u1NlUKu4Etgg4oooAGG2MsRjikwY4iWPQZ9KKKAP/2Q==</Pht></UidData></KycRes></CertificateData><Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
  <SignedInfo><CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
    <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
  <Reference URI=""><Transforms><Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/></Transforms><DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/><DigestValue>B/rsv851nCEYuARXssnLajUQafCgzkkOep8hxcNxnRw=</DigestValue></Reference></SignedInfo><SignatureValue>3DU9LSObmxPfwuWt/pmCwmtuykqvauk2eGUuktryOr32k4Q6pkj0c4VmpHNqLxaKpjrunWLlnCyZ9jVk4Ozchwz4RQ7yGtrmzO80VSBblGSIlF+1nGPmcTCYSgZDZJWqZdlQk0Zr1O3bAjpG1Sb5KB9PfyHzTrV27nqfqmSQuaRsLcYTXwIy5oweJ8WyTH8h1JqJbj3u2APD9UzS528+fK+h17kxwKWHm+C1ezuNgUdyqDcF3v5oAAYEZXsyt2Rf/+hbir07w6E80Q//ZbctyDOLx3tUr8TB3xuemyHBcEWVkoV8DqsSAWyF4pYLU2kl48E193uRQY4itwbA8eUXyA==</SignatureValue>
<KeyInfo><X509Data><X509SubjectName>CN=DS NATIONAL E-GOVERNANCE DIVISION,serialNumber=0f30cb67333f634db11fdb41868b343a6f0469581bdb9fd2a2e4cb59e7797a43,houseIdentifier=6 CGO COMPLEX,street=ELECTRONICS NIKETAN,CGO COMPLEX,NEW DELHI,NEW DELHI,ST=Delhi,postalCode=110003,OU=MINISTRY OF ELECTRONICS AND INFORMATION TECHNOLOGY,O=NATIONAL E-GOVERNANCE DIVISION,C=IN</X509SubjectName><X509Certificate>MIIGUTCCBTmgAwIBAgIIJh6AfQEBlGgwDQYJKoZIhvcNAQELBQAwdDELMAkGA1UEBhMCSU4xIjAgBgNVBAoTGVNpZnkgVGVjaG5vbG9naWVzIExpbWl0ZWQxDzANBgNVBAsTBlN1Yi1DQTEwMC4GA1UEAxMnU2FmZVNjcnlwdCBzdWItQ0EgZm9yIFJDQUkgQ2xhc3MgMiAyMDE0MB4XDTIwMDkwNTA3MTgyOVoXDTIzMDkwNTA3MTgyOVowggFhMQswCQYDVQQGEwJJTjEnMCUGA1UEChMeTkFUSU9OQUwgRS1HT1ZFUk5BTkNFIERJVklTSU9OMTswOQYDVQQLEzJNSU5JU1RSWSBPRiBFTEVDVFJPTklDUyBBTkQgSU5GT1JNQVRJT04gVEVDSE5PTE9HWTEPMA0GA1UEERMGMTEwMDAzMQ4wDAYDVQQIEwVEZWxoaTE8MDoGA1UECRMzRUxFQ1RST05JQ1MgTklLRVRBTixDR08gQ09NUExFWCxORVcgREVMSEksTkVXIERFTEhJMRYwFAYDVQQzEw02IENHTyBDT01QTEVYMUkwRwYDVQQFE0AwZjMwY2I2NzMzM2Y2MzRkYjExZmRiNDE4NjhiMzQzYTZmMDQ2OTU4MWJkYjlmZDJhMmU0Y2I1OWU3Nzk3YTQzMSowKAYDVQQDEyFEUyBOQVRJT05BTCBFLUdPVkVSTkFOQ0UgRElWSVNJT04wggEiMA0GCS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DwYDVR0TAQH/BAUwAwEB/zARBgNVHQ4ECgQIQrjFz22zV+EwCwYDVR0PBAQDAgEGMA0GCSqGSIb3DQEBCwUAA4IBAQAdAUjv0myKyt8GC1niIZplrlksOWIR6yXLg4BhFj4ziULxsGK4Jj0sIJGCkNJeHl+Ng9UlU5EI+r89DRdrGBTF/I+g3RHcViPtOne9xEgWRMRYtWD7QZe5FvoSSGkW9aV6D4iGLPBQML6FDUkQzW9CYDCFgGC2+awRMx61dQVXiFv3Nbkqa1Pejcel8NMAmxjfm5nZMd3Ft13hy3fNF6UzsOnBtMbyZWhS8Koj2KFfSUGX+M/DS1TG2ZujwKKXCuKq7+67m0WF6zohoHJbqjkmKX34zkuFnoXaXco9NkOi0RBvLCiqR2lKfzLM7B69bje+z0EqnRNo5+s8PWSdy+xt</X509Certificate><X509SubjectName>CN=SafeScrypt CA 2014,houseIdentifier=II Floor, Tidel Park,street=No.4, Rajiv Gandhi Salai, Taramani, Chennai,ST=Tamil Nadu,postalCode=600 113,OU=Certifying Authority,O=Sify Technologies Limited,C=IN</X509SubjectName><X509Certificate>MIIEfDCCA2SgAwIBAgICJ7IwDQYJKoZIhvcNAQELBQAwOjELMAkGA1UEBhMCSU4xEjAQBgNVBAoTCUluZGlhIFBLSTEXMBUGA1UEAxMOQ0NBIEluZGlhIDIwMTQwHhcNMTQwMzA1MTEyOTIyWhcNMjQwMzA1MDYzMDAwWjCB6TELMAkGA1UEBhMCSU4xIjAgBgNVBAoTGVNpZnkgVGVjaG5vbG9naWVzIExpbWl0ZWQxHTAbBgNVBAsTFENlcnRpZnlpbmcgQXV0aG9yaXR5MRAwDgYDVQQREwc2MDAgMTEzMRMwEQYDVQQIEwpUYW1pbCBOYWR1MTQwMgYDVQQJEytOby40LCBSYWppdiBHYW5kaGkgU2FsYWksIFRhcmFtYW5pLCBDaGVubmFpMR0wGwYDVQQzExRJSSBGbG9vciwgVGlkZWwgUGFyazEbMBkGA1UEAxMSU2FmZVNjcnlwdCBDQSAyM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ificate><X509SubjectName>CN=SafeScrypt sub-CA for RCAI Class 2 2014,OU=Sub-CA,O=Sify Technologies Limited,C=IN</X509SubjectName><X509Certificate>MIIFNzCCBB+gAwIBAgIFGeOxJAEwDQYJKoZIhvcNAQELBQAwgekxCzAJBgNVBAYTAklOMSIwIAYDVQQKExlTaWZ5IFRlY2hub2xvZ2llcyBMaW1pdGVkMR0wGwYDVQQLExRDZXJ0aWZ5aW5nIEF1dGhvcml0eTEQMA4GA1UEERMHNjAwIDExMzETMBEGA1UECBMKVGFtaWwgTmFkdTE0MDIGA1UECRMrTm8uNCwgUmFqaXYgR2FuZGhpIFNhbGFpLCBUYXJhbWFuaSwgQ2hlbm5haTEdMBsGA1UEMxMUSUkgRmxvb3IsIFRpZGVsIFBhcmsxGzAZBgNVBAMTElNhZmVTY3J5cHQgQ0EgMjAxNDAeFw0xNDAzMDYwNDMwMDBaFw0yNDAzMDUwNDMwMDBaMHQxCzAJBgNVBAYTAklOMSIwIAYDVQQKExlTaWZ5IFRlY2hub2xvZ2llcyBMaW1pdGVkMQ8wDQYDVQQLEwZTdWItQ0ExMDAuBgNVBAMTJ1NhZmVTY3J5cHQgc3ViLUNBIGZvciBSQ0FJIENsYXNzIDIgMjAxNDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMdLWmI2QwuMUaDmmA9sA31KCi+x3jTbmvx6+dPrqjeaN2/41l6XExq6i9g5AjK4XSwQM6pmtpi3VgUDQYud/v9my5BNasTc3GGVKfsMMCMZaSxa9JFs6BCIztjOP6Q+nKamNqiIleGCH1EFt5dlRooks0XCtTvYmzaLu72pY9/7w8yopPDDFRcAkiRP/+jEiMF3XrT+ksMkwAa2izFaWFQskxApPVZbJV007GL861c4vNeIIWMpaUPeJAWaRkC0RvuSdW19/dM3wA4pp45fwunlYao10hQwEgvN9rvT44rFmT5UYsSfEOfOSinWiemObzOdQ+h8UtcbhCcHOlsoUp8CAwEAAaOCAVgwggFUMBIGA1UdEwEB/wQIMAYBAf8CAQAwDgYDVR0PAQH/BAQDAgEGMBMGA1UdIwQMMAqACEw+jj2YAqV+MBEGA1UdDgQKBAhDDjdX6SfZCDArBgNVHREEJDAipCAwHjEcMBoGA1UEAxMTU0FGRVNDUllQVE9OTElORV8xNTA/BgNVHR8EODA2MDSgMqAwhi5odHRwOi8vY3JsLnNhZmVzY3J5cHQuY29tL1NhZmVTY3J5cHRDQTIwMTQuY3JsMIGDBggrBgEFBQcBAQR3MHUwSwYIKwYBBQUHMAKGP2h0dHBzOi8vd3d3LnNhZmVzY3J5cHQuY29tL2RydXBhbC9kb3dubG9hZC9TYWZlU2NyeXB0Q0EyMDE0LmNlcjAmBggrBgEFBQcwAYYaaHR0cDovL29jc3Auc2FmZXNjcnlwdC5jb20wEgYDVR0gBAswCTAHBgVggmRkAjANBgkqhkiG9w0BAQsFAAOCAQEAj0h3yH3B0yBhS3Ye8CS1ZdPlpTUFuyX3Fx7EEoM1TB8R1IznKBrlKCxRs9kZ2XX23Td0plriJgnATTEfAxZou4KwIs0cAtWSSQpL3AquW4/PzuYTOVCUt9cAPXziqQISVoIqWcJjsg8fIXAffumLDHvZD/0qPq6xhZvFX1hfUv2wA6LSITB9VB4YzV5OyPm+SM1BFkq3HA07YY8rfLtCfDbF6y79HV49bVESK0ZWNZqofMS9mvYM8xgAADpefe4ICh9TetGIOg3XL0vgX13MzLOy4xM/tDkRPkNXuuUZ7n1jUwGkz8LJAOAc59zr2QI/DzAoEaeeBUrlNJZUCZoFAA==</X509Certificate></X509Data></KeyInfo></Signature></Certificate>';

        if ($request_id) {
            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => "https://api.digio.in/client/kyc/v2/media/" . $request_id . "?doc_type=aadhaar&xml=true",
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'GET',
                CURLOPT_POSTFIELDS => json_encode(['doc_type' => 'aadhaar', 'xml' => true]),
                CURLOPT_HTTPHEADER => ['Content-Type:text/plain', 'Authorization:Basic ' . base64_encode(_env('DIGIO_CLIENT_ID') . ':' . _env('DIGIO_CLIENT_SECRET'))],
            ));

            $response = curl_exec($curl);

            curl_close($curl);

            return $response;
        }
        return false;
    }

    private function getLoanDates(){
        if (date('d') > 15 ){
            $date = new \DateTime('now');
            $disbursal_date = date('Y-m-d');
            $date->modify('first day of next month');
            $repay_date = date('Y-m-d', strtotime($date->format('Y-m-d').' + 4 days'));
        }else{
            $disbursal_date = date('Y-m-d');
            $repay_date = date('Y-m-d');
        }

        //$repay_date = '2031-11-24';

        return ['disbursal_date' => $disbursal_date, 'repay_date' => $repay_date];
    }

    public function updateCCC($wrapper = null)
    {
        // TODO: Implement updateCCC() method.

        $consumer = ConsumerApplication::where('id', $this->request->get('id'))->first(['id', 'mobile_number', 'gender','email','pan_card', 'dob', 'name', 'permanent_address_line_1', 'permanent_address_landmark', 'permanent_address_state', 'permanent_address_city', 'permanent_address_pincode']);

        $ABFLBreDecision = ABFLBreDecision::where('account_id', $this->request->get('id'))->first();

        if (!isset($ABFLBreDecision->id)){
            $error = new \stdClass();
            $error->description = 'BRE is not initiated yet';
            $this->error = $error;
            return $this;
        }

        if (!$consumer->dob){
            $error = new \stdClass();
            $error->description = 'DOB is missing';
            $this->error = $error;
            return $this;
        }

        if (!$consumer->email){
            $error = new \stdClass();
            $error->description = 'EMAIL is missing';
            $this->error = $error;
            return $this;
        }

        if (!isset($ABFLBreDecision->id)){
            $error = new \stdClass();
            $error->description = 'Mobile number is missing';
            $this->error = $error;
            return $this;
        }

        $name = explode(' ', $consumer->name);
        $firstName = $name[0] ?? $name;
        unset($name[0]);


        return [
            "accountId" => 'CF'.$this->request->get('id'),
            "ccc_id" => $ABFLBreDecision->ccc_id,
            "addressLine1" => ($consumer->permanent_address_line_1.' '.$consumer->permanent_address_landmark.' '.$consumer->permanent_address_city.' '.$consumer->permanent_address_state.' '.$consumer->permanent_address_pincode),
            "city" => $consumer->permanent_address_city,
            "addressLine2" => "",
            "dob" => date('d-m-Y', strtotime($consumer->dob)),
            "email" => $consumer->email,
            "firstName" => $firstName,
            "gender" => $consumer->gender,
            "lastName" => implode(' ', $name),
            "mobile" => $consumer->mobile_number,
            "panNo" => $consumer->pan_card,
            "pincode" => (int)$consumer->permanent_address_pincode,
            "state" => strtoupper($consumer->permanent_address_state)
        ];
    }
}