<?php

namespace App\Method\JM\Payload;

use App\FinBitData;
use App\Http\Controllers\Admin\ConsumerApplicationController;
use App\Http\Controllers\Admin\ConsumerDocument;
use App\Http\Controllers\Admin\LenderServices;
use App\JMDocuments;
use App\JMLoanBooking;
use App\KYCDetails;
use App\MerchantOffers;
use App\OnlinePayment;
use App\PaymentTransaction;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Method\JM\Helpers\JMHelper;
use App\ConsumerApplication;
use App\ConsumerApplicationFiles;
use App\DigitalSignDetails;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Storage;
use App\Slack;

class Payload implements JMHelper
{
    public $request;
    public $error = null;

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

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

    public function borrowerRegistration($wrapper = null){
        $application = ConsumerApplication::with('bank_details','application_element','digital_sign')->where('id', $this->request->get('id'))->first(['id', 'name', 'dob', 'gender', 'email', 'merchant_id', 'mobile_number','pan_card','permanent_address_line_1','permanent_address_state','permanent_address_city','permanent_address_pincode','created_at']);

        $name = explode(' ', $application->name);
        if (empty($application->name)){
            $error = new \stdClass();
            $error->description = 'Name is required';
            $this->error = $error;
            return $this;
        }

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

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

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

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

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

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

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

        if (empty($application->application_element->father_name)){
            $error = new \stdClass();
            $error->description = 'Father name is required';
            $this->error = $error;
            return $this;
        }

        if (empty($application->bank_details->name)){
            $error = new \stdClass();
            $error->description = 'Account Holder Name is required';
            $this->error = $error;
            return $this;
        }

        if (empty($application->bank_details->ifsc_code)){
            $error = new \stdClass();
            $error->description = 'IFSC is required';
            $this->error = $error;
            return $this;
        }

        if (empty($application->bank_details->account_type)){
            $error = new \stdClass();
            $error->description = 'Account Type is required';
            $this->error = $error;
            return $this;
        }
        //echo "<pre>";print_r($application);die;
        if (empty($application->bank_details->account_number)){
            $error = new \stdClass();
            $error->description = 'Account Number is required';
            $this->error = $error;
            return $this;
        }

        if (empty($application->digital_sign) || !$application->digital_sign[0]['isaddress']){
            $error = new \stdClass();
            $error->description = 'Ip is required';
            $this->error = $error;
            return $this;
        }
        if (empty($application->digital_sign) || !$application->digital_sign[0]['client']){
            $error = new \stdClass();
            $error->description = 'User agent is required';
            $this->error = $error;
            return $this;
        }
        if($application->gender == 'MALE'){
            $title = "Mr.";
        }else if($application->gender == 'FEMALE'){
            $title = "Ms.";
        }else{
            $title = '';
        }
        $user_agent = json_decode($application->digital_sign[0]['client'], TRUE);
        $userAgent = $user_agent['userAgent'];
        return [
            "email" => $application->email,
            "title" => $title,
            "firstName" =>$name[0],
            "lastName" =>end($name),
            "fathersName" =>$application->application_element->father_name,
            "mobile" =>$application->mobile_number,
            "pan" =>$application->pan_card,
            "dob" =>strtotime($application->dob)*1000,
            "street1" =>$application->permanent_address_line_1,
            "street2" =>$application->permanent_address_state,
            "city" =>$application->permanent_address_city,
            "pin" =>$application->permanent_address_pincode,
            "holderName" =>$application->bank_details->name,
            "ifsc" =>$application->bank_details->ifsc_code,
            "accountType" =>strtoupper($application->bank_details->account_type),
            "accountNumber" =>$application->bank_details->account_number,
            "ip" =>$application->digital_sign[0]['isaddress'],
            "ua" =>$userAgent,
            "timestamp" => strtotime($application->created_at)*1000
        ];
        

    }

    public function getFileType($isIncome = false){
        if ($isIncome){
            return [
                'salary_slip' => 'salary_slip',
                'bank_statement' => 'bank_statement',
            ];
        }
        return [
            'aadhaar_front' => ['aadhar_card_masked', 'aadhar_card'],
            'aadhaar_back' => ['aadhar_card_back_masked', 'aadhar_card_back'],
            'driving_licence' => 'driving_license',
            'voter_id' => 'votar_id_front',
            'pan_image' => 'pan_card',
            //'credit_report' => 'equifax_report',
            'nach_slip' => 'nach',
            'salary_slip' => 'salary_slip',
            'loan_agreement' => 'loan_agreement_esign',
            'sanction_letter' => 'sanction_letter',
            'bank_statement' => 'bank_statement',
            'photos' => 'customer_photo',
            'aadhaar_xml' => 'digio_report_applicant',
            'utility_bill' => 'utilitybillvalidation',
            'self_attested_aadhaar' => 'self_attested_aadhar',
            'self_attested_pan' => 'self_attested_pan',
            'electricity_bill' => 'electricity_bill',
            'verification_video' => 'video_kyc'
        ];
    }

    public function uploadDocumentV1($wrapper = null){
        $fileId = $this->request->get('file_id');
        $file = ConsumerApplicationFiles::where('id', $fileId)->first(['id', 'file_path', 'file_type', 'password']);
        $documents = [];

        $documentsCount = JMDocuments::where('consumer_application_file_id', $fileId)->first(['id']);

        if (!isset($documentsCount->id)) {
            $s3 = Storage::disk('s3');
            if($s3->exists($file->file_path)) {
                $documents[] = [
                    "fileUrl" => $s3->temporaryUrl(
                        $file->file_path, Carbon::now()->addMinutes(5)
                    ),
                    "docReferenceID" => $fileId,
                    "docCategory" => $file->file_type,
                    "docSubCategory" => $this->request->get('document_id'),
                    "encryptionKey" => $file->password,
                    "comments" => "",
                    "coApplicantId" => "",
                    "docNumber" => ""
                ];
            }else{
                $error = new \stdClass();
                $error->description = 'File is missing: '.$file->file_type;
                $this->error = $error;
                return $this;
            }
        }


        return [
            "taskType" => "sync", //async
            "documents" => $documents
        ];
    }

    public function uploadDocument($wrapper = null){
        $fileId = $this->request->get('file_id');
        $file = ConsumerApplicationFiles::where('id', $fileId)->first(['id', 'file_path', 'file_type', 'password']);
        $documents = [];

        $documentsCount = JMDocuments::where('consumer_application_file_id', $fileId)->first(['id']);

        if (!isset($documentsCount->id)) {
            $s3 = Storage::disk('s3');
            if($s3->exists($file->file_path)) {
                file_put_contents($this->request->get('file_path'), $s3->get($file->file_path));
                $documents = array(
                    'document_id' => $this->request->get('document_id'),
                    'document' => $this->request->get('file_path')
                    //'document' => curl_file_create($this->request->get('file_path'), mime_content_type($this->request->get('file_path')), basename($this->request->get('file_path')))
                );
            }else{
                $error = new \stdClass();
                $error->description = 'File is missing: '.$file->file_type;
                $this->error = $error;
                return $this;
            }
        }


        return $documents;
    }


    public function createLoan($wrapper = null, $is_update = false){
        ConsumerApplication::isApplicantType(true);
        $application = ConsumerApplication::with('creditReport','bank_details', 'emi', 'proFormaInvoice', 'merchant', 'application_element', 'merchant_bank_details', 'digital_sign')->where('id', $this->request->get('id'))->first();

        $merchant = MerchantOffers::where('id', $application->emi->offer_id)->first(['advance_type']);

        if (empty($application->approved_amount)){
            $error = new \stdClass();
            $error->description = 'Loan Amount is required';
            $this->error = $error;
            return $this;
        }

        if (empty($application->emi->tenure)){
            $error = new \stdClass();
            $error->description = 'tenure is required';
            $this->error = $error;
            return $this;
        }

        if (!isset($application->creditReport[0]->Score)){
            $error = new \stdClass();
            $error->description = 'Generate the Bureau';
            $this->error = $error;
            return $this;
        }

        if (!$application->bank_details){
            $error = new \stdClass();
            $error->description = 'bank is required';
            $this->error = $error;
            return $this;
        }else{
            $resBank = json_decode($application->bank_details->karza_response);
            if(!isset($resBank->result) || (!isset($resBank->result->bankTxnStatus) || !$resBank->result->bankTxnStatus)){
                $error = new \stdClass();
                $error->description = 'validate the bank details';
                $this->error = $error;
                return $this;
            }
        }

        $net_tenure = $application->emi->tenure;

        $net_loan_amount = $application->approved_amount;

        $merchant_collected_advance_amount = $application->proFormaInvoice && $application->proFormaInvoice->merchant_collected_advance_amount ? $application->proFormaInvoice->merchant_collected_advance_amount : 0;

        if (!$merchant_collected_advance_amount){
            $net_loan_amount -= $application->emi->upfront_from_customer;
            if ($merchant->advance_type == 'emi'){
                $net_tenure = $application->emi->tenure - $application->emi->advance_emi;
            }
        }


        $panVerified_using = $aadhaarVerified_using = 1;
        $isPANVerified = $isAadhaarVerified = false;
        $aadhaarId = $panId = $aadhaarName = $panName = '';
        $kycdetails = KYCDetails::where('application_id', $application->id)->whereNotNull('response')->first();
        if(isset($kycdetails->response) && $kycdetails->response){
            $kycResponse = json_decode($kycdetails->response);
            foreach($kycResponse as $kRes){
                if(isset($kRes->document_type)) {
                    if ($kRes->document_type == 'aadhaar' && $kRes->applicant_type == 1) {
                        $aadhaarId = strlen($kRes->id_number) != 4 ? substr($kRes->id_number, -4) : $kRes->id_number;
                        $aadhaarName = $kRes->name;
                        $isAadhaarVerified = true;
                        $aadhaarVerified_using = 4;
                    } elseif ($kRes->document_type == 'pan' && $kRes->applicant_type == 1) {
                        $panId = $kRes->id_number;
                        $panName = $kRes->name;
                        $isPANVerified = true;
                        $panVerified_using = 4;
                    }
                }else if (isset($kRes->actions)){
                    foreach ($kRes->actions as $kItem) {
                        if (isset($kItem->details)) {
                            foreach ($kItem->details as $docDetails) {
                                if ($docDetails->document_type == 'aadhaar' && $kycdetails->applicant_type == 1) {
                                    $aadhaarId = strlen($docDetails->id_number) != 4 ? substr($docDetails->id_number, -4) : $docDetails->id_number;
                                    $aadhaarName = $docDetails->name;
                                    $isAadhaarVerified = true;
                                    $aadhaarVerified_using = 4;
                                } elseif ($docDetails->document_type == 'pan' && $kycdetails->applicant_type == 1) {
                                    $panId = $docDetails->id_number;
                                    $panName = $docDetails->name;
                                    $isPANVerified = true;
                                    $panVerified_using = 4;
                                }
                            }
                        }
                    }
                }
            }
        }

        if (!$isAadhaarVerified){
            $isAadhaarVerified = true;
            $aadhaarName = $application->name;
            $aadhaarId = substr($application->aadhaar_card, -4);
        }
        if (!$isPANVerified){
            $isPANVerified = true;
            $panName = $application->name;
            $panId = $application->pan_card;
        }


        if (!$aadhaarId || !$panId){
            $error = new \stdClass();
            $error->description = 'KYC Identifier: Pan & Aadhaar No. required';
            $this->error = $error;
            return $this;
        }


        $applicationController = new ConsumerApplicationController();
        $merchantBank = $applicationController->getBankAccountDetails($application);

        $product_name = $application->application_element ? $application->application_element->product_name : '';

        $product_name = $applicationController->getProductName($product_name);

        $agreement_signature_type = 3;
        if($net_loan_amount > 150000){
            $agreement_signature_type = 2;
        }

        $agreement_date = $application->digital_sign && isset($application->digital_sign[0]) && $application->digital_sign[0]->created_at ? date('d-M-Y', strtotime($application->digital_sign[0]->created_at)) : date('d-M-Y');

        $data = [
                "email" => $application->email,
                "gender" => $application->gender == 'MALE' ? 1 : 2,
                "address" => $application->permanent_address_line_1.' '. $application->permanent_address_city.' '.$application->permanent_address_state.', '.$application->permanent_address_pincode,
                "correspondence_address" => "",
                "pincode" => $application->permanent_address_pincode,
                "full_name" => $application->name,
                "loan_type" => 2, // Education
                "no_of_advance_emis" => $merchant_collected_advance_amount ? $application->emi->advance_emi : 0,
                "loan_amount" => $net_loan_amount,
                "loan_tenure" => $net_tenure,
                "emi_start_date" => date('d-M-Y',strtotime($application->emi->emi_date)),
                "monthly_emi" => $application->emi->emi,
                "bank_account" => [
                    "ac_name" => $application->bank_details->name,
                    "ac_number" => $application->bank_details->account_number,
                    "ifsc_code" => $application->bank_details->ifsc_code
                ],
             /*   "disbursal_detail" => [
                    [
                        "date" => "26-Sep-2022",
                        "amount" => 93000,
                        "disbursal_type" => 0
                    ]
                ],*/
                "kyc" => $this->getKYC($aadhaarName, $aadhaarId, $isAadhaarVerified, $panVerified_using, $panName, $panId, $isPANVerified, $aadhaarVerified_using),
                "company_name" => "Company Name Not Present",
                "credit_score" => $application->creditReport[0]->Score,
                "fathers_name" => $application->application_element->father_name ?? "Father Name Not Present",
                "mothers_name" => "Mother Name Not Present",
                "date_of_birth" => date('d-M-Y',strtotime($application->dob)),
                "interest_rate" => $application->emi->annualised_interest, //$application->emi->interest_rate
                "mobile_number" => $application->mobile_number,
                "agreement_date" => $agreement_date,
                "monthly_income" => $application->monthly_income,
                "employment_type" => $application->employee_status == 'SALARIED' ? 1 : (in_array($application->employee_status, ['BUSINESS', 'Self Employed - Business']) ? 2 : ($application->employee_status == 'Self Employed - Professional' ? 3 : ($application->employee_status == 'UNEMPLOYED' ? 0 : 1))),
                "partner_loan_id" => 'CF'.$application->proFormaInvoice->loan_application_no,
                "repayment_count" => $net_tenure,
                "payment_frequency" => 3, //Monthly
                "execute_bre" => false,
                "institute_detail" => [
                    "brand_name" => $application->merchant->merchant_name,
                    "course_name" => $product_name,
                    "bank_account" => [
                        "ac_name" => $merchantBank['beneficiaryName'],
                        "ac_number" => $merchantBank['beneficiaryAccount'],
                        "ifsc_code" => $merchantBank['beneficiaryIFSC']
                    ],
                    "legal_entity_name" => $application->merchant->official_merchant_name
                ],
                "loan_application_date" => date('d-M-Y'),
                "agreement_signature_type" => $agreement_signature_type // 1: Physical 2: Aadhaar e-signature 3: Click wrap
        ];

        if($getCoAppDetails = $this->getCoAppDetails($application)) {
            $data["co_applicant_details"] = $getCoAppDetails;
        }

        if($is_update){

            $abb = FinBitData::where('application_id', $application->id)->sum('average_balance');

            $JMLoanBooking = JMLoanBooking::where('application_id', $application->id)->first(['id', 'created_at']);
            if (strtotime($application->emi->updated_at) > strtotime($JMLoanBooking->created_at)){
                $data["execute_bre"] = true;
            }

            $data['additional_variables'] = [
                /*"morat_emi_multiplier" => 0,
                "tranches" => [],
                "subvention" => 7,
                "fees_amount" => 100000,
                "gst_applicable" => false,
                "no_of_advance_emis" => 0,
                "flat_interest_borne_by_customer" => 0*/
                'average_bank_balance' => $abb,
                'foir' => $application->creditReport[0]->foirIncludingCFEMI
            ];
        }

        if($disbursalDetails = $this->getDisbursalDetails($application, $net_loan_amount, $agreement_date, $merchant_collected_advance_amount)){
            $data['disbursal_detail'] = $disbursalDetails;
        }

        return $data;
    }

    public function getDisbursalDetails($application, $net_loan_amount, $agreement_date, $merchant_collected_advance_amount){
        $lender = new LenderServices(new Request());
        $subvention = (new ConsumerApplicationController())->getSubventionDetails($application, false);

        $merchant_collected_upfront_from_customer = $lender->getPayloadValueByID($application->id, 'merchant_collected_upfront_from_customer');
        $net_loan_amount -= $subvention['WithGST'];
        $noOfAdvanceInstallments = $application->emi && $application->emi->advance_emi ? $application->emi->advance_emi : 0;
        if($net_loan_amount) {
            return [
                [
                    "date" => $agreement_date,
                    "amount" => $net_loan_amount,
                    "disbursal_type" => 0, //<principal/withhold> 0 - principal, 1 - withhold
                    //"processing_fee" => "<processing fee>",
                    //"pre_emi" => "<pre emi>",
                    //"gst" => "<GST on the processing fee collected>",
                    "subvention_gst" => round($subvention['GST']) ?? 0,
                    "subvention" => round($subvention['Net']) ?? 0,
                    "upfront_emi" => $merchant_collected_advance_amount ? $noOfAdvanceInstallments : 0,
                    "downpayment" => $merchant_collected_upfront_from_customer,
                    //"insurance" => "<Insurance, if any>"
                ]
            ];
        }

        return false;
    }

    public function getKYC($aadhaarName, $aadhaarId, $isAadhaarVerified, $panVerified_using, $panName, $panId, $isPANVerified, $aadhaarVerified_using){

        $kyc = [];
        if($aadhaarName && $aadhaarId) {
            array_push($kyc, [
                "kyc_name" => $aadhaarName,
                "kyc_type" => 1, //Aadhaar
                "identifier" => $aadhaarId,
                "is_verified" =>$isAadhaarVerified,
                "verified_using" => $aadhaarVerified_using
            ]);
        }

        if($panName && $panId){
            array_push($kyc, [
                "kyc_name" => $panName,
                "kyc_type" => 2, //PAN
                "identifier" => $panId,
                "is_verified" => $isPANVerified,
                "verified_using" => $panVerified_using
            ]);
        }

        return $kyc;
    }

    public function getCoAppDetails($application){

        if($application->co_applicant_name) {
            return [
                [
                    "co_dob" => date('d-M-Y', strtotime($application->co_applicant_dob)),
                    "co_email" => $application->co_applicant_email,
                    "co_phone" => $application->co_applicant_mobile_number,
                    "co_gender" => $application->co_applicant_gender == 'MALE' ? 1 : 2,
                    "co_aadhaar" => $application->co_applicant_aadhaar_card,
                    "co_address" => $application->co_applicant_address_line_1 . ' ' . $application->co_applicant_address_landmark . ' ' . $application->co_applicant_address_city . ' ' . $application->co_applicant_address_state . ', ' . $application->co_applicant_address_pincode,
                    "co_pancard" => $application->co_applicant_pan_card,
                    "co_pincode" => $application->co_applicant_address_pincode,
                    "co_relation" => 1,
                    "co_full_name" => $application->co_applicant_name,
                    "co_aadhaar_case_id" => "null"
                ]
            ];
        }

        return [];
    }

    public function getLoanStatus($wrapper = null)
    {
        return [];
    }

    public function updateLoan($wrapper = null)
    {
        return $this->createLoan($wrapper, true);
    }

    public function onboardingCompleted($wrapper = null)
    {
        return [];
    }

    public function disburseLoan($wrapper = null)
    {
        $lender = new LenderServices($this->request);
        $actual_disbursement_amt = $lender->getPayloadValueByID($this->request->get('id'), 'actual_disbursement_amt');
        $uniqueId = uniqid().time();

        return [
                "transaction_time" => date('d-M-Y, H:i:s'),
                "amount" => $actual_disbursement_amt,
                "transaction_id" => $uniqueId
            ];
    }

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

    public function repayment($wrapper = null)
    {
        $transaction = PaymentTransaction::where('id', $this->request->get('payment_id'))->first();

        $onlinePayment = OnlinePayment::where('payment_id', $transaction->trasanction_id)->first(['id', 'pay_id']);

        $payment_id = $transaction->trasanction_id;
        if (isset($onlinePayment->pay_id) && $onlinePayment->pay_id){
            $payment_id = $onlinePayment->pay_id;
        }
        $repayment = [
            "amount" => $transaction->amount,
            "payment_mode" => in_array($transaction->mode, ['NACH-LOTUS', 'nach', 'LotusPay']) ? 3 : ($transaction->mode == 'razorpay' ? 1 : $transaction->mode == 'Cheque' ? 4 : $transaction->mode == 'NEFT' ? 5 : in_array($transaction->mode, ['Cash', 'Cash | Pay']) ? 6 : $transaction->mode == 'Paytm' ? 7 : 21),
            "payment_date" => date('d-M-Y', strtotime($transaction->payment_date)),
            "payment_id" => $payment_id,
        ];

        if($transaction->payment_for == 'processing_fee'){
            $repayment = array_merge($repayment, [
                "is_foreclosure" => false,
                "is_cancelled" => false,
                "allocation" => $this->getAllocation($transaction)
            ]);
        }

        return $repayment;
    }

    public function getAllocation($transaction){

        $data = [];
        if($transaction->payment_for == 'processing_fee'){

            $id = \request()->has('id') ? \request()->get('id') : $this->request->get('id');

            $application = ConsumerApplication::where('id', $id)->first(['permanent_address_state', 'current_address_state']);

            $gstDetail = (new ConsumerDocument($this->request))->getGSTDetails(
                [
                    'amount' => $transaction->amount,
                    'state' => (isset($application->permanent_address_state) && !empty($application->permanent_address_state)) ? $application->permanent_address_state : (isset($application->current_address_state) && !empty($application->current_address_state) ? $application->current_address_state : '')
                ]
            );

            $pfNet = $gstDetail[0]['net_amount'];
            $pfGST = 0;
            foreach ($gstDetail as $item){
                $pfGST += $item['gst_amount'];
            }

            if ($pfGST){
                $data[] = [
                    "amount" => $pfGST,
                    "type" => 23 //23: Processing Fees Tax
                ];
            }

            if ($pfNet){
                $data[] = [
                    "amount" => $pfNet,
                    "type" => 22 //23: Processing Fee
                ];
            }
        }


        return $data;
    }

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

    public function mandate($wrapper = null)
    {

        $application = ConsumerApplication::with('checkmandate', 'bank_details', 'lender', 'emi')->where('id', Input::get('id'))->first(['name', 'lender_id', 'id', 'email', 'mobile_number']);

        if (!isset($application->checkmandate->id)){
            $error = new \stdClass();
            $error->description = 'Mandate is not active or created';
            $this->error = $error;
            return $this;
        }else if (((isset($application->bank_details->id)) && !$application->bank_details->account_type) || !isset($application->bank_details->id)){
            $error = new \stdClass();
            $error->description = 'Bank details is missing';
            $this->error = $error;
            return $this;
        }else if ($application->checkmandate->mandate_id != (Input::get('mandate_id') ?? $this->request->get('mandate_id'))){
            $error = new \stdClass();
            $error->description = 'Bank details is missing';
            $this->error = $error;
            return $this;
        }
        $jmBooking = JMLoanBooking::where('application_id', $application->id)->first(['loan_ac_no']);
        \request()->merge(['mandate_id' => $application->checkmandate->mandate_id]);
        $date_first_collection = $application->checkmandate->date_first_collection;
        if(!$date_first_collection){
            $date_first_collection = $application->emi->emi_date;
        }
        return [
            "name" => $application->name,
            "umrn" => $application->checkmandate->umrn,
            "email" => $application->email,
            "amount" => $application->checkmandate->mandate_amount,
            "mobile" => $application->mobile_number,
            "end_date" => date('Y-m-d', strtotime($application->checkmandate->expiry_date)),
            "auth_type" => "netbanking",
            "frequency" => "monthly",
            "ifsc_code" => $application->bank_details->ifsc_code,
            "debit_type" => "variable",
            "mandate_id" => $application->checkmandate->mandate_id,
            "start_date" => date('Y-m-d', strtotime($date_first_collection)),
            "customer_id" => $application->id,
            "account_type" => $application->bank_details->account_type,
            "account_number" => $application->bank_details->account_number,
            "loan_account_no" => $jmBooking->loan_ac_no,
            "mandate_account" => $application->lender->name,
            "registration_type" => "razorpay"
        ];
    }
}