<?php

namespace App\Http\Controllers;


use App\ApplicationEMICalculation;
use App\Avanse\Processes\AvanseProcesses;
use App\Avanse\Services\AvanseServices;
use App\Bank;
use App\BNPL;
use App\CampaignsJobProvider;
use App\Capri;
use App\Centers;
use App\Company;
use App\ConsumerApplication;
use App\ConsumerApplicationElement;
use App\ConsumerApplicationFiles;
use App\DocumentDetails;
use App\EMICalculation;
use App\EmiPayment;
use App\Events\V1\EventMandateWebhook;
use App\Events\V1\EventVendorWebhook;
use App\Console\Commands\VendorWebhook;
use App\Http\Controllers\Admin\ConsumerApplicationController;
use App\Http\Controllers\WebhookController;
use App\Http\Controllers\Admin\ConsumerDocument;
use App\Http\Controllers\Admin\Dashboard;
use App\KMGP2P;
use App\JMService\JMServices;
use App\LendBox;
use App\LendBoxLSP;
use App\LoanManagement;
use App\Mandate;
use App\MandateLogs;
use App\MandateRequestLogs;
use App\MandateStatusLog;
use App\Merchant;
use App\MerchantLocation;
use App\MerchantOffers;
use App\OCRRecognition;
use App\PaymentEmi;
use App\PaymentTransaction;
use App\PWAApplicationForm;
use App\ScoreCard;
use App\Slack;
use App\TATLogs;
use App\User;
use App\WebHookLog;
use Hashids\Hashids;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\Process\Process;
use App\ABFL\Services\Services;
use Symfony\Component\Process\Exception\ProcessFailedException;
use App\StatusLogs;
use App\Logging\CloudWatchLoggerFactory;
class NachController extends Controller
{
    private $request;
    public $until_cancelled = 0;
    /**
     * @var bool
     */
    public $retry_nach = false;
    /**
     * @var string
     */
    public $error_message = false;
    public $app_type = 1;

    public function createMandate($application_id, $variant, $frequency = null){
        $url = "";

        $consumer_data = ConsumerApplication::with('bank_details', 'bank_details_multiple', 'emi','proFormaInvoice')->where('id', $application_id)->first();

        $frequencyPreserve = $frequency;
        $isCollectingPF = 0;
        if ($this->isCollectionWithProcessingFee($consumer_data)){
            $frequency = 'ADHO';
            $isCollectingPF = 1;
        }

        if ($frequency == null || $frequency == "") {
            $frequencies = ['MNTH', 'ADHO'];
        } elseif ($frequency == 'monthly') {
            $frequencies = ['MNTH'];
        } else {
            $frequencies = ['ADHO'];
        }

//        if($variant == "emandate"){
//            $frequencies = ['ADHO'];
//        }
        $lotuspayurl = _env('LOTUSPAYBASEURL', '');
        if($consumer_data->lender_id == 1) {
            $utility_code = 'NACH00000000021321';//_env('LOTUSPAY_UTILITYCODE', '');
            $secretKey = _env('LOTUSPAYSECRETKEY', '');
        } else if($consumer_data->lender_id == ConsumerApplication::AVANSE_LENDER_ID) {
            $utility_code = _env('LOTUSPAY_UTILITYCODE_AV', '');
            $secretKey = _env('LOTUSPAYSECRETKEY_AV', '');
        } else if($consumer_data->lender_id == Capri::$lender_id) {
            $utility_code = _env('LOTUSPAYUTILITY_CAPRI', '');
            $secretKey = _env('LOTUSPAYSECRETKEY_CAPRI', '');
        } else if($consumer_data->lender_id == Services::$lender_id) {
            $utility_code = _env('LOTUSPAYUTILITY_ABFL', '');
            $secretKey = _env('LOTUSPAYSECRETKEY_ABFL', '');
        } else if($consumer_data->lender_id == LendBox::$lender_id || $consumer_data->lender_id == LendBoxLSP::$lender_id) {
            $utility_code = _env('LOTUSPAYUTILITY_LENDBOX', '');
            $secretKey = _env('LOTUSPAYSECRETKEY_LENDBOX', '');
        } else if($consumer_data->lender_id == JMServices::$lender_id) {
            $utility_code = _env('LOTUSPAYUTILITY_JMFL', '');
            $secretKey = _env('LOTUSPAYSECRETKEY_JMFL', '');
        } else{
            $utility_code = 'NACH00000000021321';//_env('LOTUSPAY_UTILITYCODE_KM', '');
            $secretKey = _env('LOTUSPAYSECRETKEY_KM', '');
        }

        $emandate_variant = $variant;
        $variant = $variant == 'emandate_esign' || $variant == 'emandate_api' ? 'emandate' : $variant;

        if($consumer_data->emi == null){
            return json_encode(array("status"=>"Error","message" => "EMI is not generated yet"));
        }

        if (isset($consumer_data->id) && isset($consumer_data->bank_details_multiple[0]->id) && isset($consumer_data->emi->emi_date) && $consumer_data->emi->emi_date != '') {
            foreach ($frequencies as $frequency){
                //$mandate = Mandate::where('consumer_application_id', $application_id)->where('status', '!=', 0)->first();
                $nach_debit = array();
                if($this->app_type == 2){
                    foreach($consumer_data->bank_details_multiple as $value){
                        if($value->applicant_type == 2){
                            $nach_debit['debtor_account_name'] = (isset($value->name) && $value->name != '') ? $value->name : $consumer_data->co_applicant_name;
                            $nach_debit['debtor_account_number'] = (isset($value->account_number) && $value->account_number != '') ? $value->account_number : "";

                            if ($variant != "emandate") {
                                $nach_debit['account_type'] = (isset($value->account_type) && $value->account_type != '') ? $value->account_type : "savings";
                            } else {
                                $nach_debit['debtor_account_type'] = (isset($value->account_type) && $value->account_type != '') ? $value->account_type : "savings";
                            }

                            if($variant == "emandate" && (isset($value->bank_name) && $value->bank_name != '' && strtolower($value->bank_name) == 'hdfc bank')){
                                if($frequency == 'ADHO') {
                                    $nach_debit['category_code'] = 'U099';
                                }else if($frequency == 'MNTH'){
                                    $nach_debit['category_code'] = 'L001';
                                }
                            }
                            if($variant == "emandate" && $emandate_variant != 'emandate_esign') {
                                $nach_debit['debtor_agent_code'] = $value->bank_ifsc_code ?? $value->ifsc_code;
                            }else{
                                $nach_debit['debtor_agent_mmbid'] = (isset($value->ifsc_code) && $value->ifsc_code != '') ? $value->ifsc_code : "";
                            }
                        }
                    }
                }else {
                    $nach_debit['debtor_account_name'] = (isset($consumer_data->bank_details->name) && $consumer_data->bank_details->name != '') ? $consumer_data->bank_details->name : $consumer_data->name;
                    $nach_debit['debtor_account_number'] = (isset($consumer_data->bank_details->account_number) && $consumer_data->bank_details->account_number != '') ? $consumer_data->bank_details->account_number : "";

                    if ($variant != "emandate") {
                        $nach_debit['account_type'] = (isset($consumer_data->bank_details->account_type) && $consumer_data->bank_details->account_type != '') ? $consumer_data->bank_details->account_type : "savings";
                    } else {
                        $nach_debit['debtor_account_type'] = (isset($consumer_data->bank_details->account_type) && $consumer_data->bank_details->account_type != '') ? $consumer_data->bank_details->account_type : "savings";
                    }
                    if($variant == "emandate" && (isset($consumer_data->bank_details->bank_name) && $consumer_data->bank_details->bank_name != '' && strtolower($consumer_data->bank_details->bank_name) == 'hdfc bank')){
                        if($frequency == 'ADHO') {
                            $nach_debit['category_code'] = 'U099';
                        }else if($frequency == 'MNTH'){
                            $nach_debit['category_code'] = 'L001';
                        }
                    }
                    $ifsc = substr($consumer_data->bank_details->ifsc_code, 0, 4);
                    if($variant == "emandate" && $emandate_variant != 'emandate_esign') {
                        $nach_debit['debtor_agent_code'] = isset($consumer_data->bank_details->bank_ifsc_code) && !empty($consumer_data->bank_details->bank_ifsc_code) ? $consumer_data->bank_details->bank_ifsc_code : $ifsc;
                    }else{
                        $nach_debit['debtor_agent_mmbid'] = (isset($consumer_data->bank_details->ifsc_code) && $consumer_data->bank_details->ifsc_code != '') ? $consumer_data->bank_details->ifsc_code : "";
                    }
                }
                $nach_debit['frequency'] = $frequency;

                // $nach_debit['date_first_collection'] = (isset($consumer_data->emi->emi_date) && $consumer_data->emi->emi_date != '') ? date('Y-m-d', strtotime($consumer_data->emi->emi_date)) : "";
                $nach_debit['date_first_collection'] = Carbon::now()->toDateString();
                if (BNPL::is($consumer_data->merchant_id)){
                    $nach_debit['date_first_collection'] = Carbon::now()->addDay(1)->toDateString();
                }
                if($variant == "emandate" || $frequency == 'MNTH') {
                    if ((isset($consumer_data->emi->remaining_emi) && $consumer_data->emi->remaining_emi != '' && $consumer_data->emi->remaining_emi != 0)) {
                        $nach_debit['date_final_collection'] = date('Y-m-d', strtotime("+" . ($consumer_data->emi->remaining_emi - 1) . " months", strtotime($consumer_data->emi->emi_date)));
                    }
                }
                $last_emi_date = date('Y-m-d', strtotime("+" . ($consumer_data->emi->remaining_emi - 1) . " months", strtotime($consumer_data->emi->emi_date)));
                $first_emi_date = (isset($consumer_data->emi->emi_date) && $consumer_data->emi->emi_date != '') ? date('Y-m-d', strtotime($consumer_data->emi->emi_date)) : "";
                $last_emi_plus_36_months = date('Y-m-d', strtotime("+36 months", strtotime($last_emi_date)));
                $first_emi_plus_360_months = date('Y-m-d', strtotime("+360 months", strtotime($first_emi_date)));
                if($variant == "emandate" && isset($nach_debit['date_final_collection'])){
                    $nach_debit['date_final_collection'] = date('Y-m-d', strtotime("+15 days", strtotime($nach_debit['date_final_collection'])));
                }

                $final_date_collection_until_calcelled = min($last_emi_plus_36_months,$first_emi_plus_360_months);
                if($this->until_cancelled){
                    $nach_debit['date_final_collection'] = $final_date_collection_until_calcelled;
                }



                if( $variant != "emandate" || $emandate_variant == 'emandate_esign') {
                    if (isset($consumer_data->proFormaInvoice->loan_application_no) && !empty($consumer_data->proFormaInvoice->loan_application_no)) {
                        $nach_debit['reference1'] = $consumer_data->proFormaInvoice->loan_application_no;
                    } else {
                        $nach_debit['reference1'] = '';
                    }
                }

                if ($frequency == 'MNTH') {
                    $nach_debit['amount_collection'] = $this->getEMIAmount($consumer_data) * 100;
                }
                if ($frequency == 'ADHO') {
                    $approved_amount = $this->getNetAmount($consumer_data);
                    if($approved_amount > 5000000){
                        $approved_amount = 5000000;
                    }

                    if($isCollectingPF && $frequencyPreserve == 'monthly'){
                        $approved_amount = $this->getEMIAmount($consumer_data);
                    }

                    $nach_debit['amount_maximum'] = $approved_amount * 100;
                }

                if($this->retry_nach) {
                    if (isset($nach_debit['amount_collection'])) {
                        $nach_debit['amount_collection'] = 100000 * 100;
                    } else {
                        $nach_debit['amount_maximum'] = 100000 * 100;
                    }
                }

                if($variant == "emandate") {
                    $nach_debit['creditor_agent_code'] = "ICIC";
                    $nach_debit['creditor_utility_code'] = $utility_code;
                }else{
                    $nach_debit['nach_sponsor_bank'] = "HDFC";
                }


                if($consumer_data->lender_id == Services::$lender_id) {
                    $nach_debit['creditor_agent_code'] = "INDB";
                }

//                    if($variant == "emandate"){
//                        $extra_amount = $consumer_data->emi->emi * (15/100);
//                        if($extra_amount < 1000){
//                            $extra_amount = 1000;
//                        }
//                        $nach_debit['maximum_amount'] = $consumer_data->emi->emi + $extra_amount;
//                    }
                if($consumer_data->lender_id == ConsumerApplication::AVANSE_LENDER_ID) {
                    $nach_debit['creditor_agent_code'] = "UTIB";
                }
                $nach_debit['variant'] = $variant == 'emandate' ? 'emandate_api' : $variant;
                if ($emandate_variant == 'emandate_esign'){
                    $nach_debit['variant'] = 'emandate_esign';
                }

                if ($nach_debit['debtor_account_name'] == "" || $nach_debit['debtor_account_number'] == "" || (isset($nach_debit['debtor_agent_mmbid']) && $nach_debit['debtor_agent_mmbid'] == "") || (isset($nach_debit['debtor_agent_code']) && $nach_debit['debtor_agent_code'] == "") ) {
                    return json_encode(array("error" => 'Data missing for Bank'));
                }
                if ($nach_debit['date_first_collection'] == "" || $nach_debit['date_first_collection'] == '1970-01-01') {
                    return json_encode(array("error" => 'Data missing for EMI'));
                }

                $owner = array();
                if($this->app_type == 2){
                    $owner['email'] = $consumer_data->co_applicant_email;
                    $owner['mobile'] = $consumer_data->co_applicant_mobile_number;

                    $nach_debit['debtor_email'] = $owner['email'];
                    $nach_debit['debtor_mobile'] = $owner['mobile'];
                }else {
                    $owner['email'] = $consumer_data->email;
                    $owner['mobile'] = $consumer_data->mobile_number;

                    $nach_debit['debtor_email'] = $owner['email'];
                    $nach_debit['debtor_mobile'] = $owner['mobile'];
                }

                $mandateModel = $this->createSystemMandate(new \stdClass(), $application_id, $frequency, $nach_debit, $variant);

                $hashids         = new Hashids('Creditfair by CS', 20);
                $transaction_id = $hashids->encode($mandateModel->id);
                if (request()->has('redirect') && request()->get('redirect') == 'esign') {
                    $url = array();
                    $url['return_url'] = asset('esign/'. $hashids->encode($application_id).'?type='.request()->get('type').'&mandate_setup=complete');
                    $payload = json_encode(array("type" => "nach_debit", "redirect" => $url, "nach_debit" => $nach_debit,'metadata' => ['transaction_id' => $transaction_id]));
                } else {
                    $payload = json_encode(array("type" => "nach_debit", "nach_debit" => $nach_debit,'metadata' => ['transaction_id' => $transaction_id]));
                }
                \Log::info($payload);
                //$lotuspayurl = "https://api.lotuspay.com/v1/sources/";
                //$lotuspayurl = "https://test.lotuspay.com/v1/sources/";
                $lotuspayurl_mandate = $lotuspayurl."sources/";
                \Log::info($lotuspayurl_mandate);
                $curl = curl_init();
                try {
                    curl_setopt_array($curl, array(
                        CURLOPT_URL => $lotuspayurl_mandate,
                        CURLOPT_RETURNTRANSFER => true,
                        CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
                        //CURLOPT_USERPWD => "$secretKey",
                        CURLOPT_USERPWD => $secretKey,
                        CURLOPT_ENCODING => "",
                        CURLOPT_MAXREDIRS => 10,
                        CURLOPT_TIMEOUT => 30,
                        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                        CURLOPT_CUSTOMREQUEST => "POST",
                        CURLOPT_POSTFIELDS => $payload,
                        CURLOPT_HTTPHEADER => array(
                            "Content-Type: application/json",
                        ),
                    ));
                } catch (\Exception $e) {
                    return json_encode(array("error" => 'Something went wrong, Please try again'));
                }


                $response = json_decode(curl_exec($curl));
                //(new Slack(new Request(['title' => 'NACH Issue Log', 'fields' => ['res' => json_encode($response), 'req' => $payload], 'group' => Slack::$STAGE_TESTING])))->send();
                MandateRequestLogs::insert([
                    'application_id' => $application_id,
                    'error_type' => (isset($response->error->param) && $response->error->param) ? $response->error->param : ((isset($response->error->type) && $response->error->type) ? $response->error->type : ''),
                    'request' => json_encode($response),
                    'response' => $payload,
                    'is_retry' => $this->retry_nach ? 1 : 0,
                    'created_by' => Auth::check() ? Auth::user()->id : ($consumer_data->user_id ?? 107),
                    'created_at' => Carbon::now()->toDateTimeString(),
                ]);
                \Log::info($response);
                $err = curl_error($curl);
                \Log::info($err);
                curl_close($curl);
                if ($err) {
                    echo "cURL Error #:" . $err;
                } else {
                    if (isset($response->error)) {
                        return json_encode(array("error" => $response));
                    }
                    $responsedata = ($response);

                    if($variant == "emandate" && isset($responsedata->redirect->url) && $responsedata->redirect->url != ""){
                        $url = $responsedata->redirect->url;
                        if(isset($mandateModel)) {
                            $_mandateModel = Mandate::find($mandateModel->id);
                            $_mandateModel->mandate_url = $url;
                            $_mandateModel->date_first_collection = isset($nach_debit['date_first_collection']) ? $nach_debit['date_first_collection'] : '';
                            $_mandateModel->save();
                        }
                    }

                    if($variant == 'physical' && isset($mandateModel)){
                        $file_name = "lotus_pay_".$mandateModel->mode."_".$frequency;
                        $this->getPrefilledNach($responsedata->mandate,$secretKey,$application_id,$file_name,$lotuspayurl);
                    }
//                        if ($frequency == 'MNTH' || $variant == "emandate") {
//                            $this->createSubcription($application_id, $mandateModel, $consumer_data);
//                        }
                }
            }
            $this->until_cancelled = 0;
            return json_encode(array("status"=>"Success","message" => "Mandate created Successfully","url"=>$url));
        }else{
            return json_encode(array("status"=>"Error","message" => "Customer Details Missing","url"=>$url));
        }
    }

    public function createMandateFromTransbnk($application_id, $variant, $frequency = null){
        $url = "";

        $consumer_data = ConsumerApplication::with('bank_details', 'bank_details_multiple', 'emi','proFormaInvoice')->where('id', $application_id)->first();

        $frequencyPreserve = $frequency;
        $isCollectingPF = 0;
        if ($this->isCollectionWithProcessingFee($consumer_data)){
            $frequency = 'ADHO';
            $isCollectingPF = 1;
        }

        // if ($frequency == null || $frequency == "") {
        //     $frequencies = ['MNTH', 'ADHO'];
        // } elseif ($frequency == 'monthly') {
        //     $frequencies = ['MNTH'];
        // } else {
        //     $frequencies = ['ADHO'];
        // }
        $frequencies = [$frequency];

        // $utility_code = 'NACH00000000062574';

        $emandate_variant = $variant;
        $variant = $variant == 'emandate_esign' || $variant == 'emandate_api' ? 'emandate' : $variant;

        if($consumer_data->emi == null){
            return json_encode(array("status"=>"Error","message" => "EMI is not generated yet"));
        }

        if (isset($consumer_data->id) && isset($consumer_data->bank_details_multiple[0]->id) && isset($consumer_data->emi->emi_date) && $consumer_data->emi->emi_date != '') {
            foreach ($frequencies as $frequency){
                //$mandate = Mandate::where('consumer_application_id', $application_id)->where('status', '!=', 0)->first();
                $nach_debit = array();
                if($this->app_type == 2){
                    foreach($consumer_data->bank_details_multiple as $value){
                        if($value->applicant_type == 2){
                            $nach_debit['debtor_account_name'] = (isset($value->name) && $value->name != '') ? $value->name : $consumer_data->co_applicant_name;
                            $nach_debit['debtor_account_number'] = (isset($value->account_number) && $value->account_number != '') ? $value->account_number : "";

                            if ($variant != "emandate") {
                                $nach_debit['account_type'] = (isset($value->account_type) && $value->account_type != '') ? $value->account_type : "savings";
                            } else {
                                $nach_debit['debtor_account_type'] = (isset($value->account_type) && $value->account_type != '') ? $value->account_type : "savings";
                            }

                            if($variant == "emandate" && (isset($value->bank_name) && $value->bank_name != '')){
                                if($frequency == 'ADHO') {
                                    $nach_debit['category_code'] = 'S001';
                                }else if($frequency == 'MNTH'){
                                    $nach_debit['category_code'] = 'L001';
                                }
                            }
                            if($variant == "emandate" && $emandate_variant != 'emandate_esign') {
                                $nach_debit['debtor_agent_code'] = $value->bank_ifsc_code ?? $value->ifsc_code;
                            }else{
                                $nach_debit['debtor_agent_mmbid'] = (isset($value->ifsc_code) && $value->ifsc_code != '') ? $value->ifsc_code : "";
                            }
                        }
                    }
                }else {
                    $nach_debit['debtor_account_name'] = (isset($consumer_data->bank_details->name) && $consumer_data->bank_details->name != '') ? $consumer_data->bank_details->name : $consumer_data->name;
                    $nach_debit['debtor_account_number'] = (isset($consumer_data->bank_details->account_number) && $consumer_data->bank_details->account_number != '') ? $consumer_data->bank_details->account_number : "";
                    $nach_debit['debtor_ifsc'] = (isset($consumer_data->bank_details->ifsc_code) && $consumer_data->bank_details->ifsc_code != '') ? $consumer_data->bank_details->ifsc_code : "";

                    if ($variant != "emandate") {
                        $nach_debit['account_type'] = (isset($consumer_data->bank_details->account_type) && $consumer_data->bank_details->account_type != '') ? $consumer_data->bank_details->account_type : "savings";
                    } else {
                        $nach_debit['debtor_account_type'] = (isset($consumer_data->bank_details->account_type) && $consumer_data->bank_details->account_type != '') ? $consumer_data->bank_details->account_type : "savings";
                    }
                    if($variant == "emandate" && (isset($consumer_data->bank_details->bank_name) && $consumer_data->bank_details->bank_name != '')){
                        if($frequency == 'ADHO') {
                            $nach_debit['category_code'] = 'S001';
                        }else if($frequency == 'MNTH'){
                            $nach_debit['category_code'] = 'L001';
                        }
                    }
                    $ifsc = substr($consumer_data->bank_details->ifsc_code, 0, 4);
                    if($variant == "emandate" && $emandate_variant != 'emandate_esign') {
                        $nach_debit['debtor_agent_code'] = isset($consumer_data->bank_details->bank_ifsc_code) && !empty($consumer_data->bank_details->bank_ifsc_code) ? $consumer_data->bank_details->bank_ifsc_code : $ifsc;
                    }else{
                        $nach_debit['debtor_agent_mmbid'] = (isset($consumer_data->bank_details->ifsc_code) && $consumer_data->bank_details->ifsc_code != '') ? $consumer_data->bank_details->ifsc_code : "";
                    }
                }
                $nach_debit['frequency'] = $frequency;

                $nach_debit['date_first_collection'] = (isset($consumer_data->emi->emi_date) && $consumer_data->emi->emi_date != '') ? date('Y-m-d', strtotime($consumer_data->emi->emi_date)) : "";
                if (BNPL::is($consumer_data->merchant_id)){
                    $nach_debit['date_first_collection'] = Carbon::now()->addDay(1)->toDateString();
                }
                if($variant == "emandate" || $frequency == 'MNTH') {
                    if ((isset($consumer_data->emi->remaining_emi) && $consumer_data->emi->remaining_emi != '' && $consumer_data->emi->remaining_emi != 0)) {
                        $nach_debit['date_final_collection'] = date('Y-m-d', strtotime("+" . ($consumer_data->emi->remaining_emi - 1) . " months", strtotime($consumer_data->emi->emi_date)));
                    }
                }
                $last_emi_date = date('Y-m-d', strtotime("+" . ($consumer_data->emi->remaining_emi - 1) . " months", strtotime($consumer_data->emi->emi_date)));
                $first_emi_date = (isset($consumer_data->emi->emi_date) && $consumer_data->emi->emi_date != '') ? date('Y-m-d', strtotime($consumer_data->emi->emi_date)) : "";
                $last_emi_plus_36_months = date('Y-m-d', strtotime("+36 months", strtotime($last_emi_date)));
                $first_emi_plus_360_months = date('Y-m-d', strtotime("+360 months", strtotime($first_emi_date)));
                if($variant == "emandate" && isset($nach_debit['date_final_collection'])){
                    $nach_debit['date_final_collection'] = date('Y-m-d', strtotime("+15 days", strtotime($nach_debit['date_final_collection'])));
                }

                $final_date_collection_until_calcelled = min($last_emi_plus_36_months,$first_emi_plus_360_months);
                if($this->until_cancelled){
                    $nach_debit['date_final_collection'] = $final_date_collection_until_calcelled;
                }

                // if( $variant != "emandate" || $emandate_variant == 'emandate_esign') {
                    if (isset($consumer_data->proFormaInvoice->loan_application_no) && !empty($consumer_data->proFormaInvoice->loan_application_no)) {
                        $nach_debit['reference1'] = $consumer_data->proFormaInvoice->loan_application_no;
                    } else {
                        $nach_debit['reference1'] = '';
                    }
                // }

                if ($frequency == 'MNTH') {
                    $nach_debit['amount_collection1'] = $this->getEMIAmount($consumer_data);
                    $nach_debit['debit_type'] = 'FIXED_AMOUNT';
                }
                if ($frequency == 'ADHO') {
                    $approved_amount = $this->getNetAmount($consumer_data);
                    if($approved_amount > 5000000){
                        $approved_amount = 5000000;
                    }

                    // if($isCollectingPF && $frequencyPreserve == 'monthly'){
                    //     $approved_amount = $this->getEMIAmount($consumer_data);
                    // }

                    $nach_debit['amount_maximum1'] = $approved_amount;
                    $nach_debit['debit_type'] = 'MAXIMUM_AMOUNT';
                }

                // if($this->retry_nach) {
                //     if (isset($nach_debit['amount_collection1'])) {
                //         $nach_debit['amount_collection1'] = 100000;
                //     } else {
                //         $nach_debit['amount_maximum1'] = 100000;
                //     }
                // }
                $nach_debit['emandate_amount'] = $nach_debit['amount_maximum1'] ?? $nach_debit['amount_collection1'];

                $nach_debit['variant'] = $variant == 'emandate' ? 'emandate_api' : $variant;
                if ($emandate_variant == 'emandate_esign'){
                    $nach_debit['variant'] = 'emandate_esign';
                }

                if ($nach_debit['debtor_account_name'] == "" || $nach_debit['debtor_account_number'] == "" || (isset($nach_debit['debtor_agent_mmbid']) && $nach_debit['debtor_agent_mmbid'] == "") || (isset($nach_debit['debtor_agent_code']) && $nach_debit['debtor_agent_code'] == "") ) {
                    return json_encode(array("error" => 'Data missing for Bank'));
                }
                if ($nach_debit['date_first_collection'] == "" || $nach_debit['date_first_collection'] == '1970-01-01') {
                    return json_encode(array("error" => 'Data missing for EMI'));
                }

                // $owner = array();

                if($this->app_type == 2){
                    $nach_debit['debtor_email'] = $consumer_data->co_applicant_email;
                    $nach_debit['debtor_mobile'] = $consumer_data->co_applicant_mobile_number;
                }else {
                    $nach_debit['debtor_email'] = $consumer_data->email;
                    $nach_debit['debtor_mobile'] = $consumer_data->mobile_number;
                }
                $nach_debit['mode'] = 'transbnk_enach';
                $nach_debit['date_first_collection'] = $nach_debit['date_first_collection']."T00:00:00Z";

                $mandateModel = $this->createSystemMandate(new \stdClass(), $application_id, $frequency, $nach_debit, $variant);

                $hashids         = new Hashids('Creditfair by CS', 20);
                $transaction_id = $hashids->encode($mandateModel->id);

                $payload = json_encode(array(
                    "user" => _env('TRANSBNK_USER'),
                    "password" => _env('TRANSBNK_PASS'),
                    "entityId" => "0d761b84-96ce-46de-9533-ba51b2d5a856",
                    "programId" => "42",
                    "external1RefId"=> $transaction_id,
                    "applicationNo"=> $application_id,
                    "bankIfsc"=> $nach_debit['debtor_ifsc'],
                    "authType"=> 0,
                    "categoryCode"=> $nach_debit['category_code'],
                    "sequenceType"=> "RCUR",
                    "frequency"=> $nach_debit['frequency'],
                    "firstCollectionDate"=> $nach_debit['date_first_collection'],
                    "collectionUnitCancel"=> $this->until_cancelled,
                    "debitType"=> $nach_debit['debit_type'],
                    "principalAmount"=> $nach_debit['emandate_amount'],
                    "collectionAmount"=> $consumer_data->emi->emi,
                    "customerReferenceNo"=> $nach_debit['reference1'],
                    "customerName"=> $consumer_data->name,
                    "customerEmail"=> $consumer_data->email,
                    "customerMobileDialingCode"=> "91",
                    "customerMobile"=> $consumer_data->mobile_number,
                    "accountHolderName"=> $nach_debit['debtor_account_name'],
                    "accountNumber"=> $nach_debit['debtor_account_number'],
                    "accountType"=> strtoupper($nach_debit['debtor_account_type'])
                ));

                $curl = curl_init();
                try {
                    curl_setopt_array($curl, array(
                        CURLOPT_URL => _env('TRANSBNK_URL'),
                        CURLOPT_RETURNTRANSFER => true,
                        CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
                        CURLOPT_ENCODING => "",
                        CURLOPT_MAXREDIRS => 10,
                        CURLOPT_TIMEOUT => 30,
                        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                        CURLOPT_CUSTOMREQUEST => "POST",
                        CURLOPT_POSTFIELDS => $payload,
                        CURLOPT_HTTPHEADER => array(
                            "Content-Type: application/json",
                            "X-Client-ID: NACH0000000000000005",
                            "Authorization: Bearer "._env('TRANSBNK_AUTH'),
                            "x-api-key: "._env('TRANSBNK_X_API_KEY')
                        ),
                    ));
                } catch (\Exception $e) {
                    (new Slack(new Request(['title' => 'Mandate Access Error', 'fields' => ['error' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()], 'group' => Slack::$STAGE_TESTING])))->send();
                }


                $response = json_decode(curl_exec($curl));
                // dd($response);
                (new Slack(new Request(['title' => 'NACH Issue Log', 'fields' => ['res' => json_encode($response), 'req' => $payload], 'group' => Slack::$STAGE_TESTING])))->send();
                MandateRequestLogs::insert([
                    'application_id' => $application_id,
                    'error_type' => (isset($response->errorMessage) && $response->errorMessage) ? $response->errorMessage : ((isset($response) && !isset($response->id)) ? json_encode($response) : ''),
                    'request' => $payload,
                    'response' => json_encode($response),
                    'is_retry' => $this->retry_nach ? 1 : 0,
                    'created_by' => Auth::check() ? Auth::user()->id : ($consumer_data->user_id ?? 107),
                    'created_at' => Carbon::now()->toDateTimeString(),
                ]);
                \Log::info($response);
                $err = curl_error($curl);
                \Log::info($err);
                curl_close($curl);
                if ($err) {
                    echo "cURL Error #:" . $err;
                } else {
                    if (isset($response->error)) {
                        return json_encode(array("error" => $response));
                    }
                    $responsedata = ($response);

                    if($variant == "emandate" && isset($responsedata->customerUrl) && $responsedata->customerUrl != ""){
                        $url = $responsedata->customerUrl;
                        if(isset($mandateModel)) {
                            $_mandateModel = Mandate::find($mandateModel->id);
                            $_mandateModel->mandate_url = $url;
                            $_mandateModel->date_first_collection = isset($nach_debit['date_first_collection']) ? $nach_debit['date_first_collection'] : '';
                            $_mandateModel->save();
                        }
                    }
                }
            }
            $this->until_cancelled = 0;
            return json_encode(array("status"=>"Success","message" => "Mandate created Successfully","url"=>$url));
        }else{
            return json_encode(array("status"=>"Error","message" => "Customer Details Missing","url"=>$url));
        }
    }

    public function getTransbnkWebhookInfo(Request $request){

        $responsedata = $request->all();

        try {
            $updatewebhook = new WebHookLog();
            $updatewebhook->vendor = "Transbnk";
            $updatewebhook->data = json_encode($responsedata);
            $updatewebhook->save();
            if ($responsedata) {
                $mandate_status = $responsedata['status'];
                $mandate_umrn = $responsedata['umrn'] ?? "";
                $mandate_id = $responsedata['id'];
                // $mandateData = Mandate::where('mandate_id', $mandate_id)->first();
                if(isset($responsedata['external1RefId'])) {
                    $hashids = new Hashids('Creditfair by CS', 20);
                    $_transaction_id = $hashids->decode($responsedata['external1RefId']);

                    $mandateData = Mandate::where('id', $_transaction_id[0])->first();
                }
                if(isset($mandateData->id)) {
                    if (!empty($mandate_umrn)) {
                        Mandate::where('id', $mandateData->id)->update(['umrn' => $mandate_umrn, 'status' => $mandate_status]);
                    } else {
                        Mandate::where('id', $mandateData->id)->update(['status' => $mandate_status]);
                    }

                    if (!$mandateData->mandate_id){
                        Mandate::where('id', $mandateData->id)->update(['mandate_id' => $mandate_id]);
                    }

                    if (isset($mandateData->consumer_application_id)) {
                        TATLogs::insert(['action' => 'e-nach completed', '_id' => $mandateData->consumer_application_id, 'id_type' => 'application_id', 'user_id' => 107, 'created_at' => Carbon::now()->toDateTimeString()]);
                    }
                }

                if (isset($mandateData->id)) {

                    (new ConsumerApplicationController())->webhook($mandateData->consumer_application_id, ['type' => 'NACH-Webhook','status' => $mandate_status]);
                    try{
                        $vendorWebhook = new VendorWebhook();
                        $payload = (new ConsumerApplicationController())->vendorWebhook($mandateData->consumer_application_id, ['type' => 'NACH-Webhook','status' => $mandate_status, 'data' => []]);
                        if (isset($payload)) {
                            $vendorWebhook->handle('NACH-Webhook', $payload);
                        }
                    } catch (\Exception $e){
                        $cwFactory = new CloudWatchLoggerFactory();
                        $cwFactory->logger(json_encode(['message' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()]));
                    }

                    MandateStatusLog::insert([
                        'mandate_id' => $mandateData->id,
                        'user_id' => 107,
                        'status' => $mandate_status,
                        'reason' => 'Transbnk Auto Update',
                        'created_at' => Carbon::now()->toDateTimeString()
                    ]);
                    $hashids = new Hashids('Creditfair by CS', 20);
                    $_app_type = 1;
                    // if (isset($responsedata->data->metadata->app_type)) {
                    //     $_app_type = $hashids->decode($responsedata->data->metadata->app_type);
                    // }
                    if(in_array($mandate_status, ['COMPLETED'])) {
                        $this->generateTransbnkMandateDocument($mandateData->consumer_application_id, $mandateData, $mandate_status, $mandate_umrn, $_app_type);
                    }
                }
            }
        }catch (\Exception $e){
            (new \App\Slack(new Request(['title'=>'Transbnk Webhook Error','fields'=>['error'=>$e->getMessage(),'line'=>$e->getLine(),'trace'=>$e->getTraceAsString()], 'group' => Slack::$STAGE_TESTING])))->send();
        }

        // $request->request->add(['job' => 1]);
        // $payloadData['request'] = $request->input();

        // $payload[] = [
        //     'payload' => json_encode($payloadData),
        //     'from' => 'transbnk_webhook_job',
        //     'application_id' => 181,
        //     'available_at' => Carbon::now()->toDateTimeString(),
        //     'created_at' => Carbon::now()->toDateTimeString()
        // ];

        // CampaignsJobProvider::insert($payload);

        try{
            $cwFactory = new CloudWatchLoggerFactory();
            $cwFactory->logger(json_encode(['application_id'=>$mandateData->consumer_application_id,'vendor'=>'transbnk enach','requestData' => $request->all()]));
        }catch(\Exception $e){
            (new \App\Slack(new Request(['title'=>'Transbnk Web hook Res 0','application_id'=>$mandateData->consumer_application_id,'fields'=>['response'=> json_encode($request->all())], 'group' => Slack::$STAGE_TESTING])))->send();
        }

        return json_encode(array("status"=>"success"));
    }

    public function generateTransbnkMandateDocument($id, $mandateModel, $mandateStatus = '', $mandate_umrn = '', $app_type = ''){
        try{
            $application = ConsumerApplication::with('bank_details', 'bank_details_multiple','lender')->where('id',$id)->first(['name','lender_id','id']);
            // if($mandateModel->mode == 'lotuspay_emandate') {

            //     $emi = ApplicationEMICalculation::where('application_id', $id)->first(['emi_date']);

                // if($application->lender_id == 1) {
                //     $utility_code = 'NACH00000000019187';
                // }elseif($application->lender_id == AvanseServices::$lender_id) {
                //     $utility_code = _env('LOTUSPAY_UTILITYCODE_AV');
                // }elseif($application->lender_id == Services::$lender_id) {
                //     $utility_code = _env('LOTUSPAYUTILITY_ABFL');
                // }elseif($application->lender_id == LendBox::$lender_id || $application->lender_id == LendBoxLSP::$lender_id) {
                //     $utility_code = _env('LOTUSPAYUTILITY_LENDBOX');
                // }else{
                //     $utility_code = 'NACH00000000021321';
                // }
                if($application->lender_id == KMGP2P::$lender_id){
                    $utility_code = 'NACH00000000062574';
                }

                if($app_type == 2){
                    foreach($application->bank_details_multiple as $value){
                        if($value->applicant_type == 2){
                            $ifsc = substr($value->ifsc_code, 0, 4);
                            $debtor_account_name = (isset($value->name) && $value->name != '') ? $value->name : $application->co_applicant_name;
                            $debtor_account_type = (isset($value->account_type) && $value->account_type != '') ? $value->account_type : 'savings';
                            $debtor_account_ifsc_code = (isset($value->ifsc_code) && $value->ifsc_code != '') ? $value->ifsc_code : '';
                            $debtor_account_number = (isset($value->account_number) && $value->account_number != '') ? $value->account_number : '';
                            $debtor_agent_code = (isset($value->bank_ifsc_code) && $value->bank_ifsc_code != '') ? $value->bank_ifsc_code : $ifsc;
                        }
                    }
                }else {
                    $ifsc = substr($application->bank_details->ifsc_code, 0, 4);
                    $debtor_account_name = (isset($application->bank_details->name) && $application->bank_details->name != '') ? $application->bank_details->name : $application->name;
                    $debtor_account_type = (isset($application->bank_details->account_type) && $application->bank_details->account_type != '') ? $application->bank_details->account_type : 'savings';
                    $debtor_account_ifsc_code = (isset($application->bank_details->ifsc_code) && $application->bank_details->ifsc_code != '') ? $application->bank_details->ifsc_code : '';
                    $debtor_account_number = (isset($application->bank_details->account_number) && $application->bank_details->account_number != '') ? $application->bank_details->account_number : '';
                    $debtor_agent_code = (isset($application->bank_details->bank_ifsc_code) && $application->bank_details->bank_ifsc_code != '') ? $application->bank_details->bank_ifsc_code : $ifsc;
                }
                $lender_name = $application->lender->name ?? '';
                $lender_id = $application->lender_id ?? '';

                $mandateArr = [
                    'name' => $debtor_account_name,
                    'mandate' => !empty($mandate_umrn) ? $mandate_umrn : $mandateModel->umrn,
                    'status' => $mandateStatus,
                    'date_submitted' => $mandateModel->created_at,
                    'amount_maximum' => $mandateModel->mandate_amount,
                    'creditor_agent_name' => 'YESB',
                    'creditor_name' => $lender_name,
                    'creditor_utility_code' => $utility_code ?? '',
                    'date_first_collection' => $mandateModel->date_first_collection ?? $emi->emi_date,
                    'date_final_collection' => $mandateModel->expiry_date,
                    'debtor_account_name' => $debtor_account_name,
                    'debtor_account_type' => $debtor_account_type,
                    'debtor_account_ifsc_code' => $debtor_account_ifsc_code,
                    'debtor_agent_code' => $debtor_agent_code,
                    'avanse_lan' => AvanseProcesses::getLANNumber($id),
                    'debtor_account_number' => $debtor_account_number,
                    'lender_id' => $lender_id
                ];

                $view = view('admin.consumer-application.mandate_document', ['data' => $mandateArr]);

                $pdf = App::make('snappy.pdf.wrapper');
                $emandateFileName = 'e-mandate';
                if($mandateStatus == 'acknowledged'){
                    $emandateFileName = 'e-mandate-'.$mandateStatus;
                }
                $file_id = (new ConsumerDocument(new Request()))->uploadToS3($emandateFileName, $id, $pdf->loadHTML($view)->output());
                (new ConsumerDocument((new Request())))->saveDocumentDetails($id, $file_id, 'MANDATE', $mandateArr);
            // }
        }catch (\Exception $e){
            (new Slack(new Request(['title'=>'Transbnk Document Failed','fields'=>['error'=>$e->getMessage(),'line'=>$e->getLine(),'trace'=>$e->getTraceAsString()], 'group' => Slack::$STAGE_TESTING])))->send();
        }
    }

    public function getNetAmount($consumer_data){
        return $consumer_data->approved_amount - $consumer_data->emi->upfront_from_customer;
    }

    public function getNetAmountV1($consumer_data){
        $upfront_from_customer = !empty($consumer_data->emi) ? $consumer_data->emi->upfront_from_customer : 0;
        return $consumer_data->approved_amount - $upfront_from_customer;
    }

    public function getEMIAmount($application){
        $offer = MerchantOffers::where('id', $application->emi->offer_id)->first(['processing_fee_first_emi']);
        if (isset($offer->processing_fee_first_emi) && $offer->processing_fee_first_emi && isset($application->emi->processing_fee) && $application->emi->processing_fee && $this->isProcessingApplicable($application->id)) {
            return $application->emi->emi + $application->emi->processing_fee;
        }
        return $application->emi->emi;
    }

    public function isCollectionWithProcessingFee($application){
        $offer = MerchantOffers::where('id', $application->emi->offer_id)->first(['processing_fee_first_emi']);
        if (isset($offer->processing_fee_first_emi) && $offer->processing_fee_first_emi && isset($application->emi->processing_fee) && $application->emi->processing_fee && $this->isProcessingApplicable($application->id)) {
            return $application->emi->processing_fee;
        }
        return false;
    }

    public function updateMetadata($application_id, $finance_ref_id){

        try {
            $consumer_data = ConsumerApplication::where('id', $application_id)->first();
            $mandates = Mandate::where('consumer_application_id', $application_id)->whereNotNull('umrn')->where('umrn', '!=', '0')->get(['id','mandate_id']);

            if ($mandates) {
                foreach ($mandates as $mandate) {
                    if (isset($mandate->mandate_id) && $mandate->mandate_id) {
                        $this->updateMandateByID($finance_ref_id, $mandate, $consumer_data);
                    }
                }
            }
        }catch (\Exception $e){
            (new \App\Slack(new Request(['title'=>'Lotus Pay Mandate Update Error','fields'=>['error'=>$e->getMessage(),'line'=>$e->getLine(),'trace'=>$e->getTraceAsString()], 'group' => Slack::$STAGE_TESTING])))->send();
        }
    }

    public function updateMandateByID($finance_ref_id, $mandate, $consumer_data){
        $hashids         = new Hashids('Creditfair by CS', 20);
        $payload['metadata']['finance_ref_id'] = $finance_ref_id;
        $payload['metadata']['transaction_id'] = $hashids->encode($mandate->id);
//        $payload['metadata']['app_type'] = $mandate->applicant_type;

        $lotuspayurl = _env('LOTUSPAYBASEURL', '');
        if($consumer_data->lender_id == 1) {
            $secretKey = _env('LOTUSPAYSECRETKEY', '');
        } else if($consumer_data->lender_id == ConsumerApplication::AVANSE_LENDER_ID) {
            $secretKey = _env('LOTUSPAYSECRETKEY_AV', '');
        } else if($consumer_data->lender_id == Capri::$lender_id) {
            $secretKey = _env('LOTUSPAYSECRETKEY_CAPRI', '');
        } else{
            $secretKey = _env('LOTUSPAYSECRETKEY_KM', '');
        }


        $curl = curl_init();

        try {
            curl_setopt_array($curl, array(
                CURLOPT_URL => $lotuspayurl."mandates/".$mandate->mandate_id."/update",
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
                CURLOPT_USERPWD => $secretKey,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "PATCH",
                CURLOPT_POSTFIELDS => json_encode($payload),
                CURLOPT_HTTPHEADER => array(
                    "Content-Type: application/json",
                ),
            ));
            $response = json_decode(curl_exec($curl));
            if ($response){
                //(new Slack(new Request(['title'=>'Lotus Pay Mandate Update res 2','fields'=>['res'=> json_encode($response)], 'group' => Slack::$STAGE_TESTING])))->send();
            }
            $err = curl_error($curl);
            if ($err){
                (new Slack(new Request(['title'=>'Lotus Pay Mandate Update Error 2','fields'=>['error'=> $err], 'group' => Slack::$STAGE_TESTING])))->send();
            }
            curl_close($curl);
        } catch (\Exception $e) {
            (new Slack(new Request(['title'=>'Lotus Pay Mandate Update Error 1','fields'=>['error'=>$e->getMessage(),'line'=>$e->getLine(),'trace'=>$e->getTraceAsString()], 'group' => Slack::$STAGE_TESTING])))->send();
            return json_encode(array("error" => 'Something went wrong, Please try again'));
        }
    }

    public function isProcessingApplicable($application_id){
        $emiPayment = PaymentTransaction::where('application_id', $application_id)->where('payment_for','processing_fee')->whereNull('is_deleted_at')->first(['id']);
        if (!isset($emiPayment->id)){
            return true;
        }
        return false;
    }

    public function createMandateV1($application_id, $variant, $frequency = null){
        $url = "";
        if ($frequency == null || $frequency == "") {
            $frequencies = ['MNTH', 'ADHO'];
        } elseif ($frequency == 'monthly') {
            $frequencies = ['MNTH'];
        } else {
            $frequencies = ['ADHO'];
        }

//        if($variant == "emandate"){
//            $frequencies = ['ADHO'];
//        }
        $consumer_data = ConsumerApplication::with('bank_details', 'emi','proFormaInvoice')->where('id', $application_id)->first();
        $lotuspayurl = _env('LOTUSPAYBASEURL', '');
        if($consumer_data->lender_id == 1) {
            $secretKey = _env('LOTUSPAYSECRETKEY', '');
        } else if($consumer_data->lender_id == ConsumerApplication::AVANSE_LENDER_ID) {
            $secretKey = _env('LOTUSPAYSECRETKEY_AV', '');
        } else if($consumer_data->lender_id == Capri::$lender_id) {
            $secretKey = _env('LOTUSPAYSECRETKEY_CAPRI', '');
        } else{
            $secretKey = _env('LOTUSPAYSECRETKEY_KM', '');
        }

        if($consumer_data->emi == null){
            return json_encode(array("status"=>"Error","message" => "EMI is not generated yet"));
        }

        if (isset($consumer_data->id) && isset($consumer_data->bank_details->id) && isset($consumer_data->emi->emi_date) && $consumer_data->emi->emi_date != '') {
            foreach ($frequencies as $frequency){
                //$mandate = Mandate::where('consumer_application_id', $application_id)->where('status', '!=', 0)->first();
                $nach_debit = array();
                $nach_debit['debtor_account_name'] = (isset($consumer_data->bank_details->name) && $consumer_data->bank_details->name != '') ? $consumer_data->bank_details->name : $consumer_data->name;
                $nach_debit['debtor_account_number'] = (isset($consumer_data->bank_details->account_number) && $consumer_data->bank_details->account_number != '') ? $consumer_data->bank_details->account_number : "";
                if($variant != "emandate") {
                    $nach_debit['account_type'] = (isset($consumer_data->bank_details->account_type) && $consumer_data->bank_details->account_type != '') ? $consumer_data->bank_details->account_type : "savings";
                }else{
                    $nach_debit['debtor_account_type'] = (isset($consumer_data->bank_details->account_type) && $consumer_data->bank_details->account_type != '') ? $consumer_data->bank_details->account_type : "savings";
                }
                $nach_debit['frequency'] = $frequency;
                $nach_debit['date_first_collection'] = (isset($consumer_data->emi->emi_date) && $consumer_data->emi->emi_date != '') ? date('Y-m-d', strtotime($consumer_data->emi->emi_date)) : "";
                if($variant == "emandate" || $frequency == 'MNTH') {
                    if ((isset($consumer_data->emi->remaining_emi) && $consumer_data->emi->remaining_emi != '' && $consumer_data->emi->remaining_emi != 0)) {
                        $nach_debit['date_final_collection'] = date('Y-m-d', strtotime("+" . ($consumer_data->emi->remaining_emi - 1) . " months", strtotime($consumer_data->emi->emi_date)));
                    }
                }

                if($variant == "emandate" && isset($nach_debit['date_final_collection'])){
                    $nach_debit['date_final_collection'] = date('Y-m-d', strtotime("+15 days", strtotime($nach_debit['date_final_collection'])));
                }

                if($this->until_cancelled){
                    $nach_debit['date_final_collection'] = '';
                }

                if($variant == "emandate") {
                    $nach_debit['debtor_agent_code'] = $consumer_data->bank_details->bank_ifsc_code;
                }else{
                    $nach_debit['debtor_agent_mmbid'] = (isset($consumer_data->bank_details->ifsc_code) && $consumer_data->bank_details->ifsc_code != '') ? $consumer_data->bank_details->ifsc_code : "";
                }
                if( $variant != "emandate") {
                    if (isset($consumer_data->proFormaInvoice->loan_application_no) && !empty($consumer_data->proFormaInvoice->loan_application_no)) {
                        $nach_debit['reference1'] = $consumer_data->proFormaInvoice->loan_application_no;
                    } else {
                        $nach_debit['reference1'] = '';
                    }
                }
                if ($frequency == 'MNTH') {
                    $nach_debit['amount_collection'] = $this->getEMIAmount($consumer_data) * 100;
                }
                if ($frequency == 'ADHO') {
                    $nach_debit['amount_maximum'] = $this->getNetAmount($consumer_data) * 100;
                }
                if($variant == "emandate") {
                    $nach_debit['creditor_agent_code'] = "YESB";
                }else{
                    $nach_debit['nach_sponsor_bank'] = "HDFC";
                }
//                    if($variant == "emandate"){
//                        $extra_amount = $consumer_data->emi->emi * (15/100);
//                        if($extra_amount < 1000){
//                            $extra_amount = 1000;
//                        }
//                        $nach_debit['maximum_amount'] = $consumer_data->emi->emi + $extra_amount;
//                    }
                $nach_debit['variant'] = $variant == 'emandate' ? 'emandate_api' : $variant;

                if ($nach_debit['debtor_account_name'] == "" || $nach_debit['debtor_account_number'] == "" || (isset($nach_debit['debtor_agent_mmbid']) && $nach_debit['debtor_agent_mmbid'] == "") || (isset($nach_debit['debtor_agent_code']) && $nach_debit['debtor_agent_code'] == "") ) {
                    return json_encode(array("error" => 'Data missing for Bank'));
                }
                if ($nach_debit['date_first_collection'] == "" || $nach_debit['date_first_collection'] == '1970-01-01') {
                    return json_encode(array("error" => 'Data missing for EMI'));
                }

                $owner = array();
                $owner['email'] = $consumer_data->email;
                $owner['mobile'] = $consumer_data->mobile_number;

                $nach_debit['debtor_email'] = $owner['email'];
                $nach_debit['debtor_mobile'] = $owner['mobile'];


                $mandateModel = $this->createSystemMandate(new \stdClass(), $application_id, $frequency, $nach_debit, $variant);

                $hashids         = new Hashids('Creditfair by CS', 20);
                $transaction_id = $hashids->encode($mandateModel->id);
                $payload = json_encode(array("type" => "nach_debit", "nach_debit" => $nach_debit, "owner" => $owner,'metadata' => ['transaction_id' => $transaction_id]));
                //$lotuspayurl = "https://api.lotuspay.com/v1/sources/";
                //$lotuspayurl = "https://test.lotuspay.com/v1/sources/";
                $lotuspayurl_mandate = $lotuspayurl."sources/";
                $curl = curl_init();
                try {
                    curl_setopt_array($curl, array(
                        CURLOPT_URL => $lotuspayurl_mandate,
                        CURLOPT_RETURNTRANSFER => true,
                        CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
                        //CURLOPT_USERPWD => "$secretKey",
                        CURLOPT_USERPWD => $secretKey,
                        CURLOPT_ENCODING => "",
                        CURLOPT_MAXREDIRS => 10,
                        CURLOPT_TIMEOUT => 30,
                        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                        CURLOPT_CUSTOMREQUEST => "POST",
                        CURLOPT_POSTFIELDS => $payload,
                        CURLOPT_HTTPHEADER => array(
                            "Content-Type: application/json",
                        ),
                    ));
                } catch (\Exception $e) {
                    return json_encode(array("error" => 'Something went wrong, Please try again'));
                }

                $response = json_decode(curl_exec($curl));
                $err = curl_error($curl);
                curl_close($curl);
                if ($err) {
                    echo "cURL Error #:" . $err;
                } else {
                    if (isset($response->error)) {
                        return json_encode(array("error" => $response));
                    }
                    $responsedata = ($response);

                    if($variant == "emandate" && isset($responsedata->redirect->url) && $responsedata->redirect->url != ""){
                        $url = $responsedata->redirect->url;
                        if(isset($mandateModel)) {
                            $_mandateModel = Mandate::find($mandateModel->id);
                            $_mandateModel->mandate_url = $url;
                            $_mandateModel->save();
                        }
                    }

                    if($variant == 'physical' && isset($mandateModel)){
                        $file_name = "lotus_pay_".$mandateModel->mode."_".$frequency;
                        $this->getPrefilledNach($responsedata->mandate,$secretKey,$application_id,$file_name,$lotuspayurl);
                    }
//                        if ($frequency == 'MNTH' || $variant == "emandate") {
//                            $this->createSubcription($application_id, $mandateModel, $consumer_data);
//                        }
                }
            }
            $this->until_cancelled = 0;
            return json_encode(array("status"=>"Success","message" => "Mandate created Successfully","url"=>$url));
        }else{
            return json_encode(array("status"=>"Error","message" => "Customer Details Missing","url"=>$url));
        }
    }

    public function createSystemMandate($responsedata, $application_id, $frequency, $nach_debit, $variant){
        $mandateModel = new Mandate();
        $mandateModel->consumer_application_id = $application_id;
        $mandateModel->mandate_id = isset($responsedata->mandate) ? $responsedata->mandate : '';
        $mandateModel->action = "N";
        if ($frequency == 'MNTH') {
            $mandateModel->frequency = "M";
            $mandateModel->mandate_amount = $nach_debit['amount_collection1'] ?? ($nach_debit['amount_collection'])/100;
            $mandateModel->monthly_frequency = 0;
        }
        if ($frequency == 'ADHO') {
            $mandateModel->frequency = "O";
            $mandateModel->mandate_amount = $nach_debit['amount_maximum1'] ?? ($nach_debit['amount_maximum'])/100;
            $mandateModel->monthly_frequency = 1;
        }
        $mandateModel->collection = ($mandateModel->frequency == "M") ? "M" : "N";
        $mandateModel->status = "inactive";

        if($nach_debit['date_final_collection']){
            $mandateModel->expiry_date = $nach_debit['date_final_collection'];
        }else{
            $mandateModel->until_cancelled = $this->until_cancelled;
        }

        $mandateModel->mode = $nach_debit['mode'] ?? "lotuspay_".$variant;
        if($variant == "emandate" && isset($responsedata->redirect->url) && $responsedata->redirect->url != ""){
            $url = $responsedata->redirect->url;
        }
        $mandateModel->mandate_url = isset($url) ? $url : '';
        $mandateModel->mandate_id = isset($responsedata->mandate) ? $responsedata->mandate : '';
        $mandateModel->save();

        return $mandateModel;
    }

    public function callLotusPaySettlementAPI($data){

        $lotuspayurl = _env('LOTUSPAYBASEURL', '');
        if($data['lender_id'] == 1) {
            $secretKey = _env('LOTUSPAYSECRETKEY', '');
        } else if($data['lender_id'] == ConsumerApplication::AVANSE_LENDER_ID) {
            $secretKey = _env('LOTUSPAYSECRETKEY_AV', '');
        } else if($data['lender_id'] == Capri::$lender_id) {
            $secretKey = _env('LOTUSPAYSECRETKEY_CAPRI', '');
        } else{
            $secretKey = _env('LOTUSPAYSECRETKEY_KM', '');
        }

        $settlement_date = isset($data['settlement_date']) ? $data['settlement_date'] : Carbon::now()->toDateString();

        //status - pending,processing,settled
        $payload = json_encode(array("status" => "settled", "limit" => 5000));
        //$lotuspayurl = "https://api.lotuspay.com/v1/sources/";
        //$lotuspayurl = "https://test.lotuspay.com/v1/sources/";
        $lotuspayurl = $lotuspayurl."settlements?status=settled";
        $curl = curl_init();
        try {
            curl_setopt_array($curl, array(
                CURLOPT_URL => $lotuspayurl,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
                //CURLOPT_USERPWD => "$secretKey",
                CURLOPT_USERPWD => $secretKey,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "GET",
                CURLOPT_POSTFIELDS => $payload,
                CURLOPT_HTTPHEADER => array(
                    "Content-Type: application/json",
                ),
            ));
        } catch (\Exception $e) {
            return json_encode(array("error" => 'Something went wrong, Please try again'));
        }

        $response = json_decode(curl_exec($curl));
        $err = curl_error($curl);
        curl_close($curl);

        $settlementData = [];
        if(isset($response->data)){
            $settlementObjectData = $response->data;
            foreach ($settlementObjectData as $settlementObject){

                $settlementDataEntity = $this->getSettlementObjectBySettlementID($settlementObject->id, $data);

                try {
                    if (is_array($settlementDataEntity) && isset($settlementDataEntity['data']) && isset($settlementDataEntity['data']->status) && $settlementDataEntity['data']->status == 'settled' && strtotime($settlementDataEntity['date']) >= strtotime($settlement_date) && strtotime($settlementDataEntity['date']) <= Carbon::parse($settlement_date)->addDay(3)->timestamp) {
                        $settlement = $this->getPaymentObjectDataBySettlementID($settlementObject->id, $data);
                        if ($settlement != 'error') {
                            $settlementData[$settlementDataEntity['data']->id] = ['date' => $settlementDataEntity['date'], 'settlement' => $settlement, 'data' => $settlementDataEntity['data']];
                        } else {
                            (new Slack(new Request(['title' => __FUNCTION__ . ' Error', 'fields' => ['error' => json_encode($settlement)]])))->send();
                            break;
                        }
                    }
                }catch (\Exception $e){

                }
            }
        }

        return $settlementData;

        /*$umrnData = [];
        $mandateData = [];
        $responseData = [];
        $totalAmount = 0;
        foreach ($settlementData as $date => $settlementItems){
            foreach ($settlementItems as $settlementItem) {
                if (isset($settlementItem->status) && $settlementItem->status == 'settled' && $settlementDataEntity['data']->id == $settlementItem->settlement) {
                    $umrnData[] = $settlementItem->umrn;
                    $mandateData[] = $settlementItem->mandate;
                    $totalAmount += $settlementItem->amount / 100;
                    $responseData[$settlementItem->mandate][] = $settlementItem;
                }
            }
        }

        $mandateDataDatabase = Mandate::with('application')->whereIn('umrn', $mandateData)->get();
        $mandateDataDatabaseConsumer = [];
        foreach ($mandateDataDatabase as $item){
            $mandateDataDatabaseConsumer[$item->umrn] = $item->application;
        }
        $receivedData = [];
        foreach ($responseData as $mandateItem=>$responseItem){
            $receivedData[] = ['settlement' => $responseItem, 'application' => isset($mandateDataDatabaseConsumer[$mandateItem]) ? $mandateDataDatabaseConsumer[$mandateItem] : []];
        }

        return $receivedData;
    }*/
    }

public function getSettlementObjectBySettlementID($settlementObject, $data){
    $lotuspayurl = _env('LOTUSPAYBASEURL', '');
    if($data['lender_id'] == 1) {
        $secretKey = _env('LOTUSPAYSECRETKEY', '');
    } else if($data['lender_id'] == ConsumerApplication::AVANSE_LENDER_ID) {
        $secretKey = _env('LOTUSPAYSECRETKEY_AV', '');
    } else if($data['lender_id'] == Capri::$lender_id) {
        $secretKey = _env('LOTUSPAYSECRETKEY_CAPRI', '');
    } else{
        $secretKey = _env('LOTUSPAYSECRETKEY_KM', '');
    }


    //status - pending,processing,settled
    $payload = json_encode(array('settlement' => $settlementObject));
    //$lotuspayurl = "https://api.lotuspay.com/v1/sources/";
    //$lotuspayurl = "https://test.lotuspay.com/v1/sources/";
    $lotuspayurl = $lotuspayurl."settlements/".$settlementObject;
    $curl = curl_init();
    try {
        curl_setopt_array($curl, array(
            CURLOPT_URL => $lotuspayurl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
            //CURLOPT_USERPWD => "$secretKey",
            CURLOPT_USERPWD => $secretKey,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_HTTPHEADER => array(
                "Content-Type: application/json",
            ),
        ));
    } catch (\Exception $e) {
        return 'error';
    }

    $response = json_decode(curl_exec($curl));
    $err = curl_error($curl);
    curl_close($curl);


    $responseData = $response;
    if (isset($response->status) && $response->status == 'settled'){
        $date = $response->arrival_date;//date('Y-m-d', $response->created);
        $responseData = ['data' => $response, 'date' => $date];
    }

    return $responseData;
}

public function getCustomerByCustomerID($settlement, $data){
    if(isset($settlement->customer) && $settlement->customer){
        $lotuspayurl = _env('LOTUSPAYBASEURL', '');
        if($data['lender_id'] == 1) {
            $secretKey = _env('LOTUSPAYSECRETKEY', '');
        } else if($data['lender_id'] == ConsumerApplication::AVANSE_LENDER_ID) {
            $secretKey = _env('LOTUSPAYSECRETKEY_AV', '');
        } else if($data['lender_id'] == Capri::$lender_id) {
            $secretKey = _env('LOTUSPAYSECRETKEY_CAPRI', '');
        } else{
            $secretKey = _env('LOTUSPAYSECRETKEY_KM', '');
        }

        //status - pending,processing,settled
        $payload = json_encode(array('settlement' =>  $settlement->customer));
        //$lotuspayurl = "https://api.lotuspay.com/v1/sources/";
        //$lotuspayurl = "https://test.lotuspay.com/v1/sources/";
        $lotuspayurl = $lotuspayurl."customers/". $settlement->customer;
        $curl = curl_init();
        try {
            curl_setopt_array($curl, array(
                CURLOPT_URL => $lotuspayurl,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
                //CURLOPT_USERPWD => "$secretKey",
                CURLOPT_USERPWD => $secretKey,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "GET",
                CURLOPT_POSTFIELDS => $payload,
                CURLOPT_HTTPHEADER => array(
                    "Content-Type: application/json",
                ),
            ));
        } catch (\Exception $e) {
            return 'error';
        }

        $response = json_decode(curl_exec($curl));
        $err = curl_error($curl);
        curl_close($curl);


        if (isset($response->id)){
            return $response;
        }
    }

    return false;
}


public function getPaymentObjectDataBySettlementID($settlementObject, $data){
    $lotuspayurl = _env('LOTUSPAYBASEURL', '');
    if($data['lender_id'] == 1) {
        $secretKey = _env('LOTUSPAYSECRETKEY', '');
    } else if($data['lender_id'] == ConsumerApplication::AVANSE_LENDER_ID) {
        $secretKey = _env('LOTUSPAYSECRETKEY_AV', '');
    } else if($data['lender_id'] == Capri::$lender_id) {
        $secretKey = _env('LOTUSPAYSECRETKEY_CAPRI', '');
    } else{
        $secretKey = _env('LOTUSPAYSECRETKEY_KM', '');
    }

    //status - pending,processing,settled
    $payload = json_encode(array('settlement' => $settlementObject));
    //$lotuspayurl = "https://api.lotuspay.com/v1/sources/";
    //$lotuspayurl = "https://test.lotuspay.com/v1/sources/";
    $lotuspayurl = $lotuspayurl."ach_debits?settlement=".$settlementObject."&limit=6000";
    //$lotuspayurl = $lotuspayurl."payments?settlement=".$settlementObject."&limit=6000";
    $curl = curl_init();
    try {
        curl_setopt_array($curl, array(
            CURLOPT_URL => $lotuspayurl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
            //CURLOPT_USERPWD => "$secretKey",
            CURLOPT_USERPWD => $secretKey,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_HTTPHEADER => array(
                "Content-Type: application/json",
            ),
        ));
    } catch (\Exception $e) {
        return 'error';
    }

    $response = json_decode(curl_exec($curl));
    $err = curl_error($curl);
    curl_close($curl);



    $responseData = [];
    if (isset($response->data)){
        foreach ($response->data as $item){
            $responseData[] = $this->paymentDataByPaymentID($item->id, $data);
        }
    }

    return $responseData;
}

public function paymentDataByPaymentID($paymentID, $data){
    $lotuspayurl = _env('LOTUSPAYBASEURL', '');
    if($data['lender_id'] == 1) {
        $secretKey = _env('LOTUSPAYSECRETKEY', '');
    } else if($data['lender_id'] == ConsumerApplication::AVANSE_LENDER_ID) {
        $secretKey = _env('LOTUSPAYSECRETKEY_AV', '');
    } else if($data['lender_id'] == Capri::$lender_id) {
        $secretKey = _env('LOTUSPAYSECRETKEY_CAPRI', '');
    } else{
        $secretKey = _env('LOTUSPAYSECRETKEY_KM', '');
    }

    //status - pending,processing,settled
    $payload = json_encode(array());
    //$lotuspayurl = "https://api.lotuspay.com/v1/sources/";
    //$lotuspayurl = "https://test.lotuspay.com/v1/sources/";
    //$lotuspayurl = $lotuspayurl."payments/".$paymentID;
    $lotuspayurl = $lotuspayurl."ach_debits/".$paymentID;
    $curl = curl_init();
    try {
        curl_setopt_array($curl, array(
            CURLOPT_URL => $lotuspayurl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
            //CURLOPT_USERPWD => "$secretKey",
            CURLOPT_USERPWD => $secretKey,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_HTTPHEADER => array(
                "Content-Type: application/json",
            ),
        ));
    } catch (\Exception $e) {
        return 'error';
    }

    $response = json_decode(curl_exec($curl));
    $err = curl_error($curl);
    curl_close($curl);


    return $response;
}

public function getPrefilledNach($mandate_id,$secretKey,$application_id,$file_name,$lotuspayurl){
    if($mandate_id != "") {
        $curl = curl_init();
        $lotuspayurl_prefilled = $lotuspayurl . "mandates/" . $mandate_id . "/pdf";

        curl_setopt_array($curl, array(
            CURLOPT_URL => $lotuspayurl_prefilled,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_USERPWD => $secretKey,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_POSTFIELDS => "",
            CURLOPT_HTTPHEADER => array(
                "cache-control: no-cache"
            ),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
            echo "cURL Error #:" . $err;
        } else {
            if ($response != "") {
                static::uploadToS3($file_name, $application_id, $response);
            }
        }
    }
}


public static function uploadToS3($file_type, $id, $file,$password = ""){
    $file_path = '/' . $id . '/' . $file_type . ".pdf";

    $s3 = Storage::disk('s3');
    if ($file) {
        $s3->put($file_path, $file);
        $data['file_type'] = $file_type;
        $data['id'] = $id;
        (new ConsumerApplicationController())->getUploadedFileNameMultiple($s3, $file_path,$data);
    }
}
public function createSubcription($application_id,$mandate = null,$consumer_data = null, $app_type = ''){
    if($mandate == null) {
        $mandate = Mandate::where('consumer_application_id', $application_id)->where('frequency',"M")->where('status', '!=', 'inactive')->first();
    }
    if(isset($mandate->id)) {
        if($consumer_data == null) {
            $consumer_data = ConsumerApplication::with('bank_details', 'emi')->where('id', $application_id)->first();
        }

        $lotuspayurl = _env('LOTUSPAYBASEURL', '');
        if($consumer_data->lender_id == 1) {
            $secretKey = _env('LOTUSPAYSECRETKEY', '');
        } else if($consumer_data->lender_id == ConsumerApplication::AVANSE_LENDER_ID) {
            $secretKey = _env('LOTUSPAYSECRETKEY_AV', '');
        } else if($consumer_data->lender_id == Capri::$lender_id) {
            $secretKey = _env('LOTUSPAYSECRETKEY_CAPRI', '');
        } else{
            $secretKey = _env('LOTUSPAYSECRETKEY_KM', '');
        }

        if (isset($consumer_data->id) && isset($consumer_data->bank_details->id) && isset($consumer_data->emi->emi_date)) {
            $subcription = array();
            $subcription['amount'] = (isset($consumer_data->emi->emi) && $consumer_data->emi->emi != '') ? $this->getEMIAmount($consumer_data)*100 : $this->getNetAmount($consumer_data)*100;
            $subcription['count'] = (isset($consumer_data->emi->remaining_emi) && $consumer_data->emi->remaining_emi != '') ? $consumer_data->emi->remaining_emi : '';
            $subcription['day_of_month'] = (isset($consumer_data->emi->emi_date) && $consumer_data->emi->emi_date != '') ? date('d', strtotime($consumer_data->emi->emi_date)) : "";
            $subcription['interval'] = 'month';
            $subcription['mandate'] = (isset($mandate->mandate_id) && $mandate->mandate_id != '') ? $mandate->mandate_id : '';
            $subcription['name'] = ($app_type == 2) ? $consumer_data->co_applicant_name." - Monthly" : $consumer_data->name." - Monthly";
            $subcription['start_date'] = (isset($consumer_data->emi->emi_date) && $consumer_data->emi->emi_date != '') ? date('Y-m-d', strtotime($consumer_data->emi->emi_date)) : "";

            if ($subcription['amount'] == "" || $subcription['count'] != "" ||$subcription['start_date'] == "" || $subcription['start_date']) {
                return json_encode(array("error" => 'Data missing for EMI'));
            }
            if ($subcription['mandate'] == "") {
                return json_encode(array("error" => 'Mandate ID missing'));
            }

            $payload = json_encode($subcription);
            $curl = curl_init();
            try {
                curl_setopt_array($curl, array(
                    CURLOPT_URL => $lotuspayurl . "sources/",
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
                    CURLOPT_USERPWD => "$secretKey",
                    CURLOPT_ENCODING => "",
                    CURLOPT_MAXREDIRS => 10,
                    CURLOPT_TIMEOUT => 30,
                    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                    CURLOPT_CUSTOMREQUEST => "POST",
                    CURLOPT_POSTFIELDS => $payload,
                    CURLOPT_HTTPHEADER => array(
                        "Content-Type: application/json",
                    ),
                ));
            } catch (\Exception $e) {
                return json_encode(array("error" => 'Something went wrong, Please try again'));
            }
            $response = json_decode(curl_exec($curl));
            $err = curl_error($curl);
            curl_close($curl);
            return json_encode(array("status"=>"Success","message" => "Subscription created Successfully"));
        }
    }
    else{
        return json_encode(array("error" => 'Mandate Does not Exist'));
    }
}

public function generateMandateDocument($id, $mandateModel, $mandateStatus = '', $mandate_umrn = '', $app_type = ''){
    try{
        $application = ConsumerApplication::with('bank_details', 'bank_details_multiple','lender')->where('id',$id)->first(['name','lender_id','id']);
        if($mandateModel->mode == 'lotuspay_emandate') {

            $emi = ApplicationEMICalculation::where('application_id', $id)->first(['emi_date']);

            if($application->lender_id == 1) {
                $utility_code = 'NACH00000000019187';
            }elseif($application->lender_id == AvanseServices::$lender_id) {
                $utility_code = _env('LOTUSPAY_UTILITYCODE_AV');
            }elseif($application->lender_id == Services::$lender_id) {
                $utility_code = _env('LOTUSPAYUTILITY_ABFL');
            }elseif($application->lender_id == Capri::$lender_id) {
                $utility_code = _env('LOTUSPAYUTILITY_CAPRI');
            }elseif($application->lender_id == JMServices::$lender_id) {
                $utility_code = _env('LOTUSPAYUTILITY_JMFL');
            }elseif($application->lender_id == LendBox::$lender_id || $application->lender_id == LendBoxLSP::$lender_id) {
                $utility_code = _env('LOTUSPAYUTILITY_LENDBOX');
            }else{
                $utility_code = 'NACH00000000021321';
            }

            if($app_type == 2){
                foreach($application->bank_details_multiple as $value){
                    if($value->applicant_type == 2){
                        $ifsc = substr($value->ifsc_code, 0, 4);
                        $debtor_account_name = (isset($value->name) && $value->name != '') ? $value->name : $application->co_applicant_name;
                        $debtor_account_type = (isset($value->account_type) && $value->account_type != '') ? $value->account_type : 'savings';
                        $debtor_account_ifsc_code = (isset($value->ifsc_code) && $value->ifsc_code != '') ? $value->ifsc_code : '';
                        $debtor_account_number = (isset($value->account_number) && $value->account_number != '') ? $value->account_number : '';
                        $debtor_agent_code = (isset($value->bank_ifsc_code) && $value->bank_ifsc_code != '') ? $value->bank_ifsc_code : $ifsc;
                    }
                }
            }else {
                $ifsc = substr($application->bank_details->ifsc_code, 0, 4);
                $debtor_account_name = (isset($application->bank_details->name) && $application->bank_details->name != '') ? $application->bank_details->name : $application->name;
                $debtor_account_type = (isset($application->bank_details->account_type) && $application->bank_details->account_type != '') ? $application->bank_details->account_type : 'savings';
                $debtor_account_ifsc_code = (isset($application->bank_details->ifsc_code) && $application->bank_details->ifsc_code != '') ? $application->bank_details->ifsc_code : '';
                $debtor_account_number = (isset($application->bank_details->account_number) && $application->bank_details->account_number != '') ? $application->bank_details->account_number : '';
                $debtor_agent_code = (isset($application->bank_details->bank_ifsc_code) && $application->bank_details->bank_ifsc_code != '') ? $application->bank_details->bank_ifsc_code : $ifsc;
            }
            $lender_name = $application->lender->name ?? '';
            $lender_id = $application->lender_id ?? '';

            $mandateArr = [
                'name' => $debtor_account_name,
                'mandate' => !empty($mandate_umrn) ? $mandate_umrn : $mandateModel->umrn,
                'status' => $mandateStatus == 1 ? 'Active' : $mandateStatus,
                'date_submitted' => $mandateModel->created_at,
                'amount_maximum' => $mandateModel->mandate_amount,
                'creditor_agent_name' => 'YESB',
                'creditor_name' => $lender_name,
                'creditor_utility_code' => $utility_code,
                'date_first_collection' => $mandateModel->date_first_collection ?? $emi->emi_date,
                'date_final_collection' => $mandateModel->expiry_date,
                'debtor_account_name' => $debtor_account_name,
                'debtor_account_type' => $debtor_account_type,
                'debtor_account_ifsc_code' => $debtor_account_ifsc_code,
                'debtor_agent_code' => $debtor_agent_code,
                'avanse_lan' => AvanseProcesses::getLANNumber($id),
                'debtor_account_number' => $debtor_account_number,
                'lender_id' => $lender_id
            ];

            $view = view('admin.consumer-application.mandate_document', ['data' => $mandateArr]);

            $pdf = App::make('snappy.pdf.wrapper');
            $emandateFileName = 'e-mandate';
            if($mandateStatus == 'acknowledged'){
                $emandateFileName = 'e-mandate-'.$mandateStatus;
            }
            $file_id = (new ConsumerDocument(new Request()))->uploadToS3($emandateFileName, $id, $pdf->loadHTML($view)->output());

//            DocumentDetails::insert([
//                'consumer_file_id' => $file_id,
//                'application_id' => $id,
//                'doc_type' => 'MANDATE',
//                'created_by' => (Auth::check()) ? Auth::user()->id : 107,
//                'json_data' => json_encode($mandateArr),
//                'created_at' => Carbon::now()->toDateTimeString()
//            ]);

            (new ConsumerDocument((new Request())))->saveDocumentDetails($id, $file_id, 'MANDATE', $mandateArr);
        }
    }catch (\Exception $e){
        (new Slack(new Request(['title'=>'Lotus Pay Document','fields'=>['error'=>$e->getMessage(),'line'=>$e->getLine(),'trace'=>$e->getTraceAsString()], 'group' => Slack::$STAGE_TESTING])))->send();
    }
}

public function lotuspayWebhookJob($payloadData, Request $request){
    $request->request->add(['job' => 1]);
    $payloadData['request'] = $request->input();

    $payload[] = [
        'payload' => json_encode($payloadData),
        'from' => 'lotuspay_webhook_job',
        'application_id' => 181,
        'available_at' => Carbon::createFromTimeString('22:00')->toDateTimeString(),
        'created_at' => Carbon::now()->toDateTimeString()
    ];

    CampaignsJobProvider::insert($payload);
}

public function getOtherServiceUpdate($responseDataServiceCheck, $responseData){
    $date = Carbon::now()->toDateTimeString();

    $hashids = new Hashids(_env('HASH_ID'), 20);
    $decodedRefId = $hashids->decode($responseDataServiceCheck->data->metadata->transaction_id);

    DB::connection('qh_service')->table('web_hook_logs')->insert([
        'mandate_id' => $decodedRefId[0],
        'vendor' => 'LotusPay',
        'data' => $responseData,
        'status' => $responseDataServiceCheck->data->status
    ]);

    if (strpos($responseDataServiceCheck->type, "mandate") === 0) {
        DB::connection('qh_service')->table('queue')->insert([
            'from' => 'mandate_webhook_update',
            'payload' => json_encode($responseDataServiceCheck),
            'available_at' => $date,
            'application_id' => $decodedRefId[0],
            'created_at' => $date,
            'is_available' => 0
        ]);
    }
}

public function getWebhookNotification($lender, Request $request){

    $str = $request->has('serialized_response') ? $request->get('serialized_response') : "";
    if ($lender == 1){
        $key32 = _env('PRIDE');
    }elseif($lender == AvanseServices::$lender_id){
        $key32 = _env('LOTUSPAY_WEBHOOK_AV');
    }elseif($lender == Services::$lender_id){
        $key32 = _env('LOTUSPAYWEBHOOK_ABFL');
    }elseif($lender == Capri::$lender_id){
        $key32 = _env('LOTUSPAYWEBHOOK_CAPRI');
    }elseif($lender == LendBox::$lender_id || $lender == LendBoxLSP::$lender_id){
        $key32 = _env('LOTUSPAYWEBHOOK_LENDBOX');
    }elseif($lender == JMServices::$lender_id){
        $key32 = _env('LOTUSPAYWEBHOOK_JMFL');
    }else{
        $key32 = _env('KM');
    }

    $iv = substr($str, 0, 16);
    $encry_data = substr($str, 16);
    $responsedata = openssl_decrypt($encry_data, "AES-128-CBC", $key32, 0, $iv);
    // $responsedata = $request->getContent();


    if(empty($str) && ($request->has('job') || $request->request->has('job'))) {
        $responsedata = $request->get('responsedata');
    }
    try {

        //check service
        $responseDataServiceCheck = json_decode($responsedata);
        if (isset($responseDataServiceCheck->data->metadata) && isset($responseDataServiceCheck->data->metadata->service) && $responseDataServiceCheck->data->metadata->service == 'CFQH'){
            $this->getOtherServiceUpdate($responseDataServiceCheck, $responsedata);
            return json_encode(array("status"=>"success"));
        }
        //end service

        $updatewebhook = new WebHookLog();
        $updatewebhook->vendor = "LotusPay";
        $updatewebhook->data = $responsedata;
        $updatewebhook->save();

        if ($responsedata) {
            $responsedata = json_decode($responsedata);
            if (strpos($responsedata->type, "mandate") === 0) {
                $mandate_status = $responsedata->data->status ?? "pending";
                $mandate_umrn = $responsedata->data->umrn ?? "";
                $mandate_id = $responsedata->data->id;
                $mandateData = Mandate::where('mandate_id', $mandate_id)->first();
                if(!isset($mandateData->id) && isset($responsedata->data) && isset($responsedata->data->metadata) && isset($responsedata->data->metadata->transaction_id)) {
                    $hashids = new Hashids('Creditfair by CS', 20);
                    $_transaction_id = $hashids->decode($responsedata->data->metadata->transaction_id);

                    $mandateData = Mandate::where('id', $_transaction_id[0])->first();
                }
                if(isset($mandateData->id)) {
                    if (!empty($mandate_umrn)) {
                        Mandate::where('id', $mandateData->id)->update(['umrn' => $mandate_umrn, 'status' => $mandate_status]);
                    } else {
                        Mandate::where('id', $mandateData->id)->update(['status' => $mandate_status]);
                    }

                    if (!$mandateData->mandate_id){
                        Mandate::where('id', $mandateData->id)->update(['mandate_id' => $mandate_id]);
                    }

//                    $mandateModel = Mandate::where('mandate_id', $mandate_id)->first();
                    if (isset($mandateData->consumer_application_id)) {
                        TATLogs::insert(['action' => 'e-mandate completed', '_id' => $mandateData->consumer_application_id, 'id_type' => 'application_id', 'user_id' => 107, 'created_at' => Carbon::now()->toDateTimeString()]);
                    }
                }

//                $mandateModel = Mandate::where('mandate_id', $mandate_id)->first();
                if (isset($mandateData->id)) {
                    try{
                        $vendorWebhook = new VendorWebhook();
                        $consumerApplicationController = new ConsumerApplicationController();
                        $consumerApplicationController->webhook($mandateData->consumer_application_id, ['type' => 'NACH-Webhook','status' => $mandate_status]);
                        $sendDAWebhook = (new WebhookController())->pushDAWebhook($mandateData->consumer_application_id, 'nach');
                        if ($sendDAWebhook) {
                            $consumerApplicationController->webhook($mandateData->consumer_application_id, ['type' => 'DA-Confirmation-Webhook','status' => 'pending', 'data' => $consumerApplicationController->getMConnectPayload($mandateData->consumer_application_id, 'DA-Confirmation-Webhook')]);
                        }
                        $payload = $consumerApplicationController->vendorWebhook($mandateData->consumer_application_id, ['type' => 'NACH-Webhook','status' => $mandate_status, 'data' => []]);
                        if (isset($payload)) {
                            $vendorWebhook->handle('NACH-Webhook', $payload);
                        }
                    } catch (\Exception $e){
                        $cwFactory = new CloudWatchLoggerFactory();
                        $cwFactory->logger(json_encode(['title' => 'Webhook failed', 'message' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()]));
                    }

                    if (isset($responsedata->data->metadata->source) && $responsedata->data->metadata->source == 'emi-checkout' && (in_array($mandate_status, ['active','submitted', 'acknowledged']))) {
                        $consumerModel = ConsumerApplication::where('id', $mandateData->consumer_application_id)->first();
                        if ($consumerModel->state != 'disbursement checklist done') {
                            $consumerModel->update(['state' => 'disbursement checklist done']);
                            StatusLogs::insert([
                                'application_id' => $mandateData->consumer_application_id,
                                'user_id' => $consumerModel->user_id,
                                'status' => 'disbursement checklist done',
                                'created_at' => Carbon::now()->toDateTimeString()
                            ]);
                        }
                    }

                    MandateStatusLog::insert([
                        'mandate_id' => $mandateData->id,
                        'user_id' => 107,
                        'status' => $mandate_status,
                        'reason' => 'Lotus Pay Auto Update',
                        'created_at' => Carbon::now()->toDateTimeString()
                    ]);
                    $hashids = new Hashids('Creditfair by CS', 20);
                    $_app_type = 1;
                    if (isset($responsedata->data->metadata->app_type)) {
                        $_app_type = $hashids->decode($responsedata->data->metadata->app_type);
                    }
                    if(in_array($mandate_status, ['active','submitted', 'acknowledged'])) {
                        $this->generateMandateDocument($mandateData->consumer_application_id, $mandateData, $mandate_status, $mandate_umrn, $_app_type);
                    }
                    if (!empty($mandate_status) && $mandate_status = "active") {
                        $this->createSubcription($mandateData->consumer_application_id, $mandateData, null, $_app_type);
                    }
                }
            }

            if (strpos($responsedata->type, "nach::debit") === 0 || strpos($responsedata->type, "payment") === 0) {

                if(!$request->has('job') && !$request->request->has('job')) {
                    $this->lotuspayWebhookJob(['responsedata' => $responsedata, 'lender_id' => $lender], $request);
                    return json_encode(array("status" => "success"));
                }

                $mandate_id = $responsedata->data->mandate;
                $mandate_umrn = $responsedata->data->umrn;
                $amount = ($responsedata->data->amount) / 100;
                $payment_date = $responsedata->data->charge_date;
                $reason = $responsedata->data->failure_message;
                $status = (isset($responsedata->data->status) && $responsedata->data->status == "confirmed") ? "success" : ((isset($responsedata->data->status) && $responsedata->data->status == "failed") ? "rejected" : "");
                if (!empty($status)) {
                    $mandateModel = Mandate::where('mandate_id', $mandate_id)->first();
                    if ($mandateModel) {
                        $transcation_id = $responsedata->data->id . "_" . $mandate_id;
                        $paymentTransaction = PaymentTransaction::where('application_id',$mandateModel->consumer_application_id)->where('trasanction_id', $transcation_id)->first(['id']);

                        if (!isset($paymentTransaction->id)) {
                            $bank_id = (new ConsumerApplicationController())->getTransactionBank($mandateModel->consumer_application_id);
                            $payment = new LoanManagement();
                            $data['amount'] = $amount;
                            $data['payment_date'] = $payment_date;
                            $data['mode'] = "NACH-LOTUS";
                            $data['paid_by'] = "";
                            $data['collected_by'] = 0;
                            $data['wallet_name'] = "";
                            $data['bank_id'] = 4;
                            $data['trasanction_id'] = $transcation_id;
                            $data['online_payment_id'] = 0;
                            $data['trasanction_acknowledgement'] = "";
                            $data['status'] = $status;
                            $data['reason'] = $reason;
                            $data['umrn'] = $mandate_umrn;
                            $data['application_id'] = $mandateModel->consumer_application_id;
                            $payment->paymentReconcile($data);
                        }
                    }
                }
            }
        }
    }catch (\Exception $e){
        (new \App\Slack(new Request(['title'=>'Lotus Pay Web hook Error','fields'=>['error'=>$e->getMessage(),'line'=>$e->getLine(),'trace'=>$e->getTraceAsString()], 'group' => Slack::$STAGE_TESTING])))->send();
    }
//        }
    return json_encode(array("status"=>"success"));
}

public function addEMandateConsumner($id, $b_type, $emandate_variant = 'emandate'){
    $dataItems = ['id' => $id, 'b_type' => $b_type, 'emandate_variant' => $emandate_variant];
    $hashids         = new Hashids('Creditfair by CS', 20);
    $application_ids = $hashids->decode($id);

    $b_type_status = $hashids->decode($b_type);
    $emandate_variant = $hashids->decode($emandate_variant);
    $emandate_variant = isset($emandate_variant[0]) ? ($emandate_variant[0] == 2 ? 'emandate_esign' : ($emandate_variant[0] == 1 ? 'emandate_api' : 'emandate')) : 'emandate';
    if (isset($b_type_status[0])){
        $b_type_status = $b_type_status[0];//$b_type_status[0] == 0 ? 'monthly' : 'ADHO';
    }

    if (request()->has('type')) {
        Input::merge(['app_type' => request()->get('type')]);
    }

    if(Input::has('app_type') && Input::get('app_type') == 2){
        $bankdata = Bank::where('application_id',$application_ids[0])->where('applicant_type', 2)->first();
    }else{
        $bankdata = Bank::where('application_id',$application_ids[0])->where('applicant_type', 1)->first();
    }

    $data = array();
    $data['req_base'] = json_encode($dataItems);
    $data['is_home'] = true;
    $data['application_ids'] = $application_ids[0];
    $data['bank_names_list'] = array_keys(Config::get('constants.emandate_bank_list'));

    $data['bank'] = $bankdata;
    $data['error'] = $this->error_message;
    $data['b_type_status'] = $b_type_status;
    $data['emandate_variant'] = $emandate_variant;
    $data['isRetry'] = $this->retry_nach;
    $data['app_type'] = Input::has('app_type') ? '?type='.Input::get('app_type') : '?type=1';
    $data['isRetryLimit'] = MandateRequestLogs::where('application_id', $application_ids[0])->where('is_retry', 1)->count();
    if ($emandate_variant) {
        $data['redirect'] = 'esign';
    }
    // if ($data['isRetryLimit'] > 2){
    //     $data['error'] = 'There seems to be an issue for emandate update.<br/> Please contact our customer care on 91 9967235047 for further assistance';
    // }
    $bnpl = ConsumerApplicationElement::with('application')->where('application_id',$application_ids[0])->first();
    $data['is_bnpl'] = $bnpl->is_bnpl ?? 0;
    $data['lender_ids'] = $bnpl->application->lender_id;

    if(request()->has('utkarsh_mandate')){
        return $data;
    }

    return view('front.bankdetails',$data);
}

public function updateEMandateConsumner(){

    $data = Input::all();
    try {
        $bankdetails = [
            'name' => isset($data['name']) ? $data['name'] : '',
            'ifsc_code' => isset($data['ifsccode']) ? $data['ifsccode'] : '',
            'bank_name' => isset($data['bankname']) ? $data['bankname'] : '',
            'branch_name' => isset($data['branch']) ? $data['branch'] : '',
            'account_number' => isset($data['accountno']) ? $data['accountno'] : '',
            'account_type' => isset($data['accounttype']) ? $data['accounttype'] : '',
            'application_id' => isset($data['applicationid']) ? $data['applicationid'] : '',
        ];
        if(isset($data['bankid']) && $data['bankid'] != 0){
            Bank::where('id',$data['bankid'])->update($bankdetails);
        }else {
            Bank::insert($bankdetails);
        }

        $frequency = isset($data['b_type']) && $data['b_type'] == 0 ? 'monthly' : 'ADHO';
        $this->until_cancelled = 0;
        if (isset($data['b_type']) && $data['b_type'] == 2){
            $this->until_cancelled = 1;
        }

        $nachresponse = $this->createMandate($data['applicationid'],'emandate',$frequency);
        if(isset($nachresponse->url) && $nachresponse->url != "") {
            return redirect()->to($nachresponse->mandate);
        }else{
            \Session::flash('success', 'Something went wrong went, Please try again later.');
        }
    }catch (\Exception $e){
        \Session::flash('success', 'Something went wrong went, Please try again later.');
    }
}
}
