<?php

namespace App\Method\OneFin\Payload;

use App\ABFLUTRUpdate;
use App\Avanse\Services\AvanseServices;
use App\CFPayoutDirectTransfer;
use App\CFPayoutRequestTransfer;
use App\CFPayoutRequestTransferStatus;
use App\ConsumerApplication;
use App\ConsumerApplicationElement;
use App\CSV;
use App\Http\Controllers\Admin\ConsumerApplicationController;
use App\Http\Controllers\Admin\ConsumerDocument;
use App\Http\Controllers\Admin\LenderServices;
use App\KYCDetails;
use App\Merchant;
use App\MerchantOffers;
use App\Method\OneFin\Helpers\OneFinHelper;
use App\OneFinService;
use App\PaymentTransaction;
use App\StatusLogs;
use Illuminate\Http\Request;
use App\Method\JM\Payload\Payload as JMPayload;

class Payload implements OneFinHelper
{

    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 createLoan($wrapper = null){

        $application = ConsumerApplication::with('creditReport','bank_details', 'emi', 'proFormaInvoice', 'merchant', 'application_element', 'merchant_bank_details', 'digital_sign')->where('id', $this->request->get('id'))->first();

        ConsumerApplication::isApplicantType(true);
        try {


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


            $partner_loan_id = $application->id;

            //$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;
//            }
//        }

            $net_tenure = $application->emi->remaining_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;
                                    }
                                }
                            }
                        }
                    }
                }
            }


            $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');

            if (!$isAadhaarVerified) {
                $isAadhaarVerified = true;
                $aadhaarName = str_replace(".", "", $application->name);
                $aadhaarId = substr($application->aadhaar_card, -4);
            }

            // Not using kyc from digio
            $isPANVerified = true;
            $panName = str_replace(".", "", $application->name);
            $panId = $application->pan_card;
            $panVerified_using = 2;

            $score = str_replace('.', '', $application->creditReport[0]->Score ?? 300);

            $payload = [
                "kyc" => $this->getKYC($aadhaarName, $aadhaarId, $isAadhaarVerified, $panVerified_using, $panName, $panId, $isPANVerified, $aadhaarVerified_using),
                "co_applicant_details" => $this->getCoApplicant($application),
                "email" => $application->email ?? 'info@creditfair.in',
                "gender" => $application->gender == 'MALE' ? 1 : 2,
                "source" => "Creditfair",
                "product" => $this->getProductName($application->lender_id, $application->purpose),
                "address" => $application->permanent_address_line_1 . ' ' . $application->permanent_address_landmark . ' ' . $application->permanent_address_city . ' ' . $application->permanent_address_state . ', ' . $application->permanent_address_pincode,
                "form_id" => "loan_booking_form",
                "pincode" => $application->permanent_address_pincode,
                "full_name" => str_replace(",", "", str_replace("_", "", str_replace("-", "", str_replace(".", "", $application->name)))),
                "loan_type" => 2,
                "loan_purpose" => $this->getPurpose($application->category->name),
                "execute_bre" => false,
                "loan_amount" => $application->approved_amount,
                "bank_account" => $this->getBankAccount($application),
                "company_name" => str_replace('\'', '' ,$application->company->company) ?? "Company Name Not Present",
                "credit_score" => !empty($score) ? $score : 300,
                "fathers_name" => $application->application_element->father_name && !in_array($application->application_element->father_name, ['.', ',']) ? str_replace(':', '', str_replace('.', '', $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)),
                "reducing_rate_input" => $application->emi->interest_rate == 0 ? 0 : round($application->emi->rate * 12, 2),
                "flat_rate_input_annualized" => 0,
                "interest_type" => 0,
                "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" => $partner_loan_id,
                "interest_rate" => $application->emi->interest_rate == 0 ? 0 : round($application->emi->rate * 12, 2),
                "repayment_count" => $net_tenure,
                "hold_amount" => round($application->application_element->hold_amount) ?? 0,
                "insurance_premium_applicable" => (bool)$application->proFormaInvoice->insurance_premium_applicable,
                "insurance_premium_amount" => round($application->proFormaInvoice->insurance_premium_amount) ?? 0,
                "insurance_premium_by_merchant" => (bool)$application->proFormaInvoice->insurance_premium_by_merchant,
                "fldg_applied" => (bool)$application->proFormaInvoice->fldg_applied,
                "institute_id" => $application->merchant_id,
                "institute_detail" => $this->getInstituteDetails($application, $merchantBank, $product_name),
                "payment_frequency" => 3,
                "no_of_advance_emis" => 0,
                "preferred_emi_date" => date('d', strtotime($application->emi->emi_date)),
                "loan_application_date" => date('d-M-Y', strtotime($application->created_at)),
                "correspondence_address" => $application->current_address_line_1 . ' ' . $application->current_address_city . ' ' . $application->current_address_state . ', ' . $application->current_address_pincode,
                "agreement_signature_type" => $agreement_signature_type,
                "emi_start_date" => date('d-M-Y', strtotime($application->emi->emi_date)),
            ];

            $subvention = (new ConsumerApplicationController())->getSubventionDetails($application, false);
            //$merchant_collected_upfront_from_customer = $lender->getPayloadValueByID($application->id, 'merchant_collected_upfront_from_customer');
            //$noOfAdvanceInstallments = $application->emi && $application->emi->advance_emi ? $application->emi->advance_emi : 0;

            $gstAmount = 0;
            if (isset($subvention['gstDetailsSubvention'])) {
                foreach ($subvention['gstDetailsSubvention'] as $gstDetailsSubvention) {
                    $gstAmount += round($gstDetailsSubvention['gst_amount'], 2);
                }
            }

            $net_loan_amount -= round($subvention['Net'], 2) + $gstAmount;

            if ($payload['insurance_premium_by_merchant'] && $payload['insurance_premium_amount']) {
                $net_loan_amount = $net_loan_amount - $payload['insurance_premium_amount'];
            }
            if ($payload['hold_amount']) {
                $net_loan_amount = $net_loan_amount - round($payload['hold_amount'], 2);
            }

            if ($disbursal_detail = $this->getDisbursalDetails($application, $net_loan_amount, $merchant)) {
                $payload['disbursal_detail'] = $disbursal_detail;
            }

            if (isset($subvention['gstDetailsSubvention'])) {
                foreach ($subvention['gstDetailsSubvention'] as $gstDetail) {
                    if ($gstDetail['taxes'] == 'CGST') {
                        $payload["subvention_cgst"] = round($gstDetail['gst_amount'], 2);
                    } else if ($gstDetail['taxes'] == 'SGST') {
                        $payload["subvention_sgst"] = round($gstDetail['gst_amount'], 2);
                    } else if ($gstDetail['taxes'] == 'IGST') {
                        $payload["subvention_igst"] = round($gstDetail['gst_amount'], 2);
                    }
                }
            }
            if (!isset($payload["subvention_igst"])) {
                $payload["subvention_igst"] = 0;
            }
            if (!isset($payload["subvention_cgst"])) {
                $payload["subvention_cgst"] = 0;
            }
            if (!isset($payload["subvention_sgst"])) {
                $payload["subvention_sgst"] = 0;
            }

            $payload["subvention_amount_gst"] = $gstAmount ?? 0;
            $payload["subvention_amount"] = round($subvention['Net'], 2) ?? 0;

//            if(isset($payload['disbursal_detail']['subvention_gst_applicable']) && !$payload['disbursal_detail']['subvention_gst_applicable'] && $payload["subvention_amount_gst"]){
//                $payload['disbursal_detail']['subvention_gst_applicable'] = true;
//            }

            if (isset($payload['disbursal_detail']) && isset($payload['disbursal_detail'][0]['subvention_gst_applicable']) && !$payload['disbursal_detail'][0]['subvention_gst_applicable']) {
                $payload['advance_interest'] = $payload["subvention_amount_gst"] + $payload["subvention_amount"];
                $payload["subvention_amount_gst"] = 0;
                $payload["subvention_amount"] = 0;
                $payload["subvention_cgst"] = 0;
                $payload["subvention_sgst"] = 0;
                $payload["subvention_igst"] = 0;
            } else {
                $payload['advance_interest'] = 0;
            }

            return $payload;
        }catch (\Exception $e){
            $p = $e;
        }

    }

    public function getProductName($lender_id, $type){
        if($this->request->get('product_code')){
            return $this->request->get('product_code');
        }

        return OneFinService::canSendToOnefin($lender_id, $type);
    }

    public function onBoardChannelEntity($wrapper = null){

        return [
            "email" => $this->request->get('email'),
            "address" => $this->request->get('address'),
            "brand_name" => $this->request->get('merchant_name'),
            "channel_id" => $this->request->get('channel_id'),//"CODE_1234",
            "gst_number" => $this->request->get('gst_number'),
            "pan_number" => $this->request->get('pan_number'),
            "entity_name" => $this->request->get('official_merchant_name'),
            "channel_type" => $this->request->get('channel_type'),//"CENTER/ANCHOR/PARTNER/INSTITUTE",
            "mobile_number" => $this->request->get('mobile_number'),
            //"master_channel_id" => $this->request->get('master_channel_id'),//"9cd6fe4f-1ea8-4cb3-8446-138ab413c93e",
            "bank_account" => $this->getBankDetails()
        ];
    }

    private function getBankDetails(){
        return [
            [
                "ac_number" => $this->request->get('ac_number'),
                "ac_name" => str_replace('\'', '', $this->request->get('ac_name')),
                "account_type" => $this->request->get('account_type'),//"PRIMARY/SECONDARY/SAVINGS/CURRENT",
                "ifsc_code" => $this->request->get('ifsc_code')
            ]
        ];
    }

    private function getInstituteDetails($application, $merchantBank, $product_name){
        return [
            "brand_name" => $application->merchant->merchant_name,
            "course_name" => str_replace('\'', '', $product_name),
            "bank_account" => [
                "ac_name" => $merchantBank['beneficiaryName'],
                "ac_number" => $merchantBank['beneficiaryAccount'],
                "ifsc_code" => $merchantBank['beneficiaryIFSC']
            ],
            "legal_entity_name" => $application->merchant->official_merchant_name
        ];
    }

    private function getDisbursalDetails($application, $net_loan_amount, $offer){


        if ($application && $application->emi && $application->emi->processing_fee > 0) {
            if (isset($application->proFormaInvoice->processing_fee_by_merchant)) {
                if ($application->proFormaInvoice->processing_fee_by_merchant == 0) {
                    $proforma_pf = 0;
                } else if ($application->proFormaInvoice->processing_fee_by_merchant == 1) {
                    $proforma_pf = 1;
                }
            }

            $is_collected_by_merchant = $proforma_pf ?? ((isset($application->merchant->is_processing_fees) && $application->merchant->is_processing_fees == 1) ? $application->merchant->is_processing_fees : 0);
        }

        $fee_type  = 'paid_to_lender';
        if($offer->processing_fee_first_emi){
            $fee_type = 'paid_in_emi';
        }elseif(isset($is_collected_by_merchant) && $is_collected_by_merchant){
            $fee_type = 'paid_to_merchant';
            $net_loan_amount -= $application->emi->processing_fee;
        }

        $downpayment_collected_by_merchant = (bool)$application->proFormaInvoice && !$application->proFormaInvoice->merchant_collected_advance_amount;
        if($downpayment_collected_by_merchant){
            $net_loan_amount -= $application->emi->upfront_from_customer;
        }

        if($net_loan_amount) {
            return [
                [
                    "date" => date('d-M-Y'),
                    "amount" => round($net_loan_amount),
                    "downpayment" => $application->emi->upfront_from_customer,
                    "downpayment_collected_by_merchant" => $downpayment_collected_by_merchant,
                    "upfront_emi" => 0,
                    "processing_fee" => $application->emi->processing_fee,
                    "subvention_on_approved_loan" => !(isset($application->merchant->charge_subvention_remaining_amount) && $application->merchant->charge_subvention_remaining_amount),
                    "subvention_percent" => $offer->subvention,
                    "subvention_gst_applicable" => (isset($application->merchant->is_gst) && $application->merchant->is_gst == 1) ? true : false,
                    "document_charges" => 0,
                    "document_charges_gst" => 0,
                    "processing_fee_type" =>$fee_type
                ]
            ];
        }

        return [];
    }

    private function getCoApplicant($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" => str_replace('\'', '', $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,
                    "partner_applicant_id" => $application->id
                ]
            ];
        }

        return [];
    }

    private function getBankAccount($application){
        return [
            "ac_name" => $application->bank_details->name,
            "ac_number" => $application->bank_details->account_number,
            "ifsc_code" => $application->bank_details->ifsc_code
        ];
    }

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

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

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

        return $kyc;
    }

    private function getPurpose($category){
        $data = [
            "Others" => [
                    "Jewelry",
                    "Electronic Products",
                    "Other",
                    "SME",
                    "Tours, Travels and Holidays"
        ],
          "Edtech" => [
                    "Education",
                    "Entrance prep",
                    "K12 Coaching",
                    "K12 Edtech",
                    "K12 Education",
                    "Upskilling Edtech"
                ],
          "Green Energy" => [
                    "Electronic Battery",
                    "Electronic Vehicles",
                    "LSP - Green Energy \u0026 Education",
                    "Solar and Rooftop Solutions",
                    "Electronic Battery",
                    "Electronic Vehicles",
                    "LSP - Green Energy \u0026 Education",
                    "Solar and Rooftop Solutions"
                ],
          "Healthcare" => [
                    "Cosmetics",
                    "Dental Care",
                    "Equipment Financing",
                    "IVF and Fertility Treatments",
                    "Multispeciality Treatments",
                    "Stemcell banking and treatment"
                ],
          "Home Decor" => [
                    "Home Automation",
                    "Home Downpayment",
                    "Loose Furniture",
                    "Modular Kitchen, wardrobes and Interior",
                    "Painting Services",
                    "Water Purifier",
                    "Home Automation",
                    "Home Downpayment",
                    "Loose Furniture",
                    "Modular Kitchen, wardrobes and Interior",
                    "Painting Services",
                    "Water Purifier"
                ],
          "Personal Loan" => [
                    "Personal Loan"
                ],
          "RBF" => [
                    "Revenue Based Financing",
                    "Strategic partnerships & Alliances (Co-lending)"
                ]
        ];


        $_mainCategory = $category;
        foreach($data as $mainCategory => $item){
            if(in_array($category, $item)){
                $_mainCategory =  $mainCategory;
                break;
            }
        }

        return $_mainCategory;
    }

    public function loanDisbursal($wrapper = null)
    {
        $statusLogs = StatusLogs::where('application_id', $this->request->get('id'))->where('status', 'disbursed')->orderBy('created_at', 'desc')->first(['id', 'application_id', 'created_at']);
        $applicationElement = ConsumerApplicationElement::where('application_id', $this->request->get('id'))->first(['reference_number']);

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

        $referenceNumber = '';
        if(isset($applicationElement->reference_number) && $applicationElement->reference_number) {
            $referenceNumber = $applicationElement->reference_number;
        }else {
            $_payoutStatus = CFPayoutDirectTransfer::where('application_id', $this->request->get('id'))->whereNotNull('utr')->get(['utr']);
            foreach ($_payoutStatus as $payoutStatus) {
                if (isset($payoutStatus->utr) && strlen($payoutStatus->utr)) {
                    $referenceNumber = $payoutStatus->utr;
                    break;
                }
            }
            if(empty($referenceNumber)) {
                $ABFLUTRUpdate = ABFLUTRUpdate::where('account_id', $this->request->get('id'))->whereNotNull('utr')->first(['utr']);
                if (isset($ABFLUTRUpdate->utr) && strlen($ABFLUTRUpdate->utr)) {
                    $referenceNumber = $ABFLUTRUpdate->utr;
                }
            }
        }

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



        return [
            "transaction_time" => date('d-M-Y h:i:s', strtotime($statusLogs->created_at)),
            "amount" => $this->getNetAmount($this->request->get('id')),
            "transaction_id" => $referenceNumber
        ];
    }

    public function postLoanRepayment($wrapper = null)
    {
        if ($this->request->has('transaction_id')){
            $transaction = PaymentTransaction::where('id', $this->request->get('transaction_id'))->first();
        }else{
            $transaction = PaymentTransaction::where('application_id', $this->request->get('id'))->whereIn('payment_for', ['processing_fee'])->first();
        }

        if (!isset($transaction->id)){
            $error = new \stdClass();
            $error->description = 'Processing Fee is missing';
            $this->error = $error;
            return $this;
        }

        $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" => $transaction->trasanction_id,
            "is_foreclosure" => false,
            "is_cancelled" => false
        ];

        if (!$this->request->has('transaction_id')){
            $repayment["allocation"] = $this->getAllocation($transaction);
        }

        return $repayment;
    }

    public function getAllocation($transaction){

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

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

            $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 getRepaymentSchedule($wrapper = null)
    {
        return [];
    }

    public function createMandate($wrapper = null)
    {
        $application = ConsumerApplication::with('checkmandate', 'bank_details', 'lender', 'emi')->where('id', $this->request->get('id'))->first(['id', 'lender_id', 'name', 'email', 'mobile_number']);
        $element = ConsumerApplicationElement::where('application_id', $this->request->get('id'))->first(['onefin_id']);

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

        if(isset($element->onefin_id) && $element->onefin_id) {
            return [
                "name" => $application->bank_details->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->mandate->expiry_date)),
                "auth_type" => "netbanking",
                "frequency" => "monthly",
                "ifsc_code" => $application->bank_details->ifsc_code,
                "debit_type" => "variable",
                "mandate_id" => !empty($application->checkmandate->mandate_id) ? $application->checkmandate->mandate_id : 'NotFound',
                "start_date" => date('Y-m-d', strtotime($application->checkmandate->date_first_collection)) ?? date('Y-m-d', strtotime($application->emi->emi_date)),
                "customer_id" => $application->id,
                "account_type" => "savings",
                "account_number" => $application->bank_details->account_number,
                "loan_account_no" => $element->onefin_id,
                "mandate_account" => $application->lender->name,
                "registration_type" => "lotuspay"
            ];
        }
        return [];
    }


    public function getNetAmount($id){

        $application = ConsumerApplication::with('emi', 'proFormaInvoice', 'merchant')->where('id', $id)->first();

        $net_loan_amount = $application->approved_amount;

        $payload["insurance_premium_by_merchant"] = (bool)$application->proFormaInvoice->insurance_premium_by_merchant;
        $payload["hold_amount"] = round($application->application_element->hold_amount) ?? 0;

        $subvention = (new ConsumerApplicationController())->getSubventionDetails($application, false);
        $gstAmount = 0;
        if (isset($subvention['gstDetailsSubvention'])) {
            foreach ($subvention['gstDetailsSubvention'] as $gstDetailsSubvention) {
                $gstAmount += round($gstDetailsSubvention['gst_amount'], 2);
            }
        }

        $net_loan_amount -= round($subvention['Net'], 2) + $gstAmount;

        if ($payload['insurance_premium_by_merchant'] && $payload['insurance_premium_amount']) {
            $net_loan_amount = $net_loan_amount - $payload['insurance_premium_amount'];
        }
        if ($payload['hold_amount']) {
            $net_loan_amount = $net_loan_amount - round($payload['hold_amount'], 2);
        }

        if ($application && $application->emi && $application->emi->processing_fee > 0) {
            $is_collected_by_merchant = $proforma_pf ?? ((isset($application->merchant->is_processing_fees) && $application->merchant->is_processing_fees == 1) ? $application->merchant->is_processing_fees : 0);
        }

        if(isset($is_collected_by_merchant) && $is_collected_by_merchant){
            $net_loan_amount -= $application->emi->processing_fee;
        }

        $downpayment_collected_by_merchant = (bool)$application->proFormaInvoice && !$application->proFormaInvoice->merchant_collected_advance_amount;
        if($downpayment_collected_by_merchant){
            $net_loan_amount -= $application->emi->upfront_from_customer;
        }

        return $net_loan_amount;
    }
}
