<?php

namespace App\Http\Controllers;


use App\ABFL\Services\Services;
use App\ApplicationEMICalculation;
use App\Bank;
use App\BNPL;
use App\BulkPayments;
use App\Bureau;
use App\Centers;
use App\ChargedInvoices;
use App\Comments;
use App\Company;
use App\Console\Commands\AdvanceReminders;
use App\ConsumerApplication;
use App\ConsumerApplicationElement;
use App\ConsumerApplicationFiles;
use App\ConsumerApplicationRelation;
use App\Http\Controllers\Admin\RepaymentController;
use App\Logging\CloudWatchLoggerFactory;
use App\MultiStageDisbursement;
use App\Jobs;
use App\PaymentMakerChecker;
use App\PaymentLogs;
use App\AvanseCreateFinance;
use App\CreditLine;
use App\CreditReport;
use App\CSV;
use App\DigitalSignDetails;
use App\Disbursement;
use App\DisbursementOffers;
use App\DisbursementOffersData;
use App\DocumentRuleLog;
use App\EMICalculation;
use App\EmiPayment;
use App\Equifax;
use App\Exports\Exporter;
use App\Exports\ExporterMultipleSheet;
use App\FinBit;
use App\FinBitData;
use App\FOIR;
use App\LiabilityLog;
use App\LendBox;
use App\RPS_Logs;
use App\RPS_Logs_new;
use App\Templates;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Admin\AccountingController;
use App\Http\Controllers\Admin\ConsumerApplicationController;
use App\Http\Controllers\Admin\ConsumerDocument;
use App\Http\Controllers\Admin\Dashboard;
use App\Http\Controllers\Admin\MerchantController;
use App\Http\Controllers\Grade\GradeController;
use App\Imports\InvoiceImport;
use App\Imports\TestImport;
use App\Invoices;
use App\JobProvider;
use App\Leads;
use App\Lenders;
use App\LoanManagement;
use App\Mandate;
use App\Merchant;
use App\MerchantLocation;
use App\MerchantOffers;
use App\Moratorium;
use App\NegativeArea;
use App\OCRRecognition;
use App\PaymentEmi;
use App\PaymentTransaction;
use App\PreApprovalLog;
use App\ProFormaInvoice;
use App\PromiseToPay;
use App\PWAApplicationForm;
use App\ScoreCard;
use App\Settlement;
use App\Slack;
use App\StatusLogs;
use App\SanctionAmountLogs;
use App\Tally\Tally;
use App\Tally\TallyJobs;
use App\Tally\TallyListener;
use App\TelecomData;
use App\User;
use App\WhatsappMessages;
use Smalot\PdfParser\Parser;
use function foo\func;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use MathPHP\Finance;
use Illuminate\Http\Response;
use App\BureauLog;
use App\UserGeolocation;
use App\Console\Commands\RQConsumerListener;
use App\CampaignsJobProvider;


class TestingController extends Controller
{
    public $decisionMessageBug = [];
    public static $coreSectors = [25,16,20,21,19,4,34,33,36,35,37,14,22,24,40,42,46,7];//Healthcare, Eduction, Home Decor, Electric vehicles

    public function getdashboard()
    {
        //$request_data = ($request->request->get('data')) ? $request->request->get('data') : ($request->get('data') ? $request->get('data') : '');
        //if ($request_data != "") {

           // $session_string = (isset($request_data->session_string)) ? explode("|", base64_decode($request_data->session_string)) : ($request->get('user') ? $request->get('user')['session_string'] : '');

           /* if (!isset($session_string[0])) {
                $data = array();
                $data['status'] = 'FAIL';
                $data['message'] = 'Invalid Session data';
                return $data;
            }
            if($error = $this->validate_session($session_string))
            {
                return $error;
            }*/
            $merchant_id = $parent_merchant = (isset($request_data->merchant_id) && $request_data->merchant_id != "") ? $request_data->merchant_id : ((isset($session_string[0])) ? $session_string[0] : 0);
            $user_type = (isset($session_string[5])) ? $session_string[5] : 0;
            $from_date = (isset($request_data->from_date) && $request_data->from_date != "" ) ? $request_data->from_date : date('Y-m-d');
            $to_date = (isset($request_data->to_date)  && $request_data->to_date != "" ) ? $request_data->to_date : date('Y-m-d');
            $duration = (isset($request_data->duration)  && $request_data->duration != "" ) ? $request_data->duration : "";
            $cfuser = 0;
            /*if($user_type == "admin"){
                $center_id = (isset($request_data->center_id) ) ? $request_data->center_id : 0;
                $cfuser = 0;
                $userid = (isset($request_data->executive_id) && $request_data->executive_id != "") ? $request_data->executive_id : 0;
            }else*/if($user_type == "admin"){
                $center_id = (isset($request_data->center_id) && $request_data->center_id != "" ) ? $request_data->center_id : 0;
                $cfuser = 0;
                $userid = (isset($request_data->executive_id) && $request_data->executive_id != "") ? $request_data->executive_id : 0;
            }elseif($user_type == "Merchant"){
                $center_id = (isset($request_data->center_id) && $request_data->center_id != ""  ) ? $request_data->center_id : 0;
                if(strpos($center_id, '_merchant') !== false){
                    $anchor_merchant_id = $merchant_id = explode('_merchant',$center_id)[0];
                    $center_id = 0;
                }
                $cfuser = 0;
                $userid = (isset($request_data->executive_id) && $request_data->executive_id != "" ) ? $request_data->executive_id : 0;
            }elseif($user_type == "Center"){
                $userid = (isset($request_data->executive_id) && $request_data->executive_id != "" ) ? $request_data->executive_id : 0;
                $cfuser = 0;
                $center_id = (isset($session_string[1])) ? $session_string[1] : 0;
            }else{
                $center_id = 0;
                $userid = (isset($session_string[2])) ? $session_string[2] : 0;
            }

            if (!isset($anchor_merchant_id)){
                $isAnchorMerchant = $this->isAnchorMerchant($parent_merchant);
                if (isset($isAnchorMerchant['merchant_ids'])){
                    $merchant_id = $isAnchorMerchant['merchant_ids'];
                }
            }


            if($duration){
                if($duration == 'day'){
                    $from_date = Carbon::now()->startOfDay()->toDateString();
                    $to_date = Carbon::now()->endOfDay()->toDateString();
                }elseif($duration == 'week'){
                    $from_date = Carbon::now()->startOfWeek()->toDateString();
                    $to_date = Carbon::now()->endOfWeek()->toDateString();
                }elseif($duration == 'month'){
                    $from_date = Carbon::now()->startOfMonth()->toDateString();
                    $to_date = Carbon::now()->endOfMonth()->toDateString();
                }
            }

            $dashboard_request = array();
            $dashboard_request['from_date'] = $from_date;
            $dashboard_request['to_date'] = $to_date;

            $applications = ConsumerApplication::whereIn('state', ['form completed','in-process', 'waiting for documents', 'approved']);

            if($merchant_id != 0){
                $dashboard_request['merchant_id'] = $merchant_id;
                $applications = $applications->where('merchant_id', $merchant_id);
            }
            if($center_id != 0){
                $dashboard_request['center_id'] = $center_id;
                $applications = $applications->where('merchant_location_id', $center_id);
            }
            if($userid != 0){
                $dashboard_request['executive_id'] = $userid;
                $applications = $applications->where('src_representative_name', $userid);
            }
            if($cfuser != 0){
                $dashboard_request['user_id'] = $cfuser;
                $applications = $applications->where('user_id', $cfuser);
            }


            $applications = $applications->whereNull('is_deleted')->orderBy('created_at', 'desc')
                ->limit(20)->get(['id']);

            $request = new Request($dashboard_request);
            $dashboard= (new Dashboard($request));
            $applicationsProcessed = $dashboard->getLoanApplicationProcessed();
            $applicationsApproved = $dashboard->getLoanApplicationByStatusV1('approved');
//            $applicationsAbort = $dashboard->getLoanApplicationByStatusV1('aborted');
//            $applicationsRejected = $dashboard->getLoanApplicationByStatusV1('rejected');
            $applicationsDisbursementTime = $dashboard->getDisbursement();


            $appl = [];
            foreach ($applications as $app){
                array_push($appl, $app->id);
            }

            $sorted_applications = ConsumerApplication::whereIn('id', $appl)->orderByRaw("CAST(loan_amount AS UNSIGNED) DESC")->get(['id', 'name', 'loan_amount', 'state']);

            $apps = [];
            $total_la = 0;
            $total_pending_la = 0;
            $total_app_ids = array();
            foreach ($sorted_applications as $key => $app){
                if($key<3){
                    $apps[$key]['name'] = $app->name;
                    $apps[$key]['loan_amount'] = number_format($app->loan_amount);
                    $apps[$key]['status'] = $app->state;
                    $apps[$key]['application_id'] = base64_encode(json_encode($app->id));
                    $apps[$key]['doc'] = (new Admin\ConsumerApplicationController)->getOtherRequiredDocument($app);
                    $total_la += (int)$app->loan_amount;
                }
                $total_pending_la += $app->loan_amount;
                array_push($total_app_ids,$app->id);
            }

            $dashboard = [
                array(
                    'title1' => 'Applications Sent',
                    'icon' => 'sent',
                    'count' => str_replace('.00','',money_format('%!i',$applicationsProcessed['processed_application'])),
                    'title2' => 'Value of applications Sent',
                    'value' => '&#8377;'.PWAApplicationForm::getAmountInLac(($applicationsProcessed['value_processed_application'])),
                    'applications' => base64_encode(json_encode($applicationsProcessed['application_ids']))
                ),
//                array(
//                    'title' => 'Value of applications Sent',
//                    'count' => '&#8377;'.PWAApplicationForm::getAmountInLac(($applicationsProcessed['value_processed_application'])),
//                    'applications' => base64_encode(json_encode($applicationsProcessed['application_ids']))
//                ),
                array(
                    'title1' => 'Applications Approved',
                    'icon' => 'approve',
                    'count' => str_replace('.00','',money_format('%!i',$applicationsApproved[0])),
                    'title2' => 'Value of loans approved',
                    'value' => '&#8377;'.PWAApplicationForm::getAmountInLac($applicationsApproved[1]),
                    'applications' => base64_encode(json_encode($applicationsApproved[2]))
                ),
//                array(
//                    'title' => 'Value of loans approved',
//                    'count' => '&#8377;'.PWAApplicationForm::getAmountInLac($applicationsApproved[1]),
//                    'applications' => base64_encode(json_encode($applicationsApproved[2]))
//                ),
                array(
                    'title1' => 'Applications Disbursed',
                    'icon' => 'disburse',
                    'count' => str_replace('.00','',money_format('%!i',$applicationsDisbursementTime[1])),
                    'title2' => 'Value of loans Disbursed',
                    'value' => '&#8377;'.PWAApplicationForm::getAmountInLac($applicationsDisbursementTime[3]),
                    'applications' => base64_encode(json_encode($applicationsDisbursementTime[4]))
                ),
                array(
                    'title1' => 'Pending Applications',
                    'icon' => 'pending_app',
                    'count' => count($total_app_ids),
                    'title2' => 'Value of open loans',
                    'value' => '&#8377;'.PWAApplicationForm::getAmountInLac($total_pending_la),
                    'applications' => base64_encode(json_encode($total_app_ids))
                ),
//                array(
//                    'title' => 'Value of loans Disbursed',
//                    'count' => '&#8377;'.PWAApplicationForm::getAmountInLac($applicationsDisbursementTime[3]),
//                    'applications' => base64_encode(json_encode($applicationsDisbursementTime[4]))
//                ),
//                array(
//                    'title' => 'Applications Rejected',
//                    'icon' => 'reject',
//                    'count' => str_replace('.00','',money_format('%!i',$applicationsRejected[0])),
//                    'applications' => base64_encode(json_encode($applicationsRejected[2]))
//                ),
//                array(
//                    'title' => 'Applications Aborted',
//                    'icon' => 'abort',
//                    'count' => str_replace('.00','',money_format('%!i',$applicationsAbort[0])),
//                    'applications' => base64_encode(json_encode($applicationsAbort[2]))
//                )
            ];

//            $apps[] = money_format('%!i',$total_la);

            $data['total_loan_amount'] = $apps != [] && !empty($apps) && $total_la > 0 ? number_format($total_la) : 0;
            $data['applications'] = $dashboard;
            $data['pending_app_ids'] = base64_encode(json_encode($total_app_ids));
            $data['pending_app'] = $apps;
            $data['status'] = 'OK';
            $data['message'] = 'Dashboard';
            print_r($data);die;

        //}
        /*$data = array();
        $data['status'] = 'FAIL';
        $data['message'] = 'No Data Found';
        return $data;*/
    }

    public function isAnchorMerchant($merchant_id){
        $merchants = Merchant::where('anchor_merchant_id',$merchant_id)->get(['id','merchant_name']);
        $isAnchorMerchant = false;
        $merchantIds[] = $merchant_id;
        $merchantList = [];
        foreach($merchants as $merchant){
            $isAnchorMerchant = true;
            $merchantIds[] = $merchant->id;
            $merchantList[] = $merchant;
        }

        if($isAnchorMerchant){
            return ['merchant_ids' => $merchantIds, 'anchor_merchant' => $merchantList];
        }else {
            return ['merchant_ids' => $merchant_id ? [$merchant_id] : 0];
        }
    }

    public function nachregister(){
        $status_array = ['disbursed'];
        $consumer_application_ids = array();
        $application = ConsumerApplication::with('merchant','lender','bank_details','proFormaInvoice','monthlymandate','fullmandate');
        $applications = $application->whereNull('is_deleted')->whereIn('consumer_application.state',$status_array)->groupBy('id')->get(['id','name','email','mobile_number','merchant_id','lender_id','state']);

        foreach($applications as $application){

            if(isset($application->monthlymandate->umrn) && !empty($application->monthlymandate->umrn) && $application->monthlymandate->umrn != "0"){
                if(isset($application->monthlymandate->mode)) {
                    array_push($consumer_application_ids,$application->id);
                    $staus_log[] = [
                        'application_id' => $application->id,
                        'user_id' => 107,
                        'status' => 'nach registered',
                        'created_at' => Carbon::now()->toDateTimeString()
                    ];

                }
            }elseif(isset($application->fullmandate->umrn) && !empty($application->fullmandate->umrn) && $application->fullmandate->umrn != "0"){
                if(isset($application->fullmandate->mode)) {
                    array_push($consumer_application_ids,$application->id);
                    $staus_log[] = [
                        'application_id' => $application->id,
                        'user_id' => 107,
                        'status' => 'nach registered',
                        'created_at' => Carbon::now()->toDateTimeString()
                    ];
                }
            }


        }
        echo "<pre>";
        ConsumerApplication::wherein('id',$consumer_application_ids)->update(['state'=>'nach registered']);
        StatusLogs::insert($staus_log);
        print_r($consumer_application_ids);
        exit;
    }

    public function getIdeaFoirData(){
        $csvFile = file(storage_path().'/foir_data.csv');
        foreach ($csvFile as $line) {
            $data[] = str_getcsv($line);
        }

        $finalData[] = ['SerialNo','ApplicationID','ProcessDate','LoanType','Status','SCORED_DATE','TS_CREDIT_INSIGHT','FOIR','SCORE'];
        unset($data[0]);
        $consumerApplication = new ConsumerApplicationController();
        foreach ($data as $datum){
            try {
                $request = new Request();
                $request->attributes->add(['application_id' => $datum[1]]);
                $response = $consumerApplication->getScoreCard($request);
                $foir = $response['foir'];
                $score = $response['score'];

                $finalData[] = [
                    'SerialNo' => $datum[0],
                    'ApplicationID' => $datum[1],
                    'ProcessDate' => $datum[2],
                    'LoanType' => $datum[3],
                    'Status' => $datum[4],
                    'SCORED_DATE' => $datum[5],
                    'TS_CREDIT_INSIGHT' => $datum[6],
                    'FOIR' => $foir,
                    'SCORE' => $score,
                ];
            }catch (\Exception $e){
                $finalData[] = [
                    'SerialNo' => $datum[0],
                    'ApplicationID' => $datum[1],
                    'ProcessDate' => $datum[2],
                    'LoanType' => $datum[3],
                    'Status' => $datum[4],
                    'SCORED_DATE' => $datum[5],
                    'TS_CREDIT_INSIGHT' => $datum[6],
                    'FOIR' => 0,
                    'SCORE' => 0,
                ];
            }
        }

        $request = new Request(['data'=>$finalData,'sheet'=>'Sheet1']);
        return \Maatwebsite\Excel\Facades\Excel::download((new Exporter($request)), 'foir_data.xls');
    }

    public function getAddress($application){
        if(empty($application->permanent_address_line_1)) {
            return $application->current_address_line_1 . ', ' . $application->current_address_landmark . ', ' . $application->current_address_state . ', ' . $application->current_address_city;
        }else{
            return $application->permanent_address_line_1 . ', ' . $application->permanent_address_landmark . ', ' . $application->permanent_address_state . ', ' . $application->permanent_address_city;
        }
    }

    public function arriveUAT(){
        $data = array(
            'name' => 'Sunil Khorwal',
            'phone' => 7874191148,
            'email' => 'piyush@creditfair.in',
            'loan_amount' => 15000,
            'pan_card' => 'DXPXK3435H',
            'aadhaar_card' => 34452345333,
            'lang' => 'BENGALI',
            'offer_id' => 22,
            'duration_year' => 1,
            'duration_month' => 2,
            'product_name' => 'Testing',
            'unique_id_number' => '343343434',
            'dob' => '1991-12-01',
            'gender' => 'F',
            'martial_status' => 'M',
            'address' => [
                [
                    'type' => 'current',
                    'address' => 'test',
                    'state' => 'Maharashtra',
                    'city' => 'Mumbai',
                    'pincode' => '400071',
                    'landmark' => 'Bandra',
                    'address_status' => 'Rented'
                ],
                [
                    'type' => 'permanent',
                    'address' => 'test',
                    'state' => 'Maharashtra',
                    'city' => 'Mumbai',
                    'pincode' => '400071',
                    'landmark' => 'Bandra',
                    'address_status' => 'Rented'
                ],
                [
                    'type' => 'work',
                    'address' => 'test',
                    'state' => 'Maharashtra',
                    'city' => 'Mumbai',
                    'pincode' => '400071',
                    'landmark' => 'Bandra',
                    'address_status' => 'Rented'
                ]
            ],
            'alternate_number' => '9920820531',
            'employment_status' => 'S',
            'company_name' => 'Testing',
            'monthly_income' => 232323,
        );

        $plaintext = http_build_query($data);



        $key ='545f114ebd7e8acb1c39b4547d55a616';
        $cipher = "AES-128-CBC";
        $iv = "lksdasfsaskllopl";
        $ciphertext_raw = openssl_encrypt($plaintext, $cipher, $key, $options = OPENSSL_RAW_DATA, $iv);
        $hmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary = true);
        return $value = base64_encode($iv . $hmac . $ciphertext_raw);
    }

    public function uploadMerchantLogoOnS3(){
        $merchants = Merchant::whereNotNull('merchant_logo')->get(['id', 'merchant_logo']);

        foreach($merchants as $merchant){
            try {
                if ($merchant->merchant_logo) {
                    $file_path = '/merchant/' . $merchant->id . '/logo' . $merchant->merchant_logo;
                    $s3 = Storage::disk('s3');
                    $s3->put($file_path, file_get_contents('https://creditfair.in' . $merchant->merchant_logo));
                    Merchant::where('id', $merchant->id)->update(['merchant_logo' => $file_path]);
                }
            }catch (\Exception $e){

            }
        }

    }

    public function getDPDDays(){

        $consumers = ConsumerApplication::with('emi_payment.transaction')->whereIn('id', [8153,
            6751,
            8587,
            10751,
            10180,
            8534,
            11554,
            11499,
            11138,
            11587,
            11565,
            13915,
            15620,
            15980,
            16549,
            16959,
            17014,
            16353,
            17354,
            17407,
            17131,
            17458,
            17422,
            17693,
            17844,
            18131,
            14261,
            18244,
            17185,
            18013,
            16827,
            18568,
            19036,
            18422,
            19155,
            19024,
            14037,
            19272,
            16750,
            19726,
            19461,
            18416,
            17607,
            19799,
            2652,
            2753,
            3989,
            4505,
            4984,
            5273,
            5431,
            5522,
            5754,
            18093,
            19173,
            19809,
            19189,
            19852,
            18626,
            18331,
            17270,
            20289,
            19459,
            18803,
            20545,
            19940,
            20425,
            17664,
            19619,
            19740,
            20942,
            20278,
            20245,
            19049,
            21088,
            21242,
            16109,
            21254,
            21183,
            20955,
            13747,
            21494,
            19384,
            21586,
            21624,
            10042,
            21500,
            21378,
            21394,
            21785,
            21555,
            21872,
            21003,
            21155,
            19339,
            22059,
            22323,
            21417,
            22646,
            22005,
            22150,
            21968,
            21726,
            22280,
            22796,
            22830,
            23024,
            23075,
            22862,
            22721,
            23103,
            21742,
            23415,
            23298,
            23138,
            22392,
            22569,
            19865,
            23521,
            22129,
            24361,
            23854,
            24631,
            24517,
            24633,
            25328,
            23208,
            25325,
            25409,
            25509,
            24602,
            25887,
            25761,
            25494,
            24994,
            25300,
            24861,
            26237,
            26014,
            25557,
            26150,
            26030,
            26387,
            25667,
            26388,
            25937,
            26167,
            26492,
            26392,
            26680,
            25114,
            21596,
            26654,
            26658,
            26695,
            22494,
            27049,
            26964,
            26786,
            26503,
            23721,
            27097,
            26482,
            26667,
            26378,
            25474,
            26662,
            25966,
            27282,
            26224,
            26768,
            27048,
            27593,
            26863,
            26180,
            21442,
            27276,
            27286,
            27055,
            26612,
            27424,
            27822,
            27417,
            17628,
            25772,
            27511,
            26145,
            27166,
            26203,
            27684,
            27845,
            26682,
            26643,
            28018,
            25959,
            28461,
            24505,
            23301,
            27671,
            27794,
            28378,
            21379,
            28551,
            28236,
            25511,
            28422,
            27004,
            23909,
            27075,
            28391,
            27844,
            29095,
            29129,
            29325,
            28456,
            28867,
            29518,
            29484,
            28187,
            29395,
            28698,
            22996,
            28183,
            27690,
            29887,
            27924,
            28886,
            26598,
            28342,
            28172,
            26453,
            26736,
            29716,
            30085,
            29347,
            29837,
            30703,
            30067,
            30373,
            28184,
            28592,
            28855,
            30911,
            30915,
            28645,
            28997,
            30889,
            30745,
            28669,
            28691,
            19531,
            29873,
            31734,
            31849,
            31902,
            30979,
            22172,
            30442,
            31917,
            32078,
            31742,
            32018,
            31690,
            31148,
            26971,
            32427,
            31700,
            19164,
            32554,
            32534,
            32424,
            32681,
            30033,
            32555,
            30847,
            32557,
            32256,
            32243,
            29738,
            32935,
            32984,
            32433,
            32982,
            33059,
            33152,
            29863,
            31788,
            32766,
            32536,
            33293,
            33075,
            32904,
            31006,
            29733,
            27919,
            32467,
            33519,
            33048,
            29446,
            28704,
            32957,
            33371,
            32203,
            32830,
            33734,
            34218,
            34377,
            32944,
            34392,
            32222,
            34656,
            32586,
            33790,
            34697,
            34645,
            34758,
            34284,
            34283,
            31924,
            32910,
            33527,
            34563,
            32587,
            34872,
            35108,
            34644,
            34437,
            34871,
            34135,
            33915,
            32682,
            34204,
            35532,
            34800,
            30879,
            33361,
            35613,
            34882,
            35561,
            35156,
            35954,
            36114,
            35060,
            35853,
            31773,
            34514,
            35507,
            34996,
            36210,
            35640,
            35942,
            19234,
            36826,
            33522,
            36745,
            35936,
            37233,
            37216,
            37117,
            36822,
            32527,
            35838,
            36991,
            34721,
            37368,
            34782,
            36930,
            34975,
            34311,
            37784,
            37119,
            35679,
            38160,
            38034,
            33802,
            32650,
            34976,
            34773,
            38290,
            36254,
            37757,
            38391,
            38299,
            35565,
            35417,
            35858,
            38592,
            37494,
            38080,
            26200,
            32653,
            36830,
            37751,
            38248,
            39148,
            37779,
            35680,
            39326,
            38241,
            38250,
            35635,
            39290,
            39292,
            39418,
            35242,
            39032,
            38860,
            38875,
            35087,
            31372,
            36752,
            38117,
            39568,
            39805,
            39145,
            39773,
            39825,
            39869,
            40049,
            39885,
            39264,
            39487,
            38390,
            39709,
            39472,
            38848,
            38128,
            40079,
            40238,
            37151,
            34797,
            34711,
            33274,
            38842,
            38428,
            39862,
            38796,
            39111,
            39219,
            36918,
            38578,
            35386,
            36768,
            37856,
            35460,
            40205,
            39540,
            40378,
            38545,
            37840,
            37561,
            38807,
            37754,
            34883,
            38363,
            40218,
            39283,
            37509,
            38418,
            34206,
            40511,
            40709,
            39205,
            40632,
            40449,
            39681,
            36428,
            40471,
            40878,
            39118,
            38072,
            36825,
            32938,
            39117,
            36779,
            40115,
            40071,
            41130,
            40983,
            39806,
            40350,
            40980,
            34960,
            34387,
            38347,
            37788,
            39201,
            37051,
            41090,
            40977,
            40356,
            39942,
            31907,
            38562,
            40137,
            41121,
            40309,
            41256,
            41372,
            40886,
            41381,
            41489,
            41459,
            40933,
            40821,
            40357,
            35167,
            41694,
            39455,
            40612,
            41412,
            41352,
            41507,
            40663,
            41271,
            41369,
            40180,
            40943,
            41270,
            41477,
            41452,
            41343,
            41787,
            39882,
            41152,
            41356,
            38902,
            39751,
            40676,
            40219,
            41857,
            41830,
            41913,
            40783,
            40883,
            34076,
            39332,
            41355,
            42050,
            41384,
            38401,
            40430,
            40862,
            40495,
            41927,
            41689,
            39747,
            40472,
            40879,
            40774,
            41565,
            41278,
            38814,
            39970,
            42047,
            40865,
            40847,
            42264,
            40958,
            39621,
            41926,
            41797,
            40140,
            40610,
            41476,
            41684,
            42059,
            41155,
            42191,
            42029,
            42299,
            40935,
            42502,
            40919,
            42512,
            41835,
            42651,
            39811,
            32238,
            40540,
            42790,
            41916,
            37120,
            42064,
            41890,
            42887,
            42096,
            40890,
            42067,
            40577,
            42643,
            37381,
            39872,
            42267,
            42934,
            42507,
            42702,
            43058,
            42657,
            41091,
            42474,
            41800,
            41445,
            42326,
            41456,
            43124,
            43145,
            43096,
            43091,
            41598,
            42964,
            43302,
            42227,
            41354,
            43129,
            42930,
            42885,
            40863,
            43516,
            41826,
            38066,
            43257,
            42917,
            37955,
            43501,
            42836,
            43052,
            43139,
            43335,
            41494,
            43260,
            39987,
            40671,
            40584,
            43578,
            42929,
            42514,
            43573,
            42825,
            43585,
            42351,
            41334,
            43656,
            42700,
            42992,
            38756,
            43599,
            43788,
            43357,
            43620,
            43072,
            43559,
            38111,
            38926,
            41197,
            40242,
            42552,
            42321,
            40347,
            43845,
            43538,
            43574,
            43958,
            44025,
            43201,
            44032,
            42081,
            5581,
            43135,
            41887,
            43939,
            43338,
            43596,
            42292,
            41115,
            41674,
            43099,
            34888,
            42692,
            42708,
            43403,
            43565,
            43722,
            44017,
            43267,
            43262,
            40872,
            40190,
            43218,
            44022,
            44303,
            44356,
            43751,
            38269,
            44298,
            44179,
            44225,
            41133,
            42226,
            43511,
            42840,
            42577,
            40243,
            43231,
            43595,
            44466,
            39829,
            44234,
            43804,
            42288,
            42776,
            42984,
            44591,
            44301,
            44182,
            44190,
            42071,
            43528,
            40102,
            39932,
            43235,
            44502,
            44256,
            43799,
            44389,
            43875,
            40067,
            43611,
            42829,
            44673,
            44853,
            44978,
            44900,
            40659,
            43277,
            43243,
            42875,
            43504,
            45114,
            44375,
            44385,
            40727,
            42587,
            44593,
            44921,
            45171,
            44231,
            45004,
            44009,
            44392,
            44647,
            44228,
            42792,
            44090,
            45041,
            45268,
            44333,
            43608,
            45288,
            45426,
            44882,
            40978,
            45325,
            43060,
            44266,
            44651,
            45521,
            43730,
            45406,
            44762,
            45144,
            43543,
            45326,
            45005,
            45580,
            45290,
            45668,
            40536,
            45690,
            45831,
            45350,
            45825,
            43114,
            43345,
            44229,
            35742,
            42695,
            45723,
            45136,
            45769,
            45870,
            45388,
            46013,
            44997,
            44971,
            45182,
            45977,
            44643,
            45459,
            40938,
            42623,
            46040,
            45877,
            45255,
            33829,
            44801,
            44810,
            45964,
            45483,
            45868,
            46095,
            43233,
            40444,
            45920,
            45878,
            44659,
            43864,
            45535,
            45912,
            45703,
            45946,
            34508,
            32202,
            43075,
            45976,
            43957,
            46617,
            45620,
            39491,
            46494,
            42404,
            46591,
            46699,
            46697,
            45587,
            39873,
            46164,
            45582,
            46460,
            35934,
            46012,
            46096,
            46518,
            45965,
            42686,
            46999,
            46513,
            44445,
            46349,
            42185,
            43660,
            46584,
            45815,
            45728,
            47005,
            42591,
            46535,
            42766,
            46230,
            43858,
            47028,
            46993,
            46743,
            45692,
            46231,
            46451,
            40240,
            46536,
            46545,
            46396,
            47180,
            45284,
            45469,
            46367,
            46406,
            47427,
            39612,
            39957,
            41102,
            35556,
            47330,
            45408,
            47512,
            46483,
            46570,
            47168,
            47537,
            47058,
            47496,
            47041,
            46899,
            47338,
            47642,
            47502,
            47706,
            47165,
            47391,
            46888,
            47733,
            45860,
            47748,
            47552,
            47533,
            46142,
            47304,
            46995,
            46393,
            46172,
            47065,
            44007,
            45130,
            46880,
            47271,
            47564,
            47880,
            47921,
            47955,
            46352,
            47164,
            42991,
            35177,
            43619,
            43616,
            47188,
            47116,
            47981,
            38434,
            47038,
            47864,
            47549,
            47163,
            47726,
            47830,
            46466,
            47042,
            46480,
            47976,
            48119,
            45188,
            46407,
            48123,
            47850,
            48115,
            48030,
            47035,
            47898,
            48217,
            47901,
            43502,
            44254,
            46615,
            46523,
            45022,
            42084,
            45709,
            47262,
            43655,
            45123,
            48240,
            48215,
            47399,
            46485,
            48074,
            46360,
            42027,
            48211,
            47971,
            48238,
            47126,
            48538,
            48541,
            47024,
            45258,
            48568,
            44452,
            47835,
            48274,
            48585,
            48620,
            48513,
            48031,
            47609,
            48652,
            46533,
            48338,
            42014,
            48636,
            43567,
            47889,
            47139,
            46509,
            48756,
            48782,
            48365,
            48831,
            48705,
            48929,
            48143,
            46907,
            48803,
            47334,
            47922,
            48726,
            48924,
            49006,
            49127,
            49136,
            42757,
            48209,
            48290,
            49169,
            48749,
            49195,
            48962,
            48589,
            46107,
            48834,
            48411,
            48281])->get(['id']);
        //$payment_data = EmiPayment::with('transaction')->where('application_id',[17420])->get();

        $DPDDays = [];
        $PDate = '2021-11-30 23:59:59';//'2021-03-31 23:59:59';

        $loanManagement = new LoanManagement();
        foreach($consumers as $consumer){

            $emiReceived = 0;
            $i = 1;
            $days = 0;
            $emis = [];
            foreach($consumer->emi_payment as $payment) {
                if(count($payment->transaction)) {
                    $isReceived = 0;
                    foreach ($payment->transaction as $transaction) {
                        /*if(strtotime($transaction->payment_date) > strtotime('2021-03-31 23:59:59')) {
                            $days = $loanManagement->calculateDelayDays($payment->emi_date, '2021-03-31 23:59:59', $payment->application_id);
                        }*/

                        if(strtotime($transaction->payment_date) <= strtotime($PDate)) {
                            $isReceived = 1;
                        }
                    }
                    if($isReceived) {
                        $emiReceived++;
                    }
                }

                $emis[$i] = $payment->emi_date;
                $i++;
            }
            if(!isset($emis)){
                $days = $loanManagement->calculateDelayDays($consumer->emi_payment[0]->emi_date, $PDate, 0);
            }

            $DPDDays[$consumer->id] = isset($emis[$emiReceived + 1]) ? $days ?? $loanManagement->calculateDelayDays($emis[$emiReceived + 1], $PDate, 0) : 0;
            $emisData[$consumer->id] = $emis;
            $emisDataRec[$consumer->id] = $emiReceived;
        }

        return $DPDDays;
    }

    public function getSantoshji($start_date = '2021-04-01 00:00:00', $last_date = '2022-03-31 23:59:59'){
        try {
//            ini_set('max_execution_time', -1);
//            set_time_limit(0);
//            ini_set('memory_limit', '-1');
            $dd = [];
            /*$apps = DB::select("select id, state from consumer_application where id in (select application_id from status_logs
                where status in ('disbursed', 'nach registered') and created_at <= '$__date' group by application_id) and is_deleted is null group by id desc");*/
//        $apps = DB::select("select id, state from consumer_application where id in (59791,59735,59042,59320,58686,55181,59150,45141,58786,58125) and is_deleted is null group by id desc");
            $apps = DB::select("select id, state from consumer_application where state in ('disbursed', 'nach registered', 'closed', 'cancelled') and is_deleted is null group by id asc");

            $ddStatus = [];
            foreach ($apps as $app) {
                $dd[] = $app->id;
                $ddStatus[] = $app->id;
            }


            $SDate = $start_date;//'2021-03-31 23:59:59';
            $FDate = $last_date;//'2021-03-31 23:59:59';
            $d = new AccountingController();
            $d->raw = true;
            $header[] = ['ID', 'principalReceivedTotal', 'pending p os', 'foreclosure', 'after foreclosure p os'];
            $ddd = [];


            foreach ($dd as $item) {
                try {
                    $v = $d->getLoanScheduleDataV1($item);
                    $statusLog = StatusLogs::where('application_id', $item)->whereIn('status', ['closed', 'cancelled'])->orderBy('created_at', 'desc')->first();
                    $isClosed = 0;
                    if ($statusLog && strtotime($statusLog->created_at) >= strtotime($SDate) && strtotime($statusLog->created_at) <= strtotime($FDate)) {
                        $isClosed = 1;
                    }
                    $principalToBeReceivedTotal = 0;
                    $principalToBeReceivedMonth = 0;
                    $monthWiseData = [];
                    $principalReceivedTotal = 0;

                    $opening = $closing = $v['summary']['loan_outstanding'];

                    foreach ($v['schedule'] as $c) {
                        $receivedOnMonth = 0;
                        $payment_date = '';
                        foreach ($c['transaction'] as $transaction) {
                            if (strtotime($transaction->payment_date) >= strtotime($SDate) && strtotime($transaction->payment_date) <= strtotime($FDate) && !$transaction->refunded_at) {
                                $receivedOnMonth += $transaction->amount;
                                $payment_date = $transaction->payment_date;
                            }
                        }

                        //if(strtotime($c['emi_date']) <= strtotime('2021-03-31 23:59:59')) {
                        $principalToBeReceivedTotal += $c['principal'];
                        $principalToBeReceivedMonth = $c['principal'];
                        //}

                        if ($principalToBeReceivedMonth <= $receivedOnMonth) {
                            $monthWiseData[$c['emi_date']]['principalReceived'] = $principalToBeReceivedMonth;
                        } else {
                            $monthWiseData[$c['emi_date']]['principalReceived'] = $receivedOnMonth;//$receivedOnMonth ? $principalToBeReceivedMonth - $receivedOnMonth : 0;
                        }

                        $principalReceivedTotal += $monthWiseData[$c['emi_date']]['principalReceived'];

                        /*if(strtotime($v['schedule'][0]['emi_date']) > strtotime('2021-03-31 23:59:59')) {
                            $principalToBeReceivedTotal += $c['principal'];
                        }*/

                        $opening = $closing;
                        $closing = $opening - $monthWiseData[$c['emi_date']]['principalReceived'];


                        $ddd[$item][$c['emi_date']] = [
                            'id' => $item,
                            'name' => $v['customer_name'],
                            'opening_balance' => round($opening, 2),
                            'interest_rate' => round($c['interest'], 2),
                            'principal' => $monthWiseData[$c['emi_date']]['principalReceived'],
                            'debit' => $c['interest'],
                            'credit' => round($monthWiseData[$c['emi_date']]['principalReceived'] + $c['interest'] + $c['bounce_charges'] + $c['delay_penalty'], 2),
                            'bounce' => $c['bounce_charges'],
                            'penal' => $c['delay_penalty'],
                            'payment_date' => $payment_date,
                            'closing_balance' => $closing,
                            'status' => $c['payment_status'],
                        ];

                    }


                } catch (\Exception $e) {

                }
            }
            $data [] = ['ID', 'Name', 'Opening balance', 'Principal', 'Debit', 'Credit', 'Bounce Charges', 'Penal Charges', 'Payment Date', 'Closing balance', 'EMI Status'];
            foreach ($ddd as $app) {
                foreach ($app as $key => $item) {
                    if (strtotime($key) >= strtotime($SDate) && strtotime($key) <= strtotime($FDate)) {
//                    $tr .= '<tr><td>' . $item['id'] . '</td><td>' . $item['name'] . '</td><td>' . $item['opening_balance'] . '</td><td>' . round($item['principal'], 2) . '</td><td>' . round($item['debit'], 2) . '</td><td>' . round($item['credit'], 2) . '</td><td>' . round($item['bounce'], 2) . '</td><td>' . round($item['penal'], 2) . '</td><td>' . $item['payment_date'] . '</td><td>' . round($item['closing_balance'], 2) . '</td><td>' . $item['status'] . '</td></tr>';
                        $data[] = [
                            'id' => $item['id'],
                            'name' => $item['name'],
                            'opening' => $item['opening_balance'],
                            'principal' => round($item['principal'], 2),
                            'debit' => round($item['debit'], 2),
                            'credit' => round($item['credit'], 2),
                            'bounce' => round($item['bounce'], 2),
                            'penal' => round($item['penal'], 2),
                            'payment_date' => $item['payment_date'],
                            'closing' => round($item['closing_balance'], 2),
                            'status' => $item['status']
                        ];
                    }
                }
            }
            $request = new Request(['data' => $data, 'sheet' => 'Sheet1']);
//        return \Maatwebsite\Excel\Facades\Excel::download((new Exporter($request)), 'SanthoshJi_audit_report.xlsx');
            $file = time() . '_' . Carbon::now()->toDateTimeString() . '_audit_report.xlsx';
            Excel::store((new Exporter($request)), $file);
            Mail::send('emails.reminders.basic_reminder',
                ['body' => 'Audit Report']
                , function ($message) use ($file) {
                    $message->to(['sarah@creditfair.in'])->subject('Audit Report');
                    $message->attachData(file_get_contents(storage_path() . '/app/' . $file), $file);
                });

            unlink(storage_path() . '/app/' . $file);
//        return "<table border='1'><tr><td>ID</td><td>Name</td><td>Opening balance</td><td>Principal</td><td>Debit</td><td>Credit</td><td>Bounce Charges</td><td>Penal Charges</td><td>Payment Date</td><td>Closing balance</td><td>EMI Status</td></tr>".$tr."</table>";
        } catch (\Exception $e) {
            (new \App\Slack(new Request(['title' => 'Error in sending audit report', 'fields' => ['error' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()]])))->send();
        }
    }

    public function getPrincipalsOutstandingAdityaNCD($payload){
        $month = $payload->month ?? '';
        $year = $payload->year ?? '';
        $app_ids = $payload->ids ?? '';

        set_time_limit(0);
        ini_set('memory_limit', '-1');

        if($app_ids != ''){
            $apps = DB::select("select id, state from consumer_application where id in (".$app_ids.") and is_deleted is null group by id");
        }else{
            $apps = DB::select("select id, state from consumer_application where lender_id=2 and id in 
                                                                 (select application_id from status_logs where status in ('disbursed', 'nach registered') group by application_id) 
                                             and is_deleted is null group by id");
        }


        $ddStatus = [];
        foreach($apps as $app){
            $dd[] = $app->id;
            $ddStatus[] = $app->id;
        }
        (new Slack(new Request(['title' => 'NCD', 'fields' => ['file preparing started' => count($dd)], 'group' => Slack::$STAGE_TESTING])))->send();
        $FDateE = Carbon::createFromDate($year, $month)->subMonth(1)->endOfMonth()->toDateTimeString();
        $FDateS = Carbon::createFromDate($year, $month)->subMonth(1)->startOfMonth()->toDateTimeString();
        $FDate1E = Carbon::createFromDate($year, $month)->subMonth(2)->endOfMonth()->toDateTimeString();
        $FDate1S = Carbon::createFromDate($year, $month)->subMonth(2)->startOfMonth()->toDateTimeString();
        /*$FDateE = '2024-02-31 23:59:59';//'2021-03-31 23:59:59';
        $FDateS = '2024-02-01 00:00:00';//'2021-03-01 00:00:00';
        $FDate1E = '2024-01-31 23:59:59';//'2021-03-31 23:59:59';
        $FDate1S = '2024-01-01 00:00:00';//'2021-03-01 00:00:00';*/
        $d = new AccountingController();
        $d->raw = true;
        $header[] = ['ID', 'no of Installments ', 'Opening Principal O/s', 'Overdue Principal o/s', 'Principal Due during the month', 'Principal Paid during the month', 'Principal Overdue', 'DPD', 'Closing Principal O/s', 'Interest O/S beginning OF Month', 'Interest due during Month', 'Interest paid during Month', 'Interest overdue', 'Prepayment s', 'J2Sec'];

        foreach($dd as $item) {
            try {
                $v = $d->getLoanScheduleDataV1($item);
                $statusLog = StatusLogs::where('application_id', $item)->whereIn('status', ['closed', 'cancelled'])->orderBy('created_at','desc')->first();
                $isClosed = 0;
                if($statusLog && $statusLog->created_at <= $FDateE){
                    $isClosed = 1;
                }
                $principalToBeReceivedTotal = 0;
                $principalToBeReceivedMonth = 0;
                $monthWiseData = [];
                $principalReceivedTotal = 0;
                $no_of_Installments_remaining = 0;
                $OverduePrincipalo_sE2 = 0;
                $OverduePrincipalo_sD2 = 0;
                $interest_OS_beginning_OF_MonthK2 = 0;
                $PrincipalDueduringthemonthF2 = 0;
                $PrincipalDueduringthemonthJ2 = 0;
                $interest_due_during_MonthL2 = 0;
                $interest_due_during_MonthM2 = 0;
                $no_of_Installments_remainingC2 = 0;
                $principal_Paid_during_the_monthG2 = 0;

                $interestToBeReceivedTotal = 0;
                $interestToBeReceivedMonth = 0;
                $interest_overdueN2 = 0;
                $principal_Overdue_H2 = 0;

                foreach($v['schedule'] as $vp => $c) {
                    $receivedOnMonth = 0;
                    foreach ($c['transaction'] as $transaction) {
                        if ($transaction->payment_date <= $FDateE && !$transaction->refunded_at) {
                            $receivedOnMonth += $transaction->amount;
                        }
                    }

                    //if(strtotime($c['emi_date']) <= strtotime('2021-03-31 23:59:59')) {
                    $principalToBeReceivedTotal += $c['principal'];
                    $principalToBeReceivedMonth = $c['principal'];

                    $interestToBeReceivedTotal += $c['interest'];
                    $interestToBeReceivedMonth = $c['interest'];
                    //}

                    if($principalToBeReceivedMonth <= $receivedOnMonth){
                        $monthWiseData[$c['emi_date']]['principalReceived'] = $principalToBeReceivedMonth;
                    }else{
                        $monthWiseData[$c['emi_date']]['principalReceived'] = $receivedOnMonth;//$receivedOnMonth ? $principalToBeReceivedMonth - $receivedOnMonth : 0;
                    }

                    if($principalToBeReceivedMonth <= $receivedOnMonth) {
                        if (round($interestToBeReceivedMonth) <= round($receivedOnMonth - $principalToBeReceivedMonth)) {
                            $monthWiseData[$c['emi_date']]['interestReceived'] = $interestToBeReceivedMonth;
                        } else {
                            $monthWiseData[$c['emi_date']]['interestReceived'] = ($receivedOnMonth - $principalToBeReceivedMonth);//$receivedOnMonth ? $principalToBeReceivedMonth - $receivedOnMonth : 0;
                        }
                    }

                    $principalReceivedTotal += $monthWiseData[$c['emi_date']]['principalReceived'];

                    /*if(strtotime($v['schedule'][0]['emi_date']) > strtotime('2021-03-31 23:59:59')) {
                        $principalToBeReceivedTotal += $c['principal'];
                    }*/

                    if($c['emi_date'] > $FDateE){
                        $no_of_Installments_remainingC2++;
                    }

                    if ($c['emi_date'] >= $FDateS && $c['emi_date'] <= $FDateE){
                        $PrincipalDueduringthemonthF2 = $principalToBeReceivedMonth;
                        $principal_Paid_during_the_monthG2 = $monthWiseData[$c['emi_date']]['principalReceived'];
                        $interest_due_during_MonthL2 = $interestToBeReceivedMonth;
                        $interest_due_during_MonthM2 = $monthWiseData[$c['emi_date']]['interestReceived'] ?? 0;
                        $PrincipalDueduringthemonthJ2 = $c['principal_outstanding'];//$v['schedule'][$vp + 1]['principal'] ?? 0;
                        $dueAfterData = isset($v['schedule'][$vp + 1]['principal_outstanding']) ? $v['schedule'][$vp + 1]['principal_outstanding'] : 0;
                        $interest_overdueN2 = round($interest_due_during_MonthL2) - round($interest_due_during_MonthM2);
                        $principal_Overdue_H2 = $principalToBeReceivedTotal - $principalReceivedTotal;
                    }

                    if($c['emi_date'] >= $FDate1S && $c['emi_date'] <= $FDate1E && !$OverduePrincipalo_sE2){
                        $OverduePrincipalo_sE2 = $principalToBeReceivedTotal - $principalReceivedTotal;
                        $OverduePrincipalo_sD2 = $c['principal_outstanding'];//$principalReceivedTotal;
                        $interest_OS_beginning_OF_MonthK2 = $interestToBeReceivedMonth - $monthWiseData[$c['emi_date']]['interestReceived'];
                    }

                }

                $foreclosureAmtReceived = 0;
                if(isset($v['foreclosureData'])) {
                    foreach ($v['foreclosureData'] as $foreclosureAmt) {
                        if ($foreclosureAmt['payment_date'] <= $FDateE) {
                            $foreclosureAmtReceived += $foreclosureAmt['amount'];
                        }
                    }
                }

                if($v['schedule'][0]['emi_date'] >= $FDate1S && !$OverduePrincipalo_sD2){
                    $OverduePrincipalo_sD2 = $principalToBeReceivedTotal;//$principalReceivedTotal;
                }

                if($v['schedule'][0]['emi_date'] > $FDateE){
                    $PrincipalDueduringthemonthJ2 = $principalToBeReceivedTotal;//$v['schedule'][0]['principal_outstanding'];
                    //$PrincipalDueduringthemonthJ2 = $v['schedule'][0]['principal_outstanding'];
                }

                if($foreclosureAmtReceived && $dueAfterData){
                    $PrincipalDueduringthemonthJ2 = $foreclosureAmtReceived >= $dueAfterData ? 0 : $dueAfterData - $foreclosureAmtReceived;
                }


                //future emi payment received
                $futureEMIPaymentReceived = 0;
                    foreach($monthWiseData as $emi_date_r => $_monthWiseData){
                        if($emi_date_r > $FDateE){
                            $futureEMIPaymentReceived += $_monthWiseData['principalReceived'] ?? 0;
                        }
                    }

                    if($PrincipalDueduringthemonthJ2 && $futureEMIPaymentReceived){
                        $PrincipalDueduringthemonthJ2 = $futureEMIPaymentReceived >= $PrincipalDueduringthemonthJ2 ? 0 : $PrincipalDueduringthemonthJ2 - $futureEMIPaymentReceived;
                    }
                //end

                //$OverduePrincipalo_sD2 = $principalToBeReceivedTotal - $OverduePrincipalo_sD2;
                $dpdDaysCount = $isClosed ? 0 : $this->getDPDReport($item, $FDateE);

                $resView[$item] = ['id' => $item, 'principalReceivedTotal' => $principalReceivedTotal, 'pending p os' => $principalToBeReceivedTotal - $principalReceivedTotal, 'foreclosure' => $foreclosureAmtReceived, 'after foreclosure p os' => $isClosed ? 0 : ($foreclosureAmtReceived > ($principalToBeReceivedTotal - $principalReceivedTotal) ? 0 : ($principalToBeReceivedTotal - ($principalReceivedTotal + $foreclosureAmtReceived))), 'no_of_Installments_remaining' => $no_of_Installments_remainingC2, 'OverduePrincipalo_sE2' => $OverduePrincipalo_sE2];
                $resView1[$item] = ['id' => $item, 'C2' => $no_of_Installments_remainingC2, 'D2' => $OverduePrincipalo_sD2, 'E2' => $OverduePrincipalo_sE2, 'F2' => $PrincipalDueduringthemonthF2, 'G2' => $principal_Paid_during_the_monthG2, 'H2' => $principal_Overdue_H2, 'I2' => $dpdDaysCount, 'J2' => $PrincipalDueduringthemonthJ2, 'K2' => $interest_OS_beginning_OF_MonthK2, 'L2' => $interest_due_during_MonthL2, 'M2' => $interest_due_during_MonthM2, 'N2' => $interest_overdueN2, 'O2' => $foreclosureAmtReceived, 'J2Sec' => $resView[$item]['after foreclosure p os']];
            }catch (\Exception $e){

            }
        }

        (new Slack(new Request(['title' => 'NCD', 'fields' => ['file preparing' => 1], 'group' => Slack::$STAGE_TESTING])))->send();

        $resC = [];
        foreach($resView1 as $itemd){
            $resC[] = $itemd;
        }

        $response = array_merge($header, $resC);
//        $request = new Request(['data' => $response, 'sheet' => 'Sheet1']);
//        $file = 'Principal Outstanding_' . Carbon::now()->toDateString() . '.xls';
//        Excel::store(new Exporter($request), $file);

        $path1 = storage_path()."/NCD".time().".csv";
        $file = fopen($path1,"w");

        foreach ($response as $line) {
            fputcsv($file, $line);
        }

        fclose($file);
        (new Slack(new Request(['title' => 'NCD', 'fields' => ['file saved: sending' => 1], 'group' => Slack::$STAGE_TESTING])))->send();

          Mail::send('emails.reminders.basic_reminder',
            ['body' => 'NCD']
            , function ($message) use ($path1) {
                $message->to(['sunil@creditfair.in','sarah@creditfair.in','shrenik@creditfair.in', 'suyog@creditfair.in'])->subject('NCD');
                $message->attach($path1, ['as' => 'NCD']);
                //$message->attachData(file_get_contents(storage_path() . '/app/' . $file), $file);
            });
        (new Slack(new Request(['title' => 'NCD', 'fields' => ['file saved: sent' => 1], 'group' => Slack::$STAGE_TESTING])))->send();

        //unlink($path1);

    }

    public function getPrincipalsOutstandingAdityaV2($__date = '2021-03-31 23:59:59', $dpd_report = false, $application = false){
        $dd=[];
        if(!$dpd_report) {
            $apps = DB::select("select id, state from consumer_application where id in (select application_id from status_logs
            where status in ('disbursed', 'nach registered') and created_at <= '$__date' group by application_id) and is_deleted is null group by id desc");
            //$apps = DB::select("select id, state from consumer_application where id in (8153) and is_deleted is null group by id desc");

            $ddStatus = [];
            foreach($apps as $app){
                $dd[] = $app->id;
                $ddStatus[] = $app->id;
            }
        }else{
            $dd[] = $application;
        }


        $FDate = $__date;//'2021-03-31 23:59:59';
        $d = new AccountingController();
        $d->raw = true;
        $header[] = ['ID', 'principalReceivedTotal', 'pending p os', 'foreclosure', 'after foreclosure p os'];
        $resView = [];
        foreach($dd as $item) {
            try {
                $v = $d->getLoanScheduleDataV1($item);
                $statusLog = StatusLogs::where('application_id', $item)->whereIn('status', ['closed', 'cancelled'])->orderBy('created_at','desc')->first();
                $isClosed = 0;
                if($statusLog && strtotime($statusLog->created_at) <= strtotime($FDate)){
                    $isClosed = 1;
                }
                $principalToBeReceivedTotal = 0;
                $principalToBeReceivedMonth = 0;
                $monthWiseData = [];
                $principalReceivedTotal = 0;

                foreach($v['schedule'] as $c) {
                    $receivedOnMonth = 0;
                    foreach ($c['transaction'] as $transaction) {
                        if (strtotime($transaction->payment_date) <= strtotime($FDate) && !$transaction->refunded_at) {
                            $receivedOnMonth += $transaction->amount;
                        }
                    }

                    //if(strtotime($c['emi_date']) <= strtotime('2021-03-31 23:59:59')) {
                    $principalToBeReceivedTotal += $c['principal'];
                    $principalToBeReceivedMonth = $c['principal'];
                    //}

                    if($principalToBeReceivedMonth <= $receivedOnMonth){
                        $monthWiseData[$c['emi_date']]['principalReceived'] = $principalToBeReceivedMonth;
                    }else{
                        $monthWiseData[$c['emi_date']]['principalReceived'] = $receivedOnMonth;//$receivedOnMonth ? $principalToBeReceivedMonth - $receivedOnMonth : 0;
                    }

                    $principalReceivedTotal += $monthWiseData[$c['emi_date']]['principalReceived'];

                    /*if(strtotime($v['schedule'][0]['emi_date']) > strtotime('2021-03-31 23:59:59')) {
                        $principalToBeReceivedTotal += $c['principal'];
                    }*/


                }

                $foreclosureAmtReceived = 0;
                if(isset($v['foreclosureData'])) {
                    foreach ($v['foreclosureData'] as $foreclosureAmt) {
                        if (strtotime($foreclosureAmt['payment_date']) <= strtotime($FDate)) {
                            $foreclosureAmtReceived += $foreclosureAmt['amount'];
                        }
                    }
                }

                $resView[$item] = ['id' => $item, 'principalReceivedTotal' => $principalReceivedTotal, 'pending p os' => $principalToBeReceivedTotal - $principalReceivedTotal, 'foreclosure' => $foreclosureAmtReceived, 'after foreclosure p os' => $isClosed ? 0 : ($foreclosureAmtReceived > ($principalToBeReceivedTotal - $principalReceivedTotal) ? 0 : ($principalToBeReceivedTotal - ($principalReceivedTotal + $foreclosureAmtReceived))), 'interest' => $c['interest']];
            }catch (\Exception $e){

            }
        }

        $resC = [];
        foreach($resView as $itemd){
            $resC[] = $itemd;
        }

        if($dpd_report){
            return $resC;
        }
        $response = array_merge($header, $resC);
//        $request = new Request(['data' => $response, 'sheet' => 'Sheet1']);
//        $file = 'Principal Outstanding_' . Carbon::now()->toDateString() . '.xls';
//        Excel::store(new Exporter($request), $file);

        $path1 = storage_path()."/Principal_Outstanding_".time().".csv";
        $file = fopen($path1,"w");

        foreach ($response as $line) {
            fputcsv($file, $line);
        }

        fclose($file);

        Mail::send('emails.reminders.basic_reminder',
            ['body' => 'Principal Outstanding']
            , function ($message) use ($path1) {
                $message->to(['sunil@creditfair.in','sarah@creditfair.in'])->subject('Principal Outstanding');
                $message->attach($path1, ['as' => 'Principal_Outstanding']);
                //$message->attachData(file_get_contents(storage_path() . '/app/' . $file), $file);
            });

        unlink($path1);

    }

    public function getPrincipalsOutstandingforCases(){
        $dd=[];
        $application_ids = [126418,117336,129500,130548,129654,130733,131992,130932,129334,132073,130844,132292,128625,132473,131099,132754,129909,130338,132671,130309,131711,133288,133171,133091,131661,130873,133305,131950,126750,132796,131193,129764,131656,128972,133476,129010,132882,132443,133533,133148,133884,134029,133578,133973,131043,133993,133935,131903,133963,133958,126508,132295,134387,132597,131673,133851,132563,134216,127028,134418,132214,133961,134290,125670,129576,134534,134969,129718,129998,131178,133129,130765,133784,131856,135758,134190,133127,131994,134452,134279,135899,130139,130897,133150,135354,133016,132501,136325,136068,130944,134932,137270,133010,131388,129327,138145,138310,131483,137303,138225,138341,136126,133535,136059,121037,134778,135669,137740,138117,132096,134242,137574,138407,133783,135802,121396,133586,140562,137180,136060,141415,136882,138860,140865,136440,141331,131385,141513,142025,142252,142334,142231,136282,144227,141460,140853,139584,139087,143332,122799,144270,142639,144578,144539,144607,141495,142493,143478,118137,116863,141931,145188,142629,142672,145233,143938,139107,141581,135434,144530,144821,145825,132335,146444,147054,145938,142097,146001,144107,145664,138866,145498,146724,141462,147693,145384,145309,140440];
//        if(!$dpd_report) {
//            $apps = DB::select("select id, state from consumer_application where id in (select application_id from status_logs
//            where status in ('disbursed', 'nach registered') group by application_id) and is_deleted is null group by id desc");
        $apps = DB::select("select id, state from consumer_application where id in (".implode(",",$application_ids).") and is_deleted is null");

        $ddStatus = [];
        foreach($apps as $app){
            $dd[] = $app->id;
            $ddStatus[] = $app->id;
        }
//        }else{
//            $dd[] = $application;
//        }


        $FDate = Carbon::now()->toDateTimeString();//'2021-03-31 23:59:59';
        $d = new AccountingController();
        $d->raw = true;
        $header[] = ['ID', 'principalReceivedTotal', 'pending p os', 'foreclosure', 'after foreclosure p os'];

        foreach($dd as $item) {
            try {
                $v = $d->getLoanScheduleDataV1($item);
                $statusLog = StatusLogs::where('application_id', $item)->whereIn('status', ['closed', 'cancelled'])->orderBy('created_at','desc')->first();
                $isClosed = 0;
                if($statusLog && strtotime($statusLog->created_at) <= strtotime($FDate)){
                    $isClosed = 1;
                }
                $principalToBeReceivedTotal = 0;
                $principalToBeReceivedMonth = 0;
                $monthWiseData = [];
                $principalReceivedTotal = 0;

                foreach($v['schedule'] as $c) {
                    $receivedOnMonth = 0;
                    foreach ($c['transaction'] as $transaction) {
                        if (strtotime($transaction->payment_date) <= strtotime($FDate) && !$transaction->refunded_at) {
                            $receivedOnMonth += $transaction->amount;
                        }
                    }

                    //if(strtotime($c['emi_date']) <= strtotime('2021-03-31 23:59:59')) {
                    $principalToBeReceivedTotal += $c['principal'];
                    $principalToBeReceivedMonth = $c['principal'];
                    //}

                    if($principalToBeReceivedMonth <= $receivedOnMonth){
                        $monthWiseData[$c['emi_date']]['principalReceived'] = $principalToBeReceivedMonth;
                    }else{
                        $monthWiseData[$c['emi_date']]['principalReceived'] = $receivedOnMonth;//$receivedOnMonth ? $principalToBeReceivedMonth - $receivedOnMonth : 0;
                    }

                    $principalReceivedTotal += $monthWiseData[$c['emi_date']]['principalReceived'];

                    /*if(strtotime($v['schedule'][0]['emi_date']) > strtotime('2021-03-31 23:59:59')) {
                        $principalToBeReceivedTotal += $c['principal'];
                    }*/


                }

                $foreclosureAmtReceived = 0;
                if(isset($v['foreclosureData'])) {
                    foreach ($v['foreclosureData'] as $foreclosureAmt) {
                        if (strtotime($foreclosureAmt['payment_date']) <= strtotime($FDate)) {
                            $foreclosureAmtReceived += $foreclosureAmt['amount'];
                        }
                    }
                }

                $resView[$item] = ['id' => $item, 'principalReceivedTotal' => $principalReceivedTotal, 'pending p os' => $principalToBeReceivedTotal - $principalReceivedTotal, 'foreclosure' => $foreclosureAmtReceived, 'after foreclosure p os' => $isClosed ? 0 : ($foreclosureAmtReceived > ($principalToBeReceivedTotal - $principalReceivedTotal) ? 0 : ($principalToBeReceivedTotal - ($principalReceivedTotal + $foreclosureAmtReceived))), 'interest' => $c['interest']];
            }catch (\Exception $e){

            }
        }

        $resC = [];
        foreach($resView as $itemd){
            $resC[] = $itemd;
        }
//
//        if($dpd_report){
//            return $resC;
//        }
        $response = array_merge($header, $resC);
//        $request = new Request(['data' => $response, 'sheet' => 'Sheet1']);
//        $file = 'Principal Outstanding_' . Carbon::now()->toDateString() . '.xls';
//        Excel::store(new Exporter($request), $file);

        $path1 = storage_path()."/Principal_Outstanding_".time().".csv";
        $file = fopen($path1,"w");

        foreach ($response as $line) {
            fputcsv($file, $line);
        }

        fclose($file);

        Mail::send('emails.reminders.basic_reminder',
            ['body' => 'Principal Outstanding']
            , function ($message) use ($path1) {
                $message->to(['sunil@creditfair.in','sarah@creditfair.in'])->subject('Principal Outstanding');
                $message->attach($path1, ['as' => 'Principal_Outstanding']);
                //$message->attachData(file_get_contents(storage_path() . '/app/' . $file), $file);
            });

        unlink($path1);

    }

    public function getPrincipalsOutstandingAdityaV1(){
        $apps = DB::select("select id from consumer_application where id in (select application_id from status_logs where status in ('disbursed', 'nach registered') and created_at <= '2021-03-31 23:59:59' group by application_id) and is_deleted is null group by id desc");
        foreach($apps as $app){
            $dd[] = $app->id;
        }

        $d = new AccountingController();
        $d->raw = true;
        $header[] = ['ID', 'Total Principal', 'Received Till 31 March'];
        foreach($dd as $item) {
            try {
                $isFetch = 0;
                $res = ['id' => $item, 'principal_outstanding' => 0, 'received' => 0, 'principal' => 0];
                $v = $d->getLoanScheduleDataV1($item);
                $principalTotal = 0;
                $carry = 0;
                $receivedTotal = 0;
                $principal = 0;
                $received = 0;
                $priPending =0;
                $allS = 1;

                foreach($v['schedule'] as $c) {
                    foreach ($c['transaction'] as $transaction) {
                        if (strtotime($transaction->payment_date) <= strtotime('2021-03-31 23:59:59')) {
                            $receivedTotal += $transaction->amount;
                            $received += $transaction->amount;
                        }
                    }

                    if(strtotime($c['emi_date']) <= strtotime('2021-03-31 23:59:59')) {
                        $principalTotal += $c['principal'];
                        $principal = $c['principal'];
                        if($received <= $c['principal']){
                            $carry += $c['principal'] - $received;
                        }
                        if (strtotime($c['emi_date']) >= strtotime('2021-03-01 00:00:00') && strtotime($c['emi_date']) <= strtotime('2021-03-31 23:59:59')) {
                            $res = ['id' => $item, 'principal_outstanding' => $c['fore_closure_amount'] + $carry, 'received' => $received];
                            $isFetch = 1;
                        }
                        $received = 0;
                    }

                    if($c['payment_status'] == 'pending' && strtotime($c['emi_date']) < strtotime('2021-03-01 00:00:00')){
                        $priPending += $c['principal'];
                    }

                }



                if(isset($received) && $received && isset($res[$item])){
                    $res['principal_outstanding'] -= $received;
                }else if(!$isFetch && isset($v['schedule'][0]['fore_closure_amount'])){
                    $res['principal_outstanding'] = $v['schedule'][0]['fore_closure_amount'] - $received;
                }

                if(strtotime($v['schedule'][0]['emi_date']) > strtotime('2021-03-31 23:59:59')){
                    $res['principal_outstanding'] = $v['schedule'][0]['fore_closure_amount'] - $received;
                }

                if($priPending){
                    $res['principal_outstanding'] = $priPending;
                }

                $isFetch = 0;

                if($res){
                    $res['received'] = $receivedTotal;
                }
                $res['id'] = $item;

                if(strtotime($v['schedule'][0]['emi_date']) > strtotime('2021-03-31 23:59:59')){
                    $res['principal'] = $v['schedule'][0]['principal'];
                }

                $resView[$item] = $res;
            }catch (\Exception $e){

            }
        }

        $resC = [];
        foreach($resView as $itemd){
            $resC[] = $itemd;
        }

        $response = array_merge($header, $resC);
//        $request = new Request(['data' => $response, 'sheet' => 'Sheet1']);
//        $file = 'Principal Outstanding_' . Carbon::now()->toDateString() . '.xls';
//        Excel::store(new Exporter($request), $file);

        $path1 = storage_path()."/Principal_Outstanding_".time().".csv";
        $file = fopen($path1,"w");

        foreach ($response as $line) {
            fputcsv($file, $line);
        }

        fclose($file);

        Mail::send('emails.reminders.basic_reminder',
            ['body' => 'Principal Outstanding']
            , function ($message) use ($path1) {
                $message->to(['sunil@creditfair.in'])->subject('Principal Outstanding');
                $message->attach($path1, ['as' => 'Principal_Outstanding']);
                //$message->attachData(file_get_contents(storage_path() . '/app/' . $file), $file);
            });

        unlink($path1);

    }

    public function getPrincipalsOutstandingAditya($type){
        //$dd = [63292,59528,57524,55987,51792,51484,51432,51008,49649,48979,48770,48587,48092,47999,47844,46902,46469,45017,44523,44487,44456,43835,43699,43651,42791,42234,42150,41900,41845,39727,38505,37520,37003,35927,35815,33622,33620,33419,32593,32181,32111,31908,31863,31550,31320,30854,30737,29890,29872,29866,29650,29478,29208,28860,28683,28633,28561,28545,28476,28449,28285,28193,27977,27827,27778,27599,27486,27464,27450,27355,27267,27205,27066,27057,26868,26791,26753,26676,26301,26295,26238,25785,25694,25637,25250,25109,25075,24963,24859,24827,24709,24593,24560,24504,24494,24418,24403,24355,24181,24072,24026,23971,23964,23903,23893,23887,23855,23849,23778,23705,23503,23495,23479,23093,22842,22837,22827,22793,22576,22476,22415,22345,22326,22205,22031,22007,21779,21692,21484,21203,21184,20701,20288,19861,19405,19402,19338,19105,18769,18659,18559,18273,18222,18149,18016,17921,17544,17506,17420,17298,17290,17145,16972,16825,14222,14182,14148,14143,14084,14047,14033,13915,13886,13861,13840,13813,13786,13724,13702,13676,13608,13581,13572,13526,13506,13490,13485,13413,13384,13350,13349,13335,13269,13259,13193,13166,13142,12893,12878,12707,12693,12667,12630,12619,12594,11683,11633,11537,11529,11524,11513,11460,11456,11441,11408,11407,11402,11395,11373,11349,11337,11302,11286,11270,11262,11135,11128,11115,11105,11093,11051,11041,11023,10995,10971,10942,10932,10895,10867,10865,10794,10772,10771,10762,10748,10735,10709,10689,10674,10652,10648,10615,10612,10600,10587,10586,10569,10557,10556,10540,10523,10521,10510,10415,10387,10370,10367,10364,10312,10285,10268,10220,10160,10134,10124,10109,10101,10071,10062,10028,10026,10020,10013,10005,10001,9973,9967,9954,9912,9886,9865,9860,9857,9852,9802,9798,9742,9707,9706,9642,9636,9611,9603,9578,9543,9504,9483,9477,9468,9450,9430,9409,9404,9392,9342,9341,9336,9281,9267,9261,9229,9214,9151,9137,9103,9040,9035,8997,8995,8945,8930,8919,8900,8890,8877,8843,8796,8770,8718,8662,8638,8612,8576,8547,8357,8239,8217,8151,8076,7984,7958,7883,7871,7869,7824,7811,7810,7783,7774,7771,7726,7721,7673,7670,7613,7580,7570,7529,7523,7486,7472,7433,7376,7362,7360,7348,7323,7319,7282,7279,7273,7237,7224,7222,7193,7155,7086,7082,7039,7017,6992,6985,6975,6957,6934,6931,6928,6924,6914,6854,6848,6842,6839,6813,6805,6775,6730,6702,6691,6649,6635,6551,6526,6513,6510,6509,6460,6441,6433,6389,6376,6331,6324,6317,6300,6294,6282,6248,6245,6232,6216,6208,6168,6157,6078,6062,6054,6052,6025,6007,5988,5978,5927,5876,5859,5854,5850,5806,5790,5773,5765,5731,5640,5586,5583,5508,5491,5474,5438,5401,5260,5242,5210,5169,5120,5106,5073,4990,4969,4948,4939,4914,4895,4881,4774,4738,4736,4651,4643,4641,4457,4425,4415,4405,4372,4336,4302,4275,4239,4182,4180,4169,4140,4138,4137,4126,4108,4104,4070,4065,4059,4036,4030,3985,3968,3958,3927,3921,3914,3912,3893,3884,3881,3845,3786,3784,3778,3742,3673,3654,3650,3619,3609,3604,3592,3574,3559,3555,3541,3518,3499,3481,3405,3403,3339,3326,3323,3301,3293,3284,3255,3240,3235,3223,3197,3191,3189,3178,3176,3169,3163,3140,3128,3113,3068,3047,3001,2986,2965,2959,2940,2920,2910,2875,2819,2807,2801,2788,2777,2754,2735,2707,2606,2592,2566,2522,2518,2330,2307,2295,2278,2274,2273,2269,2239,2236,2217,2212,2194,2193,2160,2159,2147,2145,2094,2067,2064,2059,2055,2043,2035,2016,1951,1943,1942,1940,1887,1872,1740,1723,1689,1683,1671,1616,1495,1257,1242,1217,1215,1011,996,922,881,803,735,662,586,325,124,121,58];
        if($type == 1) {
            $apps = DB::select("select id,state from consumer_application where id in (select application_id from status_logs where status in ('disbursed', 'nach registered') and created_at <= '2021-03-31 23:59:59' group by application_id) and is_deleted is null group by id desc");
        }else {
            $apps = DB::select("select id,state from consumer_application where id in (select application_id from emi_payments where emi_date like '%2021-03%' group by application_id) and is_deleted is null");
        }
        $dd = [];
        foreach($apps as $app){
            $dd[] = $app->id;
            $ddStatus[$app->id] = $app->state;
        }

        /*$appsNotActive = [];
        $logs = StatusLogs::whereIn('application_id', $dd)->where('status',['cancelled', 'cancellation in-process', 'closed'])->where('created_at', '>=','2021-03-01 00:00:00')->where('created_at', '<=','2021-03-01 23:59:59')->get(['application_id']);
        foreach($apps as $app){
            $appsNotActive[] = $app->id;
        }*/

        $elements = ConsumerApplicationElement::whereIn('application_id', $dd)->get(['application_id', 'last_emi_date']);

        $prZero = [];
        foreach($elements as $element){
            if(isset($ddStatus[$element->application_id]) && in_array($ddStatus[$element->application_id], ['closed', 'cancelled']) && strtotime($element->last_emi_date) < strtotime('2021-03-31 00:00:00')){
                $prZero[] = $element->application_id;
            }
        }


        $res = [];
        $d = new AccountingController();
        $request = new Request(['job_raw' => true]);
        $header[] = ['ID', 'EMI Date', 'Principal', 'Interest', 'Total Pri', 'Total Pri 1', 'Foreclosure Amount','Receivable', 'Received', 'Due'];
        foreach($dd as $item){
            try {

                $total_pri = 0;
                $v = $d->getPaymentsV1($request, $item);
                if(isset($v['scheduleData'])) {
                    $scheduleData = $v['scheduleData'];
                    $schD = [];
                    foreach ($scheduleData as $scheduleItem) {
                        $schD[$scheduleItem['emi_date']] = $scheduleItem;
                    }
                }
                foreach ($v['paymentsData'] as $c) {
                    if(1) {
                        $kk = ['receivable' => ($c->emi_amount + $c->bounce_charges + $c->delay_penalty), 'received' => ((($c->emi_amount + $c->bounce_charges + $c->delay_penalty)) - $c->amount_due), 'due' => $c->amount_due];
                        $principal = isset($schD[$c->emi_date]['principal']) ? round($schD[$c->emi_date]['principal']) : 0;
                        $interest = isset($schD[$c->emi_date]['interest']) ? round($schD[$c->emi_date]['interest']) : 0;

                        if(strtotime($c->emi_date) > strtotime('2021-03-31 23:59:59')){
                            $total_pri += $principal;
                        }else{
                            if ($kk['received'] < $principal){
                                $total_pri += $principal - $kk['received'];
                            }
                            //$total_pri += $principal;
                        }

                        $res[] = [
                            'id' => $c->application_id,
                            'emi_date' => $c->emi_date,
                            'principal' => $principal,
                            'interest' => $interest,
                            'total_pri' => $total_pri,
                            'final_tpri' => in_array($c->application_id, $prZero) ? 0 : $total_pri,
                            'foreclosure_amount_cals' => $v['foreclosure_amount_cals'],
                            'receivable' => $kk['receivable'],
                            'received' => $kk['received'],
                            'due' => $kk['due'],
                        ];
                    }
                }
            }catch (\Exception $e){

            }
        }
        $response = array_merge($header, $res);
//        $request = new Request(['data' => $response, 'sheet' => 'Sheet1']);
//        $file = 'Principal Outstanding_' . Carbon::now()->toDateString() . '.xls';
//        Excel::store(new Exporter($request), $file);

        $path1 = storage_path()."/Principal_Outstanding_".time().".csv";
        $file = fopen($path1,"w");

        foreach ($response as $line) {
            fputcsv($file, $line);
        }

        fclose($file);

        Mail::send('emails.reminders.basic_reminder',
            ['body' => 'Principal Outstanding']
            , function ($message) use ($path1) {
                $message->to(['sunil@creditfair.in'])->subject('Principal Outstanding');
                $message->attach($path1, ['as' => 'Principal_Outstanding']);
                //$message->attachData(file_get_contents(storage_path() . '/app/' . $file), $file);
            });

        unlink($path1);
    }


    function XIRR($values, $dates, $guess = 0.1) {
        $x1 = 0.0;
        $x2 = $guess;
        $f1 = $this->XNPV($x1, $values, $dates);
        $f2 = $this->XNPV($x2, $values, $dates);
        for ($i = 0; $i < 128; ++$i) {
            if (($f1 * $f2) < 0.0) break;
            if (abs($f1) < abs($f2)) {
                $f1 = $this->XNPV($x1 += 1.6 * ($x1 - $x2), $values, $dates);
            } else {
                $f2 = $this->XNPV($x2 += 1.6 * ($x2 - $x1), $values, $dates);
            }
        }

        $f = $this->XNPV($x1, $values, $dates);
        if ($f < 0.0) {
            $rtb = $x1;
            $dx = $x2 - $x1;
        } else {
            $rtb = $x2;
            $dx = $x1 - $x2;
        }

        for ($i = 0;  $i < FINANCIAL_MAX_ITERATIONS; ++$i) {
            $dx *= 0.5;
            $x_mid = $rtb + $dx;
            $f_mid = $this->XNPV($x_mid, $values, $dates);
            if ($f_mid <= 0.0) $rtb = $x_mid;

            if ((abs($f_mid) < FINANCIAL_PRECISION) || (abs($dx) < FINANCIAL_PRECISION)) return $x_mid;
        }

    }



    function XNPV($rate, $values, $dates) {

        $valCount = count($values);
        $xnpv = 0.0;
        for ($i = 0; $i < $valCount; ++$i)
        {

            $datediff = strtotime($dates[$i]) - strtotime($dates[0]);
            $datediff =  round($datediff / (60 * 60 * 24));
            $xnpv += $values[$i] / pow(1 + $rate,$datediff / 365);
        }
        return $xnpv;
    }

    public function getPrincipalsOutstanding(){
        $apps = [77803,
            77766,
            77106,
            77012,
            76938,
            76856,
            76655,
            76453,
            76241,
            76063,
            76029,
            75826,
            75654,
            75507,
            75446,
            75150,
            75116,
            74441,
            74272,
            74140,
            73945,
            73667,
            73592,
            73497,
            73157,
            72774,
            72706,
            72680,
            71732,
            71043,
            71036,
            70768,
            69888,
            69847,
            69625,
            69518,
            69154,
            68966,
            68248,
            68223,
            68195,
            67824,
            67734,
            67710,
            67614,
            66712,
            66409,
            65978,
            65683,
            65388,
            65282,
            65126,
            64873,
            64139,
            63318,
            63292,
            62639,
            62629,
            61974,
            61874,
            61216,
            60645,
            59946,
            59870,
            57524,
            56788,
            55987,
            55667,
            52983,
            51792,
            51484,
            51432,
            51314,
            51008,
            49649,
            48979,
            48770,
            48587,
            47999,
            47844,
            47830,
            47126,
            46902,
            46469,
            45017,
            44487,
            44456,
            43835,
            43651,
            43124,
            42791,
            42234,
            42219,
            42150,
            41900,
            41845,
            40226,
            40092,
            39968,
            38505,
            37520,
            37229,
            37003,
            35927,
            35815,
            34627,
            34242,
            33620,
            33419,
            33144,
            32593,
            32111,
            31863,
            31550,
            31320,
            30737,
            29890,
            29872,
            29866,
            29650,
            29478,
            28860,
            28683,
            28633,
            28561,
            28545,
            28285,
            28193,
            28176,
            27977,
            27827,
            27599,
            27464,
            27450,
            27424,
            27355,
            27267,
            27205,
            27095,
            26863,
            26839,
            26793,
            26791,
            26779,
            26753,
            26676,
            26576,
            26301,
            26295,
            26091,
            25785,
            25694,
            25637,
            25545,
            25494,
            25297,
            25250,
            25109,
            25075,
            24963,
            24859,
            24827,
            24709,
            24593,
            24560,
            24504,
            24494,
            24418,
            24403,
            24181,
            24026,
            23964,
            23893,
            23887,
            23855,
            23705,
            23503,
            23495,
            23093,
            22842,
            22837,
            22827,
            22793,
            22576,
            22345,
            22205,
            22031,
            21779,
            21692,
            21671,
            21484,
            21203,
            20701,
            20288,
            19861,
            19405,
            19402,
            19338,
            19232,
            19105,
            18659,
            18559,
            18222,
            18149,
            18016,
            17921,
            17544,
            17506,
            17420,
            17298,
            17290,
            17145,
            16972,
            16825,
            14222,
            14182,
            14148,
            14143,
            14084,
            14033,
            13915,
            13886,
            13861,
            13840,
            13813,
            13786,
            13724,
            13702,
            13676,
            13608,
            13581,
            13572,
            13526,
            13506,
            13490,
            13485,
            13413,
            13350,
            13349,
            13335,
            13269,
            13259,
            13193,
            13166,
            13142,
            12893,
            12878,
            12707,
            12667,
            12630,
            12619,
            12594,
            11683,
            11633,
            11537,
            11529,
            11524,
            11513,
            11460,
            11456,
            11441,
            11408,
            11407,
            11402,
            11395,
            11373,
            11349,
            11337,
            11302,
            11286,
            11270,
            11262,
            11135,
            11128,
            11115,
            11105,
            11093,
            11051,
            11041,
            11023,
            10995,
            10971,
            10942,
            10932,
            10895,
            10867,
            10865,
            10794,
            10772,
            10771,
            10762,
            10748,
            10735,
            10709,
            10689,
            10652,
            10648,
            10615,
            10612,
            10600,
            10587,
            10586,
            10569,
            10557,
            10556,
            10540,
            10523,
            10521,
            10510,
            10415,
            10387,
            10370,
            10367,
            10364,
            10312,
            10285,
            10268,
            10220,
            10160,
            10134,
            10124,
            10109,
            10101,
            10095,
            10062,
            10026,
            10020,
            10013,
            10005,
            10001,
            9973,
            9967,
            9912,
            9865,
            9860,
            9857,
            9852,
            9802,
            9798,
            9742,
            9707,
            9706,
            9642,
            9636,
            9611,
            9603,
            9578,
            9543,
            9483,
            9477,
            9468,
            9450,
            9430,
            9409,
            9404,
            9392,
            9342,
            9341,
            9336,
            9281,
            9267,
            9261,
            9229,
            9214,
            9151,
            9137,
            9103,
            9040,
            9035,
            8997,
            8995,
            8945,
            8930,
            8919,
            8900,
            8890,
            8877,
            8843,
            8796,
            8770,
            8718,
            8662,
            8638,
            8612,
            8576,
            8547,
            8239,
            8217,
            8151,
            8076,
            7984,
            7883,
            7871,
            7869,
            7824,
            7811,
            7810,
            7783,
            7774,
            7771,
            7726,
            7721,
            7673,
            7670,
            7613,
            7580,
            7570,
            7529,
            7523,
            7486,
            7472,
            7433,
            7376,
            7362,
            7360,
            7348,
            7323,
            7319,
            7282,
            7273,
            7237,
            7224,
            7222,
            7193,
            7155,
            7086,
            7082,
            7039,
            7017,
            6992,
            6985,
            6975,
            6934,
            6931,
            6928,
            6924,
            6914,
            6854,
            6848,
            6842,
            6839,
            6813,
            6805,
            6775,
            6730,
            6702,
            6691,
            6649,
            6635,
            6551,
            6526,
            6513,
            6510,
            6509,
            6460,
            6441,
            6433,
            6389,
            6376,
            6324,
            6317,
            6300,
            6294,
            6282,
            6248,
            6245,
            6232,
            6216,
            6208,
            6168,
            6157,
            6078,
            6062,
            6054,
            6052,
            6025,
            6007,
            5988,
            5978,
            5927,
            5876,
            5859,
            5854,
            5850,
            5806,
            5790,
            5773,
            5765,
            5731,
            5640,
            5583,
            5508,
            5491,
            5474,
            5438,
            5401,
            5260,
            5210,
            5169,
            5120,
            5106,
            5073,
            4990,
            4969,
            4948,
            4939,
            4914,
            4895,
            4881,
            4774,
            4738,
            4736,
            4651,
            4643,
            4641,
            4457,
            4425,
            4415,
            4405,
            4372,
            4336,
            4302,
            4275,
            4239,
            4182,
            4180,
            4169,
            4140,
            4138,
            4137,
            4126,
            4108,
            4070,
            4065,
            4059,
            4036,
            4030,
            3985,
            3968,
            3958,
            3927,
            3921,
            3914,
            3912,
            3893,
            3884,
            3881,
            3845,
            3786,
            3778,
            3742,
            3673,
            3654,
            3650,
            3619,
            3609,
            3604,
            3592,
            3574,
            3559,
            3555,
            3541,
            3518,
            3499,
            3481,
            3405,
            3403,
            3339,
            3326,
            3323,
            3301,
            3293,
            3284,
            3255,
            3240,
            3235,
            3223,
            3197,
            3191,
            3189,
            3178,
            3176,
            3169,
            3163,
            3140,
            3128,
            3113,
            3068,
            3047,
            3001,
            2965,
            2959,
            2940,
            2920,
            2910,
            2875,
            2819,
            2807,
            2801,
            2788,
            2777,
            2754,
            2735,
            2707,
            2606,
            2592,
            2566,
            2522,
            2518,
            2330,
            2307,
            2295,
            2278,
            2274,
            2273,
            2269,
            2239,
            2236,
            2217,
            2212,
            2194,
            2193,
            2160,
            2159,
            2147,
            2145,
            2094,
            2067,
            2064,
            2059,
            2055,
            2043,
            2035,
            2016,
            1990,
            1951,
            1943,
            1942,
            1940,
            1887,
            1872,
            1740,
            1723,
            1689,
            1683,
            1671,
            1616,
            1495,
            1257,
            1242,
            1217,
            1215,
            1011,
            996,
            922,
            881,
            803,
            662,
            586,
            325,
            124,
            121,
            58];
        //$apps = DB::select("select id from consumer_application where id in (select application_id from status_logs where status in ('disbursed', 'nach registered') and created_at <= '2021-03-31 23:59:59' group by application_id) and state in ('disbursed', 'nach registered') and is_deleted is null group by id desc");
        $dd = [];
        foreach($apps as $app){
            $dd[] = $app;
        }
        $res = [];
        $d = new AccountingController();
        $request = new Request(['job_raw' => true]);
        $header[] = ['ID', 'EMI Date', 'EMI Amount', 'Principal', 'Interest', 'Bounce Amount', 'Penal Amount', 'Charges Waived', 'Total Due Amount', 'Amount Due', 'Moratorium'];
        foreach($dd as $k => $item){
            try {
                $v = $d->getPaymentsV1($request, $item);
                if(isset($v['scheduleData'])) {
                    $scheduleData = $v['scheduleData'];
                    $schD = [];
                    foreach ($scheduleData as $scheduleItem) {
                        $schD[$scheduleItem['emi_date']] = $scheduleItem;
                    }
                }
                foreach ($v['paymentsData'] as $c) {
                    if(strtotime($c->emi_date) <= Carbon::now()->endOfDay()->timestamp) {
                        $kk = ['receivable' => ($c->emi_amount + $c->bounce_charges + $c->delay_penalty), 'received' => ((($c->emi_amount + $c->bounce_charges + $c->delay_penalty)) - $c->amount_due), 'due' => $c->amount_due];
                        $balance = $kk['received'] - ($c->emi_amount - (is_null($c->moratorium_amount) ? 0 : $c->moratorium_amount));
                        $breakUp = ['emi_amount' => $c->emi_amount - (is_null($c->moratorium_amount) ? 0 : $c->moratorium_amount), 'bounce_charges' => $c->bounce_charges, 'delay_penalty' => $c->delay_penalty, 'moratorium_amount' => $c->moratorium_amount];
                        if ($balance >= 0) {
                            $breakUp['emi_amount'] = 'EMI Paid';
                        }
                        if ($c->bounce_charges) {
                            $balance = $balance - $c->bounce_charges;
                            if ($balance >= 0) {
                                $breakUp['bounce_charges'] = 'Bounce Paid';
                            }
                        }
                        if ($c->delay_penalty) {
                            $balance = $balance - $c->delay_penalty;
                            if ($balance >= 0) {
                                $breakUp['delay_penalty'] = 'Penal Paid';
                            }
                        }

                        if ($c->moratorium_amount) {
                            $balance = $balance - $c->moratorium_amount;
                            if ($balance >= 0) {
                                $breakUp['moratorium_amount'] = 'Moratorium Paid';
                            }
                        }

                        $res[] = [
                            'id' => $c->application_id,
                            'emi_date' => $c->emi_date,
                            //'emi_amount' => ($c->emi_amount - (is_null($c->moratorium_amount) ? 0 : $c->moratorium_amount)) - $c->amount_due > $c->amount_due ? 'EMI Paid' : ($c->emi_amount - (is_null($c->moratorium_amount) ? 0 : $c->moratorium_amount)),
                            'emi_amount' => $breakUp['emi_amount'],
                            'principal' => isset($schD[$c->emi_date]['principal']) ? round($schD[$c->emi_date]['principal']) : 0,
                            'interest' => isset($schD[$c->emi_date]['interest']) ? round($schD[$c->emi_date]['interest']) : 0,
                            //'bounce_charges' => ($c->bounce_charges - (is_null($c->moratorium_amount) ? 0 : $c->moratorium_amount)) - $c->amount_due > ($c->amount_due - ($c->emi_amount - (is_null($c->moratorium_amount) ? 0 : $c->moratorium_amount))) ? 'Bounce Paid' : $c->bounce_charges,
                            //'delay_penalty' => ($c->delay_penalty - ($c->amount_due - ((is_null($c->moratorium_amount) ? 0 : $c->moratorium_amount)) + $c->bounce_charges)) > ($c->amount_due - ($c->emi_amount - ($c->bounce_charges + (is_null($c->moratorium_amount) ? 0 : $c->moratorium_amount)))) ? 'Penal Paid' : $c->delay_penalty,
                            'bounce_charges' => $breakUp['bounce_charges'],
                            'delay_penalty' => $breakUp['delay_penalty'],
                            'charges_waived' => $c->charges_waived,
                            'total_amount_due' => $v['application']->application_element->amount_over_due,
                            'amount_due' => $c->amount_due,
                            //'moratorium_amount' => $c->moratorium_amount > 0 && $c->payment_status == 'success' ? 'Moratorium Paid' : ($c->moratorium_amount > 0 ? $c->moratorium_amount : 0),
                            'moratorium_amount' => $breakUp['moratorium_amount'],
                        ];
                    }
                }
            }catch (\Exception $e){

            }
        }
        $response = array_merge($header, $res);
        $request = new Request(['data' => $response, 'sheet' => 'Sheet1']);
        $file = 'Principal Outstanding_' . Carbon::now()->toDateString() . '.xls';
        Excel::store(new Exporter($request), $file);

        Mail::send('emails.reminders.basic_reminder',
            ['body' => 'Principal Outstanding']
            , function ($message) use ($file) {
                $message->to(['sunil@creditfair.in', 'imran@creditfair.in'])->subject('Principal Outstanding');
                $message->attachData(file_get_contents(storage_path() . '/app/' . $file), $file);
            });

        unlink(file_get_contents(storage_path() . '/app/' . $file));
    }

    public function getAutoDecisionRulesData($id = false, $iteration=false){

        $securedLoansList = ['Personal Loan','Credit Card','Business Loan','Education Loan','Consumer Loan'];

        if($id){
            $applicationIds = [$id];
            $applications = ConsumerApplication::with('creditReport','foir','finBitDataBorrower','emi', 'equifax_report')
                ->whereIn('id', $applicationIds)->whereNull('is_deleted')
                ->get(['id','monthly_income','dob','current_address_pincode','employee_status']);
        }else{
            if(isset($iteration)){
                $limit = 10000;
                $skip = $limit;
                $applications = ConsumerApplication::with('creditReport','foir','finBitDataBorrower','emi', 'equifax_report')
                    ->whereNull('is_deleted')->orderBy('created_at', 'desc')->skip($skip*$iteration)->limit($limit)
                    ->get(['id','monthly_income','dob','current_address_pincode','employee_status']);
            }else{
                (new \App\Slack(new Request(['title' => 'Iteration not defined'])))->send();
            }
        }



        $request = new Request();

        $response = [];

        foreach (array_chunk((array)$applications, 1000) as $applicationItems){
            foreach ($applicationItems[0] as $application) {
                $negativeArea = NegativeArea::where('pincode', $application->current_address_pincode)->first(['level']);
                $negativeAreaStatus = false;
                if (isset($negativeArea->level)) {
                    $negativeAreaStatus = true;
                }

                $exceptionStatus = true;
                $approvalStatus = true;

                $rejectionStatus = $this->runRejectionRules($application, $securedLoansList);

                if (!$rejectionStatus) {
                    $exceptionStatus = $this->runExceptionRules($application, $securedLoansList, $negativeAreaStatus, $request);

                    if (!$exceptionStatus) {
                        $approvalStatus = $this->runApprovalRules($application, $securedLoansList, $negativeAreaStatus, $request);
                    }
                }

                $response[$application->id] = ['messages' => $this->decisionMessageBug, 'Rejection' => $rejectionStatus, 'Exception' => $exceptionStatus, 'Approval' => $approvalStatus];
                $this->decisionMessageBug = [];
            }
        }

        return $response;
    }

    public function exportAutoDecisionRulesData($iteration){
        try {
            $decisionData = $this->getAutoDecisionRulesData($id=false, $iteration);

            $header[] = ['Application Id', 'Messages', 'Status'];
            $response = [];
            foreach ($decisionData as $id => $data) {
                foreach ($data['messages'] as $key => $apMessages) {
                    $response[] = [
                        'application id' => $id,
                        'messages' => $key.': '.$apMessages[0],
                        'status' => $data['Rejection'] == true ? 'Rejected' : ($data['Exception'] == true ? 'Exception' : ($data['Approval'] == false ? 'Approved' : '-')),
                    ];
                }
            }
            $response = array_merge($header, $response);
            $request = new Request(['data' => $response, 'sheet' => 'Sheet1']);
            $file = 'Auto Decision Rules Data_' . Carbon::now()->toDateString() . '.xls';
            Excel::store(new Exporter($request), $file);

            $mail_ids = ['shraddha@creditfair.in', 'shrenik@creditfair.in', 'pratik@creditfair.in', 'sunil@creditfair.in', 'sarah@creditfair.in'];
            Mail::send('emails.reminders.basic_reminder',
                ['body' => 'Auto-decision Rules Data ']
                , function ($message) use ($file, $mail_ids) {
                    $message->to($mail_ids)->subject('Auto-decision Rules Data');
                    //                $message->cc([]);
                    $message->attachData(file_get_contents(storage_path() . '/app/' . $file), $file);
                });

            (new \App\Slack(new Request(['title' => 'Exported Auto Decision Data', 'fields' => ['application_count' => count($decisionData)]])))->send();
            return true;
        }catch (\Exception $e){
            (new \App\Slack(new Request(['title' => 'Error while Exporting Auto Decision Data', 'fields' => ['error' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()]])))->send();

        }
    }

    public function runApprovalRules($application, $securedLoansList, $negativeAreaStatus, Request $request){

        $age = Carbon::parse($application->dob)->age;

        if ($age <= 21 || $age >= 60){

            $this->decisionMessageBug['Approval'][] = 'Age is '. $age;
            return true;
        }

        if(!in_array($application->employee_status, ['SALARIED'])){
            $this->decisionMessageBug['Approval'][] = 'Employment is '. $application->employee_status;
            return true;
        }

        if($application->monthly_income <= 25000){
            $this->decisionMessageBug['Approval'][] = 'Income is '. $application->monthly_income;
            return true;
        }

        $score = count($application->creditReport) > 0 && $application->creditReport[0]->applicant_type == 1 ? $application->creditReport[0]->Score : (count($application->creditReport) > 0 && $application->creditReport[1]->applicant_type == 1 ? $application->creditReport[1]->Score : 0);


        if($score <= 750){
            $this->decisionMessageBug['Approval'][] = 'Score is '. $score;
            return true;
        }

        if(!$application->creditReport){
            $this->decisionMessageBug['Approval'][] = 'Credit Report is missing';
            return true;
        }

        $dpdAmount = count($application->creditReport) > 0 && $application->creditReport[0]->applicant_type == 1 ? $application->creditReport[0]->TotalPastDue : (count($application->creditReport) > 0 && $application->creditReport[1]->applicant_type == 1 ? $application->creditReport[1]->TotalPastDue : 0);

        $enquiryPast30Days = $application->equifax_report ? $application->equifax_report->EnquiryPast30Days : 0;

        if($enquiryPast30Days > 0){
            $this->decisionMessageBug['Approval'][] = 'Enquiry Past 30 Days is '. $enquiryPast30Days;
            return true;
        }

        if($negativeAreaStatus){
            $this->decisionMessageBug['Approval'][] = 'Current address is in negative area';
            return true;
        }

        if($dpdAmount){
            $this->decisionMessageBug['Approval'][] = 'DPD is greater than '. $dpdAmount;
            return true;
        }


        $gradeController = new GradeController($request);


        $outstanding = 0;
        $outstandingCC = 0;
        $loanDisbursement = false;
        $approvedAmount = 0;
        foreach ($application->foir as $foir) {

            if($foir->AccountType != 'Credit Fair EMI') {
                if ($foir->applicant_type == 1) {
                    $gradeController->setFOIRAttributes($foir);
                }

                if (in_array($foir->AccountType, $securedLoansList)) {
                    $outstanding += $foir->Balance;
                }

                if (in_array($foir->AccountType, ['Credit Card'])) {
                    $outstandingCC += $foir->Balance;
                }

                if (strtotime($foir->DateOpened) >= Carbon::now()->subDay(90)->timestamp) {
                    $loanDisbursement = true;
                }

                /*if ($foir->AccountType == 'Personal Loan' && $foir->ApprovedAmount <= 10000) {
                    $this->decisionMessageBug['Approval'][] = 'If any PL taken for LV <= 10,000';
                    return true;
                }*/


                if ($foir->DateClosed && strtotime($foir->DateOpened) <= Carbon::now()->subYear(2)->timestamp) {
                    $approvedAmount += $foir->ApprovedAmount;
                }
            }
        }

        $gradeController->getFOIRCalculation($application);

        $foir = round($gradeController->foirNAIncludingCFEMI);
        $cfFoir = round($gradeController->foirIncludingCFEMI);

        if($foir > 75){
            $this->decisionMessageBug['Approval'][] = 'FOIR is '.$foir;
            return true;
        }

        if($cfFoir > 35){
            $this->decisionMessageBug['Approval'][] = 'CF FOIR is '.$cfFoir;
            return true;
        }

        if(($approvedAmount * 50 /100) < $application->approved_amount){
            $this->decisionMessageBug['Approval'][] = 'Closed LV of 50% + of LV in last 2 year';
            return true;
        }

        if($loanDisbursement){
            $this->decisionMessageBug['Approval'][] = 'Loan disbursed in last 90 days';
            return true;
        }

        $Indebtedness = $outstanding / $application->monthly_income;
        $IndebtednessCC = $outstandingCC / $application->monthly_income;


        if($IndebtednessCC >= 12){
            $this->decisionMessageBug['Approval'][] = 'Less than 12x';
            return true;
        }

        if($Indebtedness >= 12){
            $this->decisionMessageBug['Approval'][] = 'Indebtedness is less than 12x';
            return true;
        }

        if(!$application->finBitDataBorrower){
            $this->decisionMessageBug['Approval'][] = 'No Finbit';
            return true;
        }

        if($application->finBitDataBorrower && $application->emi && $application->finBitDataBorrower->average_balance < $application->emi->emi){
            $this->decisionMessageBug['Approval'][] = 'Less than 1x of EMI (ABB)';
            return true;
        }

        return false;
    }

    public function runExceptionRules($application, $securedLoansList, $negativeAreaStatus, Request $request){
        $age = Carbon::parse($application->dob)->age;

        if ($age >= 18 && $age <= 21){

            $this->decisionMessageBug['Exception'][] = 'Age is '. $age;
            return true;
        }else if ($age >= 60 && $age <= 65){

            $this->decisionMessageBug['Exception'][] = 'Age is '. $age;
            return true;
        }

        if($negativeAreaStatus){
            $this->decisionMessageBug['Exception'][] = 'Current address is in negative area';
            return true;
        }

        if(in_array($application->employee_status, ['Self Employed - Professional', 'Self Employed - Business'])){
            $this->decisionMessageBug['Exception'][] = 'Employment is '. $application->employee_status;
            return true;
        }

        if($application->monthly_income >= 15000 && $application->monthly_income <= 25000){
            $this->decisionMessageBug['Exception'][] = 'Income is '. $application->monthly_income;
            return true;
        }

        $score = count($application->creditReport) > 0 && $application->creditReport[0]->applicant_type == 1 ? $application->creditReport[0]->Score : (count($application->creditReport) > 0 && $application->creditReport[1]->applicant_type == 1 ? $application->creditReport[1]->Score : 0);


        if($score >= 625 && $score <= 749){
            $this->decisionMessageBug['Exception'][] = 'Score is '. $score;
            return true;
        }

        if(!$application->creditReport){
            $this->decisionMessageBug['Exception'][] = 'Credit Report is missing';
            return true;
        }

        $dpdAmount = count($application->creditReport) > 0 && $application->creditReport[0]->applicant_type == 1 ? $application->creditReport[0]->TotalPastDue : (count($application->creditReport) > 0 && $application->creditReport[1]->applicant_type == 1 ? $application->creditReport[1]->TotalPastDue : 0);

        $enquiryPast30Days = $application->equifax_report ? $application->equifax_report->EnquiryPast30Days : 0;

        if($enquiryPast30Days > 0){
            $this->decisionMessageBug['Exception'][] = 'Enquiry Past 30 Days is '. $enquiryPast30Days;
            return true;
        }


        if($dpdAmount > 5000){
            $this->decisionMessageBug['Exception'][] = 'DPD is greater than '. $dpdAmount;
            return true;
        }


        $gradeController = new GradeController($request);

        $outstanding = 0;
        $outstandingCC = 0;
        $loanDisbursement = false;
        foreach ($application->foir as $foir) {

            if($foir->AccountType != 'Credit Fair EMI' && $foir->isOpened) {
                if ($foir->applicant_type == 1) {
                    $gradeController->setFOIRAttributes($foir);
                }

                if (in_array($foir->AccountType, $securedLoansList)) {
                    $outstanding += $foir->Balance;
                }

                if (in_array($foir->AccountType, ['Credit Card'])) {
                    $outstandingCC += $foir->Balance;
                }

                if (strtotime($foir->DateOpened) >= Carbon::now()->subDay(90)->timestamp) {
                    $loanDisbursement = true;
                }

                if ($foir->AccountType == 'Personal Loan' && $foir->ApprovedAmount <= 10000) {
                    $this->decisionMessageBug['Exception'][] = 'If any PL taken for LV <= 10,000';
                    return true;
                }
            }
        }

        $gradeController->getFOIRCalculation($application);

        $foir = round($gradeController->foirNAIncludingCFEMI);
        $cfFoir = round($gradeController->foirIncludingCFEMI);

        if($foir > 75){
            $this->decisionMessageBug['Exception'][] = 'FOIR is '.$foir;
            return true;
        }

        if($cfFoir > 35){
            $this->decisionMessageBug['Exception'][] = 'CF FOIR is '.$cfFoir;
            return true;
        }

        if($loanDisbursement){
            $this->decisionMessageBug['Exception'][] = 'Loan disbursed in last 90 days';
            return true;
        }

        $Indebtedness = $outstanding / $application->monthly_income;
        $IndebtednessCC = $outstandingCC / $application->monthly_income;


        if($IndebtednessCC >= 2 && $IndebtednessCC <= 5){
            $this->decisionMessageBug['Exception'][] = '2x - 5x of monthly income';
            return true;
        }

        if($Indebtedness >= 12 && $Indebtedness <= 18){
            $this->decisionMessageBug['Exception'][] = 'Indebtedness is 12x - 18x';
            return true;
        }

        if(!$application->finBitDataBorrower){
            $this->decisionMessageBug['Exception'][] = 'No Finbit';
            return true;
        }

        if($application->finBitDataBorrower && $application->emi && $application->finBitDataBorrower->average_balance < $application->emi->emi){
            $this->decisionMessageBug['Exception'][] = 'Less than 1x of EMI (ABB)';
            return true;
        }

        return false;
    }

    public function runRejectionRules($application, $securedLoansList){
        $age = Carbon::parse($application->dob)->age;

        if($age < 18 || $age > 65){
            $this->decisionMessageBug['Rejection'][] = 'Age is '. $age;
            return true;
        }

        if($application->monthly_income < 15000){
            $this->decisionMessageBug['Rejection'][] = 'Income is '. $application->monthly_income;
            return true;
        }

        $score = count($application->creditReport) > 0 && $application->creditReport[0]->applicant_type == 1 ? $application->creditReport[0]->Score : (count($application->creditReport) > 1 && $application->creditReport[1]->applicant_type == 1 ? $application->creditReport[1]->Score : 0);

        if($score < 625){
            $this->decisionMessageBug['Rejection'][] = 'Score is '. $score;
            return true;
        }

        $NoOfActiveAccounts = count($application->creditReport) > 0 && $application->creditReport[0]->applicant_type == 1 ? $application->creditReport[0]->NoOfActiveAccounts : (count($application->creditReport) > 1 && $application->creditReport[1]->applicant_type == 1 ? $application->creditReport[1]->NoOfActiveAccounts : 0);

        $hasWriteOffSettled = 0;
        $outstanding = 0;
        $hasDPD = false;
        foreach ($application->foir as $foir) {
            if($foir->AccountType != 'Credit Fair EMI' && $foir->isOpened) {
                $foirData = json_decode($foir->dpd, 1);


                $dpdAmount = $foir->PastDueAmount;

                if ($dpdAmount > 5000 && $foir->AccountType == 'Personal Loan') {
                    $hasDPD = $dpdAmount;
                    break;
                }

                if ($foirData) {
                    $_caseType = array_keys($foirData);
                    if ($_caseType) {
                        foreach ($_caseType as $type) {
                            if (in_array($type, ['PWOS', 'SET'])) {
                                $hasWriteOffSettled++;
                            }
                        }
                    }
                }


                if (in_array($foir->AccountType, $securedLoansList)) {
                    $outstanding += $foir->Balance;
                }
            }
        }

        if($hasDPD){
            $this->decisionMessageBug['Rejection'][] = 'DPD is '. $hasDPD;
            return true;
        }

        $Indebtedness = $application->monthly_income > 0 ? $outstanding / $application->monthly_income : 0;

        $more_than_50Percentage_of_tradelines = $NoOfActiveAccounts > 0 && (($hasWriteOffSettled / $NoOfActiveAccounts) * 100) > 50;

        if($more_than_50Percentage_of_tradelines){
            $this->decisionMessageBug['Rejection'][] = 'More than 50% of trade-lines (Settled / written off)';
            return true;
        }

        if($Indebtedness >= 18){
            $this->decisionMessageBug['Rejection'][] = 'Indebtedness is greater than equal to 18';
            return true;
        }

        return false;
    }

    public function generateSubventionInvoice($invoice){

        $application = ConsumerApplication::with('application_element','proFormaInvoice','lender')->where('id', $invoice->application_id)->first(['id', 'name', 'merchant_id', 'lender_id']);

        $request = new Request();
        $request->request->add([
            'type' => 'Merchant Disbursed',
            'bot' => true,
            'test_bot' => 1
        ]);
        $document = (new ConsumerDocument($request));

        if(1) {

            $invoice = Invoices::where('id',$invoice->id)->first();

            $center_name = isset($application->application_element->merchant_center->name) ? $application->application_element->merchant_center->name : '';
            $center_address = isset($application->application_element->merchant_center->location) ? $application->application_element->merchant_center->location : '';
            $center_gst_number = isset($application->application_element->merchant_center->gst_number) ? $application->application_element->merchant_center->gst_number : '';

            $merchant_gst_number = isset($application->proFormaInvoice->gst_number) ? $application->proFormaInvoice->gst_number : '';
            $official_merchant_name = (isset($application->merchant->merchant_name) ? $application->merchant->merchant_name : '');
            $merchant_address = isset($application->merchant->address) ? ucwords(strtolower($application->merchant->address)) : '';

            $getGSTDetailsSubvention = [];

            if($invoice->igst) {
                $getGSTDetailsSubvention[] = ['tax_type' => 18, 'taxes' => 'IGST', 'gst_amount' => $invoice->igst > 0 ? $invoice->igst : ($invoice->amount * 0.18) , 'net_amount' => $invoice->net_amount];
            }
            if($invoice->cgst) {
                $getGSTDetailsSubvention[] = ['tax_type' => 9, 'taxes' => 'CGST', 'gst_amount' => $invoice->cgst > 0 ? $invoice->cgst : ($invoice->amount * 0.09), 'net_amount' => $invoice->net_amount];
            }
            if($invoice->sgst) {
                $getGSTDetailsSubvention[] = ['tax_type' => 9, 'taxes' => 'SGST', 'gst_amount' => $invoice->sgst > 0 ? $invoice->sgst : ($invoice->amount * 0.09), 'net_amount' => $invoice->net_amount];
            }

            // if($application->lender->name == "Aditya Birla Finance Limited") {
            //     $application->lender = Lenders::where('name', 'K. M. Global Credit Private Limited')->first();
            // }


            $documentDetails = [
                'invoice_number' => $invoice->invoice_id,
                'total_subvention' => $invoice->amount,
                'invoice_date' => date('Y-m-d',strtotime($invoice->created_at)),
                'net_amount' => $invoice->net_amount,
                'loan_application_no' => $application->proFormaInvoice->loan_application_no,
                'customer_name' => $application->name,
                'lender' => $application->lender,
                'user' => [
                    'center_gst_number' => $center_gst_number,
                    'disbursed_date' => $document->getDisbursedDate($application->id),
                    'center_name' => $center_name,
                    'invoice' => $invoice,
                    'center_address' => $center_address,
                    'customer_name' => $application->name,
                    'proFormaInvoice' => $application->proFormaInvoice,
                    'official_merchant_name' => $official_merchant_name,
                    'merchant_address' => $merchant_address,
                    'merchant_gst_number' => $merchant_gst_number,
                    'getGSTDetailsSubvention' => $getGSTDetailsSubvention,
                ]
            ];

            $data = [
                'txt' => view('admin.documents.subvention_fee_invoice', $documentDetails),
                'test_bot' => 1
            ];

            $request->request->add($data);
            (new ConsumerApplicationController())->uploadToS3($document, $request, $application->id);
        }
    }

    public function generateSubvention(){

        $application = ConsumerApplication::with('application_element','proFormaInvoice','lender')->whereIn('id', [44853])->first(['id', 'name', 'merchant_id', 'lender_id']);

        $request = new Request();
        $request->request->add([
            'type' => 'Merchant Disbursed',
            'bot' => true,
        ]);
        $document = (new ConsumerDocument($request));

        if(1) {

            $invoice = Invoices::where('application_id',$application->id)->where('type','subvention_invoice')->first();

            $center_name = isset($application->application_element->merchant_center->name) ? $application->application_element->merchant_center->name : '';
            $center_address = isset($application->application_element->merchant_center->location) ? $application->application_element->merchant_center->location : '';
            $center_gst_number = isset($application->application_element->merchant_center->gst_number) ? $application->application_element->merchant_center->gst_number : '';

            $merchant_gst_number = isset($application->proFormaInvoice->gst_number) ? $application->proFormaInvoice->gst_number : '';
            $official_merchant_name = (isset($application->merchant->merchant_name) ? $application->merchant->merchant_name : '');
            $merchant_address = isset($application->merchant->address) ? ucwords(strtolower($application->merchant->address)) : '';

            $documentDetails = [
                'invoice_number' => $invoice->invoice_id,
                'total_subvention' => $invoice->amount,
                'invoice_date' => date('Y-m-d',strtotime($invoice->created_at)),
                'net_amount' => $invoice->net_amount,
                'loan_application_no' => $application->proFormaInvoice->loan_application_no,
                'customer_name' => $application->name,
                'lender' => $application->lender,
                'user' => [
                    'center_gst_number' => $center_gst_number,
                    'disbursed_date' => $document->getDisbursedDate($application->id),
                    'center_name' => $center_name,
                    'invoice' => $invoice,
                    'center_address' => $center_address,
                    'customer_name' => $application->name,
                    'proFormaInvoice' => $application->proFormaInvoice,
                    'official_merchant_name' => $official_merchant_name,
                    'merchant_address' => $merchant_address,
                    'merchant_gst_number' => $merchant_gst_number,
                    'getGSTDetailsSubvention' => [
                        ['tax_type' => 18, 'taxes' => 'IGST', 'gst_amount' => $invoice->igst, 'net_amount' => $invoice->amount],
                        ['tax_type' => 9, 'taxes' => 'CGST', 'gst_amount' => $invoice->cgst, 'net_amount' => $invoice->amount],
                        ['tax_type' => 9, 'taxes' => 'SGST', 'gst_amount' => $invoice->sgst, 'net_amount' => $invoice->amount],
                    ],
                ]
            ];

            $data = [
                'txt' => view('admin.documents.subvention_fee_invoice', $documentDetails)
            ];

            $request->request->add($data);
            (new ConsumerApplicationController())->uploadToS3($document, $request, $application->id);
        }
    }

    public function generateInvoice(){
        try {
            $request = new Request();
            $request->request->add([
                'type' => 'Welcome Letter',
                'bot' => true
            ]);
            $document = (new ConsumerDocument($request));
            $invoices = Invoices::whereIn('application_id',[43218,44022,44303,44356,41102,43751,38269,44298,39968,43699,44179])->where('type','processing_invoice')->get();
            foreach ($invoices as $invoice) {
                $gstDetails = $document->getDocument($invoice->application_id); //759
                $pdf = App::make('snappy.pdf.wrapper');
                $gstDetails['invoice_id'] = $invoice->invoice_id;
                $path = $pdf->loadView('admin.documents.processing_fee_invoice', $gstDetails)->setOption('encoding', 'UTF-8')->setPaper('a4')->setOrientation('portrait');
                $document->uploadToS3('Processing Fee Invoice', $invoice->application_id, $path->output());
            }
            // $document->uploadToS3('Processing Fee Invoice', 735, $path->output());
        }catch (\Exception $e){
            return 'Exception occurred while generating invoice';
        }
    }

    public function generateProcessingInvoice($invoice){
        try {
            $request = new Request();
            $request->request->add([
                'type' => 'Welcome Letter',
                'test_bot' => 1,
                'bot' => true
            ]);
            $document = (new ConsumerDocument($request));
            $gstDetails = $document->getDocument($invoice->application_id); //759
            $pdf = App::make('snappy.pdf.wrapper');
            $gstDetails['invoice_id'] = $invoice->invoice_id;
            $path = $pdf->loadView('admin.documents.processing_fee_invoice', $gstDetails)->setOption('encoding', 'UTF-8')->setPaper('a4')->setOrientation('portrait');
            $document->uploadToS3('Processing Fee Invoice', $invoice->application_id, $path->output());
            // $document->uploadToS3('Processing Fee Invoice', 735, $path->output());
        }catch (\Exception $e){
            return 'Exception occurred while generating processed invoice';
        }
    }

    public function resetInvoiceIds(){
        $isInvoiceExist = $invoiceExist = Invoices::where('lender_id', 5);

        if($isInvoiceExist->count() > 1){
            $invoices = $invoiceExist->get();
            $isInvoiceExist->update(['deleted_at' => Carbon::now()->toDateTimeString()]);
            foreach($invoices as $invoice){
                (new ConsumerApplicationController())->generateInvoice($invoice->application_id);
                (new ConsumerApplicationController())->generateInvoiceSubvention($invoice->application_id);
            }
        }

        return 'true';
    }

    public function cancelRazorPayLink(){
        $data = DB::select("select * from online_payments where emi_date = '2019-03-05' and status = 'issued'");
        $consumerController = new ConsumerApplicationController();
        foreach ($data as $item){
            $app = ConsumerApplication::find($item->application_id);
            $consumerController->cancelraazorpaylink(['payment_id'=>$item->payment_id,'lender_id'=>$app->lender_id]);
        }
    }

    public function sendProforma(){

        //return phpinfo();
        /*(new ConsumerApplicationController())->sendProForma(990);
        return ;*/

        try {
            $request = new Request();
            $request->request->add([
                'type' => 'Welcome Letter',
                'bot' => true
            ]);
            $document = (new ConsumerDocument($request));
            $invoices = Invoices::where('id',115)->get();
            $id = 87;
            foreach ($invoices as $invoice) {
                $gstDetails = $document->getDocument($invoice->application_id); //759
                $pdf = App::make('snappy.pdf.wrapper');
                $concatstring = "";
                if (strlen($id) < 7) {
                    $diff = 7 - strlen($id);
                    for ($i = 0; $i < $diff; $i++) {
                        $concatstring = $concatstring . "0";
                    }
                }

                $in =  'CF-2'.$concatstring.$id.'-18-19';
                $gstDetails['invoice_id'] = $in;
                $path = $pdf->loadView('admin.documents.processing_fee_invoice', $gstDetails)->setOption('encoding', 'UTF-8')->setPaper('a4')->setOrientation('portrait');
                $document->uploadToS3('Processing Fee Invoice', $invoice->application_id, $path->output());
                Invoices::where('id',$invoice->id)->where('application_id',$invoice->application_id)->update(['invoice_id'=>$in]);
                $id++;
            }
           // $document->uploadToS3('Processing Fee Invoice', 735, $path->output());
        }catch (\Exception $e){
            return 'Exception occurred while sending proforma invoice';
        }
    }


    public function getNachStatusAndCourierStatusFile(){
        $applications = ConsumerApplication::whereHas('logs', function($query){
            $query->where('status','disbursed');
        })->whereIn('state',['disbursed','nach register'])->whereNull('is_deleted')->groupBy('id')->get(['id','name','email']);

        $courier = new CouriersController(new Request());
        $response[] = ['ID','Name','Email','Nach Status','Courier Status'];
        foreach($applications as $application){
            $courierData =  $courier->getCourier($application->id, 2);
            $courierStatus = '';
            if(isset($courierData[1]) && $courierData[1]){
                $courierStatus = 'Courier Received';
            }elseif(isset($courierData[0]) && $courierData[0]){
                $courierStatus = 'Couriered';
            }elseif(!isset($courierData[0])){
                $courierStatus = 'Courier Not Sent';
            }


            $nach_status = 0;
            $mandates = Mandate::where('consumer_application_id',$application->id)->get(['id','status']);
            if(isset($mandates[0])){
                foreach ($mandates as $mandate){
                    if(!empty($mandate->umrn)){
                        $nach_status = 1;
                        break;
                    }else{
                        $nach_status = ($mandate->status == 1) ? 0 : $mandate->status;
                    }
                }
            }else{
                $nach_status = 0;
            }

            $statusView = [1=>'Active',2=>'Submitted',3=>'Pending',4=>'Rejected',0=>'Inactive'];;

            $response[] = [
                'id' => $application->id,
                'name' => $application->name,
                'email' => $application->email,
                'nach_status' => isset($statusView[$nach_status]) ? $statusView[$nach_status] : 'Mandate Not Created',
                'courier_status' => $courierStatus
            ];
        }

        $request = new Request(['data'=>$response,'sheet'=>'Sheet1']);
        return Excel::download((new Exporter($request)), 'data.xls');
    }


    public function setReminders(){
        $ids = [278,
            416,
            711,
            857,
            922,
            1071,
            1099,
            1158,
            1185,
            324,
            347,
            596,
            676,
            692,
            700,
            726,
            735,
            742,
            760,
            828,
            836,
            886,
            1029,
            1074,
            1085,
            1115,
            1125,
            1128,
            1137,
            1138,
            1142,
            1196,
            61,
            197,
            1024,
            1033,
            1131,
            1135,
            1193,
            1206,
            1248];

return count($ids);
        //return Mandate::whereIn('consumer_application_id',$ids)->get();
        foreach ($ids as $id) {
            $t = JobProvider::where('application_id', $id)->orderBy('available_at','asc')->first();
            $view = json_decode($t->payload,1);

            $payload = [
                "id"=> $view['id'],
                "offer_id"=> $view['offer_id'],
                "emi_id"=> $view['emi_id'],
                "emi_date"=> "2019-02-18",
                "amount"=> $view['amount']
            ];
            $payloads[] = [
                'payload' => json_encode($payload),
                'from' => 'emiDueReminder',
                'application_id' => $id,
                'available_at' => '2019-02-16 10:00:00',
                'created_at' => Carbon::now()->toDateTimeString(),
                'is_available' => 1
            ];
        }
        JobProvider::insert($payloads);
        return $payloads;
    }


    public function sendreminders(){


        $ids = [
            [325,1888],
            [478,3750],
        [566,3750],
[662,9083],
[674,2917],
[771,5556],
[885,5000],
[951,4444],
[974,6667],
[1153,8583],
[1168,5556],
[1176,1250],
[1242,6667],
[1280,3917],
[1282,5000],
[1664,4458],
[1673,3388],
[1689,2417],
[1702,3125],
[1710,7000],
[1719,2750],
[1740,6577],
[1759,1750],
[1788,2175],
[1823,1333],
[1909,5000],
[1961,6125],
[1965,3536],
[2094,5638],
[2159,5178],
[2163,1500],
[2197,1438],
[2210,5000],
[2236,9458],
[2239,10240],
[2259,6114],
[2278,5638],
[2285,2927],
[2304,6906],
[2305,2063],
[2339,5350],
[2422,7000],
[2450,6107],
[2522,3039],
[2529,1250],
[101,9100],
[121,9042],
[1852,2125]
        ];

        try {
            $consumerApplication = (new ConsumerApplicationController());
            foreach ($ids as $item) {
                $application = ConsumerApplication::where('id', $item[0])->whereIn('state', ['disbursed', 'nach registered'])->first(['email', 'mobile_number', 'state']);
                if(isset($application->email)) {
                    $data = $consumerApplication->getDetails($item[0]);
                    $razorpaydata['amount'] = $item[1];
                    $razorpaydata['email'] = "";
                    $razorpaydata['lender_id'] = $data['lender_id'];
                    $razorpaydata['id'] = $item[0];
                    $razorpaydata['purpose'] = 'emi';
                    $razorpaydata['emi_date'] = '2019-05-05';
                    $rajorpay_link = $consumerApplication->getrazorpaylink($razorpaydata);
                    $view['body'] = view('emails.reminders.emi_due_reminder_with_payment_link', ['data' => $data, 'consumerEmi' => ['amount'=>$item[1],'emi_date'=>'05 May, 2019'],'rajorpay_link'=>$rajorpay_link])->render();
                    $view['subject'] = 'EMI of Rs ' . $item[1] . ' due on 05 May, 2019.';
                    $view['sms'] = 'Dear ' . $data['name'] . ',<br/>An installment  of Rs '.$item[1].' for your purchase from ' . $data['merchant_name'] . ' is due on 05 May, 2019 for your loan application no. ' . (isset($data['proFormaInvoice']->loan_application_no) ? $data['proFormaInvoice']->loan_application_no : '______________') . 'Since your Auto Debit i.e. NACH mandate has not yet been registered, please pay the EMI using '.$rajorpay_link.' . <br> You can reach us on +91-9967235047 or ops@creditfair.in if you have any questions.<br/>Best Regards,<br/>Team Credit Fair';
                    //$view['body'] = view('emails.reminders.emi_due_reminder', ['data' => $data, 'consumerEmi' => ['amount' => $item[1]], 'emi_date' => '05 Mar, 2019'])->render();
                    //$view['subject'] = 'EMI of Rs ' . money_format('%!i', $item[1]) . ' due on 05 Mar, 2019. (Please Ignore Previous Email)';
                    //$view['sms'] = 'Dear ' . $data['name'] . ',<br/>EMI of Rs ' . money_format('%!i', $item[1]) . ' will be debited on 05 Mar, 2019 for your loan application no. ' . (isset($data['proFormaInvoice']->loan_application_no) ? $data['proFormaInvoice']->loan_application_no : '______________') . '. Please ensure balance in your ' . $data['bank']->bank_name . ' account number ending with ' . str_repeat('X', strlen(substr($data['bank']->account_number, 0, -4))) . substr($data['bank']->account_number, -4) . ' at least one day before.<br/>Please note that it would take 3 working days to update payment in our system post debit from your account. <br/>Best Regards,<br/>Team Credit Fair';

                    $view['sms'] = str_replace('<br/>', "\n", $view['sms']);
                    $view['sms'] = str_replace('<br>', "\n", $view['sms']);
                    if (isset($application->email) && !empty($application->email)) {
                        \Mail::send('emails.blank',
                            ['body' => $view['body']]
                            , function ($message) use ($application, $view) {
                                $message->to($application->email)->subject($view['subject']);
                                //$message->cc(_env('NOTIFY_EMAIL', ''));
                            });
                    }
                    if (isset($application->mobile_number) && !empty($application->mobile_number) && isset($view['sms'])) {
                        $mobile = '91' . $application->mobile_number;
                        send_sms($mobile, ['message'=>$view['sms'],'id'=>$item[0],'id_type'=>'application_id']);
                    }

                    $sent[] = $item[0];
                }
            }
        }catch (\Exception $e){
            return [$e, $sent];
        }
    }

    public function emiReminderTesting(){
        return (new AdvanceReminders())->handle();
    }

    public function getIdeaData(){
        $applicationDocument = new ConsumerDocument(new Request());
        $applications = ConsumerApplication::whereNull('is_deleted')->get();
        $data[] = ['APPLICATION ID','DISBURSED DATE','APPLICATION DATE','MOBILE','LOAN TYPE','STATUS'];
        foreach($applications as $application){
            $data[] = [
                'application_id' => $application->id,
                'disbursed_date' => $applicationDocument->getDisbursedDate($application->id),
                'application_date' => ($application->state == 'rejected') ? $application->created_at : '',
                'mobile_number' => $application->mobile_number,
                'type_of_loan' => 'Personal Loan',
                'status' => $application->state
            ];
        }

        $request = new Request(['data'=>$data,'sheet'=>'Application Data']);
        return Excel::download((new Exporter($request)), 'Application_data'.Carbon::now()->toDateTimeString().'.xls');
    }

//    public function emiReminder()
//    {
//
//        $data = ['1664',
//            '991',
//            '1703',
//            '1168',
//            '1712',
//            '1740',
//            '1732',
//            '1823',
//            '1829',
//            '662',
//            '1310',
//            '1702',
//            '812',
//            '1063',
//            '1153',
//            '1350',
//            '1705',
//            '1776',
//            '1777',
//            '1843',
//            '1986',
//            '1742',
//            '1656',
//            '1788',
//            '1176',
//            '1643',
//            '1696',
//            '1909',
//            '313',
//            '1280',
//            '546',
//            '1743',
//            '1514',
//            '1861',
//            '478',
//            '566',
//            '567',
//            '771',
//            '882',
//            '885',
//            '907',
//            '951',
//            '1255',
//            '1282',
//            '1291',
//            '1371',
//            '1563',
//            '1602',
//            '1704',
//            '1709',
//            '1718',
//            '1751',
//            '1806',
//            '1807',
//            '1853',
//            '1968',
//            '2001',
//            '2283',
//            '1395',
//            '1617',
//            '1416',
//            '1673',
//            '1667',
//            '1683',
//            '1943',
//            '1944',
//            '325',
//            '1723',
//            '1249',
//            '1887',
//            '1965',
//            '974',
//            '1242',
//            '1847',
//            '1408',
//            '674',
//            '1716',
//            '1719',
//            '1721',
//            '1839',
//            '1838',
//            '1648',
//            '1852',
//            '1810',
//            '1910',
//            '1018',
//            '1640',
//            '1660',
//            '1682',
//            '1687',
//            '1688',
//            '1689',
//            '1756',
//            '1766',
//            '1836',
//            '1848',
//            '1961',
//            '1962',
//            '1973',
//            '2052'];
//
//
//        foreach ($data as $item) {
//            $reminder = new ConsumerApplicationController();
//            $data = $reminder->getTemplateReminders(5, $item, $payload);
//            $data = $data->getData();
//            if (isset($data->error)) {
//                $this->sendOps($data->error, $job);
//            } else {
//                $this->sendEmail($data, $job);
//                $id[] = $job->id;
//            }
//        }
//    }

    public function updateData(){
        //$data = [['SH100012','Priyanka Vijay Pathari','421301'],['CF100005','Amit Jadhav','422103'],['CF100005','Jyoti Jadhav','411015'],['IF100008','SNEHAL PRABHAKAR TITURKAR','444606'],['IF100002','Mamta Rajesh Lumar','560032'],['FL100001','Virendra Sharma','560032'],['IF100014','Gazala Asif Hussain',''],['IF100016','Shaila Yadav','713324'],['OF1000011','BIRUDHARAJU SWAPNIKA','500047'],['OF1000011','BIRUDHARAJU UMA DEVI','500047'],['IF100022','Bindu Deepak Gautam','231217'],['IF100021','Diksha Singh','110059'],['IF100026','Rajni Lalit Sharma','249401'],['IF100022','Sangeeta Jangale','425502'],['SH100016','Anuja Prasanna Abhyankar','400601'],['SH100016','Prasanna Abhyankar','400601'],['IF100023','Ragini Sushant Kumar Gupta','201310'],['IF100024','Kiran Tejas Merchant','400064'],['IF100027','Reena Ramkrishna Gharde','440009'],['IF100028','Santosh Kumar Yadav','700027'],['IF100028','Shardha Santosh Kumar Yadav','700027'],['IF100028','Manisha',''],['IF100028','Neha Arora','560064']];

        $data = [['IF0000061','Sheetal Sharma',''],['MG000011','Stay Vista Private Limited',''],['CF100005','Jyoti Jadhav','744405487133'],['IF100009','Punita Devi','716950086994'],['IF100002','Mamta Rajesh Lumar',''],['IF0000094','Archana Tiwari','647993610837'],['IF100011','Syeda Arif Zeba','906220333739'],['IF100012','Ketan Patil',''],['MG000011','Stay Vista Private Limited',''],['MG000011','Stay Vista Private Limited',''],['SH100014','Renuka Naik','994989545019'],['IF100014','Gazala Asif Hussain','543993539963'],['IF100016','Sonam Chauhan','823869858212'],['IF100019','Sneha Manish Taywade','379545729940'],['SH100015','Kanika Mutreja','480423960341'],['IF100017','Meena Vijay Ghogare','234929459031'],['IF100020','Manisha Hemant Pradhan',''],['IF100022','Bindu Deepak Gautam',''],['IF100021','Diksha Singh','521263686229'],['IF100026','Rajni Lalit Sharma',''],['IF100022','Sangeeta Jangale',''],['AV100002','Meherbanu Khan','317281843924'],['IF100023','Ragini Sushant Kumar Gupta',''],['IF100025','Chin Thapa','507870721518'],['IF100025','Lila Thapa',''],['IF100027','Reena Ramkrishna Gharde',''],['SE1000011','OM CHANDRA DIXIT',''],['IF100028','Shardha Santosh Kumar Yadav','370063706562'],['IF100028','Manisha',''],['IF100028','Neha Arora',''],['IF0000357','Sumitra Samir Shah',''],['SH0000374','Ananya Joshi',''],['IF0000375','Ragini Kumari',''],['IF0000391','Babita Kumari',''],['IF0000408','Annu A Rai',''],['IF0000499','Manju Sanjeev Tiwari',''],['SH0000520','Chetan Shah','545550210982'],['SH0000521','Rohan Patil',''],['MF0000546','T K SOUJANYA',''],['IF0000560','Nilima',''],['IF0000593','Sajara Khatoon Reyaz Alam Khalifa',''],['EL0000662','MAHESH KUMAR L',''],['0000678','ASHWINI ASHOK KORADE',''],['IF0000734','Laxmi Pandey',''],['IF0000767','Priya Biwas',''],['CB0000771','Deepak Kumar',''],['IF0000844','Nisha Devi',''],['IF0000946','Arpita Singh',''],['CB0000979','RENJINI P R',''],['IF0000982','KRISHNA KUMARI',''],['IF0001071','SHIRISHA.P',''],['CB0001131','Shikha',''],['IF0001142','Medha Mannu',''],['AM0001149','Bhagya Bhaskaran',''],['IF0001169','Komal Grover',''],['CB0001185','Sherin Ali','']];
        echo "<pre>";
        foreach($data as $details){
            if($details[2] != "") {
                $application = ProFormaInvoice::with('consumner')->where('loan_application_no',$details[0])->first();
                //print_r($application);
                //exit;
                if($application->consumner->name == $details[1]){
                    //echo "Applicant_".$application->consumner->id."_".$application->consumner->co_applicant_dob;
                    //echo "<br>";
                    if($application->consumner->aadhaar_card == "") {
                        //ConsumerApplication::where('id', $application->consumner->id)->update(['aadhaar_card' => $details[2]]);
                        echo "Applicant_".$application->consumner->id."_Current_"."$details[0]";
                        echo "<br>";
                    }

//                    if($application->consumner->permanent_address_pincode == "" && $application->consumner->permanent_address_line_1 != "") {
//                        //ConsumerApplication::where('id', $application->consumner->id)->update(['permanent_address_pincode' => $details[2]]);
//                        echo "Applicant_".$application->consumner->id."_permanent";
//                        echo "<br>";
//                    }
                }elseif($application->consumner->co_applicant_name == $details[1]) {
                    //echo "Co - Applicant"."_".$application->consumner->co_applicant_dob;
                    //echo "<br>";
                    if($application->consumner->co_applicant_aadhaar_card == "") {
                        //ConsumerApplication::where('id', $application->consumner->id)->update(['co_applicant_aadhaar_card' => $details[2]]);
                        echo "Co - Applicant_".$application->consumner->id."_".$details[0];
                        echo "<br>";
                    }
                }
                //exit;
            }
        }
    }

    public function approvalLogicFromOLD(Request $request){
        if($request->has('custom_grade_id')) {
            $custom_grade_id = $request->get('custom_grade_id');
            $applications = ConsumerApplication::with('merchant')->where('created_at','>=','2019-05-20 00:00:00')->where('created_at','<=','2019-05-26 23:59:00')->whereNull('is_deleted')->get();
            $approvalData[] = ['Grade Status', 'Negative Profile', 'guarantor' ,'Duplicate','loan_amount','tenure','monthly_income','score','is_credit_card','ageAtLastEMI','age','credit_limit_five_times','AccountType','foir','cf_foir','aboveThreeYear','threeYear','pastDues','termLoan','caseType','Approval Status','Name', 'Merchant Name', 'Auto Reject'];
            foreach ($applications as $application) {
                if($application->merchant) {
                    try {
                        $grade = new GradeController($request);
                        $__grade = $grade->ApprovalCheck($application->id);
//                        $_grade = $__grade->getOutput();

                        if ($__grade) {
                            $_grade = ['status'=>'Approved'];
                        }else{
                            $_grade = ['status'=>'Not Approved'];
                        }
                        $_grade = array_merge($_grade,['name'=>$application->name, 'merchant_name'=>$application->merchant->merchant_name, 'reject' => $this->autoRejectOLD($_grade)]);

                        $approvalData[] = $_grade;
                    }catch (\Exception $e){
                        var_dump($e);
                    }
                }
            }
            $request = new Request(['data'=>$approvalData,'sheet'=>'Sheet1']);
            return Excel::download((new Exporter($request)), 'NEW Approval Logic testing '.Carbon::now()->toDateTimeString().'_Grade_ID_'.$custom_grade_id.'.xls');
        }

        return 'Grade not found';
    }


    public function approvalLogicV1(){
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        //if($request->has('custom_grade_id')) {
            if (Carbon::now()->isMonday()) {
                $from_date = Carbon::now()->subWeek()->startOfWeek()->toDateString();
                $to_date = Carbon::now()->subWeek()->endOfWeek()->toDateString();
            }else{
                $from_date = Carbon::now()->startOfWeek()->toDateString();
                $to_date = Carbon::now()->endOfWeek()->toDateString();
            }

            if (Input::has('day')){
                $from_date = Carbon::now()->startOfDay()->toDateTimeString();
                $to_date = Carbon::now()->endOfDay()->toDateTimeString();
            }

            $custom_grade_id =1;
            $applications = ConsumerApplication::with('merchant','creditReport')->where('created_at','>=',$from_date)->where('created_at','<=',$to_date)->whereNull('is_deleted')->get();
            //$approvalData[] = ['Grade Status', 'Negative Profile', 'guarantor' ,'Duplicate','loan_amount','tenure','monthly_income','score','is_credit_card','ageAtLastEMI','age','credit_limit_five_times','AccountType','foir','cf_foir','aboveThreeYear','threeYear','
        //
        //Dues','termLoan','caseType','rejected','downpayment','address_status','negative_area','Auto Approval','Address Status','Downpayment','Negative Area','Approval Status','Name', 'Merchant Name', 'Auto Reject','Credit Score'];
            $i = 0;
            foreach ($applications as $application) {
                if($application->merchant && $application->merchant->status == 'active' && $application->merchant->is_guest_active == 1) {
                    try {
                        $grade = new GradeController(new Request());
                        $__grade = $grade->ApprovalCheckV1($application->id);
//                           $_grade = $__grade->getOutput();

//                        if (empty(array_filter($_grade))) {
                        if ($__grade) {
//                            $_grade = array_merge($_grade,['status'=>'Approved']);
                            $_grade = ['status'=>'Approved'];
                        }else{
//                            $_grade = array_merge($_grade,['status'=>'Not Approved']);
                            $_grade = ['status'=>'Not Approved'];
                        }
                        $_grade = array_merge($_grade,['name'=>$application->name, 'merchant_name'=>$application->merchant->merchant_name, 'reject' => $this->autoRejectOLD($_grade),'credit_score'=>(isset($application->creditReport[0]) ? $application->creditReport[0]->Score : 0)]);
                        if (!$i)
                            $approvalData[] =  array_keys($_grade);
                        $approvalData[] = $_grade;
                        $i = 1;
                    }catch (\Exception $e){
                        var_dump($e);
                    }
                }
            }

            if (!isset($approvalData))
                $approvalData = [];

            $autoApprovalRuleData = $this->autoApprovalRuleData($from_date, $to_date);
            $preApprovalData = $this->preApprovalData($from_date, $to_date);

            $request = new Request([
                'sheet' => ['Auto Decision','Auto Document Rule','Pre-Approval'],
                'data'  => [$approvalData, $autoApprovalRuleData, $preApprovalData]
            ]);
            return Excel::download((new ExporterMultipleSheet($request)), 'Weekly Report '.Carbon::now()->toDateTimeString().'_Grade_ID_'.$custom_grade_id.'.xls');
        //}

       // return 'Grade not found';
    }

    public function preApprovalData($from_date, $to_date){
        $data = PreApprovalLog::with('application.activeMerchant')->where('created_at','>=',$from_date)->where('created_at','<=',$to_date)->get();
        $preApprovalData = [];
        $i = 0;
        foreach ($data as $item) {
            if (isset($item->application) && $item->application && isset($item->application->activeMerchant) && $item->application->activeMerchant) {
                if (!$i)
                    $preApprovalData[] = array_keys($item->toArray());
                $preApprovalData[] = array_values($item->toArray());
                $i = 1;
            }
        }
        return $preApprovalData;
    }

    public function autoApprovalRuleData($from_date, $to_date){
        $data = DocumentRuleLog::with('application.activeMerchant')->where('created_at','>=',$from_date)->where('created_at','<=',$to_date)->get();
        $autoApprovalRuleData = [];
        $i = 0;
        foreach ($data as $item) {
            if (isset($item->application) && $item->application &&  isset($item->application->activeMerchant) && $item->application->activeMerchant){
                if (!$i)
                    $autoApprovalRuleData[] = array_keys($item->toArray());
                $autoApprovalRuleData[] = array_values($item->toArray());
                $i = 1;
            }
        }
        return $autoApprovalRuleData;
    }

    public function autoRejectOLD($check_approval){
        if((isset($check_approval['score']) && $check_approval['score'] > 10 && $check_approval['score'] < 580) || (isset($check_approval['pastDues']) && $check_approval['pastDues'] > 5000)){
            return true;
        }
        return false;
    }

    public function approvalLogic(Request $request){
        if($request->has('custom_grade_id')) {
            $custom_grade_id = $request->get('custom_grade_id');
            $applications = ConsumerApplication::with('merchant')->whereNull('is_deleted')->get();
            $approvalData[] = ['Grade Status', 'guarantor','loan_amount','tenure','monthly_income','score','is_credit_card','ageAtLastEMI','age','credit_limit_five_times','AccountType','foir','cf_foir','aboveThreeYear','threeYear','pastDues','termLoan','caseType','rejected','Approval Status','Merchant','Name','Auto Reject','Created At'];
            foreach ($applications as $application) {
                if($application->merchant) {
                    try {
                        $grade = new GradeController($request);
                        $__grade = $grade->testingApprovalCheck($application->id);
//                        $_grade = $__grade->getOutput();
//                        unset($_grade['negativeProfile']);
//                        unset($_grade['checkDuplicates']);

                        if ($__grade) {
                            $_grade = ['status'=>'Approved'];
                        }else{
                            $_grade = ['status'=>'Not Approved'];
                        }
                        $_grade = array_merge($_grade,['merchant_name'=>$application->merchant->merchant_name,'name'=>$application->name,'auto_reject'=>$grade->autoReject($__grade, $application->id),'created_at' => $application->created_at]);

                        $approvalData[] = $_grade;
                    }catch (\Exception $e){
                        var_dump($e);
                    }
                }
            }
            $request = new Request(['data'=>$approvalData,'sheet'=>'Sheet1']);
            return Excel::download((new Exporter($request)), 'NEW Approval Logic testing '.Carbon::now()->toDateTimeString().'_Grade_ID_'.$custom_grade_id.'.xls');
        }

        return 'Grade not found';
    }

    public function setDefaultAttributes(Request $request){
        $defaults = ["max_application_count"=>10,
                    "a_tier_1_first"=>50,
                    "a_tier_1_second"=>100,
                    "a_tier_2_first"=>25,
                    "a_tier_2_second"=>50,
                    "a_tier_3_first"=>0,
                    "a_tier_3_second"=>25,
                    "d_tier_1_first"=>0,
                    "d_tier_1_second"=>3,
                    "d_tier_2_first"=>3,
                    "d_tier_2_second"=>6,
                    "d_tier_3_first"=>6,
                    "d_tier_3_second"=>100,
                    "av_tier_1_first"=>100000,
                    "av_tier_1_second"=>200000,
                    "av_tier_2_first"=>50000,
                    "av_tier_2_second"=>100000,
                    "av_tier_3_first"=>0,
                    "av_tier_3_second"=>50000,
                    "avd_tier_1_first"=>50000,
                    "avd_tier_1_second"=>200000,
                    "avd_tier_2_first"=>25000,
                    "avd_tier_2_second"=>50000,
                    "avd_tier_3_first"=>0,
                    "avd_tier_3_second"=>25000,
                    "n_tier_1_first"=>40,
                    "n_tier_1_second"=>100,
                    "n_tier_2_first"=>20,
                    "n_tier_2_second"=>40,
                    "n_tier_3_first"=>0,
                    "n_tier_3_second"=>20];

        if (!$request->all()){
            $request->merge($defaults);
        }

        return $request;
    }

    public function getMerchantWiseCustomerAppData(Request $request){

        $request = $this->setDefaultAttributes($request);

        $applications = ConsumerApplication::leftJoin('merchant as m','m.id','=','merchant_id')
            ->leftJoin('consumer_application_element as e','e.application_id','=','consumer_application.id')
            ->leftJoin('emi_calculation as ec','ec.application_id','=','consumer_application.id')
            ->leftJoin('merchant_location as ml','ml.id','=','e.center_id')
            ->leftJoin('credit_report as c','c.application_id','=','consumer_application.id')
            ->whereNull('is_deleted')
            /*->whereIn('category_id',[6,7])*/
            ->get(['m.merchant_name','ml.phone as contact_number','m.contact_number as merchant_contact_number','m.address','consumer_application.id','m.id as merchant_id','e.center_id','ml.name as center','c.Score','consumer_application.state','consumer_application.approved_amount','consumer_application.loan_amount', 'ec.emi_date','ec.upfront_from_credit_fair']);


        //$applicationController = new ConsumerApplicationController();

        $data = [];
        foreach ($applications as $application){

            $_center_id = ($application->center_id) ? $application->center_id : 0;
            $data[$application->merchant_id][$_center_id][] = $application;
        }

        $response = [];
        $account = new AccountingController();
        foreach ($data as $merchant_id => $_application) {

            foreach ($_application as $center_id => $application) {
                $score = 0;
                $scoreCount = 0;
                $approved = 0;
                $approvedAmount = 0;
                $loanAmount = 0;
                $disbursedAmount = 0;
                $disbursed = 0;
                $delayApp = 0;
                $delayAppBy15Days = 0;
                $disbursedIDs = [];
                $oneToSixApp = 0;
                $disbursed_loan_amount = 0;
                $total_cash_paid_by_customer = 0;
                $first_emi_came_due = 0;
                $netDisbursedAmount = 0;

                //calculate -1 to 6 application
                foreach ($application as $item) {

                    if(strtotime($item->emi_date) <= Carbon::now()->timestamp){
                        $first_emi_came_due++;
                    }

                    if ($item->Score >= -1 && $item->Score <= 6) {
                        $oneToSixApp++;
                    }
                    if ($item->Score > 6) {
                        $scoreCount++;
                        $score += $item->Score;
                    }

                    $emi_generated = false;
                    if ($item->state == 'approved') {
                        $approved++;
                        $approvedAmount += $item->approved_amount;
                        $emi_generated = true;
                    } else if (in_array($item->state, ['closed', 'nach registered', 'disbursed', 'cancelled'])) {
                        $disbursed++;
                        $emi_generated = true;
                        $disbursedIDs[] = $item->id;
                        $disbursed_loan_amount += $item->approved_amount;
                        $netDisbursedAmount += $item->upfront_from_credit_fair;
                    }
                    $loanAmount += ($item->loan_amount) ? $item->loan_amount : 0;

                    if ($emi_generated) {
                        try {
                            $accountData = $account->viewloanschedule($item->id, 1);
                            $delay = 0;
                            $delayedHappened = false;
                            foreach ($accountData['schedule'] as $schedule) {
                                $delay += $schedule['delay_penalty'];
                                if (isset($schedule['transaction'])) {
                                    foreach ($schedule['transaction'] as $transaction) {
                                        if ($transaction) {
                                            $total_cash_paid_by_customer += $transaction->amount;
                                        }
                                    }
                                }

                                if ($schedule['delay_penalty'] > 0 && $schedule['delay_penalty'] <= 15) {
                                    $delayedHappened = true;
                                }
                            }

                            if ($delayedHappened){
                                $delayAppBy15Days++;
                            }

                            if ($delay > 0) {
                                $delayApp++;
                            }
                        } catch (\Exception $e) {

                        }
                    }

                }

                $disbursedData = ApplicationEMICalculation::whereIn('application_id', $disbursedIDs)->get();
                foreach ($disbursedData as $item) {
                    $disbursedAmount += $item->upfront_from_credit_fair;
                }


                $approval_rate = (count($application)) ? round((($approved+$disbursed)/count($application)) * 100) : 0;
                $delayedTheEMI = ($delayAppBy15Days) ? round(($delayAppBy15Days/$first_emi_came_due) * 100) : 0;
                $average_loan_amount = (count($application)) ? round($loanAmount/count($application)) : 0;
                $average_disbursement_value = ($disbursed) ? round($disbursed_loan_amount / $disbursed) : 0;
                $net_disbursement_to_cash_repaid = ($netDisbursedAmount) ? round(($total_cash_paid_by_customer / $netDisbursedAmount) * 100) : 0;

                /*$approval_rate_tier = ($approval_rate > 50) ? 1 : (($approval_rate > 25 && $approval_rate < 50) ? 2 : (($approval_rate < 25) ? 3 : 3));
                $delayed_the_emi_tier = ($delayedTheEMI < 3) ? 1 : (($delayedTheEMI > 3 && $delayedTheEMI < 6) ? 2 : (($delayedTheEMI > 6) ? 3 : 3));
                $average_loan_amount_tier = ($average_loan_amount > 100000) ? 1 : (($average_loan_amount > 50000 && $average_loan_amount < 100000) ? 2 : (($average_loan_amount < 50000) ? 3 : 3));*/

                $approval_rate_tier = (in_array($approval_rate, range($request->get('a_tier_1_first'), $request->get('a_tier_1_second')))) ? 1 : ((in_array($approval_rate, range($request->get('a_tier_2_first'), $request->get('a_tier_2_second')))) ? 2 : ((in_array($approval_rate, range($request->get('a_tier_3_first'), $request->get('a_tier_3_second')))) ? 3 : 3));
                $delayed_the_emi_tier = (in_array($delayedTheEMI, range($request->get('d_tier_1_first'), $request->get('d_tier_1_second')))) ? 1 : ((in_array($delayedTheEMI, range($request->get('d_tier_2_first'), $request->get('d_tier_2_second')))) ? 2 : ((in_array($delayedTheEMI, range($request->get('d_tier_3_first'), $request->get('d_tier_3_second')))) ? 3 : 3));
                $average_loan_amount_tier = (in_array($average_loan_amount, range($request->get('av_tier_1_first'), $request->get('av_tier_1_second')))) ? 1 : ((in_array($average_loan_amount, range($request->get('av_tier_2_first'), $request->get('av_tier_2_second')))) ? 2 : ((in_array($average_loan_amount, range($request->get('av_tier_3_first'), $request->get('av_tier_3_second')))) ? 3 : 3));

                $average_disbursement_value_tier = (in_array($average_disbursement_value, range($request->get('avd_tier_1_first'), $request->get('avd_tier_1_second')))) ? 1 : ((in_array($average_disbursement_value, range($request->get('avd_tier_2_first'), $request->get('avd_tier_2_second')))) ? 2 : ((in_array($average_disbursement_value, range($request->get('avd_tier_3_first'), $request->get('avd_tier_3_second')))) ? 3 : 3));
                $net_disbursement_to_cash_repaid_tier = (in_array($net_disbursement_to_cash_repaid, range($request->get('n_tier_1_first'), $request->get('n_tier_1_second')))) ? 1 : ((in_array($net_disbursement_to_cash_repaid, range($request->get('n_tier_2_first'), $request->get('n_tier_2_second')))) ? 2 : ((in_array($net_disbursement_to_cash_repaid, range($request->get('n_tier_3_first'), $request->get('n_tier_3_second')))) ? 3 : 3));

                $tierArray = [$approval_rate_tier, $delayed_the_emi_tier, $average_loan_amount_tier, $average_disbursement_value_tier, $net_disbursement_to_cash_repaid_tier];



                /*$negativeAreaData = [];
                $pincode = new \stdClass();
                $pincode->current_address_pincode = $application
                $negativeAreaData['consumer_applications'] = $pincode;
                $negativeArea = $applicationController->getNegativeAreaList($negativeAreaData);*/


                $response[$merchant_id][$center_id] = [
                    'merchant_name' => $application[0]->merchant_name,
                    'merchant_mobile' => ($application[0]->contact_number) ? $application[0]->contact_number : $application[0]->merchant_contact_number,
                    'center_name' => ($application[0]->center) ? $application[0]->center : '',
                    'total_application_count' => count($application),
                    'average_score' => ($score) ? $score / $scoreCount : 0,
                    'new_to_credit' => $oneToSixApp,
                    'first_emi_came_due' => $first_emi_came_due,
                    'address' => $application[0]->address,
                    'approved' => $approved,
                    'disbursed' => $disbursed,
                    'no_of_application_delayed_the_emi' => $delayApp,
                    'no_of_application_delayed_over_15_days' => $delayAppBy15Days,
                    'approvedAmount' => $approvedAmount,
                    'loanAmount' => $loanAmount,
                    'ds_loan' => $disbursed_loan_amount,
                    'net_disbursement_amount' => $disbursedAmount,
                    'total_cash_paid_by_customer' => $total_cash_paid_by_customer,
                    'approval_rate' => round($approval_rate,2).'%',
                    'delayed_the_emi' => round($delayedTheEMI,2).'%',
                    'average_loan_amount' => $average_loan_amount,
                    'average_disbursement_value' => $average_disbursement_value,
                    'net_disbursement_to_cash_repaid' => round($net_disbursement_to_cash_repaid,2).'%',
                    'approval_rate_tier' => 'Tier '.$approval_rate_tier,
                    'delayed_the_emi_tier' => 'Tier '.$delayed_the_emi_tier,
                    'average_loan_amount_tier' => 'Tier '.$average_loan_amount_tier,
                    'average_disbursement_value_tier' => 'Tier '.$average_disbursement_value_tier,
                    'net_disbursement_to_cash_repaid_tier' => 'Tier '.$net_disbursement_to_cash_repaid_tier,
                    'tier' => (count($application) > $request->get('max_application_count')) ? 'Tier '.max($tierArray) : 'Tier 3',

                ];
            }
        }

        $paymentData = array();
        if ($request->has('export')) {
            $paymentData[] = ['Merchant Name', 'Center/Merchant Number', 'Center Name', 'Total Application Count', 'Average Score', 'New to Credit', 'First EMI Came Due', 'Address', 'Current Approved Cases', 'Total Disbursed Cases', 'No of Application Delayed The EMI', 'No of Application Delayed The EMI (In 15 Days)', 'Approved Amount', 'Loan Amount', 'Disbursed loan amount (including advance EMI)', 'Net Disbursement Amount', 'Total Cash Paid', 'Approval Rate (%)', 'Delay EMI (%)', 'Average  Loan Amount (%)','Average Disbursement Value','Net Disbursement To Cash Repaid', 'Approval Rate Tier', 'Delay EMI Tier', 'Average Loan Amount Tier', 'Tier'];
        }

        foreach ($response as $_item){
            foreach ($_item as $item) {
                $paymentData[] = $item;
            }
        }

        $file = time().'_'.Carbon::now()->toDateTimeString().'Merchant_wise_data_final.xlsx';

        $requestData = new Request(['data' => $paymentData, 'sheet' => 'Sheet1']);
        Excel::store((new Exporter($requestData)), $file);

        Mail::send('emails.reminders.basic_reminder',
            ['body'=>'Merchant Wise Data']
            , function ($message) use ($file) {
                $message->to(['piyush@creditfiar.in','imran@creditfiar.in'])->subject('Merchant Wise Data');
                //$message->cc(['imran@creditfair.in']);
                $message->attachData(file_get_contents(storage_path().'/app/'.$file), 'Merchant Wise Data '.Carbon::now()->toDateTimeString().'.xlsx');
            });

        return true;

        if ($request->has('export')) {
            $requestData = new Request(['data' => $paymentData, 'sheet' => 'Sheet1']);
            return Excel::download((new Exporter($requestData)), 'Merchant_wise_data_final.xls');
        }else{
            $data = ['from_date' => Carbon::now()->toDateString(), 'to_date' => Carbon::now()->toDateString(), 'payments' => $paymentData, 'export_query' => http_build_query($request->all())];
            $data = array_merge($data,$request->all());
            return view('admin.merchant_wise_data',$data);
        }
    }


    public function sendRejectCommunication(){
        $applications = BulkPayments::where('created_at','>=','2020-06-18 19:18:02')->where('execution_status','like','%rejected%')->get();
        foreach ($applications as $application){
            $payload = json_decode($application->payload);
            $payload = $payload->item;
            $mandate = Mandate::where('umrn', $payload[22])->first(['consumer_application_id']);
            if(isset($mandate->consumer_application_id)) {
                (new LoanManagement())->overDueReminder($mandate->consumer_application_id,1,1,1,0,'rejected',0);
            }
        }
        return 4;
    }

    public function getApplicationWiseData(){
        ConsumerApplication::$isCFFoirNotInclude = true;
        $applications = ConsumerApplication::whereHas('logs', function($query){
            $query->where('status','approved');
        })->with('merchant','foir')->where('created_at','>=','2019-01-01 00:00:00')->where('created_at','<=',Carbon::now()->endOfDay()->toDateTimeString())->whereNull('is_deleted')->whereNotIn('state',['aborted','rejected','cancelled'])->get();

        $response = [];
        foreach ($applications as $application){
            $score = CreditReport::where('application_id',$application->id)->first(['Score']);


            $credit_limit = 0;
            $total_existing_emi= 0;
            foreach ($application->foir as $item) {
                if ($item->applicant_type == 1) {
                    if ($item->isOpened == 1) {
                        if ($item->cc_loan === 0) {
                            $credit_limit += $item->Balance;
                        } else if ($item->Balance > 0 || $item->created_by > 0) {
                            $total_existing_emi += $item->InstallmentAmount;
                        }
                    }
                }
            }



            $response[] = [
                'name' => $application->name,
                'mobile_number' => $application->mobile_number,
                'merchant_name' => $application->merchant->merchant_name,
                'score' => isset($score->Score) ? $score->Score : '',
                'foir' => $this->getFOIRCalculation($application->monthly_income,$credit_limit, $total_existing_emi, $application->id)
            ];
        }

        $request = new Request(['data' => $response, 'sheet' => 'Sheet1']);
        return Excel::download((new Exporter($request)), 'ApplicationWiseDataJanToTillDate.xls');
    }

    public function getFOIRCalculation($income ,$credit_limit, $total_existing_emi, $id){
        $creditFairEMI = FOIR::where('application_id',$id)->where('AccountType', 'Credit Fair EMI')->where('InstallmentAmount','>',0)->first(['InstallmentAmount']);
        if($income > 0) {
            $total_credit_card_limit_five = ($credit_limit * 5) / 100;
            $total_monthly_payment = $total_existing_emi + $total_credit_card_limit_five;
            if(isset($creditFairEMI->InstallmentAmount)){
                $total_monthly_payment += $creditFairEMI->InstallmentAmount;
            }
            return round(($total_monthly_payment / $income) * 100);
        }
        return 0;
    }

    public function sendWhatsAppMessage(){

        $lists = (new CSV())->read(storage_path().'/good_customers.csv');
        foreach ($lists as $list){
            $this->sendNotificationOnWhatsApp($list[1], $list[0]);
        }
    }

    public function sendNotificationOnWhatsApp($phone, $name){
        $message = "Dear $name,

Haven't seen you in long!
Come check out Credit fair's easy EMI options over various segments.
Click on the link below to know more.
https://bit.ly/2wFeYCq

Regards,
Credit Fair.";



        $message = str_replace('<br/>',"\n",$message);
        $message = trim(str_replace('<br>',"\n",$message));
        return sendWhatsAppMessage($phone, $message);
    }

    public function updateMerchantPincode(){
        $merchants = Merchant::whereNull('deleted_at')->get();

        $response = [];
        foreach ($merchants as $merchant){
            preg_match_all('!\d+!', $merchant->address, $matches);
            foreach ($matches as $match){
                foreach ($match as $check) {
                    if ($check && strlen($check) == 6) {
                        $response[] = [$merchant->id, $check];
                    }
                }
            }
        }

        foreach ($response as $item){
            Merchant::where('id',$item[0])->update(['pincode' => $item[1]]);
        }

        return $response;
    }

    public function TallyEntryForOLDApplication(){
        $applications = ConsumerApplication::whereHas('logs', function($query){
            $query->where('status','disbursed')->where('created_at','>=','2020-03-13 00:00:00')->where('created_at','<=','2020-04-13 23:59:59');
        })->whereNull('is_deleted')->where('lender_id',2)->whereIn('state',['disbursed','closed','nach registered'])->orderBy('created_at','desc')->get();

        //$applications = ConsumerApplication::whereNull('is_deleted')->whereIn('id',[2531,2532,2533])->where('lender_id',2)->whereIn('state',['disbursed','closed','nach registered'])->orderBy('created_at','desc')->get();

        foreach ($applications as $application){
            if (isset($application->logs) && $application->logs) {
                $disbursed_date = Tally::getDisbursedDate($application->id);
                TallyJobs::saveTally(['id' => $application->id, 'emi_date' => date('Y-m-d', strtotime($disbursed_date)), 'type' => 'LEDGER']);
            }
        }
    }

    public function creditLineTesting(){
        $applications = ConsumerApplication::with('emi')->where('created_at','>=','2020-01-03 00:00:00')->whereNull('is_deleted')->get();

        $response[] = ['ID','Sanction By ML','EMI By ML','Sanction By Foir','EMI By Foir','Flag','Approved','EMI','Error'];
        foreach ($applications as $application){

            $max_loan_amount_to_sanction_basis_ml = 0;
            $eligible_emi_amount_ml = 0;
            $alert_flag = 0;
            $max_loan_amount_to_sanction_basis_foir = 0;
            $eligible_emi_amount_basis_foir = 0;

            try {
                $creditLine = new CreditLine(new Request(['id' => $application->id]));
                $creditLimit = $creditLine->getCreditData();

                $max_loan_amount_to_sanction_basis_ml = $creditLimit['max_loan_amount_to_sanction_basis_ml'];
                $eligible_emi_amount_ml = $creditLimit['eligible_emi_amount_ml'];
                $alert_flag = $creditLimit['alert_flag'];
                $max_loan_amount_to_sanction_basis_foir = $creditLimit['max_loan_amount_to_sanction_basis_foir'];
                $eligible_emi_amount_basis_foir = $creditLimit['eligible_emi_amount_basis_foir'];
            } catch (\Exception $e) {
                $creditLimit = 'Exception occurred - Credit Limit Error Code';
            }


            $response[] = [
                'id' => $application->id,
                'sanction_by_ml' => $max_loan_amount_to_sanction_basis_ml,
                'emi_by_ml' => $eligible_emi_amount_ml,
                'sanction_by_foir' => $max_loan_amount_to_sanction_basis_foir,
                'emi_by_foir' => $eligible_emi_amount_basis_foir,
                'flag' => $alert_flag,
                'approved' => $application->approved_amount,
                'emi' => $application->emi ? $application->emi->emi : 0,
                'error' => $creditLimit
            ];
        }

        $request = new Request(['data' => $response, 'sheet' => 'Sheet1']);
        return Excel::download((new Exporter($request)), 'ApplicationWiseDataJanToTillDate.xls');
    }

    public function createUsers(){
        $applications = ConsumerApplication::whereNull('is_deleted')->whereNull('user_id')->get();

        foreach ($applications as $application) {

            $user = User::where('mobile_number',$application->mobile_number)->first(['id']);

            if(!isset($user->id)) {

                $userSave = new User();

                $code = (new MerchantController())->getReferralCode();

                $userSave->fill([
                    'name' => $application->name,
                    'email' => $application->email,
                    'mobile_number' => $application->mobile_number,
                    'user_type' => 1,
                    'code' => $code
                ]);

                $userSave->save();

                ConsumerApplication::where('id', $application->id)->update(['user_id' => $userSave->id]);
            }else{
                ConsumerApplication::where('id', $application->id)->update(['user_id' => $user->id]);
            }
        }

        return count($applications);
    }

    public function creditLineTestingV1(){
        ini_set('max_execution_time', -1);
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $applications = ConsumerApplication::with('emi')->where('created_at','>=','2020-01-03 00:00:00')->whereNull('is_deleted')->get();

        $response[] = ['ID','Sanction Amount By ML','EMI Amount By ML','Sanction Amount By Foir','EMI Amount By Foir','Flag','Approved Amount','EMI Amount','Status','Error'];
        foreach ($applications as $application){

            $max_loan_amount_to_sanction_basis_ml = 0;
            $eligible_emi_amount_ml = 0;
            $alert_flag = 0;
            $max_loan_amount_to_sanction_basis_foir = 0;
            $eligible_emi_amount_basis_foir = 0;

            $error = '';
            try {
                $creditLine = new CreditLine(new Request(['id' => $application->id]));
                $creditLimit = $creditLine->getCreditData();

                $max_loan_amount_to_sanction_basis_ml = $creditLimit['max_loan_amount_to_sanction_basis_ml'];
                $eligible_emi_amount_ml = $creditLimit['eligible_emi_amount_ml'];
                $alert_flag = $creditLimit['alert_flag'];
                $max_loan_amount_to_sanction_basis_foir = $creditLimit['max_loan_amount_to_sanction_basis_foir'];
                $eligible_emi_amount_basis_foir = $creditLimit['eligible_emi_amount_basis_foir'];
            } catch (\Exception $e) {
                $error = 'Exception occurred - Credit Limit Error Code';
            }


            $response[] = [
                'id' => $application->id,
                'sanction_by_ml' => $max_loan_amount_to_sanction_basis_ml,
                'emi_by_ml' => $eligible_emi_amount_ml,
                'sanction_by_foir' => $max_loan_amount_to_sanction_basis_foir,
                'emi_by_foir' => $eligible_emi_amount_basis_foir,
                'flag' => $alert_flag,
                'approved' => $application->approved_amount,
                'emi' => $application->emi ? $application->emi->emi : 0,
                'state' => $application->state,
                'error' => $error
            ];
        }

        $request = new Request(['data' => $response, 'sheet' => 'Sheet1']);
        //return Excel::download((new Exporter($request)), 'Credit Line Analysis.xls');
        Excel::store((new Exporter($request)), 'Credit Line Analysis_'.time().'_'.Carbon::now()->toDateString().'.xls');
    }

    public function getPaymentDataTally($id, $emiIds = []){
        $payment_data = EmiPayment::with('transaction')->whereIn('id',$emiIds)->where('application_id',$id)->get();
        $emiPaymentIds = [];
        $response = [];

        foreach ($payment_data as $emi_payment){
                if ($emi_payment->transaction) {
                $amount_received = 0;
                $emiPaymentIds[$emi_payment->emi_date] = $emi_payment->id;
                foreach ($emi_payment->transaction as $transaction) {
                    $amount_received = $amount_received + $transaction->amount;
                }


                if (!isset($response[$emi_payment->emi_date]['emi_amount'])) {
                    $response[$emi_payment->emi_date]['emi_amount'] = 0;
                    $response[$emi_payment->emi_date]['bounce_charges'] = 0;
                    $response[$emi_payment->emi_date]['penal_interest'] = 0;
                }


                if ($amount_received > $emi_payment->emi_amount) {
                    $response[$emi_payment->emi_date]['emi_amount'] += $emi_payment->emi_amount;
                    $amount_received = $amount_received - $emi_payment->emi_amount;

                    if ($amount_received > $emi_payment->bounce_charges) {
                        $response[$emi_payment->emi_date]['bounce_charges'] += $emi_payment->bounce_charges;
                        $amount_received = $amount_received - $emi_payment->bounce_charges;

                        if ($amount_received > 0) {
                            $response[$emi_payment->emi_date]['penal_interest'] += $emi_payment->delay_penalty;
                        }
                    } else {
                        $response[$emi_payment->emi_date]['bounce_charges'] += $amount_received;
                    }
                } else {
                    $response[$emi_payment->emi_date]['emi_amount'] += $amount_received;
                }
            }
        }
        return ['response' => $response, 'emiPaymentIds' => $emiPaymentIds];
    }

    public function apologiesEmail(){
        $query = "select * from emi_payments where id in (3955,
3956,
3957,
3958,
3959,
3960,
3961,
3962,
3963,
3964,
3965,
3966,
3967,
3968,
3969,
3970,
3971,
3972,
3973,
3974,
3975,
3976,
3977,
3978,
3979,
3980,
3981,
3982
) and payment_status = 'pending_from_bank'";

        $data =  DB::select($query);

        foreach ($data as $item){

            $application = ConsumerApplication::find($item->application_id);

            $loan_application_no = ProFormaInvoice::where('application_id',$item->application_id)->first(['loan_application_no']);

            $view = ['email' => $application->email, 'phone' => $application->mobile_number, 'amount' => $item->emi_amount];

            $name = $application->name;

            if ($application->co_applicant_name){
                $name .= ' & '.$application->co_applicant_name;
            }

            $body = '<b>Dear '.$name.'</b>, <br/><br/>We\'v not received payment of Rs '.$item->emi_amount.' for your loan ID '.$loan_application_no->loan_application_no.' on 2019-06-06.
<br/><br/>Please disregard the previous message as it was sent in error. We haven\'t received a confirmation on the payment status from the bank. We will confirm once we do.';

            if ($view['email']) {
                \Mail::send('emails.reminders.basic_reminder',
                    ['body' => $body]
                    , function ($message) use ($view) {
                        $message->to($view['email'])->subject('Please disregard: Payment Received - Rs ' . $view['amount']);
                        $message->cc(_env('NOTIFY_EMAIL', ''));
                    });
            }
            if ($view['phone']) {
                send_sms($view['phone'], ['message' => $body, 'id' => $item->application_id, 'id_type' => 'application_id']);
            }
        }
    }

    public function TallyEMIEntryOLDApplication(){
        /*$applications = ConsumerApplication::WhereHas('emi',function ($query){
            $query->where('emi_date','<=',Carbon::now()->toDateTimeString());
        })->whereNull('is_deleted')->whereIn('state',['disbursed','closed','nach registered'])->where('lender_id',2)->orderBy('created_at','desc')->get();*/

        //$applications = ConsumerApplication::whereNull('is_deleted')->whereIn('state',['disbursed','closed','nach registered'])->where('lender_id',2)->orderBy('created_at','desc')->get();

        $applications = DB::select("select tally_jobs_new.application_id as id from tally_jobs_new
left join emi_calculation on emi_calculation.application_id = tally_jobs_new.application_id
where is_available = 2 and available_at >= '2020-05-07 00:00:00'");

        $idsData = [];
        foreach ($applications as $application_key){
            $idsData[] = $application_key->id;
        }

        //$applications = TallyJobs::where('is_available',0)->groupBy('application_id')->get(['application_id as id']);

        $applications = PaymentTransaction::where('payment_reconciliation_date','>=','2020-03-01 00:00:00')->where('payment_reconciliation_date','<=','2020-04-31 00:00:00')->whereIn('application_id', $idsData)->get(['application_id as id','emi_payment_id']);

        $arrIds = [];
        $emiIds = [];
        foreach ($applications as $applicationItem){
            if (!in_array($applicationItem->id, $arrIds)) {
                $arrIds[] = $applicationItem->id;
            }
            if (!in_array($applicationItem->emi_payment_id, $emiIds)) {
                $emiIds[] = $applicationItem->emi_payment_id;
            }
        }
        $consumerApplication = ConsumerApplication::whereIn('id',$arrIds)->whereIn('state',['disbursed','nach registered','closed'])->get(['id']);

        foreach ($consumerApplication as $application){
            $tally = $this->getPaymentDataTally($application->id, $emiIds);
            if ($tally['response']) {
                foreach ($tally['response'] as $key=>$value) {
                    TallyJobs::saveTally(['tally' => [$key=>$value], 'id' => $application->id, 'emiPaymentID' => $tally['emiPaymentIds'][$key], 'emi_date' => $key, 'type' => 'EMI']);
                }
            }
        }
    }

    public function getInvoiceFromS3(){
        $applications =  StatusLogs::whereIn('status',['disbursed'])->where('created_at','>=',Carbon::now()->subMonth(4)->startOfMonth()->toDateTimeString())->where('created_at','<=',Carbon::now()->subMonth(1)->endOfMonth()->toDateTimeString())->get();
        foreach ($applications as $index=>$applicationCheck){
            $application = ConsumerApplication::where('id',$applicationCheck->application_id)->whereIn('state',['disbursed','nach registered','closed'])->whereNull('is_deleted')->first();
            if(isset($application->id)) {
                return (new ConsumerApplicationController())->viewFile($application->id, 'Processing Fee Invoice.pdf');
            }
        }
    }

    public function getAllInvoice(){
        $merchantInvoice = [];
        $customerInvoice = [];
        $invoicesIds = [];
        $invoicesIdsData = [];
        $data = [];
        $applications =  StatusLogs::whereIn('status',['disbursed'])->where('created_at','>=',Carbon::now()->subMonth(4)->startOfMonth()->toDateTimeString())->where('created_at','<=',Carbon::now()->subMonth(1)->endOfMonth()->toDateTimeString())->get();
        foreach ($applications as $index=>$applicationCheck){
            $application = ConsumerApplication::where('id',$applicationCheck->application_id)->whereIn('state',['disbursed','nach registered','closed'])->whereNull('is_deleted')->first();
            if(isset($application->id)) {
                $invoices = Invoices::where('application_id', $application->id)->get(['id', 'application_id', 'invoice_id', 'type', 'created_at', 'net_amount', 'amount']);
                foreach ($invoices as $invoice) {
                    if (isset($invoice->id)) {
                        $applicationData = ConsumerApplication::with('merchant')->where('id', $invoice->application_id)->first(['id', 'merchant_id', 'permanent_address_state']);
                        if ($invoice->type != 'processing_invoice') {
                            $merchantInvoice[] = ['invoice_id' => $invoice->invoice_id, 'gst' => $applicationData->merchant->gst_number, 'created_at' => $invoice->created_at, 'state' => $applicationData->merchant->state, 'invoice_value' => $invoice->net_amount, 'taxable_amount' => $invoice->amount];
                        } else {
                            $customerInvoice[] = ['state' => $applicationData->permanent_address_state, 'taxable_amount' => $invoice->amount, 'invoice_id' => $invoice->invoice_id];
                        }

                        $invoicesIdsData[(int)substr(explode('-', $invoice->invoice_id)[1], 1)] = $invoice->invoice_id;
                        $invoicesIds[] = (int)substr(explode('-', $invoice->invoice_id)[1], 1);


                    } else {
                        $data[] = $application->id;
                    }
                }
            }else{
                $data[] = $applications[$index]->application_id;
            }
        }

        $arr2 = range(min($invoicesIds),max($invoicesIds));

        $missing = array_diff($invoicesIds,$arr2);

        $excelData = [['Details Required for GSTR 1'],['FOR B2B']];

        $excelData = array_merge($excelData,[['INVOICE NO.','GST NO.','INVOICE DATE','STATE','INVOICE VALUE','TAXABLE AMOUNT']]);

        $excelData = array_merge($excelData,$merchantInvoice);

        $excelData = array_merge($excelData,[['FOR B2C']]);

        $excelData = array_merge($excelData,[['STATE','TAXABLE VALUE']]);

        $excelData = array_merge($excelData,$customerInvoice);

        $excelData = array_merge($excelData,[['TOTAL NO. OF INVOICE ISSUED', count($invoicesIds)]]);

        $excelData = array_merge($excelData,[['SERIAL']]);

        $excelData = array_merge($excelData,[['FROM','TO','CANCELLED']]);

        $excelData = array_merge($excelData,[[$invoicesIdsData[min($invoicesIds)],$invoicesIdsData[max($invoicesIds)], count($missing)]]);

        $excelData = array_merge($excelData,[['Not Generated Invoice', count($data)]]);

        $request = new Request(['data' => $excelData, 'sheet' => 'Sheet1']);
        return Excel::download((new Exporter($request)), 'data_file.xls');
    }

    //Markytics
    public function merchantDataFormat($event){
        $data[] = ['Application ID', 'Customer Name', 'Date of Birth', 'Loan Amount', 'Approved Amount', 'Purpose', 'Tenure', 'Interest', 'Address', 'City', 'State', 'Pincode', 'Employment Type', 'Monthly Income', 'Merchant ID', 'Merchant Name', 'Category', 'Average Ticket Size', 'Account Holder Name', 'Account Type', 'Bank Name', 'Account Status','Score', 'Total Accounts', 'Active Accounts', 'Active Credit Card Limit', 'sanctionAmount', 'TotalPastDue', 'Final Score', 'First EMI Date', 'Total Due Amount', 'EMI PAID', 'Total Paid',/* 'Average Monthly Balance Month 1',	'Average Monthly Balance Month 2',*/ 'Average Monthly Balance Month 3', /*'Average Monthly Balance Month 4', 'Average Monthly Balance Month 5',	'Average Monthly Balance Month 6',*/ 'Total EMI Monthly', 'DPD in last 6 months', 'DPD in last 12 months','Sanction Amount','Total Repayment Made By Customer','Total Number of Bounce','Total DPD','Sum of DPD Days','Total No. Of Debit Txn', 'Total Amount of Debit Txn','Total No. Of Credit txn', 'Total Amount of Credit txn', 'No of Cheque and ECS/Nach bounce', 'No of Cheque and ECS/Nach bounce total amount','Co-Applicant Name','Co-Applicant Email','Co-Applicant Mobile Number','Co-Applicant Gender','Co-Applicant DOB','Co-Applicant Pan Card','Co-Applicant Aadhaar Card', 'Co-Applicant Address', 'Co-Applicant Landmark','Co-Applicant City','Co-Applicant State','Co-Applicant Pincode','Co-Applicant Address Status','Co-Applicant Monthly Income','Co-Applicant Relationship','Co-Applicant Company Name','Co-Applicant Employee Status','Subvention Amount','CGST','SGST','IGST','Sanction Amount','Existing EMIs in Bureau Data','Foir all Cases'];

        ConsumerApplication::$isCFFoirNotInclude = true;
        $applications = ConsumerApplication::with('merchant.merchant_category','emi','bank_details','creditReport','foir')->whereNull('is_deleted')->get();
        $request = new Request();

        $finbit = new FinBit(new Request());
        if (!$finbit->token)
            $finbit = new FinBit(new Request());

        try{
            foreach ($applications as $application){

                $event->comment("Processing ".$application->id);

                $bank_validation = ($application->bank_details && $application->bank_details->karza_response) ? json_decode($application->bank_details->karza_response) : 'Account Not Validated';

                $account_status =  (!isset($bank_validation->result->bankResponse)) ? 'InActive' : ($bank_validation->result->bankTxnStatus ? 'Active' : 'Inactive');

                if($bank_validation == 'Account Not Validated'){
                    $account_status = $bank_validation;
                }

                $statements = ConsumerApplicationFiles::where('consumer_application_id', $application->id)->whereNotNull('accountUID')->where('file_type','bank_statement')->orderBy('created_at','desc')->first();

                $DPDs = (new ConsumerApplicationController())->getDPD($application->id);

                $six = 0;
                $twelve = 0;

                if ($DPDs) {
                    foreach ($DPDs as $datum) {
                        if (is_array($datum)) {
                            foreach ($datum as $item) {
                                $item = array_values($item);
                                if (isset($item[0])) {
                                    $six += isset($item[0]['six']) ? $item[0]['six']['dpd'] : 0;
                                    $twelve += isset($item[0]['twelve']) ? $item[0]['twelve']['dpd'] : 0;
                                }
                            }
                        }
                    }
                }
                $request->request->add(['raw' => 1]);

                $bounced = 0;
                $delay_penalty = 0;
                $delay_days = 0;

                if(in_array($application->state, ['disbursed','nach registered','closed'])) {
                    $EMIPayment = new PaymentEmi();
                    $payments = $EMIPayment->getPaymentDueHistory($application->id);

                    $payments = isset($payments[$application->id]) ? $payments[$application->id] : [];

                    if ($payments && isset($payments['payment'])) {
                        foreach ($payments['payment'] as $payment) {
                            if (isset($payment['bounce_charges']) && $payment['bounce_charges']) {
                                $bounced++;
                            }
                            if (isset($payment['delay_penalty']) && $payment['delay_penalty']) {
                                $delay_penalty++;
                            }
                            if (isset($payment['delay_days']) && $payment['delay_days'] > 0) {
                                $delay_days = +$payment['delay_days'];
                            }
                        }
                    }
                }

                $finData = FinBitData::where('application_id', $application->id)->first(['average_balance_three_months']);


                $netDebitTxn = 0;
                $netCreditTxn = 0;
                $ECSNach = 0;
                if (isset($statements->accountUID)) {
                    $netDebitTxn = $this->calculateNetDebitTransaction(6, $statements->accountUID, $finbit->token);
                    $netCreditTxn = $this->calculateNetCreditTransaction(6, $statements->accountUID, $finbit->token);
                    $ECSNach = $this->calculateBounceTransactions(6, $statements->accountUID, $finbit->token);

                    if ($netDebitTxn['response'] || $netCreditTxn['response'] || $ECSNach['response']){
                        $finBitData = FinBitData::where('finbit_uid',$statements->accountUID)->first(['id']);
                        if (isset($finBitData->id)) {
                            $finBitDataUpdate = FinBitData::find($finBitData->id);
                            if ($netDebitTxn['response'])
                                $finBitDataUpdate->net_debit_txn = json_encode($netCreditTxn['response']);
                            if ($netCreditTxn['response'])
                                $finBitDataUpdate->net_credit_txn = json_encode($netCreditTxn['response']);
                            if ($ECSNach['response'])
                                $finBitDataUpdate->ecs_nach_txn = json_encode($ECSNach['response']);

                            $finBitDataUpdate->save();
                        }else{
                            $finBitDataUpdate = new FinBitData();
                            $finBitDataUpdate->finbit_uid = $statements->accountUID;
                            $finBitDataUpdate->application_id = $application->id;
                            if ($netDebitTxn['response'])
                                $finBitDataUpdate->net_debit_txn = json_encode($netCreditTxn['response']);
                            if ($netCreditTxn['response'])
                                $finBitDataUpdate->net_credit_txn = json_encode($netCreditTxn['response']);
                            if ($ECSNach['response'])
                                $finBitDataUpdate->ecs_nach_txn = json_encode($ECSNach['response']);

                            $finBitDataUpdate->save();
                        }
                    }
                }


                $mData = [
                    'id' => $application->id,
                    'name' => $application->name,
                    'date_of_birth' => $application->dob,
                    'loan_amount' => $application->loan_amount,
                    'approved_amount' => $application->amount_approved,
                    'purpose' => $application->merchant && $application->merchant->merchant_category ? $application->merchant->merchant_category->name : '',
                    'tenure' => $application->tenure,
                    'interest' => ($application->emi) ? $application->emi->interest_rate : '',
                    'address' => $application->permanent_address_line_1 ? $application->permanent_address_line_1.' '.$application->permanent_address_landmark.' '.$application->permanent_address_pincode : ($application->current_address_line_1 ? $application->current_address_line_1.' '.$application->current_address_landmark.' '.$application->current_address_pincode : ''),
                    'city' => ($application->permanent_address_city) ? $application->permanent_address_city  : $application->current_address_city,
                    'state' => ($application->permanent_address_state) ? $application->permanent_address_state  : $application->current_address_state,
                    'pincode' => ($application->permanent_address_pincode) ? $application->permanent_address_pincode  : $application->current_address_pincode,
                    'employee_status' => $application->employee_status,
                    'monthly_income' => $application->monthly_income,
                    'merchant_id' => $application->merchant ? $application->merchant->id : '',
                    'merchant_name' => $application->merchant ? $application->merchant->merchant_name : '',
                    'category' => $application->merchant ? $application->merchant->merchant_category->name : '',
                    'avg_ticket_size' => $application->merchant ? $application->merchant->avg_ticket_size : '',
                    'account_holder_name' => $application->bank_details ? $application->bank_details->name : '',
                    'account_type' => $application->bank_details ? $application->bank_details->account_type : '',
                    'bank_name' => $application->bank_details ? $application->bank_details->bank_name : '',
                    'account_status' => $account_status,
                    'score' => $application->creditReport && isset($application->creditReport[0]) ? $application->creditReport[0]->Score : '',
                    'total_account' => $application->foir && isset($application->foir[0]) ? count($application->foir) : '',
                    'NoOfActiveAccounts' => $application->creditReport && isset($application->creditReport[0]) ? $application->creditReport[0]->NoOfActiveAccounts : '',
                    'activeCreditCardLimit' => $application->creditReport && isset($application->creditReport[0]) ? $application->creditReport[0]->activeCreditCardLimit : '',
                    'sanctionAmount' => $application->creditReport && isset($application->creditReport[0]) ? $application->creditReport[0]->sanctionAmount : '',
                    'TotalPastDue' => $application->creditReport && isset($application->creditReport[0]) ? $application->creditReport[0]->TotalPastDue : '',
                    'final_score' => $application->creditReport && isset($application->creditReport[0]) ? $application->creditReport[0]->finalCategory : '',
                    'first_emi_date' => ($application->emi) ? $application->emi->emi_date : '',
                    'total_due_amount' => isset($payments['amount_pending']) ? $payments['amount_pending'] : '',
                    'emi_paid' => isset($payments['emi_paid']) ? $payments['emi_paid'] : '',
                    'total_paid' => isset($payments['amount_paid']) ? $payments['amount_paid'] : '',
                    /*'average_monthly_one' => 0,
                    'average_monthly_two' => 0,*/
                    'average_monthly_three' => isset($finData->average_balance_three_months) ? $finData->average_balance_three_months : 'No Data',
                    /*'average_monthly_four' => 0,
                    'average_monthly_five' => 0,
                    'average_monthly_six' => 0,*/
                    'total_emi_monthly' => ($application->emi) ? $application->emi->emi : '',
                    'dpd_in_last_6_months' => $six,
                    'dpd_in_last_12_months' => $twelve,
                    'sanction_amount' => $application->approved_amount,
                    'total_repayment_made_by_customer' => isset($payments['emi_paid']) ? $payments['emi_paid'] : 0,
                    'total_number_of_bounce' => $bounced,
                    'total_dpd' => $delay_penalty,
                    'sum_of_dpd_days' => $delay_days,
                    'total_debit_transaction' => isset($netDebitTxn) ? $netDebitTxn['total_debit_transaction'] : 0,
                    'total_debit_transaction_amount' => isset($netDebitTxn) ? $netDebitTxn['total_debit_transaction_amount'] : 0,
                    'total_credit_transaction' => isset($netCreditTxn) ? $netCreditTxn['total_credit_transaction'] : 0,
                    'total_credit_transaction_amount' => isset($netCreditTxn) ? $netCreditTxn['total_credit_transaction_amount'] : 0,
                    'total_bounced_transaction' => isset($ECSNach) ? $ECSNach['total_bounced_transaction'] : 0,
                    'total_transaction_amount' => isset($ECSNach) ? $ECSNach['total_transaction_amount'] : 0,
                ];

                $mkData = $this->getMarkyticsData($request, $application->id);
                $data[] = array_merge($mData,$mkData);
            }
        }catch (\Exception $e){

        }


        $file = time().'_'.Carbon::now()->toDateTimeString().'_customer_data.xlsx';

        $requestData = new Request(['data' => $data, 'sheet' => 'Sheet1']);
        Excel::store((new Exporter($requestData)), $file);

        Mail::send('emails.reminders.basic_reminder',
            ['body'=>'Merchant Wise Data']
            , function ($message) use ($file) {
                $message->to(['sunil@creditfair.in','ashish@creditfair.in'])->subject('Customer Wise Data - marketing data');
                //$message->cc(['imran@creditfair.in']);
                $message->attachData(file_get_contents(storage_path().'/app/'.$file), 'Customer Wise Data '.Carbon::now()->toDateTimeString().'.xlsx');
            });

        if (file_exists(storage_path().'/app/'.$file)){
            unlink(storage_path().'/app/'.$file);
        }
        return true;
    }

    public function getAverageBalanceFromFinBit(){

        //return $this->calculateNetCreditTransaction(6);
        /*return $d = json_decode("{\"averageBalanceList\":[{\"netAverageBalance\":89846.77,\"monthAndYear\":\"Jun 2018\",\"dayBalanceMap\":{\"1\":22603.67,\"5\":22603.67,\"10\":22603.67,\"15\":72603.67,\"20\":70253.67,\"25\":60703.67,\"30\":311146.67}},{\"netAverageBalance\":307061.93,\"monthAndYear\":\"Jul 2018\",\"dayBalanceMap\":{\"1\":311146.67,\"5\":311146.67,\"10\":311146.67,\"15\":308936.67,\"20\":302758.67,\"25\":302758.67,\"30\":302758.67}},{\"netAverageBalance\":391056.86,\"monthAndYear\":\"Aug 2018\",\"dayBalanceMap\":{\"1\":302758.67,\"5\":402151.67,\"10\":402151.67,\"15\":393356.67,\"20\":390356.67,\"25\":390356.67,\"30\":379866.67}},{\"netAverageBalance\":359552.26,\"monthAndYear\":\"Sep 2018\",\"dayBalanceMap\":{\"1\":379866.67,\"5\":379866.67,\"10\":329573.67,\"15\":237173.67,\"20\":237155.97,\"25\":220204.05,\"30\":873423.49}},{\"netAverageBalance\":667701.55,\"monthAndYear\":\"Oct 2018\",\"dayBalanceMap\":{\"1\":653544.65,\"5\":646073.05,\"10\":530273.05,\"15\":473126.05,\"20\":828798.05,\"25\":770675.35,\"30\":484273.35}},{\"netAverageBalance\":393337.03,\"monthAndYear\":\"Nov 2018\",\"dayBalanceMap\":{\"1\":479173.35,\"5\":373013.75,\"10\":373013.75,\"15\":365706.75,\"20\":157723.15,\"25\":569634.15,\"30\":-1}}],\"message\":\"Monthly average balance report generated successfully.\",\"status\":\"SUCCESS\"}",1);

        $d = $d['averageBalanceList'];
        foreach($d as $a){
            $netAverageBalance =  $a['netAverageBalance'];
            $monthAndYear =  $a['monthAndYear'];


            $data = [
                'Opening Balance' => '',
                'Total Amount of Debit Transactions' => '',
                'Total Amount of Credit Transactions' => '',
                'Closing Balance' => '',
                'Total Number of Debit Transactions' => '',
                'Total Number of Credit Transactions' => '',
                'Min Balance' => '',
                'Max Balance' => '',
                'Average Balance' => '',
                'Total Amount of Cash Deposit' => '',
                'Total Amount of Cash Withdrawal' => '',
                'Total Number of Cash deposit' => '',
                'Total Number of Cash Withdraw' => '',
                'Total Number of Cheque Deposit' => '',
                'Total Amount of Cheque Deposit' => '',
                'Total Number of Cheque Issues' => '',
                'Total Amount of Cheque Issues' => '',
                'Total Number of Debit Internal Transactions' => '',
                'Total Number of Credit Internal Transactions' => '',
                'Total Amount of Debit Internal Transactions' => '',
                'Total Amount of Credit Internal Transactions' => '',
                'Total Amount of Credit Card Transactions' => '',
                'No.of Penalty Charges' => '',
                'Total Amount of Penalty charges' => '',
                'No. of EMI / loan payments' => '',
                'Total Amount of EMI / loan Payments' => '',
                'No of Salary' => '',
                'Amount of Salary' => '',
                'Total No. of ECS/NACH Issued' => '',
                'Total Amount of ECS/NACH Issued' => '',
                'Total No. of I/W Cheques Bounced: Insufficient Funds' => '',
                'Sum of I/W Bounced Cheque: Insufficient Funds' => '',
                'Total Number of Outward Cheque Bounces' => '',
                'Inward Cheque Bounced %' => '',
                'No. of Bank Charges' => '',
                'Amount of Bank Charges' => ''
            ];

        }*/

        $files = ConsumerApplicationFiles::whereNotNull('accountUID')->where('file_type','bank_statement')->get();

        $finbit = new FinBit(new Request());
        $finbit->connect();

        $applications = [];

        foreach ($files as $file) {
            if (!in_array($file->consumer_application_id, $applications)) {

                $applications[] = $file->consumer_application_id;

                if (strlen($file->accountUID) > 0) {

                    $url_period = "https://www.fin360.in/bank-account/api/v1/monthlyAverageBalance/" . str_replace("\"",'',$file->accountUID) . ".json?access_token=" . $finbit->token;
                    $curl = curl_init();
                    curl_setopt_array($curl, array(
                        CURLOPT_URL => $url_period,
                        CURLOPT_RETURNTRANSFER => true,
                        CURLOPT_ENCODING => "",
                        CURLOPT_MAXREDIRS => 10,
                        CURLOPT_TIMEOUT => 30,
                        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                        CURLOPT_CUSTOMREQUEST => "GET",
                        CURLOPT_POSTFIELDS => "",
                        CURLOPT_HTTPHEADER => array(),
                    ));

                    $response_average_balance = curl_exec($curl);
                    $err_average_balance = curl_error($curl);
                    curl_close($curl);

                    return $response_average_balance;
                }
            }
        }
    }

    public function getBounceTransactions($accountUID, $token){
        if (strlen($accountUID) > 0) {
            $url_period = "https://www.fin360.in/bank-account/api/v1/bounceTransactions/" . str_replace("\"",'',$accountUID) . ".json?access_token=" . $token;
            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => $url_period,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "GET",
                CURLOPT_POSTFIELDS => "",
                CURLOPT_HTTPHEADER => array(),
            ));

            $response = curl_exec($curl);
            $error = curl_error($curl);
            curl_close($curl);

            return json_decode($response);
        }

        return false;
    }

    public function getECSAndNACHInstances($accountUID, $token){
        if (strlen($accountUID) > 0) {
            $url_period = "https://www.fin360.in/bank-account/api/v1/ecsAndNachInstances/" . str_replace("\"",'',$accountUID) . ".json?access_token=" . $token;
            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => $url_period,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "GET",
                CURLOPT_POSTFIELDS => "",
                CURLOPT_HTTPHEADER => array(),
            ));

            $response = curl_exec($curl);
            $error = curl_error($curl);
            curl_close($curl);

            return json_decode($response);
        }

        return false;
    }

    public function calculateBounceTransactions($yearFrom, $accountUID, $token){
        $total_credit_transaction = 0;
        $total_credit_transaction_amount = 0;
        if($data = $this->getBounceTransactions($accountUID, $token)) {
            if (!isset($data->status) || (isset($data->status) && $data->status != 'NO_DATA')) {
                if(isset($data->outwardChequeBounceMonthwise) && $data->outwardChequeBounceMonthwise) {
                    foreach ($data->outwardChequeBounceMonthwise as $outwardChequeBounceMonthwise) {
                        foreach ($outwardChequeBounceMonthwise as $outward) {
                            if (isset($outward->date) && strtotime($outward->date) >= Carbon::now()->subMonth($yearFrom)->startOfMonth()->timestamp) {
                                $total_credit_transaction++;
                                $total_credit_transaction_amount += $outward->amount;
                            }
                        }
                    }
                }
            }
        }
        return ['total_bounced_transaction' => $total_credit_transaction, 'total_transaction_amount' => $total_credit_transaction_amount, 'response' => $data];
    }

    public function calculateECSAndNACHInstances($yearFrom, $accountUID, $token){
        $total_credit_transaction = 0;
        $total_credit_transaction_amount = 0;
        if($data = $this->getECSAndNACHInstances($accountUID, $token)) {
            if (!isset($data->status) || (isset($data->status) && $data->status != 'NO_DATA')) {
                foreach ($data as $item) {
                    if (isset($item->date) && strtotime($item->date) >= Carbon::now()->subMonth($yearFrom)->startOfMonth()->timestamp) {
                        $total_credit_transaction += $item->total;
                        $total_credit_transaction_amount += $item->amount;
                    }
                }
            }
        }
        return ['total_bounced_transaction' => $total_credit_transaction, 'total_transaction_amount' => $total_credit_transaction_amount, 'response' => $data];
    }

    public function calculateNetCreditTransaction($yearFrom, $accountUID, $token){
        $total_bounced_transaction = 0;
        $total_transaction_amount = 0;
        if($data = $this->getNetCreditTransaction($accountUID, $token)) {
            foreach ($data as $item) {
                if (isset($item->date) && strtotime($item->date) >= Carbon::now()->subMonth($yearFrom)->startOfMonth()->timestamp) {
                    $total_bounced_transaction += $item->total;
                    $total_transaction_amount += $item->amount;
                }
            }
        }
        return ['total_credit_transaction' => $total_bounced_transaction, 'total_credit_transaction_amount' => $total_transaction_amount, 'response' => $data];
    }

    public function getNetCreditTransaction($accountUID, $token){
        if (strlen($accountUID) > 0) {
            $url_period = "https://www.fin360.in/bank-account/api/v1/netCreditTransaction/" . str_replace("\"",'',$accountUID) . ".json?access_token=" . $token;
            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => $url_period,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "GET",
                CURLOPT_POSTFIELDS => "",
                CURLOPT_HTTPHEADER => array(),
            ));

            $response = curl_exec($curl);
            $error = curl_error($curl);
            curl_close($curl);

            return json_decode($response);
        }
        return false;
    }

    public function calculateNetDebitTransaction($yearFrom, $accountUID, $token){
        $total_debit_transaction = 0;
        $total_debit_transaction_amount = 0;
        if($data = $this->getNetDebitTransaction($accountUID, $token)) {
            foreach ($data as $item) {
                if (isset($item->date) && strtotime($item->date) >= Carbon::now()->subMonth($yearFrom)->startOfMonth()->timestamp) {
                    $total_debit_transaction += $item->total;
                    $total_debit_transaction_amount += $item->amount;
                }
            }
        }

        return ['total_debit_transaction' => $total_debit_transaction, 'total_debit_transaction_amount' => $total_debit_transaction_amount, 'response' => $data];
    }

    public function getNetDebitTransaction($accountUID, $token){
        if (strlen($accountUID) > 0) {
            $url_period = "https://www.fin360.in/bank-account/api/v1/netDebitTransaction/" . str_replace("\"",'',$accountUID) . ".json?access_token=" . $token;
            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => $url_period,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "GET",
                CURLOPT_POSTFIELDS => "",
                CURLOPT_HTTPHEADER => array(),
            ));

            $response = curl_exec($curl);
            $error = curl_error($curl);
            curl_close($curl);

            return json_decode($response);
        }
        return false;
    }

    public function invoicesFixes($event){
        Excel::import(new InvoiceImport(new Request(['event' => $event])), storage_path().'/final_santosh_ji_invoice.xlsx');
    }

    public function getDataFromExcel(){

        ini_set('max_execution_time', -1);
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        Excel::import(new TestImport(new Request(['from' => __FUNCTION__])), storage_path().'/SBI_Excel_File_1607180145_91.xlsx');
    }

    public function tallySubventionUpload(){
        Excel::import(new TestImport(new Request(['from' => __FUNCTION__])), storage_path().'/Jan2022-subvention-interest.xlsx');
    }

    public function tallySubventionUploadCSV(){
        $import = new TestImport(new Request(['from' => __FUNCTION__]));
        $import->tallySubventionUpload((new CSV())->read(storage_path().'/sub-int entires - May.csv'));
    }

    public function merchantUserCreation(){
        $import = new TestImport(new Request(['from' => __FUNCTION__]));
        return $import->merchantUserCreation((new CSV())->read(storage_path().'/merchant_users.csv'));
    }

    public function tallyBouncePenalUploadCSV(){
        $import = new TestImport(new Request(['from' => __FUNCTION__]));
        $import->bounce_panel_tally_entries((new CSV())->read(storage_path().'/sub-int entires - May.csv'));
    }

    public function tokenGenJWT(){
        $data['merchant_id'] = 0;
        $type = "Executive";
        $data['session_expiry'] = strtotime("+90 days");
        $user_data = json_decode("{\"id\":40139,\"name\":\"Credit Risk Analysis\",\"user_type\":\"25\",\"code\":\"9e6fe\",\"remember_token\":null,\"email\":\"mohitkokli@markytics.in\",\"center_id\":null,\"mobile_number\":null,\"session_string\":\"MHwwfDQwMTM5fDk0MjM4NjQ1NDN8MTY0MTk4ODgzNHxhZG1pbg==\"}");

        $session_string = base64_encode($data['merchant_id']."|0|".$user_data->id."|".$user_data->mobile_number."|".$data['session_expiry']."|".$type);
        $userObject = new \stdClass();
        $userObject->id = $user_data->id;
        $userObject->session_string = $session_string;
        $userObject->user_type = $user_data->user_type;
        $userObject->center_id = 0;
        $userObject->remember_token = $user_data->remember_token;
        $userObject->code = $user_data->code;
        $userObject->email = $user_data->email;
        $userObject->mobile = $user_data->mobile_number;
        $userObject->name = $user_data->name;
        $JWTAccess = new JWTAccess();
        return $data['session_string'] = $JWTAccess->generateAccessToken($userObject);
    }

    public function sendSMSToMerchants(){

        $merchants = Merchant::where('status','active')->where('is_guest_active', 1)->whereNull('deleted_at')->get();

        foreach ($merchants as $merchant) {

            if ($merchant->contact_number) {
                $merchant_content = "Dear $merchant->merchant_name,
Good news! We are now serving our merchants on Sundays too !
Now grow your sales all through the week with Credit Fair's Easy EMI Options. Enjoy your weekends.
<br/>Regards 
Credit Fair.";

             send_sms($merchant->contact_number, $merchant_content);
            }
        }


    }

    public function encryptData(){

        $applications = ConsumerApplication::with('bank_details','mandateMany','creditReport')->get();

        foreach($applications as $application) {

            $mandates = [];
            foreach ($application->mandateMany as $mandate){
                $mandates[] = ['id' => $mandate->id,'umrn' => wall_encrypt($mandate->umrn)];
            }

            $plainText = [
                'account_number' => $application->bank_details ? wall_encrypt($application->bank_details->account_number) : '',
                'ifsc_code' => $application->bank_details ? wall_encrypt($application->bank_details->ifsc_code) : '',
                'mobile_number' => wall_encrypt($application->mobile_number),
                'email' => wall_encrypt($application->email),
                'pan' => wall_encrypt($application->pan_card),
                'aadhar_card' => wall_encrypt($application->aadhaar_card),
                'umrn_no' => $mandates,
                'permanent_address_pincode' => wall_encrypt($application->permanent_address_pincode),
                'current_address_pincode' => wall_encrypt($application->permanent_address_pincode),
                'co_applicant_address_pincode' => wall_encrypt($application->co_applicant_address_pincode),
                'work_address_pincode' => wall_encrypt($application->work_address_pincode),
                'permanent_address_city' => wall_encrypt($application->permanent_address_city),
                'current_address_city' => wall_encrypt($application->current_address_city),
                'co_applicant_address_city' => wall_encrypt($application->co_applicant_address_city),
                'work_address_city' => wall_encrypt($application->work_address_city),
                'permanent_address_state' => wall_encrypt($application->permanent_address_state),
                'current_address_state' => wall_encrypt($application->current_address_state),
                'co_applicant_address_state' => wall_encrypt($application->co_applicant_address_state),
                'work_address_state' => wall_encrypt($application->work_address_state),
                'score' => $application->creditReport && isset($application->creditReport[0]) ? wall_encrypt($application->creditReport[0]->Score) : ''
            ];

            return $plainText;
        }
    }

    public function setPreApprovedAndDoc(){
        Excel::import(new TestImport(new Request(['from' => __FUNCTION__])), storage_path().'/auto_documentation_and_pre_approval.xlsx');
    }

    /*Bureau Data Report*/
    public function getAnalyticsData($event, $type = null){
        try {
            $creditReport = CreditReport::with('application');
            if ($type){
                $creditReport = $creditReport->where('application_id', $type);
            }
            $foirResponse = [];
            $creditReport = $creditReport->get();
            foreach ($creditReport as $report) {
                $file_path = $report->application_id . "/" . $report->application_id . "_response.json";
                if ($report->application_id && Equifax::isFileExist($file_path)) {
                    $is_existing = (new ConsumerApplicationController())->isExistingCustomer($report->application_id);
                    $CountOFSUBSMADBTLSS = 0;
                    $equifax = new Equifax(new Request(array('application_id' => $report->application_id, 'applicant_type' => 1, 'request_type' => 'customer')));
                    $response = $equifax->parseResponse(false);
                    if (!isset($response['e'])) {
                        $event->comment('Executed '.$report->id);
                        $nameInfo = isset($response['IDAndContactInfo']['sch:PersonalInfo']['sch:Name']) ? $response['IDAndContactInfo']['sch:PersonalInfo']['sch:Name'] : '';

                        $Accounts = $response['Accounts'];
                        $EnquirySummary = $response['EnquirySummary'];

                        $historyType = [];
                        $sixMonthDPD = [];
                        if ($Accounts) {
                            foreach ($Accounts as $account) {
                                $CountOFSUBSMADBTLSSFound = false;
                                if (isset($account["sch:History48Months"]["sch:Month"]["sch:PaymentStatus"])) {
                                    $historyData = $account["sch:History48Months"]["sch:Month"]["sch:PaymentStatus"];
                                    $history = $account["sch:History48Months"]["sch:Month"];
                                    $date = '01-' . ((explode('-', $history["@key"])[1] == 19) ? explode('-', $history["@key"])[0] . '-2019' : $history["@key"]);
                                    $date = Carbon::parse($date)->toDateTimeString();
                                    if (in_array($historyData, ['SUB', 'SMA', 'DBT', 'LSS'])) {
                                        $CountOFSUBSMADBTLSSFound = true;
                                    }
                                    $historyType[] = $historyData;
                                    if (strtotime($date) >= Carbon::now()->subMonth(6)->startOfDay()->timestamp) {
                                        $sixMonthDPD[] = $historyData;
                                    }
                                } else if (isset($account["sch:History48Months"]["sch:Month"])) {
                                    foreach ($account["sch:History48Months"]["sch:Month"] as $history) {
                                        $historyData = $history["sch:PaymentStatus"];
                                        $date = '01-' . ((explode('-', $history["@key"])[1] == 19) ? explode('-', $history["@key"])[0] . '-2019' : $history["@key"]);
                                        $date = Carbon::parse($date)->toDateTimeString();
                                        if (in_array($historyData, ['SUB', 'SMA', 'DBT', 'LSS'])) {
                                            $CountOFSUBSMADBTLSSFound = true;
                                        }
                                        $historyType[] = $historyData;
                                        if (strtotime($date) >= Carbon::now()->subMonth(6)->startOfDay()->timestamp) {
                                            $sixMonthDPD[] = $historyData;
                                        }
                                    }
                                }
                                if ($CountOFSUBSMADBTLSSFound)
                                    $CountOFSUBSMADBTLSS++;
                            }
                        }

                        $dpdsData = array_count_values($historyType);
                        $sixMonthdpdsData = array_count_values($sixMonthDPD);
                        $Lessthan30days = 0;
                        $Lessthan90days = 0;
                        $Morethan90days = 0;
                        $sixMonthdpdsDPD = 0;
                        if ($sixMonthdpdsData) {
                            foreach ($sixMonthdpdsData as $dpd => $value) {
                                if (!in_array($dpd, ['000', '*']) && is_numeric(str_replace('+','',$dpd))) {
                                    if ((int)$dpd) {
                                        $sixMonthdpdsDPD++;
                                    }
                                }
                            }
                        }
                        if ($dpdsData) {
                            foreach ($dpdsData as $dpd => $value) {
                                if (!in_array($dpd, ['000', '*']) && is_numeric(str_replace('+','',$dpd))) {
                                    $_dpd = (int)$dpd;
                                    if ($_dpd < 30) {
                                        $Lessthan30days++;
                                    } else if ($_dpd < 90) {
                                        $Lessthan90days++;
                                    } else if ($_dpd > 90) {
                                        $Morethan90days++;
                                    }
                                }
                            }
                        }

                        $AverageOpenBalance = isset($response['AccountSummary']['sch:AverageOpenBalance']) ? $response['AccountSummary']['sch:AverageOpenBalance'] : 0;
                        $NoOfAccounts = isset($response['AccountSummary']['sch:NoOfAccounts']) ? $response['AccountSummary']['sch:NoOfAccounts'] : 0;
                        $NoOfActiveAccounts = isset($response['AccountSummary']['sch:NoOfActiveAccounts']) ? $response['AccountSummary']['sch:NoOfActiveAccounts'] : 0;

                        $foirData = FOIR::where('application_id',$report->application_id)->where('AccountType','!=','Credit Card')->get(['ApprovedAmount','AccountType']);

                        foreach ($foirData as $foirItem){
                            $foirResponse[] = ['AccountType' => $foirItem->AccountType, 'ApprovedAmount' => $foirItem->ApprovedAmount];
                        }

                        $data[] = [
                            'ID' => $report->application_id,
                            'Name on Cibil Report' => (isset($nameInfo['sch:FirstName']) ? $nameInfo['sch:FirstName'] : '') . ' ' . (isset($nameInfo['sch:MiddleName']) ? $nameInfo['sch:MiddleName'] : '') . ' ' . (isset($nameInfo['sch:LastName']) ? $nameInfo['sch:LastName'] : ''),
                            'PAN' => isset($report->PANIdsList) ? $report->PANIdsList : '',
                            'Cibil Score' => isset($report->Score) ? $report->Score : '',
                            'Number of Enquires in last 12 Months' => isset($EnquirySummary['sch:Past12Months']) ? $EnquirySummary['sch:Past12Months'] : 0,
                            'Total Accounts' => isset($response['AccountSummary']['sch:NoOfAccounts']) ? $response['AccountSummary']['sch:NoOfAccounts'] : 0,
                            'Total Closed Accounts' => $NoOfAccounts - $NoOfActiveAccounts,
                            'Count of SUB,SMA,DBT,LSS' => $CountOFSUBSMADBTLSS,
                            'Count of Settled & Written off accounts' => isset($response['AccountSummary']['sch:NoOfWriteOffs']) ? $response['AccountSummary']['sch:NoOfWriteOffs'] : 0,
                            'Total Sanctioned Amount' => isset($response['AccountSummary']['sch:TotalSanctionAmount']) ? $response['AccountSummary']['sch:TotalSanctionAmount'] : 0,
                            'Total Outstanding Amount' => isset($response['AccountSummary']['sch:TotalBalanceAmount']) ? $response['AccountSummary']['sch:TotalBalanceAmount'] : 0,
                            'Total Overdue Amount' => isset($report->TotalPastDue) ? $report->TotalPastDue : 0,
                            '# DPD in last 6months' => $sixMonthdpdsDPD,
                            '# DPD in past ( Less than 30 days)' => $Lessthan30days,
                            '# DPD in past ( Less than 90 days)' => $Lessthan90days,
                            '# DPD in past ( More than 90 days)' => $Morethan90days,
                            'AverageOpenBalance' => $AverageOpenBalance,
                            'is_existing' => $is_existing ? 1 : 0
                        ];
                    }
                }
            }

            if (isset($data)) {
                if ($type)
                    return $data;
                $Bureau_Data_Report = Carbon::now()->toDateTimeString() . 'Bureau_Data_Report.xlsx';

                $requestData = new Request(['data' => $data, 'sheet' => 'Sheet1']);
                Excel::store((new Exporter($requestData)), $Bureau_Data_Report);


                $Bureau_Data_Report_Foir = Carbon::now()->toDateTimeString() . 'Bureau_Data_Report_Foir.xlsx';
                $reportFoir = 0;
                if (isset($foirResponse) && !empty($foirResponse)) {
                    $reportFoir = 1;
                    $requestDataFoir = new Request(['data' => $foirResponse, 'sheet' => 'Sheet1']);
                    Excel::store((new Exporter($requestDataFoir)), $Bureau_Data_Report_Foir);
                }



                $event->comment('sending email total:count'. count($data));
                Mail::send('emails.reminders.basic_reminder',
                    ['body' => 'Bureau_Data_Report']
                    , function ($message) use ($Bureau_Data_Report, $Bureau_Data_Report_Foir, $reportFoir) {
                        $message->to(['sunil@creditfair.in'])->subject('Bureau Data Report');
                        $message->attachData(file_get_contents(storage_path() . '/app/' . $Bureau_Data_Report), 'Bureau_Data_Report ' . Carbon::now()->toDateTimeString() . '.xlsx');
                        if ($reportFoir){
                            $message->attachData(file_get_contents(storage_path() . '/app/' . $Bureau_Data_Report_Foir), 'Bureau_Data_Report_FOIR ' . Carbon::now()->toDateTimeString() . '.xlsx');
                        }
                    });
                $event->comment('email sent successfully');
            }else{
                $event->comment('error while sending email');
            }
        }catch (\Exception $e){
            (new Slack(new Request(['title' => 'Job Error', 'fields' => ['error' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString(), 'application_id' => 0, 'id_type' => 'application_id']])))->send();
        }
    }

    public function getDataForML($event = array()){
        $consumerApplication = new ConsumerApplicationController();
        $data = ConsumerApplication::with('creditReport','company')->whereNull('is_deleted')->get();
        $views = [];
        foreach($data as $item){
            $event->comment('Processing '.$item->id);
            if($item->loan_amount && $item->employee_status && $item->monthly_income && $item->tenure) {
                $grade = new GradeController(new Request());
                $foir = $grade->getFOIRByID($item->id, true);
                if (round($foir->foirIncludingCFEMI, 2) && round($foir->foirNAIncludingCFEMI, 2)) {
                    $BureauData = $this->getAnalyticsData($event, $item->id);
                    $views[] = array(
                        'id' => $item->id,
                        'gender' => $item->gender,
                        'employee_status' => $item->employee_status,
                        'marital_status' => empty($item->marital_status) ? 'Married' : $item->marital_status,
                        'house_type' => ($item->permanent_address_status) ? $item->permanent_address_status : ($item->current_address_status ? $item->current_address_status : ''),
                        'company_score' => ($item->company) && isset($item->company->category) ? $item->company->category : 'CAT D',
                        'age' => $item->age,
                        'loan_amount' => $item->loan_amount,
                        'monthly_income' => $item->monthly_income,
                        'tenure' => $item->tenure,
                        'score' => ($item->creditReport) && isset($item->creditReport[0]->Score) ? $item->creditReport[0]->Score : 0,
                        'foir' => round($foir->foirNAIncludingCFEMI, 2),
                        'cf_foir' => round($foir->foirIncludingCFEMI, 2),
                        'dpd_last_six_month' => isset($BureauData[0]) && isset($BureauData[0]['# DPD in last 6months']) ? $BureauData[0]['# DPD in last 6months'] : 0,
                        'status' => in_array($item->state, $consumerApplication->statusreversearray['approved']) ? 0 : 1
                    );
                }
            }
        }

        $event->comment('Total Data count: '.count($views));
        $file = fopen(storage_path()."/customers_latest.csv","w");

        foreach ($views as $line) {
            fputcsv($file, $line);
        }

        fclose($file);
        return 4;
    }

    public function getMarkyticsData(Request $request, $single = false){
        $data = ConsumerApplication::with('emi','foir')->whereNotNull('co_applicant_name')->whereNull('is_deleted');
            if($single){
                $data = $data->where('id',$single);
            }
        $data = $data->get();
        $views[] = ['Id','Co-Applicant Name','Co-Applicant Email','Co-Applicant Mobile Number','Co-Applicant Gender','Co-Applicant DOB','Co-Applicant Pan Card','Co-Applicant Aadhaar Card', 'Co-Applicant Address', 'Co-Applicant Landmark','Co-Applicant City','Co-Applicant State','Co-Applicant Pincode','Co-Applicant Address Status','Co-Applicant Monthly Income','Co-Applicant Relationship','Co-Applicant Company Name','Co-Applicant Employee Status','Subvention Amount','CGST','SGST','IGST','Sanction Amount','Existing EMIs in Bureau Data','Foir all Cases','Interest Rate','Tenure'];
        foreach($data as $item){

            $installment_amount = 0;
            if ($item->foir) {
                foreach ($item->foir as $foir){
                    if($foir->cc_loan == 1 && $foir->isOpened == 1 && ($foir->Balance > 0 || $foir->created_by > 0)) {
                        $installment_amount += $foir->InstallmentAmount;
                    }
                }
            }
            $grade = new GradeController($request);
            $foir = $grade->getFOIRByID($item->id, true);

            $views[] = array(
                /*'id' => $item->id,*/
                'co_applicant_name' => $item->co_applicant_name,
                'co_applicant_email' => $item->co_applicant_email,
                'co_applicant_mobile_number' => $item->co_applicant_mobile_number,
                'co_applicant_gender' => $item->co_applicant_gender,
                'co_applicant_dob' => $item->co_applicant_dob,
                'co_applicant_pan_card' => $item->co_applicant_pan_card,
                'co_applicant_aadhaar_card' => $item->co_applicant_aadhaar_card,
                'co_applicant_address_line_1' => $item->co_applicant_address_line_1,
                'co_applicant_address_landmark' => $item->co_applicant_address_landmark,
                'co_applicant_address_city' => $item->co_applicant_address_city,
                'co_applicant_address_state' => $item->co_applicant_address_state,
                'co_applicant_address_pincode' => $item->co_applicant_address_pincode,
                'co_applicant_address_status' => $item->co_applicant_address_status,
                'co_applicant_monthly_income' => $item->co_applicant_monthly_income,
                'co_applicant_relationship' => $item->co_applicant_relationship,
                'co_applicant_company_name' => $item->co_applicant_company_name,
                'co_applicant_employee_status' => $item->co_applicant_employee_status,
                'subvention_amount' => ($item->emi) ? ($item->approved_amount * $item->emi->subvention) / 100 : '',
                'cgst_subvention' => ($item->emi) ? $item->emi->subvention_cgst : '',
                'sgst_subvention' => ($item->emi) ? $item->emi->subvention_sgst : '',
                'igst_subvention' => ($item->emi) ? $item->emi->subvention_igst : '',
                'approved_amount' => $item->approved_amount,
                'Existing emi from bureau data' => $installment_amount,
                'Foir for all cases' => $foir->foirIncludingCFEMI,
                /*'Interest Rate' => ($item->emi) ? $item->emi->interest_rate : '',
                'Tenure of Loan' => $item->tenure,*/
            );

            if ($single){
                return $views[1];
            }
        }

        return array(
            /*'id' => $item->id,*/
            'co_applicant_name' => '',
            'co_applicant_email' => '',
            'co_applicant_mobile_number' => '',
            'co_applicant_gender' => '',
            'co_applicant_dob' => '',
            'co_applicant_pan_card' => '',
            'co_applicant_aadhaar_card' => '',
            'co_applicant_address_line_1' => '',
            'co_applicant_address_landmark' => '',
            'co_applicant_address_city' => '',
            'co_applicant_address_state' => '',
            'co_applicant_address_pincode' => '',
            'co_applicant_address_status' => '',
            'co_applicant_monthly_income' => '',
            'co_applicant_relationship' => '',
            'co_applicant_company_name' => '',
            'co_applicant_employee_status' => '',
            'subvention_amount' => '',
            'cgst_subvention' => '',
            'sgst_subvention' => '',
            'igst_subvention' => '',
            'approved_amount' => '',
            'Existing emi from bureau data' => '',
            'Foir for all cases' => '',
            /*'Interest Rate' => '',
            'Tenure of Loan' => '',*/
        );

        $Bureau_Data_Report = Carbon::now()->toDateTimeString() . 'Bureau_Data_Report_latest.xlsx';

        $requestData = new Request(['data' => $views, 'sheet' => 'Sheet1']);
        return Excel::download((new Exporter($requestData)), $Bureau_Data_Report);
    }

    public function updateUserTypes(){
        $types = ['consumer', 'merchant', 'center_head', 'center_executive'];
        $users = User::whereIn('user_type',$types)->get(['id']);
        foreach ($users as $user){
            if ($user->user_type == 'consumer'){
                User::where('id',$user->id)->update(['user_type' => 1]);
            }else if ($user->user_type == 'merchant'){
                User::where('id',$user->id)->update(['user_type' => 2]);
            }else if ($user->user_type == 'center_head'){
                User::where('id',$user->id)->update(['user_type' => 3]);
            }else if ($user->user_type == 'center_executive'){
                User::where('id',$user->id)->update(['user_type' => 4]);
            }
        }
    }

    public function rejectBulkV1(){
        Excel::import(new TestImport(new Request(['from' => __FUNCTION__])), storage_path().'/rejection_with_message.xlsx');
    }

    public function rejectBulk(){
        Excel::import(new TestImport(new Request(['from' => __FUNCTION__])), storage_path().'/rejectBulk.xlsx');
    }

    public function ConsumerApplicationEncrypt(){

        $encryptable = ConsumerApplication::$encryptable;
        array_push($encryptable, 'id');
        $ConsumerApplication = ConsumerApplication::whereNull('is_deleted')->whereNotIn('id',[7,11])->get($encryptable);
        foreach ($ConsumerApplication as $item){
            unset($encryptable[array_search('id',$encryptable)]);
            $res = [];
            foreach ($encryptable as $_item){
                if ($item->$_item) {
                    $res[$_item] = wall_encrypt($item->$_item);
                }
            }
            if ($res) {
                ConsumerApplication::where('id', $item->id)->update($res);
            }
        }
    }


    public function ConsumerApplicationElementEncrypt(){

        $encryptable = ConsumerApplicationElement::$encryptable;
        array_push($encryptable, 'id');
        $ConsumerApplication = ConsumerApplicationElement::whereNotNull('id')->get($encryptable);
        foreach ($ConsumerApplication as $item){
            unset($encryptable[array_search('id',$encryptable)]);
            $res = [];
            foreach ($encryptable as $_item){
                if ($item->$_item) {
                    $res[$_item] = wall_encrypt($item->$_item);
                }
            }
            if ($res) {
                ConsumerApplicationElement::where('id', $item->id)->update($res);
            }
        }
    }


    public function ConsumerApplicationFilesEncrypt(){

        $encryptable = ConsumerApplicationFiles::$encryptable;
        array_push($encryptable, 'id');
        $ConsumerApplication = ConsumerApplicationFiles::whereNotNull('id')->get($encryptable);
        foreach ($ConsumerApplication as $item){
            unset($encryptable[array_search('id',$encryptable)]);
            $res = [];
            foreach ($encryptable as $_item){
                if ($item->$_item) {
                    $res[$_item] = wall_encrypt($item->$_item);
                }
            }
            if ($res) {
                ConsumerApplicationFiles::where('id', $item->id)->update($res);
            }
        }
    }


    public function CreditReportEncrypt(){

        $encryptable = CreditReport::$encryptable;
        array_push($encryptable, 'id');
        $ConsumerApplication = CreditReport::whereNull('is_deleted')->get($encryptable);
        foreach ($ConsumerApplication as $item){
            unset($encryptable[array_search('id',$encryptable)]);
            $res = [];
            foreach ($encryptable as $_item){
                if ($item->$_item) {
                    $res[$_item] = wall_encrypt($item->$_item);
                }
            }
            if ($res) {
                CreditReport::where('id', $item->id)->update($res);
            }
        }
    }


    public function MerchantEncrypt(){

        $encryptable = Merchant::$encryptable;
        array_push($encryptable, 'id');
        $ConsumerApplication = Merchant::whereNull('deleted_at')->get($encryptable);
        foreach ($ConsumerApplication as $item){
            unset($encryptable[array_search('id',$encryptable)]);
            $res = [];
            foreach ($encryptable as $_item){
                if ($item->$_item) {
                    $res[$_item] = wall_encrypt($item->$_item);
                }
            }
            if ($res) {
                Merchant::where('id', $item->id)->update($res);
            }
        }
    }

    public function tallyTesting(){
        /*$tally = new Tally(
            new Request([
                'job' => 1,
                'is_auto' => false
            ]),
            new TallyConnector()
        );*/

        //return $tally->createMasters(6511);
        //return (new TallySettlementJobs())->handle();

        $data = Settlement::where('id', 297)->first();
        $data = json_decode($data->data);
        $txt = '';
        $names = [];
        foreach ($data->data as $item){
            if($item->amount == 11083){
                $d = 1;
            }
            $amounts[] = (int)trim($item->amount);
            $names[] = $item->application_id;
        }
        //$myfile = fopen("amt_lt.txt", "w") or die("Unable to open file!");
        //fwrite($myfile, $txt);
        //fclose($myfile);
        //return 4;


        //$amounts = file_get_contents(storage_path().'/amt_lt.txt');

        $all_amt = [];
        $list = simplexml_load_file(storage_path().'/scratch.xml');
        $processedAmount = 0;
        foreach($list->BODY->IMPORTDATA->REQUESTDATA->TALLYMESSAGE->VOUCHER as $item){
            foreach ($item as $key => $data){
                if(strpos($key,'ALLLEDGERENTRIES') !== false) {
                    $amount = (int)$data->AMOUNT;
                    $all_amt[] = $amount;
                    if(isset(explode('-',$data->LEDGERNAME)[1])) {
                        $all_names[] = explode('-', $data->LEDGERNAME)[1];
                    }
                    if($amount < 0){
                        $TOTAL_AMOUNT = $amount;
                    }else{
                        $processedAmount += $amount;
                    }
                }else{
                    $d = 3;
                }
            }
        }

        $cc = [];
        //$amounts = explode("\n",$txt);
        foreach ($all_amt as $itemc) {
            if(!in_array(trim($itemc), $amounts)){
                $cc[] = $itemc;
            }
        }
        foreach ($names as $dd){
            if(!in_array($dd, $all_names)){
                $c[] = $dd;
             }
        }
        return 4;
    }

    public function MerchantLocationEncrypt(){

        $encryptable = MerchantLocation::$encryptable;
        array_push($encryptable, 'id');
        $ConsumerApplication = MerchantLocation::whereNull('is_deleted')->get($encryptable);
        foreach ($ConsumerApplication as $item){
            unset($encryptable[array_search('id',$encryptable)]);
            $res = [];
            foreach ($encryptable as $_item){
                if ($item->$_item) {
                    $res[$_item] = wall_encrypt($item->$_item);
                }
            }
            if ($res) {
                MerchantLocation::where('id', $item->id)->update($res);
            }
        }
    }

    public function TelecomDataEncrypt(){

        $encryptable = TelecomData::$encryptable;
        array_push($encryptable, 'id');
        $ConsumerApplication = TelecomData::whereNull('is_deleted')->get($encryptable);
        foreach ($ConsumerApplication as $item){
            unset($encryptable[array_search('id',$encryptable)]);
            $res = [];
            foreach ($encryptable as $_item){
                if ($item->$_item) {
                    $res[$_item] = wall_encrypt($item->$_item);
                }
            }
            if ($res) {
                TelecomData::where('id', $item->id)->update($res);
            }
        }
    }

    public function UserEncrypt(){

        $encryptable = User::$encryptable;
        array_push($encryptable, 'id');
        $ConsumerApplication = User::whereNotNull('id')->get($encryptable);
        foreach ($ConsumerApplication as $item){
            unset($encryptable[array_search('id',$encryptable)]);
            $res = [];
            foreach ($encryptable as $_item){
                if ($item->$_item) {
                    $res[$_item] = wall_encrypt($item->$_item);
                }
            }
            if ($res) {
                User::where('id', $item->id)->update($res);
            }
        }
    }

    public function importCustomerDocuments(){

        $directory = "/Users/sunilkhorwal/Sites/customer_documents/";
        $request = new Request(['test_bot' => true]);
        $response = [];
        $files2 = scandir($directory, 1);
        $name = [];
        foreach ($files2 as $item){
            if (!in_array($item, ['.','..']) && is_dir($directory.'/'.$item)) {

                $files3 = scandir($directory.'/'.$item, 1);
                if (count($files3) > 2) {
                    foreach ($files3 as $item1) {
                        if (!in_array($item1, ['.','..']) && is_dir($directory.$item.'/'.$item1)) {
                            $files4 = scandir($directory . $item.'/'.$item1, 1);
                            if (count($files4) > 2) {
                                foreach ($files4 as $item2) {
                                    if (!in_array($item2, ['.','..'])) {
                                        if(strpos($item2,'.zip') === false) {
                                            $response[] = ['id' => trim(str_replace('(1)', '', $item1)), 'file' => $item2, 'path' => '/' . $item1 . '/' . $item2, 'user_id' => $item];
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        $done = $d = [];
        $document = new ConsumerDocument($request);
        foreach ($response as $item){
            if (true){
                $ex = substr($item['file'], 0, strrpos( $item['file'], '.'));
                if($ex) {
                    try {
                        $consumer_application_file = new ConsumerApplicationFiles();
                        $consumer_application_file->consumer_application_id = $item['id'];
                        $consumer_application_file->file_type = $ex;
                        $consumer_application_file->bank_name = '';
                        $consumer_application_file->password = '';
                        $consumer_application_file->accounttype = '';
                        $consumer_application_file->statementtype = '';
                        $consumer_application_file->statemenfilettype = '';
                        $consumer_application_file->customer_id = '';
                        $consumer_application_file->provider = '';
                        $consumer_application_file->finbit_analysis_date = '';
                        $consumer_application_file->bp_number = '';
                        $consumer_application_file->accountUID = '';
                        $consumer_application_file->file_path = $item['path'];
                        $consumer_application_file->created_by = 54397;
                        $consumer_application_file->image_score = '';
                        $consumer_application_file->m_generated = 1;
                        $consumer_application_file->applicant_type = 1;
                        $consumer_application_file->bureau_report_type = '';
                        $consumer_application_file->bureau_report_score = '';
                        $consumer_application_file->is_masked = 0;
                        $consumer_application_file->save();


                        $done[] = $item;
                    }catch (\Exception $e){
                        $d[] = [$item, $e->getMessage(), $e->getLine(), $e->getFile()];
                    }
                }
            }else{
                $d[] = $item;
            }
        }

        return [$directory, $done, $d];

    }

    public function importZokoDocuments(){
        //Excel::import(new TestImport(new Request(['from' => __FUNCTION__])), storage_path().'/zoko_complete_data_latest.xlsx');

        $collection = Excel::toCollection(new TestImport(new Request(['from' => __FUNCTION__])), storage_path().'/zoko_complete_data_latest.xlsx');
        $collection = $collection[0];

        unset($collection[0]);
        $directory = "/Users/sunilkhorwal/Sites/zoko_backup/ceb767af-f50f-48db-a560-fc448c62b50b/";
        $request = new Request(['test_bot' => true]);

        $files2 = scandir($directory, 1);
        $name = [];
        foreach ($files2 as $item){
            $nameE = explode('.', $item)[0];
            $name[$nameE] = trim($item);
        }


        $document = new ConsumerDocument($request);
        foreach ($collection as $item){
            if (isset($name[$item[0]]) && file_exists($directory.$name[$item[0]])){
                $ids = explode(',', $item[1]);
                foreach ($ids as $_id) {
                    $document->uploadToS3($item[2], (int)$_id, file_get_contents($directory . $name[$item[0]]), '.' . explode('.', $name[$item[0]])[1]);
                }
                $done[] = $item[0];
            }else{
                $d[] = $item[0];
            }
        }

        return $directory;

    }

    public function importDocument(){

        $directory = storage_path("/CustomerDocuments");
        $request = new Request(['test_bot' => true]);

        $files2 = scandir($directory, 1);
        $name = [];

        foreach ($files2 as $item){
            if (!in_array($item, ['..', '.'])){
                if(is_dir($directory . '/' . $item)) {
                    $item1 = scandir($directory . '/' . $item, 1);
                    foreach ($item1 as $value) {
                        if (!in_array($value, ['..', '.'])) {
                            if(is_dir($directory . '/' . $item.'/'.$value)) {
                                $item2 = scandir($directory . '/' . $item.'/'.$value, 1);
                                foreach ($item2 as $value1) {
                                    if (!in_array($value1, ['..', '.'])) {
                                        return $item2;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        $document = new ConsumerDocument($request);
        foreach ($collection as $item){
            if (isset($name[$item[0]]) && file_exists($directory.$name[$item[0]])){
                $ids = explode(',', $item[1]);
                foreach ($ids as $_id) {
                    $document->uploadToS3($item[2], (int)$_id, file_get_contents($directory . $name[$item[0]]), '.' . explode('.', $name[$item[0]])[1]);
                }
                $done[] = $item[0];
            }else{
                $d[] = $item[0];
            }
        }

        return $directory;

    }

    public function importMerchantLocation(){
        Excel::import(new TestImport(new Request(['from' => __FUNCTION__])), storage_path().'/merchant_centre_list.xlsx');
    }

    public function importMerchantCategoryFile(){
        Excel::import(new TestImport(new Request(['from' => __FUNCTION__])), storage_path().'/merchant_categorisation.xlsx');
    }

    public function importMerchantCenterVLCC(){
        Excel::import(new TestImport(new Request(['from' => __FUNCTION__])), storage_path().'/list_of_centers.xlsx');
    }

    public function importMerchantCenterVLCCUsers(){
        Excel::import(new TestImport(new Request(['from' => __FUNCTION__])), storage_path().'/list_of_centers.xlsx');
    }

    public function generatePanValidationEquifax(){
        $applicants = [
            6135,
6134,
6120,
6138,
6139,
6140,
6141,
6143,
6131,
6122,
6123,
6124,
6125,
6126,
6127,
6118,
6119,
6101,
6102,
6103,
6105,
6106,
6109,
6107,
6111,
6115,
6112,
6113,
6116,
6117,
6099];


        $coapplicant = [
            5875,
            6119,
            6101,
            6085

        ];

        $update = [];
        foreach ($applicants as $applicant) {
            $pan = (new Equifax(new Request(['applicant_type' => 1, 'application_id' => $applicant])))->getPanValidationData();
            CreditReport::where('application_id', $applicant)->where('applicant_type', 1)->update(['panValidation' => json_encode($pan)]);
            $update++;
        }

        foreach ($coapplicant as $_applicant) {
            $_pan = (new Equifax(new Request(['applicant_type' => 2, 'application_id' => $_applicant])))->getPanValidationData();
            CreditReport::where('application_id', $_applicant)->where('applicant_type', 2)->update(['panValidation' => json_encode($_pan)]);
            $update++;
        }

        return $update;
    }

    public function ImranAuditData(){
        $d = ConsumerApplication::with('merchant')->whereHas('logs', function($q){
            $q->where('created_at','>=',"2019-10-06 00:00:00")
                ->where('created_at','<=',"2019-10-15 23:59:59");
        })->whereNull('is_deleted')->where('state',['disbursed','nach registered'])
            ->groupBy('id')->get(['id','merchant_id','name','mobile_number','state','permanent_address_line_1','permanent_address_state','permanent_address_pincode']);

        $response = [];
        foreach ($d as $item){
            $response[] = [
                'id' => $item->id,
                'name' => $item->name,
                'mobile_number' => $item->mobile_number,
                'state' => $item->state,
                'permanent_address_line_1' => $item->permanent_address_line_1,
                'permanent_address_state' => $item->permanent_address_state,
                'permanent_address_pincode' => $item->permanent_address_pincode,
                'merchant' => $item->merchant ? $item->merchant->merchant_name : '',
            ];
        }
        $request = new Request(['data' => $response, 'sheet' => 'Sheet1']);
        return Excel::download((new Exporter($request)), 'imran.xls');
    }

    public function ProcessingFeeEntries(){
        return Excel::import(new TestImport(new Request(['from' => __FUNCTION__])), storage_path().'/processing_fee_entries_pending.xlsx');
    }

    public function uploadNachData(){
        return Excel::import(new TestImport(new Request(['from' => __FUNCTION__])), storage_path().'/hdfc_final_expiry_date_update_data.xlsx');
    }

    public function uploadBankDetails(){
        Excel::import(new TestImport(new Request(['from' => __FUNCTION__])), storage_path().'/live_bank_list_nach_supported.xlsx');
    }

    public function uploadPincodeLists(){
        Excel::import(new TestImport(new Request(['from' => __FUNCTION__])), storage_path().'/new_pincode_list.xlsx');
    }

    public function getMahimaData(){
        ini_set('max_execution_time', 0);
        $applications = ConsumerApplication::with('merchant')->whereNull('is_deleted')->get();

        foreach ($applications as $application){

            if (isset($application->permanent_address_line_1) && $application->permanent_address_line_1 != "") {
                $address_line1 = $application->permanent_address_line_1;
                $address_state = $application->permanent_address_state;
                $address_city = $application->permanent_address_city;
                $address_pincode = $application->permanent_address_pincode;
            } else {
                $address_line1 = $application->current_address_line_1;
                $address_state = $application->current_address_state;
                $address_city = $application->current_address_city;
                $address_pincode = $application->current_address_pincode;
            }

            $data[] = [
                'app_id' => $application->id,
                'loan_amount' => $application->loan_amount,
                'full_name' => $application->name,
                'address' => $address_line1.', '.$address_state.', '.$address_city.' '.$address_pincode,
                'city' => $address_city,
                'pin code' => $address_pincode,
                'state'  => $address_state,
                'pan number' => $application->pan_card,
                'phone number' => $application->mobile_number,
                'gender' => $application->gender,
                'birthdate' => $application->dob,
                'current stage' => $application->state,
                'date of login' => $application->created_at,
                'merchant name' => ($application->merchant) ? $application->merchant->merchant_name: ''
            ];
        }


        $request = new Request(['data'=>$data,'sheet'=>'Sheet1']);
        return \Maatwebsite\Excel\Facades\Excel::download((new Exporter($request)), 'mahima_data.xls');
    }

    public function uploadPendingCollectionReport(){
        return Excel::import(new TestImport(new Request(['from' => __FUNCTION__])), storage_path().'/imran_merchant_list_to_set_collection_reminder.xlsx');
    }

    public function fixMissingReferral(){
        $merchant = Merchant::whereNull('code')->get(['id','code']);
        foreach ($merchant as $item){
            $code = (new MerchantController())->getReferralCode();
            Merchant::where('id', $item->id)->update(['code' => $code]);
        }
        return 4;
    }

    public function uploadPendingLotusPayEntries(){
        ini_set('max_execution_time', -1);
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        return Excel::import(new TestImport(new Request(['from' => __FUNCTION__])), storage_path().'/lotuspay_sample_file.xlsx');
    }

    public function uploadCompanyData(){
        ini_set('max_execution_time', -1);
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        return Excel::import(new TestImport(new Request(['from' => __FUNCTION__])), storage_path().'/cat_list.xls');
    }

    public function uploadPincodeDataForApprover(Request $request){
        return Excel::import(new TestImport(new Request(['from' => __FUNCTION__, 'id' => $request->get('id')])), storage_path().'/pincode_1.xlsx');
    }

    public function sageMakerDataSets(Request $request, $event){

        ini_set('max_execution_time', -1);
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $applicationController = new ConsumerApplicationController();
        (new ConsumerApplication())->isAccountOpened(true);
        $applications = ConsumerApplication::whereNull('is_deleted')->get();

        //$data[] = ['ID','Category','Loan Amount',	'Tenure',	'Monthly Income',	'Score',	'Age',	'FOIR',	'Past Dues',	'Term Loan',	'Case Type', 'Auto Approved', 'Auto Rejected',	'Rejected',	'Rejected Reason', 'Abort',	'Abort Reason',	'Pincode',	'Bank Name',	'Branch Name',	'Industry',	'Marital Status',	'City',	'State','All Documents','Document Received','Pending Documents','Mandatory Document','Account Has DPD (have had even 1 DPD)','Approval Status'];
        $data[] = ['ID','Abort', 'Approval Status'];

        $termloanarray = ['Auto Loan', 'Housing Loan', 'Personal Loan', 'Consumer Loan', 'Education Loan', 'Loan to Professional', 'Two-wheeler Loan', 'Commercial Vehicle Loan', 'Used Car Loan',
            'Business Loan-Priority Sector-Small Business', 'Business Loan - Priority Sector- Agriculture', 'Business Loan - Priority Sector- Others', 'Business Non-Funded Credit Facility',
            'Business Non-Funded Credit Facility - Priority', 'Staff Loan'];

        $_termLoan = 0;

        foreach ($applications as $application) {
            try {

                /*$event->comment($application->id);

                $creditReport = CreditReport::where('application_id', $application->id)->where('applicant_type', 1)->first(['id','Score','TotalPastDue']);
                $foirReport = [];
                if (isset($creditReport->id)) {
                    $foirReport = FOIR::where('application_id', $application->id)->where('applicant_type', 1)->get();
                }
                $bank_details = Bank::where('application_id', $application->id)->first();
                $application_element = ConsumerApplicationElement::where('application_id', $application->id)->first();
                $logs = StatusLogs::where('application_id', $application->id)->get();

                $accountDPD = 0;
                $caseTypeData = '';

                if ($creditReport && $creditReport->Score < 10) {
                    $oldloan = 0;
                    $unsecuredloan = 0;
                } else {
                    $oldloan = 1;
                    $unsecuredloan = 1;
                }*/

                /*if (isset($foirReport) && $foirReport) {
                    foreach ($foirReport as $foir) {

                        $foirDataCheck = json_decode($foir->dpd, 1);

                        foreach ($foirDataCheck as $key => $item) {
                            if (!in_array($key, ['NEW', '*', '000', 'CLSD'])) {
                                $accountDPD++;
                                break;
                            }
                        }


                        $caseType = array_keys($foirDataCheck);
                        if ($caseType) {
                            foreach ($caseType as $type) {
                                if (in_array($type, ['PWOS', 'SET'])) {
                                    $caseTypeData = $type;
                                    break;
                                }
                            }
                        }

                        if ($foir->DateOpened) {
                            if (!$foir->DateClosed) {
                                $foir->DateClosed = "";
                            }
                            if ($foir->DateClosed) {
                                $termLoan = GradeController::calculatedifferenceindate($foir->DateOpened, $foir->DateClosed);
                            } else {
                                $termLoan = GradeController::calculatedifferenceindate($foir->DateOpened);
                            }

                            if ($termLoan > 0 && $oldloan != 0) {
                                $oldloan = 0;
                            }

                            if ((in_array($foir->AccountType, $termloanarray)) && $unsecuredloan != 0) {
                                $unsecuredloan = 0;
                            }
                        }


                        if ($oldloan == 0 && $unsecuredloan == 0) {
                            $_termLoan = 0;
                        } else {
                            $_termLoan = 1;
                        }
                    }
                }*/
                $logs = StatusLogs::where('application_id', $application->id)->get();

                $rejected = false;
                $reason = '';


                $abort = false;
                $abort_reason = '';
                $auto_approved = false;
                $auto_rejected = false;

                if ($application->state == 'aborted') {
                    $abort = true;
                }


                foreach ($logs as $log) {
                    if ($abort && $log->status == 'aborted') {
                        $abort_reason = $log->reason;
                    }
                    if($log->status == 'approved' && $log->user_id == 107){
                        $auto_approved = true;
                    }
                    if($log->status == 'rejected' && $log->user_id == 107){
                        $auto_rejected = true;
                    }

                }

                /*if (count($logs) && $logs[count($logs) - 1]->status == 'rejected') {
                    $rejected = true;
                    if ($logs[count($logs) - 1]->reason) {
                        $reason = $logs[count($logs) - 1]->reason;
                    }
                }*/

                /*$foirData = (new GradeController($request))->getFOIRByID($application->id);*/

                $status = in_array($application->state, ['form completed', 'incomplete form', 'rejected', 'aborted', 'in-process', 'waiting for documents', 'waiting for decision', 'pre approved']) ? 'No' : 'Yes';

                /*$documents = $applicationController->pendingDoc($application, []);

                $received = '';
                if (isset($documents['document']) && $documents['document'] && isset($documents['docsRequired'])) {
                    if (isset($documents['document']['Get Pincode Approval']))
                        unset($documents['document']['Get Pincode Approval']);
                    if (isset($documents['docsRequired']['Get Pincode Approval']))
                        unset($documents['docsRequired']['Get Pincode Approval']);


                    $documents['document'] = array_keys($documents['document']);
                    $documents['docsRequired'] = array_keys($documents['docsRequired']);
                    $lists = [];
                    foreach ($documents['document'] as $d){
                        $_lists = explode('Or',$d);
                        foreach ($_lists as $c){
                            if($c) {
                                $lists[] = trim($c);
                            }
                        }
                    }


                    $lists_ = [];
                    foreach ($documents['docsRequired'] as $p){
                        $_lists_ = explode('Or',$p);
                        foreach ($_lists_ as $l){
                            if($l) {
                                $lists_[] = trim($l);
                            }
                        }
                    }

                    $documents['document'] = $lists;

                    $documents['docsRequired'] = $lists_;
                    $received = array_diff($documents['document'], $documents['docsRequired']);
                    if (is_array($received)) {
                        $received = implode(',', $received);
                    }
                    if (is_array($documents['document'])) {
                        $documents['document'] = str_replace('"','',str_replace('":2','',str_replace('":1','',str_replace('":0','',str_replace('{"','',implode(',', $documents['document']))))));
                    }
                    if (is_array($documents['docsRequired'])) {
                        $documents['docsRequired'] = str_replace('"','',str_replace('":2','',str_replace('":1','',str_replace('":0','',str_replace('{"','',implode(',', $documents['docsRequired']))))));
                    }
                }else if($documents['docsRequired']){
                    $documents['docsRequired'] = implode(',',array_keys($documents['docsRequired']));
                }*/
                $data[] =[
                    'id' => $application->id,
                    'abort' => $abort,
                    'abort_reason' => $abort_reason,
                    'auto_approved' => $auto_approved,
                    'auto_rejected' => $auto_rejected,
                    'rejected' => $rejected,
                    'approval_Status' => $status,
                ];

               /* $data[] = [
                    'id' => $application->id,
                    'category' => $application->purpose,
                    'loan_amount' => $application->loan_amount,
                    'tenure' => $application->tenure,
                    'monthly_income' => $application->monthly_income,
                    'score' => $creditReport ? $creditReport->Score : '',
                    'age' => $application->Age,
                    'foir' => $foirData,
                    'past_dues' => $creditReport ? $creditReport->TotalPastDue : '',
                    'term_loan' => $_termLoan,
                    'case_type' => $caseTypeData,
                    'auto_approved' => $rejected,
                    'auto_rejected' => $rejected,
                    'rejected' => $rejected,
                    'reason' => $reason,
                    'abort' => $abort,
                    'abort_reason' => $abort_reason,
                    'Pin_code' => $application->current_address_pincode,
                    'bank_name' => isset($bank_details->bank_name) ? $bank_details->bank_name : '',
                    'branch_name' => isset($bank_details->branch_name) ? $bank_details->branch_name : '',
                    'industry' => $application_element ? ($application_element->industry == 0 ? 'Services' : ($application_element->industry == 1 ? 'Manufacturing' : ($application_element->industry == 3 ? 'Trading' : ''))) : '',
                    'marital_status' => $application->marital_status,
                    'city' => $application->current_address_city,
                    'state' => $application->current_address_state,
                    'all_documents' => isset($documents['document']) ? $documents['document'] : '',
                    'received' => $received,
                    'pending' => isset($documents['docsRequired']) ? $documents['docsRequired'] : '',
                    'mandatory' => $application_element ? ucwords(str_replace('_', ' ', $application_element->mandatory_document_list)) : '',
                    'account_dpd' => $accountDPD,
                    'approval_Status' => $status,
                ];*/
            }catch (\Exception $e){
                $event->comment('Error - '.$e->getMessage().'|'.$e->getLine(),'|'.$e->getFile());
            }
        }


        $request = new Request(['data'=>$data,'sheet'=>'Sheet1']);
        //(new Slack(new Request(['title' => 'SageMaker Data is ready', 'fields' => ['Total Rows' => count($data)]])))->send();
        return \Maatwebsite\Excel\Facades\Excel::download((new Exporter($request)), Carbon::now()->toDateString().'_sageMakerDataSets.xls');
    }

    public function getMachineLearningDataSets(){


        $applications = ConsumerApplication::with('application_element','creditReport')->whereNull('is_deleted')->where('merchant_id',8)->get();

        foreach ($applications as $application) {

            if($application->current_address_pincode) {
                $negativeArea = NegativeArea::where('pincode', $application->current_address_pincode)->first(['id']);
            }

            if (!isset($negativeArea->id) && $application->permanent_address_pincode){
                $negativeArea = NegativeArea::where('pincode', $application->permanent_address_pincode)->first(['id']);
            }

            $company = Company::where('id', $application->company_name)->first(['id']);

            $data[] = [
                'ID' => $application->id,
                'Age' => $application->Age,
                'Sex' => $application->gender == 'Male' ? 0 : ($application->gender == 'Female' ? 1 : null),
                'Martial Status' => !$application->gender ? null : ($application->gender == 'MARRIED' ? 1 : 0),
                'Child' => ($application->gender == 'MARRIED' ? ($application->Age > 30 && $application->Age < 40 ? 1 : 2) : 0),
                'Negative Area' => isset($negativeArea->id) ? 1 : 0,
                'Loan Amount' => $application->loan_amount,
                'Tenure' => $application->tenure,
                'Monthly Income' => $application->monthly_income,
                'Company' => isset($company->id) ? $company->category : 'CAT D',
                'Employee Status' => $application->employee_status,
                'Negative Profession' => $application->application_element && $application->application_element->negative_profile ? 1 : 0,
                'Company Type' => $application->profession_type,
                'Industry' => $application->industry,
                'Score' => $application->creditReport ? $application->creditReport->Score : null,
                'No of Active Accounts' => $application->creditReport ? $application->creditReport->NoOfActiveAccounts : null,
                'Past Dues' => $application->creditReport ? $application->creditReport->TotalPastDue : null,
                'Foir' => '',
                'Average Balance' => '',
                'Is Current Rented Is Permanent Rented Has Credit Card' => '',
            ];
        }
    }

    public function downloadMoratoriumSheet(){
        Excel::import(new TestImport(new Request(['from' => __FUNCTION__])), storage_path().'/ash_sheet_mora.xlsx');
    }

    public function sendMoratoriumCommunications(){
        Excel::import(new TestImport(new Request(['from' => __FUNCTION__])), storage_path().'/copy_of_moratorium_with_amount14.xlsx');
    }

    public function saveMoratoriumData(){
        Excel::import(new TestImport(new Request(['from' => __FUNCTION__])), storage_path().'/april_lt_imran.xlsx');
    }

    public function waiveOffData(){
        Excel::import(new TestImport(new Request(['from' => __FUNCTION__])), storage_path().'/waiveoff_data.xlsx');
    }

    public function uploadInvoiceData(){
        Excel::import(new TestImport(new Request(['from' => __FUNCTION__])), storage_path().'/invoice_update.xlsx');
    }

    public function allDisbursementAdvices(){

        ini_set('max_execution_time', -1);
        set_time_limit(0);
        ini_set('memory_limit', '-1');

        $zip = new \ZipArchive();
        $zipFileName = 'disbursement_advice_' . Carbon::now()->toDateTimeString() . '.zip';
        $res = $zip->open($zipFileName, \ZipArchive::CREATE);
        $applications = ConsumerApplication::with('disbursementAdvice','merchant')->whereNull('is_deleted')->whereIn('state',['nach registered','closed','disbursed'])->get();

        $notFound = [];
        $s3 = Storage::disk('s3');
        foreach ($applications as $application) {
            try {
                if ($application->disbursementAdvice) {
                    $lists = explode('/', $application->disbursementAdvice->file_path);
                    $last = isset($lists[count($lists) - 1]) ? $lists[count($lists) - 1] : $application->disbursementAdvice->file_path;
                    $extension = isset(explode('.', $last)[1]) ? explode('.', $last)[1] : '.pdf';
                    $content = $s3->get($application->disbursementAdvice->file_path);
                    if ($res && $content) {
                        $zip->addFromString($application->merchant->merchant_name . '/' . $application->name . '_' . $application->id . '_disbursement_advice.' . $extension, $content);
                    }
                }
            }catch (\Exception $e){
                $d = $e;
                $notFound[] = $application->id;
            }
        }


        if (true) {
            $zip->close();
            return response()->download($zipFileName)->deleteFileAfterSend(true);
        }
    }

    public function trelloToLead(){
        try {
            //$file = Storage::disk('www')->get("1142_response.json");
            $file_path = storage_path('leads/home_decor.json');
            $myfile = fopen($file_path, "r") or die("Unable to open file!");
            $file = fread($myfile, filesize($file_path));
        } catch (\Exception $e) {
            return false;
        }
        $no = [];

        $data = json_decode($file,1);


        $usersData = [
            'Aditya Damani' => 26,
            'Ashwini Sonavane' => 4,
            'Darshan Mehta' => 2020,
            'dhananjay' => 4740,
            'Himanshu Thakker' => 5063,
            'Piyush Bang' => 10,
            'Sunil Khorwal' => 27,
            'Vinesh Philase' => 17544,
            'khushboo' => 13329,
            'rohit' => 519,
            'suraj jagtap' => 14160
        ];

        foreach ($data['cards'] as $card) {
            try {

                $status = '';

                foreach ($data['lists'] as $list) {
                    if ($list['id'] == $card['idList']) {
                        $status = $list['name'];
                        break;
                    }
                }


                if (in_array($status, ['Lead generation','Lead Gen'])) {
                    $status = 1;
                } else if ($status == 'Call/ meeting / follow up') {
                    $status = 2;
                } else if ($status == 'Pricing negotiation') {
                    $status = 3;
                } else if ($status == 'onboarding') {
                    $status = 4;
                } else if ($status == 'agreement signing') {
                    $status = 4;
                } else if ($status == 'Checklist and activation') {
                    $status = 4;
                } else if ($status == 'marketing and training') {
                    $status = 6;
                } else if ($status == 'Pending 1st disbursement') {
                    $status = 9;
                } else if ($status == 'Pending 2nd disbursement') {
                    $status = 9;
                } else if ($status == 'Pending 3rd Disbursement') {
                    $status = 9;
                } else if ($status == 'Successfully Activated') {
                    $status = 9;
                } else if ($status == 'Dead leads') {
                    $status = 8;
                } else if ($status == 'Retargeting') {
                    $status = 7;
                }


                $cardDetails = [];
                $cardDetailsUp = [];
                foreach ($data['actions'] as $action) {
                    $comment_ = isset($action['data']['text']) ? $action['data']['text'] : '';
                    if (isset($action['data']['card']) && $action['data']['card']['id'] == $card['id'] && $comment_) {
                        $comment[] = [
                            'card_id' => $card['id'],
                            'comment' => $comment_,
                            'user_id' => isset($action['memberCreator']['fullName']) ? $usersData[$action['memberCreator']['fullName']] : 107,
                            'date' => isset($action['date']) ? $action['date'] : '',
                        ];
                    }

                    if ($action['type'] == 'createCard') {
                        $cardDetails[$action['data']['card']['id']] = ['date' => $action['date'], 'created_by' => $usersData[$action['memberCreator']['fullName']]];
                    }
                    if ($action['type'] == 'updateCard') {
                        $cardDetailsUp[$action['data']['card']['id']] = ['date' => $action['date'], 'created_by' => $usersData[$action['memberCreator']['fullName']]];
                    }
                }


                $dataItems = [
                    'firm' => $card['name'],
                    'sector_id' => 7,
                    'business' => '',
                    'address' => '',
                    'state_id' => 0,
                    'city' => '',
                    'pincode' => '',
                    'monthly_sales_value' => 0,
                    'monthly_sales_volume' => 0,
                    'description' => $card['desc'],
                    'source' => 'trello',
                    'contacts' => '',
                    'status' => $status,
                    'lead_generated_by' => isset($cardDetails[$card['id']]) ? $cardDetails[$card['id']]['created_by'] : (isset($cardDetailsUp[$card['id']]) ? $cardDetailsUp[$card['id']]['created_by'] : 107),
                    'user_id' => 107,
                    'created_at' => isset($cardDetails[$card['id']]) ? date('Y-m-d', strtotime($cardDetails[$card['id']]['date'])) : (isset($cardDetailsUp[$card['id']]) ? date('Y-m-d', strtotime($cardDetailsUp[$card['id']]['date'])) : Carbon::now()->toDateTimeString()),
                    'action_date' => ''
                ];

                $ld = Leads::where('firm', $card['name'])->first(['id']);

                if (!isset($ld->id)) {
                    $id = Leads::insertGetId($dataItems);



                if (isset($comment)) {
                    foreach ($comment as $item) {
                        $c[] = [
                            'application_id' => $id,
                            'user_id' => $item['user_id'],
                            'comment' => $item['comment'],
                            'type' => 'lead',
                            'show_merchant' => 0,
                            'show_consumer' => 0,
                            'created_at' => Carbon::now()->toDateString(),
                            'updated_at' => Carbon::now()->toDateString(),
                        ];
                    }


                    if (isset($c)) {
                        Comments::insert($c);
                    }

                }
                    $comment = [];
                    $c =[];
                }
            } catch (\Exception $e) {
                $no[] = $item;
            }
        }

        return $no;
    }

    public function updateApplicationIdDetails($event){
        $applications = ConsumerApplication::whereNull('applicant_id')->whereNull('is_deleted')->get();
        foreach ($applications as $application){
            $event->comment($application->id);
            $consumer = new ConsumerApplication();
            $customer = $consumer->saveCustomer($application->toArray());

            $flag = false;
            $updateApplication = ConsumerApplication::find($application->id);
            if (!$updateApplication->applicant_id) {
                $updateApplication->applicant_id = $customer->applicant_id;
                $flag = true;
            }
            if (!$updateApplication->co_applicant_id) {
                $updateApplication->co_applicant_id = $customer->co_applicant_id;
                $flag = true;
            }
            if($flag) {
                $updateApplication->save();
            }
        }
    }

    public function updateLastReportedDate(){
        $reports = CreditReport::get();
        foreach ($reports as $report) {
            try {
                $equifax = new Equifax(new Request(array("application_id" => $report->application_id, "applicant_type" => 1, "request_type" => 'customer')));
                $response = $equifax->parseResponse();
                foreach ($response->response['foir'] as $_item) {
                    $foir = FOIR::where('application_id', $report->application_id)->where('Institution', $_item['Institution'])->where('OwnershipType', $_item['OwnershipType'])->where('ApprovedAmount',$_item['ApprovedAmount'])->where('Balance',$_item['Balance'])->where('InterestRate',$_item['InterestRate'])->first();
                    if(isset($foir->id)){
                        FOIR::where('id', $foir->id)->update(['ReportedDate' => $_item['ReportedDate']]);
                    }
                }
            }catch (\Exception $e){

            }
        }
    }

    public function getDocLegal(){
        $applications = [
            9791,
9670,
7811,
7193,
5850,
4736,
4415,
4137,
4070,
3604,
3405,
3235,
3139,
2801,
2752,
2159,
1671,
1616,
1217,
7391,
6848,
6513,
6429,
6300,
6208,
4879,
4393,
4336,
4331,
4308,
4126,
3481,
3316,
3293,
2518,
2269,
2239,
2236,
2064,
996,
8718,
4668,
3912,
3784,
3778,
3742,
3555,
3255,
3148,
3037,
2613,
2273,
2217,
2059,
2035,
1975,
1942,
1723,
8661,
7774,
7486,
7444,
6078,
5640,
5508,
4848,
4651,
4275,
4169,
4036,
3921,
3914,
3907,
3894,
3884,
3881,
3845,
3786,
3764,
3673,
3654,
3619,
3592,
3541,
3531,
3502,
3403,
3301,
3284,
3223,
3197,
3189,
3180,
3169,
3083,
3073,
3022,
2951,
2940,
2920,
2910,
2819,
2777,
2735,
2612,
2606,
2592,
2430,
2300,
2295,
2212,
2194,
2193,
2160,
2145,
2135,
2067,
2055,
2043,
2018,
2016,
2000,
1940,
1887,
1740,
1689,
1683,
1664,
1495,
1257,
1242,
1146,
1074,
922,
881,
803,
662,
586,
325,
124
        ];

        ini_set('max_execution_time', -1);
        set_time_limit(0);
        ini_set('memory_limit', '-1');

        $zip = new \ZipArchive();
        $zipFileName = 'sanction_' . Carbon::now()->toDateTimeString() . '.zip';
        $res = $zip->open($zipFileName, \ZipArchive::CREATE);

        if($res) {
            foreach ($applications as $application) {
            /*    $file = ConsumerApplicationFiles::with('ConsumerApplication')->where('consumer_application_id', $application)->where('file_type', 'sanction_letter')->orderBy('created_at', 'desc')->first(['file_path','consumer_application_id']);
                if (isset($file->file_path) && $file->file_path) {
                    $d = (new ConsumerApplicationController());
                    $d->isInternal = true;
                    $content = $d->viewFile($application, ['LEGAL',$file->file_path]);
                    if ($content) {
                        $zip->addFile($content, 'Sanction_Letter_' . $file->ConsumerApplication->name . '_' . $application . '_' . '.pdf');
                    }
                }*/

                $frontController = new FrontController();
                $statement = $frontController->getStatement($application, true);
                $_application = ConsumerApplication::where('id', $application)->first(['name']);
                if($statement){
                    $path = time().$application.'.pdf';
                    $file = fopen($path, "w");
                    fwrite($file, $statement->output());
                    fclose($file);

                    $zip->addFile($path, 'Loan Statement_' . $_application . '_' . $application . '_' . '.pdf');
                  }
                }


        }


        $zip->close();
        return response()->download($zipFileName)->deleteFileAfterSend(true);

    }

    public function generateEsignLoanAgreement($id){

        try {
            $vernaculardeclarationarray = array("ENGLISH" => "I have been read out and explained in the language known to me, the contents of the loan documents and all other documents incidental to availing the loan from Pride Financial Services Private Limited and I have signed the said documents after having understood them and by signing the same I do hereby agree to abide by all the general terms and conditions of the loan and the articles of the same.",
                "HINDI" => "मुझे ज्ञात भाषा में पढ़ा गया है और समझाया गया है, ऋण दस्तावेजों की सामग्री और प्राइड फाइनेंशियल सर्विसेज प्राइवेट लिमिटेड से ऋण लेने के लिए आकस्मिक अन्य सभी दस्तावेज और मैंने उन्हें समझने के बाद और हस्ताक्षर करके दस्तावेजों पर हस्ताक्षर किए हैं वैसे ही मैं ऋण के सभी सामान्य नियमों और शर्तों और उसके लेखों का पालन करने के लिए सहमत हूं।",
                "MARATHI" => "प्राइड फायनान्शियल सर्व्हिसेस प्रायव्हेट लिमिटेडकडून कर्जाचा लाभ घेण्यासाठी मला कर्जदारांच्या कागदपत्रांची सामग्री आणि अन्य सर्व कागदपत्रे वाचून दाखवण्यात आले आहे आणि मी त्यांना समजावून घेतल्याबद्दल आणि त्यावर स्वाक्षरी करून त्या कागदपत्रांवर स्वाक्षरी केली आहे. त्याचप्रमाणे मी याद्वारे कर्जाच्या सर्व सामान्य अटी व शर्ती व त्याच नमुन्याचे पालन करण्यास सहमत आहे.",
                "GUJARATI" => "પ્રાઇડ ફાઇનાન્સિયલ સર્વિસીઝ પ્રાઇવેટ લિમિટેડ પાસેથી લોન લેવા માટે લોન દસ્તાવેજોની સામગ્રીઓ અને અન્ય તમામ દસ્તાવેજોને આકસ્મિક રીતે વાંચવામાં અને સમજાવી શકાય છે અને મેં તેમને સમજી લીધેલ હોવાના દસ્તાવેજો પર સહી કરી અને સાઇન ઇન કરીને એ જ રીતે હું લોનના તમામ સામાન્ય નિયમો અને શરતો અને એ જ લેખોના પાલન માટે સહમત છું.",
                "BENGALI" => "আমি প্রাইড ফাইন্যান্সিয়াল সার্ভিসেস প্রাইভেট লিমিটেডের কাছ থেকে ঋণ গ্রহণের জন্য ঋণপত্রের বিষয়বস্তু এবং অন্যান্য সকল দস্তাবেজের সামগ্রী সম্পর্কে জানানো ভাষাতে ব্যাখ্যা করেছি এবং ব্যাখ্যা করেছি এবং আমি তাদের বোঝার পর এবং তাদের স্বাক্ষর করার মাধ্যমে এই ডকুমেন্টগুলি সই করেছি। একইভাবে আমি এখান থেকে ঋণের সমস্ত সাধারণ শর্তাবলী এবং একই সাথে নিবন্ধগুলি মেনে চলতে সম্মত হই।",
                "PUNJABI" => "ਮੈਨੂੰ ਪ੍ਰਿਡ ਫਾਈਨੈਂਸ਼ੀਅਲ ਸਰਵਿਸਿਜ਼ ਪ੍ਰਾਈਵੇਟ ਲਿਮਟਿਡ ਦੇ ਲੋਨ ਲੈਣ ਲਈ ਲੋਨ ਦੇ ਦਸਤਾਵੇਜ਼ਾਂ ਦੀ ਸਮਗਰੀ ਅਤੇ ਹੋਰ ਦਸਤਾਵੇਜ਼ਾਂ ਦੀ ਜਾਣਕਾਰੀ ਪੜ੍ਹ ਕੇ ਸਮਝਾਇਆ ਗਿਆ ਹੈ ਅਤੇ ਮੈਂ ਉਨ੍ਹਾਂ ਨੂੰ ਸਮਝਣ ਤੋਂ ਬਾਅਦ ਦਸਤਖ਼ਤ ਕੀਤੇ ਹਨ ਅਤੇ ਉਨ੍ਹਾਂ ਨੂੰ ਸਮਝਣ ਤੋਂ ਬਾਅਦ ਦਸਤਖ਼ਤ ਕੀਤੇ ਹਨ. ਉਸੇ ਤਰ੍ਹਾਂ ਮੈਂ ਏਦਾਂ ਸਹਿਮਤ ਹਾਂ ਕਿ ਲੋਨ ਦੇ ਸਾਰੇ ਆਮ ਨਿਯਮਾਂ ਅਤੇ ਸ਼ਰਤਾਂ ਅਤੇ ਇਸ ਦੇ ਲੇਖਾਂ ਦੀ ਪਾਲਣਾ ਕਰਨ ਲਈ ਸਹਿਮਤ ਹਾਂ.",
                "TAMIL" => "நான் வாசிக்கப்பட்டு, எனக்குத் தெரிந்த மொழி, கடன் ஆவணங்களின் உள்ளடக்கங்கள் மற்றும் பிரைட் பைனான்சியல் சர்வீசஸ் பிரைவேட் லிமிடில் இருந்து கடன் பெறும் அனைத்து மற்ற ஆவணங்கள் ஆகியவற்றைப் பற்றியும், அவற்றை புரிந்து கொண்டு பின்னர் அந்த ஆவணங்களை கையொப்பமிட்டேன். அதே வேளையில், கடனின் அனைத்து பொது நிபந்தனைகளும் நிபந்தனைகளும் அதனுடன் இணைந்த கட்டுரையுடன் நான் உடன்படுகிறேன்.",
                "TELUGU" => "నేను చదివాను మరియు నాకు తెలిసిన భాషలో, రుణ పత్రాల యొక్క విషయాలు మరియు ప్రైడ్ ఫైనాన్షియల్ సర్వీసెస్ ప్రైవేట్ లిమిటెడ్ నుండి రుణం లభించేలా అన్ని ఇతర పత్రాలు మరియు నేను వాటిని అర్థం చేసుకున్న తర్వాత ఆ సంతకాలు సంతకం చేసి మరియు సంతకం చేయడం ద్వారా అదే విధంగానే నేను రుణం మరియు సాధారణ వ్యాసాల అన్ని సాధారణ నిబంధనలు మరియు షరతులకు కట్టుబడి ఉంటాను.",
                "KANNADA" => "ಪ್ರೈಡ್ ಫೈನಾನ್ಷಿಯಲ್ ಸರ್ವಿಸಸ್ ಪ್ರೈವೇಟ್ ಲಿಮಿಟೆಡ್ನಿಂದ ಸಾಲವನ್ನು ಪಡೆಯಲು ಸಾಂದರ್ಭಿಕ ಸಾಲದ ದಾಖಲೆಗಳು ಮತ್ತು ಎಲ್ಲಾ ಇತರ ದಾಖಲೆಗಳ ವಿಷಯಗಳ ಬಗ್ಗೆ ನನಗೆ ತಿಳಿದಿರುವ ಭಾಷೆಯಲ್ಲಿ ನಾನು ಓದಿದ್ದೇನೆ ಮತ್ತು ವಿವರಿಸಿದ್ದೇನೆ ಮತ್ತು ಅವುಗಳನ್ನು ಅರ್ಥಮಾಡಿಕೊಂಡ ನಂತರ ನಾನು ತಿಳಿಸಿದ ದಾಖಲೆಗಳನ್ನು ಸಹಿ ಹಾಕಿ ಅದೇ ರೀತಿ ನಾನು ಸಾಲದ ಎಲ್ಲಾ ಸಾಮಾನ್ಯ ನಿಯಮಗಳು ಮತ್ತು ಷರತ್ತುಗಳು ಮತ್ತು ಅದರ ಲೇಖನಗಳ ಅನುಸರಣೆಗೆ ಒಪ್ಪುತ್ತೇನೆ.",
                "MALAYALAM" => "ഞാൻ അറിയാവുന്ന ഭാഷയിൽ വായിക്കുകയും വിശദീകരിക്കുകയും ചെയ്തു, വായ്പ രേഖകളുടെ ഉള്ളടക്കം, പ്രൈഡ് ഫിനാൻഷ്യൽ സർവീസസ് പ്രൈവറ്റ് ലിമിറ്റഡിൽ നിന്നുള്ള വായ്പ ലഭിക്കാൻ ഇടയ്ക്കിടെയുള്ള മറ്റ് രേഖകൾ എന്നിവയും അവ മനസ്സിലാക്കി ഞാൻ ഈ പ്രമാണങ്ങളിൽ ഒപ്പിട്ടിട്ടുണ്ട്. ഞാനും അതേ വായ്പയുടെ എല്ലാ പൊതു വ്യവസ്ഥകളും വ്യവസ്ഥകളും ഒരേ വിധത്തിൽ പാലിക്കാൻ സമ്മതിക്കുന്നു.",
                "URDU" => "میں پڑھ کر پڑھ کر زبان میں بیان کرتا ہوں، قرض دستاویزات اور دیگر تمام دستاویزات جو فڈ فائنل سروسز نجی لمیٹڈ سے قرض حاصل کرنے کے لۓ واقع ہیں، اور میں نے ان دستاویزات پر دستخط کئے اور ان پر دستخط کرکے دستخط کئے ہیں. اسی طرح میں اس کے ساتھ قرض کے تمام عام شرائط و ضوابط اور اس کے مضامین کی طرف سے رہنا پر اتفاق کرتا ہوں.",
                "ODIA" => "ମୋତେ ଜଣାଥିବା ଭାଷାରେ, K ଣ ଦଲିଲର ବିଷୟବସ୍ତୁ ଏବଂ କେଏମ ଗ୍ଲୋବାଲ କ୍ରେଡିଟ ପ୍ରାଇଭେଟ ଲିମିଟେଡରୁ loan ଣ ପାଇବା ପାଇଁ ଘଟୁଥିବା ଅନ୍ୟ ସମସ୍ତ ଦଲିଲରେ ମୋତେ ପ read ଼ାଯାଇଛି ଏବଂ ବ୍ୟାଖ୍ୟା କରାଯାଇଛି ଏବଂ ମୁଁ ସେଗୁଡ଼ିକୁ ବୁ understood ିବା ପରେ ଏବଂ ଦସ୍ତଖତ କରି ଦସ୍ତଖତ କରିଛି | ସମାନ ଭାବରେ ମୁଁ loan ଣର ସମସ୍ତ ସାଧାରଣ ସର୍ତ୍ତାବଳୀ ଏବଂ ସମାନ ଆର୍ଟିକିଲ୍ ମାନିବାକୁ ରାଜି ଅଟେ |"
            );

            $aggrementgenerate = 0;

            $applicant_count = 0;
            $consumer_details = ConsumerApplication::where('id', $id)->first();
            $applicant_name = $consumer_details['name'];
            $co_applicant_name = $consumer_details['co_applicant_name'];
            if ($applicant_name != "") {
                $applicant_count = $applicant_count + 1;
            }
            if ($co_applicant_name != "") {
                $applicant_count = $applicant_count + 1;
            }
            $signed_data = DigitalSignDetails::where('application_id', $id)->where('type', 'consumer')->orderBy('applicant', 'asc')->get();
            if (count($signed_data) == $applicant_count) {

                $signed_data = $this->updateSignedData($vernaculardeclarationarray, $signed_data, $id);


                $type = "Loan Agreement Esign";
                $request = new Request(['test_bot' => true]);
                $request->attributes->add(['type' => $type]);
                $consumerDocument = new ConsumerDocument($request);
                $viewParameter = ($consumerDocument->getDocument($id));
                (new FrontController())->downloadDocument($id, $viewParameter, $signed_data, 1);
                return true;
            }
        } catch (\Exception $e) {
            (new Slack(new Request(['title' => 'Loan Agreement Script Error', 'fields' => ['error' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString(), 'application_id' => $id, 'id_type' => 'application_id']])))->send();
        }
    }

    public function updateSignedData($vernaculardeclarationarray, $signed_data, $app_id) {
        $geolocation = UserGeolocation::where('_id', $app_id)->where('id_type', 'application_id')->orderBy('applicant_type', 'asc')->get();
        if (isset($signed_data[0]['applicant'])) {
            if (isset($signed_data[0]['isagreementsigned']) && $signed_data[0]['isagreementsigned'] == 1) {
                $aggrementgenerate = 1;
            }
            $signed_data[0]['consent'] = $vernaculardeclarationarray[$signed_data[0]['language']];
            if (isset($geolocation[0])) {
                $signed_data[0]['latitude'] = $geolocation[0]->latitude;
                $signed_data[0]['longitude'] = $geolocation[0]->longitude;
            }
        }
        if (isset($signed_data[1]['applicant'])) {
            if (isset($signed_data[1]['isagreementsigned']) && $signed_data[1]['isagreementsigned'] == 1) {
                $aggrementgenerate = 1;
            }
            $signed_data[1]['consent'] = $vernaculardeclarationarray[$signed_data[1]['language']];
            if (isset($geolocation[1])) {
                $signed_data[1]['latitude'] = $geolocation[1]->latitude;
                $signed_data[1]['longitude'] = $geolocation[1]->longitude;
            }
        }
        return $signed_data;
    }

    public function lotuspayTransactionIdsUpdate(){
        Excel::import(new TestImport(new Request(['from' => __FUNCTION__])), storage_path().'/lotuspay_tr_update.xlsx');
    }

    public function getFinbitDocumentsExcel(){
        ini_set('max_execution_time', -1);
        set_time_limit(0);
        ini_set('memory_limit', '-1');

        $error = [];

        $applications = ConsumerApplicationFiles::where('created_at','>=','2021-04-21 11:21:03')->get(['consumer_application_id']);


        $v = [];
        foreach ($applications as $application){
            $v[] = $application->consumer_application_id;
        }

        $files = ConsumerApplicationFiles::where(DB::raw('LENGTH(accountUID)'),'>','3')->whereNotIn('consumer_application_id', $v)->get(['accountUID','bank_name','consumer_application_id']);
        $request = new Request(['id']);
        $finbit = new FinBit($request);
        $p = [];
        foreach ($files as $file){
            try {
                $accountUID = str_replace('"', '', $file->accountUID);
                if(!in_array($file->accountUID, $p)) {
                    $finbit->response = new \stdClass();
                    $finbit->response->accountUID = $accountUID;
                    $finbit->getExcel(new Request(['bank_name' => $file->bank_name, 'id' => $file->consumer_application_id]));
                    $finbit->getFraudReport();
                    $p[] = $accountUID;
                }
            }catch (\Exception $e){
                $error[] = $file->consumer_application_id;
            }
        }

        return $error;
    }

    public function reUploadInvoice(){

        ini_set('max_execution_time', -1);
        set_time_limit(0);
        ini_set('memory_limit', '-1');


        $collection = Excel::toCollection(new TestImport(new Request(['from' => __FUNCTION__])), storage_path().'/gst_invoice_surbhi.xlsx');

        $collection = $collection[0];
        unset($collection[0]);
        $applications = [];
        $d  = 0;
        foreach ($collection as $statusLog){
            try {
                $application_id = $statusLog[0];
                if (!in_array($application_id, $applications)) {
                    $applications[] = $application_id;


                    $invoice_number = $statusLog[2];
                    $total_subvention = $statusLog[5];
                    $igst = $statusLog[6] ? $statusLog[6] : 0;
                    $cgst = $statusLog[7] ? $statusLog[7] : 0;
                    $sgst = $statusLog[8] ? $statusLog[8] : 0;
                    $net_amount = $statusLog[9];
                    $invoice_date = $statusLog[10];


                    $application = ConsumerApplication::with('application_element','proFormaInvoice','lender')->where('id', $application_id)->first(['id', 'name', 'merchant_id', 'lender_id']);

                    /*$request = new Request();
                    $request->request->add([
                        'type' => 'Welcome Letter',
                        'bot' => true
                    ]);
                    $document = (new ConsumerDocument($request));
                    $processing_fee_invoice_attributes = $document->getDocument($statusLog->application_id);

                    $pdf = App::make('snappy.pdf.wrapper');
                    $path = $pdf->loadView('admin.documents.processing_fee_invoice', $processing_fee_invoice_attributes)->setOption('encoding', 'UTF-8')->setPaper('a4')->setOrientation('portrait');

                    $document->uploadToS3('Processing Fee Invoice', $statusLog->application_id, $path->output());*/

                    $request = new Request();
                    $request->request->add([
                        'type' => 'Merchant Disbursed',
                        'bot' => true,
                    ]);
                    $document = (new ConsumerDocument($request));
                    /*$documentDetails = $document->getDocument($application_id);*/
                    if(1) {


                        $center_name = isset($application->application_element->merchant_center->name) ? $application->application_element->merchant_center->name : '';
                        $center_address = isset($application->application_element->merchant_center->location) ? $application->application_element->merchant_center->location : '';
                        $center_gst_number = isset($application->application_element->merchant_center->gst_number) ? $application->application_element->merchant_center->gst_number : '';

                        $merchant_gst_number = isset($application->proFormaInvoice->gst_number) ? $application->proFormaInvoice->gst_number : '';
                        $official_merchant_name = (isset($application->merchant->merchant_name) ? $application->merchant->merchant_name : '');
                        $merchant_address = isset($application->merchant->address) ? ucwords(strtolower($application->merchant->address)) : '';

                        $documentDetails = [
                            'invoice_number' => $invoice_number,
                            'total_subvention' => $total_subvention,
                            'invoice_date' => $invoice_date,
                            'net_amount' => $net_amount,
                            'loan_application_no' => $application->proFormaInvoice->loan_application_no,
                            'customer_name' => $application->name,
                            'lender' => $application->lender,
                            'user' => [
                                'center_gst_number' => $center_gst_number,
                                'center_name' => $center_name,
                                'center_address' => $center_address,
                                'official_merchant_name' => $official_merchant_name,
                                'merchant_address' => $merchant_address,
                                'merchant_gst_number' => $merchant_gst_number,
                                'getGSTDetailsSubvention' => [
                                    ['taxes' => 18, 'tax_type' => 'IGST', 'gst_amount' => $igst],
                                    ['taxes' => 9, 'tax_type' => 'CGST', 'gst_amount' => $cgst],
                                    ['taxes' => 9, 'tax_type' => 'SGST', 'gst_amount' => $sgst],
                                ],
                            ]
                        ];

                        $data = [
                            'txt' => view('admin.documents.subvention_fee_invoice', $documentDetails)
                        ];

                        $request->request->add($data);
                        (new ConsumerApplicationController())->uploadToS3($document, $request, $application_id);
                    }

                }
            }catch (\Exception $e){
                if($d == 0){
                    (new Slack(new Request(['title' => 'Update Invoice E', 'fields' => ['total' => count($applications), 'e' => $e->getMessage(),'l' => $e->getLine(), 'f' => $e->getFile()], 'group' => Slack::$STAGE_TESTING])))->send();
                }
                $d = 1;
            }
        }

        (new Slack(new Request(['title' => 'Update Invoice', 'fields' => ['total' => count($applications)], 'group' => Slack::$STAGE_TESTING])))->send();
    }

    public function getImranPaymentData(){

        ini_set('max_execution_time', -1);
        set_time_limit(0);
        ini_set('memory_limit', '-1');

        $query = "select consumer_application.id, consumer_application.name as customer_name ,email,	mobile_number, gender,	emi_calculation.tenure,	merchant_category.name as _purpose,	loan_amount,	lender_id,	approved_amount,	src_merchant_name,	pan_card,	aadhaar_card,	dob,	marital_status,	current_address_line_1,	current_address_state,	current_address_city,	current_address_pincode,	alt_contact_number,	employee_status	, monthly_income,	company.company as _company_name, company_name,	company_number,	experience,	contact_address,	co_applicant_name,	co_applicant_relationship,	co_applicant_dob,	co_applicant_gender,	co_applicant_pan_card, co_applicant_aadhaar_card,	co_applicant_email,	co_applicant_mobile_number,	co_applicant_address_line_1,	co_applicant_address_state,	co_applicant_address_pincode,	co_applicant_address_city,	co_applicant_address_landmark,	co_applicant_required,	state,	consumer_application.created_at as login_date,	(select created_at from status_logs where applicant_id = consumer_application.id and status = 'closed' order by created_at desc limit 1) as closed_date,	emi_calculation.emi_date as first_emi_date,	(select emi_date from emi_payments where emi_payments.application_id = consumer_application.id order by emi_date desc limit 1) as last_emi_date,	(select payment_date from payment_transactions where payment_transactions.application_id = consumer_application.id order by payment_date desc limit 1) as last_payment_date,	principal_outstanding.principal_outstanding,	if(moratorium.id > 1, 'Yes', 'No') as moratorium_avail,	(select count(moratorium.id) from moratorium where moratorium.application_id = consumer_application.id and moratorium.stopped_date is null) as number_of_moratorium_avail
from consumer_application
       left join emi_calculation on emi_calculation.application_id = consumer_application.id
       left join principal_outstanding on principal_outstanding.application_id = consumer_application.id
       left join moratorium on moratorium.application_id = consumer_application.id
       left join company on company.id = consumer_application.company_name
       left join merchant_category on merchant_category.id = consumer_application.purpose
where consumer_application.state in ('disbursed','nach registered','closed') and consumer_application.is_deleted is null and emi_calculation.emi_date <= '2020-02-29 23:59:59'";

        $data = DB::select($query);


        (new Slack(new Request(['title' => 'Payment data populated', 'fields' => ['total' => count($data)], 'group' => Slack::$STAGE_TESTING])))->send();
        //$response = [];
        $applications = [];
        $i = 0;
        $c = 0;
        foreach ($data as $keyItem => $item){

            try {
                if (!in_array($item->id, $applications)) {
                    $applications[] = $item->id;

                    $response[$keyItem] = (array)$item;
                    $response[$keyItem]['mobile_number'] = wall_decrypt($item->mobile_number);
                    $response[$keyItem]['pan_card'] = wall_decrypt($item->pan_card);
                    $response[$keyItem]['co_applicant_mobile_number'] = wall_decrypt($item->co_applicant_mobile_number);
                    $response[$keyItem]['co_applicant_aadhaar_card'] = wall_decrypt($item->co_applicant_aadhaar_card);
                    $response[$keyItem]['aadhaar_card'] = wall_decrypt($item->aadhaar_card);
                    $response[$keyItem]['co_applicant_pan_card'] = wall_decrypt($item->co_applicant_pan_card);
                    $response[$keyItem]['company_number'] = wall_decrypt($item->company_number);
                    $response[$keyItem]['alt_contact_number'] = wall_decrypt($item->alt_contact_number);
                    $response[$keyItem]['company_name'] = $item->_company_name ? $item->_company_name : $item->company_name;
                    unset($response[$keyItem]['_company_name']);
                    $schedules = (new AccountingController())->viewloanschedule($item->id, 1, 1);
                    if(isset($schedules['schedule']) && $schedules['schedule']) {
                        foreach ($schedules['schedule'] as $key => $schedule) {
                            try {
                                if (date('Y-m', strtotime($schedule['emi_date'])) == date('Y-m', strtotime('2020-02-29 23:59:59'))) {
                                    $response[$keyItem]['principal_outstanding'] = round($schedule['principal_outstanding'], 2);
                                    break;
                                }
                            } catch (\Exception $e) {
                                if (!$c) {
                                    (new Slack(new Request(['title' => 'Payment Data Error 1', 'fields' => ['message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()], 'group' => Slack::$STAGE_TESTING])))->send();
                                    $c = 1;
                                }
                            }
                        }
                    }
                }
            }catch (\Exception $e){
                if(!$i) {
                    (new Slack(new Request(['title' => 'Payment Data Error 2', 'fields' => ['message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()], 'group' => Slack::$STAGE_TESTING])))->send();
                    $i = 1;
                }
            }
        }

        $file = time().'_'.Carbon::now()->toDateTimeString().'payment_data_imran_today.xlsx';

        $requestData = new Request(['data' => $response, 'sheet' => 'Sheet1']);
        Excel::store((new Exporter($requestData)), $file);

        (new Slack(new Request(['title' => 'Payment file stored', 'fields' => ['total' => count($data)], 'group' => Slack::$STAGE_TESTING])))->send();
    }

    public function getAdityaData(){


        $applications = ConsumerApplication::whereIn('state',['disbursed','nach registered','closed'])->whereNull('is_deleted')->groupBy('id')->get(['id','merchant_id']);
        $i = 0;
        (new Slack(new Request(['title' => 'Payment data populated', 'fields' => ['total' => count($applications)], 'group' => Slack::$STAGE_TESTING])))->send();
        foreach ($applications as $application) {

            try {
                $emi = ApplicationEMICalculation::where('application_id', $application->id)->first();

                $frequency = $emi ? $emi->payment_frequency : 0;
                $payment_frequency_offer = [1 => 12, 2 => 24, 3 => 52, 4 => 365, 5 => 4, 6 => 2, 7 => 1];
                $frequecy_multiplier = ($frequency > 0) ? $payment_frequency_offer[$frequency] : 12;

                $accountingController = new AccountingController();
                $schedule = $accountingController->viewloanschedule($application->id, 1);

                $merchant = Merchant::where('id', $application->merchant_id)->first(['is_gst']);
                $is_gst = isset($merchant->is_gst) ? $merchant->is_gst : 0;

                if (isset($schedule['schedule'][0])) {
                    $repayable = $emi->upfront_from_customer;
                    $principal_amount = 0;
                    $subvention = 0;
                    $total_interest = 0;
                    foreach ($schedule['schedule'] as $key => $loan_schedule) {
                        $repayable = $repayable + $loan_schedule['amount'];
                        $principal_amount = $principal_amount + $loan_schedule['principal'];
                        $subvention = $subvention + $loan_schedule['subvention'];
                        $total_interest = $total_interest + ($loan_schedule['subvention'] + $loan_schedule['interest']);
                        if ($is_gst == 0 && $subvention > 0) {
                            $principal = ($principal_amount + $emi->upfront_from_customer) - $subvention;
                        } else {
                            $principal = $principal_amount + $emi->upfront_from_customer;
                        }
                    }
                }

                //$interest_rate = ($total_interest) / ($principal_amount + $emi->upfront_from_customer);
                $annualized_interest_rate = round(((($repayable - $principal) / $principal) * ($frequecy_multiplier / $emi->remaining_emi)) * 100, 2);

                $reducing_balance_rate = $schedule['summary']['annualised_irr'];
                $flat_rate = $annualized_interest_rate;



                DB::table('irr')->insert(['application_id' => $application->id, 'flat_rate' => $flat_rate, 'reducing_balance_rate' => $reducing_balance_rate, 'created_at' => Carbon::now()->toDateTimeString()]);


            }catch (\Exception $e){
                if(!$i) {
                    (new Slack(new Request(['title' => 'Payment Data Error 1', 'fields' => ['message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()], 'group' => Slack::$STAGE_TESTING])))->send();
                    $i = 1;
                }
            }
        }

        (new Slack(new Request(['title' => 'Payment data stored', 'fields' => ['error' => $i], 'group' => Slack::$STAGE_TESTING])))->send();
    }

    public function MultiStageIRRFixation(){

        ini_set('max_execution_time', -1);
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        /*$disbursementOffersData = DisbursementOffersData::get();
        $ids = [];
        foreach ($disbursementOffersData as $disbursementOffersItem){
            if (!in_array($disbursementOffersItem->offer_id, $ids)) {
                $ids[] = $disbursementOffersItem->offer_id;
            }
        }*/
        $applications = ConsumerApplication::with('DisbursementOffersData','emi','emi_payment')->where('id', 5099)->whereNull('is_deleted')->get();

        $payment_frequency_offer = [1 => 12, 2 => 24, 3 => 52, 4 => 365, 5 => 4, 6 => 2, 7 => 1];

        foreach ($applications as $application){

            try {
                $gross_exposure = [];

                if ($application->DisbursementOffersData && $application->emi) {

                    $frequecy_multiplier = isset($application->emi) ? $payment_frequency_offer[$application->emi->payment_frequency] : 12;

                    $emis = [];
                    foreach ($application->emi_payment as $emi_payments) {
                        $emiAmount = $emi_payments->emi_amount;
                        if ($emi_payments->moratorium_amount) {
                            $emiAmount -= $emi_payments->moratorium_amount;
                        }
                        $emis[] = $emiAmount;
                    }

                    foreach ($application->DisbursementOffersData as $emiIndex => $item) {
                        $percentageAmount = ($item->per_disbursement_amount * $application->approved_amount) / 100;
                        $outflows_from_credit_fair = -(($percentageAmount) - (($percentageAmount) * $application->emi->subvention) / 100);
                        if ($item->phase == 1 && $application->emi->upfront_from_customer) {
                            $outflows_from_credit_fair += $application->emi->upfront_from_customer + $application->emi->processing_fee;
                        } else {
                            $outflows_from_credit_fair += $emis[$emiIndex];
                        }

                        array_push($gross_exposure, $outflows_from_credit_fair);
                    }

                    foreach ($emis as $key => $emi) {
                        if ($key < $emiIndex)
                            continue;
                        array_push($gross_exposure, $emis[$emiIndex]);
                    }


                    if ($gross_exposure) {
                        $irr_rate = (Finance::irr($gross_exposure)) * 100;
                        if ($irr_rate < 0) {
                            $irr_rate = 0;
                        }

                        $annualised_irr = round((pow((($irr_rate/100) + 1), $frequecy_multiplier) - 1) * 100, 2);

                        ApplicationEMICalculation::where('id', $application->emi->id)
                            ->update(['irr_rate' => $irr_rate, 'annualised_irr' => $annualised_irr]);
                    }
                } else {
                    $c[] = $application->id;
                }
            }catch (\Exception $e){
                $d[] = $application->id;
            }
        }

        return 4;
    }

    public function imranPaymentData(){
        $data = DB::select("select id from consumer_application where consumer_application.merchant_id = 90 and consumer_application.state in ('disbursed','nach registered') and consumer_application.is_deleted is null");
        $ids = [];
        foreach ($data as $item) {
            $ids[] = $item->id;
        }

        $data1 = DB::select("SELECT application_id, MAX(p2.payment_date) as payment_date FROM payment_transactions p2 WHERE p2.application_id in (".implode(',',$ids).") group by application_id");
        $ids = [];
        foreach ($data1 as $item) {
            $ids[$item->application_id] = $item->payment_date;
        }

        $response = [];
        foreach ($ids as $id => $date) {
            $dd = DB::select("SELECT p1.* FROM payment_transactions p1 WHERE p1.payment_date = '$date' and application_id = '$id'");
            foreach ($dd as $p => $cc) {
                if (!$p){
                    $response[] = array_keys((array)$cc);
                }
                $response[] = (array)$cc;
            }
        }

        $request = new Request(['data' => $response, 'sheet' => 'Sheet1']);
        $file = time() . 'imran_data_28' . '.xlsx';

        Excel::store((new Exporter($request)), $file);
        return $data;
    }

    public function abortApps(){

        $date = Carbon::now()->toDateTimeString();

        $users = [35238,
            35367,
            35389,
            35415,
            35518,
            35568,
            35576,
            35581,
            35586,
            35660,
            35683,
            35686,
            35689,
            35690,
            35700,
            35701,
            35704,
            35706,
            35719,
            35721,
            35724,
            35725,
            35780,
            35782,
            35783,
            35789,
            35796,
            35801,
            35802,
            35808,
            35810,
            35811,
            35821,
            35824,
            35839,
            35887,
            35889,
            35891,
            35897,
            35901,
            35905,
            35909,
            35911,
            35912,
            35920,
            35930,
            35940,
            35943,
            35944,
            35945,
            35951,
            35956,
            35958,
            35972,
            35978,
            35979,
            36001,
            36011,
            36017,
            36023,
            36035,
            36039,
            36040,
            36044,
            36045,
            36046,
            36058,
            36060,
            36070,
            36072,
            36086,
            36096,
            36098,
            36099,
            36105,
            36107,
            36108,
            36110,
            36122,
            36127,
            36128,
            36142,
            36143,
            36144,
            36151,
            36153,
            36169,
            36170,
            36173,
            36176,
            36181,
            36185,
            36189,
            36190,
            36193,
            36195,
            36198,
            36203,
            36205,
            36211,
            36217,
            36221,
            36222,
            36229,
            36230,
            36232,
            36233,
            36240,
            36243,
            36245,
            36248,
            36249,
            36251,
            36253,
            36255,
            36257,
            36258,
            36259,
            36262,
            36264,
            36266,
            36267,
            36268,
            36273,
            36276,
            36278,
            36283,
            36287,
            36291,
            36293,
            36295,
            36296,
            36299,
            36300,
            36303,
            36304,
            36306,
            36308,
            36311,
            36314,
            36319,
            36323,
            36324,
            36325,
            36326,
            36327,
            36330,
            36331,
            36333,
            36334,
            36337,
            36340,
            36346,
            36347,
            36349,
            36358,
            36366,
            36367,
            36371,
            36373,
            36374,
            36377,
            36379,
            36382,
            36384,
            36387,
            36388,
            36389,
            36391,
            36396,
            36399,
            36405,
            36407,
            36408,
            36410,
            36412,
            36422,
            36424,
            36425,
            36430,
            36435,
            36437,
            36438,
            36439,
            36441,
            36443,
            36444,
            36450,
            36457,
            36458,
            36459,
            36463,
            36465,
            36467,
            36474,
            36476,
            36487,
            36488,
            36492,
            36495,
            36496,
            36508,
            36509,
            36514,
            36515,
            36519,
            36522,
            36523,
            36531,
            36532,
            36536,
            36537,
            36542,
            36543,
            36549,
            36552,
            36553,
            36557,
            36560,
            36566,
            36567,
            36569,
            36570,
            36574,
            36575,
            36580,
            36583,
            36584,
            36588,
            36589,
            36592,
            36593,
            36594,
            36597,
            36600,
            36601,
            36602,
            36603,
            36605,
            36606,
            36612,
            36616,
            36620,
            36625,
            36631,
            36636,
            36638,
            36639,
            36641,
            36643,
            36653,
            36654,
            36661,
            36662,
            36664,
            36666,
            36670,
            36672,
            36680,
            36681,
            36682,
            36687,
            36691,
            36693,
            36700,
            36714,
            36725,
            36732,
            36740,
            36750,
            36758,
            36766,
            36777,
            36790,
            36813,
            36824,
            36837,
            36846,
            36847,
            36848,
            36850,
            36851,
            36852,
            36853,
            36856,
            36857,
            36858,
            36860,
            36861,
            36864,
            36865,
            36868,
            36872,
            36877,
            36900,
            36924,
            36925,
            36927,
            36928,
            36929,
            36931,
            36932,
            36935,
            36937,
            36939,
            36941,
            36948,
            36951,
            36952,
            36953,
            36959,
            36961,
            36963,
            36965,
            36970,
            36971,
            36974,
            36975,
            36978,
            36979,
            36983,
            36984,
            36985,
            36986,
            36989,
            36990,
            36994,
            36995,
            36997,
            36998,
            36999,
            37001,
            37002,
            37004,
            37008,
            37009,
            37014,
            37015,
            37021,
            37022,
            37024,
            37026,
            37028,
            37030,
            37032,
            37033,
            37036,
            37038,
            37039,
            37040,
            37045,
            37048,
            37049,
            37050,
            37052,
            37055,
            37056,
            37058,
            37059,
            37062,
            37065,
            37083,
            37085,
            37087,
            37090,
            37093,
            37095,
            37096,
            37099,
            37100,
            37101,
            37103,
            37109,
            37127,
            37133,
            37138,
            37178,
            37179,
            37181,
            37186,
            37188,
            37191,
            37192,
            37193,
            37195,
            37197,
            37198,
            37203,
            37204,
            37212,
            37219,
            37226,
            37228,
            37234,
            37235,
            37238,
            37240,
            37242,
            37243,
            37244,
            37246,
            37247,
            37249,
            37250,
            37251,
            37253,
            37255,
            37256,
            37258,
            37260,
            37261,
            37262,
            37265,
            37267,
            37268,
            37270,
            37271,
            37272,
            37273,
            37275,
            37276,
            37277,
            37279,
            37280,
            37281,
            37283,
            37285,
            37286,
            37289,
            37290,
            37291,
            37292,
            37294,
            37296,
            37314,
            37315,
            37318,
            37323,
            37324,
            37325,
            37326,
            37327,
            37329,
            37331,
            37333,
            37338,
            37341,
            37342,
            37343,
            37344,
            37346,
            37347,
            37351,
            37354,
            37355,
            37356,
            37357,
            37358,
            37359,
            37360,
            37361,
            37362,
            37363,
            37365,
            37366,
            37370,
            37373,
            37375,
            37376,
            37377,
            37384,
            37387,
            37393,
            37394,
            37397,
            37400,
            37402,
            37405,
            37410,
            37420,
            37421,
            37423,
            37424,
            37426,
            37429,
            37430,
            37431,
            37432,
            37434,
            37435,
            37440,
            37441,
            37443,
            37444,
            37445,
            37446,
            37447,
            37451,
            37452,
            37454,
            37455,
            37457,
            37458,
            37460,
            37461,
            37463,
            37464,
            37465,
            37466,
            37467,
            37468,
            37469,
            37470,
            37471,
            37472,
            37473,
            37474,
            37475,
            37479,
            37480,
            37481,
            37482,
            37484,
            37496,
            37498,
            37507,
            37510,
            37512,
            37534,
            37541,
            37546,
            37548,
            37549,
            37550,
            37551,
            37552,
            37555,
            37560,
            37566,
            37568,
            37571,
            37577,
            37578,
            37579,
            37580,
            37583,
            37585,
            37589,
            37594,
            37595,
            37597,
            37599,
            37614,
            37619,
            37623,
            37632,
            37633,
            37638,
            37639,
            37641,
            37646,
            37648,
            37649,
            37650,
            37652,
            37655,
            37665,
            37667,
            37670,
            37673,
            37681,
            37689,
            37690,
            37692,
            37694,
            37695,
            37696,
            37697,
            37700,
            37701,
            37702,
            37704,
            37707,
            37708,
            37710,
            37711,
            37713,
            37714,
            37715,
            37716,
            37717,
            37719,
            37720,
            37721,
            37722,
            37724,
            37725,
            37726,
            37727,
            37728,
            37729,
            37730,
            37731,
            37732,
            37733,
            37734,
            37735,
            37736,
            37737,
            37738,
            37739,
            37742,
            37749,
            37750,
            37752,
            37781,
            37783,
            37786,
            37790,
            37791,
            37792,
            37795,
            37796,
            37799,
            37801,
            37802,
            37803,
            37804,
            37806,
            37807,
            37808,
            37809,
            37810,
            37813,
            37814,
            37815,
            37816,
            37819,
            37820,
            37821,
            37823,
            37829,
            37830,
            37831,
            37833,
            37834,
            37835,
            37836,
            37837,
            37838,
            37839,
            37840,
            37841,
            37843,
            37844,
            37845,
            37846,
            37848,
            37850,
            37854,
            37857,
            37858,
            37860,
            37862,
            37863,
            37864,
            37865,
            37867,
            37871,
            37876,
            37877,
            37878,
            37879,
            37880,
            37881,
            37883,
            37886,
            37887,
            37888,
            37889,
            37891,
            37892,
            37895,
            37896,
            37897,
            37900,
            37903,
            37905,
            37906,
            37907,
            37908,
            37909,
            37911,
            37912,
            37915,
            37916,
            37918,
            37919,
            37920,
            37922,
            37924,
            37925,
            37926,
            37928,
            37929,
            37931,
            37932,
            37934,
            37935,
            37936,
            37939,
            37941,
            37944,
            37945,
            37946,
            37947,
            37948,
            37949,
            37950,
            37952,
            37953,
            37956,
            37957,
            37958,
            37960,
            37962,
            37963,
            37965,
            37969,
            37970,
            37972,
            37973,
            37974,
            37975,
            37977,
            37978,
            37979,
            37981,
            37982,
            37983,
            37985,
            37986,
            37988,
            37989,
            37990,
            37991,
            37992,
            37994,
            37995,
            37996,
            37997,
            37998,
            37999,
            38000,
            38001,
            38002,
            38003,
            38005,
            38008,
            38009,
            38011,
            38012,
            38013,
            38014,
            38015,
            38016,
            38019,
            38020,
            38021,
            38023,
            38028,
            38029,
            38032,
            38035,
            38042,
            38043,
            38044,
            38046,
            38048,
            38053,
            38059,
            38060,
            38064,
            38065,
            38071,
            38073,
            38074,
            38075,
            38076,
            38082,
            38083,
            38090,
            38093,
            38103,
            38112,
            38116,
            38123,
            38124,
            38130,
            38132,
            38133,
            38139,
            38140,
            38142,
            38146,
            38149,
            38169,
            38172,
            38174,
            38180,
            38188,
            38189,
            38198,
            38201,
            38206,
            38209,
            38216,
            38217,
            38219,
            38221,
            38222,
            38226,
            38228,
            38229,
            38232,
            38234,
            38238,
            38239,
            38242,
            38243,
            38245,
            38247,
            38260,
            38263,
            38265,
            38271,
            38273,
            38276,
            38277,
            38279,
            38280,
            38284,
            38286,
            38289,
            38294,
            38298,
            38306,
            38307,
            38308,
            38309,
            38310,
            38311,
            38312,
            38313,
            38314,
            38315,
            38316,
            38317,
            38319,
            38320,
            38322,
            38323,
            38324,
            38326];


        $applications = [];
        foreach ($users as $user) {
            $applications[] = ['application_id' => $user, 'status' => 'aborted', 'user_id' => 107, 'reason' => "This case was auto-aborted because we haven\'t heard from the customer", 'created_at' => $date];
        }

        StatusLogs::insert($applications);

    }

    public function NetDisbursementIRRFixation(){

        ini_set('max_execution_time', -1);
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $merchants = Merchant::where('charge_subvention_remaining_amount', 1)->get();
        $ids = [];
        foreach ($merchants as $merchant){
            if (!in_array($merchant->id, $ids)) {
                $ids[] = $merchant->id;
            }
        }
        $applications = ConsumerApplication::with('emi','emi_payment')->whereIn('merchant_id', $ids)->whereIn('state',['disbursed','nach registered','closed'])->whereNull('is_deleted')->get();

        $payment_frequency_offer = [1 => 12, 2 => 24, 3 => 52, 4 => 365, 5 => 4, 6 => 2, 7 => 1];

        foreach ($applications as $application){

            try {
                $gross_exposure = [];

                if ($application->emi) {

                    $frequecy_multiplier = isset($application->emi) ? $payment_frequency_offer[$application->emi->payment_frequency] : 12;

                    $emis = [];
                    foreach ($application->emi_payment as $emi_payments) {
                        $emiAmount = $emi_payments->emi_amount;
                        if ($emi_payments->moratorium_amount) {
                            $emiAmount -= $emi_payments->moratorium_amount;
                        }
                        $emis[] = $emiAmount;
                    }

                    $outflows_from_credit_fair = -($application->approved_amount - ((($application->approved_amount- $application->emi->upfront_from_customer)*$application->emi->subvention)) / 100);

                    array_push($gross_exposure, ($outflows_from_credit_fair + $emis[0]));

                    foreach ($emis as $key => $emi) {
                        if (!$key)
                            continue;
                        array_push($gross_exposure, $emi);
                    }


                    if ($gross_exposure) {
                        $irr_rate = (Finance::irr($gross_exposure)) * 100;
                        if ($irr_rate < 0) {
                            $irr_rate = 0;
                        }

                        //$annualised_interest = round((((($rate+1)*$frequecy_multiplier)-$frequecy_multiplier)*100)/100, 2);
                        $annualised_irr = round((((($irr_rate + 1) * $frequecy_multiplier) - $frequecy_multiplier) * 100) / 100, 2);
                        ApplicationEMICalculation::where('id', $application->emi->id)
                            ->update(['irr_rate' => $irr_rate, 'annualised_irr' => $annualised_irr]);
                    }
                } else {
                    $c[] = $application->id;
                }
            }catch (\Exception $e){
                $d[] = $application->id;
            }
        }

        return 4;
    }

    public function uploadExGratia(){

        ini_set('max_execution_time', -1);
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        return Excel::import(new TestImport(new Request(['from' => __FUNCTION__])), storage_path().'/gratia.xlsx');
    }

    public function tallyRepaymentUpload(){

        ini_set('max_execution_time', -1);
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        return Excel::import(new TestImport(new Request(['from' => __FUNCTION__])), storage_path().'/surbhi/razorpay/oct-2020/20-10-2020-razorpay.xlsx');
    }

    public function tallyImportData(){
        ini_set('max_execution_time', -1);
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        return Excel::import(new TestImport(new Request(['from' => __FUNCTION__])), storage_path().'/tally/2019/apr/ACH-DR-HDFC-HDFCA22955-08042019-000749-RES.xlsx');
    }

    public function generateCustomerDocuments($type){
        switch ($type){
            case 'SanctionLetter':
                $this->sendSanctionLetter();
                break;
            case 'WelcomeLetter':
                $this->sendWelcomeLetter();
                break;
        }
    }

    public function removeUploadedZokoDocuments(){
        $directory = "/Users/sunilkhorwal/Sites/zoko_backup/ceb767af-f50f-48db-a560-fc448c62b50b_2 copy/";
        $files2 = scandir($directory, 1);
        $deleted = 0;
        $files = ConsumerApplicationFiles::where('created_at','>=','2021-04-12 00:00:00')->where('created_at','<=','2021-04-12 23:59:59')->where('m_generated', 1)->get(['id','file_type']);
        $lists = [];
        foreach ($files as $file){
            $lists[] = $file->file_type;
        }
        foreach ($files2 as $item){
            if (file_exists($directory.trim($item)) && in_array(trim($item), $lists)){
                unlink($directory.trim($item));
                $deleted++;
            }
        }

        return $deleted;

    }

    public function uploadZokoDocuments(){

        $directory = "/Users/sunilkhorwal/Sites/zoko_backup/ceb767af-f50f-48db-a560-fc448c62b50b_2/";
        $files2 = scandir($directory, 1);
        $name = [];
        foreach ($files2 as $item){
            $name[] = trim($item);
        }

        $data1 = WhatsappMessages::where('message','like','%BINARY%')->get(['payload','PlatformSenderId']);

        $ids = [];
        $ids1 = [];

        $plt = [];
        foreach($data1 as $item){
            $plt[] = wall_encrypt(str_replace('91', '', str_replace('+91', '', $item->PlatformSenderId)));
        }

        //$app = ConsumerApplication::whereIn('mobile_number', $plt)->whereNull('is_deleted')->get(['id', 'mobile_number']);
        //$app = ConsumerApplication::whereIn('co_applicant_mobile_number', $plt)->whereNull('is_deleted')->get(['id', 'co_applicant_mobile_number as mobile_number']);
        $app = ConsumerApplication::whereIn('mobile_number', $plt)->whereNotNull('is_deleted')->get(['id', 'mobile_number']);
        //$app = ConsumerApplication::whereIn('co_applicant_mobile_number', $plt)->whereNotNull('is_deleted')->get(['id', 'co_applicant_mobile_number as mobile_number']);

        $idsMap = [];
        foreach ($app as $kl){
            $idsMap[$kl->mobile_number] = $kl->id;
        }

        foreach($data1 as $item){
            $c = json_decode($item->payload);
            $p = explode('.', $c->fileUrl);
            $v = $p[count($p) - 2];
            $ex = $p[count($p) - 1];
            $g = explode('/',$v);
            $ids[$item->PlatformSenderId][] = $g[count($g) - 1].'.'.$ex;
            $ids1[] = $g[count($g) - 1].'.'.$ex;
        }

        $l = array_values($ids1);
        $k = array_intersect($l, $name);

        $request = new Request(['test_bot' => true]);

        $document = new ConsumerDocument($request);
        $processed = [];
        $notProcessed = [];

        foreach($k as $_item){
            if (file_exists($directory.$_item)){
                foreach ($ids as $m => $b){
                    if (in_array($_item, $b)){
                        $_m = str_replace('91', '', str_replace('+91', '', $m));
                        if (isset($idsMap[$_m])) {
                            $id = $idsMap[$_m];
                            $document->uploadToS3($_item, $id, file_get_contents($directory . $_item));
                            $processed[] = $_item;
                        }else{
                            $notProcessed[] = $_item;
                        }
                    }
                }
            }
        }

        $list = array_values($name);

        $data = WhatsappMessages::whereIn('request_id', $list)->get();

        $data = WhatsappMessages::Where(function ($query) use($name) {
            for ($i = 0; $i < count($name); $i++){
                $query->orwhere('request_id', 'like',  '%' . trim($name[$i]) .'%');
            }
        })->get();
    }

    public function sendWelcomeLetter(){
        $ids = StatusLogs::where('status','disbursed')->where('created_at','<=', '2021-04-03')->get(['application_id']);
        $applicationIds = [];
        /* For specific application ids */
//        $data = file_get_contents(storage_path() . "/welcome_letter_generated.txt");
//        $data = explode("\n", $data);
//        $data = array_filter($data);
        foreach ($ids as $_id){
//            if(!in_array($_id->application_id, $data)) {
                $applicationIds[] = $_id->application_id;
//            }
        }
        /* For cases with no previous welcome letter docs uploaded */
//        $ids = ConsumerApplicationFiles::whereIn('consumer_application_id',$applicationIds)->where('file_type','welcome_letter')->get(['consumer_application_id']);
//        $id_file = [];
//        foreach ($ids as $_id){
//            $id_file[] = $_id->consumer_application_id;
//        }
//
//        $rem = array_diff($applicationIds, $id_file);

        $applications = ConsumerApplication::whereNull('is_deleted')->whereIn('state',['disbursed', 'nach registered'])->whereIn('id',$applicationIds)->orderBy('created_at','desc')->get(['id']);
        $controller = new ConsumerApplicationController();

        $request = new Request(['test_bot' => true]);

        $document = new ConsumerDocument($request);
        $type = 'Welcome Letter';
        $i = 0;
        foreach ($applications as $application){
            try {
                $welcomeLetter = $controller->sendWelcomeLetter($application->id, true);
                if($welcomeLetter) {
                    $document->uploadToS3(str_replace(' ', '_', strtolower($type)), $application->id, $welcomeLetter);
//                    file_put_contents(storage_path() . "/welcome_letter_generated.txt", $application->id . PHP_EOL, FILE_APPEND | LOCK_EX);
                }
            }catch (\Exception $e){
                if($i == 0){
                    (new Slack(new Request(['title' => 'Welcome Script Error', 'fields' => ['error' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString(), 'application_id' => $application->id, 'id_type' => 'application_id']])))->send();
                    $i = 1;
                }
//                file_put_contents(storage_path()."/welcome_letter_not_generated.txt", $application->id.PHP_EOL , FILE_APPEND | LOCK_EX);
            }
        }
        return 'true';
    }

    public function sendSanctionLetter(){

        $ids = StatusLogs::where('status','nach registered')->where('created_at','<=', '2021-04-03')->get(['application_id']);
        $applicationIds = [];

        $data = file_get_contents(storage_path() . "/sanction_letter_generated.txt");
        $data = explode("\n", $data);
        $data = array_filter($data);

        foreach ($ids as $_id){
            if(!in_array($_id->application_id, $data)) {
                $applicationIds[] = $_id->application_id;
            }
        }
        $applications = ConsumerApplication::whereNull('is_deleted')->where('state','nach registered')->whereIn('id',$applicationIds)->orderBy('created_at','desc')->get(['id']);


        $controller = new ConsumerApplicationController();

        $request = new Request(['test_bot' => true]);

        $document = new ConsumerDocument($request);

        $i = 0;
        $type = 'Sanction Letter';
        foreach ($applications as $application){
            try {
                $sanctionLetter = $controller->sendSanctionLetter($application->id, true);
                $document->uploadToS3(str_replace(' ', '_', strtolower($type)), $application->id, $sanctionLetter);
                file_put_contents(storage_path() . "/sanction_letter_generated.txt", $application->id . PHP_EOL, FILE_APPEND | LOCK_EX);
            }catch (\Exception $e){
                if($i == 0){
                    (new Slack(new Request(['title' => 'Sanction Script Error', 'fields' => ['error' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString(), 'application_id' => $application->id, 'id_type' => 'application_id']])))->send();
                    $i = 1;
                }
                file_put_contents(storage_path()."/sanction_letter_not_generated.txt", $application->id.PHP_EOL , FILE_APPEND | LOCK_EX);
            }
        }
    }

    public function sendLoanAgreement(){

        $ids = StatusLogs::where('status','disbursed')->where('created_at','<=', '2021-04-03')->get(['application_id']);
        $applicationIds = [];
        /* For specific application ids */
//        $data = file_get_contents(storage_path() . "/loan_agreement_generated.txt");
//        $data = explode("\n", $data);
//        $data = array_filter($data);

        foreach ($ids as $_id){
//            if(!in_array($_id->application_id, $data)) {
                $applicationIds[] = $_id->application_id;
//            }
        }
        /* For cases with no previous welcome letter docs uploaded */
//        $ids = ConsumerApplicationFiles::whereIn('consumer_application_id',$applicationIds)->where('file_type','welcome_letter')->get(['consumer_application_id']);
//        $id_file = [];
//        foreach ($ids as $_id){
//            $id_file[] = $_id->consumer_application_id;
//        }
//        $rem = array_diff($applicationIds, $id_file);

        $applications = ConsumerApplication::whereNull('is_deleted')->whereIn('state',['disbursed', 'nach registered'])->whereIn('id',$applicationIds)->orderBy('created_at','desc')->get(['id']);

        $request = new Request(['test_bot' => true]);

        $document = new ConsumerDocument($request);
        $i = 0;
        $type = 'Loan Agreement';
        foreach ($applications as $application){
            try {
                $loanAgreement = $document->getLoanAgreement($application->id, 1, true);
                if($loanAgreement){
                    $document->uploadToS3(str_replace(' ', '_', strtolower($type)), $application->id, $loanAgreement->pdf);
                }
//                file_put_contents(storage_path() . "/loan_agreement_generated.txt", $application->id . PHP_EOL, FILE_APPEND | LOCK_EX);
            }catch (\Exception $e){
                if($i == 0){
                    (new Slack(new Request(['title' => 'Loan Agreement Script Error', 'fields' => ['error' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString(), 'application_id' => $application->id, 'id_type' => 'application_id']])))->send();
                    $i = 1;
                }
//                file_put_contents(storage_path()."/loan_agreement_generated.txt", $application->id.PHP_EOL , FILE_APPEND | LOCK_EX);
            }
        }
    }
    public function generateSignedLoanAgreement(){

        $ids = StatusLogs::where('status','disbursed')->where('created_at','<=', '2021-04-03')->get(['application_id']);
        $applicationIds = [];
        /* For specific application ids */
//        $data = file_get_contents(storage_path() . "/loan_agreement_generated.txt");
//        $data = explode("\n", $data);
//        $data = array_filter($data);

        foreach ($ids as $_id){
//            if(!in_array($_id->application_id, $data)) {
                $applicationIds[] = $_id->application_id;
//            }
        }
        /* For cases with no previous welcome letter docs uploaded */
//        $ids = ConsumerApplicationFiles::whereIn('consumer_application_id',$applicationIds)->where('file_type','welcome_letter')->get(['consumer_application_id']);
//        $id_file = [];
//        foreach ($ids as $_id){
//            $id_file[] = $_id->consumer_application_id;
//        }
//        $rem = array_diff($applicationIds, $id_file);

        $applications = ConsumerApplication::whereNull('is_deleted')->whereIn('state',['disbursed', 'nach registered'])->whereIn('id',$applicationIds)->orderBy('created_at','desc')->get(['id']);

        $request = new Request(['test_bot' => true]);

        $i = 0;
        foreach ($applications as $application){
            try {
                $this->generateEsignLoanAgreement($application->id);
//                file_put_contents(storage_path() . "/loan_agreement_generated.txt", $application->id . PHP_EOL, FILE_APPEND | LOCK_EX);
            }catch (\Exception $e){
                if($i == 0){
                    (new Slack(new Request(['title' => 'Signed Loan Agreement Script Error', 'fields' => ['error' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString(), 'application_id' => $application->id, 'id_type' => 'application_id']])))->send();
                    $i = 1;
                }
//                file_put_contents(storage_path()."/loan_agreement_generated.txt", $application->id.PHP_EOL , FILE_APPEND | LOCK_EX);
            }
        }
    }


    public function tallyEntriesOldDataFromSystem(){
        $payment_date = '2019-04-01';
        $payments = DB::select("select * from payment_transactions where payment_date >= '2019-04-01 00:00:00' and payment_date <= '2019-04-31 23:59:59' and payment_for = 'EMI' and status = 'success'");

        $paymentReconcileData = [];
        $totalAmountReceived = 0;

        $ids = [];
        foreach ($payments as $payment){
            $ids[] = $payment->application_id;
        }

        $applications = ConsumerApplication::whereIn('id', $ids)->where('lender_id', 2)->get();

        $ids = [];
        foreach ($applications as $application){
            $ids[] = $application->id;
        }

        $i = 0;
        $v = 1;
        foreach ($payments as $p => $payment){

            if(in_array($payment->application_id, $ids)) {


                if(isset($paymentReconcileData[$payment->application_id]) && $paymentReconcileData[$payment->application_id]['payment_reconciliation_date'] == $payment->payment_date){
                    $paymentReconcileData[$payment->application_id]['amount'] += $payment->amount;
                }else {

                    $paymentReconcileData[$payment->application_id] = [
                        'mode' => $payment->mode,
                        'paid_by' => '',
                        'application_id' => $payment->application_id,
                        'bank_id' => $payment->bank_id,
                        'umrn' => $payment->umrn,
                        'collected_by' => 107,
                        'trasanction_id' => $payment->trasanction_id,
                        'wallet_name' => '',
                        'payment_date' => $payment->payment_date,
                        'payment_reconciliation_date' => $payment->payment_date,
                        'amount' => $payment->amount,
                        'status' => $payment->status,
                        'reason' => '',
                        'trasanction_acknowledgement' => '',
                        'online_payment_id' => ''
                    ];
                }

                $totalAmountReceived += $payment->amount;

                unset($v);
                if (count($paymentReconcileData) == 50 || !isset($payments[$p + 1])) {
                    $paymentReconcileData = array_values($paymentReconcileData);
                    Settlement::import(['data' => $paymentReconcileData, 'settled_amount' => $totalAmountReceived, 'payment_date' => $payment_date, 'reconciliation_date' => $payment_date, 'type' => 'nach']);
                    $i = 0;
                    $paymentReconcileData = [];
                    $totalAmountReceived = 0;
                    $v = 1;
                } else {
                    $i++;
                }
            }
        }


        if($paymentReconcileData && !isset($v)){
            Settlement::import(['data' => $paymentReconcileData, 'settled_amount' => $totalAmountReceived, 'payment_date' => $payment_date, 'reconciliation_date' => $payment_date, 'type' => 'nach']);
        }
    }

    public function bounce_panel_tally_entries(){
        ini_set('max_execution_time', -1);
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        Excel::import(new TestImport(new Request(['from' => __FUNCTION__])), storage_path().'/Apr-21-BP.xlsx');
    }

    public function getOLDPrincipalOutstanding($id, $moratorium, $emi_date = null){


        /*$applications = DB::select('select application_id from emi_payments where moratorium_amount > 0 group by application_id');

        $dataResponse = [];
        foreach ($applications as $applicationItem) {
            $emi_payment = EmiPayment::where('application_id', $applicationItem->application_id)->get();
            $data = (new LoanManagement())->getWithMoratoriumDetails($emi_payment);
            if($data['emis']) {
                $dataResponse = array_merge($dataResponse, $data['emis']);
            }
        }

        $request = new Request(['data' => $dataResponse, 'sheet' => 'Sheet1']);
        $file = time() . 'Moratorium_data_28' . '.xlsx';

        Excel::store((new Exporter($request)), $file);
        return 4;*/



        if(!isset($id->id)){
            $application = ConsumerApplication::on('mysql_readonly')->with('emi')->where('id',$id)->first();
        }else{
            $application = $id;
        }

        $id = $application->id;
        $payment = new PaymentEmi();
        $emi_dues =  $payment->generateDues($id,1, true);
        $loanamount = ((isset($application->approved_amount) && $application->approved_amount != 0) ? $application->approved_amount : $application->loan_amount) - $application->emi->upfront_from_customer;
        $subvention_amount = (isset($application->emi->subvention) && $application->emi->subvention > 0) ? ((((isset($application->approved_amount) && $application->approved_amount != 0) ? $application->approved_amount : $application->loan_amount)* ($application->emi->subvention))/100) : 0;
        $amount_disbursed = $loanamount - $subvention_amount;
        $i = 0;


        $emis_array = array();
        $emi_irr_array = array();
        array_push($emis_array, -$loanamount);
        array_push($emi_irr_array, -($amount_disbursed));

        if (isset($emi_dues['beforePayload'])) {
            foreach ($emi_dues['beforePayload'] as $emis) {
                array_push($emis_array, $emis['amount']);
                array_push($emi_irr_array, $emis['amount']);

            }
        }
        $rate = (Finance::irr($emis_array)) * 100;
        if ($rate < 0) {
            $rate = 0;
        }

        $irr_rate = (Finance::irr($emi_irr_array)) * 100;
        if ($irr_rate < 0) {
            $irr_rate = 0;
        }

        $loan_amount_subvention = $loanamount - $subvention_amount;
        $principal_outstanding = 0;

        $i = 0;
        if(isset($emi_dues['beforePayload'])){
            $principal_oustanding = $loanamount;
            $principal_oustanding_subvention = $loan_amount_subvention;
            $subvention_amount_balance = $subvention_amount;
            foreach ($emi_dues['beforePayload'] as $emis){
                //if($emis['emi_date'] <= Carbon::createFromFormat('Y-m-d', $moratorium->emi_date)->addMonth(1)->endOfMonth()->toDateString()) {
                $emi_dues['beforePayload'][$i]['interest'] = $principal_oustanding * ($rate / 100);
                $emi_dues['beforePayload'][$i]['principal'] = $emis['amount'] - $emi_dues['beforePayload'][$i]['interest'];
                $emi_dues['beforePayload'][$i]['irr'] = $principal_oustanding_subvention * ($irr_rate / 100);
                $emi_dues['beforePayload'][$i]['subvention'] = $emi_dues['beforePayload'][$i]['irr'] - $emi_dues['beforePayload'][$i]['interest'];
                $subvention_amount_balance = $subvention_amount_balance - $emi_dues['beforePayload'][$i]['subvention'];
                $emi_dues['beforePayload'][$i]['subvention_amount_balance'] = $subvention_amount_balance;
                $principal_oustanding = $principal_oustanding - $emi_dues['beforePayload'][$i]['principal'];
                $principal_oustanding_subvention = $principal_oustanding_subvention - $emi_dues['beforePayload'][$i]['principal'] + $emi_dues['beforePayload'][$i]['subvention'];
                $emi_dues['beforePayload'][$i]['principal_outstanding'] = $principal_oustanding;
                $emi_dues['beforePayload'][$i]['principal_outstanding_subvention'] = $principal_oustanding_subvention;
                $i++;
                //}
            }
        }


        $moratoriumTable = Moratorium::on('mysql_readonly')->where('application_id',$id)->orderBy('emi_date','desc')->get();
        $moratoriumTableExist = [];
        foreach ($moratoriumTable as $moratoriumTableItem){
            $moratoriumTableExist[] = $moratoriumTableItem->emi_date;
            $moratoriumTableExistInterest[$moratoriumTableItem->emi_date] = $moratoriumTableItem->interest_rate;
        }


        foreach ($emi_dues['beforePayload'] as $lk => $emis){
            if(isset($moratoriumTableExistInterest[$emis['emi_date']])) {
                $principal_outstanding = isset($emis['principal_outstanding']) ? $emis['principal_outstanding'] + $emis['amount'] : 0;
                $amount = ($principal_outstanding * $moratoriumTableExistInterest[$emis['emi_date']]) / 100;
                $emi_dues['beforePayload'][$lk]['moratorium_amount'] = round($amount);
            }
        }
        return $emi_dues;
        /*$i = 0;
        if(isset($emi_dues['payload'])){
            $principal_oustanding = $loanamount;
            $principal_oustanding_subvention = $loan_amount_subvention;
            $subvention_amount_balance = $subvention_amount;
            foreach ($emi_dues['payload'] as $emis){
                //if($emis['emi_date'] <= Carbon::createFromFormat('Y-m-d', $moratorium->emi_date)->addMonth(1)->endOfMonth()->toDateString()) {
                    $emi_dues['payload'][$i]['interest'] = $principal_oustanding * ($rate / 100);
                    $emi_dues['payload'][$i]['principal'] = $emis['amount'] - $emi_dues['payload'][$i]['interest'];
                    $emi_dues['payload'][$i]['irr'] = $principal_oustanding_subvention * ($irr_rate / 100);
                    $emi_dues['payload'][$i]['subvention'] = $emi_dues['payload'][$i]['irr'] - $emi_dues['payload'][$i]['interest'];
                    $subvention_amount_balance = $subvention_amount_balance - $emi_dues['payload'][$i]['subvention'];
                    $emi_dues['payload'][$i]['subvention_amount_balance'] = $subvention_amount_balance;
                    $principal_oustanding = $principal_oustanding - $emi_dues['payload'][$i]['principal'];
                    $principal_oustanding_subvention = $principal_oustanding_subvention - $emi_dues['payload'][$i]['principal'] + $emi_dues['payload'][$i]['subvention'];
                    $emi_dues['payload'][$i]['principal_outstanding'] = $principal_oustanding;
                    $emi_dues['payload'][$i]['principal_outstanding_subvention'] = $principal_oustanding_subvention;
                    $i++;
                //}
            }
        }*/



        /*$moraAmount = [];
        foreach ($emi_dues['payload'] as $c => $item){*/
        /* --- if($item['emi_date'] <= $moratorium->emi_date){
            $principal_outstanding = isset($emi_dues['beforePayload'][$c]['principal_outstanding']) ? $emi_dues['beforePayload'][$c]['principal_outstanding'] + $emi_dues['beforePayload'][$c]['amount'] : 0;
            $moraAmount[$moratorium->emi_date] = round($principal_outstanding * $moratorium->interest_rate / 100);
        } --- */
        /*if(in_array($item['emi_date'], $moratoriumTableExist)) {
            $principal_outstanding = isset($emi_dues['payload'][$c]['principal_outstanding']) ? $emi_dues['payload'][$c]['principal_outstanding'] + $emi_dues['payload'][$c]['amount'] : 0;
            $moraAmount[$item['emi_date']] = round($principal_outstanding * $moratorium->interest_rate / 100);
        }*/
        /*}*/


        /*$amount = 0;
        $check = true;
        $cc = 0;
        $date = $moratorium->emi_date;
        while ($check){
            $cc++;
            $date = Carbon::createFromFormat('Y-m-d', $date)->subMonth(1)->toDateString();
            if(!in_array($date, $moratoriumTableExist)){
                $check = false;
                $date = Carbon::createFromFormat('Y-m-d', $date)->addMonth(1)->toDateString();
                $amount = $moraAmount[$date] * $cc;
                break;
            }
        }
        return $amount;*/
    }

//    public function getDataForML(){
//        $data = ConsumerApplication::whereNull('is_deleted')->get();
//        $views = [];
//        foreach($data as $item){
//            if($item->loan_amount && $item->employee_status && $item->monthly_income && $item->tenure && $item->gender) {
//                $views[] = array(
//                    'id' => $item->id,
//                    'gender' => $item->gender,
//                    'employee_status' => $item->employee_status,
//                    'loan_amount' => $item->loan_amount,
//                    'monthly_income' => $item->monthly_income,
//                    'tenure' => $item->tenure,
//                    'status' => in_array($item->state, $this->statusreversearray['approved']) ? 0 : 1
//                );
//            }
//        }
//
//
//        $file = fopen(storage_path()."/customers.csv","w");
//
//        foreach ($views as $line) {
//            fputcsv($file, $line);
//        }
//
//        fclose($file);
//        return 4;
//    }

    public function incompleteFormCommunication($userID, $send = false){
        if($send){
            $payload = [
                'payload' => json_encode(['new_user_id' => $userID]),
                'from' => 'incomplete_form_communication',
                'application_id' => $userID,
                'available_at' => Carbon::now()->addMinutes(30)->toDateTimeString(),
                'created_at' => Carbon::now()->toDateTimeString(),
                'is_available' => 0
            ];
            JobProvider::insert($payload);
        }else{
            $user_status = ConsumerApplication::where('id',$userID->application_id)->whereNull('is_deleted')->first();

            if(isset($user_status)){
                if($user_status->state == 'incomplete form'){
                    if(isset($user_status->email) && $user_status->email){
                        $message = "Hello ".$user_status->name.",<br/>
            
                        Greetings from Credit Fair!<br/>
            
                        We noticed that you started applying for loan at Credit Fair but didn’t complete the application. We would love to help you complete your application and avail the loan.<br/> 
            
                        You may complete your application by downloading our app here https://bit.ly/2HQO1EX.<br/>
            
                        If you are facing any issues, feel free to call us at +91-9967235047 or email us at ops@creditfair.in.<br/>
            
                        Best Regards,<br/>
            
                        Team Credit Fair";
                        $email = $user_status->email;
                        Mail::send('emails.reminders.basic_reminder',
                            ['body'=> $message], function ($message) use ($email) {
                                $message->to($email)->subject('Credit Fair Detected Incomplete Form');
                            });
                    }
                    if(isset($user_status->mobile_number) && $user_status->mobile_number){
                        // sms notification
                        $msg = "Complete your application by downloading our app here https://lnk.creditfair.in/Wgmx. Call us at +919967235047 for help. - Team Credit Fair";
                        $entity = ['templateid' => '1307164931524623174', 'entityid' => Templates::$entityid];

                        $mobile_number = '91' . $user_status->mobile_number;
                        send_sms($mobile_number, ['message' => $msg, 'new_user_state' => 'Incomplete_form_communication', 'templateDetails' => $entity]);
                    }
                }
            }
        }
    }

    public function incompleteFormAbort(){
        $exceedtime = ConsumerApplication::whereIn('updated_by',['website','consumer_app','co-partner'])->whereNull('is_deleted')->where('state','incomplete form')->where('created_at','<=',Carbon::now()->subDay(1)->toDateTimeString())->get();

        if(count($exceedtime) > 0){
            foreach($exceedtime as $k => $v){
                // check for new customer and abort it
                if(!((new ConsumerApplicationController())->isExistingCustomer($v['id']))){
                    if($v['state'] == 'incomplete form'){
                        ConsumerApplication::where('id',$v['id'])->update(['state'=>'aborted']);
                        $statelog = [
                            'application_id' => $v['id'],
                            'user_id' => 107,
                            'status' => 'aborted',
                            'created_at' => Carbon::now()->toDateTimeString(),
                            'is_reversed' => 0
                        ];
                        StatusLogs::insert($statelog);
                    }
                }
            }
        }

        JobProvider::where('from', 'auto_abort_incomplete_form')->update(['is_available' => 0, 'available_at' => Carbon::now()->addDay(1)->startOfDay()->addHours(20)->toDateTimeString()]);
    }

    public function getBureauReportAsJson(){
        try {
//            BNPL cases
//            $applications = ConsumerApplication::with('application_element')->whereHas('application_element', function ($query) {
//                return $query->where('is_bnpl', 1)->where('created_at', '<', Carbon::parse('2022-04-23')->startOfDay());
//            })->get();
//            ABFL cases
            $applications = ConsumerApplication::where('lender_id', 4)->limit(60)->get();
            $s3 = Storage::disk('s3');

//            $zip = new \ZipArchive();
//            $zipFileName = 'BNPL_bureau_report.zip';
//            $res = $zip->open(storage_path($zipFileName), \ZipArchive::CREATE);

            foreach ($applications as $application) {
//                if($application->application_element && $application->application_element->is_bnpl) {
//                    $name = $application->id . '_' . $application->name . '_response.json';
                    $filename = '/' . $application->id . '/' . $application->id . '_response.json';
                    if (/*$res === TRUE &&*/ $s3->exists($filename)) {
                        $data = $s3->get($filename);
                        $filePath = storage_path().'/abfl/'.$application->id.'_'.$application->name.'.json';
                        file_put_contents($filePath, $data);
//                        $zip->addFile($data, $name);
                    }
//                }
            }
//            $zip->close();
//            return response()->download(storage_path($zipFileName), $zipFileName)->deleteFileAfterSend(true);
            return 'success';
        }catch (\Exception $e){
            (new \App\Slack(new Request(['title' => 'Error in downloading reports json', 'fields' => ['error' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()]])))->send();
            return 'failed';
        }
        return true;
    }

    public function delinquencyReport(){
        try{
            (new Slack(new Request(['title' => 'Delinquency Report: Started' , 'fields' => ['Date' => date('y-m-d H:i:s')], 'group' => Slack::$STAGE_TESTING])))->send();
            $reports = (new AccountingController())->getDPDReport(new Request(['report' => true]));
            (new Slack(new Request(['title' => 'Delinquency Report: Data Prepared' , 'fields' => ['Date' => date('y-m-d H:i:s'), 'count' => count($reports)], 'group' => Slack::$STAGE_TESTING])))->send();
            if($reports){
//                Initializing all variables
                $offBC_principal_outstanding = $offBC_count = $offBC_current_amount = $offBC_current_count
                    = $offBC_thirty_amount = $offBC_thirty_count = $offBC_sixty_amount = $offBC_sixty_count
                    = $offBC_ninety_amount = $offBC_ninety_count = $offBC_oneTwenty_amount = $offBC_oneTwenty_count
                    = $offBC_oneFifty_amount = $offBC_oneFifty_count = $offBC_oneEighty_amount = $offBC_oneEighty_count
                    = $offBC_threeSixtyFive_amount = $offBC_threeSixtyFive_count = $offBC_writeOff_amount = $offBC_writeOff_count = null;

                $offBNC_principal_outstanding = $offBNC_count = $offBNC_current_amount = $offBNC_current_count
                    = $offBNC_thirty_amount = $offBNC_thirty_count = $offBNC_sixty_amount = $offBNC_sixty_count
                    = $offBNC_ninety_amount = $offBNC_ninety_count = $offBNC_oneTwenty_amount = $offBNC_oneTwenty_count
                    = $offBNC_oneFifty_amount = $offBNC_oneFifty_count = $offBNC_oneEighty_amount = $offBNC_oneEighty_count
                    = $offBNC_threeSixtyFive_amount = $offBNC_threeSixtyFive_count = $offBNC_writeOff_amount = $offBNC_writeOff_count = null;

                $onBC_principal_outstanding = $onBC_count = $onBC_current_amount = $onBC_current_count
                    = $onBC_thirty_amount = $onBC_thirty_count = $onBC_sixty_amount = $onBC_sixty_count
                    = $onBC_ninety_amount = $onBC_ninety_count = $onBC_oneTwenty_amount = $onBC_oneTwenty_count
                    = $onBC_oneFifty_amount = $onBC_oneFifty_count = $onBC_oneEighty_amount = $onBC_oneEighty_count
                    = $onBC_threeSixtyFive_amount = $onBC_threeSixtyFive_count = $onBC_writeOff_amount = $onBC_writeOff_count = null;

                $onBNC_principal_outstanding = $onBNC_count = $onBNC_current_amount = $onBNC_current_count
                    = $onBNC_thirty_amount = $onBNC_thirty_count = $onBNC_sixty_amount = $onBNC_sixty_count
                    = $onBNC_ninety_amount = $onBNC_ninety_count = $onBNC_oneTwenty_amount = $onBNC_oneTwenty_count
                    = $onBNC_oneFifty_amount = $onBNC_oneFifty_count = $onBNC_oneEighty_amount = $onBNC_oneEighty_count
                    = $onBNC_threeSixtyFive_amount = $onBNC_threeSixtyFive_count = $onBNC_writeOff_amount = $onBNC_writeOff_count = null;

//              Running loop to find the cumulative data
                foreach($reports as $data){
                    if($data['lender_id'] > 2) {
                        if (in_array($data['category_id'], static::$coreSectors)) {
                            $offBC_principal_outstanding +=  $data['principal_outstanding'];
                            $offBC_count++;
                        }else{
                            $offBNC_principal_outstanding +=  $data['principal_outstanding'];
                            $offBNC_count++;
                        }
                    }
                    else{
                        if (in_array($data['category_id'], static::$coreSectors)) {
                            $onBC_principal_outstanding +=  $data['principal_outstanding'];
                            $onBC_count++;
                        }else{
                            $onBNC_principal_outstanding +=  $data['principal_outstanding'];
                            $onBNC_count++;
                        }
                    }

                    switch (true){
                        case ($data['dpd_days'] < 15):
                            if($data['lender_id'] > 2){
                                if(in_array($data['category_id'], static::$coreSectors)) {
                                    $offBC_current_amount += $data['principal_outstanding'];
                                    $offBC_current_count++;
                                }else{
                                    $offBNC_current_amount += $data['principal_outstanding'];
                                    $offBNC_current_count++;
                                }
                            }else{
                                if(in_array($data['category_id'], static::$coreSectors)) {
                                    $onBC_current_amount += $data['principal_outstanding'];
                                    $onBC_current_count++;
                                }else{
                                    $onBNC_current_amount += $data['principal_outstanding'];
                                    $onBNC_current_count++;
                                }
                            }
                            break;
                        case ($data['dpd_days'] < 30):
                            if($data['lender_id'] > 2){
                                if(in_array($data['category_id'], static::$coreSectors)) {
                                    $offBC_thirty_amount += $data['principal_outstanding'];
                                    $offBC_thirty_count++;
                                }else{
                                    $offBNC_thirty_amount += $data['principal_outstanding'];
                                    $offBNC_thirty_count++;
                                }
                            }else{
                                if(in_array($data['category_id'], static::$coreSectors)) {
                                    $onBC_thirty_amount += $data['principal_outstanding'];
                                    $onBC_thirty_count++;
                                }else{
                                    $onBNC_thirty_amount += $data['principal_outstanding'];
                                    $onBNC_thirty_count++;
                                }
                            }
                            break;
                        case ($data['dpd_days'] < 60):
                            if($data['lender_id'] > 2){
                                if(in_array($data['category_id'], static::$coreSectors)) {
                                    $offBC_sixty_amount += $data['principal_outstanding'];
                                    $offBC_sixty_count++;
                                }else{
                                    $offBNC_sixty_amount += $data['principal_outstanding'];
                                    $offBNC_sixty_count++;
                                }
                            }else{
                                if(in_array($data['category_id'], static::$coreSectors)) {
                                    $onBC_sixty_amount += $data['principal_outstanding'];
                                    $onBC_sixty_count++;
                                }else{
                                    $onBNC_sixty_amount += $data['principal_outstanding'];
                                    $onBNC_sixty_count++;
                                }
                            }
                            break;
                        case ($data['dpd_days'] < 90):
                            if($data['lender_id'] > 2){
                                if(in_array($data['category_id'], static::$coreSectors)) {
                                    $offBC_ninety_amount += $data['principal_outstanding'];
                                    $offBC_ninety_count++;
                                }else{
                                    $offBNC_ninety_amount += $data['principal_outstanding'];
                                    $offBNC_ninety_count++;
                                }
                            }else{
                                if(in_array($data['category_id'], static::$coreSectors)) {
                                    $onBC_ninety_amount += $data['principal_outstanding'];
                                    $onBC_ninety_count++;
                                }else{
                                    $onBNC_ninety_amount += $data['principal_outstanding'];
                                    $onBNC_ninety_count++;
                                }
                            }
                            break;
                        case ($data['dpd_days'] < 120):
                            if($data['lender_id'] > 2){
                                if(in_array($data['category_id'], static::$coreSectors)) {
                                    $offBC_oneTwenty_amount += $data['principal_outstanding'];
                                    $offBC_oneTwenty_count++;
                                }else{
                                    $offBNC_oneTwenty_amount += $data['principal_outstanding'];
                                    $offBNC_oneTwenty_count++;
                                }
                            }else{
                                if(in_array($data['category_id'], static::$coreSectors)) {
                                    $onBC_oneTwenty_amount += $data['principal_outstanding'];
                                    $onBC_oneTwenty_count++;
                                }else{
                                    $onBNC_oneTwenty_amount += $data['principal_outstanding'];
                                    $onBNC_oneTwenty_count++;
                                }
                            }
                            break;
                        case ($data['dpd_days'] < 150):
                            if($data['lender_id'] > 2){
                                if(in_array($data['category_id'], static::$coreSectors)) {
                                    $offBC_oneFifty_amount += $data['principal_outstanding'];
                                    $offBC_oneFifty_count++;
                                }else{
                                    $offBNC_oneFifty_amount += $data['principal_outstanding'];
                                    $offBNC_oneFifty_count++;
                                }
                            }else{
                                if(in_array($data['category_id'], static::$coreSectors)) {
                                    $onBC_oneFifty_amount += $data['principal_outstanding'];
                                    $onBC_oneFifty_count++;
                                }else{
                                    $onBNC_oneFifty_amount += $data['principal_outstanding'];
                                    $onBNC_oneFifty_count++;
                                }
                            }
                            break;
                        case ($data['dpd_days'] < 180):
                            if($data['lender_id'] > 2){
                                if(in_array($data['category_id'], static::$coreSectors)) {
                                    $offBC_oneEighty_amount += $data['principal_outstanding'];
                                    $offBC_oneEighty_count++;
                                }else{
                                    $offBNC_oneEighty_amount += $data['principal_outstanding'];
                                    $offBNC_oneEighty_count++;
                                }
                            }else{
                                if(in_array($data['category_id'], static::$coreSectors)) {
                                    $onBC_oneEighty_amount += $data['principal_outstanding'];
                                    $onBC_oneEighty_count++;
                                }else{
                                    $onBNC_oneEighty_amount += $data['principal_outstanding'];
                                    $onBNC_oneEighty_count++;
                                }
                            }
                            break;
                        case ($data['dpd_days'] < 365):
                            if($data['lender_id'] > 2){
                                if(in_array($data['category_id'], static::$coreSectors)) {
                                    $offBC_threeSixtyFive_amount += $data['principal_outstanding'];
                                    $offBC_threeSixtyFive_count++;
                                }else{
                                    $offBNC_threeSixtyFive_amount += $data['principal_outstanding'];
                                    $offBNC_threeSixtyFive_count++;
                                }
                            }else{
                                if(in_array($data['category_id'], static::$coreSectors)) {
                                    $onBC_threeSixtyFive_amount += $data['principal_outstanding'];
                                    $onBC_threeSixtyFive_count++;
                                }else{
                                    $onBNC_threeSixtyFive_amount += $data['principal_outstanding'];
                                    $onBNC_threeSixtyFive_count++;
                                }
                            }
                            break;
                        case ($data['dpd_days'] > 365):
                            if($data['lender_id'] > 2){
                                if(in_array($data['category_id'], static::$coreSectors)) {
                                    $offBC_writeOff_amount += $data['principal_outstanding'];
                                    $offBC_writeOff_count++;
                                }else{
                                    $offBNC_writeOff_amount += $data['principal_outstanding'];
                                    $offBNC_writeOff_count++;
                                }
                            }else{
                                if(in_array($data['category_id'], static::$coreSectors)) {
                                    $onBC_writeOff_amount += $data['principal_outstanding'];
                                    $onBC_writeOff_count++;
                                }else{
                                    $onBNC_writeOff_amount += $data['principal_outstanding'];
                                    $onBNC_writeOff_count++;
                                }
                            }
                            break;
                    }
                }

//               Pull old data
//                $old_logs = DelinquencyLogs::whereNull('deleted_at')->orderBy('created_at', 'desc')->get();
                $offBookCoreLogs = $offBookNonCoreLogs = $onBookCorLogs = $onBookNonCoreLogs = [];
//                foreach($old_logs as $key => $value){
//                    $period[$key] = $value->period;
//                    $offBookCoreLogs[$key] = json_decode($value->offBookCore, true);
//                    $offBookNonCoreLogs[$key] = json_decode($value->offBookNonCore, true);
//                    $onBookCorLogs[$key] = json_decode($value->onBookCore, true);
//                    $onBookNonCoreLogs[$key] = json_decode($value->onBookNonCore, true);
//                }

//               Marking the header for all sheets
                $header = ['Moving Delinquency as on', 'Total Principal Outstanding', 'No. of loans', 'Current (Rs)', 'No. of loans', '0 TO 30 (Rs)', 'No. of loans', '31TO60 (Rs )', 'No. of loans', '61TO90 (Rs)', 'No. of loans', '90 TO120 (Rs)', 'No. of loans', '121TO150 (Rs)', 'No. of loans', '151TO180 (Rs)', 'No. of loans', '181 - 364 (Rs)', 'No. of loans', '>364 (Rs)', 'No. of loans', 'Write Off for the month (Rs)', 'No. of loans'];
                $month = Carbon::now()->format('M');
                $year = Carbon::now()->format('Y');

//               Setting the variables back in an array
                $offBookCore = [
                    'delinquency' => $month.' '.$year,
                    'principal_outstanding' => $offBC_principal_outstanding,
                    'count' => $offBC_count,
                    'current_amount' => $offBC_current_amount,
                    'current_count' => $offBC_current_count,
                    'thirty_amount' => $offBC_thirty_amount,
                    'thirty_count' => $offBC_thirty_count,
                    'sixty_amount' => $offBC_sixty_amount,
                    'sixty_count' => $offBC_sixty_count,
                    'ninety_amount' => $offBC_ninety_amount,
                    'ninety_count' => $offBC_ninety_count,
                    'oneTwenty_amount' => $offBC_oneTwenty_amount,
                    'oneTwenty_count' => $offBC_oneTwenty_count,
                    'oneFifty_amount' => $offBC_oneFifty_amount,
                    'oneFifty_count' => $offBC_oneFifty_count,
                    'oneEighty_amount' => $offBC_oneEighty_amount,
                    'oneEighty_count' => $offBC_oneEighty_count,
                    'threeSixtyFive_amount' => $offBC_threeSixtyFive_amount,
                    'threeSixtyFive_count' => $offBC_threeSixtyFive_count,
                    'writeOff_amount' => $offBC_writeOff_amount,
                    'writeOff_coun' => $offBC_writeOff_count
                ];
                $offBookNonCore = [
                    'delinquency' => $month.' '.$year,
                    'principal_outstanding' => $offBNC_principal_outstanding,
                    'count' => $offBNC_count,
                    'current_amount' => $offBNC_current_amount,
                    'current_count' => $offBNC_current_count,
                    'thirty_amount' => $offBNC_thirty_amount,
                    'thirty_count' => $offBNC_thirty_count,
                    'sixty_amount' => $offBNC_sixty_amount,
                    'sixty_count' => $offBNC_sixty_count,
                    'ninety_amount' => $offBNC_ninety_amount,
                    'ninety_count' => $offBNC_ninety_count,
                    'oneTwenty_amount' => $offBNC_oneTwenty_amount,
                    'oneTwenty_count' => $offBNC_oneTwenty_count,
                    'oneFifty_amount' => $offBNC_oneFifty_amount,
                    'oneFifty_count' => $offBNC_oneFifty_count,
                    'oneEighty_amount' => $offBNC_oneEighty_amount,
                    'oneEighty_count' => $offBNC_oneEighty_count,
                    'threeSixtyFive_amount' => $offBNC_threeSixtyFive_amount,
                    'threeSixtyFive_count' => $offBNC_threeSixtyFive_count,
                    'writeOff_amount' => $offBNC_writeOff_amount,
                    'writeOff_count' => $offBNC_writeOff_count
                ];
                $onBookCore = [
                    'delinquency' => $month.' '.$year,
                    'principal_outstanding' => $onBC_principal_outstanding,
                    'count' => $onBC_count,
                    'current_amount' => $onBC_current_amount,
                    'current_count' => $onBC_current_count,
                    'thirty_amount' => $onBC_thirty_amount,
                    'thirty_count' => $onBC_thirty_count,
                    'sixty_amount' => $onBC_sixty_amount,
                    'sixty_count' => $onBC_sixty_count,
                    'ninety_amount' => $onBC_ninety_amount,
                    'ninety_count' => $onBC_ninety_count,
                    'oneTwenty_amount' => $onBC_oneTwenty_amount,
                    'oneTwenty_count' => $onBC_oneTwenty_count,
                    'oneFifty_amount' => $onBC_oneFifty_amount,
                    'oneFifty_count' => $onBC_oneFifty_count,
                    'oneEighty_amount' => $onBC_oneEighty_amount,
                    'oneEighty_count' => $onBC_oneEighty_count,
                    'threeSixtyFive_amount' => $onBC_threeSixtyFive_amount,
                    'threeSixtyFive_count' => $onBC_threeSixtyFive_count,
                    'writeOff_amount' => $onBC_writeOff_amount,
                    'writeOff_count' => $onBC_writeOff_count
                ];
                $onBookNonCore = [
                    'delinquency' => $month.' '.$year,
                    'principal_outstanding' => $onBNC_principal_outstanding,
                    'count' => $onBNC_count,
                    'current_amount' => $onBNC_current_amount,
                    'current_count' => $onBNC_current_count,
                    'thirty_amount' => $onBNC_thirty_amount,
                    'thirty_count' => $onBNC_thirty_count,
                    'sixty_amount' => $onBNC_sixty_amount,
                    'sixty_count' => $onBNC_sixty_count,
                    'ninety_amount' => $onBNC_ninety_amount,
                    'ninety_count' => $onBNC_ninety_count,
                    'oneTwenty_amount' => $onBNC_oneTwenty_amount,
                    'oneTwenty_count' => $onBNC_oneTwenty_count,
                    'oneFifty_amount' => $onBNC_oneFifty_amount,
                    'oneFifty_count' => $onBNC_oneFifty_count,
                    'oneEighty_amount' => $onBNC_oneEighty_amount,
                    'oneEighty_count' => $onBNC_oneEighty_count,
                    'threeSixtyFive_amount' => $onBNC_threeSixtyFive_amount,
                    'threeSixtyFive_count' => $onBNC_threeSixtyFive_count,
                    'writeOff_amount' => $onBNC_writeOff_amount,
                    'writeOff_count' => $onBNC_writeOff_count
                ];

//                DelinquencyLogs::insert([
//                    'period' => $month.' '.$year,
//                    'offBookCore' => json_encode($offBookCore),
//                    'offBookNonCore' => json_encode($offBookNonCore),
//                    'onBookCore' => json_encode($onBookCore),
//                    'onBookNonCore' => json_encode($onBookNonCore)
//                ]);

//               Merging the header with data
                $offBookCore = [$header, $offBookCore];
                $offBookNonCore = [$header, $offBookNonCore];
                $onBookCore = [$header, $onBookCore];
                $onBookNonCore = [$header, $onBookNonCore];

//               Putting it all in a request to print on multiple sheets
                $request = new Request([
                    'sheet' => ['Core-Off Book','Non Core-Off Book','Core-On Book','Non Core-On Book'],
//                    'data'  => [array_merge($offBookCore, $offBookCoreLogs), array_merge($offBookNonCore, $offBookNonCoreLogs), array_merge($onBookCore, $onBookCorLogs), array_merge($onBookNonCore, $onBookNonCoreLogs)]
                    'data'  => [$offBookCore,$offBookNonCore,$onBookCore,$onBookNonCore]
                ]);


                $month = Carbon::now()->format('M');
                $year = Carbon::now()->format('Y');
                $file = 'Monthly_Delinquency_Report_'.$month.'_'.$year.'.xlsx';

                Excel::store((new Exporter($request)), $file);
//                return Excel::download((new ExporterMultipleSheet($request)), $file);
                Mail::send('emails.reminders.basic_reminder',
                    ['body' => 'Monthly Delinquency Report of month ' . $month . '-' . $year]
                    , function ($message) use ($file, $month, $year) {
                        $message->to(_env('NOTIFY_EMAIL', ''))->subject('Monthly Delinquency Report of month '.$month.'-'.$year);
                        $message->cc(['sarah@creditfair.in','sunil@creditfair.in']);
                        $message->attachData(file_get_contents(storage_path() . '/app/' . $file), 'Monthly_Delinquency_Report_'.$month.'_'.$year.'.xlsx');
                    });
            }
            (new Slack(new Request(['title' => 'Delinquency Report Sent' ,'fields' => ['Report' => $file ?? 'No Data Found'], 'group' => Slack::$STAGE_TESTING])))->send();
        }catch (\Exception $exception){
            (new Slack(new Request(['title' => 'Delinquency Report failed' , 'fields' => ['e' => $exception->getMessage(),'l' => $exception->getLine(),'t' => $exception->getTraceAsString()], 'group' => Slack::$STAGE_TESTING])))->send();
        }
    }

    public function getTransactions(){


        $res = json_decode('{"mode":7,"paid_by":"","application_id":115886,"bank_id":4,"umrn":"ICIC7023006220017462","collected_by":107,"trasanction_id":"ND0012J89ONDAU","wallet_name":"","payment_date":"2023-04-21 00:00:00","payment_reconciliation_date":"2023-04-22 00:00:00","amount":4425,"status":"success","reason":"","trasanction_acknowledgement":"","online_payment_id":""}', 1);
        $PaymentEmi = new LoanManagement();
        $PaymentEmi->paymentReconcile($res);
        return 0;

        $transactions = PaymentTransaction::where('application_id', 115886)->get();

        $amount = [];
        foreach($transactions as $transaction){
            if(isset($amount[$transaction->cf_transaction_id]['amount'])){
                $amount[$transaction->cf_transaction_id]['amount'] += $transaction->amount;
            }else{
                $amount[$transaction->cf_transaction_id]['amount'] = $transaction->amount;
                $amount[$transaction->cf_transaction_id]['tr'] = $transaction;
            }
        }


        foreach($amount as $tx => $item){
            $res[$tx][] =  json_encode([
                'mode' => 7,
                'paid_by' => '',
                'application_id' => $item['tr']->application_id,
                'bank_id' => $item['tr']->bank_id,
                'umrn' => $item['tr']->umrn,
                'collected_by' => 107,
                'trasanction_id' => $item['tr']->trasanction_id,
                'wallet_name' => '',
                'payment_date' => $item['tr']->payment_date,
                'payment_reconciliation_date' => $item['tr']->payment_reconciliation_date,
                'amount' => $item['amount'],
                'status' => 'success',
                'reason' => $item['tr']->reason,
                'trasanction_acknowledgement' => '',
                'online_payment_id' => ''
            ]);
        }

        return $res;
    }

    public function documentGeneration(){
        ini_set('max_execution_time', -1);
        set_time_limit(0);
        ini_set('memory_limit', '-1');

        try {
            $data = ConsumerApplicationFiles::whereIn('consumer_application_id', [67403, 70484, 73921, 74083, 61371, 74115, 70746, 70274, 71519, 71797, 71837, 72243, 72095, 70699, 70139, 71743, 69355, 68548, 69985, 70836, 70363, 71314, 71524, 72032, 71882, 72215, 72104, 72221, 72089, 73407, 67346, 67135, 58877, 67329, 67134, 67164, 68073, 66981, 69401, 70373, 68575, 66010, 73137, 74236, 58432, 67358, 73567, 48211, 65380, 67324, 67095, 65384, 54460])->orderBy('consumer_application_id', 'ASC')->get(['consumer_application_id', 'file_path', 'file_type'])->toArray();
            $data_array = [];
            $zipFileName = storage_path() . '/ApplicationDoc.zip';
            $zip = new \ZipArchive();
            $res = $zip->open($zipFileName, \ZipArchive::CREATE);
            $ex = 'pdf';
            if ($res !== TRUE) {
                die ("An error occurred creating your ZIP file.");
            }
            foreach ($data as $key => $value) {
                $data_array[$value['consumer_application_id']][$value['file_type']] = $value['file_path'];
            }

            foreach ($data_array as $key => $value) {
                //        $FileName = $zipFileName.'/'.'ApplicationID_'.$key.'_' . Carbon::now()->toDateTimeString() . '.zip';

                foreach ($value as $k => $v) {
                    $s3 = Storage::disk('s3');

                    if ($s3->exists($v)) {
                        $path = storage_path() . '/ApplicationTempDoc/' . time() . '_' . uniqid();
                        $paths = explode('/', $v);
                        $lPath = $paths[count($paths) - 1];
                        if (isset(explode('.', $lPath)[1])) {
                            $ex = explode('.', $lPath)[1];
                        } else {
                            $lPathLastChar = substr($lPath, -3);
                            if ($lPathLastChar == 'png') {
                                $ex = 'png';
                            } elseif ($lPathLastChar == 'jpg') {
                                $ex = 'jpg';
                            } elseif ($lPathLastChar == 'pdf') {
                                $ex = 'pdf';
                            } elseif (substr($lPath, -4) == 'jpeg') {
                                $ex = 'jpeg';
                            }
                        }
                        $doc = $s3->get($v);
                        $file = fopen($path, "w");
                        fwrite($file, $doc);
                        fclose($file);
                        $zip->addFile($path, 'AppID_' . $key . '_' . $k . '.' . $ex);
                    }
                }

            }
            if (true) {
                $zip->close();

                Mail::send('emails.reminders.basic_reminder', ['body' => 'Uploaded document']
                    , function ($message) use ($file) {
                        $message->to(['sarah@creditfair.in'])->subject('Document Upload');
                        $message->attachData(file_get_contents(storage_path() . '/ApplicationDoc.zip'), 'ApplicationDoc.zip');
                    });
                //        return response()->download($zipFileName)->deleteFileAfterSend(true);
            }
            echo "Success";

        }catch (\Exception $e){
            (new \App\Slack(new Request(['title' => 'Document export failed', 'fields' => ['error' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()]])))->send();
        }
    }

    public function bureauDocumentGeneration(){
        ini_set('max_execution_time', -1);
        set_time_limit(0);
        ini_set('memory_limit', '-1');

        try {
            $app_ids = [67403, 70484, 73921, 74083, 61371, 74115, 70746, 70274, 71519, 71797, 71837, 72243, 72095, 70699, 70139, 71743, 69355, 68548, 69985, 70836, 70363, 71314, 71524, 72032, 71882, 72215, 72104, 72221, 72089, 73407, 67346, 67135, 58877, 67329, 67134, 67164, 68073, 66981, 69401, 70373, 68575, 66010, 73137, 74236, 58432, 67358, 73567, 48211, 65380, 67324, 67095, 65384, 54460];
            $data_array = [];
            $zipFileName = storage_path() . '/ApplicationDoc.zip';
            $zip = new \ZipArchive();
            $res = $zip->open($zipFileName, \ZipArchive::CREATE);
            $ex = 'pdf';
            if ($res !== TRUE) {
                die ("An error occurred creating your ZIP file.");
            }

            foreach ($app_ids as $id) {
                $data = array();
                $data['is_home'] = true;
                try {
                    for($i=1; $i<3; $i++) {
                        $applicant_type = (empty($i) || $i == 1) ? '' : '_'.$i;
                        $path = storage_path() . '/ApplicationTempDoc/' . time() . '_' . uniqid();
                        $file_path = $id . '/' . $id . '_response' . $applicant_type . '.json';
                        if (false !== $file = Equifax::readFile($file_path)) {
                            $report_data = json_decode($file, true);
                            if (isset($report_data['soapenv:Envelope'])) {
                                $data['report_data'] = $report_data['soapenv:Envelope']['soapenv:Body']['sch:InquiryResponse'];

                                $view = view('front.cibil-report', $data);
                            } else {
                                $report_data = json_decode($file);
                                $report = $report_data->Body->ProcessResponse->Out->INProfileResponse;
                                $data = [
                                    'id' => $report_data->ID ?? '',
                                    'user_id' => $report_data->UserID ?? '',
                                    'applicant_type' => $report_data->ApplicantType ?? 1,
                                    'header' => $report->Header ?? '',
                                    'applicant_details' => $report->CurrentApplication->Current_Application_Details ?? '',
                                    'account_details' => $report->CAIS_Account ?? '',
                                    'credit_caps' => $report->CAPS->CAPS_Summary ?? '',
                                    'credit_caps_details' => $report->CAPS->CAPS_Application_Details ?? '',
                                    'non_credit_caps' => $report->NonCreditCAPS->NonCreditCAPS_Summary ?? '',
                                    'non_credit_caps_details' => $report->NonCreditCAPS->CAPS_Application_Details ?? '',
                                    'score' => $report->SCORE ?? '',
                                    'error' => $report_data->Body->ProcessResponse->Out->INProfileResponse->UserMessage->UserMessageText ?? '',
                                ];

                                $view = view('front.experian-report', $data);
                            }
                            $pdf = App::make('snappy.pdf.wrapper');
                            $pdf->loadHTML($view)->setOption('encoding', 'UTF-8')->setPaper('a4')->setOrientation('portrait');
                            $pdf->setOption('margin-bottom', 25);
                            $pdf->save($path);
                            $zip->addFile($path, 'AppID_' . $id . '_' . $applicant_type . '.pdf');
                        }
                    }
                } catch (\Exception $e) {
                    (new Slack(new Request(['title'=>'Bureau script error','fields'=>['Application ID'=>$id,'error'=>$e->getMessage(),'line'=>$e->getLine(),'trace'=>$e->getTraceAsString(),'application_id'=>$id], 'group' => Slack::$STAGE_TESTING])))->send();
                }
//                $doc = $s3->get($v);
//                $file = fopen($path, "w");
//                fwrite($file, $doc);
//                fclose($file);
            }
            if (true) {
                $zip->close();

                Mail::send('emails.reminders.basic_reminder', ['body' => 'Uploaded document']
                    , function ($message) use ($file) {
                        $message->to(['sarah@creditfair.in'])->subject('Document Upload');
                        $message->attachData(file_get_contents(storage_path() . '/ApplicationDoc.zip'), 'ApplicationDoc.zip');
                    });
                //        return response()->download($zipFileName)->deleteFileAfterSend(true);
            }
            echo "Success";

        }catch (\Exception $e){
            (new \App\Slack(new Request(['title' => 'Document export failed', 'fields' => ['error' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()]])))->send();
        }
    }

    public function getDPDReport($id, $date){
        //$date = '2022-07-31';

        $data =  EmiPayment::with('transaction')->where('application_id',$id)->get(['id', 'application_id', 'emi_date','emi_amount', 'bounce_charges', 'delay_penalty', 'charges_waived']);
        $dpdAsOn = 0;
        foreach($data as $key => $item){

            $dpdData1[$item->application_id][$item->id]['charges_waived'] = $item->charges_waived;
            $dpdData[$item->application_id][$item->emi_date] = [
                'dpd_days' => 0,
                'emi_amount' => $item->emi_amount,
                'bounce_charges' => $item->bounce_charges,
                'delay_penalty' => $item->delay_penalty,
                'charges_waived' => $item->charges_waived,
                'amount_received' => 0
            ];
            $amountReceived = 0;
            foreach($item->transaction as $transaction){
                if($transaction->refunded_at == null && strtotime($transaction->payment_date) <= strtotime($date)){
                    $amountReceived += $transaction->amount;
                    if ($dpdData1[$item->application_id][$transaction->emi_payment_id]['charges_waived']){
                        $amountReceived += $dpdData1[$item->application_id][$transaction->emi_payment_id]['charges_waived'];
                    }
                }
            }

            $overpayments = PaymentTransaction::where('application_id', $item->application_id)->whereIn('payment_for', ['Over Payment', 'Advance Payment', 'rejected', 'Foreclosure'])->get();
            if(count($overpayments)){
                foreach($overpayments as $overpayment){
                    if($overpayment->refunded_at == null && strtotime($overpayment->payment_date) <= strtotime($date)){
                        $amountReceived += $overpayment->amount;
                    }
                }
            }

            if ($amountReceived < $item->emi_amount){
                $nextDate = ($data[$key + 1]->emi_date ?? $date);
                if (strtotime($nextDate) > strtotime($date)){
                    $nextDate = $date;
                }
                $dpdDaysValue = $this->calculateDays($item->emi_date, date('Y-m-d', strtotime($nextDate)));
                $dpdData[$item->application_id][$item->emi_date]['dpd_days'] = $dpdDaysValue;
                if(strtotime($item->emi_date) <= strtotime($date)){
                    $dpdAsOn += $dpdDaysValue;
                }
            }

            $dpdData[$item->application_id][$item->emi_date]['amount_received'] = $amountReceived;
        }
        return $dpdAsOn;
//        $file = fopen(storage_path('dpd_file'),"w");
//
//        foreach ($response as $line) {
//            fputcsv($file, $line);
//        }
//
//        fclose($file);

        //return (new LoanManagement())->paymentCalculateV3($id,$date,'all');
    }

    public function calculateDays($due_date, $payment_date){
        $now = strtotime($payment_date); // or your date as well
        $your_date = strtotime($due_date);
        $datediff = $now - $your_date;

        return round($datediff / (60 * 60 * 24),0);
    }

    public function replaceRepaymentType(){
        $data = ConsumerApplication::with(['emi' =>function($query){
            return $query->select('application_id','remaining_emi','emi_date','subvention','upfront_from_customer','emi');
        }])->whereIn('state',['disbursed','nach registered'])->get(['id','approved_amount', 'loan_amount']);
        foreach($data as $val){
            //$remaining_emi = ApplicationEMICalculation::where('application_id', $val->id)->first();
            if($val->emi->remaining_emi == 1){
                ConsumerApplicationElement::where('application_id', $val->id)->update(['repayment_type' => 2]);
                $disb_date = StatusLogs::where('application_id', $val->id)->where('status','disbursed')->orderBy('created_at','DESC')->first();
                $disb_date_f = Carbon::parse($disb_date->created_at);
                $repay_date = Carbon::parse($val->emi->emi_date);
                $p_days = $disb_date_f->diffInDays($repay_date);
                $loanamount = ((isset($val->approved_amount) && $val->approved_amount != 0) ? $val->approved_amount : $val->loan_amount) - $val->emi->upfront_from_customer;
                $subvention_amount = (isset($val->emi->subvention) && $val->emi->subvention > 0) ? ((((isset($val->approved_amount) && $val->approved_amount != 0) ? $val->approved_amount : $val->loan_amount) * ($val->emi->subvention)) / 100) : 0;
                $amount_disbursed = $loanamount - $subvention_amount;
                $c = (1/$p_days);
                $d = $c;
                $v = $val->emi->emi/(-$amount_disbursed);
                $irr_data = (pow(-$v, $d) - 1);
                $irr_data_anuualize = $irr_data*365;
                $irr_data_percent = round($irr_data * 100, 2);
                $irr_data_anuualize_percent = round($irr_data_anuualize * 100, 2);
                ApplicationEMICalculation::where('application_id', $val->id)->update(["irr_rate"=>$irr_data_percent, "annualised_irr"=>$irr_data_anuualize_percent]);
            }
        }
        echo "done";
    }

    public function creditReportEntries(){

        ini_set('max_execution_time', -1);
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $data = array(array());

        $applications = CreditReport::whereNull('deleted_at')->whereNull('ml_loan_amount')->get(['application_id', 'id']);
        $path = storage_path()."/credit_report.csv";
        $file = fopen($path,"a");
        // dd($applications);
        foreach($applications as $application){
            $id = $application->application_id;

                try{

                $creditLine = new CreditLine(new Request(['id' => $id]));
                $creditDatainsert = $creditLine->getCreditData();

                $data[$id]['ml_loan_amount'] = $creditDatainsert['max_loan_amount_to_sanction_basis_ml'] ;

                $data[$id]['ml_eligible_emi_amount'] = $creditDatainsert['eligible_emi_amount_ml'] ;

                $data[$id]['foir_loan_amount'] = $creditDatainsert['max_loan_amount_to_sanction_basis_foir'] ;

                $data[$id]['foir_eligible_emi_amount'] = $creditDatainsert['eligible_emi_amount_basis_foir'] ;

                $line = "UPDATE credit_report SET ml_loan_amount = ".$data[$id]['ml_loan_amount']." , ml_eligible_emi_amount = ".$data[$id]['ml_eligible_emi_amount'].", foir_loan_amount = ".$data[$id]['foir_loan_amount'].", foir_eligible_emi_amount = ". $data[$id]['foir_eligible_emi_amount']." WHERE id = ".$application->id."\n";

                fwrite($file, $line);

            }catch(\Exception $e){

                //dd($e->getMessage().$e->getLine());
                    // continue;
            }
    }
        fclose($file);

        return true;

    }

    public function accruedRevenueSinceInception() {
        try{

            ini_set('max_execution_time', -1);
            set_time_limit(0);
            ini_set('memory_limit', '-1');

            $idsData = [];
//            if (isset($event['year']) && isset($event['month'])){
                $from_date = Carbon::parse('2023-07-01')->startOfMonth()->toDateTimeString();
                $to_date = Carbon::parse('2023-09-30')->startOfMonth()->toDateTimeString();
//                $to_date = Carbon::now()->toDateTimeString();
                $emisPayemetnsData = EmiPayment::where('emi_date', '>=', $from_date)->where('emi_date', '<=', $to_date)->get(['application_id']);
                foreach($emisPayemetnsData as $emisPayemetnsDatum){
                    $idsData[] = $emisPayemetnsDatum->application_id;
                }
//            }



            $status = ['disbursed'];
            $consumerApplications1 = ConsumerApplicationRelation::with( 'emi', 'emi_payment')->wherein('state', $status)->whereNotNull('merchant_id')->whereNull('is_deleted');

            if (isset($event['lender_id'])){
                $consumerApplications1 = $consumerApplications1->where('lender_id', $event['lender_id']);
            }else{
                $consumerApplications1 = $consumerApplications1->whereIn('lender_id', [1, 2]);
            }

            if ($idsData){
                $consumerApplications1 = $consumerApplications1->whereIn('id', $idsData);
            }

            $consumerApplications1 = $consumerApplications1->get();

            $status = ['nach registered', 'closed'];

            $consumerApplications = ConsumerApplicationRelation::with( 'emi', 'emi_payment')->wherein('state', $status)->whereNotNull('merchant_id')->whereNull('is_deleted')->whereIn('lender_id', [1, 2]);

            if ($idsData){
                $consumerApplications = $consumerApplications->whereIn('id', $idsData);
            }

            if (isset($event['lender_id'])){
                $consumerApplications = $consumerApplications->where('lender_id', $event['lender_id']);
            }else{
                $consumerApplications = $consumerApplications->whereIn('lender_id', [1, 2]);
            }

            $consumerApplications = $consumerApplications->get();

            $consumerApplications = $consumerApplications1->merge($consumerApplications);
            $dataItems = [];
            $response = [];

            foreach($consumerApplications as $application) {

                $loanamount = ((isset($application->approved_amount) && $application->approved_amount != 0) ? $application->approved_amount : $application->loan_amount) - ($application->emi ? $application->emi->upfront_from_customer : 0);

                $subvention_amount = (isset($application->emi->subvention) && $application->emi->subvention > 0) ? ((((isset($application->approved_amount) && $application->approved_amount != 0) ? $application->approved_amount : $application->loan_amount) * ($application->emi->subvention)) / 100) : 0;
                $amount_disbursed = $loanamount - $subvention_amount;

                $emis_array = array();
                $emi_irr_array = array();

                array_push($emis_array, -$loanamount);
                array_push($emi_irr_array, -($amount_disbursed));

                $emi_dues = [];
                $payload = [];
                foreach($application->emi_payment as $emi_payment){





                    //$emimonth = date('Y-m', strtotime($emi_payment->emi_date));
                    if (1) { //$emi_payment->payment_status == "success"
                        $penal_interest = ($emi_payment->charges_waived > $emi_payment->delay_penalty) ? $emi_payment->delay_penalty : ($emi_payment->delay_penalty - $emi_payment->charges_waived);
                        if ($penal_interest > 0) {
                            $response[$emi_payment->application_id][$emi_payment->emi_date]['penal_interest'] = round($penal_interest, 2);
                            /*if (isset($response[$emimonth]['penal_interest'])) {
                                $response[$emimonth]['penal_interest'] = round($response[$emimonth]['penal_interest'] + $penal_interest, 2);
                            } else {
                                $response[$emimonth]['penal_interest'] = round($penal_interest, 2);
                            }*/
                        }
                        $bounce_charge = $emi_payment->bounce_charges;
                        if ($emi_payment->charges_waived > 0) {
                            if ($emi_payment->charges_waived > ($emi_payment->delay_penalty + $emi_payment->bounce_charges)) {
                                $bounce_charge = 0;
                            } elseif ($emi_payment->charges_waived <= ($emi_payment->delay_penalty)) {
                                $bounce_charge = $emi_payment->bounce_charges;
                            } else {
                                $charges_waived_bounce_charges = $emi_payment->charges_waived - $emi_payment->delay_penalty;
                                $bounce_charge = $emi_payment->bounce_charges - $charges_waived_bounce_charges;

                            }
                        }

                        if ($bounce_charge > 0) {
                            $response[$emi_payment->application_id][$emi_payment->emi_date]['bounce_charges'] = round($bounce_charge, 2);

                            /*if (isset($response[$emimonth]['bounce_charges'])) {
                                $response[$emimonth]['bounce_charges'] = round($response[$emimonth]['bounce_charges'] + $bounce_charge, 2);
                            } else {
                                $response[$emimonth]['bounce_charges'] = round($bounce_charge, 2);
                            }*/
                        }
                    }

                    $payload[] = ['emi_date' => $emi_payment->emi_date, 'emi_amount' => $emi_payment->emi_amount, 'moratorium_amount' => $emi_payment->moratorium_amount, 'bounce_charges' => $response[$emi_payment->application_id][$emi_payment->emi_date]['bounce_charges'] ?? 0, 'penal_interest' => $response[$emi_payment->application_id][$emi_payment->emi_date]['penal_interest'] ?? 0];
                }

                usort($payload, function($a, $b){
                    return strtotime($a['emi_date']) - strtotime($b['emi_date']);
                });

                foreach($payload as $k => $item){
                    $emi_dues['payload'][$k]['emi_date'] = $item['emi_date'];
                    $emi_dues['payload'][$k]['amount'] = $item['emi_amount'];
                    $emi_dues['payload'][$k]['moratorium_amount'] = $item['moratorium_amount'];
                    $emi_dues['payload'][$k]['bounce_charges'] = $item['bounce_charges'];
                    $emi_dues['payload'][$k]['penal_interest'] = $item['penal_interest'];
                }

                if (isset($emi_dues['payload'])) {
                    foreach ($emi_dues['payload'] as $emis) {
                        array_push($emis_array, $emis['amount'] - $emis['moratorium_amount']);
                        array_push($emi_irr_array, $emis['amount'] - $emis['moratorium_amount']);

                    }
                }

                $rate = (Finance::irr($emis_array)) * 100;
                if ($rate < 0) {
                    $rate = 0;
                }

                $irr_rate = (Finance::irr($emi_irr_array)) * 100;
                if ($irr_rate < 0) {
                    $irr_rate = 0;
                }

                $principal_oustanding = $loanamount;
                $principal_oustanding_subvention = $amount_disbursed;

                if(isset($emi_dues['payload'])){
                    foreach($emi_dues['payload'] as $i => $payloadItem) {

                        $emi_dues['payload'][$i]['interest'] = $principal_oustanding * ($rate / 100);
                        $emi_dues['payload'][$i]['principal'] = ($emi_dues['payload'][$i]['amount'] - $emi_dues['payload'][$i]['moratorium_amount']) - $emi_dues['payload'][$i]['interest'];
                        $emi_dues['payload'][$i]['irr'] = $principal_oustanding_subvention * ($irr_rate / 100);
                        $emi_dues['payload'][$i]['subvention'] = $emi_dues['payload'][$i]['irr'] - $emi_dues['payload'][$i]['interest'];
                        $principal_oustanding = $principal_oustanding - $emi_dues['payload'][$i]['principal'];
                        $principal_oustanding_subvention = $principal_oustanding_subvention - $emi_dues['payload'][$i]['principal'] + $emi_dues['payload'][$i]['subvention'];
                    }

                    foreach($emi_dues['payload'] as $i => $payloadItem) {

                        if (strtotime($payloadItem['emi_date']) >= strtotime(date('Y-m-d', strtotime($from_date))) && strtotime($payloadItem['emi_date']) <= strtotime(date('Y-m-d', strtotime($to_date)))) {
                            $dataItems[$application->id] = ['id' => $application->id, 'interest' => $emi_dues['payload'][$i]['interest'], 'subvention' => $emi_dues['payload'][$i]['subvention'], 'emi_date' => $payloadItem['emi_date'], 'Penal Interest' => $payloadItem['penal_interest'] ?? 0, 'Bounce Charges' => $payloadItem['bounce_charges'] ?? 0];
                        }
                    }
                }

                //$applicationData[$application->id] = $emi_dues;
            }

            $path1 = storage_path().'/app/Accrued_Revenue.csv';
            $file = fopen($path1,"w");

            foreach ($dataItems as $line) {
                fputcsv($file, $line);
            }
            fclose($file);

            Mail::send('emails.reminders.basic_reminder',
                ['body' => 'Accrued Revenue Profits on mail']
                , function ($message) use ($path1) {
                    $message->to(['sunil@creditfair.in','sarah@creditfair.in', 'accounts@creditfair.in'])->subject('Accrued Revenue');
                    $message->attach($path1, ['as' => 'Accrued_Revenue.csv']);
                    //$message->attachData(file_get_contents(storage_path() . '/app/' . $file), $file);
                });

            unlink($path1);

            return true;
        } catch (\Exception $e) {
            (new \App\Slack(new Request(['title' => 'Error in sending entire accrued report', 'fields' => ['error' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()]])))->send();
        }
    }


    public function uploadCreditReportFileToS3(){
        try{
            $file = storage_path().'/credit_report.csv';
            $file_path = '/credit_report/credit_report.csv';
            $s3 = Storage::disk('s3');
            $s3->put($file_path, file_get_contents($file));
            return true;
        } catch (\Exception $e) {
            (new \App\Slack(new Request(['title' => 'File uploading fsailed here', 'fields' => ['error' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()]])))->send();
        }
    }

    public function getBureauJsonForABFL(){
        $application_id = [73218,74043,75385,75611,75782,75786,75823,75888,76442,76444,76488,76753,76805,77049,77094,77255,77391,77451,77760,78018,78141,79574,80375,80611,80612,80671,80707,80842,81056,81579,81617,82648,82672,82770,83053,83057,83064,83224,83282,83297,83340,83382,83415,83478,83581,83656,83663,84007,84068,84107,84186,84568,84825,84925,85260,85275,85421,85456,85480,85496,85622,85763,85808,86197,86228,86436,86520,86933,87104,87437,87559,88413,88753,89015,89028,89217,91676,92128,93776,96006,96542,96605,96629,96785,97073,98197,98826,99799,100130,101271,101874,102554,102970,103426,103493,103712,103816,103951,103983,104110,104114,104149,104205,104222,104234,104237,104432,104774,104792,104923,105014,105027,105155,105792,105805,105846,105939,106002,106240,106353,106599,106662,106663,106779,106789,106794,106828,106844,106930,106945,106973,107120,107146,107176,107341,107360,107377,107386,107429,107452,107459,107469,107473,107528,107657,107659,107750,107789,107851,107899,107902,107950,107951,107961,108107,108109,108113,108153,108230,108294,108311,108337,108360,108380,108417,108470,108482,108484,108485,108491,108529,108531,108533,108534,108549,108556,108561,108567,108583,108628,108637,108638,108646,108661,108667,108675,108687,108690,108695,108704,108713,108726,108744,108760,108764,108768,108789,108801,108812,108821,108847,108853,108888,108891,108893,108916,109045,109050,109088,109096,109097,109099,109113,109131,109135,109154,109165,109172,109181,109194,109238,109261,109262,109267,109273,109280,109284,109295,109301,109305,109306,109327,109328,109333,109346,109358,109399,109408,109472,109487,109500,109503,109537,109540,109548,109557,109558,109563,109567,109576,109592,109642,109659,109660,109698,109722,109735,109748,109756,109767,109779,109787,109794,109807,109843,109899,109901,109905,109907,109942,109944,109957,109959,109961,109964,109982,110000,110008,110014,110019,110032,110035,110093,110127,110129,110130,110135,110137,110139,110145,110146,110155,110163,110180,110188,110202,110205,110212,110213,110272,110301,110303,110307,110311,110324,110328,110336,110391,110398,110409,110435,110443,110458,110461,110462,110494,110504,110534,110535,110537,110538,110549,110551,110592,110624,110631,110633,110643,110653,110668,110680,110688,110710,110714,110718,110728,110731,110732,110733,110750,110771,110774,110777,110778,110784,110786,110789,110790,110836,110842,110861,110866,110888,110937,110952,110956,110961,110963,110965,110971,110989,111028,111046,111055,111057,111061,111080,111088,111093,111099,111105,111115,111119,111125,111126,111127,111132,111137,111142,111143,111145,111146,111167,111176,111184,111207,111216,111218,111222,111239,111240,111245,111257,111264,111289,111301,111306,111318,111420,111426,111465,111470,111471,111482,111509,111522,111532,111573,111577,111582,111583,111593,111596,111598,111614,111617,111648,111654,111665,111681,111684,111694,111705,111722,111739,111760,111766,111781,111804,111812,111815,111821,111824,111835,111851,111859,111862,111896,111912,111915,111918,111921,111922,111951,111973,111976,111981,111983,111986,111991,112004,112016,112017,112024,112040,112066,112085,112109,112111,112113,112130,112135,112147,112149,112181,112182,112195,112199,112200,112201,112204,112207,112223,112230,112238,112254,112255,112259,112268,112281,112282,112294,112308,112312,112313,112314,112321,112325,112327,112335,112392,112397,112399,112407,112411,112420,112424,112430,112437,112442,112446,112449,112457,112462,112490,112492,112496,112512,112535,112543,112547,112548,112551,112554,112599,112603,112606,112617,112623,112625,112631,112632,112653,112654,112661,112665,112666,112668,112709,112714,112717,112721,112724,112737,112743,112744,112745,112746,112751,112793,112795,112808,112809,112851,112853,112856,112864,112869,112872,112875,112878,112881,112891,112951,112961,112963,112975,112977,112981,112983,112985,112988,113001,113010,113015,113017,113043,113054,113064,113086,113100,113125,113138,113143,113158,113160,113173,113176,113184,113186,113187,113212,113224,113229,113231,113240,113246,113252,113269,113280,113294,113321,113324,113327,113336,113339,113341,113346,113349,113363,113377,113386,113399,113440,113442,113443,113449,113473,113474,113509,113541,113554,113566,113571,113582,113612,113618,113623,113625,113627,113639,113643,113678,113695,113697,113702,113718,113726,113743,113789,113809,113810,113811,113837,113843,113885,113902,113907,113912,113920,113993,113999,114019,114055,114079,114081,114083,114090,114106,114114,114116,114118,114136,114150,114204,114208,114216,114217,114230,114241,114249,114257,114273,114333,114355,114364,114370,114375,114382,114392,114394,114424,114430,114438,114441,114444,114456,114458,114460,114472,114481,114488,114490,114511,114541,114575,114598,114601,114614,114617,114645,114650,114651,114685,114694,114744,114751,114757,114763,114764,114771,114772,114790,114817,114823,114832,114873,114878,114938,114954,114974,114976,114988,114993,114994,114995,115003,115005,115010,115011,115016,115034,115083,115087,115090,115093,115114,115120,115129,115131,115146,115159,115191,115199,115212,115213,115230,115245,115250,115255,115277,115281,115305,115340,115342,115356,115369,115379,115381,115386,115389,115394,115397,115425,115439,115448,115455,115479,115486,115519,115528,115555,115557,115562,115587,115594,115605,115613,115620,115633,115654,115656,115660,115667,115678,115682,115686,115694,115695,115700,115707,115722,115743,115747,115749,115751,115754,115773,115779,115782,115796,115818,115839,115845,115864,115865,115868,115869,115872,115887,115888,115894,115904,115907,115908,115909,115912,115915,115918,115925,115941,115952,115962,115965,115970,115988,115990,115992,116000,116007,116011,116035,116056,116058,116060,116069,116074,116076,116082,116096,116097,116106,116120,116122,116126,116135,116145,116147,116153,116156,116232,116257,116259,116260,116267,116270,116274,116284,116287,116289,116290,116297,116319,116351,116357,116360,116361,116363,116365,116379,116382,116406,116410,116422,116426,116429,116479,116495,116509,116522,116526,116540,116545,116549,116551,116581,116584,116589,116599,116601,116605,116607,116611,116623,116633,116650,116652,116653,116659,116664,116670,116671,116672,116705,116708,116724,116726,116727,116736,116740,116742,116748,116749,116756,116766,116768,116777,116778,116784,116795,116805,116809,116817,116819,116828,116829,116833,116847,116851,116857,116879,116888,116897,116901,116902,116904,116907,116920,116925,116929,116934,116951,116958,116959,116963,116964,116969,116971,116981,116983,116989,116990,116991,116993,116995,116998,117011,117034,117041,117042,117051,117057,117071,117088,117090,117091,117096,117100,117102,117119,117131,117138,117139,117146,117158,117163,117189,117200,117210,117213,117220,117225,117235,117240,117243,117245,117257,117260,117283,117304,117320,117339,117340,117342,117358,117366,117369,117374,117377,117389,117391,117396,117399,117410,117413,117435,117437,117438,117446,117448,117451,117458,117467,117472,117475,117476,117477,117478,117481,117488,117494,117514,117522,117523,117527,117556,117560,117563,117567,117569,117572,117582,117596,117597,117615,117626,117633,117646,117649,117660,117665,117686,117697,117705,117706,117707,117734,117735,117738,117742,117743,117748,117762,117768,117769,117771,117816,117818,117833,117854,117867,117897,117899,117914,117950,117956,117960,117964,117974,117979,117984,117991,118008,118033,118055,118070,118081,118089,118125,118128,118145,118165,118172,118182,118200,118211,118219,118225,118226,118231,118236,118247,118266,118272,118277,118305,118312,118314,118315,118320,118334,118335,118342,118349,118350,118358,118361,118387,118394,118416,118418,118432,118435,118445,118447,118461,118467,118469,118473,118493,118533,118542,118546,118554,118557,118558,118566,118568,118580,118588,118602,118628,118629,118631,118632,118649,118654,118669,118684,118685,118695,118718,118729,118737,118738,118744,118774,118785,118790,118813,118822,118836,118837,118854,118877,118882,118891,118912,118913,118920,118927,118929,118930,118956,118969,118978,118989,119000,119008,119046,119052,119065,119068,119069,119074,119075,119076,119081,119094,119097,119109,119125,119139,119143,119159,119163,119175,119209,119211,119223,119224,119264,119281,119300,119301,119328,119335,119388,119391,119409,119412,119413,119431,119443,119462,119472,119475,119492,119494,119498,119504,119510,119520,119543,119551,119567,119568,119589,119590,119591,119601,119604,119607,119632,119655,119661,119668,119669,119695,119704,119709,119713,119728,119739,119745,119746,119754,119755,119758,119760,119773,119778,119779,119781,119786,119803,119812,119832,119840,119844,119872,119875,119884,119885,119893,119896,119905,119908,119920,119937,119940,119955,119957,119965,119974,119975,119977,120008,120014,120020,120032,120038,120049,120055,120074,120083,120112,120120,120148,120151,120161,120166,120167,120184,120186,120188,120191,120192,120194,120196,120205,120232,120261,120266,120274,120285,120288,120298,120310,120318,120325,120326,120351,120371,120378,120388,120392,120394,120406,120418,120458,120478,120506,120519,120521,120529,120534,120536,120543,120560,120568,120606,120612,120629,120649,120659,120679,120698,120700,120708,120747,120749,120776,120802,120895,120908,120913,120920,120925,120926,120938,120947,120985,121010,121013,121017,121024,121057,121067,121083,121097,121105,121106,121156,121164,121184,121193,121226,121231,121240,121282,121285,121288,121290,121310,121311,121319,121320,121337,121338,121356,121382,121383,121385,121399,121400,121411,121413,121422,121430,121434,121446,121462,121467,121473,121482,121486,121505,121510,121514,121528,121545,121591,121607,121621,121622,121623,121635,121666,121672,121680,121681,121688,121715,121731,121733,121741,121751,121772,121777,121785,121788,121791,121822,121823,121828,121853,121857,121859,121864,121866,121874,121920,121957,121991,122002,122015,122024,122033,122068,122070,122083,122085,122098,122103,122158,122161,122179,122182,122188,122190,122206,122209,122211,122229,122236,122242,122243,122270,122271,122274,122283,122285,122287,122295,122307,122343,122344,122349,122359,122368,122371,122386,122392,122426,122439,122472,122474,122488,122494,122497,122503,122518,122539,122557,122563,122570,122580,122584,122592,122595,122607,122615,122617,122630,122639,122640,122658,122660,122664,122672,122687,122691,122701,122710,122712,122722,122723,122725,122727,122740,122782,122788,122800,122808,122812,122817,122821,122827,122828,122834,122852,122860,122861,122865,122869,122879,122900,122902,122909,122913,122923,122925,122929,122930,122945,122951,122988,122995,123000,123006,123007,123018,123020,123024,123028,123036,123037,123040,123044,123051,123053,123054,123055,123057,123058,123060,123062,123067,123084,123096,123122,123129,123142,123144,123151,123156,123171,123209,123219,123225,123241,123242,123245,123246,123247,123257,123260,123273,123288,123302,123303,123320,123326,123334,123342,123347,123348,123358,123375,123377,123381,123383,123386,123398,123429,123431,123444,123464,123469,123475,123498,123520,123535,123545,123547,123548,123551,123552,123560,123565,123572,123577,123601,123611,123620,123624,123630,123632,123634,123640,123648,123653,123660,123661,123662,123667,123668,123683,123693,123695,123700,123710,123711,123712,123715,123716,123720,123722,123723,123724,123730,123738,123748,123755,123767,123803,123806,123810,123815,123818,123826,123827,123838,123851,123859,123863,123867,123875,123876,123885,123901,123909,123912,123923,123955,123976,123985,123990,123993,124007,124009,124011,124019,124023,124029,124040,124042,124047,124055,124058,124066,124070,124071,124076,124077,124087,124102,124105,124156,124162,124163,124173,124179,124182,124223,124235,124239,124242,124245,124292,124298,124318,124319,124321,124356,124370,124375,124391,124394,124400,124401,124406,124461,124465,124468,124471,124475,124480,124481,124490,124495,124496,124506,124507,124517,124531,124535,124543,124574,124575,124580,124583,124584,124592,124595,124605,124612,124628,124630,124632,124646,124650,124652,124681,124683,124686,124693,124744,124759,124767,124768,124771,124772,124783,124801,124823,124837,124843,124866,124902,124905,124914,124917,124924,124926,124939,124962,124974,124976,124977,124982,124993,124996,125013,125029,125032,125061,125062,125064,125076,125114,125116,125117,125119,125128,125158,125159,125180,125186,125188,125197,125199,125202,125210,125211,125227,125239,125241,125252,125261,125312,125333,125351,125353,125358,125361,125373,125412,125443,125446,125466,125481,125503,125524,125526,125531,125546,125549,125606,125608,125614,125639,125652,125655,125660,125668,125669,125672,125674,125682,125683,125692,125694,125705,125706,125707,125742,125754,125763,125765,125771,125772,125778,125780,125794,125805,125811,125812,125847,125850,125852,125859,125863,125873,125874,125887,125894,125920,125922,125924,125925,125942,125943,125947,125950,125951,125955,125960,125982,125989,125992,125994,125996,126006,126010,126018,126024,126041,126048,126055,126063,126069,126070,126114,126116,126122,126152,126156,126162,126170,126171,126174,126185,126186,126196,126204,126205,126206,126214,126216,126218,126223,126243,126246,126250,126261,126292,126320,126331,126332,126350,126351,126354,126376,126378,126379,126384,126399,126401,126426,126440,126445,126490,126521,126551,126554,126557,126558,126587,126590,126598,126607,126611,126613,126641,126644,126648,126649,126651,126682,126694,126725,126748,126755,126756,126764,126769,126775,126785,126791,126792,126795,126813,126817,126819,126820,126821,126823,126831,126833,126836,126838,126846,126854,126855,126869,126872,126874,126878,126879,126891,126928,126930,126947,126951,126953,126954,126958,126968,126991,127023,127032,127040,127048,127053,127059,127093,127108,127119,127152,127161,127164,127168,127170,127171,127186,127201,127221,127223,127224,127233,127241,127247,127261,127262,127306,127314,127319,127322,127324,127334,127335,127345,127364,127370,127385,127388,127392,127393,127396,127405,127406,127435,127442,127450,127460,127461,127463,127469,127533,127555,127578,127588,127595,127711,127754,127777,127782,127950,128878,129423,140582,140962,140975,140995,141008,141050,141318,141345,141379,141380,141476,141508,141824,141831,141879,141887,141970,142342,142344,142356,142385,142447,142748,143335,143344,143386,143602,143920,143928,144071,144133,152264,157296,160807,160832,160834,160911,160937,163103];
        $report = [];
        foreach($application_id as $app_id){
            $file_path = $app_id.'/'.$app_id.'_response_experian.json';
            if (false !== $file = Equifax::readFile($file_path)) {
                $report_data = json_decode($file, true);
                $report[$app_id] = $report_data;
            }else{
                $report[$app_id] = "";
            }
        }

        $report = json_encode($report);
        Storage::disk('storage')->put('ABFL_Bureau_reports.json', $report);
        $time = Carbon::now()->toDateTimeString();
        Mail::send('emails.reminders.basic_reminder', [
            'body' => 'Bureau Report in JSON Format'], function ($message) use ($file_path, $time){
            $message->to('sarah@creditfair.in')->subject('Bureau Report');
            $message->attachData(Storage::disk('storage')->get('ABFL_Bureau_reports.json'), 'Bureau Report'.$time.'.json');
        });
    }

    public function put_bureau_report(){
        $s3 = Storage::disk('s3');
        $s3->put('1/1_response.json', file_get_contents(storage_path().'/app/1_response.json'));
        return 'done';
    }

    public function OLDBureauDataSave(){

        try {
            $date = Carbon::now()->toDateTimeString();

            $bureauData = BureauLog::get(['application_id']);

            $ids = [];
            foreach($bureauData as $ach){
                $ids[] = $ach->application_id;
            }


            $data = ConsumerApplication::with('creditReport')->whereNotIn('id', $ids)->limit(100)->orderBy('created_at','desc')->get();
            foreach($data as $val){
               if(isset($val->creditReport[0])){
                    if($val->creditReport[0]->applicant_type == 2){
                        $app_type = 2;
                    }else{
                        $app_type = '';
                    }
                    $file_path = $val->id. '/'.$val->id. '_response'.$app_type.'.json';
                   $fileRaw = '';
                    //(new Slack(new Request(['title' => 'readFile checking', 'fields' => ['file_path' => $file_path], 'group' => Slack::$STAGE_TESTING])))->send();
                    if (false !== $file = Equifax::readFile($file_path)) {
                        if($val->creditReport[0]->bureau == "equifax"){
                            $bureau_array = json_decode(str_replace('sch:', '', str_replace('soapenv:', '', $file)), 1);
                            $unique_id = $bureau_array['Envelope']['Body']['InquiryResponse']['InquiryResponseHeader']['ReportOrderNO'];
                            $bureau_array = json_encode($bureau_array, true);
                        }else{
                            $unique_id = '';
                            $s3 = Storage::disk('s3');
                            $file_path = $val->id.'/'.$val->id.'_response_experian.xml';
                            if($s3->exists($file_path)){
                                $fileRaw = $s3->get($file_path);
                            }

                            $bureau_array = $file;
                            if(empty($file)) {
                                $file_path = $val->id . '/' . $val->id . '_response_experian.json';
                                if ($s3->exists($file_path)) {
                                    $bureau_array = $s3->get($file_path);
                                }
                            }
                        }

                        //echo "<pre>";print_r(json_decode($bureau_array,true));die;
                        BureauLog::insert([
                            'unique_id' => $unique_id,
                            'application_id' => $val->id,
                            'bureau_name' => $val->creditReport[0]->bureau,
                            'raw_bureau_data' => $fileRaw,
                            'converted_bureau_data' => $bureau_array,
                            'applicant_type' =>$val->creditReport[0]->applicant_type,
                            'created_at' => $date,
                            'updated_at' => $date
                        ]);
                    }
                }

            }
            return 'done';
        } catch (\Exception $e) {
            //@todo: report if file do not exist on S3
            (new \App\Slack(new Request(['title' => 'Old Bureau Data Upload Exception', 'fields' => ['error' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()]])))->send();
            return false;
        }
    }

    public function create(Request $request)
    {
        $first_name = $request->get('first_name');
        if($first_name != null){
            // Status OK
            return response('{
                "status": "OK",
                "data": {
                    "id": "CFLD98745",
                    "product_name": "Master Digital Product Design: UX Research & UI Design",
                    "amount": 58000,
                    "tennure": "2 Months"
                }
            }', 200)->header('Content-Type', 'application/json');
        }else{
            //Status Bad Request
            return response('{
                "status": "FAIL",
                "error": {
                    "message": "Failed to create the Customer",
                    "code": "CF400220"
                }
            }', 400)->header('Content-Type', 'application/json');
        }
    }
    public function generateOtp(Request $request)
    {
        $number = $request->get('phone');
        if($number != null){
            // Status OK
            return response('{
                "status": "OK",
                "message": "OTP sent successfully"
            }', 200)->header('Content-Type', 'application/json');
        }else{
            //Status Bad Request
            return response('{
                "status": "FAIL",
                "error": {
                    "message": "Failed to generate the OTP",
                    "code": "CF400219"
                }
            }', 400)->header('Content-Type', 'application/json');
        }
    }
    public function verifyOtp(Request $request)
    {
        $otp = $request->get('otp');
        if($otp != null){
            // Status OK
            return response('{
                "status": "OK",
                "message": "OTP validate successfully",
                "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2Nzc4NDYxMjUsImlhdCI6MTY3Nzc1OTcyNSwiaWQiOjU4NiwibmJmIjoxNjc3NzU5MTI1fQ.XBinEZqrMWUYF_SreBqVXCm1FrAjacHmMY-nT6coNuk"
            }', 200)->header('Content-Type', 'application/json');
        }else{
            //Status Bad Request
            return response('{
                "status": "FAIL",
                "error": {
                    "message": "Failed to verify the OTP",
                    "code": "CF400218"
                }
            }', 400)->header('Content-Type', 'application/json');
        }
    }
    public function customerDetails(Request $request)
    {
        $id = $request->get('id');
        if($id != null){
            // Status OK
            return response('{
                "status": "OK",
                "message": "Details updated"
            }', 200)->header('Content-Type', 'application/json');
        }else{
            //Status Bad Request
            return response('{
                "status": "FAIL",
                "error": {
                    "message": "Failed to update the details",
                    "code": "CF400217"
                }
            }', 400)->header('Content-Type', 'application/json');
        }
    }
    public function uploadDocuments(Request $request)
    {
        $id = $request->get('id');
        if($id != null){
            // Status OK
            return response('{
                "status": "OK",
                "message": "Document uploaded"
            }', 200)->header('Content-Type', 'application/json');
        }else{
            //Status Bad Request
            return response('{
                "status": "FAIL",
                "error": {
                    "message": "Failed to upload the document",
                    "code": "CF400216"
                }
            }', 400)->header('Content-Type', 'application/json');
        }
    }
    public function updateDetails(Request $request)
    {
        $id = $request->get('id');
        if($id != null){
            // Status OK
            return response('{
                "status": "OK",
                "message": "Address details updated"
            }', 200)->header('Content-Type', 'application/json');
        }else{
            //Status Bad Request
            return response('{
                "status": "FAIL",
                "error": {
                    "message": "Failed to update the details",
                    "code": "CF400215"
                }
            }', 400)->header('Content-Type', 'application/json');
        }
    }
    public function updateEmployement(Request $request)
    {
        $id = $request->get('id');
        if($id != null){
            // Status OK
            return response('{
                "status": "OK",
                "message": "Employment details updated"
            }', 200)->header('Content-Type', 'application/json');
        }else{
            //Status Bad Request
            return response('{
                "status": "FAIL",
                "error": {
                    "message": "Failed to update the details",
                    "code": "CF400214"
                }
            }', 400)->header('Content-Type', 'application/json');
        }
    }
    public function getEmiDetails(Request $request)
    {
        $id = $request->get('id');
        if($id != null){
            // Status OK
            return response('{
                "status": "OK",
                "data": {
                    "amount": 58850,
                    "emi_summary": [
                        {
                            "tenure": 3,
                            "emi": 18335,
                            "interest_rate": "No COST",
                            "total": "55000"
                        },
                        {
                            "tenure": 6,
                            "emi": 9166,
                            "interest_rate": "No COST",
                            "total": "55000"
                        },
                        {
                            "tenure": 9,
                            "emi": 6100,
                            "interest_rate": "No COST",
                            "total": "55000"
                        },{
                            "tenure": 12,
                            "emi": 4583,
                            "interest_rate": "No COST",
                            "total": "55000"
                        }
            
                    ]
                }
            }', 200)->header('Content-Type', 'application/json');
        }else{
            //Status Bad Request
            return response('{
                "status": "FAIL",
                "error": {
                    "message": "Failed to get the details",
                    "code": "CF400214"
                }
            }', 400)->header('Content-Type', 'application/json');
        }
    }
    public function getEmiSummary(Request $request)
    {
        $id = $request->get('id');
        if($id != null){
            // Status OK
            return response('{
                "status": "OK",
                "data": {
                    "emi_summary": {
                        "tenure": 3,
                        "emi": 18335,
                        "interest_rate": "No COST",
                        "total": "55000"
                    },
                    "fees": [
                        {
                            "type": "processing_fee",
                            "amount": 350,
                            "payment_link": "https://rzp.link"
                        },
                        {
                            "type": "advance_fee",
                            "amount": 350,
                            "payment_link": "https://rzp.link"
                        }
                    ],
                    "product_details": {
                        "product_name": "Master Digital Product Design: UX Research & UI Design",
                        "amount": 58000,
                        "tennure": "2 Months"
                    }
                }
            }', 200)->header('Content-Type', 'application/json');
        }else{
            //Status Bad Request
            return response('{
                "status": "FAIL",
                "error": {
                    "message": "Failed to get the details",
                    "code": "CF400213"
                }
            }', 400)->header('Content-Type', 'application/json');
        }
    }
    public function getAgreement(Request $request)
    {
        $id = $request->get('id');
        if($id != null){
            // Status OK
            return response('{
                "status": "OK",
                "agreement_link": "/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAABkAAD/4QMpaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/PiA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJBZG9iZSBYTVAgQ29yZSA1LjAtYzA2MCA2MS4xMzQ3NzcsIDIwMTAvMDIvMTItMTc6MzI6MDAgICAgICAgICI+IDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+IDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiIHhtbG5zOnhtcD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLyIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bXA6Q3JlYXRvclRvb2w9IkFkb2JlIFBob3Rvc2hvcCBDUzUgV2luZG93cyIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDpFNUI4Qjk3ODQzRTExMUU4ODU5RkQ5RDcwRTQ0MzNBRCIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDpFNUI4Qjk3OTQzRTExMUU4ODU5RkQ5RDcwRTQ0MzNBRCI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOkU1QjhCOTc2NDNFMTExRTg4NTlGRDlENzBFNDQzM0FEIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOkU1QjhCOTc3NDNFMTExRTg4NTlGRDlENzBFNDQzM0FEIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+/+4AJkFkb2JlAGTAAAAAAQMAFQQDBgoNAAANQwAAHkwAAClTAAA3SP/bAIQAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQICAgICAgICAgICAwMDAwMDAwMDAwEBAQEBAQECAQECAgIBAgIDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMD/8IAEQgAWwCVAwERAAIRAQMRAf/EAR4AAAEEAwEBAQAAAAAAAAAAAAAEBQcIAgYJCgEDAQABBAMBAQAAAAAAAAAAAAAABAUGBwIDCAEJEAABBAEBBQYEBgMAAAAAAAADAQIEBQYAIBESEwchMTMUFQhAIjUWEDIjJDQlJhcYEQABAwIEAgUFDAQJDQAAAAACAQMEEQUAIRIGMRNBUWEiFHGRMkIVIIGhUnKyIzNzJBYHQLFi0xDwQ1Njs7QldsHRgpKiozR01IWVZpYSAAECAwMGCgcGBQUAAAAAAAEAAhESAyExE0FRYSIyBBAwcYGRwdGS0hTwobFCciMzQOFSYoIFIPGiQzTCU2ODJBMBAAICAgECBgMBAQEAAAAAAREhADFBUWFxgSDwkaGxwTBA0RDh8f/aAAwDAQACEQMRAAAB7+AAAAAAAAAAAAAAAAAAAAABz1Y7I4yQnpW+lWt8rxxwy98T789TckSpvkfz1M3bMq7TnOEpSn9QFq8MKvcQAAAAOZTBa3BODdabc3NHUyg3NW15VNt2z7cwXlxc0z2K3CSxxI1lMrWQ4bsfXRbnzvVe4gAAAAc2GC1uCMF68atiK8lcMUmx2w6xWVPOglLcpWsjFdUqknQ9JLedoLkulx92eu+2/niq9xAAAAA5oMFscL4B2Mjz07qzN1pmuTx5vlV8Ka5Wn1ogMJK7A5M9E2zpi5Vnmi9f9r/PpV7iAAAABzXjlrcJoJ2I+IvLvVI76xJ0tna6i/N+5UzMq0dBque4Hc3ulNstrzi3+vC2/n+p9xAAAAApDALXoxzF1RsTzFq1vt4QrNJHdSuqPpBOR8UStw1TCzFVVSxrI00r5l6Eus/nsoyxAAAAAo3BLejjkW15+jlYeezq3qDZE0yeUq5OmgShyeoMdUtvK1qrrLRdV0WtW8O23Y/EKjLEAAAACPWh1jmIOyTZhAcqfVmHv647f1172dQmyDZ0aKV2NtS5brMT6IZ++AAAUXZLQ1HWp3BQ1a5qXJtaqwrhEqYNFg7XvbmPWpvE7162ebK0tsvjjQ7zstjEaJ3dy2aZyVxq1jnCgIYSvjJrVyapZsw0jUv2/YijhO7vexImx2/DzeN7doyd0d9qRo1qnPLQ147pwWR7IAAAAAAAAAAAAAAAAAAAP//aAAgBAQABBQL4b3H31tj2JF6p521cO6p2ORVLsxuW6dmVvwOzua0ddmmR2tOzMr3S51coi5vkLtZX1RycT5PUTMXQg+Dte6dOLB5bOLWKXTsdtguQwAC+XJrYcuR0rA30bJce9GNyk4Liy9NjSDPKWSv7EHg7Xue7cNIxH6eJqN6XZW2XEya23MIJW66ZkVK+wZHmx7GEauJlNhzDqvHojv2gPB2vdGu7ClE1qH7WYfUzpNmRiSwFFvJ0vdGHBnuXiyAXq0G9eZs5neVFQAPB2vc/FkS8NkfK6lri3UyJBh1sWJa1j7xtcCG3qI3/ADChy/LqiSTIWS0yvGnXEdvE9xEdJih8Ha65/RrDHazKNRekEjGoeUyzjK3WF3K3EDqE1fvDDaxsRpjldLqJZ7wF10p4yTYsaHSi8La67tV1DitKaqRXtCKRdHubbkS2pUWRqydlrA3GZ2uSVscc6fZSWe3+0IC+KJz2Z5RLUxBeFtZDjNZk4CdNKUil6XURgp7Yumiab7a+nrNf83dPuOV7cOnkxE9sPTJuv+Yumeqf29YHRTP9X0mj9KMclx2pwpsZR1LfT9TrKflJLCnt7rMMqw+vy7JMLrM/uzYx0syc+T4nkWXZZX5DlWV5HFCTLsmTEuoeS/amJdM8mJlOIHvLi8bmOeTEnRp2V5TkszLcohMzXJ8hgF6cSMkNM/CR0/xOXDldMMPnWQceqo97RUNZjkIXT/Fg19bjdPT2EzpjiNhZzMBxifqy6eYtauB09xsSVWOVFJLt+nWK3U/7GxbmS+neLzIf2HiiY8Ppzig6ZE3J8J//2gAIAQIAAQUC+GnqqA4yLqxNZwzNuLDf63Y70tLdyyLGdFlOtZ+vUbHXqE7Vc+W9GFNzNux/jpqbHSUA4uWQi9tXEeEV6RW2ojKTXEvFEj+YI1qNaPxtux8BNb9XMDetbC3uRdZA3+zGjm6buVa8HKFpnibdj/H36TVhJGEa8KaR3ZkHG6yEVEZBc5ksCtezTPz7do9rIze1JUhsURClO9BygQjPK99N9Pl10CQx8NYrK6wSMTTFRhdvJfpUWdJiONYNnurIyN07U6Ig30/8CUTjdwNVksA4JImQrww3vNYJ3bWRLurZXC9ib1Vo0EHe3Rx81tY5zYTI7lVrGN1lcdr4o93HUl45Sd21NhBnhTFqhukxipa7yMfXp8TS10RUHWQx68jH15CPo9TCkj+2KnTcaq2P2SSOGS/j3tVxCCaR4WmfyoxOYIhCNeUj0TmP5cgnKFHJzBcTn6MZd/6hC8wiaMR6aj8zf+HJGqLHEruBvE1jWJyR7kY1qrHErlENdOAN2kANNNY1quAJ68oelAJU5IuWgBIz4X//2gAIAQMAAQUC+GxcI5FitPXtQVPDI9KCvdpMfgb0xuLvHX1SWLqCs0uP1+koqxNPpKpFlUtUKEvftYd9WMm/T0Vumva7RH9tfGcNmQKrLSpt/UBKRVf2Na1dWPbWL37WHfVnt36VqJpv6Z68HzNKu/JW/wBiIpYxYUoU0cpyo5O3U1f69e/aw3tt+BNE/K2Mh9RjdqaypXLZDXsoOcGZuXe3U5q+SXv2sO+ruci6H8+kbwtmRDgB5lTLE/KasjzHw6xsVpUauk3uW0lBSvXv2sOTfbF5YWwcnht1WoKQJe1J0f06VD7UYJWMGNGis7SNWFgWseyl2gmtrV79rCuy5vLJs527e6ON0JobUmp0cFpEqhb0825SGfKIl9Ha6OP5XDtPP1K9+1EmGhP9Yl69Xlov3Tca+6rrQ8tuxONmN4fSZXcpr7suV0XJLMzfWJWmXk0a7MKlQ9IAcTgOEEGFYHhxbItVF9Qu4TYc6HCgliQYUR7/ACMTztPC8/YXMNIM9AAjLW1jFG5kOHCSFDJqthxiatvKcv8ABtlNaRlxYDCskzo8iQaURbKapCyjmEy4sBAZYzB6DaTgafaTH6LJOdke2nxhefmbmWs4ZPUp3m3Ws50j4X//2gAIAQICBj8C+zRBIMVCd8PiKgx7sA/md4lCc95/iUJvW/xKWm6Ljda7xIbo6o4vw2m915vF/Qtt8Pid2rbd3ndqtqv7zu1Y1So+GTWd2oAvdCOc8Rz8Bp+8pSrFi1/rH1DtX/U1QyjgDTd1KDdlN5eI5+HHYF5iqNQbI6+CY/7bUHhRCt2z6Q4By8Rz8OG8TOdk60HU/pG7s5uAERNPDbyKXKg+GoL/AE9iD2bJ4By8RF5gIqIuWK/mGcovqfUKIsjGPIvmElN+IoursA0iwowtpk3+wLDqH/zuPQc/bwNxCBb08Q9FzHEM9Si45Lh2LzD/ANPbwWbKHxOWELhepHXFHHeG0/dyuPMvLU7MzjfydiZUeYmPEOWpcoNvim0sjWgLMpSi2GuKrx61F1nBT3j3mPhzH7xwU7p48R5evHD0WLZd0qYMMfTQrlsqEqJa29XK5YVUai2D6uxCoxrg8af4gyOpl5Td6aVVeHkSdFylJIGGCiQ909vqKdvL7MgHppVtrxYU5wLoB45IWKrabHN6k4gulnAEb9KLsqBO1cU97nPsdCDcnKogvlw42Z9KwnuhBgNmUqSaMtUCPUqsCbJU6M2Hkmv08JaRYVMRap/egoNuQbCwGKLheVMRajEXn2IxG1fzLkMUS3KpiLVdkhzIAi67+awoaiLIWH7N/9oACAEDAgY/Avs2FVaHNLcoByjOvps7rfCi0sZ3WeFQlHdZ4VCH9NPwKVjYuN2rT8Cd+216bcSGqZWW5xs9C+mIfCzwr6be6zwrWps7rfCpBSZ3W9iqVmUmThv4W+HiP09Y4MRt6itW5CpW+ofV96dCwwBj0rDqf5LL9I/F28E7lE3qtnl6+I/T/qbwQKh/bKxqmyLh1qKmOWkzrTa9H6jShXp2HKMx9LkKWUX9nBUB/DxEPy9Y4LFrDUWC/ab6xkPUdPBBsZBSZaoZVi09i6GRxyd2/wDmou28qtVX4eIByS9YVilClC803aBt0BRJsTviKDA0YpyixfLM1HIevn9kFEX8FWnT1qsuS4W5TxEPydYT69Uy0W3o094Y5jSdq/pQ3uiQ6kblK61pUP7TrkeVf8tT1Myn9V3IpTsrDcYuvCwd5i0O2bbCdOnMqoZCEOviP0dYWBu/+Kw945+TN0qAvPWmjdSWSgCy6xQ3thhnb2ItokOeLs6ONsM2ubJym5GrD5h9WYcyi93p6ZkytDWa6HTwVaVSHm2st/MM/bxBfRhFzYW5l7ndUwkjyLb9OlQxPTpU9OoA7kRDntAJiYNhE5zBQDx0fetsenOpKjmlvIrmd1TNw4/D/FU3ktcd6dF1MwslpbcdLomHwrcN2du7KnmRrG2e2oWxBByDQm1mMZUe3fKrIutma0CEfaqVN+7UfKBtNzgAYmdgLrY6YtVD9l3UTujPUqQtlOsBzU+lxRwmlu7VAHsBvDXZDpbdzLdqTmUMSru9Qw1sVzwXyyu2RcL1uE1NhxKFYujcS2eBdyQC3enVp0sZ+7VHvDI4Z1XGmW26LYGEUyiQTSGs6H4W2npuGkp1NgLaDoPZG+V1oHNceRbvu1Klu78Wg2oX1jCcu91hiJYXWWxRovpbvj+eNNwfHZDYlrLYki2GVHf93pCrPvL2NxIkMa21oIs1nA5cybvOEGmruFWpJka5sQHNywMIhft2IxpxTXmj70uzHQFRwsHzsHYmFsX6uiMIxho4adVryH0mgN0AaLsvPlQ3em+VjQQIBswBtIDoTC/IUN1J+QHF0NJsPsWLXMXwA5miA9SfVn+ZUpyE2bNlmi4JlGq6LKcZdEbTam7vTeAxrS0arZgDeA6EwvzqnI76TXNbYLA6M3TEqnhv+jNJYDCbaFuQ5k61rZ2SmVrW2RjDVAyplOqYtpghvITH2oUaT/lt2YhrpfhmBl5lCc/VxNM/4o3xVSq1wjVMXCVpaTnlIljzLz2IfNZ9F0IXQhZC5N3mf5tMQbAABoOZsIZTk+zf/9oACAEBAQY/Av0axTbPPkwHz3VEjulHffY50c7ZdSJh5Y7jThNKYCtK8UTAOJuG4MqCiY0uF1VFIFRU1Cc9RIVXii8cc92a/wC0WS0yW0kzRFV+MjYyshr8CphD5rlOBapdx+Ck3GrmcM/+LumdPLOwTj8jkNtCpul4y5dwESqlq8dRfJh+9x5Lox2bjNimysqerrUdl1BjyS++VVCRe/8AFXC1mu6kSqp4q40/tmMpr9f+Ynf9ZhdE6T8rxcynm8VjwMa7zm1ChyibmzhXUv1McSCUJD8c+yidOHyb3DemXRRvS6F3uyGOp5sVVNU4h9EurDVc/owz/wBFPd2BP/cIPwWu7riiLVUp3fgywzMUl8M8Qsymq0HSvdE16tNaL2L2YB5nvtONo42XHUh8PN09uF5i5r0ZZda4OJCX7kwXfcFcpTw+sn9C2vDrXPEgFRDRy6XASaVEVCFSRFr1iqLngnmRXwElfolVVXkOdMU17OIdaeTFerLPp7fJhx0RRT+rYb4a3z9AfJ0r2JgzdLmOEREbi+u4a6jP31+DD+WdGv7Qzhn7Jv5qe72//i2N8FnvWMsutfLhRLNOtf454e27KdrKiCrkAj4usesHaSJ8KduFgRTXnGFJbor6DZJ9QKp6ziel1Jhf1YebFFqN0mqRJ0IRjlh6FK7zTzdD66p6JgvQQFmi4djPEhjmTLyJRHma0E+wk9ZOhcJoL6MEMY6fsrk5I8ryppH9hO3GrVn1YeFepv8Ar2sM/ZN/NT3e3v8AGENPPabwmB6a/wAaJjuotf1eXAXKG6UIbaupZelF1PKP0bACuR55l1J72CmIPLf5hNTmePImjm6idPKerzG1+IXZiiIq9iIqr5kxL5rjISPacz7u64229p1JpJGnCE6L0ZZ4U/RTjxrTqVE4UxJjuOctGxU0fFRQ2iLLlinVI9EuzPow+zIa5TzZ6Db6ApkKB1taPR7MZ07MPdX0X9e1hn7Jv5qe7263FYOQ5+MrevKbzcJPZt2TuD6658MK2dQcbyVtwSbcBa+uBUIVwMFhaevIe9VhlF77h9vQKdK4aixG+XFjhlqyLrcdcLpI1zVcUPX4SS0kWSaLRqQ4BVYdUaaqs1VBLLUi0wiMsgFaEJgAprFaU73rIqdOJxV73hoaV4U7hcFTqxGj2i6SpAm4IDbZpnNhO16FaeUiaSnSCiqYCGQgzcAEXZjAFVs5Gj6TkmWZtMcNPFM8eLih/ecUFIaUTxTKVVY6/tj/ACfm6caaaVFc9SKi5LQkVOKKmH2obTspweRzSYBTZjp4hrN9/wCrDyVrhr7MPmp7vaq/F3lby81vumI8CZbWpkx/uMPs/QzGyXhpkN6TRB4rXu40WJ8LkTh82SkjQ1NNxE9EHcmXmmkyBO4vT04dtJCUd+OWm4NEig6J5EMdwfVoKoS9eWOlO3pRehU8mPZkhz77ARVbrxejdNOtWq1+T5MXAepmIKf6pYdvkge8NQhIXX0uZ+fzdePENKSOAetDT1SRclrgUt8NyXKDS1M5dG4kZ6n8pI/bTvIiZ0XDl7mDrFaHOtsVSZi6umUemjz1fXzROmnHEuLGYbYaRoaA0KCCUeaWqIKImG/kB81Pd7ZRKqq7vgUQUqSr4C50RE6Vx4mYBJOkBTlrxjMLwaRf54+J+bBOuKggy2b56uGhgFdL/ZHFwuc8iN+4zZErnh3JA890jFFNE0vAAKiIhoWSY1CHjmlT04/ckgn9JFVaH5QXDFwhnpfiuISgqKJKKL323GyotFTJexcHIA0ZiTYNrmmbq0CM1IAiVs3OlQKo+9gYNtE5YMDywVB0AtOJqmS95c89OFq74dv+bj5FT5eVPepi72bUvKuNtScI0U1KTb3hEjTj3yYkrXyYrpyVNJVGtehRWuSoqYnSGRcW3vinKyX7q8TzVY5r8Rc1BerLDf2YfNT3cNi5eJRLfObuMQ4sgozrUtpp5lt1HBzqIvl7+FUrnuiq8VTcE1P8uHI53XdatOtOMmn4im5g6Cgae+JYyc3Snk3C/wDusdyZvAfk7mlJ+pvHNWZu4z+M7uJ91f8AeMlgRed3NQQEKBfDb1CFdOvSwmrTqxRF3Mn/AH579zj0tz/+fe/c4SfbZO6WJItuMoabhkJQHkoad1sVzxT2tuz/AOjn/wCfDkWXO3LLjPU5rEm+ynmnNJIQ6gOqLQkrhBTgKIie9l7mw2IJcYLFESNbtxgclgH1uW59Q2dxtgi5zrVuWKKvEOTYyO90Y/Ny8Q943G1/gaUw9abe6EGRYnGW9uxro9Emx34yvEMp6o6hdEh1ZYk2527Xaxw7l+Wm0twBHtrrTL1suNwnyHJTkYn2H0Q3G20bXUi9zF9ucfe+4l3D7R3BbbQUqRDWAy9Yr4+zBVxhuG3r8Y1ERp/UqppMlREWmN0/mbeHjt8BiEFg25ttHm0je245JCnT5BUTW5Jvxq03UqNx2lXpxGcuEliVe7Q/Isl8ejvMvsvXG3loWU08wqtOszWVB0SHurqyxvebGu+5m4e3N3WKK24DVvkbQtdokjbCuIXts21uS1afNRVqumqZpj82ljXu4x/Y+6tjwrUcbQbtvhXJLd49qCHKPUUlHyyVCqS43lNt9/vb1rtu79r2ew3O7sxoe5AMrhCY3JAuDAR2XAbade5Yc1oHFRV7MXa6g42E1WxgWvmGDYLdbiaRIOo3O4INPO8wlXJABVxb5kp9p+6wSes16cZcB5o7raz8NJfbda+jdamIIvgQ5ELiUxu6/TNy7tssexboum2rZadn2pu4ram7S3r9r7gi+DlSJrcuiuLrUGRboica4iz4u6t1sWpz8soF+tr9lgMC3KvcmccWHPvUR2LIjwIExwhFxCIGxUkSuIe0bpfZO2itOybHfryu31iNzb1eLmrjMrwk51mSDVqt7rNF5Sd8zTOmJlhcvj8xzbn5q7P26N/AWWJN0tF3AZL9tuPJbGOcqMh8t5RQdWXBcfnKkO8zoo2KL+X5WjkkP92rc5AjcCiIrZd+UHFF1VxuNJ724pW2AK2fhyXu2EEG+uvkw6t3RWkjxXjgA7y+UTgIta0qn8N8hyrUEgdxzX7hdX3XXinOy3uT9IzOU/FROQkcOULRCLenu0xLuc2FMluT3osmfEfu1zK2T5EJhiNGdm2xJSQpZA1HH6wCRVTNMSdxtMKF1lWyLZ3nkdc5XgIbzsiOyMfVyA0OPLmg1wVvtLJMRTmzrgQG86+virjKcmSz1vEZ0N95VpwToxbLUkFw7daby7f4sN2XJeZW6PPSJCvSQcdLxYA/KIxbc1AK0yyTF1udsiJDkXrwa3AGCIIjrkFlY7DwQ0Xw7D3JXSRAKKdErWmJ10mRJz7lzms3C4wyu9zG1T5cYWhYcl2sJQwpCN8ge6QKOXDF98TCdP8AEdxtV1u1JksOfNsqsLb3A0upyBa8MNRCiF04vpSob4/iR22yLuEadMityJdoMThTRbYeAWJgaEQnA0kaImquIYvDc7mEC6e2YwXm83O7NjPSIcIHSCfKfFwGmHS0AVQE11U1Z4u021xUhuXt+PKuDbRmkU5EeOMUHmourw8YzZBEPQI66VXPEm5yYsyPLngDVzK13a52kLs02OgAubVulxmptG+7U01acq0w4fsljQ5tpNoFGQnUh/h4T5iW8YiHyBFC9ZE19uLPEcjzgOwxfA2m5Rrtc415iwqIKxPazEoJz0dRFE0OGSZYc2sloa9jOveKcZ5sjxDk7mjI9onP5vjyuXPBD5/M5tU44uliWDIfiXt+NJu78q4z5NyuL8Nxl2Kcq5vSDnHyFjigpr0iKUpmuEROCJT9F//aAAgBAQMBPyH+to9HfaQa63uMp2lLgacUkFOAZrTXIQiL75zl6Gooe2JEYJSbUDwaJjHSK9LTDIqoWobwmU1ZSReq0OJzbKBKhaivjOLBILgerZMFAW2Eg8SRWAqBctmpnoZyHIpJyHZpQtRONVSl1MqsyravxqXy9/YvTBjGnAwbbERjxzosTB194HDIUolCC12Tp0GOyCTCeWydVzrLuoLSmYImh+sxptLI/SGkB7wBkpkCF3ZGxuvawWei6Ase2pOKv2AsJh3tJ+Gcl5i+GsH0+iGTP+yH+ARkGsX35R9zGkOhCwptdzeSZzEAtPcmGVJfko2voX3Mof5niMjznW0jbVEINHs4wmymA2l5S/GU6G7HO20MLkwe8EylA1p/o8RFvWWVVfqBHEuEnuoVyd4UgIuHiX7fwIyQoTb7/d4pTTbN9+KMJBCFO0NOGzpAhDs6OM+3FLg3KiKNzPKA2sUmHP0CFvJ8pcpOcAdqcMHEPOKVUkj64JBFGJEApHRYoXh/i3AyKaCEimLkKLTgG8eOQPsfwIz+OLk4ScektyR6s4ywHxCZ3A745C2/Lr7wwTEEI7+Fy78RhEzx1w8hiFK0TDI6MCWQCYBJOOS5RFQ64jiWq9Ol7KBPMfFsxIHhIqyTO8ezQgdHaRyvvqIpJXgQmQWpCOkxgbC1B1j9Tw/gvRH1pK4d4TA/VbtGdMtAKiY6RSkWFqeTJcFWFNvCHr9kB4vDJyzIWFgFo4VnO7ymaRn0Q7ZMSNonUc3rBvMfJh6fkjC1XvwyEtgvc1jLqkrUualA3BdWOgh5DSL62xJ5T3ApIVtv+AwSRWgwQdqtGCZgA0o8JsOI6smdIqOwQbwUoCaPTYyIgBMhLsJzB4oOX6YmmD33AZWkmwzbX+6nUaEtkhgO7IHC8fPKCggyx1uj10R7K85fsFpAiaNUzA6ylAgIBREEihHDxi61Cqhkt9hfx0IhSLHArRnUHjOXCCV7rbOU0I1MV3DAQPACBAaCKxkFQ2fozCCIwUQaOLlTtldTlrEGidYRDjgI+2FOvqr6YQ/26EOlhO8BERu8sQ85sQKQeORMHlhVsAEvNHwuC1ZpBU5jyLFKvlpmmpKpemQmg0jRs4e8RvBBCBCip31SUoNiDDpEw7cxJscvILCv3yE9DI18UZpPK1veYLoZM06GijJQ4MP5kcE+W1qHgWWbJuo6gytUqHJl2K8ETcQrUw2T0MAPfYlsGCFkr/2eBIousaviVqk6w1o1jpr1XwNBd9abJbEU2OhLmJ0GVcEE2vGxeRYT/wB4lhVEfYsmmFprxDIojvXIxFckD3Br4fVjMQWAxXkoLCyh1ONgAYZc/VjYWqijQicL7Cq4kIt0HBqC8oT3Y1KZWeuqphd90jsWXD+zdvDrxnJSBkz+RdvQUCQnBZZINuHESZEtsiZ5M43huRW6MXi0qQk4rqKCsyltxUAduEcGJJwEDabEjWApsFqRlFIrE2fPsgASBqQHNBBbev6v/9oACAECAwE/If63iyBTvrIapHybyevoX8vymc2gcIl7LKoiOS+j92OGqUjQo8fqzYLsYx+rPfka1N1942vQxri8Rr4/me+POEAk/eMlLOQ9OCtXR9r1c9Fd5GdBf9fv1kK2fvec1MlB2Xob+e8KHAIDx/yDXx/O9HEmFpMHVHf7P2e+FshZy9vBx23gpgSYhIPSchHp+TEMEevPzrLU87469m3zgRWG/Br4+b5byTm94NkKugNp46O/TDwLnxPkMgm5EPYAWVzZWcw/KpwfJuLMJ69j9XicQqSk+e+8fGRzGvjTk5TrTvOBL5LH3xvdxycB/rwYpMvxrwB9gw6PARKeY49TjGEp5c1uP24k2DXH7m/ecOm8J12dQc8s58ugvY/64yonjEsFoLfoNuGvjlTv/wAcEGXTa9Rr9+cjPkgaPPaV23j+weX3/Q6vIRihNrP89tfTKfLXiB23k8Ht+ckzEojvFBjY0fHhqXKHQVdj9h/8Yvufb6OaPjmfn9OLUQ58/wCYRtDAerrBRdg8H7zgGXT/ALhQ98ev/uKyBc9NvpeSrh88/wCY1RL5yNJudU/iDIBOCeeReyGz95o+NHbsspPiesMgg8/+MKQBnZxeJ95W2ft/mShTxX4xVKVNs27/ABi/L/imBZD9PbFN4D/lkQCfb4qaQg7f4ovCuDVrhYR7cfIFKoVZjLViCWiSPxDktYRboSp9/sMQliJDlOffeQWOTUdkm+eMgihEbBtHrOFPzhGwL/7kIManq0f7k2hH1Cn6798QAJhwDkczu6yIqkPY08AfpggRMNFNs9HjvIrIO3I7XppyhjXHE7j1zyEPafZ1P/W1hl9fX5jF85ItsKakmMAZLA9jInRJfqy4BxGF7v8A3DpiGfbF8xMtsKakmM6US73CPxng82SeD6+cgKWhKtxHLgZQuX8Y7tdwpPrDfvlkwv0/CM1vMKWQ905wHx/fc+d4AbUtsr5d8f1v/9oACAEDAwE/If63jqqHIQScvnv5iww+l74lLvj/AJzQojZHKfTFKDQQO/XyT3K3m0Z2J4cLml1iJ9u49Rtp7w/LKI8/HpM8qDfWQrQfxg4Wn7d4WLxQx1/1z1rHhIG6Mr69ZELV+kPX6Hw5AO8ZtjnrvFKj/wCLN/r/AAEJ1hvBgobfo8P6fbBoXesnL04z3DgS8A84eOJB+x8JSYJvBz856crkwOap8XZ+z7ZXM3gfLLM3+vxgBc50Ae8IwGN2Q358T5xyVqv5B+wezIUzWJJVEsmGSTCZLwuipKeRL8vthnyqZTtXbgNQyYcf6M3+vx7zS2ZcrNtjzkJX6fO3BsOk5Tf3iet94ShYanLdEGSlTBY9VOts8ZfkVI4Um0cLufBgvB++OAQR3i8e4UPB+c3+v8EHUiZT180HOsWpGchxEsY6kzaRSMnl/WAQoEJ2OKseRfP09fXBO7eTsOM+Q6PVkDilzrGdS9U9PGrgzqBmnSjFuEw63gsgGgjhm/1+NgLEC3rOenY6fx6/2ycVKR+GOl4zZDk8uUGvlT/iPTAIwvGXSNk/mMMMi/8AU8tDcz1jDFajYT2IFW+2SPB4/wB0ewxmcq8Hl9TD2SWePOTKBvQJXzwe705v9fjtnRwklCn2zjAnowBCFnXjPF+jirh98eVAf+nBqORVo0Jfnlw2h9WHa+k4k+bMNK98/wDisgKI7hiyz8MDG8SNRaKTy1wh+cKMx4YJCShi8jpXiAOISS0RF5BwEoO2GlwRCGzNwBmJlFOAhatnBhMW2pYBNiSzCpk8AEGXIHFhpzmalZbea8CjGHKTBdkoWJUgDc5YcEKWOMOwegYZsQCAcg4b+ZZOtqjkYpLXaFXjGByopjKghqJfGVf7iDpDKYnUUEy44C2XYOSopSsXFYvxZFfkT0wGMNhWMKyvaccr/wCwfxOIkQUltMjZtg+1CJVoAVaN5MPGQNYk7sHMZyg/gKBVGgGOukEBQAEHAlIU224iDeImWDkk3CsXG8cAIlj8gJTHJzWn0WM1falJrBDwEoXqGZG0hLAS4w5gXqR6QEpbELFY5+cGxCJ2klJWJrAQSKJw7Uhc6Xe8q69/yh6xl5EdsKTLLkDlCiorw4XomlRibgmEoRCBmzks7/rf/9oADAMBAAIRAxEAABAAAAAAAAAAADPGF5J7AAAf8NCDqkAAC36UX2QgAAB77HzBEAAB48jDa4gAAN4+wEgcAADArTH4NAAARMGaGgoAAmnJkmbbQgVhXJbhA/gAAAAAAAAAD//aAAgBAQMBPxD+tLc1UTS0QxisjGTZDUFsoIKCOL+zy+BXbCpHbKN/cAWaGG3aT74GWIEqELIQkMpE49LqJzBVcFIhYMpEZa+dvSENkzBkzN3ZIRBwAL4xoRLlsCVcybJcYSwamKDgXQmckX9Op+4BXOBsQL0RtJxC5gExiZS1PmXIMq2vxmWLeEAUZC6xFBLJg0QNp7uOC8nCUoWbajXcgzQPKGQZPPi+nCdNRyBOxouEDbGGgINJbTCUbAdamKS0VURqFCZButrH2YyUge0hQMloHKgx4QkTKKTfkGSjLlaycGsKQKO6StX0ZAwC40DS4d/f+AENIcVEyKaoHJfmeKLLlAN6uXCcCbApKCGAttM5AdaY0NxBkBKe8XjSQDBEJEF5K4bAoMDgQA2QEZHwY+IkyiVlIJMkAHwDE8JNciyRRn8SyYRMYO+CNKTYTegQ+SJb4J3OAOlYMLkLX7xhEorSURHf1fr+AEKAIUFMDy5klTzAKCBgDKd7x6QFgDESb9t1iNkH3p0O7iK5BRqoAcu1XGLpDoAMRTNEpt1lLoqzT/WtALROQfuAEyivgkEL6hw2F7qTDSLSlE4VrvnVghzzDJnIZqAWIkBahOyryYC3OaZiQ9RdfwAgoUlDcIVMSloXE2mT44NJhId4fIIzqWgkTbss0keTDgNB9HhcUAGdjy9xwxiJyqbnYli1v7yGZnImIafAWC4pEwJadFOKakOBRdYClqMqRAFuegZSHAHzXCrZBWawFdIfMZgSBBQMRkxQY1mscIExQNsCA7BfUF+/xpXRPKUoBwld4xkjcYMBVAPzIyTZwz+DPiJGBJZLjCaQwh5LewoC5fpiKI8JkKSlhEA2rtxEZtgDIlCUFIAwjUcYJhYXDEYISAQUBpY+KpGsMF5hIkZFx3mZGIBoOoblE5UbHNk1qsuLdGGlr+UIiNpF2/wSJDwHB+02AtcnMyAxo1TgNKBWAix7K/UkCQyN+uBAD6rMwPcEUHEDmxMqQ4+6R3GYyQTlsAB4mh5rD9RrCAhClCUwIyAGxraGl6mgSGMtsnIVxBEMPqlvHFcMs0qrelKaZBFgNpFgBiJI1ib0cRyQjMkgFMP8BtGPt6uF6w1ILIyDOyABO5Q5twno0mEMcVCjvCQSZ8UgEAUcYMJHIyPYoIwRhw7umh66xahk8CdJk2Y1AlkboEMPYCTgiLL/AAtEYHmdWUqByBJBRgyZwRkzIyMu84e2AGxmE2pDoiZL/YTZyWtjz8JcyfAcSNttYSYYsdQHebTwdpJRMWauKX8tE1xDb8FO3bFPgZUyQx8vsUBM68gPtfyPJOkyoE1DENurdzWREW0pHq1dpQdGVZb+pRwQIhF2fXQlAiw0RwgRac9G1AVSQAi5jUBZhap05SZtcZbJrG7CSYK3u0HrWjg5B67INxP0vJ1XEAcEzkpNpNgKYd2n030seK6H/wCR5qL9iMc424gE/wDEINXa/E6NwOSFuZ+Z5CA7+Hu5HS4jEQVbw90aJLATcjUIRcboqn6sA09OgTpVY6KSIQ9Lysgy/wAVmNFC2RYDKHpsO7aMi4yiBJwEld5IuFBRx0sSiTHSJhDM7JjkIFr7qkjqUAAMXq4AooeFOrIxWeIgcOUCHIgKQpHzoklGDLkqIFVUGBRUDbf9X//aAAgBAgMBPxD+tCEDbOqShjxrJgoIwFJDCSK0iI4EGko0juCZPsHWDSbKn8MN4DhSxsieflOBB6iCVgJKeeEK1kwkiKKzUW00GYYynKIFmnpA4/YyiSX7/rgIRkwhJ9cUkgNneCTwbl4wb8JKE6b8frLB8fGol4/jDRLiSCQsS+B55PJHOIvDFjUd+js8VgSkD1z9P/s5M0y1LcpTw34m+LkHg5QYURPS3jPSZgCOp507B9cajm60ePXJDOinkPHR2gyNZQNAID6b7ZcMSNR/Dmj0+PT6cAJbxkbME7Ug7381UeDB4maDW6nl110AmXLcby5ZI5Rb2GnU041tiA67dTDI6yrGJVorjyPLkxAjQ8MD5BteM4isSNsP7zR6fGkg4P4wITrEllZByJkSAQL0e0vBwOIngo0MCiWnGA6gdqB9WsgNvFggiZkEkyTePRLzBACXKszFjWUTXJBaZcw86OB8Zo/T0Gg2IzgrtiXfDNHp8YVmJoFluDy1kCW1EAeBI+zh6qKGwUdHPcPQ9beU9DliCAX7zkBhJcnIamywxIJZmcrQEQjHoTBzo+2KYFpzY04e8Zk1SQNQJLgCFYjJSB5W2CjtPR1VBwBBlWSAPOgOojdSotlFJYzYjpHhOMqADoaGvfJiDvLl8HxqM4Yg9c2XgeVSe0vUDpLD0Q5AHMFIsBoBMBgALJQhsF5VnwFuwKBCNIwiNI+E365VV5fHbyrdkucp3YD7HHCuPkRN3/GCpPSuDsT5hs1ikwYii6DtdIknIvUdG9TXbAUKNGFJiSq9Vr7BWfYH4+MHYg5Ued6xzNOKNPJjpoCdy5XNIMMgQixlrDvOaCpCruUKu1ZxVrj2nsNe+PbS3MhDs4FfR4xnHKgpx6JC4uOcsnGatb5sS7YN85DPPfJX3Y8YD5MpAHoM8EB2veFSMBNPVz35OchG0kC90TVHl4a+wPx8b0RYVgSUGULJzhB8TELv1zGM89iB9QYqmT6f5ist9TCHU836DBZGuXQkDITCXbG8Vlk9T/MB5z6n+YzWmAm9No56xMaHnEkBlwHScyk0imBBBo+FhRjagtoOSKXEJxS1BMqJBBkSKRushdanJ4pDCwD4yelugoKsFIO0XWGkSIiSmnlVvjJ6ImBFwhNggPnDsY0W4Re9LTksyAveXA1dye7h3JYiUYgISwAmF4jIHFh1gnkXoWXgcWYBQZF5B5KB6GRxVyPFiLBZ0IGBD3HoSAaKCTMDCw5xklCg3kRC7MRkgjBUg1IAqZKmpvAK4tXOegj65I7eqBu0gbRybiv+mBVyrKou0kQRCUIjGznBcAFaoBsdTljDLLsUI1SvE5xDIlbZLnarg6sUKBqVlu0gyDoowmeg6UQMaGKkCYJ1jJhya4laxBEnBm8m72sd1EKIGLxJ7DhIdBIEFIWCVgwsw0o9KV2hYGiZCcEyJDMKAGNDADATF49aEHBzQSDFbVWsWS3I6b6ovqcRJEQOJEAEYpFZy5ZW23M2nZdrXOUgNKgkRVUkIl0Rr+t//9oACAEDAwE/EP6y9BxLAcAQFBiYU5yQRUYlv4fTFAg6KnJJ675yqTcgvvLxxilq3ifTAkE6BGAlIO2ahdYXsFFxRIgJiHNCBJgFTAs/p78nDMeP00MHKBW2e+W1KlvDgnm4KFPbAWREGhRcjCYQTQvz8YFnLyGbkfKMXp0JsTuTiPqinWQPVKHhopyM114wBQAiwb6CPPEzlcRkha6HwXyDynDyPZRQqJYEFGkyBnWkETA9PAhF+nIivYiQDqO4wMCQoO14nwf+GPccsr+A9McSED6mP3L8/GGKMQHJGV7cUysqX/5eAbqWZ5EPQWOqXocGBs1Da0dKjyk8XdIhG+b5/wByV5Cj0E/Zric9O9IjQ+Zytj3DjcKVMwJXlXsPkQcAAFGwFRyEdajY5Q9aaMI8ImDmM/vX5+OAA/1/1kmFJTd+hkiUx6xPeMDUWSaajUNvB5jAkAQM7z2RAaVrCakTtWpwgQmFG0AgjsmTkwUzo1E9i94GKTB1EQX2HAaowkwKwSlPKq/YrDtzrBEWreX3r8/HANlL2iCjneQNoaNJfN78Yth0OpiX8GQOEUFhXxt+pOskkTxGLiwxEEIRBKsa4EZGE5jh3UfbCKKSB0k/m/vgJYSAp4oEMoEAqYuEI+4BlsxLSiIwG4UnY/3y+mQDkzNKN5NHAKaKrodQKuIz71+fjSNarOeZRBoPCWqxCVIC8e3RFuusBQmIM65DutcWyU0zImEhqcloo6wEMnSMYMkv04uBe6l4eGIFyPrDhtEL3yR2CjhozZkXWqgj1LH2vrJDlEBV9RtYU2CZhxAIRStZKoeSgpUSUEMAIjSD57z7l+fjcMNKoAOqugCV6xiFkR0yFHqhzKtIDlAFNyofdw2gVFgBXpsVNyyOEohZQnnQ+ZLEOsCYAXGNAhSAqchqGUEUAIdfhktJwplANKAQQDBa2yVxV1Y7DxADx6hyOg5ShWMputtWXziFDIEGFDIEsRJEsbM3jmG42fJYFpB4PuX5+NgTAaywCm0T4k05EAZoBPSnWHUjCVKEd8IRna73b9cVRQ9ffgqEsliPZJHnvnIKwerVqlC7CVYmQXBMFQ06q+mGoiJrKwwskxe2U+TeEDtAJASEmdJSaecRltZ+GgedFMKUE1tNnCV49DM6ICVYpKTxBJHJE1mEFMpWNklFbmTDzIayC2JHJ17qNAMogML71V/QAXpRk7xZX1nAARKCANkJ4jk5MsBFsjC3nGLidEo8bTmoByQZjorBFsXFoS3HsTWm7VyxNhnEJgFyEA1RFo6MBaRSyD0EtIQVxhEiFYhmZIY6qTp3Y8BUaPO8xhsfHOiLZJItlAZWMmgiEfQrbSRFgJ/9hYiQ9fZZWxMpYfAcIOualIAggrOCg7FWU4WFCJAVwVAicAaA3SJYlVlxGQ70toYMSQRCSi8kUR0EwwATASmaC0yDbYOlMEIOSHl8O/X2HIBBAqiLHBoLaxekZIGPBKrUpRAEIGIWKwGkLqAuRAYx11KK6VkG0xwbYGKdjMtAXGSA2pExN4/FacdAkCQQVhBR4LvQBwUZmG+0sZUfzICyZaEkJYJ/V//Z"
            }', 200)->header('Content-Type', 'application/json');
        }else{
            //Status Bad Request
            return response('{
                "status": "FAIL",
                "error": {
                    "message": "Failed to get the details",
                    "code": "CF400212"
                }
            }', 400)->header('Content-Type', 'application/json');
        }
    }
    public function addBank(Request $request)
    {
        $id = $request->get('id');
        if($id != null){
            // Status OK
            return response('{
                "status": "OK",
                "message": "Bank details updated"
            }', 200)->header('Content-Type', 'application/json');
        }else{
            //Status Bad Request
            return response('{
                "status": "FAIL",
                "error": {
                    "message": "Failed to update the details",
                    "code": "CF400211"
                }
            }', 400)->header('Content-Type', 'application/json');
        }
    }
    public function addReference(Request $request)
    {
        $id = $request->get('id');
        if($id != null){
            // Status OK
            return response('{
                "status": "OK",
                "message": "Reference details updated"
            }', 200)->header('Content-Type', 'application/json');
        }else{
            //Status Bad Request
            return response('{
                "status": "FAIL",
                "error": {
                    "message": "Failed to update the details",
                    "code": "CF400210"
                }
            }', 400)->header('Content-Type', 'application/json');
        }
    }
    public function getMandateLink(Request $request)
    {
        $id = $request->get('id');
        if($id != null){
            // Status OK
            return response('{
                "status": "OK",
                "data": {
                    "link" : "https://testapp.lotuspay.com/rssjped"
                }
            }', 200)->header('Content-Type', 'application/json');
        }else{
            //Status Bad Request
            return response('{
                "status": "FAIL",
                "error": {
                    "message": "Failed to get the details",
                    "code": "CF400209"
                }
            }', 400)->header('Content-Type', 'application/json');
        }
    }

    public function updatePFinvoices(){
        $invoices = Invoices::with('application')->where('type', 'processing_invoice')
            ->where('merchant_id', 0)->where('lender_id',5)
            ->where('created_at', '>=', '2023-04-01 00:00:00')->get();
        $now = Carbon::now()->toDateTimeString();

        foreach ($invoices as $invoice){
            $invoice_id = (new ConsumerApplicationController())->getInvoiceID($invoice->application, $invoice->type);

            Invoices::where('id', $invoice->id)->update([
                'invoice_id' => $invoice_id,
                'updated_at' => $now
            ]);
        }

        return true;
    }
    public function updateBPinvoices(){
        $invoices = ChargedInvoices::with('application')->where('type', 'bounce')
            /*->where('deleted_at', '>=', '2023-05-01 00:00:00')*/->where('lender_id',2)
            /*->where('invoice_date', '>=', '2023-04-01 00:00:00')*/->where('invoice_id', 'like', '%-2325%')->get();
        $now = Carbon::now()->toDateTimeString();

        foreach ($invoices as $invoice){
            $invoice_id = (new LoanManagement())->getInvoiceNumberV1(new ConsumerApplicationController(), $invoice->application, $invoice->type);

            ChargedInvoices::where('id', $invoice->id)->update([
                'invoice_id' => $invoice_id,
                'updated_at' => $now
            ]);
        }

        return true;
    }

    public function updateLANinProformaTable(){
        $users = ConsumerApplication::with('merchant', 'proFormaInvoice')
            ->whereHas('proFormaInvoice', function($q){
                $q->whereNull('loan_application_no');
            })->get();

        foreach($users as $user){
            $type = 7;
            if($user->merchant_id == 5026){
                $type = 8;
            }

            if (strlen($user->id) < $type) {
                $diff = $type - strlen($user->id);
                $concatstring = "";
                for ($i = 0; $i < $diff; $i++) {
                    $concatstring = $concatstring . "0";
                }
            }
            $application_id = $user->merchant->slug.$concatstring.$user->id;

            ProFormaInvoice::where('application_id', $user->id)->update(['loan_application_no'=> $application_id]);
        }
    }

    public function calculatorTata(){
        return view('admin.reports.calculator_v1');
    }

    public function calculatorPraveg(){
        return view('admin.reports.praveg_calculator');
    }

    public function calculatorHeavenSolar(){
        return view('admin.reports.calculator_heaven');
    }

    public function calculatorTataRajasthan(){
        return view('admin.reports.calculator_rajastan');
    }

    public function calculatorNew(){
        return view('admin.reports.calculator_new');
    }

    public function getCollectionPanel($ids){

        if ($ids != "" ){
            $id = intval($ids);
            $data = [];

            (new LoanManagement())->paymentCalculate($id,'','all');

            $data['paymentsData'] = EmiPayment::with('transaction.bank','moratoriums')->where('application_id', $id)->orderBy('emi_date','asc')->get();
            $data['application'] = ConsumerApplication::with('application_element','proFormaInvoice','emi')->where('id', $id)->first(['id','name','lender_id']);

            $overPayments = PaymentTransaction::with('refundPayment')->where('application_id',$id)->whereIn('payment_for',['processing_fee','Over Payment','Advance Payment','rejected','Foreclosure','refund','collection_charges','insurance_fee','adhoc_transaction','advance_amount', 'cancellation_charges', 'Write-off'])->whereNull('is_deleted_at')->get();
            $amount_paid = 0;
            $max_payable = $data['application']->application_element->amount_over_due;
            foreach ($data['paymentsData'] as $i => $emi_payments){
                $amount_paid = $amount_paid + ($emi_payments->total_payable - $emi_payments->amount_due);
                $check_date = date('Y-m-d',strtotime("+11 days",time()));
                if($check_date >= $emi_payments->emi_date && $emi_payments->emi_date > date('Y-m-d') && $emi_payments->payment_status != 'success') {
                    if($emi_payments->payment_status == 'pending') {
                        $max_payable = $max_payable + $emi_payments->emi_amount;
                    }else{
                        $max_payable = $max_payable + $emi_payments->amount_due;
                    }
                }

                $data['paymentsData'][$i]->pending_amount = $emi_payments->amount_due;

                // adding checker/verifier name and time in transaction
                foreach($emi_payments->transaction as $pay){
                    // $checkerInfo = PaymentMakerChecker::where(DB::raw("json_extract(data, '$.trasanction_id')"), str_replace("'","",$pay->trasanction_id))->get();
                    $checkerInfo = PaymentMakerChecker::where('trasanction_id_virtual', $pay->trasanction_id)->get();

                    //$checkerInfo = DB::select("select * from payments_maker_checker where json_extract(data, '$.trasanction_id') = $pay->trasanction_id");
                    foreach($checkerInfo as $transaction){
                        $userData = User::find($transaction->checker_id);
                        if($userData){
                        $pay->verifier_name = $userData->name;
                        $pay->verify_date = $transaction->verify_date;
                        }
                    }
                }
            }

            $over_payment = 0;
            $adhoc_payment = 0;
            $advance_amount = 0;
            $processing_fee = 0;
            $foreclosure_amount_cals = 0;

            $isForeclosed = 0;
            if($overPayments) {
                foreach ($overPayments as $overpayment) {
                    if ($overpayment->amount > 0 && ($overpayment->payment_for == "Over Payment") && $overpayment->status != "rejected"){
                        $over_payment = $over_payment + $overpayment->amount;
                        if($overpayment->refunded_at && $overpayment->refunded_by && $overpayment->refund_maker_id && $overpayment->refund_maker_at){
                            $over_payment = $over_payment - $overpayment->amount;
                        }
                    }
                    if ($overpayment->amount > 0 && ($overpayment->payment_for == "processing_fee" )){
                        $processing_fee = $processing_fee + $overpayment->amount;
                    }
                    if($overpayment->amount > 0 && $overpayment->payment_for == "refund"){
                        $over_payment = $over_payment - $overpayment->amount;
                    }
                    if ($overpayment->amount > 0 && ($overpayment->payment_for == "Over Payment" || $overpayment->payment_for == "Advance Payment"  || $overpayment->payment_for == "Foreclosure") && $overpayment->status != "rejected"){
                        $adhoc_payment = $adhoc_payment + $overpayment->amount;
                    }
                    if ($overpayment->amount > 0 && ($overpayment->payment_for == "advance_amount" )){
                        $advance_amount = $advance_amount + $overpayment->amount;
                    }
                    if ($overpayment->amount > 0 && ($overpayment->payment_for == "Foreclosure") && $overpayment->status != "rejected"){
                        $isForeclosed = 1;
                    }

                    if ($overpayment->payment_for == "Foreclosure"){
                        $foreclosure_amount_cals = $foreclosure_amount_cals + $overpayment->amount;
                        $foreclosure_payment_date = $overpayment->payment_date;
                        $foreclosure_payment_reconcile_date = $overpayment->payment_reconciliation_date;
                        $payment_mode = $overpayment->payment_mode;
                        $forecloser_transaction_id = $overpayment->transaction_id;
                        $forecloser_id = $overpayment->id;

                    }

                }
                $data['over_payment'] = $over_payment;
            }else{
                $data['over_payment'] = 0;
            }
            if($data['application']->application_element->total_amount_due == 0){
                $max_payable = 0;
            }

            $data['adhoc_transactions'] = $overPayments;
            $data['amount_paid'] = $amount_paid + $adhoc_payment;
            $data['max_payable'] = $max_payable;
            $data['processing_fee_due'] = (isset($data['application']->emi->processing_fee)) ?  ($data['application']->emi->processing_fee - $processing_fee) : 0;
            $data['advance_amount_due'] = (isset($data['application']->proFormaInvoice->merchant_collected_advance_amount) && $data['application']->proFormaInvoice->merchant_collected_advance_amount && $data['application']->emi) ?  ($data['application']->emi->upfront_from_customer - $advance_amount) : 0;


            $paymentsData = (new LoanManagement())->getWithMoratoriumDetails($data['paymentsData']);


            $scheduleData =  (new Moratorium())->getSchedule($id);
            $schedule['schedule'] = $scheduleData['payload'];


            $foreclosure_date = '';

            if($foreclosure_date == ""){
                $foreclosure_date = date('Y-m-d',(strtotime ('29 day',time())));
            }

            $response['previous_pending'] = 0;
            $response['future_emi'] = 0;
            $response['due_emi'] = 0;
            $response['bounce_charges'] = 0;
            $response['penal_interest'] = 0;
            $response['gst'] = 0;
            $response['advance_payment'] = 0;

            //$moratorium = new Moratorium();

            foreach ($paymentsData as $c => $payments){
                if($payments->emi_date <= $foreclosure_date) {
                    if($payments['amount_due'] > 0) {
                        $response['previous_pending'] = $response['previous_pending'] + $payments['pending_amount'];
                        $response['bounce_charges'] = $response['bounce_charges'] + (isset($payments['bounce_charges']) ? $payments['bounce_charges'] : 0);
                        $response['penal_interest'] = $response['penal_interest'] + (isset($payments['delay_penalty']) ? $payments['delay_penalty'] : 0);
                    }
                    $response['foreclosure_date'] = $payments->emi_date;
                }else{
                    $response['advance_payment'] = $response['advance_payment'] + ($payments['total_payable'] - $payments['amount_due']);
                }

                if(isset($payments->moratoriums) && count($payments->moratoriums)){
                    foreach ($payments->moratoriums as $moratoriumItem){
                        if($moratoriumItem->emi_date == Carbon::createFromFormat('Y-m-d', $payments->emi_date)->subMonth(1)->toDateString()) {
                            //$moratoriumAmount = $moratorium->getPrincipalOutstanding($id, $moratoriumItem);
                            $moratoriumItem['moratoriumAmount'] = $payments->moratorium_amount;//$moratoriumAmount;
                            $paymentHistory['moratorium'] = $moratoriumItem;
                            $paymentsData[$c]->moratorium = $moratoriumItem;
                        }
                    }

                    unset($payments->moratoriums);
                }
            }


            foreach ($schedule['schedule'] as $loan_schedule){
                if($loan_schedule['emi_date'] > $foreclosure_date){
                    $response['future_emi'] = $response['future_emi'] + $loan_schedule['principal'];
                }
            }
            $response['future_emi'] = round(($response['future_emi']-$response['advance_payment']),0);
            $response['total_outstanding'] = $response['previous_pending'] + $response['future_emi'];

            $data['foreclosure_amount'] = $response['total_outstanding'];

            $data['foreclosure_date'] = isset($response['foreclosure_date']) ? $response['foreclosure_date'] : '';
            if(isset($payment['processing_fee_due']) && $processing_fee > 0){
                $data['foreclosure_amount'] = $data['foreclosure_amount'] + $processing_fee;
            }

            $foreclosedAmount = DB::select("select sum(amount) as 'amount' from payment_transactions where trasanction_id=(select trasanction_id from payment_transactions where application_id=".$id." and payment_for='Foreclosure');");
            if(isset($foreclosedAmount[0]->amount) && isset($data['foreclosure_amount']) && $foreclosedAmount[0]->amount < $data['foreclosure_amount']){
                $isForeclosed = 0;
            }

            return response()->json($data,200);
        }
        return response()->json(['status' => 'FAIL', 'error' => "Can't find the application"]);
    }

    public function getAgencyReport(Request $request){
        $ids = json_decode($request->get('ids')) ?? 0;

        $_data = [];
        $_data [] = ['App id', 'LAN', 'Name', 'Merchant Name', 'Mobile Number', 'Alternate Contact', 'Bucket', 'DPD', 'Email', 'DOB', 'PAN', 'Product', 'EMI Date', 'Last EMI', 'EMI', 'EMI Pending', 'Total Amount due', 'Max payable', 'Outstanding', 'Emp Status', 'Company name', 'Address', 'City', 'Pincode', 'State', 'Ref name', 'Ref contact', 'Ref name', 'Ref contact', 'Principal due', 'Last paid amount', 'Last paid date', 'Agency'];
        if($ids > 0) {
            $appl = ConsumerApplication::with('proFormaInvoice', 'emi', 'application_element', 'merchant', 'last_payment_date')->whereIn('id', $ids)->get();
            foreach ($appl as $app) {
                $data['paymentsData'] = EmiPayment::with('transaction.bank', 'moratoriums')->where('application_id', $app->id)->orderBy('emi_date', 'asc')->get();
                if (isset($app->permanent_address_line_1) && $app->permanent_address_line_1 != "") {
                    $address_line1 = $app->permanent_address_line_1;
                    $address_state = $app->permanent_address_state;
                    $address_city = $app->permanent_address_city;
                    $address_pincode = $app->permanent_address_pincode;
                } else {
                    $address_line1 = $app->current_address_line_1;
                    $address_state = $app->current_address_state;
                    $address_city = $app->current_address_city;
                    $address_pincode = $app->current_address_pincode;
                }

                $max_payable = $app->application_element->amount_over_due;
                foreach ($data['paymentsData'] as $i => $emi_payments) {
                    $amount_paid = 0;
                    $amount_paid = $amount_paid + ($emi_payments->total_payable - $emi_payments->amount_due);
                    $check_date = date('Y-m-d', strtotime("+11 days", time()));
                    if ($check_date >= $emi_payments->emi_date && $emi_payments->emi_date > date('Y-m-d') && $emi_payments->payment_status != 'success') {
                        if ($emi_payments->payment_status == 'pending') {
                            $max_payable = $max_payable + $emi_payments->emi_amount;
                        } else {
                            $max_payable = $max_payable + $emi_payments->amount_due;
                        }
                    }
                }

                $_data [] = [
                    'id' => $app->id ?? '',
                    'agreement_id' => $app->proFormaInvoice->loan_application_no ?? '',
                    'name' => $app->name ?? '',
                    'merchant' => $app->merchant->merchant_name ?? '',
                    'contact' => $app->mobile_number ?? '',
                    'alternate_contact' => '',
                    'bucket' => 30,
                    'dpd' => '',
                    'email' => $app->email ?? '',
                    'dob' => $app->dob ?? '',
                    'pan' => $app->pan_card ?? '',
                    'product' => $app->application_element->product_name ?? '',
                    'emi_date' => $app->emi->emi_date ?? '',
                    'last_emi' => $app->application_element->last_emi_date ?? '',
                    'emi' => $app->emi->emi ?? '',
                    'no_due' => $app->emi->emi_pending ?? '',
                    'total_due' => $app->application_element->total_amount_due ?? '',
                    'max_payable' => $max_payable ?? '',
                    'outstanding' => $app->application_element->total_amount_due ?? '',
                    'emp_status' => $app->employee_status ?? '',
                    'company_name' => $app->company->company ?? '',
                    'address' => $address_line1 . ', ' . $address_state . ', ' . $address_city . ' ' . $address_pincode,
                    'city' => $address_city ?? '',
                    'pin code' => $address_pincode ?? '',
                    'state' => $address_state ?? '',
                    'ref_name' => $app->application_element->reference_name_1,
                    'ref_num' => $app->application_element->reference_contact_1,
                    'ref_name2' => $app->application_element->reference_name_2,
                    'ref_num2' => $app->application_element->reference_contact_2,
                    'principal_due' => $app->application_element->total_principLAal_due ?? '',
                    'last_payment_amt' => $app->last_payment_date->amount ?? '',
                    'last_payment_date' => $app->last_payment_date->payment_date ?? '',
                    'agency' => 'PAMAC'
                ];
            }

            $request = new Request(['data' => $_data, 'sheet' => 'Sheet1']);
            $file = 'imran_data.xlsx';
            Excel::store((new Exporter($request)), $file);
            Mail::send('emails.reminders.basic_reminder',
                ['body' => 'Agency Report']
                , function ($message) use ($file) {
                    $message->to(['sarah@creditfair.in', 'imran@creditfair.in'])->subject('Agency Report');
                    $message->attachData(file_get_contents(storage_path() . '/app/' . $file), $file);
                });

            unlink(storage_path() . '/app/' . $file);
        }
        return true;
    }

    public function runEmiDueReminderById($id){
        if (!_env('APP_CONNECTION')){
            $_this = new \stdClass();
            $_this->job_id = $id ?? 0;
            try{
                (new Jobs())->start($_this);
                return response()->json(['status' => 'OK', 'message' => 'success']);
            }catch (\Exception $e){
                return response()->json(['status' => 'FAIL', 'error' => $e->getMessage()]);
            }
            return response()->json(['status' => 'FAIL', 'error' => "Failed to run job"]);
        }
        abort(404);
    }

    public function runQueueLogById($id){
        if (!_env('APP_CONNECTION')){
            try{
                $automation = true;
                $result = (new RQConsumerListener())->handle($id, $automation);
                if ($result){
                    return response()->json(['status' => 'OK', 'message' => 'success']);
                }
                return response()->json(['status' => 'FAIL', 'error' => "Failed to run job"]);
            }catch (\Exception $e){
                return response()->json(['status' => 'FAIL', 'error' => $e->getMessage()]);
            }
            return response()->json(['status' => 'FAIL', 'error' => "Failed to run job"]);

        }
        abort(404);
    }

    public function runCampaignJobById($id){
        if (!_env('APP_CONNECTION')){
            $_this = new \stdClass();
            $_this->job_id = $id ?? 0;
            try{
                (new CampaignsJobProvider())->start($_this);
                return response()->json(['status' => 'OK', 'message' => 'success']);
            }catch (\Exception $e){
                return response()->json(['status' => 'FAIL', 'error' => $e->getMessage()]);
            }
            return response()->json(['status' => 'FAIL', 'error' => "Failed to run job"]);
        }
        abort(404);
    }

    public function jifyAadhaarPDFToCSV(){
        $data = [
            ['id' => 28393, 'file' => 'emp-application/jiffy/28393/aadhaar_card_full.pdf']
        ];
        $csvFile = fopen(storage_path('output.csv'), 'a');
        foreach($data as $item) {

            $s3 = Storage::disk('s3');
            $d = $s3->get($item['file']);

            $parner = new Parser();
            $pdf = $parner->parseFile($d);
            $text = $pdf->getText();

            $lines = explode("\n", $text);

// Open a file for writing CSV
            //$csvFile = fopen(storage_path('output.csv'), 'w');

// Parse lines and save them into CSV format
            foreach ($lines as $line) {
                if (strpos($line, 'Masked Aadhaar Number') !== false) {
                    $columns = preg_split("/\t+/", $line);
                    fputcsv($csvFile, ['id' => $item['id'], 'number' => $columns[1]]);
                } else if (strpos($line, 'xxxxxxxx') !== false) {
                    $pattern = '/x{8}\d{4}/';

                    preg_match($pattern, $line, $matches);

                    fputcsv($csvFile, ['id' => $item['id'], 'number' => $matches[0]]);
                }
            }
        }

        fclose($csvFile);
    }

    public function newRPSScript(){
        try {
//            $application_list = [234993,242138,246036,247202,247930,248492,250630,250633,250777,251202,251449,251495,252223,253634,254599,255133,255265,255306,255736,255748,255826,255868,256126,256351,256372,256804,256922,257454,257485,257517,257519,257804,258312,258487,258629,258727,258757,258765,258771,258876,258909,258934,259105,259162,259329,259416,259479,259537,259601,259610,259626,259632,259679,259745,259779,259788,259821,259850,259866,259956,260025,260048,260118,260133,260208,260281,260321,260335,260362,260457,260461,260473,260530,260590,260602,260726,260729,260733,260752,260849,260861,260871,260886,260916,260922,260962,260977,261009,261018,261021,261098,261176,261207,261210,261218,261229,261237,261261,261262,261281,261351,261365,261382,261396,261413,261463,261482,261493,261511,261538,261559,261563,261579,261585,261611,261629,261643,261651,261671,261715,261753,261762,261780,261821,261823,261827,261861,261871,261874,261884,261893,261897,261900,261910,261925,261932,261936,261948,261959,261970,261976,261982,261997,262001,262036,262044,262055,262063,262071,262084,262090,262096,262108,262109,262126,262130,262137,262152,262168,262171,262181,262184,262185,262197,262213,262224,262225,262241,262252,262266,262287,262308,262324,262328,262332,262345,262373,262394,262399,262406,262407,262414,262429,262447,262449,262460,262478,262495,262506,262507,262513,262521,262534,262544,262545,262565,262579,262589,262591,262600,262639,262647,262649,262658,262678,262679,262685,262688,262695,262702,262715,262716,262717,262723,262737,262749,262760,262763,262765,262795,262810,262828,262833,262845,262846,262850,262852,262860,262865,262884,262898,262901,262904,262934,262957,262958,262979,262985,262995,262997,262999,263019,263022,263050,263069,263077,263080,263097,263106,263108,263144,263148,263152,263153,263158,263161,263162,263195,263196,263213,263215,263219,263221,263229,263230,263263,263286,263304,263315,263324,263325,263336,263342,263346,263350,263369,263385,263390,263393,263395,263402,263403,263433,263459,263470,263483,263487,263511,263522,263525,263527,263534,263537,263556,263570,263575,263580,263585,263592,263593,263594,263595,263624,263633,263646,263647,263655,263656,263664,263666,263668,263672,263675,263685,263699,263705,263706,263710,263712,263717,263719,263720,263727,263733,263747,263751,263762,263775,263776,263792,263797,263821,263829,263836,263850,263856,263899,263926,263935,263942,263959,263969,263971,263985,264186,264192,264194,264198,264210,264211,264213,264222,264224,264238,264252,264260,264265,264272,264279,264282,264283,264308,264311,264327,264336,264339,264341,264351,264353,264360,264376,264395,264398,264401,264407,264410,264418,264419,264421,264423,264424,264430,264438,264447,264454,264462,264495,264530,264550,264551,264562,264569,264576,264577,264585,264594,264599,264601,264608,264611,264623,264635,264643,264645,264654,264660,264665,264666,264670,264678,264680,264700,264717,264733,264742,264754,264765,264769,264785,264788,264807,264808,264819,264829,264830,264845,264849,264862,264870,264891,264893,264898,264905,264909,264918,264928,264937,264944,264945,264953,264954,264955,264957,264961,264964,264968,264991,265003,265004,265006,265012,265013,265016,265030,265032,265065,265090,265091,265095,265105,265106,265115,265117,265139,265151,265152,265161,265163,265165,265197,265201,265210,265213,265223,265235,265240,265245,265248,265250,265253,265257,265280,265302,265306,265312,265325,265331,265339,265361,265384,265385,265396,265419,265422,265423,265426,265438,265449,265451,265460,265468,265478,265500,265504,265505,265507,265511,265512,265517,265518,265521,265529,265530,265538,265539,265541,265555,265557,265561,265574,265575,265587,265610,265612,265626,265627,265630,265650,265651,265656,265658,265668,265669,265679,265681,265695,265696,265702,265705,265719,265723,265726,265728,265729,265731,265755,265759,265769,265777,265778,265790,265797,265799,265802,265809,265814,265840,265843,265856,265861,265874,265879,265883,265885,265889,265895,265897,265900,265905,265928,265930,265942,265945,265946,265947,265948,265954,265955,265965,265969,265973,265989,265990,265997,266007,266008,266009,266010,266013,266016,266021,266022,266034,266047,266049,266055,266062,266069,266070,266080,266089,266090,266096,266112,266116,266121,266123,266140,266144,266146,266154,266165,266166,266169,266184,266185,266187,266191,266195,266201,266239,266253,266257,266266,266267,266274,266280,266283,266296,266301,266303,266316,266330,266331,266332,266333,266337,266343,266344,266345,266380,266382,266389,266408,266414,266417,266419,266425,266426,266427,266430,266433,266434,266447,266452,266462,266465,266474,266487,266489,266509,266515,266559,266571,266575,266583,266586,266595,266600,266611,266626,266633,266634,266646,266654,266661,266668,266677,266680,266704,266709,266728,266731,266732,266733,266751,266754,266760,266766,266773,266775,266777,266784,266785,266793,266807,266813,266837,266844,266845,266885,266889,266897,266899,266919,266926,266929,266944,266957,266960,266968,266977,266991,266993,266998,267004,267018,267021,267025,267054,267063,267067,267074,267075,267080,267084,267093,267094,267105,267112,267123,267127,267136,267141,267153,267155,267156,267158,267160,267164,267173,267174,267179,267188,267195,267197,267200,267201,267219,267220,267222,267227,267250,267271,267273,267283,267286,267302,267308,267318,267326,267334,267336,267351,267381,267382,267383,267384,267387,267395,267417,267419,267424,267425,267430,267441,267455,267457,267470,267482,267491,267516,267520,267554,267556,267564,267571,267581,267585,267593,267598,267600,267601,267609,267611,267634,267638,267641,267645,267651,267669,267687,267690,267710,267714,267716,267722,267742,267754,267767,267771,267791,267793,267804,267833,267834,267882,267885,267888,267892,267900,267925,267938,267941,267947,267953,267957,267965,267969,267978,267988,267998,268002,268003,268005,268018,268020,268048,268090,268094,268105,268109,268118,268133,268146,268147,268151,268160,268162,268166,268180,268199,268200,268202,268204,268206,268212,268213,268214,268222,268232,268237,268259,268261,268270,268272,268282,268291,268299,268308,268315,268320,268342,268347,268375,268380,268387,268404,268411,268415,268436,268445,268447,268450,268473,268491,268505,268511,268531,268534,268542,268548,268554,268555,268558,268567,268583,268614,268624,268631,268634,268648,268653,268658,268660,268663,268697,268698,268703,268706,268712,268721,268724,268739,268764,268773,268776,268780,268782,268788,268804,268805,268808,268809,268812,268823,268832,268844,268853,268863,268865,268871,268889,268893,268894,268899,268902,268905,268906,268914,268916,268918,268919,268933,268949,268950,268970,268975,268985,269003,269006,269030,269040,269058,269073,269078,269097,269100,269102,269103,269107,269111,269121,269135,269142,269144,269149,269166,269173,269187,269196,269200,269208,269219,269226,269230,269231,269232,269250,269271,269272,269273,269305,269308,269311,269313,269317,269319,269325,269347,269349,269360,269368,269370,269371,269381,269389,269394,269397,269410,269412,269419,269432,269440,269444,269448,269474,269477,269490,269498,269512,269517,269520,269527,269528,269530,269534,269549,269551,269552,269558,269566,269569,269571,269581,269591,269600,269603,269615,269619,269630,269632,269634,269640,269642,269648,269649,269651,269652,269654,269656,269664,269669,269670,269677,269686,269688,269705,269708,269718,269730,269743,269746,269753,269754,269758,269759,269760,269763,269768,269778,269787,269792,269794,269796,269799,269803,269813,269816,269818,269829,269847,269850,269854,269858,269860,269866,269869,269883,269891,269893,269897,269898,269899,269901,269914,269920,269924,269927,269932,269946,269947,269949,269950,269952,269957,269962,269965,269969,269974,269990,269991,270008,270009,270016,270018,270027,270047,270050,270061,270066,270084,270092,270102,270108,270120,270127,270131,270136,270137,270139,270142,270144,270145,270150,270166,270176,270213,270225,270227,270234,270251,270252,270253,270262,270265,270268,270272,270275,270281,270282,270308,270311,270314,270320,270322,270326,270330,270333,270334,270339,270342,270346,270348,270357,270363,270373,270377,270383,270388,270409,270446,270458,270464,270507,270522,270529,270535,270540,270544,270547,270557,270562,270580,270588,270592,270600,270608,270609,270632,270644,270661,270667,270682,270684,270709,270710,270713,270714,270718,270721,270725,270739,270746,270751,270755,270760,270764,270772,270778,270792,270795,270796,270803,270805,270807,270809,270824,270826,270861,270872,270876,270883,270891,270893,270894,270899,270901,270909,270911,270919,270924,270925,270926,270936,270941,270954,270957,270966,270983,270984,270997,270998,271000,271005,271017,271042,271067,271068,271077,271094,271116,271131,271138,271142,271147,271162,271177,271180,271194,271204,271208,271216,271217,271222,271226,271228,271235,271239,271250,271254,271258,271261,271275,271279,271281,271283,271289,271290,271303,271310,271322,271327,271331,271345,271352,271356,271362,271371,271382,271394,271400,271403,271412,271414,271420,271421,271436,271447,271449,271481,271482,271484,271486,271498,271529,271537,271538,271550,271551,271557,271570,271572,271579,271596,271599,271605,271612,271615,271668,271671,271673,271676,271691,271700,271702,271721,271726,271728,271748,271749,271757,271759,271766,271772,271803,271809,271812,271817,271819,271824,271834,271838,271864,271869,271895,271916,271931,271936,271953,271960,271974,271980,271984,271988,271991,271997,272000,272001,272014,272068,272072,272078,272083,272086,272089,272098,272113,272115,272116,272128,272135,272136,272141,272143,272166,272179,272181,272206,272208,272237,272239,272240,272257,272265,272276,272278,272324,272337,272349,272357,272360,272364,272365,272381,272386,272393,272394,272403,272407,272411,272417,272421,272429,272455,272459,272468,272476,272479,272485,272490,272492,272495,272503,272516,272537,272556,272559,272561,272584,272593,272605,272609,272610,272616,272622,272627,272639,272648,272669,272673,272674,272684,272705,272720,272724,272746,272755,272769,272781,272785,272789,272838,272843,272865,272891,272897,272914,272916,272917,272920,272965,272984,272985,272986,272987,272994,272995,273003,273009,273013,273027,273029,273038,273045,273046,273054,273083,273084,273085,273097,273116,273128,273129,273139,273152,273167,273191,273216,273224,273240,273248,273252,273273,273275,273282,273283,273284,273286,273304,273321,273326,273334,273343,273345,273347,273358,273365,273392,273463,273492,273494,273515,273516,273521,273541,273552,273558,273599,273610,273623,273675,273689,273690,273721,273729,273744,273772,273797,273819,273877,273878,273968,274000,274025];
//            $application_list = [234993,242138,246036,247202,247930,248492,250777,251202,251495,252223,254599,255133,255265,255306,255748,255826,255868,256126,256372,256804,256922,257454,257517,257519,257804,258312,258487,258757,258765,258934,259329,259416,259479,259537,259587,259610,259679,259779,259788,259850,260048,260118,260133,260208,260281,260321,260335,260461,260530,260590,260726,260752,260849,260861,260871,260916,260922,260977,261018,261207,261210,261229,261237,261261,261262,261365,261413,261463,261482,261493,261498,261538,261559,261563,261579,261585,261611,261643,261651,261671,261780,261821,261823,261827,261861,261871,261874,261897,261900,261925,261932,261948,261959,261970,261976,261979,261982,261997,262001,262090,262096,262109,262126,262130,262137,262152,262168,262171,262181,262184,262185,262197,262213,262224,262225,262241,262287,262308,262324,262332,262345,262373,262399,262406,262414,262429,262431,262495,262506,262507,262513,262534,262565,262579,262589,262647,262658,262678,262685,262688,262702,262715,262716,262717,262737,262763,262795,262828,262833,262846,262850,262852,262860,262865,262884,262934,262957,262958,262979,262985,262995,262997,262999,263050,263077,263080,263106,263108,263118,263144,263148,263152,263153,263158,263161,263162,263195,263196,263213,263215,263219,263229,263230,263263,263286,263315,263324,263342,263346,263350,263385,263395,263433,263459,263483,263487,263511,263522,263527,263534,263537,263556,263570,263575,263580,263592,263593,263594,263595,263612,263624,263633,263646,263647,263655,263656,263664,263666,263668,263672,263675,263685,263699,263705,263706,263710,263712,263717,263719,263720,263727,263733,263747,263751,263762,263775,263776,263792,263797,263821,263829,263836,263850,263899,263926,263935,263942,263959,263969,263971,263985,264192,264198,264210,264213,264224,264238,264252,264265,264272,264283,264311,264336,264339,264341,264351,264353,264376,264395,264398,264401,264407,264410,264419,264421,264424,264430,264447,264454,264462,264495,264530,264550,264562,264569,264577,264585,264594,264601,264608,264611,264623,264643,264645,264654,264660,264665,264670,264717,264733,264742,264754,264785,264788,264807,264808,264819,264829,264830,264849,264862,264870,264891,264893,264898,264909,264918,264928,264937,264944,264945,264953,264954,264955,264957,264961,264964,264968,264991,265003,265004,265006,265013,265030,265032,265065,265090,265091,265095,265105,265106,265115,265117,265139,265151,265152,265161,265163,265165,265173,265197,265201,265210,265213,265223,265235,265240,265248,265250,265253,265280,265302,265306,265319,265325,265339,265361,265384,265385,265396,265419,265423,265426,265438,265451,265460,265468,265478,265500,265505,265511,265512,265517,265518,265521,265529,265538,265539,265541,265555,265561,265574,265575,265587,265610,265612,265627,265630,265656,265658,265668,265679,265695,265696,265702,265705,265719,265723,265726,265728,265729,265755,265756,265759,265769,265790,265797,265799,265802,265808,265809,265814,265840,265843,265856,265861,265883,265885,265889,265895,265928,265930,265942,265945,265946,265948,265954,265955,265965,265969,265973,265990,265997,266007,266008,266009,266013,266016,266021,266022,266034,266047,266049,266055,266062,266069,266070,266076,266089,266090,266096,266116,266117,266121,266140,266144,266146,266154,266165,266166,266169,266184,266191,266195,266201,266239,266241,266257,266267,266283,266301,266303,266316,266330,266331,266333,266344,266345,266380,266382,266389,266408,266417,266419,266425,266426,266427,266433,266434,266447,266462,266474,266487,266489,266509,266515,266575,266583,266590,266600,266611,266633,266634,266646,266661,266668,266677,266680,266704,266709,266728,266731,266732,266733,266751,266754,266760,266766,266773,266775,266777,266784,266785,266793,266807,266813,266837,266844,266845,266885,266889,266897,266899,266919,266926,266929,266957,266960,266968,266977,266991,266993,266998,267018,267021,267025,267054,267063,267067,267075,267080,267084,267093,267094,267105,267112,267123,267127,267136,267141,267155,267156,267158,267160,267164,267173,267174,267179,267188,267195,267200,267201,267219,267220,267227,267250,267271,267273,267283,267302,267308,267318,267326,267334,267336,267351,267379,267382,267383,267384,267387,267395,267417,267419,267425,267430,267441,267455,267457,267470,267482,267491,267516,267520,267564,267571,267581,267585,267593,267601,267609,267611,267634,267641,267651,267669,267687,267710,267714,267722,267742,267754,267767,267793,267804,267834,267882,267885,267888,267892,267900,267938,267941,267947,267953,267965,267969,267978,268002,268003,268005,268018,268020,268048,268090,268105,268109,268118,268133,268146,268147,268151,268160,268162,268166,268180,268199,268200,268202,268204,268206,268212,268213,268214,268222,268232,268237,268259,268261,268270,268272,268282,268291,268299,268308,268315,268320,268342,268347,268380,268387,268404,268411,268415,268436,268445,268447,268473,268478,268505,268511,268531,268542,268548,268554,268555,268558,268583,268614,268631,268634,268653,268658,268660,268663,268697,268698,268703,268721,268724,268739,268773,268776,268780,268782,268788,268804,268805,268812,268823,268832,268844,268853,268863,268865,268871,268889,268893,268894,268899,268902,268905,268906,268914,268916,268918,268919,268949,268950,268970,268975,268985,269003,269006,269030,269040,269073,269100,269103,269107,269111,269121,269135,269142,269144,269149,269166,269173,269187,269196,269200,269208,269219,269226,269230,269231,269232,269250,269271,269272,269305,269308,269311,269313,269317,269319,269325,269347,269349,269368,269370,269371,269381,269394,269397,269410,269412,269419,269440,269444,269448,269474,269477,269490,269512,269517,269520,269527,269528,269530,269534,269549,269552,269558,269566,269569,269571,269581,269591,269600,269603,269615,269619,269630,269634,269640,269642,269648,269649,269651,269652,269654,269656,269669,269670,269677,269686,269688,269705,269708,269730,269743,269753,269754,269758,269759,269760,269763,269768,269778,269787,269792,269794,269796,269799,269803,269813,269816,269818,269829,269847,269850,269854,269858,269860,269866,269869,269883,269891,269893,269897,269898,269899,269901,269914,269920,269927,269932,269946,269949,269950,269957,269965,269969,269990,270008,270009,270016,270018,270027,270047,270050,270061,270066,270092,270102,270108,270120,270127,270131,270136,270137,270139,270142,270144,270145,270150,270166,270176,270213,270225,270227,270234,270251,270252,270253,270262,270265,270275,270281,270282,270308,270311,270314,270320,270322,270326,270333,270334,270339,270342,270346,270348,270357,270363,270377,270383,270388,270409,270458,270464,270507,270522,270529,270535,270540,270544,270547,270557,270562,270580,270588,270592,270600,270608,270609,270632,270644,270661,270667,270682,270684,270709,270710,270713,270714,270718,270721,270725,270739,270746,270751,270760,270764,270772,270778,270792,270795,270796,270803,270805,270807,270809,270824,270826,270861,270872,270876,270883,270891,270893,270894,270899,270901,270909,270911,270919,270924,270926,270936,270941,270954,270957,270966,270983,270984,270997,270998,271000,271005,271017,271042,271067,271068,271077,271094,271116,271121,271131,271138,271142,271147,271162,271177,271180,271194,271204,271208,271216,271217,271222,271226,271228,271235,271239,271250,271254,271258,271261,271275,271279,271281,271283,271289,271290,271303,271310,271322,271345,271352,271356,271362,271371,271382,271394,271400,271403,271412,271414,271421,271436,271447,271449,271481,271482,271484,271486,271498,271529,271537,271538,271550,271551,271557,271570,271572,271579,271599,271605,271612,271615,271668,271671,271673,271676,271691,271700,271702,271721,271726,271728,271748,271749,271759,271766,271772,271803,271809,271812,271817,271819,271824,271834,271838,271864,271869,271895,271916,271931,271936,271953,271960,271967,271974,271980,271984,271988,271997,272000,272001,272014,272068,272072,272078,272086,272089,272098,272113,272115,272116,272128,272135,272136,272141,272143,272166,272179,272181,272206,272208,272237,272239,272240,272265,272276,272278,272324,272337,272349,272357,272360,272364,272365,272368,272381,272386,272393,272394,272403,272407,272411,272417,272421,272429,272455,272459,272468,272476,272479,272485,272490,272492,272495,272503,272516,272537,272559,272561,272584,272593,272605,272609,272610,272616,272622,272627,272648,272669,272673,272674,272676,272684,272702,272705,272720,272724,272746,272755,272769,272781,272785,272789,272800,272807,272835,272838,272843,272865,272883,272891,272897,272914,272916,272917,272920,272955,272965,272974,272984,272985,272986,272987,272989,272994,272995,273003,273009,273013,273027,273029,273038,273045,273046,273054,273083,273084,273085,273097,273108,273116,273125,273128,273129,273139,273152,273167,273191,273193,273216,273224,273240,273248,273252,273273,273275,273282,273283,273284,273304,273321,273326,273334,273343,273345,273347,273358,273365,273392,273397,273425,273463,273488,273492,273494,273515,273516,273521,273534,273535,273541,273552,273558,273566,273599,273610,273623,273641,273675,273686,273689,273690,273721,273729,273742,273744,273763,273765,273772,273797,273819,273877,273878,273964,273968,273972,274000,274014,274025,274057,274110,274213,274217,274308,274320,274387,274463,274483];
            $application_list = [260473,262055,262108,262478,262639,262999,264194,264418,265626,265651,266112,266123,266571,266586,267554,267556,267598,267600,268648,268712,269632,270084,270268,270925,271331,271991,273853];
            foreach(array_chunk($application_list, 200) as $app_ids) {
                foreach($app_ids as $app_id) {
                    $exceptionList = [262979, 262999, 263304, 258629, 253121, 258629, 270925];
                    $application = ConsumerApplication::with('emi', 'emi.offer')->where('id', $app_id)->whereNotIn('id', $exceptionList)->first(['id', 'state']);
                    if (strtotime(Carbon::now()->format('d-m-Y')) >= strtotime(_env('CF_RPS_START_DATE')) && isset($application->state)) {
                        (new Slack(new Request(['title' => 'New RPS log script - 1', 'fields' => ['id' => $app_id], 'group' => Slack::$STAGE_TESTING])))->send();

                        $application_details = ConsumerApplication::with(['offer' => function ($query) {
                            $query->select('id', 'tenure', 'advance_emi', 'interest_rate', 'annualised_irr');
                        }, 'emi' => function ($query) {
                            $query->select('application_id', 'offer_id', 'tenure', 'remaining_emi', 'advance_emi', 'emi_date',
                                'subvention', 'processing_fee',
                                'annualised_interest', 'annualised_irr', 'upfront_from_customer');
                        }, 'proFormaInvoice' => function ($query) {
                            $query->select('application_id', 'insurance_premium_amount');
                        }, 'application_element' => function ($query) {
                            $query->select('application_id', 'payment_transfer_date');
                        }, 'disbursed' => function ($query) {
                            $query->select('application_id', 'created_at');
                        },
                        ])->where('id', $app_id)->first(['id', 'loan_amount', 'approved_amount', 'offer_id']);

                        $payload = [
                            'loan_principal' => $application_details->approved_amount - $application_details->emi->upfront_from_customer ?? $application_details->loan_amount - $application_details->emi->upfront_from_customer ?? 0,
                            'annualised_interest' => (float)$application_details->emi->annualised_interest ?? (int)$application_details->offer->annualised_irr ?? 0,
                            'annualised_irr' => (float)$application_details->emi->annualised_irr ?? (int)$application_details->offer->annualised_irr ?? 0,
                            'remaining_emi' => $application_details->emi->remaining_emi ?? $application_details->offer->tenure - $application_details->offer->advance_emi ?? 0,
    //            'disbursal_date_str' => $payment_transfer_date != null ? Carbon::parse($payment_transfer_date)->format('d-m-Y') : Carbon::now()->toDate()->format('d-m-Y'),
                            'disbursal_date_str' => Carbon::parse($application_details->disbursed->created_at)->format('d-m-Y'),
                            'first_emi_date_str' => Carbon::parse($application_details->emi->emi_date)->format('d-m-Y'),
                            'morat_months' => 0,
                            'morat_start_date_str' => '',
                            'subvention' => $application_details->emi->subvention ?? 0,
                            'insurance_amount' => $application_details->pro_forma_invoice->insurance_premium_amount ?? 0,
                            'processing_fee' => $application_details->emi->processing_fee ?? 0,
                        ];
                        $payload = json_encode($payload);
                        (new Slack(new Request(['title' => 'New RPS log script - 2', 'fields' => ['id' => $app_id, 'payload' => json_encode($payload)], 'group' => Slack::$STAGE_TESTING])))->send();
                        $curl = curl_init();
                        curl_setopt_array($curl, array(
                            CURLOPT_URL => _env('CF_RPS_ENDPOINT', 'http://65.1.61.53:8000/api/5th_emi_date'),
                            CURLOPT_RETURNTRANSFER => true,
                            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',
                            ),
                        ));

                        $curl1 = $curl;

                        $response = curl_exec($curl1);
                        (new Slack(new Request(['title' => 'New RPS log script - 3', 'fields' => ['id' => $app_id, 'response' => json_encode($response)], 'group' => Slack::$STAGE_TESTING])))->send();

                        if (curl_error($curl1)) {
                            $error = curl_error($curl1);
                            (new Slack(new Request(['title' => 'New RPS log script Error', 'fields' => [$error]])))->send();
                        }
                        curl_close($curl1);

                        $response = json_decode($response, 1);

                        if (isset($response['rps_json'])) {
                            $rps_summary = $response;
                            $rps_json = $response['rps_json'];
                            unset($rps_summary['rps_json']);

                            foreach ($rps_json as $index => $resp) {
                                $rps_json[$index]['application_id'] = (int)$app_id ?? 0;
                                $rps_json[$index]['created_at'] = Carbon::now()->toDateTimeString();
                                $rps_json[$index]['loan_summary'] = $index == 0 ? json_encode($rps_summary) : null;

                            }

                            $is_update = RPS_Logs_new::where('application_id', $app_id)->exists();

                            if ($is_update) {
                                RPS_Logs_new::where('application_id', $app_id)->delete();
                            }

                            RPS_Logs_new::insert($rps_json);
                            (new Slack(new Request(['title' => 'New RPS log script completed - 4', 'fields' => ['id' => $app_id], 'group' => Slack::$STAGE_TESTING])))->send();
                        }
                    }
                }
            }
            (new Slack(new Request(['title' => 'New RPS log script complete! - 5', 'group' => Slack::$STAGE_TESTING])))->send();
        } catch (\Exception $e) {
            $cwFactory = new CloudWatchLoggerFactory();
            $_data = array(
                'exception' => 'Error while calling New RPS Script',
                'message' => $e->getMessage(),
                'line' => $e->getLine(),
                'trace' => $e->getTraceAsString()
            );
            $cwFactory->logger(json_encode($_data));
        }
        return false;
    }

    // Script to create entries in emi_payments table from rps_logs
    public function saveRPSInEmiPayments(){
        $application_list = [];
        $repaymentController = new RepaymentController();
        foreach(array_chunk($application_list, 10) as $app_ids) {
            foreach ($app_ids as $app_id) {
                $exceptionList = [262979, 262999, 263304, 258629, 253121, 258629, 270925];

                if(!in_array($app_id, $exceptionList)){
                    $exists = $repaymentController->checkRPSExists($app_id);

                    if ($exists) {
                        $repaymentController->setEMIdetails($app_id);
                    }
                }
            }
        }
    }

    // Script to re-run allocation of payments
    public function runAllocationScriptBPI(){
        $repaymentController = new RepaymentController();
        $application_list = [258487,258757,259537,259779,260118,260133,260461,260977,261493,261807,261871,261874,262096,262181,262181,262181,262181,262181,262185,262333,262394,262810,262899,262904,262904,262954,262985,263077,263100,263112,263112,263112,263112,263144,263144,263144,263158,263215,263219,263267,263385,263433,263444,263486,263487,263534,263537,263580,263592,263594,263624,263655,263668,263675,263675,263675,263706,263727,263791,263791,263791,263791,264376,264395,264495,264594,264608,264645,264665,264754,264754,264829,264891,264967,264967,265030,265095,265106,265117,265117,265117,265197,265201,265213,265257,265257,265399,265399,265399,265518,265541,265555,265575,265695,265790,265843,265885,265895,266012,266055,266089,266121,266201,266239,266239,266239,266283,266316,266345,266425,266509,266602,266609,266609,266731,266751,266751,266751,266754,266754,266760,266775,266775,266777,266777,266777,266807,266837,266837,266837,266885,266885,266885,266885,266929,266929,266998,266998,266998,266998,267053,267063,267063,267067,267067,267080,267080,267093,267093,267093,267094,267094,267094,267123,267123,267123,267141,267141,267141,267160,267160,267160,267188,267201,267201,267227,267227,267227,267302,267308,267308,267326,267326,267326,267334,267376,267382,267382,267382,267383,267383,267383,267383,267417,267417,267417,267430,267457,267457,267457,267467,267467,267499,267499,267544,267544,267549,267564,267564,267564,267578,267585,267585,267585,267609,267634,267651,267651,267651,267669,267669,267710,267722,267722,267722,267742,267754,267754,267793,267813,267938,267941,267953,267965,267965,267965,268005,268005,268090,268183,268213,268222,268222,268237,268259,268277,268291,268315,268355,268505,268546,268548,268554,268660,268721,268788,268844,268906,268950,269135,269173,269271,269272,269272,269305,269308,269313,269490,269517,269534,269549,269566,269630,269642,269651,269743,269758,269869,269883,269899,270050,270108,270110,270127,270137,270210,270231,270348,270522,270529,270778,271362,271529,271819,274110];
        foreach(array_chunk($application_list, 10) as $app_ids) {
            foreach ($app_ids as $app_id) {
                $exceptionList = [262979, 262999, 263304, 258629, 253121, 258629, 270925];

                if(!in_array($app_id, $exceptionList)){

                    $rows = PaymentTransaction::where('application_id', $app_id)
                        ->whereIn('payment_for', ['EMI', 'Pre-EMI'])
                        ->whereNull('deleted_at')
                        ->whereNull('is_deleted_at')->get();

                    $payments = $rows->groupBy('cf_transaction_id')->map(function ($group) {
                        $total = $group->sum('amount');
                        return $group->first()->toArray() + ['total_score' => $total];
                    })->values();

//                    $payments = PaymentTransaction::select('cf_transaction_id', 'payment_date', 'payment_for', 'mode', 'paid_by',
//                        'collected_by', 'collected_by_type', 'trasanction_id', 'trasanction_acknowledgement', 'status',
//                        'payment_reconciliation_date', 'wallet_name', 'bank_id', 'cf_transaction_id', 'reason', 'umrn', 'status', 'adjust_with_disbursement'
//                    )
//                        ->selectRaw('SUM(amount) as total_paid')
//                        ->where('application_id', $app_id)
//                        ->whereIn('payment_for', ['EMI', 'Pre-EMI'])
//                        ->whereNull('deleted_at')
//                        ->whereNull('is_deleted_at')
//                        ->groupBy('cf_transaction_id')
//                        ->get();

                    PaymentTransaction::where('application_id', $app_id)->whereIn('payment_for', ['EMI', 'Pre-EMI'])
                        ->whereNull('deleted_at')->whereNull('is_deleted_at')->update([
                       'deleted_at' => Carbon::now()->endOfDay()->toDateTimeString(),
                       'is_deleted_at' => Carbon::now()->endOfDay()->toDateTimeString(),
                       'deleted_by' => 107,
                    ]);

                    foreach($payments as $payment) {
                        $_data = [
                            'amount' => (int)$payment['total_score'],
                            'payment_date' => Carbon::parse($payment['payment_date'])->format('d-m-Y'),
                            'payment_for' => $payment['payment_for'],
                            'payment_mode' => $payment['mode'],
                            'paid_by' => $payment['paid_by'],
                            'collected_by' => $payment['collected_by'],
                            'collected_by_type' => $payment['collected_by_type'],
                            'trasanction_id' => $payment['trasanction_id'],
//                            'online_payment_id' => $payment->online_payment_id,
                            'trasanction_acknowledgement' => $payment['trasanction_acknowledgement'],
                            'payment_status' => $payment['status'],
                            'payment_reconciliation_date' => Carbon::parse($payment['payment_reconciliation_date'])->format('d-m-Y'),
                            'wallet_name' => $payment['wallet_name'],
                            'bank_id' => $payment['bank_id'],
                            'cf_transaction_id' => $payment['cf_transaction_id'],
                            'reason' => $payment['reason'],
                            'umrn' => $payment['umrn'],
                            'status' => $payment['status'],
                            'adjust_with_disbursement' => $payment['adjust_with_disbursement'],
                        ];
                        $repaymentController->reconcilePayment($app_id, $_data);
                    }
                }
            }
        }
        return true;
    }

    //This function is to adjust the pending interest or principal in the older EMIs to avoid the wrong dpd bucket calculation
    public function adjustPaymentTransactionsInEMI(){
        $ids = [];
        foreach($ids as $id) {
            (new LoanManagement())->paymentCalculate($id);
            $emi_payments = EmiPayment::with('transaction')->where('application_id', $id)->get();

            $response = [];
            $transactions_data = [];
            foreach ($emi_payments as $emi_payment) {
                if ($emi_payment->pre_emi_amount == 0) {
                    $emi_date = $emi_payment->emi_date;
                    $emi_amount = $emi_payment->emi_amount - $emi_payment->moratorium_amount;
                    $payable = $emi_payment->total_payable;
                    $bp = ($emi_payment->bounce_charges + $emi_payment->delay_penalty);
                    $cp = $emi_payment->moratorium_amount;
                    $pending_amount = $emi_payment->total_payable - ($bp + $cp);


                    $emi_received = 0;
                    foreach ($emi_payment->transaction as $transaction) {
                        $emi_received += $transaction->amount;
                        $transactions_data[$emi_date][] = ['amount_received' => $transaction->amount, 'transaction' => $transaction];
                    }

                    if ($emi_received > $emi_amount) {
                        $emi_received = $emi_amount;
                    }

                    $emi_pending = $emi_payment->total_payable > $emi_amount ? ($pending_amount < $emi_amount ? $pending_amount : 0) : 0;


                    $expected_emi = $pending_amount - $emi_received;
                    $response[$emi_payment->emi_date] = ['expected_emi' => $expected_emi, 'emi_amount' => $emi_amount, 'id' => $emi_payment->id];
                }

            }


            $updated_response = [];
            $adjusted_emis = [];
            foreach (array_reverse($transactions_data) as $key => $tr_data) {

                if (!in_array($key, $adjusted_emis)) {
                    foreach ($tr_data as $key1 => $reversed) {

                        $pending_to_allocate = $transactions_data[$key][$key1]['amount_received'];

                        if ($pending_to_allocate) {

                            foreach ($response as $emi_date => $item) {

                                if ($item['expected_emi'] > 0 && $pending_to_allocate && $key > $emi_date) {

                                    $adjusted_emi_from_transaction = 0;
                                    if ($pending_to_allocate <= $item['expected_emi']) {
                                        $adjusted_emi_from_transaction = $item['expected_emi'] - $pending_to_allocate;
                                        $response[$emi_date]['expected_emi'] = $adjusted_emi_from_transaction;
                                        $adjusted_emi = $pending_to_allocate;
                                        $pending_to_allocate = 0;
                                    } else {
                                        $adjusted_emi = $item['expected_emi'];
                                        $pending_to_allocate -= $item['expected_emi'];
                                        $response[$emi_date]['expected_emi'] = 0;
                                    }
                                    if ($pending_to_allocate < 0) {
                                        $pending_to_allocate += $item['expected_emi'];
                                        $adjusted_emi = 0;
                                        continue;
                                    }

                                    $trDataEntry = [];
                                    $trDataEntry['id'] = $transactions_data[$key][$key1]['transaction']['id'];
                                    $trDataEntry['amount'] = $adjusted_emi;
                                    $trDataEntry['adjusted_from_emi_date'] = $key;
                                    $trDataEntry['emi_payment_id'] = $item['id'];
                                    $updated_response[$emi_date][] = ['id' => $item['id'], 'emi_date' => $emi_date, 'expected_emi' => $item['expected_emi'], 'revised_expected_emi' => $adjusted_emi_from_transaction, 'adjusted_emi' => $adjusted_emi, 'transaction' => $trDataEntry, 'paymentTransaction' => $transactions_data[$key][$key1]['transaction']];
                                    $transactions_data[$key][$key1]['amount_received'] = $pending_to_allocate;
                                    $transactions_data[$key][$key1]['is_change'] = 1;
                                    $adjusted_emis[] = $emi_date;
                                }
                            }
                        }
                    }
                }
            }


            $transaction_to_be_updated = [];
            foreach ($transactions_data as $t => $_transactions_data) {
                foreach ($_transactions_data as $c => $new_item) {
                    if (isset($new_item['is_change'])) {
                        //$transactions_data[$t][$c]['transaction']['amount'] = $new_item['amount_received'];
                        $transaction_to_be_updated[] = $new_item;
                    }
                }
            }


            return [
                'updated_response' => $updated_response,
                'transaction_to_be_updated' => $transaction_to_be_updated
            ];

            if($updated_response) {
                foreach ($updated_response as $__updated_response) {
                    foreach ($__updated_response as $_updated_response) {
                        try {
                            $columns = ['mode', 'trasanction_id', 'trasanction_acknowledgement', 'payment_date', 'status', 'created_at', 'updated_at', 'paid_by', 'collected_by', 'wallet_name', 'reason', 'umrn', 'application_id', 'payment_for', 'payment_reconciliation_date', 'cf_transaction_id', 'bank_name', 'bank_id', 'deleted_at', 'is_deleted_at', 'deleted_by', 'refunded_at', 'refunded_by', 'collected_by_type', 'adjust_with_disbursement', 'adjusted_to', 'adjusted_by', 'differ_id', 'refund_maker_id', 'refund_maker_at', 'settlement_date'];
                            $to_be_update_columns = [];
                            foreach ($columns as $_c) {
                                $to_be_update_columns[$_c] = $_updated_response['paymentTransaction']->$_c;
                            }
                            $paymentTransaction = new PaymentTransaction();
                            $paymentTransaction->fill($to_be_update_columns);
                            $paymentTransaction->amount = $_updated_response['adjusted_emi'];
                            $paymentTransaction->emi_payment_id = $_updated_response['transaction']['emi_payment_id'];
                            $paymentTransaction->save();
                        }catch (\Exception $e){
                            $error = $e;
                        }
                    }
                }
            }

            if($transaction_to_be_updated) {
                foreach ($transaction_to_be_updated as $_transaction_to_be_updated) {
                    PaymentTransaction::where('id', $_transaction_to_be_updated['transaction']->id)->update(['amount' => $_transaction_to_be_updated['amount_received']]);
                }
            }

//            return [
//                'updated_response' => $updated_response,
//                'transaction_to_be_updated' => $transaction_to_be_updated
//            ];
        }
    }
}
