<?php

namespace App\Http\Controllers\Admin;

use App\AccountAggregator;
use App\AccountAggregatorModel;
use App\AccountAggregatorMonitoring;
use App\ConsumerApplication;
use App\ConsumerApplicationFiles;
use App\EmiPayment;
use App\Events\V1\EventAgencyCommunication;
use App\Events\V1\EventAgencyApplication;
use App\Exports\Exporter;
use App\Http\Controllers\Controller;
use App\Imports\CallingFile;
use App\LoanManagement;
use App\PaymentTransaction;
use App\PromiseToPay;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Storage;
use App\CampaignsJobProvider;
use App\JobProvider;
use App\Imports\CollectionImport;
use App\AgencyApplication;
use App\Slack;
use App\Products;
use App\Templates;

class CollectionController extends Controller{

    private $request;

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

    public function dailyCallingFile(){
        return view('admin.collection.daily_calling');
    }

    public function dailyCallingImport(){
        try {
            Excel::import(new CallingFile($this->request), $this->request->file('calling_file'));
            \Session::flash('success', 'Calling file successfully processed');
            return redirect()->back();
        }catch (\Exception $e){
            \Session::flash('error', 'Something went wrong, '.$e->getFile().$e->getLine());
            return redirect()->back();
        }
    }

    public function auditReport(){
        $from_date = $this->request->has('from_date') ? $this->request->get('from_date') : Carbon::now()->startOfMonth()->toDateString();
        $to_date = $this->request->has('to_date') ? $this->request->get('to_date') : Carbon::now()->endOfMonth()->toDateString();

        if($this->request->has('from_date') && $this->request->has('to_date')){

            $applications = ConsumerApplication::with('merchant','application_element')->whereIn('state',['disbursed','nach registered'])->whereNull('is_deleted')
                ->whereHas('logs', function ($query) use ($from_date, $to_date) {
                    $query->whereIn('status', ['disbursed','nach registered'])->where('created_at', '>=', $from_date)->where('created_at', '<=', $to_date)->where('is_reversed',0);
                })->groupBy('id')->get();

            $response[] = ['ID','Name','Phone','Merchant Name','Product Name','Address', 'Invoice' ,'Permanent Address Line 1','Permanent Address Pincode'];
            foreach ($applications as $application){
                if($application->logs && in_array($application->state,['disbursed','nach registered'])) {

                    $file = ConsumerApplicationFiles::where('consumer_application_id', $application->id)->where('file_type','proforma')->first(['file_path']);
                    $product_name = $application->application_element->product_name;
                    $product_name_by_id = Products::where('id',$product_name)->whereNull('deleted_at')->value('name');
                    if ($product_name_by_id != null) {
                        $product_name = $product_name_by_id;
                     }
                    $response[] = [
                        'id' => $application->id,
                        'name' => $application->name,
                        'Contact_no' => $application->mobile_number,
                        'merchant_name' => $application->merchant->merchant_name,
                        'product_name' => $product_name,
                        'address' => str_replace(',,',',', $application->permanent_address_line_1 . ' ' . $application->permanent_address_landmark . ', ' . $application->permanent_address_city . ', ' . $application->permanent_address_pincode . ' ' . $application->permanent_address_state),
                        'invoice' => isset($file->file_path) ? asset('/admin/consumer-application/get-documents').'/'.$file->file_path : '',
                        'permanent_address_line_1' => $application->permanent_address_line_1,
                        'permanent_address_pincode' => $application->permanent_address_pincode,
                    ];
                }
            }


            if($response) {
                $request = new Request(['data' => $response, 'sheet' => 'Sheet1']);
                return Excel::download((new Exporter($request)), 'Audit_Report_From_' . $from_date . '_To_' . $to_date . '.xls');
            }else{
                \Session::flash('error', 'No data found in selected period');
                return redirect()->back();
            }
        }

        return view('admin.collection.audit_report', ['from_date' => $from_date, 'to_date' => $to_date]);
    }

    public function getPaymentInfo(){

        $txn_id = $this->request->get('txn_id');

        $response = [];

        if ($this->request->has('export')){
            $response[] = ['ID', 'Name', 'Paid Amount'];
        }

        if ($txn_id) {
            $PaymentTransaction = PaymentTransaction::with(array('application'=>function($query){
                $query->select('id','name');
            }))->where('trasanction_id', $txn_id)->whereNull('is_deleted_at')->get(['id', 'application_id', 'amount']);

            foreach ($PaymentTransaction as $item) {
                $response[] = [
                    'id' => $item->application_id,
                    'name' => $item->application->name,
                    'amount' => $item->amount,
                ];
            }

            if ($this->request->has('export')){
                $request = new Request(['data' => $response, 'sheet' => 'Sheet1']);
                return Excel::download((new Exporter($request)), 'Payment Info Data' . Carbon::now()->toDateTimeString() . '.xls');
            }
        }


        return view('admin.collection.payment_info', ['txn_id' => $txn_id, 'payment_info' => $response]);
    }

    public function getPaymentMIS(){
        $from_date = $this->request->has('from_date') ? $this->request->get('from_date') : Carbon::now()->startOfMonth()->toDateString();
        $to_date = $this->request->has('to_date') ? $this->request->get('to_date') : Carbon::now()->endOfMonth()->toDateString();

        $response = [];

        if($this->request->get('export')){
            if ($this->request->get('from_date') && $this->request->get('to_date')) {
            $payments = \DB::select('SELECT payment_transactions.* from payment_transactions LEFT join consumer_application on consumer_application.id = payment_transactions.application_id where payment_transactions.payment_date BETWEEN "'.$from_date.' 00:00:00" and "'.$to_date.' 23:59:59" and consumer_application.is_deleted is null and payment_transactions.is_deleted_at is null');

            if(isset($payments[0])){

                $auth = Auth::user();
                $email = $auth->email;

                $jobs = new CampaignsJobProvider();
                $jobs->from = 'paymentMISReport';
                $jobs->payload = json_encode(['email' => $email, 'from_date' => $from_date, 'to_date' => $to_date]);
                $jobs->available_at = Carbon::now()->toDateTimeString();
                $jobs->application_id = 181;
                $jobs->created_at = Carbon::now()->toDateTimeString();
                $jobs->is_available = 0;
                $jobs->save();

                \Session::flash('success', 'Data will be received on your email');
                }
            }else{
                \Session::flash('error', 'No data found in selected period');
            }
        }

        return view('admin.collection.payment_mis', ['from_date' => $from_date, 'to_date' => $to_date, 'payment_mis' => []]);
    }

    public function generateEMIPPendingCase(){
        $status = "'disbursed','nach registered'";
        $apps = DB::select("select consumer_application.id from consumer_application left join emi_payments on emi_payments.application_id = consumer_application.id where state in(".$status.") and emi_payments.id is null and consumer_application.is_deleted is null");
        foreach ($apps as $app){
            if(isset($app->id)) {
                (new LoanManagement())->paymentCalculate($app->id);
            }
        }
    }

    public function sendMISReport(){

        try {
            $from_date = $this->request->has('from_date') ? $this->request->get('from_date') : Carbon::now()->startOfMonth()->toDateString();
            $to_date = $this->request->has('to_date') ? $this->request->get('to_date') : Carbon::now()->endOfMonth()->toDateString();

            $payments = \DB::select('SELECT payment_transactions.*, lenders.name as lender_name from payment_transactions LEFT join consumer_application on consumer_application.id = payment_transactions.application_id LEFT join lenders on lenders.id = consumer_application.lender_id where payment_transactions.payment_date BETWEEN "' . $from_date . ' 00:00:00" and "' . $to_date . ' 23:59:59" and consumer_application.is_deleted is null and payment_transactions.is_deleted_at is null');

            if (isset($payments[0])) {

                $email = $this->request->get('email');

                if ($email) {
                    $response[] = array_map(function ($item) {
                        return ucwords(str_replace('_', ' ', $item));
                    }, array_keys((array)$payments[0]));

                    $payments = json_decode(json_encode($payments), true);

                    $response = array_merge($response, $payments);
//                    $request = new Request(['data' => $response, 'sheet' => 'Sheet1']);

                    $path1 = storage_path().'/app/Payment_MIS.csv';
                    $file = fopen($path1,"w");

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

//                    $file = 'Payment MIS Data_' . Carbon::now()->toDateString() . '.xls';
//                    Excel::store(new Exporter($request), $file);

                    Mail::send('emails.reminders.basic_reminder',
                        ['body' => 'Payment MIS Report ']
                        , function ($message) use ($path1, $email, $from_date, $to_date) {
                            $message->to($email)->cc(['sarah@creditfair.in'])->subject('Payment MIS Report');
                            $message->attach($path1, ['as' => 'Payment_MIS_Data'.$from_date.'_'.$to_date.'.csv']);
                        });

                    unlink($path1);
                }

            }
        }catch(\Exception $e){
            (new Slack(new Request(['title'=>'Error while sending Payment MIS','fields'=> ['e' => $e->getMessage(),'l' => $e->getLine(),'t' => $e->getTraceAsString()]])))->send();
        }
    }

    public function dailyPtpInfo(){

        $header[] = ['Agent Name','Total PTP Tagged', 'Total PTP Paid', 'Total PTP Broken'];

        $dailyPTP = PromiseToPay::selectRaw('sum(CASE WHEN cast(now() as date) THEN 1 ELSE 0 END) AS count, sum(CASE WHEN(cast(promise_to_pay.date as date) = cast(now() as date)) AND (promise_to_pay.payment_received = 0) THEN 1 ELSE 0 END) AS totalunpaid, sum(CASE WHEN(promise_to_pay.payment_received = 1) AND (promise_to_pay.payment_received_date is not NULL) THEN 1 ELSE 0 END) AS totalpaid, users.name')->join('users','promise_to_pay.user_id','users.id')->where('promise_to_pay.created_at','>=', Carbon::now()->startOfDay()->toDateTimeString())->where('promise_to_pay.created_at','<=',Carbon::now()->endOfDay()->toDateTimeString())->groupBy('users.name')->orWhere('promise_to_pay.date',Carbon::now()->toDateString())->get();
        // check if $dailyPTP has some count or not
        if(count($dailyPTP)) {
            foreach ($dailyPTP as $ptp) {
                $response[] = [
                    'agent_name' => $ptp['name'],
                    'total_ptp_tagged' => $ptp['count'],
                    'total_ptp_paid' => $ptp['totalpaid'],
                    'total_ptp_broken' => $ptp['totalunpaid'],
                ];
            }

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

            $mail_ids = _env('APP_CONNECTION') ? ['imran@creditfair.in', 'ketan@creditfair.in', 'rajendra@creditfair.in'] : ['himanshubamania@creditfair.in', 'pratik@creditfair.in', 'suyog@creditfair.in'];
            Mail::send('emails.reminders.basic_reminder',
                ['body' => 'Daily PTP Tagging Data']
                , function ($message) use ($file, $mail_ids) {
                    $message->to($mail_ids)->subject('Daily PTP Tagging Data');
                    $message->attachData(file_get_contents(storage_path() . '/app/' . $file), $file);
                });

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

        CampaignsJobProvider::where('from', 'dailyPtpInfo')->update(['is_available' => 0, 'available_at' => Carbon::now()->addDay(1)->endOfDay()->toDateTimeString()]);
    }

    public function agencyData(Request $request){
        if($request->hasFile('agency_file')){
            $this->request->validate([
                'agency_file' => 'required|max:5000|mimes:xlsx,xls',
            ]);

            // $Excelfile = $this->request->file('agency_file');
            // $array = (new CollectionImport())->toArray($Excelfile);
//
            // if(count($array[0]) > 0){
            //     try{
            //         foreach($array[0] as $entry => $excel_entry){
            //             if(($excel_entry['application_id'] == null || empty($excel_entry['application_id'])) || ($excel_entry['agreement_number'] == null || empty($excel_entry['agreement_number'])) || ($excel_entry['name'] == null || empty($excel_entry['name'])) || ($excel_entry['merchant_name'] == null || empty($excel_entry['merchant_name'])) || ($excel_entry['agency_id'] == null || empty($excel_entry['agency_id']))){
            //                 return back()->with('error','Please check for empty fields in excel file before uploading');
            //             }
            //         }
            //     }catch(\Exception $e){
            //         (new Slack(new Request(['title' => 'Agency Application Upload Error',
            //         'fields' => ['message' => 'Upload File Entries/Size Too large to compute', 'id' => 107, 'error'=>$e, 'message'=>$e->getMessage()],'group' => 'payment_collection'])))->send();
            //     }
            // }else{
            //     return back()->with('error','Empty File Failed to Upload Data');
            // }

            $file = $request->file('agency_file'); // Retrieve the uploaded file from the request
            $filename = $file->getClientOriginalName(); // Retrieve the original filename
            $path = 'agency/'.Carbon::now()->toDateString(). '/'.$filename;

//            Storage::disk('local')->put($filename, file_get_contents($file));
            $s3 = Storage::disk('s3');
            $s3->put($path, file_get_contents($file));
            // Storage::disk('local')->delete($filename);
            $mailtocf = false;
            if($s3->exists($path)){
                // if(Session::has('Agency_Allotment_View|4-13-0')){
                    $mailtocf = true;
                // }
                $fileUploaderId = Auth::user()->id;

                event(new EventAgencyApplication(['fileUploaderId' => $fileUploaderId, 'filename' => $path, 'mailtocf' => $mailtocf]));
            }

            // $payload[] = [
            //     'payload' => json_encode(['fileUploaderId' => Auth::user()->id, 'filename' => $filename, 'mailtocf'=> $mailtocf]),
            //     'from' => 'ImportAgencyApplication',
            //     'application_id' => 107,
            //     'available_at' => Carbon::now()->toDateTimeString(),
            //     'created_at' => Carbon::now()->toDateTimeString()
            // ];

            // JobProvider::insert($payload);

            return back()->with('success','Excel Data will be uploading in shortly');
        }else{
            return view('admin.collection.agency');
        }
    }

    public function importAgencyApplication($filename,$fileUploaderId,$mailtocf){

        // if (Storage::disk('local')->exists($filename)) {
        //     $Excelfile = Storage::disk('local')->get($filename);
        // }else{
        if(!Storage::disk('s3')->exists($filename)){
            // throw new FileNotFoundException(sprintf('File not found: %s', $payload->filename), 404);
            $data['status'] = 'FAIL';
            $data['message'] = 'File Not Found '.$filename;
            throw new \Exception($data['message']);
        }

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

        // $emails = _env('APP_CONNECTION') ? ['imran@creditfair', 'amol@creditfair.in', 'ketan@creditfair.in'] : ['himanshubamania@creditfair.in'];
        //         Mail::send('emails.reminders.basic_reminder', [
        //             'body' => 'Please check the attached excel that is uploaded by '.'Himanshu'.'.'], function ($message) use ($Excelfile,$emails) {
        //             $message->to($emails)->subject('Excel File From Agency');
        //             // $message->attach($Excelfile, array(
        //             //     'as' => 'Agency Report_'.Carbon::now()->toDateString(),
        //             //     'mime' => $Excelfile->getMimeType())
        //             // );
        //             $message->attachData(file_get_contents(storage_path() . '/app/' . $Excelfile), $Excelfile);
        //         });

        //         return true;

        // $array = Excel::toArray(new CollectionImport(), $payload->filename);

        $s3 = Storage::disk('s3');
        // $file = $s3->url($filename);
        $s3data = $s3->get($filename);
        $filename = explode('/',$filename);
        Storage::disk('local')->put(end($filename), $s3data);
        $localFileName = end($filename);
        $array = (new CollectionImport())->toArray($localFileName);

        // excel file not empty
        if(count($array[0]) > 0){
            //$query = "SELECT t.id, t.application_id, t.agency_id FROM agency_application t inner join(select application_id, max(created_at) as MaxDate, deleted_at from agency_application group by application_id limit 1) tm on t.created_at = tm.MaxDate AND tm.deleted_at IS NOT NULL order by tm.deleted_at DESC";
            //$query = "select * from agency_application where deleted_at is null order by created_at desc";
            $query = "select application_id,agency_id,deleted_at from agency_application order by created_at desc";
            $old_data = DB::select($query);
            $sms_id_arr = [];
            $old_id_arr = [];
            $agency_old_arr = [];
            if(!empty($old_data)){
                foreach($old_data as $v){
                    $old_id_arr[] = $v->application_id;
                }
                $old_id_arr = array_unique($old_id_arr);
            }
            foreach($array[0] as $entry => $excel_entry){
                if(($excel_entry['application_id'] == null || empty($excel_entry['application_id'])) || ($excel_entry['agreement_number'] == null || empty($excel_entry['agreement_number'])) || ($excel_entry['name'] == null || empty($excel_entry['name'])) || ($excel_entry['merchant_name'] == null || empty($excel_entry['merchant_name'])) || ($excel_entry['agency_id'] == null || empty($excel_entry['agency_id']))){
                    // return back()->with('error','Please check for empty fields in excel file before uploading');
                    $data['status'] = 'FAIL';
                    $data['message'] = 'Please check for empty fields or missing column in excel file before uploading';
                    throw new \Exception($data['message']);
                }
                $agencyApplications[] = ['application_id' => trim($excel_entry['application_id']),
                    'agreement_number' => trim($excel_entry['agreement_number']),
                    'name' => trim($excel_entry['name']),
                    'merchant_name' => trim($excel_entry['merchant_name']),
                    'agency_id' => trim($excel_entry['agency_id']),
                    'feedback' => trim($excel_entry['feedback']),
                    'amount' => trim($excel_entry['paid_amount']),
                    'created_at' => Carbon::now()->toDateTimeString()
                ];
                $existing = [];
                foreach($old_data as $v){
                    if(!in_array($v->application_id, $existing) && $v->application_id == $excel_entry['application_id'] && $v->agency_id != $excel_entry['agency_id'] && $v->deleted_at == null){
                        $sms_id_arr[] = $v->application_id;
                        $existing[] = $v->application_id;
                    }
                }
                if(!empty($old_id_arr)){
                    if(!in_array($excel_entry['application_id'], $old_id_arr)){
                        $sms_id_arr[] = $excel_entry['application_id'];
                    }
                }
                if(empty($old_id_arr)){
                    $sms_id_arr[] = $excel_entry['application_id'];
                }

            }
            //echo "<pre>";print_r($agencyApplication);die;
            AgencyApplication::whereNotNull('id')->delete();
            if (isset($agencyApplications) && $agencyApplications) {
                //$aapDetails = new AgencyApplication;
                //$aapDetails->fill($agencyApplication);
                //$aapDetails->save();
                foreach(array_chunk($agencyApplications,2000) as $agencyApplication){
                    AgencyApplication::insert($agencyApplication);
                }
            }

            $sms_id_arr = array_unique($sms_id_arr);
            //print_r($sms_id_arr);die;
            // if(Session::has('Agency_Allotment_View|4-13-0')){
            $user = User::where('id',$fileUploaderId)->first(['name','email']);
            if($mailtocf){
                (new Slack(new Request(['title'=>'Agency Uploaded Excel File','fields'=> ['Message' => 'Dear Collection team, New excel file is uploaded by agency '.$user->name.'. You can find uploaded excel file in respective mails'],'group' => 'payment_collection'])))->send();

                $emails = _env('APP_CONNECTION') ? ['imran@creditfair', 'amol@creditfair.in', 'ketan@creditfair.in'] : [$user->email];
                Mail::send('emails.reminders.basic_reminder', [
                    'body' => 'Please check the attached excel that is uploaded by '.$user->name.'.'], function ($message) use ($localFileName,$emails) {
                    $message->to($emails)->cc(['sarah@creditfair.in'])->subject('Excel File From Agency');
                    // $message->attach($Excelfile->getRealPath(), array(
                    //     'as' => 'Agency Report_'.Carbon::now()->toDateString(),
                    //     'mime' => $Excelfile->getMimeType())
                    // );
                    $message->attachData(file_get_contents(storage_path() . '/app/' . $localFileName), $localFileName);
                });
            }
            if(!empty($sms_id_arr)){
                event(new EventAgencyCommunication($sms_id_arr));
            }
            // remove the file from local stoarge
            Storage::disk('local')->delete($localFileName);

            $data['status'] = 'SUCCESS';
            $data['message'] = 'Excel Data Imported Successfully';
            return $data;
        }
        Storage::disk('local')->delete($localFileName);
        $data['status'] = 'FAIL';
        $data['message'] = 'Something went wrong while uploading file';
        // return $data;
        throw new \Exception($data['message']);
    }

    public function sendCommToCustomerOnAgencyChange($ids = []){
        if(!empty($ids)){
            $data = ConsumerApplication::with(['agency'=>function($query){ $query->with('agency_name');},'proFormaInvoice'=>function($query){ $query->select('application_id','loan_application_no');}])->whereIn('id', $ids)->get(['id','name','email','mobile_number','current_address_line_1','current_address_state','current_address_city','current_address_pincode']);
            $entity = ['templateid' => '1307166730667574368', 'entityid' => Templates::$entityid];
            //echo "<pre>";print_r($data);die;
            foreach($data as $key => $value){
            try{
                $msg_email = 'To, <br /> Application ID:- '.$value->id.'<br /> Loan ID:- '.$value->proFormaInvoice->loan_application_no.'<br /> Customer Name :- '.$value->name.' <br /> Address :- '.$value->current_address_line_1.' '.$value->current_address_city.' '.$value->current_address_state.' - '.$value->current_address_pincode.' <br /> <br /> Subject - Enrolment of collection Agency. <br /> <br />Dear '.$value->name. ', <br /> This is to informed you that we have authorised '.$value->agency->agency_name->name.' as our Collection Partner to collect the dues on behalf of Credit Fair.';
                //$msg = 'Dear '.$value->name. ',This is to informed you that we have authorised '.$value->agency->agency_name->name.' as our Collection Partner to collect the dues on behalf of Credit Fair.';
                $msg = 'Dear '.$value->name.', This is to informed you that we have authorised '.$value->agency->agency_name->name.' as our Collection Partner to collect the dues on behalf of Credit Fair. Regards, Team Credit Fair.';

                if(isset($value->email)){
                    $email = $value->email;
                    Mail::send('emails.reminders.agency_communication', [
                        'body' => $msg_email], function ($message) use ($email) {
                        $message->to($email)->subject('Enrolment of Collection Agency');
                    });
                }else{
                    $aId = array();
                    array_push($aId,$value->id);
                }
                if(isset($value->mobile_number)){
                    $mobile = '91' .$value->mobile_number;
                    send_sms($mobile, ['message' => $msg, 'id' => $value->id, 'id_type' => 'application_id', 'message_type'=>"payment", 'templateDetails' => $entity]);
                }else{
                    $aId = array();
                    array_push($aId,$value->id);
                }
            }catch(\Exception $e){
                $aId = array();
                array_push($aId,$value->id);
            }
            }
            if(isset($aId[0])){
                $aId = array_unique($aId);
                (new Slack(new Request(['title'=>'SMS/Email Send Failed/Error for Agency Applications','fields'=>['application_ids'=>json_encode($aId)]])))->send();
            }
        }
    }

    public function getCancellationCalculatorIndex(){
        return view('admin.collection.cancellation_calculator');
    }

    public function getCancellationCalculator($id){


        if($id){

            $queryData = DB::select("select ca.id, ca.approved_amount, m.is_collected, mo.processing_fee_first_emi, pfi.processing_fee_by_merchant, ec.processing_fee, cae.emi_paid, cae.principal_due, cae.total_amount_due, (select DATE_FORMAT(status_logs.created_at, '%Y-%m-%d') from status_logs where status_logs.application_id = ca.id and status_logs.status = 'disbursed' order by id desc limit 1) as disbursed_date  from consumer_application as ca
left join emi_calculation as ec on ec.application_id = ca.id
left join pro_forma_invoice as pfi on pfi.application_id = ca.id
left join merchant as m on m.id = ca.merchant_id
left join merchant_offers as mo on mo.id = ca.offer_id
left join consumer_application_element as cae on cae.application_id = ca.id
where ca.id=".$id);

            foreach ($queryData as $query) {
                if (isset($query->id)) {

                    $diffInDays = Carbon::parse($query->disbursed_date)->diffInDays(Carbon::now());

                    //$diffInDays = $date1->diffInDays(Carbon::now());

                    $loan_disbursed_amount = (new ConsumerApplicationController())->getDisbursementAmount($id);

                    $merchant_processing_collected = $query->is_collected == 1 ? $query->is_collected : ($query->processing_fee_by_merchant == 1 ? $query->processing_fee_by_merchant : 0);


                    $total_paid_emi = PaymentTransaction::where('application_id', $id)->where('payment_for', 'EMI')->whereNull('deleted_at')->whereNull('is_deleted_at')->sum('amount');

                    /*foreach ($data['paymentsData'] as $payment){
                        if($payment->payment_status == 'success') {
                            $total_paid_emi += $payment->emi_amount;
                        }else if ($payment->payment_status == 'partial'){
                            $total_paid_emi += $total_paid_emi + ($payment->total_payable - $payment->amount_due);
                        }
                    }*/

                    $processing_fee = $merchant_processing_collected ? $query->processing_fee : 0;

                    if(!$processing_fee && $query->processing_fee_first_emi){
                        $isProcessingFeePaid = PaymentTransaction::where('application_id', $id)->where('payment_for', 'processing_fee')->whereNull('deleted_at')->whereNull('is_deleted_at')->first(['id']);
                        if (!isset($isProcessingFeePaid->id)) {
                            $processing_fee = $query->processing_fee;
                        }
                    }

                    $principal_outstanding = $query->approved_amount;//$query->approved_amount - $total_paid_emi;
                    $cancellation_fee = ($principal_outstanding * 1.4 * ceil($diffInDays/30)) / 100;
                    $total_payable = ($loan_disbursed_amount + $cancellation_fee + $processing_fee);

                    $data = [
                        'disbursed_date' => $query->disbursed_date,
                        'total_days' => $diffInDays,
                        'loan_disbursed_amount' => $loan_disbursed_amount,
                        'loan_amount' => $query->approved_amount,
                        'total_paid_emi' => $total_paid_emi,
                        'principal_outstanding' => $principal_outstanding,//$query->principal_due,
                        'processing_fee' => $processing_fee,
                        'total_payable' => round($total_payable),
                        'cancellation_fee' => round($cancellation_fee),
                        'final_payable' => round($total_payable)
                    ];

                    return response()->json(['status' => 'OK', 'message' => 'getCancellationCalculator', 'data' => $data]);
                }
            }
        }

        return response()->json(['status' => 'FAIL', 'message' => 'getCancellationCalculator']);
    }

    public function getAccountAggregatorReport($id){

        $data = [];
        $accountAggregatorMonitoring = AccountAggregatorMonitoring::where('status', 1)->whereNull('is_subsidy_received')->orWhere('is_subsidy_received', 2)->get(['id', 'account_aggregator_id']);
        foreach($accountAggregatorMonitoring as $accountAggregatorMonitoringItem) {
            $accountAggregator = AccountAggregatorModel::where('id', $accountAggregatorMonitoringItem->account_aggregator_id)->first(['id', 'application_id', 'created_at', 'updated_at', 'consent_status']);
            $application = ConsumerApplication::where('id', $accountAggregator->application_id)->first(['id', 'name']);

            $job = JobProvider::where('application_id', $accountAggregator->id)->where('from', 'create_monitoring_request')->first(['id', 'available_at', 'is_available', 'updated_at', 'created_at']);

            if (isset($accountAggregator->consent_status) && $accountAggregator->consent_status == 1) {

                if($job->is_available){
                    if ($job->available_at < date('Y-m-d')){
                        $available_at_new = now()->addDays((new AccountAggregator($this->request))->getMonitoringFrequency())->toDateTimeString();
                        JobProvider::where('id',$job->id)->update(['is_available' => 0, 'available_at' => $available_at_new]);
                    }
                }

                $data[] = [
                    'id' => $application->id,
                    'account_aggregator_id' => $accountAggregatorMonitoringItem->account_aggregator_id,
                    'account_aggregator_monitoring_id' => $accountAggregatorMonitoringItem->id,
                    'name' => $application->name,
                    'fetched_at' => $job->updated_at != '' && $job->updated_at != null && $job->updated_at != '1970-01-01'  ? date('Y-m-d', strtotime($job->updated_at)) :  date('Y-m-d', strtotime($job->created_at)),
                    'status' => 'Success',
                    'next_fetch_date' => isset($job->available_at) ? date('Y-m-d', strtotime($job->available_at)) : '',
                    'reports' => $this->getAAFetchedData($application->id, $accountAggregatorMonitoringItem->account_aggregator_id)
                ];
            }
        }

        $default_frequency  = (new AccountAggregator(new Request()))->getMonitoringFrequency();

        return view('admin.collection.account_aggregator_report', ['data' => $data, 'default_frequency' => $default_frequency]);
    }

    private function getAAFetchedData($id, $account_aggregator_id){
        $s3 = Storage::disk('s3');
        $dataObjects = [];

        $filePath = $id.'/'.$account_aggregator_id.'_account_aggregator.json';
        if ($s3->exists($filePath)) {
            $data = $s3->get($filePath);
            $accounts = json_decode($data, 1);

            foreach($accounts['account'] as $account){

                $period = $account['data']['Transactions']['startDate'].'-'.$account['data']['Transactions']['endDate'];
                $transactions = [];
                $subsidy_flag = 'No';
                if(isset($account['data']['Transactions']['Transaction']) && $account['data']['Transactions']['Transaction']) {
                    foreach ($account['data']['Transactions']['Transaction'] as $transaction) {
                        if ($transaction['type'] == 'CREDIT') {
                            if ((strpos(strtolower($transaction['narration']), strtolower('subsidy')) !== false || strpos(strtolower($transaction['narration']), strtolower('Credit Through PFMS')) !== false) && ($transaction['amount'] >= 30000 && $transaction['amount'] <= 150000)) {
                                $subsidy_flag = 'Yes';
                            }
                            $transactions[] = [
                                "type" => $transaction['type'],
                                "mode" => $transaction['mode'],
                                "amount" => $transaction['amount'],
                                "transactionTimestamp" => $transaction['transactionTimestamp'],
                                "txnId" => $transaction['txnId'],
                                "narration" => $transaction['narration']
                            ];
                        }
                    }
                }

                $dataObjects[] = [
                    'bank_name' => $account['data']['fipName'] ?? 'No Bank',
                    'account_number' => $account['data']['maskedAccountNumber'] ?? ($account['data']['maskedAccNumber'] ?? '-'),
                    'accountType' => $account['data']['accountType'] ?? '-',
                    'period' => $period,
                    'subsidy_flag' => $subsidy_flag,
                    'transactions' => $transactions
                ];
            }
        }

        return $dataObjects;
    }
}
