<?php
/**
 * Created by PhpStorm.
 * User => sunilkhorwal
 * Date => 2019-05-30
 * Time => 15 =>57
 */

namespace App\Avanse\DataModels;

use App\Avanse\Processes\AvanseProcesses;
use App\AvanseCollaterals;
use App\AvanseCreateCustomer;
use App\AvanseCreateDocument;
use App\AvanseCreateFinance;
use App\AvanseFeeDueInsuranceStep;
use App\AvanseFees;
use App\AvanseFinanceDetails;
use App\AvanseFinSummary;
use App\AvanseFinVas;
use App\AvanseMasterData;
use App\AvanseOverdueCharges;
use App\AvansePlanEMIHmonthsDates;
use App\AvanseSchedules;
use App\AvanseTransactions;
use App\ConsumerApplication;
use App\EmiPayment;
use App\Http\Controllers\Admin\ConsumerDocument;
use App\Http\Controllers\Admin\DisbursementController;
use App\Http\Controllers\NachController;
use App\Http\Controllers\Grade\GradeController;
use App\LiabilityLog;
use App\MultiStageDisbursement;
use Carbon\Carbon;
use Illuminate\Support\Facades\Config;
use Illuminate\Http\Request;
use App\Slack;
use App\AvanseBRE;
use Illuminate\Support\Facades\Storage;

class AvanseFinance
{
    public $error = null;
    private $request;
    public $service = null;
    private $prefix = 'CF000';

    public function __construct(Request $request)
    {

        $this->request = $request;
    }

    public function getPayload()
    {
        if ($this->service) {
            $service = $this->service;
            return $this->$service();
        }

        if (!$this->dataInitialize()){
            return false;
        }

        $payload = [
            'stp' => false,
            'financeSchedule' => [
                'financeDetail' => $this->getFinanceDetails(),
                'fees' => $this->getFees()
            ],
            'disbursement' => $this->getDisbursement(),
        ];

        if(_env('APP_CONNECTION')){
            $payload['extendedDetails'] = $this->getExtendedDetails();
        }

        if ($this->request->get('co_applicant_name')) {
            $payload['coApplicants'] = $this->getCoApplicantDetails();
        }

        if($this->request->get('mandate')){
            $payload['mandateDetail'] = $this->getMandateDetails();
        }

        if($this->request->get('documents')){
            $payload['documents'] = $this->getDocuments();
        }

        return $payload;
    }

    private function getCoApplicantDetails(){

        $data[] = [
            "cif" => $this->request->get('co_cif'),
            "includeRepay" => null,
            "repayAccountId" => null,
            "authoritySignatory" => true,
            "sequence" => "2",
            "catOfcoApplicant" => $this->request->get('co_applicant_relationship'),
            "includeIncome" => ""
        ];

        return $data;
    }

    private function getExtendedDetails(){

        $avanse = new AvanseMasterData();
        $avanse->setTable('BMTPinCodes');
        $cityPincodeData = $avanse->where('PinCode', $this->request->get('current_address_pincode'))->first();

        if (isset($cityPincodeData->City)) {
            $avanse->setTable('RMTProvinceVsCity');
            $cityData = $avanse->where('PCCity', $cityPincodeData->City)->first();
        }

        return [
            [
                "extendedFields" => [
                    [
                        'fieldName' => 'ADDRESS1',
                        'fieldValue' => $this->request->get('address')
                    ],
                    [
                        'fieldName' => 'ADMISSIONSTATUS',
                        'fieldValue' => $this->request->get('admission_status')
                    ],
                    [
                        'fieldName' => 'CITY1',
                        'fieldValue' => isset($cityPincodeData->City) ? $cityPincodeData->City : ''
                    ],
                    [
                        'fieldName' => 'CONTACTNAME1',
                        'fieldValue' => $this->request->get('name')
                    ],
                    [
                        'fieldName' => 'COUNTRYREFERENCE1',
                        'fieldValue' => isset($cityData->PCCountry) ? $cityData->PCCountry : ''
                    ],
                    [
                        'fieldName' => 'LANDMARK1',
                        'fieldValue' => $this->request->get('current_address_landmark')
                    ],
                    [
                        'fieldName' => 'MOBILE1',
                        'fieldValue' => $this->request->get('phone')
                    ],
                    [
                        'fieldName' => 'PINCODE1',
                        'fieldValue' => $this->request->get('current_address_pincode')
                    ],
                    [
                        'fieldName' => 'STATE1',
                        'fieldValue' => isset($cityData->PCProvince) ? $cityData->PCProvince : ''
                    ]
            ]
        ]
          ];
    }

    private function getDisbursement(){
        return [];
        if ($this->request->get('merchant_bank_details')) {
            return [
                [
                    'disbParty' => 'CS',
                    'disbType' => 'NEFT',
                    'disbDate' => date('Y-m-d\TH:i:s'),
                    'disbAmount' => $this->request->get('net_disbursement_amount') * 100,
                    'remarks' => null,
                    'issueBank' => '50250',
                    'favourName' => $this->request->get('merchant_bank_details')->bank_name,
                    'partnerBankId' => '46',
                    'payableLoc' => '',
                    'printingLoc' => '',
                    'valueDate' => date('Y-m-d\TH:i:s'),
                    'bankCode' => '',
                    'branchCode' => '',
                    'ifsc' => $this->request->get('merchant_bank_details')->ifsc_code,
                    'accountNo' => $this->request->get('merchant_bank_details')->account_number,
                    'acHolderName' => $this->request->get('merchant_bank_details')->account_holder,
                    'phoneCountryCode' => '91',
                    'phoneAreaCode' => '',
                    'phoneNumber' => $this->request->get('merchant')->contact_number
                ]
            ];
        }

        return [];
    }

    private function getMandateDetails(){

        $mandate = [];
        if ($this->request->get('mandate') && $this->request->get('bank_details')) {
            $bankDetails = $this->request->get('bank_details');
            $mandate = [
                'mandateType' => 'NACH',
                'ifsc' => $bankDetails->ifsc_code,
                'accNumber' => $bankDetails->account_number,
                'accHolderName' => $bankDetails->account_holder,
                'accType' => '10',
                'openMandate' => true,
                'startDate' => date('c', strtotime($this->request->get('first_emi_date'))),
                'maxLimit' => $this->request->get('mandate')->mandate_amount,
                'partnerBankId' => '46',
                'documentName' => 'mandate.jpg',
                'docRefId' => $this->request->get('mandate')->id
            ];
        }

        return $mandate;
    }

    private function getDocuments(){

        return $documentsLists = [];

        if ($this->request->get('documents')) {
            $s3 = Storage::disk('s3');
            foreach ($this->request->get('documents') as $document) {
                if ($s3->exists($document->file_path)) {
                    $data = $s3->get($document->file_path);
                    $getExtension = explode('.', $document->file_path);
                    $extension = $getExtension[count($getExtension) - 1] == 'pdf' ? 'PDF' : 'IMAGE';
                    $documentsLists[] = [
                        'custDocTitle' => $document->file_type,
                        'docCategory' => ucwords($document->file_type),
                        'custDocIssuedCountry' => 'IN',
                        'custDocIssuedAuth' => $extension,
                        'docFormat' => $extension,
                        'docRefId' => $document->id,
                        'custDocIssuedOn' => null,
                        'custDocExpDate' => null,
                        'docContent' => base64_encode($data),
                        'docName' => $document->file_type . '.pdf'
                    ];
                }
            }
        }

        return $documentsLists;
    }

    private function getFinanceDetails(){

        $Branch = Config::get('avanse')['Branches'];

        $avanseProcesses = new AvanseProcesses($this->request);
        return [
            'cif' => $this->request->get('cif'),
            'applicationNo' => $this->prefix.$this->request->get('id'),
            'finType' => $this->request->get('liability_log') ? _env('AVANSE_LOAN_TYPE_LIABILITY') : _env('AVANSE_LOAN_TYPE'),
            'finCcy' => 'INR',
            'finBranch' => $Branch['DELHI'],
            'profitDaysBasis' => '30E/360',
            'finAmount' => round($avanseProcesses->getNetAmountAsPerAvanse(0,0)) * 100,//$this->request->get('loan_amount') * 100,
            'finAssetValue' => round($avanseProcesses->getNetAmountAsPerAvanse(0,0)) * 100,//$this->request->get('approved_amount') * 100,
            'finStartDate' => date('c', Carbon::createFromFormat('d/m/Y',$this->request->get('payment_transfer_date'))->timestamp),
            'numberOfTerms' => $this->request->get('tenure'),
            'repayRateBasis' => 'R',
            'repayPftRate' => $this->request->get('interest_rate'),
            'finRepayMethod' => 'MANUAL', //MANUAL, NACH
            'scheduleMethod' => 'EQUAL',
            'alwBpiTreatment' => false,
            'nextRepayDate' => date('c', strtotime($this->request->get('emi_date'))),
            'dsaCode' => _env('AVANSE_DSA_CODE'),
            'dmaCode' => _env('AVANSE_SALES_MANAGER_CODE'),
            'accountsOfficer' => _env('AVANSE_ACCOUNTS_OFFICER'),
            'referralId' => _env('AVANSE_REFERRAL_ID'),
            "advType" => "AE",
            "advTerms" => $this->request->get('merchant_collected_advance_amount') && $this->request->get('merchant_collected_advance_amount') ? $this->request->get('advance_emi') : "0",
            "advStage" => "FE"
        ];
    }

    private function getFees(){

        $data = [
            [
                'feeCode' => 'DSASUB', //Subvention fee
                'feeAmount' => $this->request->get('subvention_amount') ? round($this->request->get('subvention_amount')) * 100 : 0,
                'feeMethod' => 'DISB',
                'waiverAmount' => 0,
                'paidAmount' => 0 ,
                'TotalPaidAmount' => $this->request->get('subvention_amount') ? round($this->request->get('subvention_amount')) * 100 : 0,
            ],
            [
                'feeCode' => 'PROCFEE', //Processing Fee
                'feeAmount' => $this->request->get('processing_fee') ? $this->request->get('processing_fee') * 100 : 0,
                'feeMethod' => 'DISB',
                'waiverAmount' => 0,
                'paidAmount' => 0 ,
                'TotalPaidAmount' => $this->request->get('processing_fee') ? $this->request->get('processing_fee') * 100 : 0,
            ],
            [
                'feeCode' => 'ADVEMI', //Advance Amount
                'feeAmount' => $this->request->get('merchant_collected_advance_amount') ? $this->request->get('merchant_collected_advance_amount') * 100 : 0,
                'feeMethod' => 'DISB',
                'waiverAmount' => 0,
                'paidAmount' => 0 ,
                'TotalPaidAmount' => $this->request->get('merchant_collected_advance_amount') ? $this->request->get('merchant_collected_advance_amount') * 100 : 0,
            ]
        ];

        if ($this->request->get('liability_log') && $this->request->get('liability_hold_amount')){
            $data[] = [
                'feeCode' => 'ADVINC',
                'feeAmount' => $this->request->get('liability_hold_amount') ? $this->request->get('liability_hold_amount') * 100 : 0,
                'feeMethod' => 'DISB',
                'waiverAmount' => 0,
                'paidAmount' => 0 ,
                'TotalPaidAmount' => $this->request->get('liability_hold_amount') ? $this->request->get('liability_hold_amount') * 100 : 0,
            ];
        }

        return $data;
    }

    private function getUpdateFees(){
            return [
                [
                    'feeCategory' =>  'FC', // FC FeeOrCharges, BC - Bounce Charges, AD - Advice
                    'feeCode' =>  'DSASUB',
                    'feeAmount' =>  $this->request->get('subvention_amount') ? round($this->request->get('subvention_amount')) * 100 : 0,
                    'waiverAmount' =>  0,
                    'feeMethod' =>  'DISB',
                    'scheduleTerms' =>  0,
                    'feeBalance' =>  0,
                    'finFeeReceipts' =>  []
                ],
                [
                    'feeCategory' =>  'FC',
                    'feeCode' =>  'PROCFEE',
                    'feeAmount' =>  $this->request->get('processing_fee') ? $this->request->get('processing_fee') * 100 : 0,
                    'waiverAmount' =>  0,
                    'feeMethod' =>  'DISB',
                    'scheduleTerms' =>  0,
                    'feeBalance' =>  0,
                    'finFeeReceipts' =>  []
                ],
                [
                    'feeCategory' =>  'FC',
                    'feeCode' =>  'ADVEMI',
                    'feeAmount' =>  $this->request->get('merchant_collected_advance_amount') ? $this->request->get('merchant_collected_advance_amount') * 100 : 0,
                    'waiverAmount' =>  0,
                    'feeMethod' =>  'DISB',
                    'scheduleTerms' =>  0,
                    'feeBalance' =>  0,
                    'finFeeReceipts' =>  []
                ]
            ];
    }

    private function getBorrowerDetails(){
        return [

            "Relationship_with_Applicant" =>  "Applicant",

            "PayParty_Flag" => $this->request->get('PayParty_Flag'),

            "income_to_be_considered" => $this->request->get('income_to_be_considered'),

            "politically_exposed_person" => $this->request->get('politically_exposed_person'),

            "real_estate_broker_or_contractor" => $this->request->get('real_estate_broker_or_contractor'),

            "Monthly_Income_Self_Declared" => $this->request->get('Monthly_Income_Self_Declared'),

            "Monthly_Income_Banking" => $this->request->get('Monthly_Income_Banking'),

            "ABB_Banking" => $this->request->get('ABB_Banking'),

            "Net_Monthly_Obligation_Self_Declared" => $this->request->get('Net_Monthly_Obligation_Self_Declared'),

            "Net_Monthly_Obligation_Banking" => $this->request->get('Net_Monthly_Obligation_Banking'),

            "Banking_Start_Date" => $this->request->get('Banking_Start_Date'),

            "Banking_End_Date" => $this->request->get('Banking_End_Date'),

            "Years_of_Work_Experience" => $this->request->get('Years_of_Work_Experience'),

            "Occupation_Type" => $this->request->get('Occupation_Type'),

            "sEntityType" => $this->request->get('sEntityType'),

            "sApplGndr" =>  $this->request->get('sApplGndr'),

            "sDob" => $this->request->get('sDob'),

            "sNationality" => $this->request->get('sNationality'),

            "sMarStat" => $this->request->get('sMarStat'),

            "iNoOfDep" => $this->request->get('iNoOfDep'),

            "aAddr" =>  [

                [

                    "sLine1" => $this->request->get('sLine1'),

                    "sLine2" => $this->request->get('sLine2'),

                    "sLine3" => $this->request->get('sLine3'),

                    "sCity" => $this->request->get('sCity'),

                    "iPinCode" => $this->request->get('iPinCode'),

                    "sDistrict" => $this->request->get('sDistrict'),

                    "sState" => $this->request->get('sState'),

                    "sCountry" => $this->request->get('sCountry'),

                    "sAddrType" => $this->request->get('sAddrType'),

                    "Metro_Flag" => $this->request->get('Metro_Flag'),

                ]

            ],

            "oApplName" =>  [

                "sFirstName" => $this->request->get('sFirstName'),

                "sLastName" => $this->request->get('sLastName'),

                "sMiddleName" => $this->request->get('sMiddleName'),

                "sPrefix" => $this->request->get('sPrefix'),

                "sSuffix" => $this->request->get('sSuffix'),

            ],

            "aEmail" =>  [

                [

                    "sEmailAddr" => $this->request->get('sEmailAddr'),

                    "sEmailType" => $this->request->get('sEmailType'),

                ]

            ],

            "aKycDocs" =>  [

                [

                    "sKycName" => $this->request->get('sKycName'),

                    "PAN_NSDL_Verified" => $this->request->get('PAN_NSDL_Verified'),

                    "sKycNumber" => $this->request->get('sKycNumber'),

                ]

            ],

            "aPhone" =>  [

                [

                    "sPhoneType" =>  $this->request->get('sPhoneType'),

                    "sCountryCode" => $this->request->get('sCountryCode'),

                    "sAreaCode" =>  $this->request->get('sAreaCode'),

                    "sExt" =>  $this->request->get('sExt'),

                    "sPhoneNumber" => $this->request->get('sPhoneNumber'),

                    "sPhoneNumber1" =>  $this->request->get('sPhoneNumber1'),

                ]

            ]

        ];
    }

    private function getCoBorrowerDetails(){
        return [

            [

                "Relationship_with_Applicant" =>  $this->request->get('Co-Relationship_with_Applicant'),

                "PayParty_Flag" => $this->request->get('Co-PayParty_Flag'),

                "income_to_be_considered" => $this->request->get('Co-income_to_be_considered'),

                "politically_exposed_person" => $this->request->get('Co-politically_exposed_person'),

                "real_estate_broker_or_contractor" => $this->request->get('Co-real_estate_broker_or_contractor'),

                "Monthly_Income_Self_Declared" => $this->request->get('Co-Monthly_Income_Self_Declared'),

                "Monthly_Income_Banking" => $this->request->get('Co-Monthly_Income_Banking'),

                "ABB_Banking" => $this->request->get('Co-ABB_Banking'),

                "Net_Monthly_Obligation_Self_Declared" => $this->request->get('Co-Net_Monthly_Obligation_Self_Declared'),

                "Net_Monthly_Obligation_Banking" => $this->request->get('Co-Net_Monthly_Obligation_Banking'),

                "Banking_Start_Date" => $this->request->get('Co-Banking_Start_Date'),

                "Banking_End_Date" => $this->request->get('Co-Banking_End_Date'),

                "Years_of_Work_Experience" => $this->request->get('Co-Years_of_Work_Experience'),

                "Occupation_Type" => $this->request->get('Co-Occupation_Type'),

                "sEntityType" => $this->request->get('Co-sEntityType'),

                "sApplGndr" => $this->request->get('Co-sApplGndr'),

                "sDob" => $this->request->get('Co-sDob'),

                "sNationality" => $this->request->get('Co-sNationality'),

                "sMarStat" => $this->request->get('Co-sMarStat'),

                "iNoOfDep" => $this->request->get('Co-iNoOfDep'),

                "aAddr" =>  [

                    [

                        "sLine1" =>  $this->request->get('Co-sLine1'),

                        "sLine2" =>  $this->request->get('Co-sLine2'),

                        "sLine3" =>  $this->request->get('Co-sLine3'),

                        "sCity" =>  $this->request->get('Co-sCity'),

                        "iPinCode" =>  $this->request->get('Co-iPinCode'),

                        "sDistrict" =>  $this->request->get('Co-sDistrict'),

                        "sState" =>  $this->request->get('Co-sState'),

                        "sCountry" =>  $this->request->get('Co-sCountry'),

                        "sAddrType" => $this->request->get('Co-sAddrType'),

                        "Metro_Flag" => $this->request->get('Co-Metro_Flag'),

                    ]

                ],

                "oApplName" =>  [

                    "sFirstName" => $this->request->get('Co-sFirstName'),

                    "sLastName" => $this->request->get('Co-sLastName'),

                    "sMiddleName" => $this->request->get('Co-sMiddleName'),

                    "sPrefix" => $this->request->get('Co-sPrefix'),

                    "sSuffix" => $this->request->get('Co-sSuffix'),

                ],

                "aEmail" =>  [

                    [

                        "sEmailAddr" => $this->request->get('Co-sEmailAddr'),

                        "sEmailType" => $this->request->get('Co-sEmailType'),

                    ]

                ],

                "aKycDocs" =>  [

                    [

                        "sKycName" => $this->request->get('Co-sKycName'),

                        "PAN_NSDL_Verified" => $this->request->get('Co-PAN_NSDL_Verified'),

                        "sKycNumber" => $this->request->get('Co-sKycNumber'),

                    ]

                ],

                "aPhone" =>  [

                    [

                        "sPhoneType" => $this->request->get('Co-sPhoneType'),

                        "sCountryCode" => $this->request->get('Co-sCountryCode'),

                        "sAreaCode" =>  $this->request->get('Co-sAreaCode'),

                        "sExt" =>  $this->request->get('Co-sExt'),

                        "sPhoneNumber" => $this->request->get('Co-sPhoneNumber'),

                        "sPhoneNumber1" =>  $this->request->get('Co-sPhoneNumber1'),
                    ]

                ]

            ]

        ];
    }

    private function callBRE(){
        if (!$this->dataInitializeBRE()){
            return false;
        }

        return [

            "values" =>  [

                "input" =>  [

                    "Unique_Lead_ID" =>  $this->request->get('id'),

                    "datetime_stamp" => $this->request->get('datetime_stamp'),

                    "Partner_ID" =>  $this->request->get('Partner_ID'),

                    "Scheme_ID" =>  $this->request->get('Scheme_ID'),

                    "Loan_Type" =>  $this->request->get('Loan_Type'),

                    "Institute_Name" => $this->request->get('Institute_Name'),

                    "Course_Name" =>  $this->request->get('Course_Name'),

                    "Course_Duration" =>  $this->request->get('Course_Duration'),

                    "Requested_Loan_Amount" =>  $this->request->get('Requested_Loan_Amount'),

                    "Requested_Loan_Tenure" =>  $this->request->get('Requested_Loan_Tenure'),

                    "Annual_Rate_of_Interest_Reducing" =>  $this->request->get('Annual_Rate_of_Interest_Reducing'),

                    "Number_of_Existing_Avanse_Loans" =>  $this->request->get('Number_of_Existing_Avanse_Loans'),

                    "oApplicant" =>  $this->getBorrowerDetails(),

                    "aCoApplicant" =>  $this->getCoBorrowerDetails()

                ]

            ]

        ];
    }

    private function updateFinancials(){

        if (!$this->dataInitialize()){
            return false;
        }

        $avanseFinance = AvanseCreateFinance::where('application_id', $this->request->get('id'))->first(['id', 'finReference']);
        if (!isset($avanseFinance->id)){
            $this->error[] = 'Please create loan for avanse before creating disbursement instruction';
            return false;
        }

        $avanseProcesses = new AvanseProcesses($this->request);

        return [
            'financeSchedule' =>  [
                'financeDetail' =>  [
                    'finAmount' =>  round($avanseProcesses->getNetAmountAsPerAvanse()) * 100,
                    'finAssetValue' =>  round($avanseProcesses->getNetAmountAsPerAvanse()) * 100,
                    'finStartDate' =>  date('c', Carbon::createFromFormat('d/m/Y',$this->request->get('payment_transfer_date'))->timestamp),
                    'allowGrcPeriod' =>  false, //Grace true if customer wants to start the repayment from 2-3 months later
                    'grcTerms' =>  '',
                    'grcPeriodEndDate' =>  null,
                    'grcBaseRate' =>  '',
                    /*'grcPftRate' =>  null,
                    'grcMargin' =>  null,
                    'grcPftFrq' =>  null, //M0004
                    'grcPftRvwFrq' =>  null, //M0004
                    'grcCpzFrq' =>  null, //M0004*/
                    'nextGrcPftDate' =>  null,
                    'nextGrcPftRvwDate' =>  null,
                    'nextGrcCpzDate' =>  null,
                    'allowGrcRepay' =>  false,
                    'grcSchdMthd' =>  null, //'PFT'
                    'grcMaxAmount' =>  0,
                    'grcAdvBaseRate' =>  null,
                    'numberOfTerms' =>  $this->request->get('tenure'),
                    'reqRepayAmount' =>  0.0,
                    'repayBaseRate' =>  '',
                    'repayMargin' =>  0,
                    'scheduleMethod' =>  'EQUAL',
                    'repayRateBasis' =>  'R',
                    'repayPftFrq' =>  '', //M0004
                    'repayFrq' =>  '', //M0004
                    'repayRvwFrq' =>  '', //M0004
                    'repayCpzFrq' =>  '', //M0004
                    'nextRepayDate' =>  null,
                    'nextRepayPftDate' =>  null,
                    'nextRepayRvwDate' =>  null,
                    'nextRepayCpzDate' =>  null,
                    'maturityDate' =>  null,
                    'repayPftRate' =>  $this->request->get('interest_rate'),
                    'alwBpiTreatment' =>  true,
                    'dftBpiTreatment' =>  null, // D Insurance related
                    'grcAdvType' =>  null,
                    'grcAdvTerms' =>  null,
                    'advType' =>  null,
                    'advTerms' =>  null,
                    'advStage' =>  null,
                    'grcRateBasis' =>  'R'
                ],
                'fees' => $this->getUpdateFees(),
                'extendedDetails' => $this->getExtendedDetails(),
            ],
            'finReference' =>  $avanseFinance->finReference
        ];

    }

    private function dataInitializeBRE(){
        $application = ConsumerApplication::with('creditReport','merchant', 'finBitData', 'foir', 'finBitDataCoBorrower', 'finBitDataBorrower', 'products','category','bank_details','application_element','application_element.merchant_center')->where('id', $this->request->get('id'))->first();

        if (!$application->activeOffer){
            $this->error[] = 'Offer is not assigned';
            return false;
        }
        $names = explode(' ',$application->name);
        $first_name = $names[0];
        $last_name = end($names);

        $co_names = explode(' ',$application->co_applicant_name);
        $co_first_name = $co_names[0];
        $co_last_name = end($co_names);

        if(isset($application->employee_status)){
            if($application->employee_status == 'SALARIED'){
                $occupation_type = 'Salaried';
            }
            if($application->employee_status == 'Self Employed - Business'){
                $occupation_type = 'SENP';
            }
            if($application->employee_status == 'Self Employed - Professional'){
                $occupation_type = 'SEP';
            }
        }
        if(isset($application->co_applicant_employee_status)){
            if($application->co_applicant_employee_status == 'SALARIED'){
                $co_occupation_type = 'Salaried';
            }
            if($application->co_applicant_employee_status == 'Self Employed - Business'){
                $co_occupation_type = 'SENP';
            }
            if($application->co_applicant_employee_status == 'Self Employed - Professional'){
                $co_occupation_type = 'SEP';
            }
        }
        if(isset($application->employee_status)){
            if($application->employee_status != 'SALARIED'){
                $entity_type = '';
            }else{
                $entity_type = 'Not Applicable';
            }
        }
        if(isset($application->co_applicant_employee_status)){
            if($application->co_applicant_employee_status != 'SALARIED'){
                $co_entity_type = '';
            }else{
                $co_entity_type = 'Not Applicable';
            }
        }

        // $kyc_details = $application->kycdetails ? json_decode($application->kycdetails->response) : null;
        // $co_kyc_details = $application->co_kycdetails ? json_decode($application->co_kycdetails->response) : null;
        // $app_kyc_name = $app_kyc_number = $coapp_kyc_name = $coapp_kyc_number = null;
        // if(isset($kyc_details)){
        //     foreach($kyc_details as $kyc){
        //         if($kyc->document_type = 'pan'){
        //             $app_kyc_name = "PAN";
        //             $app_kyc_number = $kyc->id_number ? $kyc->id_number : null;
        //             break;
        //         }
        //     }
        // }
        // if(isset($co_kyc_details)){
        //     foreach($co_kyc_details as $kyc){
        //         if($kyc->document_type = 'pan'){
        //             $coapp_kyc_name = "PAN";
        //             $coapp_kyc_number = $kyc->id_number ? $kyc->id_number : null;
        //             break;
        //         }
        //     }
        // }

        if(isset($application->creditReport)){
            $creditReport = $application->creditReport->reverse();
            foreach($creditReport as $credit){
                if(isset($credit->panValidation) && $credit->applicant_type == 1){
                    if(!isset($app_pan)){
                        $app_kyc = json_decode(str_replace('sch:', '', $credit->panValidation));
                        if($credit->panVendor == "decentro"){
                            $app_pan = $app_kyc->kycResult->idNumber;
                        }elseif($credit->panVendor == "equifax" || $credit->panVendor == ''){
                            $app_pan = $app_kyc->PAN;
                        }
                    }
                }elseif(isset($credit->panValidation) && $credit->applicant_type == 2){
                    if(!isset($coapp_pan)){
                        $coapp_kyc = json_decode(str_replace('sch:', '', $credit->panValidation));
                        if($credit->panVendor == "decentro"){
                            $coapp_pan = $coapp_kyc->kycResult->idNumber;
                        }elseif($credit->panVendor == "equifax" || $credit->panVendor == ''){
                            $coapp_pan = $coapp_kyc->PAN;
                        }
                    }
                }
            }
        }

        if(isset($application->dob)){
            list($year, $month, $day) = explode("-", $application->dob);
            $app_dob = $day.$month.$year;
        }
        if(isset($application->co_applicant_dob)){
            list($year, $month, $day) = explode("-", $application->co_applicant_dob);
            $co_app_dob = $day.$month.$year;
        }
        $applicant_obligation = 0;
        $co_applicant_obligation = 0;
        $grade = new GradeController($this->request);
        $grade->getFOIRByID($this->request->id, false, 1);
        if(isset($grade->total_existing_emi)){
            // $applicant_obligation = (($grade->credit_limit * 5) / 100) + $grade->total_existing_emi;        //with credit card
            $applicant_obligation = $grade->total_existing_emi;                                                //without credit card
        }
        $grade->getFOIRByID($this->request->id, false, 2);
        if(isset($grade->total_existing_emi)){
            // $co_applicant_obligation = (($grade->credit_limit * 5) / 100) + $grade->total_existing_emi;      //with credit card
            $co_applicant_obligation = $grade->total_existing_emi;                                              //without credit card
        }
        // if(isset($application->foir)){
            // foreach($application->foir as $foir){
            //     if($foir->applicant_type == 1){
            //         if($foir->DateClosed == null && $foir->isOpened == 1){
            //             $applicant_obligation += intval($foir->InstallmentAmountNEW);
            //         }
            //     }
            //     if($foir->applicant_type == 2){
            //         if($foir->DateClosed == null && $foir->isOpened == 1){
            //             $co_applicant_obligation += intval($foir->InstallmentAmountNEW);
            //         }
            //     }
            // }
        // }
        if(isset($application->finBitData)){
            if($application->finBitData->applicant_type == 1){
                list($day, $month, $year) = explode("/", $application->finBitData->period_from);
                $banking_start_date = $day.$month.$year;
                list($day, $month, $year) = explode("/", $application->finBitData->period_too);
                $banking_end_date = $day.$month.$year;
            }
            if($application->finBitData->applicant_type == 2){
                list($day, $month, $year) = explode("/", $application->finBitData->period_from);
                $co_banking_start_date = $day.$month.$year;
                list($day, $month, $year) = explode("/", $application->finBitData->period_too);
                $co_banking_end_date = $day.$month.$year;
            }
        }
        // if(isset($application->application_element)){
        //     list($month, $year) = explode("|", $application->application_element->duration);
        //     $year = (int)$year;
        //     $month = (int)$month;
        //     $course_duration = ($year * 12 + $month);
        // }

        return $this->request->merge([
            'datetime_stamp' => null,
            'Partner_ID' => "CREDIT FAIR",
            'Scheme_ID' => "CREDIT_FIAR_DIGCF",
            'Loan_Type' =>  $application->category ? $application->category->name : null,
            'Institute_Name' => isset($application->merchant) ? $application->merchant->merchant_name : null,
            'Course_Name' => $application->application_element ? $application->application_element->product_name : null,
            'Course_Duration' => 0,
            'Requested_Loan_Amount' => $application->loan_amount ? (int)$application->loan_amount : null,
            'Requested_Loan_Tenure' => $application->offer && $application->offer->tenure ? (int)$application->offer->tenure : null,
            'Annual_Rate_of_Interest_Reducing' => $application->offer && $application->offer->interest_rate ? (int)$application->offer->interest_rate : null,
            'Number_of_Existing_Avanse_Loans' => null,
            // Applicant--------------------------------------------------------------------------------------------------------------

            'PayParty_Flag' => "Yes",
            'income_to_be_considered' => "Yes",
            'politically_exposed_person' => "No",
            'real_estate_broker_or_contractor' => $application->application_element && $application->application_element->negative_profile > 0 ? 'Yes' : 'No',
            'Monthly_Income_Self_Declared' => $application->monthly_income ? (int)$application->monthly_income : null,
            'Monthly_Income_Banking' => null,
            // 'ABB_Banking' => $application->finBitDataBorrower ? (int)str_replace(',', '', $application->finBitDataBorrower->average_balance): null,
            'ABB_Banking' => null,
//            'Monthly_Income_Self_Declared' => $application->monthly_income ? (int)$application->monthly_income : null,
//            'Monthly_Income_Banking' => $application->monthly_income ? (int)$application->monthly_income : null,
//            'ABB_Banking' => $application->finBitDataBorrower ? (int)str_replace(',', '', $application->finBitDataBorrower->average_balance): null,
            'Net_Monthly_Obligation_Self_Declared' => null,
            // 'Net_Monthly_Obligation_Banking' => $applicant_obligation > 0 ? (int)($applicant_obligation) : null,
            'Net_Monthly_Obligation_Banking' => null,
//            'Net_Monthly_Obligation_Banking' => null,
//            // 'Net_Monthly_Obligation_Banking' => $applicant_obligation > 0 ? (int)($applicant_obligation) : null,
            'Banking_Start_Date' => isset($banking_start_date) ? $banking_start_date : null,
            'Banking_End_Date' => isset($banking_end_date) ? $banking_end_date : null,
            // 'Banking_Start_Date' => null,
            // 'Banking_End_Date' => null,
            'Years_of_Work_Experience' => $application->experience ? strval(round($application->experience / 12, 2)) : null,
            'Occupation_Type' => isset($occupation_type) ? $occupation_type : null,
            'sEntityType' => isset($entity_type) ? $entity_type : null,
            'sApplGndr' => $application->gender ? ucfirst($application->gender) : null,
            'sDob' => isset($app_dob) ? $app_dob : null,
            'sNationality' => "Indian",
            'sMarStat' => null,
            'iNoOfDep' => null,

            // address

            'sLine1' => isset($application->current_address_line_1) ? $application->current_address_line_1 : null,
            'sLine2' => null,
            'sLine3' => null,
            'sCity' => isset($application->current_address_city) ? $application->current_address_city : null,
            'iPinCode' => isset($application->current_address_pincode) ? $application->current_address_pincode : null,
            'sDistrict' => null,
            'sState' => isset($application->current_address_state) ? $application->current_address_state : null,
            'sCountry' => 'INDIA',
            'sAddrType' => 'RESIDENCE',
            'Metro_Flag' => "Yes",

            // names

            'sFirstName' => isset($first_name) ? $first_name : null,
            'sLastName' => isset($last_name) ? $last_name : null,
            'sMiddleName' => null,
            'sPrefix' => null,
            'sSuffix' => null,

            // email

            'sEmailAddr' => isset($application->email) ? wall_decrypt($application->email) : null,
            'sEmailType' => "Personal",

            //kyc docs

            'PAN_NSDL_Verified' => "Yes",
            'sKycName' => isset($app_pan) ? "PAN" : null,
            'sKycNumber' => isset($app_pan) ? $app_pan : null,

            // phone

            'sPhoneType' => "MOBILE",
            'sAreaCode' => null,
            'sCountryCode' => "+91",
            'sExt' => null,
            'sPhoneNumber' => isset($application->mobile_number) ? wall_decrypt($application->mobile_number) : null,
            'sPhoneNumber1' => null,


            // Co-applicant -------------------------------------------------------------------------------------------------------

            'Co-Relationship_with_Applicant' => $application->co_applicant_relationship ? $application->co_applicant_relationship : null,
            'Co-PayParty_Flag' => "Yes",
            'Co-income_to_be_considered' => "Yes",
            'Co-politically_exposed_person' => "No",
            'Co-real_estate_broker_or_contractor' => $application->application_element && $application->application_element->negative_profile > 0 ? 'Yes' : 'No',
            'Co-Monthly_Income_Self_Declared' => $application->co_applicant_monthly_income ? (int)$application->co_applicant_monthly_income : null,
            'Co-Monthly_Income_Banking' => null,
            // 'Co-ABB_Banking' => $application->finBitDataCoBorrower ? (int)str_replace(',', '', $application->finBitDataCoBorrower->average_balance): null,
            'Co-ABB_Banking' => null,
//            'Co-Monthly_Income_Self_Declared' => $application->co_applicant_monthly_income ? (int)$application->co_applicant_monthly_income : null,
//            'Co-Monthly_Income_Banking' => $application->co_applicant_monthly_income ? (int)$application->co_applicant_monthly_income : null,
//            'Co-ABB_Banking' => $application->finBitDataCoBorrower ? (int)str_replace(',', '', $application->finBitDataCoBorrower->average_balance): null,
            // 'Co-ABB_Banking' => null,
            'Co-Net_Monthly_Obligation_Self_Declared' => null,
            // 'Co-Net_Monthly_Obligation_Banking' => $co_applicant_obligation > 0 ? (int)$co_applicant_obligation : null,
            'Co-Net_Monthly_Obligation_Banking' => null,
//            'Co-Net_Monthly_Obligation_Banking' => null,
//            // 'Co-Net_Monthly_Obligation_Banking' => $co_applicant_obligation > 0 ? (int)$co_applicant_obligation : null,
            'Co-Banking_Start_Date' => isset($co_banking_start_date) ? $co_banking_start_date : null,
            'Co-Banking_End_Date' => isset($co_banking_end_date) ? $co_banking_end_date : null,
            // 'Co-Banking_Start_Date' => null,
            // 'Co-Banking_End_Date' => null,
            'Co-Years_of_Work_Experience' => $application->co_applicant_experience ?  strval(round($application->co_applicant_experience / 12, 2)) : null,
            'Co-Occupation_Type' => isset($co_occupation_type) ? $co_occupation_type : null,
            'Co-sEntityType' => isset($co_entity_type) ? $co_entity_type : null,
            'Co-sApplGndr' => isset($application->co_applicant_gender) ? ucfirst($application->co_applicant_gender) : null,
            'Co-sDob' => isset($co_app_dob) ? $co_app_dob : null,
            'Co-sNationality' => "Indian",
            'Co-sMarStat' => null,
            'Co-iNoOfDep' => null,

            // address

            'Co-sLine1' => $application->co_applicant_address_line_1 ? $application->co_applicant_address_line_1 : null,
            'Co-sLine2' => null,
            'Co-sLine3' => null,
            'Co-sCity' => $application->co_applicant_address_city ? $application->co_applicant_address_city : null,
            'Co-iPinCode' => $application->co_applicant_address_pincode ? $application->co_applicant_address_pincode : null,
            'Co-sDistrict' => null,
            'Co-sState' => $application->co_applicant_address_state ? $application->co_applicant_address_state : null,
            'Co-sCountry' => "INDIA",
            'Co-sAddrType' => 'RESIDENCE',
            'Co-Metro_Flag' => "Yes",

            // name

            'Co-sFirstName' => isset($co_first_name) ? $co_first_name : null,
            'Co-sLastName' => isset($co_last_name) ? $co_last_name : null,
            'Co-sMiddleName' => null,
            'Co-sPrefix' => null,
            'Co-sSuffix' => null,

            // email

            'Co-sEmailAddr' => isset($application->email) ? wall_decrypt($application->email) : null,
            'Co-sEmailType' => "Personal",

            //kyc docs

            'Co-PAN_NSDL_Verified' => "Yes",
            'Co-sKycName' => isset($coapp_pan) ? "PAN" : null,
            'Co-sKycNumber' => isset($coapp_pan) ? $coapp_pan : null,

            // phone

            'Co-sPhoneType' => "MOBILE",
            'Co-sAreaCode' => null,
            'Co-sCountryCode' => "+91",
            'Co-sExt' => null,
            'Co-sPhoneNumber' => isset($application->mobile_number) ? wall_decrypt($application->mobile_number) : null,
            'Co-sPhoneNumber1' => null

        ]);
    }

    private function dataInitialize(){
        $application = ConsumerApplication::with('documents','emi','proFormaInvoice','checkmandate','bank_details','avanse', 'avanseByApplicant','merchant_bank_details','merchant','activeOffer','emi_payment','application_element','application_element.merchant_center','lender.banks')->where('id', $this->request->get('id'))->first();

        if(!$application->avanse && !$application->avanseByApplicant){
            $this->error[] = 'Please create customer for avanse before creating loan';
            return false;
        }

        if (!$application->activeOffer){
            $this->error[] = 'Offer is not assigned';
            return false;
        }else{
            if ($application->activeOffer->advance_emi && $application->activeOffer->advance_type != 'fixed_amount'){
                /*$this->error[] = 'Advance EMI should be in amount';
                return false;*/
            }
        }

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

        if (!$application->emi_payment){
            $this->error[] = 'EMI schedule is not generated';
            return false;
        }

        $nextRepayDate = null;
        foreach ($application->emi_payment as $key => $payment){
            if ($key){
                $nextRepayDate = $payment->emi_date;
                break;
            }
        }

        if (!$nextRepayDate){
            $nextRepayDate = Carbon::parse($application->emi->emi_date)->addMonth(1)->toDateString();
        }

        $charge_subvention_remaining_amount = $application->merchant && $application->merchant->charge_subvention_remaining_amount ? 1 : 0;
        $downPayment = 0;
        if($charge_subvention_remaining_amount){
            $downPayment = $application->emi->upfront_from_customer;
        }
        $subvention_amount = (($application->approved_amount - $downPayment)*$application->emi->subvention)/100;

        $multiStageDisbursement = (new MultiStageDisbursement())->getSubventionInvoiceAmount($application, $subvention_amount);
        $subvention_amount = isset($multiStageDisbursement['subvention_amount']) ? $multiStageDisbursement['subvention_amount'] : $multiStageDisbursement;


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

        if ($subvention_amount) {
            $gstDetailsSubvention = (new ConsumerDocument(new Request()))->getGSTDetails(
                [
                    'amount' => $subvention_amount,
                    'state' => $application->merchant->state
                ]
            ,0);
        }

        /*if ($application->emi->processing_fee && $processing_fee_by_merchant) {
            $gstDetailsProcessing = (new ConsumerDocument(new Request()))->getGSTDetails(
                [
                    'amount' => $application->emi->processing_fee,
                    'state' => (isset($application->permanent_address_state) && !empty($application->permanent_address_state)) ? $application->permanent_address_state : (isset($application->current_address_state) && !empty($application->current_address_state) ? $application->current_address_state : '')
                ]
            );
        }*/

        //$disbursementController = new DisbursementController($this->request);
        //$net_disbursement_amount = $disbursementController->getDisbursementAmount($application)['net_disbursement'];

        $avanseCustomer = AvanseCreateCustomer::where('applicant_id', $application->applicant_id)->first();
        if($application->co_applicant_id) {
            $avanseCoCustomer = AvanseCreateCustomer::where('applicant_id', $application->co_applicant_id)->first();
        }

        $tenure = $application->activeOffer->advance_type == 'emi' && !$application->proFormaInvoice->merchant_collected_advance_amount && $application->emi ? ($application->emi->tenure - $application->emi->advance_emi) : $application->emi->tenure;

        $interest_rate = $application->activeOffer->interest_rate;
        $avanseProcesses = new AvanseProcesses($this->request);
        if($application->activeOffer->interest_type_id != 2){
            $interest_rate = $avanseProcesses->flatBalanceToReducing($application->emi->remaining_emi, $application, $avanseProcesses->getNetAmountAsPerAvanse());
        }

        $liabilityLog = LiabilityLog::where('application_id', $this->request->get('id'))->first(['id', 'liability_percent']);


        $hold_amount = $this->getLiabilityHoldAmount($avanseProcesses, $liabilityLog);


        //$this->mandateApproval();
        return $this->request->merge([
            'name' => $application->name,
            'phone' => $application->mobile_number,
            'tenure' => $tenure,
            'documents' => $application->documents,
            'mandate' => null,$application->checkmandate,
            'bank_details' => $application->bank_details,
            'merchant_bank_details' => $application->merchant_bank_details,
            'merchant' => $application->merchant,
            'offer' => $application->activeOffer,
            'interest_rate' => $interest_rate,
            'cif' => isset($avanseCustomer->cif) && $avanseCustomer->cif ? $avanseCustomer->cif : '',// $application->avanse ? $application->avanse->cif : ($application->avanseByApplicant ? $application->avanseByApplicant->cif : ''),
            'co_cif' => isset($avanseCoCustomer->cif) && $avanseCoCustomer->cif ? $avanseCoCustomer->cif : '',//$application->coAvanse ? $application->coAvanse->cif : ($application->avanseByCoApplicant ? $application->avanseByCoApplicant->cif : ''),
            'emi_date' => $application->emi->emi_date,
            'nextRepayDate' => $nextRepayDate,
            'advance_emi' => $application->emi->advance_emi,
            'co_applicant_relationship' => $application->co_applicant_relationship,
            'co_applicant_name' => $application->co_applicant_name,
            //'net_disbursement_amount' => $net_disbursement_amount,
            'address' => $application->current_address_line_1,
            'current_address_city' => $application->current_address_city,
            'current_address_landmark' => $application->current_address_landmark,
            'current_address_pincode' => $application->current_address_pincode,
            'payment_transfer_date' => $application->application_element->payment_transfer_date,
            'admission_status' => $application->application_element ? $application->application_element->admission_status : null,
            'liability_hold_amount' => $hold_amount,
            'subvention_amount' => isset($gstDetailsSubvention) && isset($gstDetailsSubvention[0]['net_amount']) ? $gstDetailsSubvention[0]['net_amount'] : 0,
            'processing_fee' => isset($gstDetailsProcessing) && isset($gstDetailsProcessing[0]['net_amount']) ? $gstDetailsProcessing[0]['net_amount'] : 0,
            'merchant_collected_advance_amount' => $application->activeOffer->advance_type == 'emi' && $merchant_collected_advance_amount && $application->emi ? $application->emi->upfront_from_customer : 0,
            'liability_log' => $liabilityLog->id ?? 0
        ]);
    }

    public function getLiabilityHoldAmount(AvanseProcesses $avanseProcesses, $liabilityLog){

        return ((isset($liabilityLog->liability_percent) ? $liabilityLog->liability_percent : 0)  * $avanseProcesses->getNetAmountAsPerAvanse(0,0))/100;
    }

    public function saveResponse(AvanseFinance $avanseFinance, $response, $getService = null){

        //$response = json_decode('{"finReference":"DELDP00205637","stp":false,"financeSchedule":{"financeDetail":{"applicationNo":"5517","cif":"399561","finType":"SFFCREFA","finCcy":"INR","finBranch":"DEL","profitDaysBasis":"30E/360","finAmount":5000000,"finAssetValue":5000000,"downPayBank":0,"downPaySupl":0,"finRepayMethod":"NACH","finStartDate":"2021-07-07","allowGrcPeriod":false,"tdsApplicable":false,"manualSchedule":false,"planDeferCount":0,"stepFinance":false,"alwManualSteps":false,"grcTerms":0,"grcPeriodEndDate":"2021-07-07","grcRateBasis":"#","grcPftRate":0,"grcMargin":0,"grcProfitDaysBasis":"30E/360","nextGrcPftRvwDate":"2021-07-07","nextGrcCpzDate":"2021-07-07","allowGrcRepay":false,"grcSchdMthd":"EQUAL","grcMinRate":0,"grcMaxRate":0,"grcMaxAmount":0,"grcAdvPftRate":0,"grcAdvMargin":0,"numberOfTerms":8,"reqRepayAmount":0,"repayRateBasis":"R","repayPftRate":0,"repayMargin":0,"scheduleMethod":"EQUAL","repayFrq":"M0007","nextRepayDate":"2021-08-07","repayPftFrq":"M0007","nextRepayPftDate":"2021-08-07","nextRepayRvwDate":"2022-03-07","nextRepayCpzDate":"2022-03-07","maturityDate":"2022-03-07","finRepayPftOnFrq":false,"repayMinRate":0,"repayMaxRate":0,"repayAdvPftRate":0,"repayAdvMargin":0,"supplementRent":0,"increasedCost":0,"dsaCode":"7001099","accountsOfficer":7000613,"dmaCode":"7000573","referralId":"DMADSA","quickDisb":false,"unPlanEMIHLockPeriod":0,"unPlanEMICpz":false,"reAgeCpz":false,"maxUnplannedEmi":0,"maxReAgeHolidays":0,"alwBpiTreatment":false,"dftBpiTreatment":"N","planEMIHAlw":false,"planEMIHMethod":"","planEMIHMaxPerYear":0,"planEMIHMax":0,"planEMIHLockPeriod":0,"planEMICpz":false,"grcAdvTerms":0,"advTerms":0,"fixedRateTenor":0,"fixedTenorRate":0,"finCurrAssetValue":5000000},"fees":[{"feeCategory":"FC","feeCode":"DSASUB","feeAmount":0,"waiverAmount":0,"paidAmount":0,"feeMethod":"DISB","scheduleTerms":0,"feeBalance":0,"finFeeReceipts":[]},{"feeCategory":"FC","feeCode":"PROCFEE","feeAmount":867,"waiverAmount":0,"paidAmount":867,"feeMethod":"DISB","scheduleTerms":0,"feeBalance":0,"finFeeReceipts":[]}],"feeDues":[],"insurance":[],"step":[],"schedules":[{"schDate":"2021-07-07","pftAmount":0,"schdPft":0,"schdPftPaid":0,"schdPri":0,"schdPriPaid":0,"feeSchd":0,"tDSAmount":0,"totalAmount":0,"endBal":5000000,"limitDrop":0,"dropLineLimit":0,"availableLimit":0},{"schDate":"2021-08-07","pftAmount":29200,"schdPft":29200,"schdPftPaid":0,"schdPri":612300,"schdPriPaid":0,"feeSchd":0,"tDSAmount":0,"totalAmount":641500,"endBal":4387700,"limitDrop":0,"dropLineLimit":0,"availableLimit":0},{"schDate":"2021-09-07","pftAmount":25600,"schdPft":25600,"schdPftPaid":0,"schdPri":615900,"schdPriPaid":0,"feeSchd":0,"tDSAmount":0,"totalAmount":641500,"endBal":3771800,"limitDrop":0,"dropLineLimit":0,"availableLimit":0},{"schDate":"2021-10-07","pftAmount":22000,"schdPft":22000,"schdPftPaid":0,"schdPri":619500,"schdPriPaid":0,"feeSchd":0,"tDSAmount":0,"totalAmount":641500,"endBal":3152300,"limitDrop":0,"dropLineLimit":0,"availableLimit":0},{"schDate":"2021-11-07","pftAmount":18400,"schdPft":18400,"schdPftPaid":0,"schdPri":623100,"schdPriPaid":0,"feeSchd":0,"tDSAmount":0,"totalAmount":641500,"endBal":2529200,"limitDrop":0,"dropLineLimit":0,"availableLimit":0},{"schDate":"2021-12-07","pftAmount":14700,"schdPft":14700,"schdPftPaid":0,"schdPri":626800,"schdPriPaid":0,"feeSchd":0,"tDSAmount":0,"totalAmount":641500,"endBal":1902400,"limitDrop":0,"dropLineLimit":0,"availableLimit":0},{"schDate":"2022-01-07","pftAmount":11100,"schdPft":11100,"schdPftPaid":0,"schdPri":630400,"schdPriPaid":0,"feeSchd":0,"tDSAmount":0,"totalAmount":641500,"endBal":1272000,"limitDrop":0,"dropLineLimit":0,"availableLimit":0},{"schDate":"2022-02-07","pftAmount":7400,"schdPft":7400,"schdPftPaid":0,"schdPri":634100,"schdPriPaid":0,"feeSchd":0,"tDSAmount":0,"totalAmount":641500,"endBal":637900,"limitDrop":0,"dropLineLimit":0,"availableLimit":0},{"schDate":"2022-03-07","pftAmount":3700,"schdPft":3700,"schdPftPaid":0,"schdPri":637900,"schdPriPaid":0,"feeSchd":0,"tDSAmount":0,"totalAmount":641600,"endBal":0,"limitDrop":0,"dropLineLimit":0,"availableLimit":0}],"planEMIHmonths":[],"planEMIHDates":[],"overdueCharges":[],"summary":{"effectiveRateOfReturn":7.171928809,"totalGracePft":0,"totalGraceCpz":0,"totalGrossGrcPft":0,"totalCpz":0,"totalProfit":132100,"totalRepayAmt":5132100,"feeChargeAmount":0,"numberOfTerms":8,"loanTenor":8,"maturityDate":"2022-03-07","firstEmiAmount":641500,"nextSchDate":"2021-08-07","nextRepayAmount":641500,"futureInst":8,"futureTenor":7,"firstInstDate":"2021-08-07","paidTotal":0,"paidPri":0,"paidPft":0,"lastRepayDate":"2021-07-07","outstandingTotal":5132100,"outstandingPri":5000000,"outstandingPft":132100,"overdueTotal":0,"overduePri":0,"overduePft":0,"overdueInst":0,"overdueCharges":[],"advPaymentAmount":0,"finActiveStatus":"A","fullyDisb":false},"vas":[],"outstandingPri":0,"isUpfrontAuto":false},"collaterals":[],"transactions":[],"returnStatus":{"returnCode":"0000","returnText":"Success"},"collateralOverride":false,"receiptId":0}');

        if($getService == 'callBRE'){

            if($response){
                try {

                    $partner_registration = $response->Partner_Registration;
                    $unique_lead_id = $response->Unique_Lead_Id;
                    $decision = $response->Decision;
                    $criteria_bureau_score_cutoff = $response->Criteria_Bureau_Score_Cutoff;
                    $criteria_bureau_90dpd_12mon = $response->Criteria_Bureau_90dpd_12mon;
                    $criteria_bureau_overdue = $response->Criteria_Bureau_Overdue;
                    $criteria_bureau_derog = $response->Criteria_Bureau_Derog;
                    $criteria_geo_location = $response->Criteria_Geo_Location;
                    $criteria_min_age = $response->Criteria_Min_Age;
                    $criteria_max_age = $response->Criteria_Max_Age;
                    $criteria_max_requested_loan_amount = $response->Criteria_Max_Requested_Loan_Amount;
                    $criteria_min_requested_loan_amount = $response->Criteria_Min_Requested_Loan_Amount;
                    $criteria_max_requested_loan_tenure = $response->Criteria_Max_Requested_Loan_Tenure;
                    $criteria_min_requested_loan_tenure = $response->Criteria_Min_Requested_Loan_Tenure;
                    $criteria_income = $response->Criteria_Income;
                    $criteria_abb = $response->Criteria_ABB;
                    $criteria_politically_exposed_profile = $response->Criteria_Politically_Exposed_Profile;
                    $criteria_real_estate_profile = $response->Criteria_Real_Estate_Profile;
                    $created_at = Carbon::now()->toDateTimeString();

                    $avanse_bre_decision = new AvanseBRE();
                    $avanse_bre_decision->fill([
                        'partner_registration' => $partner_registration,
                        'decision' => $decision,
                        'criteria_bureau_score_cutoff' => $criteria_bureau_score_cutoff,
                        'criteria_bureau_90dpd_12mon' => $criteria_bureau_90dpd_12mon,
                        'criteria_bureau_overdue' => $criteria_bureau_overdue,
                        'criteria_bureau_derog' => $criteria_bureau_derog,
                        'criteria_geo_location' => $criteria_geo_location,
                        'criteria_min_age' => $criteria_min_age,
                        'criteria_max_age' => $criteria_max_age,
                        'criteria_max_requested_loan_amount' => $criteria_max_requested_loan_amount,
                        'criteria_min_requested_loan_amount' => $criteria_min_requested_loan_amount,
                        'criteria_max_requested_loan_tenure' => $criteria_max_requested_loan_tenure,
                        'criteria_min_requested_loan_tenure' => $criteria_min_requested_loan_tenure,
                        'criteria_income' => $criteria_income,
                        'criteria_abb' => $criteria_abb,
                        'criteria_politically_exposed_profile' => $criteria_politically_exposed_profile,
                        'criteria_real_estate_profile' => $criteria_real_estate_profile,
                        'created_at' => $created_at,
                        'application_id' => $unique_lead_id
                    ]);

                    $avanse_bre_decision->save();
                    if($partner_registration == "Registration_Unsuccessful"){
                        $message = "Partner Registration_Unsuccessful";
                        return $message;
                    }
                    if($decision == "Hard Declined"){
                        $message = "Hard Decline policy hit, 
                        application not flown forward";
                        return $message;
                    }
                    if($decision == "Approved"){
                        return true;
                    }
                    if($decision == "Refer"){
                        $message = "Refer for NTC case, application to be 
                        resent with NTC Challenger Strategy";
                        return $message;
                    }
                    if($decision == "Declined"){
                        $message = "Declined as per Bureau or NTC 
                        policies";
                        return $message;
                    }
                    if($decision == "Experian Timed Out"){
                        $message = "Experian Credit Bureau did 
                        not respond and application needs to be resent";
                        return $message;
                    }
                }catch (\Exception $exception){
                    (new Slack(new Request(['title' => 'Request Error', 'fields' => ['response' => $response, 'request' => json_encode($this->request->all()), 'message' => $exception->getMessage(), 'line' => $exception->getLine(), 'trace' => $exception->getTraceAsString()]])))->send();
                    $avanseFinance->error = $exception->getMessage();
                    return false;
                }

            }else{
                return false;
            }
        }

        if ($getService){
            $avanseFinance->error = 'Error';
            return false;
        }

        if ($response){
            try {

                if (!isset($response->returnStatus->returnCode) || $response->returnStatus->returnCode != '0000'){
                    $avanseFinance->error = isset($response->returnStatus->returnText) ? $response->returnStatus->returnText : 'Avanse: Incomplete data found!';
                    return false;
                }

                $finReference = $response->finReference;
                $stp = $response->stp;
                $financeDetail = $response->financeSchedule->financeDetail;
                $fees = $response->financeSchedule->fees;
                $feeDues = $response->financeSchedule->feeDues;
                $insurance = $response->financeSchedule->insurance;
                $step = $response->financeSchedule->step;
                $schedules = $response->financeSchedule->schedules;
                $planEMIHmonths = $response->financeSchedule->planEMIHmonths;
                $planEMIHDates = $response->financeSchedule->planEMIHDates;
                $overdueCharges = $response->financeSchedule->overdueCharges;
                $summary = $response->financeSchedule->summary;
                $vas = $response->financeSchedule->vas;
                $outstandingPri = $response->financeSchedule->outstandingPri;
                $isUpfrontAuto = $response->financeSchedule->isUpfrontAuto;
                $collaterals = $response->collaterals;
                $transactions = $response->transactions;
                $collateralOverride = $response->collateralOverride;
                $receiptId = $response->receiptId;
                $created_at = Carbon::now()->toDateTimeString();

                $avanse_finance = new AvanseCreateFinance();
                $avanse_finance->fill([
                    'application_id' => $this->request->get('id'),
                    'finReference' => $finReference,
                    'collateralOverride' => $collateralOverride,
                    'outstandingPri' => $outstandingPri,
                    'isUpfrontAuto' => $isUpfrontAuto,
                    'receiptId' => $receiptId,
                    'stp' => $stp,
                    'created_at' => $created_at
                ]);

                $avanse_finance->save();

                (new NachController())->updateMetadata($this->request->get('id'), $finReference);

                $avanse_finance_id = $avanse_finance->id;


                if ($avanse_finance_id){
                    if ($financeDetail){
                        $avFinanceDetail = (array)$financeDetail;
                        $avFinanceDetail['finance_id'] = $avanse_finance_id;
                        $avanseFinanceDetails = new AvanseFinanceDetails();
                        $avanseFinanceDetails->fill($avFinanceDetail);
                        $avanseFinanceDetails->created_at = $created_at;
                        $avanseFinanceDetails->save();
                    }

                    if ($fees){
                        $avFees = (array)$fees;
                        foreach ($avFees as $fee) {
                            $fee = (array)$fee;
                            $fee['finance_id'] = $avanse_finance_id;
                            $avanseFees = new AvanseFees();
                            $avanseFees->fill($fee);
                            $avanseFees->created_at = $created_at;
                            $avanseFees->finFeeReceipts = json_encode($fee['finFeeReceipts']);
                            $avanseFees->save();
                        }
                    }

                    if ($feeDues){
                        //$feeDues, $insurance, $step

                        $avFeeDues = (array)$feeDues;
                        $avFeeDues['finance_id'] = $avanse_finance_id;
                        $avanseFeeDueInsuranceStep = new AvanseFeeDueInsuranceStep();
                        $avanseFeeDueInsuranceStep->fill($avFeeDues);
                        $avanseFeeDueInsuranceStep->created_at = $created_at;
                        $avanseFeeDueInsuranceStep->save();
                    }

                    if ($schedules){

                        $avSchedules = (array)$schedules;
                        foreach ($avSchedules as $schedule) {
                            $schedule = (array)$schedule;
                            $schedule['finance_id'] = $avanse_finance_id;
                            $avanseSchedules = new AvanseSchedules();
                            $avanseSchedules->fill($schedule);
                            $avanseSchedules->created_at = $created_at;
                            $avanseSchedules->save();
                        }
                    }

                    if ($planEMIHmonths){
                        //$planEMIHmonths, $planEMIHDates

                        $avPlanEMIHmonths = (array)$planEMIHmonths;
                        $avPlanEMIHmonths['finance_id'] = $avanse_finance_id;
                        $avansePlanEMIHmonthsDates = new AvansePlanEMIHmonthsDates();
                        $avansePlanEMIHmonthsDates->fill($avPlanEMIHmonths);
                        $avansePlanEMIHmonthsDates->created_at = $created_at;
                        $avansePlanEMIHmonthsDates->save();
                    }

                    if ($overdueCharges){

                        $avOverdueCharges = (array)$overdueCharges;
                        $avOverdueCharges['finance_id'] = $avanse_finance_id;
                        $avanseOverdueCharges = new AvanseOverdueCharges();
                        $avanseOverdueCharges->fill($avOverdueCharges);
                        $avanseOverdueCharges->created_at = $created_at;
                        $avanseOverdueCharges->save();
                    }

                    if ($summary){

                        $avSummary = (array)$summary;
                        $avSummary['finance_id'] = $avanse_finance_id;

                        $avanseFinSummary = new AvanseFinSummary();
                        $avanseFinSummary->fill($avSummary);
                        $avanseFinSummary->created_at = $created_at;
                        $avanseFinSummary->overdueCharges = json_encode($avSummary['overdueCharges']);
                        $avanseFinSummary->save();
                    }

                    if ($vas){

                        $avVas = (array)$vas;
                        $avVas['finance_id'] = $avanse_finance_id;
                        $avanseFinVas = new AvanseFinVas();
                        $avanseFinVas->fill($avVas);
                        $avanseFinVas->created_at = $created_at;
                        $avanseFinVas->save();
                    }

                    if ($collaterals){

                        $avCollaterals = (array)$collaterals;
                        $avCollaterals['finance_id'] = $avanse_finance_id;
                        $avanseCollaterals = new AvanseCollaterals();
                        $avanseCollaterals->fill($avCollaterals);
                        $avanseCollaterals->created_at = $created_at;
                        $avanseCollaterals->save();
                    }

                    if ($transactions){

                        $avTransactions = (array)$transactions;
                        $avTransactions['finance_id'] = $avanse_finance_id;
                        $vanseTransactions = new AvanseTransactions();
                        $vanseTransactions->fill($avTransactions);
                        $vanseTransactions->created_at = $created_at;
                        $vanseTransactions->save();
                    }
                }

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

        return false;
    }

}
