<?php

namespace App\Http\Controllers\Admin;

use App\BlackSoil;
use App\Capri;
use App\Console\Commands\AdvanceReminders;
use App\DisbursementLogs;
use App\DisbursementOffers;
use App\EmiPaymentTemp;
use App\Events\V1\EventSendDbBackupEmail;
use App\ABFL\Services\Services;
use App\Amortization;
use App\ApplicationEMICalculation;
use App\Avanse\Services\AvanseServices;
use App\AvanseCreateFinance;
use App\AvanseDisbursement;
use App\BNPL;
use App\BulkPayments;
use App\CampaignsJobProvider;
use App\ChargedInvoices;
use App\Company;
use App\ConsumerApplication;
use App\ConsumerApplicationElement;
use App\ConsumerApplicationRelation;
use App\DpdLogs;
use App\EmiPayment;
use App\Exports\Exporter;
use App\Exports\ExporterMultipleSheet;
use App\ForeclosureBreakup;
use App\Http\Controllers\Admin\ConsumerDocument;
use App\Http\Controllers\Controller;
use App\ParkedTransaction;
use App\Imports\BulkManualPaymentFile;
use App\Imports\BulkPaymentFile;
use App\Imports\LotusPayPaymentFile;
use App\Imports\MandateFile;
use App\Imports\MoratoriumImport;
use App\Imports\PaymentFile;
use App\Invoices;
use App\JobProvider;
use App\Jobs;
use App\Lenders;
use App\LendBox;
use App\LendBoxLSP;
use App\LoanDefault;
use App\LoanManagement;
use App\Logging\CloudWatchLoggerFactory;
use App\Merchant;
use App\MerchantCategory;
use App\MerchantLocation;
use App\MerchantOffers;
use App\Moratorium;
use App\MultiStageDisbursement;
use App\PaymentTransactionTemp;
use App\ProFormaInvoice;
use App\PaymentEmi;
use App\PaymentLogs;
use App\PaymentMakerChecker;
use App\PaymentTransaction;
use App\PaymentTransactionDifferLogs;
use App\PromiseToPay;
use App\ReportCloseLoan;
use App\RPS_Logs;
use App\Singularity\Singularity;
use App\Slack;
use App\StatusLogs;
use App\SecondaryStatusLogs;
use App\Templates;
use App\User;
use App\Vivriti;
use App\WaiveOffLog;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use App\Http\Controllers\TestingController;
use MathPHP\Finance;
use App\AvanseNoc;
use App\Events\V1\EventAvanseNoc;
use App\Avanse\Processes\AvanseProcesses;
use App\ConsumerApplicationFiles;
use App\Http\Controllers\Admin\LenderServices;
use App\KMGP2P;


use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use App\CollectionAction;
use App\Services\Foreclosure\ForeclosureValidationService;

define('FINANCIAL_MAX_ITERATIONS', 128);
define('FINANCIAL_PRECISION', 1.0e-08);
set_time_limit(0);
class AccountingController extends Controller
{

    private $payment_frequency = [];
    public $raw = false;
    private $with_unpaid_charges = false;

    public function __construct(){
        $this->payment_frequency = Config::get('constants.payment_frequency_offer');
    }

    public function getRevenueDetails(Request $request){

        $from_date = Input::has('from_date') ? Input::get('from_date') : '2017-01-01 00:00:00';
        $too_date = Input::has('too_date') ? Input::get('too_date') : date('Y-m-d H:i:s',time());
        $lender_id = Input::has('lender_id') ? Input::get('lender_id') : 1;
        $response_data['lenders'] = Lenders::all();
        $status_array = ['disbursed','nach registered','closed'];
        $response_data['lender_id'] = $lender_id;
        $applications = ConsumerApplication::with('merchant','emi','application_element','emi.offer')->where('lender_id',$lender_id)->whereIn('consumer_application.state',$status_array)->where('id','!=','5580')->whereNull('is_deleted')->get();
        $applications = ConsumerApplication::with('merchant','emi','application_element','emi.offer')->where('lender_id',$lender_id)->whereIn('consumer_application.state',$status_array)->where('id','!=','5580')->whereNull('is_deleted')->get();

        $response = array();

        foreach ($applications as $application) {
            if ($application->emi) {
                $subvention_monthly_value = 0;
                $subvention_paid = 0;
                $principal = 0;
                $interest = 0;
                $rate = 0;
                $upfront_from_customer = isset($application->emi->upfront_from_customer) && $application->emi->upfront_from_customer ? $application->emi->upfront_from_customer : 0;
                $net_disbursement_amount = (isset($application->emi->upfront_from_credit_fair) && $application->emi->upfront_from_credit_fair != 0) ? $application->emi->upfront_from_credit_fair : ((isset($application->approved_amount) && $application->approved_amount != 0) ? $application->approved_amount : $application->loan_amount);
                $loanamount = ((isset($application->approved_amount) && $application->approved_amount != 0) ? $application->approved_amount : $application->loan_amount) - $upfront_from_customer;

                $balance = $loanamount;
                if ($application->emi->subvention > 0) {
                    $subvention_value = ($application->emi->subvention * ((isset($application->approved_amount) && $application->approved_amount != 0) ? $application->approved_amount : $application->loan_amount)) / 100;
                    $subvention_monthly_value = $subvention_value / $application->emi->remaining_emi;
                }
                $current_date = date("Y-m-d 00:00:00", time());
                $paid_term = 0;
                $emi_date = $application->emi->emi_date;
                while ($current_date > $emi_date) {
                    $paid_term++;
                    if ($subvention_monthly_value > 0) {
                        $subvention_paid = $subvention_paid + $subvention_monthly_value;
                    }
                    if ($application->emi->interest_rate == 0.00) {
                        $principal = $principal + $application->emi->emi;
                        $balance = $balance - $application->emi->emi;
                    }
                    $emi_date = date("Y-m-d H:i:s", strtotime("+1 months", strtotime($emi_date)));
                }
                if ($application->emi->interest_rate > 0) {
                    $rate = $application->emi->interest_rate;
                    if ($application->emi->offer && $application->emi->offer->interest_type_id != 2) {
                        if ($application->emi->offer->interest_type_id == 4) {
                            $rate = (12 / $application->emi->remaining_emi) * $rate;
                        }
                        $rate = ($this->monthlyInterestRate($application->emi->remaining_emi, $application->emi->emi, $loanamount) * 100);
                    }
                    $payable_by_customer = (($application->emi->payable_by_customer - $application->emi->processing_fee) - $upfront_from_customer);
                    $data = array(
                        'loan_amount' => $loanamount,
                        'interest' => $rate,
                        'terms' => $application->emi->remaining_emi,
                        'paid_term' => $paid_term,
                        'emi' => $application->emi->emi,
                        'amount_payable' => $payable_by_customer,
                        'amount_paid' => 0,
                    );
                    $amortization = new Amortization($data);
                    $schedule = $amortization->getShedule();
                    foreach ($schedule as $emis) {
                        $principal = $emis['principal'] + $principal;
                        $interest = $emis['interest'] + $interest;
                        $balance = $emis['balance'];
                    }
                }
                $data['id'] = $application->id;
                $data['name'] = $application->name;
                $data['merchant_name'] = isset($application->merchant) && isset($application->merchant->merchant_name) ? $application->merchant->merchant_name : '';
                $data['email'] = $application->email;
                $data['mobile_number'] = $application->mobile_number;
                $data['loan_amount'] = ((isset($application->approved_amount) && $application->approved_amount != 0) ? $application->approved_amount : $application->loan_amount);
                $data['net_disbursement_amount'] = $net_disbursement_amount;
                $data['emi'] = $application->emi->emi;
                $data['subvention'] = $application->emi->subvention;
                $data['quoted_interest'] = $application->emi->interest_rate;
                $data['interest'] = $rate;
                $data['first_emi_date'] = $application->emi->emi_date;
                $data['principle_due'] = round($principal, 0);
                $data['interest_due'] = round(($interest), 0);
                $data['tenure'] = $application->emi->tenure;
                $data['remaining_emi'] = $application->emi->remaining_emi;
                $data['subvention_amount'] = round(($subvention_paid), 0);
                $data['principle_outstanding'] = round($balance, 0);
                $data['processing_fee'] = $application->emi->processing_fee;
                $response[] = $data;
            }
        }

        if($request->has('export')){
            $exporter[] = ['ID','Customer Name','Merchant Name','Loan Amount','Net Disbursement Amount','Emi','Subvention','Quoted rate','Interest','First Emi Date','Principle Due','Interest Due','Subvention Amount','Principle Outstanding','Processing Fee','Tenure','Remaining EMI'];
            foreach ($response as $value){
                $exporter[] = [
                    'id' => $value['id'],
                    'name' => $value['name'],
                    'merchant_name' => $value['merchant_name'],
                    'loan_amount' => $value['loan_amount'],
                    'net_disbursement_amount' => $value['net_disbursement_amount'],
                    'emi' => $value['emi'],
                    'subvention' => $value['subvention'],
                    'quoted_interest' => $value['quoted_interest'],
                    'interest' => $value['interest'],
                    'first_emi_date' => date('Y-m-d',strtotime($value['first_emi_date'])),
                    'principle_due' => $value['principle_due'],
                    'interest_due' => $value['interest_due'],
                    'subvention_amount' => $value['subvention_amount'],
                    'principle_outstanding' => $value['principle_outstanding'],
                    'processing_fee' => $value['processing_fee'],
                    'tenure' => $value['tenure'],
                    'remaining_emi' => $value['remaining_emi'],
                ];
            }

            $request = new Request(['data'=>$exporter,'sheet'=>'Sheet1']);
            return Excel::download((new Exporter($request)), 'Revenue'.$from_date.'.xls');
        }
        $response_data['response'] = $response;
        return view('admin.accounting.show', $response_data);
    }

    public static function annualInterestRate($nper, $pmt, $pv) {
        $Compound_Period = 12;
        $rate = self::monthlyInterestRate($nper, $pmt, $pv);
        return round(((($rate+1)*$Compound_Period)-$Compound_Period)*100, 2);
    }

    public static function monthlyInterestRate($nper, $pmt, $pv) {
        $pmt = -$pmt;
        $Compound_Period = 12;
        $type = 0;
        $fv = 0.0;
        $guess = 0.1;
        //$pv = -$pv;
        $rate = $guess;
        if (abs($rate) < FINANCIAL_PRECISION) {
            $y = $pv * (1 + $nper * $rate) + $pmt * (1 + $rate * $type) * $nper + $fv;
        } else {
            $f = exp($nper * log(1 + $rate));
            $y = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv;
        }
        $y0 = $pv + $pmt * $nper + $fv;
        $y1 = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv;

// find root by secant method
        $i = $x0 = 0.0;
        $x1 = $rate;
        while ((abs($y0 - $y1) > FINANCIAL_PRECISION) && ($i < FINANCIAL_MAX_ITERATIONS)) {
            $rate = ($y1 * $x0 - $y0 * $x1) / ($y1 - $y0);
            $x0 = $x1;
            $x1 = $rate;

            if (abs($rate) < FINANCIAL_PRECISION) {
                $y = $pv * (1 + $nper * $rate) + $pmt * (1 + $rate * $type) * $nper + $fv;
            } else {
                $f = exp($nper * log(1 + $rate));
                $y = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv;
            }

            $y0 = $y1;
            $y1 = $y;
            ++$i;
        }
        return $rate;
    }

    public function getIrrRate($id, $emiData){
        $application = ConsumerApplication::where('id', $id)->whereNull('is_deleted')->first();
        //$loanamount = ((isset($application->approved_amount) && $application->approved_amount != 0) ? $application->approved_amount : $application->loan_amount) - $emiData['upfront_from_customer'];
        $loanamount = EMICalculation::getLoanAmountWithInsuranceAmount($id) - $emiData['upfront_from_customer'];

        $subvention_amount = (isset($emiData['subvention']) && $emiData['subvention'] > 0) ? ((((isset($application->approved_amount) && $application->approved_amount != 0) ? $application->approved_amount : $application->loan_amount)* ($emiData['subvention']))/100) : 0;
        $amount_disbursed = $loanamount - $subvention_amount;

        $payment = new PaymentEmi();
        $emi_dues =  $payment->generateDues($application->id);
        $emis_array =array();
        $emi_irr_array = array();
        array_push($emis_array,-$loanamount);
        array_push($emi_irr_array,-($amount_disbursed));

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

            }
        }
        $response['rate'] = 0;
        $response['irr_rate'] = 0;
        $response['rate'] = (Finance::irr($emis_array))*100;
        $response['annualised_interest'] = 0;
        $response['annualised_irr'] = 0;

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

        $frequecy_multiplier = isset($emiData) ?  $payment_frequency_offer[$emiData['payment_frequency']] : 12;
        if($response['rate'] < 0){
            $response['rate'] = 0;
        }else{
            $response['annualised_interest'] = round((((($response['rate']+1)*$frequecy_multiplier)-$frequecy_multiplier)*100)/100, 2);

        }
        $response['irr_rate'] = (Finance::irr($emi_irr_array))*100;
        if($response['irr_rate'] < 0){
            $response['irr_rate'] = 0;
        }else{
            $response['annualised_irr'] = round((((($response['irr_rate']+1)*12)-12)*100)/100, 2);

        }

        return json_encode($response);
    }

    public function MultiStageIRR($id){

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

        $applications = ConsumerApplication::with('DisbursementOffersData','emi','emi_payment')->where('id', $id)->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]);
                    }
                }
            }catch (\Exception $e){

            }
        }
    }

    public function viewloanschedule($id,$json = 0,$foreclosure = 0,$noforclosure = 0,$revenue = 0)
    {

        $application = ConsumerApplication::with('merchant', 'emi', 'application_element', 'emi.offer','moratoriums')->where('id', $id)->whereNull('is_deleted')->first();
        //$approved_amount = ((isset($application->approved_amount) && $application->approved_amount != 0) ? $application->approved_amount : $application->loan_amount);
        $loanamount = EMICalculation::getLoanAmountWithInsuranceAmount($id) - ($application->emi ? $application->emi->upfront_from_customer : 0);


        $payment_details = array();
        $payment_details_data = EmiPayment::with('transaction')->where('application_id', $id)->get();
        foreach ($payment_details_data as $payments) {
            $payment_details[$payments['emi_date']] = $payments;
        }
        $PaymentEmi = new PaymentEmi();
        $due_amount_details = $PaymentEmi->getEMIdetails($id);

        $approvedAmount = ((isset($application->approved_amount) && $application->approved_amount != 0) ? $application->approved_amount : $application->loan_amount);
        if ($application->merchant && $application->merchant->charge_subvention_remaining_amount){
            $approvedAmount -= ($application->emi ? $application->emi->upfront_from_customer : 0);
        }

        $subvention_amount = (isset($application->emi->subvention) && $application->emi->subvention > 0) ? (($approvedAmount* ($application->emi->subvention))/100) : 0;
        $amount_disbursed = $loanamount - $subvention_amount;
//        if(isset($application->merchant->is_gst) && $application->merchant->is_gst == 0){
//            $loan_amount_subvention = $loanamount - $subvention_amount;
//        }else{
//            if($revenue == 1){
//                $loan_amount_subvention = $loanamount - $subvention_amount;
//            }else {
//                $loan_amount_subvention = $loanamount;
//            }
//        }
        $loan_amount_subvention = $loanamount - $subvention_amount;
        $payment = new PaymentEmi();
        $emi_dues =  $payment->generateDues($application->id,1);
        $payment_frequency_offer = [1 => 12, 2 => 24, 3 => 52, 4 => 365, 5 => 4, 6 => 2, 7 => 1];

        $frequecy_multiplier = isset($application->emi) ?  $payment_frequency_offer[$application->emi->payment_frequency] : 12;
        if(false) {
            $rate = $application->emi->rate;
            $annualised_interest = $application->emi->annualised_interest;
            if($revenue == 1){
                $emi_irr_array = array();
                array_push($emi_irr_array, -($amount_disbursed));
                if (isset($emi_dues['payload'])) {
                    foreach ($emi_dues['payload'] as $emis) {
                        array_push($emi_irr_array, $emis['amount']);

                    }
                }
                $irr_rate = (Finance::irr($emi_irr_array)) * 100;
                if ($irr_rate < 0) {
                    $irr_rate = 0;
                }
                $annualised_irr = round((((($irr_rate+1)*$frequecy_multiplier)-$frequecy_multiplier)*100)/100, 2);

            }else {
                $irr_rate = $application->emi->irr_rate;
                $annualised_irr = $application->emi->annualised_irr;
            }
        }else{
            $emis_array = array();
            $emi_irr_array = array();
            array_push($emis_array, -$loanamount);
            array_push($emi_irr_array, -($amount_disbursed));

            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(is_nan($rate)) {
                // Usage (equivalent to npf.rate(144,2967,-211892,0)*12)
                //$rate = $this->km_rate(count($emis_array) - 1, $emis_array[1], $emis_array[0], 0);
                $rate = Finance::rate(count($emis_array) - 1, $emis_array[1], $emis_array[0], 0) * 100;
//                if ($monthly_rate !== false) {
//                    $rate = ($monthly_rate * 12) * 100;
//                }
            }

            if ($rate < 0) {
                $rate = 0;
            }


//            if(isset($application->lender_id) && $application->lender_id == Services::$lender_id) {
//                $lenderServices = new LenderServices(new Request(['id' => $id]));
//                $rate = $lenderServices->getPayloadValueByID( $id, 'roi') / 100;
//            }

            $irr_rate = (Finance::irr($emi_irr_array)) * 100;

            if(is_nan($irr_rate)) {
                // Usage (equivalent to npf.rate(144,2967,-211892,0)*12)
                //$irr_rate = $this->km_rate(count($emi_irr_array) - 1, $emi_irr_array[1], $emi_irr_array[0], 0);
                $irr_rate = Finance::rate(count($emi_irr_array) - 1, $emi_irr_array[1], $emi_irr_array[0], 0) * 100;
//                if ($monthly_rate !== false) {
//                    $irr_rate = ($monthly_rate * 12) * 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);
            if($revenue == 0 && $rate > 0  && $annualised_interest > 0 && $irr_rate > 0 && $annualised_irr > 0 && isset($application->emi)) {
                ApplicationEMICalculation::where('id', $application->emi->id)
                    ->update(['rate' => $rate, 'annualised_interest' => $annualised_interest, 'irr_rate' => $irr_rate, 'annualised_irr' => $annualised_irr]);
            }

        }
//        if($application->emi->offer->interest_type_id == 2){
//            $rate = $rate / 12;
//        }
//        if ($application->emi->offer->interest_type_id == 4) {
//            $rate = (12 / $application->emi->remaining_emi) * $rate;
//        }

        $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){
                $emi_dues['payload'][$i]['interest'] = $principal_oustanding * ($rate/100);
                $emi_dues['payload'][$i]['principal'] = ($emis['amount']  - $emis['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'];
                $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++;
            }

            $app_id_var = 0;
            foreach ($emi_dues['payload'] as $emis) {
                if ($foreclosure == 0) {

                    $_foreclosure_date = $emis['emi_date'];
                    $future_emi_amt = 0;
                    foreach ($emi_dues['payload'] as $_loan_schedule){
                        if($_loan_schedule['emi_date'] > $_foreclosure_date){
                            $future_emi_amt = $future_emi_amt + $_loan_schedule['principal'];
                        }
                    }

                    //$payment_emi = new PaymentEmi();
                    //$foreclosuredetails = $payment_emi->getForeclosureAmount($id, $emis['emi_date'], $emi_dues['payload']);
                    $emi_dues['payload'][$app_id_var]['fore_closure_amount'] = $future_emi_amt;//isset($foreclosuredetails['future_emi']) ? $foreclosuredetails['future_emi'] : 0;
                } else {
                    $emi_dues['payload'][$app_id_var]['fore_closure_amount'] = 0;
                }
                $app_id_var++;
            }
        }

        $response['summary']['loan_amount'] = ((isset($application->approved_amount) && $application->approved_amount != 0) ? $application->approved_amount : $application->loan_amount);
        $response['summary']['loan_outstanding'] = $loanamount;
        $response['summary']['tenure'] = isset($application->emi) && isset($application->emi->tenure) ? $application->emi->tenure : '';
        $response['summary']['remaining_emi'] = isset($application->emi) && isset($application->emi->remaining_emi) ? $application->emi->remaining_emi : '';
        $response['summary']['moratoriums'] = $application->moratoriums;
        $response['summary']['quoted_interest'] = isset($application->emi) && isset($application->emi->interest_rate) ? $application->emi->interest_rate : '';
        $response['summary']['interest'] = $rate;
        $response['summary']['annualised_interest'] = $annualised_interest;
        $response['summary']['irr'] = $irr_rate;
        $response['summary']['annualised_irr'] = $annualised_irr;
        $response['summary']['subvention'] = isset($application->emi) && isset($application->emi->subvention) ? $application->emi->subvention : '';
        $response['summary']['processing_fee'] = isset($application->emi) && isset($application->emi->processing_fee) ? $application->emi->processing_fee : '';
        $response['summary']['emi'] = isset($application->emi) && isset($application->emi->emi) ? $application->emi->emi : '';
        $response['summary']['advance_due'] = isset($application->emi) && isset($application->emi->upfront_from_customer) ? $application->emi->upfront_from_customer : '';
        $response['customer_name'] = $application->name;
        $response['id'] = $application->id;
        $response['summary']['merchant_name'] = isset($application->merchant) && isset($application->merchant->merchant_name) ? $application->merchant->merchant_name : '';
        $response['summary']['net_disbursement_amount'] = (isset($application->emi->upfront_from_credit_fair) && $application->emi->upfront_from_credit_fair != 0) ? $application->emi->upfront_from_credit_fair : ((isset($application->approved_amount) && $application->approved_amount != 0) ? $application->approved_amount : $application->loan_amount);
        $response['schedule'] = $emi_dues['payload'];
        $i = 0;
        foreach ($response['schedule'] as $schedule) {
            //$response['schedule'][$i]['emi_date'] = Carbon::createFromFormat('Y-m-d', (date('Y-m-d', strtotime($application->emi->emi_date))))->addMonths($i)->toDateString();
            $response['schedule'][$i]['emi_date'] = isset($schedule['emi_date']) ? $schedule['emi_date'] : "";

            if (isset($payment_details[$response['schedule'][$i]['emi_date']])) {
                $response['schedule'][$i]['payment_status'] = $payment_details[$response['schedule'][$i]['emi_date']]['payment_status'];
                $response['schedule'][$i]['bounce_charges'] = isset($payment_details[$response['schedule'][$i]['emi_date']]['bounce_charges']) ? $payment_details[$response['schedule'][$i]['emi_date']]['bounce_charges'] : 0;
                $response['schedule'][$i]['delay_penalty'] = isset($payment_details[$response['schedule'][$i]['emi_date']]['delay_penalty']) ? $payment_details[$response['schedule'][$i]['emi_date']]['delay_penalty'] : 0;
                $response['schedule'][$i]['charges_waived'] = isset($payment_details[$response['schedule'][$i]['emi_date']]['charges_waived']) ? $payment_details[$response['schedule'][$i]['emi_date']]['charges_waived'] : 0;
                $response['schedule'][$i]['transaction'] = $payment_details[$response['schedule'][$i]['emi_date']]['transaction'];
            } else {
                $response['schedule'][$i]['payment_status'] = "pending";
                $response['schedule'][$i]['bounce_charges'] = 0;
                $response['schedule'][$i]['delay_penalty'] = 0;
                $response['schedule'][$i]['charges_waived'] = 0;
            }
            if (isset($due_amount_details[$id][$response['schedule'][$i]['emi_date']])) {
                $response['schedule'][$i]['bounce_charges'] = isset($due_amount_details[$id][$response['schedule'][$i]['emi_date']]['bounce_charges']) ? $due_amount_details[$id][$response['schedule'][$i]['emi_date']]['bounce_charges'] : 0;
                $response['schedule'][$i]['delay_penalty'] = isset($due_amount_details[$id][$response['schedule'][$i]['emi_date']]['delay_penalty']) ? $due_amount_details[$id][$response['schedule'][$i]['emi_date']]['delay_penalty'] : 0;
            }
            $i++;
        }

        if($json == 0) {
            return view('admin.accounting.loanschedule', $response);
        }else{
            return $response;
        }
    }

//    public function getPayments($id = 0, Request $request){
////        $from_date = ($request->has('from_date') && !empty($request->get('from_date'))) ? Carbon::createFromFormat('Y-m-d',$request->get('from_date'))->startOfDay()->toDateTimeString() : Carbon::now()->startOfDay()->toDateTimeString();
////        $to_date = ($request->has('to_date') && !empty($request->get('to_date'))) ? Carbon::createFromFormat('Y-m-d',$request->get('to_date'))->endOfDay()->toDateTimeString() : Carbon::now()->endOfDay()->toDateTimeString();
////        $data['from_date'] = date('Y-m-d',strtotime($from_date));
////        $data['to_date'] = date('Y-m-d',strtotime($to_date));
//        $EMIPayment = new PaymentEmi();
//        if ($request->has('isPagination')) {
//            $EMIPayment->isPagination = 10;
//            $EMIPayment->isPaginationSkip = 10 * ($request->has('page') && $request->get('page') > 1  ? $request->get('page') : 0);
//        }
//        $EMIPayment->status = (new ConsumerApplicationController())->statusreversearray['approved'];
//        $EMIPaymentData = $EMIPayment->getPaymentDueHistory($id);
//        /*$EMIPayment = EmiPayment::with('application:id,name','transaction')->where('emi_date','>=',$from_date)->where('emi_date','<=',$to_date);
//            if($request->has('application_id') && $request->ge('application_id')){
//                $EMIPayment = $EMIPayment->where('application_id',$request->get('application_id'));
//            }
//        $EMIPayment = $EMIPayment->get();*/
//        $isDue = $request->has('due') ? true : false;
//        $data['payments'] = $EMIPaymentData;
//        $response = [];
//        $newPayments = [];
//        $values = [];
//        foreach ($data['payments'] as $application_id => $payment) {
//            if (($isDue && $payment['amount_due'] > 0) || !$isDue) {
//                foreach ($payment['payment'] as $emi_date => $item) {
//                    if (isset($item['payment_history'])) {
//                        $paymentHistory = $item;
//                        if (isset($item['payment_history']['transaction'])) {
//                            $paymentHistory['transaction'] = $item['payment_history']['transaction'];
//                        }
////                    $paymentHistory = $item['payment_history'];
////                    $paymentHistory['amount_received'] = $item['amount_received'];
////                    $paymentHistory['pending_amount'] = $item['pending_amount'];
//                    } else {
//                        $paymentHistory = $item;
//                    }
//                    $response[$application_id][$emi_date] = $paymentHistory;
//
//                    $newPayments[$application_id] = ['name' => $payment['applicant_name'], 'amount_due' => $payment['amount_due'], 'max_payable' => $payment['max_payable'], 'over_payment' => $payment['over_payment'], 'adhoc_transaction' => $payment['adhoc_transaction'], 'waived_off_data' => isset($payment['waived_off_data']) ? $payment['waived_off_data'] : [],'amount_paid' =>  $payment['amount_paid'],'emi_due' =>  $payment['emi_due'],'emi_paid' =>  $payment['emi_paid'],'amount_pending' =>  $payment['amount_pending']];
//                }
//            }
//        }
//
//        foreach ($response as $id_index=>$item){
//            $values[] = [
//                'id' => $id_index,
//                'name' => $newPayments[$id_index]['name'],
//                'amount_due' => $newPayments[$id_index]['amount_due'],
//                'max_payable' => $newPayments[$id_index]['max_payable'],
//                'over_payment' => $newPayments[$id_index]['over_payment'],
//                'adhoc_transaction' => $newPayments[$id_index]['adhoc_transaction'],
//                'payment' => $item,
//                'waived_off_data' => $newPayments[$id_index]['waived_off_data'],
//                'amount_paid' => $newPayments[$id_index]['amount_paid'],
//                'emi_due' => $newPayments[$id_index]['emi_due'],
//                'emi_paid' => $newPayments[$id_index]['emi_paid'],
//                'amount_pending' => $newPayments[$id_index]['amount_pending']
//            ];
//        }
//
//        $data['payments'] = $values;
//        $data['paginationTotal'] = $EMIPayment->isPaginationTotal;
//        $data['paginationLastPage'] = $EMIPayment->isPaginationLastPage;
//        $data['application_id'] = $id;
//
//        if($request->has('raw')){
//            return $data;
//        }
//
//        return view('admin.accounting.payment', $data);
//    }

    public function getSubventionInterest($event, $export = false){

        if($export) {
            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($event['year'].'-'.$event['month'].'-01')->startOfMonth()->toDateTimeString();
            $to_date = Carbon::parse($event['year'].'-'.$event['month'].'-01')->endOfMonth()->toDateTimeString();
            /*$emisPayemetnsData = EmiPayment::where('emi_date', '>=', $from_date)->where('emi_date', '<=', $to_date)->get(['application_id']);
            foreach($emisPayemetnsData as $emisPayemetnsDatum){
                $idsData[] = $emisPayemetnsDatum->application_id;
            }*/
        }

        if($event['user_email']){
            $user_mail = [$event['user_email']];
        }

        if (isset($event['emi_date'])) {
            $emi_date = $event['emi_date'];
        }

        $excludeMerchant = _env('APP_CONNECTION') ? [6478, 7516] : [7875];
        $_date = $from_date ?? $emi_date ?? Carbon::now()->toDateString() ;

        $status = ['disbursed', 'cancelled', 'cancellation in-process'];
        $consumerApplications1 = ConsumerApplicationRelation::with( 'emi', 'emi_payment', 'application_element', 'merchant', 'offer')
            ->wherein('state', $status)
            ->whereNotNull('merchant_id')->whereNotIn('merchant_id', $excludeMerchant)
            ->whereNull('is_deleted')
            ->whereHas('application_element', function($query) use ($_date){
                $query->whereNull('foreclosure_date')
                    ->orWhere('foreclosure_date', '>=', $_date);
            });

        if (isset($event['lender_id'])){
            $consumerApplications1 = $consumerApplications1->where('lender_id', $event['lender_id']);
        }else{
            $consumerApplications1 = $consumerApplications1->whereIn('lender_id', [1, 2]);
        }

        if (isset($from_date) && $from_date && isset($to_date) && $to_date){
            $consumerApplications1 = $consumerApplications1->whereHas('emi_payment',function($query) use($from_date, $to_date){
                return $query->where('emi_date', '>=', $from_date)->where('emi_date', '<=', $to_date)->select(['application_id']);
            });
        }

        if (isset($emi_date)) {
            $consumerApplications1 = $consumerApplications1->whereHas('emi_payment',function($query) use($emi_date){
                return $query->where('emi_date', $emi_date)->select(['application_id']);
            });
        }

        $consumerApplications1 = $consumerApplications1->get();

        $status = ['nach registered', 'closed'];

        $consumerApplications = ConsumerApplicationRelation::with( 'emi', 'emi_payment', 'application_element', 'merchant', 'offer')
            ->wherein('state', $status)
            ->whereNotNull('merchant_id')->whereNotIn('merchant_id', $excludeMerchant)
            ->whereNull('is_deleted')
            ->whereHas('application_element', function($query) use ($_date){
                $query->whereNull('foreclosure_date')
                    ->orWhere('foreclosure_date', '>=', $_date);
            });

        if (isset($from_date) && $from_date && isset($to_date) && $to_date){
            $consumerApplications = $consumerApplications->whereHas('emi_payment',function($query) use($from_date, $to_date){
                return $query->where('emi_date', '>=', $from_date)->where('emi_date', '<=', $to_date)->select(['application_id']);
            });
        }

        if (isset($emi_date)) {
            $consumerApplications = $consumerApplications->whereHas('emi_payment',function($query) use($emi_date){
                return $query->where('emi_date', $emi_date)->select(['application_id']);
            });
        }

        /*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 = [];
        if($export){
            $dataItems[] = ['ID', 'Interest', 'Subvention', 'EMI Date', 'Penal', 'Bounce'];
        }
        $dataItems1 = [];
        $dataItems2 = [];
        $response = [];

        $applicationDuplicates = [];
        $_date = $from_date ?? $emi_date ?? Carbon::now()->toDateString() ;
        foreach($consumerApplications as $application) {
//            if($first_condition || $second_condition){
                if (!in_array($application->id, $applicationDuplicates)) {
                    if (isset($to_date)) {
                        if (in_array($application->state, ['cancelled', 'cancellation in-process'])){
                            $statusLogs = StatusLogs::whereIn('status', ['cancelled', 'cancellation in-process'])
                                /*->where('created_at', '>=', $from_date)*/->where('created_at', '<=', $to_date)
                                ->where('application_id', $application->id)->first(['id']);
                            if (isset($statusLogs->id)){
                                continue;
                            }
                        }
                    }

                    if (isset($emi_date)) {
                        if (in_array($application->state, ['cancelled', 'cancellation in-process'])){
                            $statusLogs = StatusLogs::whereIn('status', ['cancelled', 'cancellation in-process'])
                                /*->where('created_at', '>=', $from_date)*/->where('created_at', '<=', Carbon::parse($emi_date)->endOfMonth()->toDateTimeString())
                                ->where('application_id', $application->id)->first(['id']);
                            if (isset($statusLogs->id)){
                                continue;
                            }
                        }
                    }

                    $applicationDuplicates[] = $application->id;

                    $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 = 0;
                    if(isset($application->emi->subvention) && $application->emi->subvention > 0){
                        $_amount = $application->loan_amount;
                        if(isset($application->approved_amount) && $application->approved_amount != 0){
                            $_amount = $application->approved_amount;
                        }
                        if($application->merchant && $application->merchant->charge_subvention_remaining_amount){
                            $_amount -= $application->emi->upfront_from_customer;
                        }

                        $subvention_amount = ($_amount * $application->emi->subvention) / 100;
                    }
//                    $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;
//                    $subvention = (new ConsumerApplicationController())->getSubventionDetails($application, true, true);
//                    $subvention_amount = $subvention['Net'];

                    $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 (isset($from_date) && isset($to_date)) {
                                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];
                                    $dataItems1[$application->id] = $emi_dues['payload'][$i]['subvention'];
                                    $dataItems2[$application->id] = $emi_dues['payload'][$i]['interest'];
                                }
                            }
                            if (isset($emi_date)) {
                                if (strtotime($payloadItem['emi_date']) == strtotime(date('Y-m-d', strtotime($emi_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];
                                    $dataItems1[$application->id] = $emi_dues['payload'][$i]['subvention'];
                                    $dataItems2[$application->id] = $emi_dues['payload'][$i]['interest'];
                                }
                            }
                        }
                    }
                    //$applicationData[$application->id] = $emi_dues;
                }
//            }
        }

        if($export) {
            try{
                if(isset($event['month']) && isset($event['year'])) {
                    $report_date = $event['month'] . '_' . $event['year'];
                }else{
                    $report_date = $event['emi_date'];
                }
                $path1 = storage_path().'/app/Subvention_Interest_Data.csv';
                $file = fopen($path1,"w");

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

                $to_mail = ['surbhi@creditfair.in','ravi.mehta@creditfair.in'];
                if(isset($user_mail)){
                    $to_mail = array_merge($user_mail, $to_mail);
                }
                Mail::send('emails.reminders.basic_reminder',
                    ['body' => 'Please find attached the Subvention interest report.']
                    , function ($message) use ($path1, $report_date,$to_mail) {
                        $message->to($to_mail)->cc(['sarah@creditfair.in'])->subject('Subvention Interest Report');
                        $message->attach($path1, ['as' => 'Subvention_Interest_'.$report_date]);
                    });

                unlink($path1);
            }catch (\Exception $e){
                (new \App\Slack(new Request(['title' => 'Error while sending SubInv Report', 'fields' => ['error' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()]])))->send();
            }
        }

        return $dataItems ?? [];
    }

    function km_rate($nper, $pmt, $pv, $fv = 0, $type = 0, $guess = 0.1, $tol = 1e-6, $max_iter = 1000) {
        $rate = $guess;
        for ($i = 0; $i < $max_iter; $i++) {
            $f = $pv * pow(1 + $rate, $nper) + $pmt * (1 + $rate * $type) * ( (pow(1 + $rate, $nper) - 1) / $rate ) + $fv;
            $df = $pv * $nper * pow(1 + $rate, $nper - 1)
                + $pmt * (1 + $rate * $type) * ( ( $nper * pow(1 + $rate, $nper - 1) * $rate - (pow(1 + $rate, $nper) - 1) ) / ($rate * $rate) );
            $rate_new = $rate - $f / $df;
            if (abs($rate_new - $rate) < $tol) {
                return $rate_new;
            }
            $rate = $rate_new;
        }
        // If no convergence, return false or throw an error
        return false;
    }

    public function getBouncePenalCharges($event){

//        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($event['year'].'-'.$event['month'].'-01')->startOfMonth()->toDateTimeString();
            $to_date = Carbon::parse($event['year'].'-'.$event['month'].'-01')->endOfMonth()->toDateTimeString();
            $bouncPenalData = ChargedInvoices::where('invoice_date', '>=', $from_date)->where('invoice_date', '<=', $to_date)->get(['application_id']);

            foreach($bouncPenalData as $val){
                if(!in_array($val->application_id, $idsData) /*&& !in_array($val->application_id, [43502,46049,48957,61576,84108,86974,88899,89640,95330,96426,97234,98668,100264])*/){
                    $idsData[] = $val->application_id;
                }
            }
        }


        $status = ['disbursed','nach registered', 'closed'];

        $consumerApplications = ConsumerApplicationRelation::with( 'emi', 'emi_payment', 'charged_invoices')
            ->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();

        $dataItems = [];
        $key = 0;
        foreach($consumerApplications as $application) {
            $emi_dues = [];
            $payload = [];
            $response = [];

            if(count($application->charged_invoices) > 0) {
                foreach ($application->charged_invoices as $charged_invoice) {
                    if(strtotime($charged_invoice->invoice_date) >= strtotime(date('Y-m-d', strtotime($from_date))) && strtotime($charged_invoice->invoice_date) <= strtotime(date('Y-m-d', strtotime($to_date)))){
                        if ($charged_invoice->type == 'bounce'){
                            $bounce_charge = $charged_invoice->amount/* - ($charged_invoice->igst + $charged_invoice->cgst + $charged_invoice->sgst)*/;
                            if($bounce_charge > 0){
                                $response[$charged_invoice->id][$charged_invoice->invoice_date]['bounce_charges'] = round($bounce_charge, 2);
                            }
                        }
                        if ($charged_invoice->type == 'penal'){
                            $penal_interest = $charged_invoice->amount/* - ($charged_invoice->igst + $charged_invoice->cgst + $charged_invoice->sgst)*/;
                            if($penal_interest > 0){
                                $response[$charged_invoice->id][$charged_invoice->invoice_date]['penal_interest'] = round($penal_interest, 2);
                            }
                        }
                    }
                    $payload[] = ['invoice_date' => $charged_invoice->invoice_date, 'bounce_charges' => $response[$charged_invoice->id][$charged_invoice->invoice_date]['bounce_charges'] ?? 0, 'penal_interest' => $response[$charged_invoice->id][$charged_invoice->invoice_date]['penal_interest'] ?? 0];
                }
            }

            foreach($payload as $k => $item){
                $emi_dues['payload'][$k]['invoice_date'] = $item['invoice_date'];
                $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 $i => $payloadItem) {
                    if (strtotime($payloadItem['invoice_date']) >= strtotime(date('Y-m-d', strtotime($from_date))) && strtotime($payloadItem['invoice_date']) <= strtotime(date('Y-m-d', strtotime($to_date)))) {
//                        $dataItems[$i] = ['id' => $application->id, 'invoice_date' => date('Y-m-d', strtotime($payloadItem['invoice_date'])) ?? 0, 'Penal Interest' => $payloadItem['penal_interest'] ?? 0, 'Bounce Charges' => $payloadItem['bounce_charges'] ?? 0];
                        $key += 1;
                        $dataItems[$key] = ['id' => $application->id, 'invoice_date' => date('Y-m-d', strtotime($payloadItem['invoice_date'])) ?? 0, 'Penal Interest' => $payloadItem['penal_interest'] ?? 0, 'Bounce Charges' => $payloadItem['bounce_charges'] ?? 0];

                    }
                }
            }

        }

//        $path1 = storage_path().'/app/Subvention_Interest_Data.csv';
//        $file = fopen($path1,"w");
//
//        foreach ($dataItems as $line) {
//            fputcsv($file, $line);
//        }
//        fclose($file);

//        unlink($path1);

        return $dataItems ?? [];
    }

    public function paymentCalculateWithoutBounceAndCharges(){
        $loan_management = new LoanManagement();
        $loan_management->paymentCalculateWithoutCharges(0,'','all');
    }

    public function getLoanScheduleDataV2($id){

        $application = ConsumerApplication::with(['merchant' => function($query){
            return $query->select(['id','merchant_name']);
        }])->with(['emi' => function($query){
            return $query->select(['application_id','tenure', 'remaining_emi', 'subvention', 'processing_fee', 'upfront_from_customer', 'emi', 'annualised_interest']);
        }])->with('application_element', 'foreclosed_transaction')->where('id', $id)->first(['id', 'merchant_id', 'name', 'approved_amount']);

        // Foreclosure context so the schedule blade can stop at the foreclosure date and show the
        // foreclosure payment as the final entry.
        $foreclosureData = [
            'isForeclosed' => (bool)($application->foreclosure_event->id ?? false),
            'foreclosureDate' => $application->application_element->foreclosure_date ?? null,
            'foreclosedAmount' => $application->foreclosure_event->amount ?? null,
            'foreclosedMode' => $application->foreclosure_event->mode ?? null,
        ];

        $approved_amount = EMICalculation::getLoanAmountWithInsuranceAmount($id);

        if(_env('LOAN_SCHEDULE_PYTHON') && $response = $this->getLoanScheduleUsingPythonService($id)){
            if(isset($response['status']) && $response['status'] != 'FAILED' || !isset($response['status'])){
                return view('admin.accounting.loanschedule_v2', array_merge(['schedule_summary' => $response, 'summary' => $application, 'approved_amount' => ($approved_amount - ($application->emi ? $application->emi->upfront_from_customer : 0))], $foreclosureData));
            }
        }


        $rps = RPS_Logs::where('application_id', $id)->orderBy('installment_number', 'asc')->get();

        if (!isset($rps[0]->id)){
            return $this->getLoanScheduleDataV1($id);
        }

        return view('admin.accounting.loanschedule_v2', array_merge(['schedule' => $rps, 'summary' => $application, 'approved_amount' => $approved_amount], $foreclosureData));
    }

    private function sendDPDReport($payload){


        try {
            $cwFactory = new CloudWatchLoggerFactory();
            $_data = array(
                'api_name' => 'sendingDPDReport api',
                'fields' => $payload,
                'url' => _env('PY_SCRIPT_SERVER_HOST') . '/dpd-report?' . http_build_query($payload)
            );
            $cwFactory->logger(json_encode($_data));


            $curl = curl_init();

            curl_setopt_array($curl, array(
                CURLOPT_URL => _env('PY_SCRIPT_SERVER_HOST') . '/dpd-report?' . http_build_query($payload),
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'GET',
                CURLOPT_HTTPHEADER => array(
                    "Content-Type: application/json"
                ),
            ));

            $error_msg = '';
            $response = curl_exec($curl);
            if (curl_error($curl)) {
                $error_msg = curl_error($curl);
            }
            curl_close($curl);

            $_data = array(
                'exception' => 'sendDPDReport api',
                'error' => $error_msg,
                'fields' => $payload,
                'url' => _env('PY_SCRIPT_SERVER_HOST') . '/dpd-report?' . http_build_query($payload),
                'response' => $response
            );
            $cwFactory->logger(json_encode($_data));

            return $error_msg ? false : json_decode($response, 1);
        }catch (\Exception $e){
            $_data = array(
                'exception' => 'sendDPDReport exception',
                'error' => $e->getMessage(),
                'fields' => $payload,
                'url' => _env('PY_SCRIPT_SERVER_HOST') . '/dpd-report?' . http_build_query($payload),
                'response' => $response ?? '',
                'file' => $e->getFile()
            );
            $cwFactory->logger(json_encode($_data));
        }
    }

    public function getLoanScheduleUsingPythonService($id){

        $payload = ["application_id" => (int)trim($id)];

        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => _env('PY_SCRIPT_SERVER_HOST').'/api/foreclosure_breakup',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => json_encode($payload),
            CURLOPT_HTTPHEADER => array(
                "Content-Type: application/json"
            ),
        ));

        $error_msg = '';
        $response = curl_exec($curl);
        if (curl_error($curl)) {
            $error_msg = curl_error($curl);
        }
        curl_close($curl);


        $cwFactory = new CloudWatchLoggerFactory();
        $_data = array(
            'exception' => 'foreclosure_breakup api',
            'error' => $error_msg,
            'fields' => $payload,
            'response' => $response
        );
        $cwFactory->logger(json_encode($_data));

        return $error_msg ? false : json_decode($response, 1);
    }

    public function getLoanScheduleDataV1($id){

        $application = ConsumerApplication::on('mysql_readonly')->with('emi','merchant', 'activeOffer')->where('id',$id)->first();
        $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;

        $id = $application->id;
        $isHybrid = $application->activeOffer->subvention_type_id > 1;
        if(RepaymentController::isNEWRPSApplicable($application->id) && $application->lender_id != AvanseServices::$lender_id){
            $is_exist = RPS_Logs::where('application_id', $id)->exists();
            if($is_exist) {
//                $emi_schedules_new = RPS_Logs::where('application_id', $id)->get()->toArray();
//            } else{
                $emi_schedules_new = (new RepaymentController())->getLoanScheduleDetails($id);
            }
        }

        if($application->activeOffer->subvention_type_id == 1 || (isset($emi_schedules_new) && !$emi_schedules_new) || !isset($emi_schedules_new)){
            $payment = new PaymentEmi();
            $emi_dues = $payment->generateDues($id, 1, true);

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

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

                }
            }
            $rate = (Finance::irr($emis_array)) * 100;

            if(is_nan($rate)) {
                $rate = Finance::rate(count($emis_array) - 1, $emis_array[1], $emis_array[0], 0) * 100;
            }

            if ($rate < 0) {
                $rate = 0;
            }

            $irr_rate = (Finance::irr($emi_irr_array)) * 100;

            if(is_nan($irr_rate)) {
                $irr_rate = Finance::rate(count($emi_irr_array) - 1, $emi_irr_array[1], $emi_irr_array[0], 0);
            }

            if ($irr_rate < 0) {
                $irr_rate = 0;
            }

            $loan_amount_subvention = $loanamount - $subvention_amount;

            $i = 0;
            if (isset($emi_dues['payload'])) {
                $principal_oustanding = $loanamount;
                $principal_oustanding_subvention = $loan_amount_subvention;
                $subvention_amount_balance = $subvention_amount;
                //$pre_payment_controller = new PrePaymentController();
                foreach ($emi_dues['payload'] as $emis) {
                    //$principal_oustanding = $pre_payment_controller->getPrincipalOutstanding($id, $emis['emi_date'], $principal_oustanding);
                    $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++;
                }
            }
            $emi_schedules = $emi_dues['payload'];
        }

        $loanamount = ((isset($application->approved_amount) && $application->approved_amount != 0) ? $application->approved_amount : $application->loan_amount) - $application->emi->upfront_from_customer;

        $PaymentEmi = new PaymentEmi();
        $due_amount_details = $PaymentEmi->getEMIdetails($id);

        $payment_details = array();
        $payment_details_data = EmiPayment::with('transaction')->where('application_id', $id)->get();
        foreach ($payment_details_data as $payments) {
            $payment_details[$payments['emi_date']] = $payments;
        }

        $downPayment = 0;
        if($application->merchant && $application->merchant->charge_subvention_remaining_amount){
            $downPayment = $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) - $downPayment) * ($application->emi->subvention)) / 100) : 0;
        $amount_disbursed = $loanamount - $subvention_amount;

        $frequency_multiplier = $this->payment_frequency[$application->emi->payment_frequency];

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

        if (isset($emi_schedules)) {
            foreach ($emi_schedules as $schedule) {
                array_push($emis_array, $schedule['amount']);
                array_push($emi_irr_array, $schedule['amount']);
            }
        }elseif(isset($emi_schedules_new)){
            foreach ($emi_schedules_new as $schedule) {
                array_push($emis_array, $schedule['emi_amount']);
                array_push($emi_irr_array, $schedule['emi_amount']);
            }
        }

        $rate = (Finance::irr($emis_array)) * 100;

        if(is_nan($rate)) {
            $rate = Finance::rate(count($emis_array) - 1, $emis_array[1], $emis_array[0], 0) * 100;
        }

        if ($rate < 0) {
            $rate = 0;
        }

        $irr_rate = (Finance::irr($emi_irr_array)) * 100;

        if(is_nan($irr_rate)) {
            $irr_rate = Finance::rate(count($emi_irr_array) - 1, $emi_irr_array[1], $emi_irr_array[0], 0);
        }

        if ($irr_rate < 0) {
            $irr_rate = 0;
        }

        $annualised_interest = round((((($rate + 1) * $frequency_multiplier) - $frequency_multiplier) * 100) / 100, 2);
        $annualised_irr = round((((($irr_rate + 1) * $frequency_multiplier) - $frequency_multiplier) * 100) / 100, 2);


        $response['summary']['loan_amount'] = ((isset($application->approved_amount) && $application->approved_amount != 0) ? $application->approved_amount : $application->loan_amount);
        $response['summary']['loan_outstanding'] = $loanamount;
        $response['summary']['tenure'] = $application->emi->tenure;
        $response['summary']['remaining_emi'] = $application->emi->remaining_emi;
        $response['summary']['moratoriums'] = $application->moratoriums;
        $response['summary']['quoted_interest'] = $application->emi->interest_rate;
        $response['summary']['interest'] = $rate;
        $response['summary']['annualised_interest'] = $annualised_interest;
        $response['summary']['irr'] = $irr_rate;
        $response['summary']['annualised_irr'] = $annualised_irr;
        $response['summary']['subvention'] = $application->emi->subvention;
        $response['summary']['processing_fee'] = $application->emi->processing_fee;
        $response['summary']['emi'] = $application->emi->emi;
        $response['summary']['advance_due'] = $application->emi->upfront_from_customer;
        $response['customer_name'] = $application->name;
        $response['id'] = $application->id;
        $response['summary']['merchant_name'] = isset($application->merchant) && isset($application->merchant->merchant_name) ? $application->merchant->merchant_name : '';
        $response['summary']['net_disbursement_amount'] = (isset($application->emi->upfront_from_credit_fair) && $application->emi->upfront_from_credit_fair != 0) ? $application->emi->upfront_from_credit_fair : ((isset($application->approved_amount) && $application->approved_amount != 0) ? $application->approved_amount : $application->loan_amount);
        $response['schedule'] = $emi_schedules ?? [];
        $response['schedule_new'] = $emi_schedules_new ?? [];


        $overpayments = PaymentTransaction::on('mysql_readonly')->where('application_id',$application->id)->whereIn('payment_for',['processing_fee','Over Payment','Advance Payment','rejected','Foreclosure','refund','collection_charges','insurance_fee','adhoc_transaction','advance_amount','foreclosure_bpi','foreclosure_interest','foreclosure_principal','foreclosure_bounce','foreclosure_penal','foreclosure_over_payment'])->whereNull('is_deleted_at')->get();

        // When granular foreclosure splits exist (new cases) use them as the foreclosure-paid amount
        // (they exclude processing_fee, which is credited separately) so PF isn't counted twice.
        // Historical foreclosures (monolith only) keep using the 'Foreclosure' row.
        $hasForeclosureBreakup = RepaymentController::hasForeclosureBreakup($application->id);

        $processing_fee = 0;
        $responseData['advance_payment'] = 0;
        if($overpayments) {
            foreach ($overpayments as $overpayment) {
                if ($overpayment->amount > 0 && ($overpayment->payment_for == "processing_fee" )){
                    $processing_fee = $processing_fee + $overpayment->amount;
                }
                if ($overpayment->amount > 0 && ($overpayment->payment_for == "advance_amount" )){
                    $responseData['advance_payment'] = $responseData['advance_payment'] + $overpayment->amount;
                }

                $isForeclosureLump = $hasForeclosureBreakup
                    ? (strpos($overpayment->payment_for, 'foreclosure_') !== false)
                    : ($overpayment->payment_for == 'Foreclosure');
                if($isForeclosureLump && $overpayment->amount > 0){
                    $response['foreclosureData'][] = ['amount' => $overpayment->amount, 'payment_date' => $overpayment->payment_date];
                }
            }
        }

        $i = 0;
        $processing_fee = (isset($application->emi->processing_fee)) ?  ($application->emi->processing_fee - $processing_fee) : 0;

        $foreclosure = 0;
        foreach ($response['schedule'] as $schedule) {
            //$response['schedule'][$i]['emi_date'] = Carbon::createFromFormat('Y-m-d', (date('Y-m-d', strtotime($application->emi->emi_date))))->addMonths($i)->toDateString();
            $response['schedule'][$i]['emi_date'] = isset($schedule['emi_date']) ? $schedule['emi_date'] : "";
            $foreclosure_date = $response['schedule'][$i]['emi_date'];
            if (isset($payment_details[$response['schedule'][$i]['emi_date']])) {
                $response['schedule'][$i]['payment_status'] = $payment_details[$response['schedule'][$i]['emi_date']]['payment_status'];
                $response['schedule'][$i]['bounce_charges'] = isset($payment_details[$response['schedule'][$i]['emi_date']]['bounce_charges']) ? $payment_details[$response['schedule'][$i]['emi_date']]['bounce_charges'] : 0;
                $response['schedule'][$i]['delay_penalty'] = isset($payment_details[$response['schedule'][$i]['emi_date']]['delay_penalty']) ? $payment_details[$response['schedule'][$i]['emi_date']]['delay_penalty'] : 0;
                $response['schedule'][$i]['charges_waived'] = isset($payment_details[$response['schedule'][$i]['emi_date']]['charges_waived']) ? $payment_details[$response['schedule'][$i]['emi_date']]['charges_waived'] : 0;
                $response['schedule'][$i]['transaction'] = $payment_details[$response['schedule'][$i]['emi_date']]['transaction'];
            } else {
                $response['schedule'][$i]['payment_status'] = "pending";
                $response['schedule'][$i]['bounce_charges'] = 0;
                $response['schedule'][$i]['delay_penalty'] = 0;
                $response['schedule'][$i]['charges_waived'] = 0;
            }
            if (isset($due_amount_details[$id][$response['schedule'][$i]['emi_date']])) {
                $response['schedule'][$i]['bounce_charges'] = isset($due_amount_details[$id][$response['schedule'][$i]['emi_date']]['bounce_charges']) ? $due_amount_details[$id][$response['schedule'][$i]['emi_date']]['bounce_charges'] : 0;
                $response['schedule'][$i]['delay_penalty'] = isset($due_amount_details[$id][$response['schedule'][$i]['emi_date']]['delay_penalty']) ? $due_amount_details[$id][$response['schedule'][$i]['emi_date']]['delay_penalty'] : 0;
            }


            if ($foreclosure == 0) {

                $responseData['future_emi'] = 0;
                $responseData['previous_pending'] = 0;
                foreach ($response['schedule'] as $scheduleItem) {
                    if ($scheduleItem['emi_date'] > $foreclosure_date) {
                        $responseData['future_emi'] = $responseData['future_emi'] + $scheduleItem['principal'];
                    }
                }
                $responseData['future_emi'] = round(($responseData['future_emi']-$responseData['advance_payment']),0);
                $responseData['total_outstanding'] = $responseData['previous_pending'] + $responseData['future_emi'];

                if($processing_fee){
                    $responseData['total_outstanding'] = $responseData['total_outstanding'] + $processing_fee;
                }

                $response['schedule'][$i]['fore_closure_amount'] = isset($responseData['total_outstanding']) ? $responseData['total_outstanding'] : 0;
            } else {
                $response['schedule'][$i]['fore_closure_amount'] = 0;
            }

            $i++;
        }

        if($this->raw){
            return $response;
        }

        return view('admin.accounting.loanschedule_v1', $response);
    }

    public function getPaymentsV1(Request $request, $id = 0, $ids = ''){

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

        $data = [];

        if($request->has('ids')){
            $application_id_array = json_decode(base64_decode($request->get('ids')));
            $applications = ConsumerApplication::with('merchant','application_element', 'highest_dpd')->whereIn('id', $application_id_array)->get(['id','name','merchant_id', 'lender_id']);
            return view('admin.accounting.payment-view', ['applications' => $applications]);
        }

        if(!is_numeric($id)){
            return redirect()->to('/404');
        }else{
            $existApp = ConsumerApplication::with('emi')->where('id',$id)->first(['id', 'lender_id', 'secondary_status']);
            if(!isset($existApp->id) || !isset($existApp->emi)){
                Session::flash('error', 'Application or EMI of this application does not exist');
                return redirect()->to('/admin/consumer-applications');
            }
        }

        // Settlement option in payment_type dropdown: visible only when a Settlement
        // CollectionAction exists AND its maker-checker record is approved.
        $showSettlementOption = \App\SettlementMakerChecker::where('application_id', $id)
            ->where('status', 'approved')->whereHas('collectionAction', function ($q) {$q->where('dispo_code', 'Settlement');})->exists();
        
        $data['settled_sub_transactions'] = ParkedTransaction::where('application_id', $id)->where('payment_for', 'settlement_payment')->where('reconciliation_status', 'reconciled')->get();
        $data['showSettlementOption'] = $showSettlementOption && in_array($existApp->secondary_status, ['settlement-in-progress']);
        $parkedTransaction = ParkedTransaction::where('application_id', $id)->where('reconciliation_status', 'parked')->get();
        $data['parked_transactions'] = $parkedTransaction;

        $consumer_application_controller = (new ConsumerApplicationController());
        $consumer_application_controller->updateInsuranceFeesPayment($id);
        $rpsLog_exists = RPS_Logs::where('application_id', $id)->exists();

        $is_pre_payment = PaymentTransaction::where('application_id',$id)->whereIn('payment_for',['pre_part_payment'])->whereNull('is_deleted_at')->first(['id']);
        $is_pre_payment_flag = isset($is_pre_payment->id);

        if($existApp->lender_id != Capri::$lender_id) {
            $loan_management = new LoanManagement();
            $loan_management->payment_entry_page = true;
            $loan_management->paymentCalculate($id, '', 'all');
        }

        if($rpsLog_exists || $is_pre_payment_flag){ //($rpsLog_exists && $existApp->lender_id != Singularity::$lender_id)
            $repaymentController = new RepaymentController();
            $paymentData = $repaymentController->getPaymentPageDetails($id);
            if(!$paymentData){
                Session::flash('error', 'Something went wrong while fetching the details');
                return redirect()->to('/admin/consumer-applications');
            }
            $data = array_merge($data, $paymentData);
            $consumer_application_controller->updateProcessFeesPayment($id);
            $consumer_application_controller->updateLegalChargesPayment($id);
            return view('admin.accounting.payment_v1', $data);
        }

        $data['paymentsData'] = EmiPayment::with('transaction.bank','moratoriums')->where('application_id', $id)->orderBy('emi_date','asc')->get();
        $data['application'] = ConsumerApplication::with('application_element','emi','settlement_payment')->where('id', $id)->first(['id','name','lender_id', 'state', 'secondary_status']);
        $isSettled = false;
        $settlement_amount = 0;
        if(isset($data['application']->secondary_status) && $data['application']->secondary_status == 'settled'){
            $settlement_amount = $data['application']->settlement_payment->sum('amount');
            $isSettled = true;
        }
        $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', 'legal_charges', 'Pre-EMI', 'pre_payment', 'pre_part_payment', 'settled_principal', 'settled_interest', 'settled_bounce', 'settled_penal', 'written_off_principal', 'written_off_interest', 'written_off_bounce', 'written_off_penal', 'waived_off_bounce', 'waived_off_penal', 'foreclosure_bpi', 'foreclosure_interest', 'foreclosure_principal', 'foreclosure_bounce', 'foreclosure_penal', 'foreclosure_over_payment', 'security_deposit'])->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;
                    }
                }
            }
        }

        $foreclosure_date = '';
        $over_payment = 0;
        $adhoc_payment = 0;
        $advance_amount = 0;
        $processing_fee = 0;
        $foreclosure_amount_cals = 0;
        $foreclosed_info = [];
        $isForeclosed = 0;
        $settled_info = [];

        if (isset($existApp->foreclosure_event->id)) {
            $isForeclosed = 1;
            $foreclosure_date = $existApp->foreclosure_event->payment_date;
            $foreclosed_info = [
                'foreclosed_amount' => $foreclosure_amount_cals + $existApp->foreclosure_event->amount,
                'foreclosed_payment_date' => $existApp->foreclosure_event->payment_date,
                'foreclosed_payment_mode' => $existApp->foreclosure_event->mode,
                'foreclosed_transaction_id' => $existApp->foreclosure_event->trasanction_id,
                'foreclosed_cf_transaction_id' => $existApp->foreclosure_event->cf_transaction_id,
            ];
        }

        // When granular foreclosure splits exist (new cases) use them as the foreclosure-paid amount
        // (they exclude processing_fee, which is credited separately) so PF isn't counted twice in
        // amount_paid. Historical foreclosures (monolith only) keep using the 'Foreclosure' row.
        $hasForeclosureBreakup = RepaymentController::hasForeclosureBreakup($id);

        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;
                }
                $isForeclosureLump = $hasForeclosureBreakup
                    ? (strpos($overpayment->payment_for, 'foreclosure_') !== false)
                    : ($overpayment->payment_for == "Foreclosure");
                if ($overpayment->amount > 0 && ($overpayment->payment_for == "Over Payment" || $overpayment->payment_for == "Advance Payment"  || $isForeclosureLump || strpos($overpayment->payment_for, 'settled') !== false) && $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 ($isSettled && ($overpayment->payment_for == "settled_principal")){
                    $settled_info = [
                        'settled_amount' => $settlement_amount,
                        'settled_payment_date' => $overpayment->payment_date,
//                        'settled_payment_reconcile_date' => $overpayment->payment_reconciliation_date,
                        'settled_payment_mode' => $overpayment->mode,
                        'settled_transaction_id' => $overpayment->trasanction_id,
                        'settled_cf_transaction_id' => $overpayment->cf_transaction_id,
                    ];
                }

            }
            $data['over_payment'] = $over_payment;
        }else{
            $data['over_payment'] = 0;
        }

        if($data['application']->application_element->total_amount_due == 0){
            $max_payable = 0;
        }

        // Keep foreclosure_bounce / foreclosure_penal visible in the adhoc-transactions list, but hide
        // the other foreclosure splits (bpi/interest/principal/over_payment); the foreclosure lump is
        // surfaced via the foreclosed_info card.
        $data['adhoc_transactions'] = $overPayments->reject(function($t){ return strpos($t->payment_for, 'foreclosure_') !== false && !in_array($t->payment_for, ['foreclosure_bounce', 'foreclosure_penal'], true); })->values();
        $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['moratoriumsLogs'] = Moratorium::with('user','stopped')->where('application_id', $id)->get();
        $data['frequencyDetails'] = ApplicationEMICalculation::where('application_id', $id)->first(['payment_frequency']);
        $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'];




        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['waiver'] = 0;
        $response['advance_payment'] = 0;
        $response['foreclosure_date'] = $foreclosure_date;

        $_paid_dues = [];
        $_breakup = ['principal' => 0, 'moratorium' => 0, 'interest' => 0];
        foreach ($paymentsData as $c => $payments){
            if($payments->emi_date <= $foreclosure_date) {
                if($payments['amount_due'] > 0) {
                    $payments['bounce_charges'] = $payments['bounce_charges'] ?? 0;
                    $payments['delay_penalty'] = $payments['delay_penalty'] ?? 0;
                    $charges_waived = $payments['charges_waived'] ?? 0;
                    $bounce_waived = 0;
                    $penalty_waived = 0;

                    $delay_penalty = $payments['delay_penalty'];
                    $bounce_charges = $payments['bounce_charges'];
                    $pending_amount_reco = $payments['amount_due'];

                    if($pending_amount_reco && ($delay_penalty || $bounce_charges)){
                        if($pending_amount_reco <= $delay_penalty){
                            $delay_penalty = $pending_amount_reco;
                            $bounce_charges = 0;
                        }else{
                            $bounce_balance = $pending_amount_reco - $delay_penalty;
                            if($bounce_balance == $bounce_charges) {
                                $bounce_charges = $pending_amount_reco - $delay_penalty;
                            }
                        }
                    }



                    if($charges_waived >= $payments['delay_penalty']){
                        $charges_waived -= $payments['delay_penalty'];
                        $penalty_waived = $payments['delay_penalty'];
                        if($charges_waived >= $payments['bounce_charges']){
                            $charges_waived -= $payments['bounce_charges'];
                            $bounce_waived = $payments['bounce_charges'];
                        }else{
                            $bounce_waived = $charges_waived;
                            $charges_waived = 0;
                        }
                    }else{
                        $penalty_waived = $charges_waived;
                        $charges_waived = 0;
                    }
                    $response['previous_pending'] = $response['previous_pending'] + $payments['pending_amount'];
                    $response['bounce_charges'] = $response['bounce_charges'] + ($bounce_charges - $bounce_waived);
                    $response['penal_interest'] = $response['penal_interest'] + ($delay_penalty - $penalty_waived);
                    $response['waiver'] += $charges_waived;
                }
                $response['foreclosure_date'] = $payments->emi_date;
            }else{
                $response['advance_payment'] = $response['advance_payment'] + ($payments['total_payable'] - $payments['amount_due']);
            }
            $_paid_dues[$payments->emi_date] = $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;
                        $_breakup['moratorium'] += $payments->moratorium_amount;
                    }
                }

                unset($payments->moratoriums);
            }
        }

        foreach ($schedule['schedule'] as $loan_schedule){
            $_principalDiff = $loan_schedule['principal'] - $_paid_dues[$loan_schedule['emi_date']];
            $_remainingInterest = $_paid_dues[$loan_schedule['emi_date']] - $loan_schedule['principal'] > 0 ? $_paid_dues[$loan_schedule['emi_date']] - $loan_schedule['principal'] : 0;
            $_interestDiff = $loan_schedule['interest'] - $_remainingInterest;
            if($_paid_dues[$loan_schedule['emi_date']] > 0){
                $_breakup['principal'] += ($_principalDiff > 0 ? (int)$_principalDiff : 0);
            }else{
                $_breakup['principal'] += $loan_schedule['principal'];
            }

            if($loan_schedule['emi_date'] > $response['foreclosure_date']){
                $response['future_emi'] = $response['future_emi'] + $loan_schedule['principal'];

                $_val1 = strtotime($loan_schedule['emi_date']);
                $_val2 = strtotime($response['foreclosure_date']);
                $datediff = $_val1 - $_val2;
                if(round($datediff / (60 * 60 * 24)) < 15){
                    $_breakup['interest'] += ($_interestDiff > 0 ? $_interestDiff : 0);
                }
            }else{
                $_breakup['interest'] += ($_interestDiff > 0 ? $_interestDiff : 0);
            }
        }

        $response['future_emi'] = round(($response['future_emi']-$response['advance_payment']),0);
        $response['total_outstanding'] = $response['previous_pending'] + $response['future_emi'];
        $data['foreclosure_date'] = $response['foreclosure_date'] ?? '';

        $data['waived_off_data'] = (new LoanManagement())->getWaivedOff($id);
        $data['can_waive_off'] = static::canWaiveOff($id) ? 1 : 0;


        // Use the foreclosure_event accessor to dynamically handle both legacy monoliths
        // and new granular splits, ensuring we correctly compare the full paid amount.
        $foreclosedAmount = $existApp->foreclosure_event->amount ?? null;
        if($foreclosedAmount !== null && isset($data['foreclosure_amount']) && $foreclosedAmount < $data['foreclosure_amount']){
            $isForeclosed = 0;
        }
        $data['foreclosure_breakup'] = [];

        if(isset($data['foreclosure_breakup']['is_foreclosed']) && $data['foreclosure_breakup']['is_foreclosed']){
            $data['processing_fee_due'] = round($data['processing_fee_due'] - $data['foreclosure_breakup']['pf_due']);
            $data['advance_amount_due'] = round($data['advance_amount_due'] - $data['foreclosure_breakup']['advance_due']);
        }

        $payment_logs = PaymentLogs::where('application_id', $id)->orderBy('created_at','desc')->get();
        $data['payment_logs'] = [];
        foreach ($payment_logs as $payment_log){
            $data['payment_logs'][$id][$payment_log->emi_payment_id][] = $payment_log;
        }

        if ($request->has('job_raw')){
            $data['scheduleData'] = $schedule['schedule'];
            $data['foreclosure_amount_cals'] = $foreclosure_amount_cals;
            return $data;
        }
        $data['foreclosed_info'] = $foreclosed_info;
        $data['isForeclosed'] = $isForeclosed;
        $data['isSettled'] = $isSettled;
        $data['settled_info'] = $settled_info;

        $data['reference'] = AvanseCreateFinance::where('application_id', $id)->first();
        $data['lender_name'] = $data['application']->lender->name ?? '';
        return view('admin.accounting.payment_v1', $data);
    }

    public function saveStopFollowUp(Request $request, $id)
    {
        $application = \App\ConsumerApplication::where('id', $id)
            ->whereIn('state', ['disbursed', 'nach registered'])
            ->first(['id', 'state']);

        if (!$application) {
            return response()->json(['status' => 'FAIL', 'message' => 'Application not found or invalid state'], 404);
        }

        $status = $request->get('follow_up_status');
        if (!in_array($status, ['active', 'stopped'])) {
            return response()->json(['status' => 'FAIL', 'message' => 'Invalid follow-up status'], 422);
        }

        $reason = $request->get('follow_up_reason', '');
        if ($status === 'stopped' && empty(trim($reason))) {
            return response()->json(['status' => 'FAIL', 'message' => 'Reason is required when status is Stopped'], 422);
        }

        // Always insert a new row to maintain history
        \App\ConsumerApplicationFollowUp::create([
            'application_id'      => $id,
            'follow_up_status'    => $status,
            'follow_up_reason'    => $status === 'stopped' ? trim($reason) : null,
            'follow_up_stopped_by'=> \Auth::user()->id,
        ]);

        return response()->json(['status' => 'OK', 'message' => 'Follow-up status updated successfully']);
    }

    public function getForeclosureDetails($id){
        if ($foreclosure_details = (new RepaymentController())->getForeclosureThroughAPI($id)){
            return response()->json(['status' => 'OK', 'data' => $foreclosure_details]);
        }

        return response()->json(['message' => 'Failed to get foreclosure details', 'status' => 'FAIL']);
    }

    public function validateForeclosureAmount(Request $request)
    {
        $result = (new ForeclosureValidationService())->validateForeclosurePayableAmount(
            $request->input('payment_type'),
            $request->input('payable_amount'),
            $request->input('bounce_charges'),
            $request->input('penal_charges'),
            $request->input('total_amount_due')
        );
        return response()->json($result);
    }

    public function getForeclosureBreakup($response, $data, $_breakup, $id, $isForeclosed){
        $breakupLogs = ForeclosureBreakup::where('application_id', $id)->orderBy('created_at', 'desc')->first();
        if(isset($breakupLogs->id) && $isForeclosed){
            return [
                'is_foreclosed' => 1,
                'pre_emi_due' => 0,
                'principal_due' => round($breakupLogs->principal_due, 2),
                'interest_due' => round($breakupLogs->interest_due),
                'moratorium_due' => round($breakupLogs->moratorium_due, 2),
                'bounce_charges' => $breakupLogs->bounce_due,
                'penal_charges' => $breakupLogs->penal_due,
                'emi_due' => $breakupLogs->emi_due,
                'pf_due' => $breakupLogs->pf_due,
                'advance_due' => $breakupLogs->advance_due,
                'total_foreclosure_amount' => $breakupLogs->foreclosure_amount,
            ];
        } else{

            if ($foreclosure_details = (new RepaymentController())->getForeclosureThroughAPI($id)){
                return $foreclosure_details;
            }


            $pf_due = 0;
            $emi_due = $response['total_outstanding'];
//        $foreclosure_date = $response['foreclosure_date'] ?? '';
            if(isset($data['processing_fee_due'])){
                $pf_due = $data['processing_fee_due'];
            }
            $advance_due = $data['advance_amount_due'];

            $foreclosure_amount = round($_breakup['principal'] - $response['waiver']) + round($_breakup['moratorium']) + round($_breakup['interest']) +
                round($response['bounce_charges']) + round($response['penal_interest']) +
                $pf_due + $advance_due;

            return [
                'is_foreclosed' => 0,
                'pre_emi_due' => 0,
                'principal_due' => round($_breakup['principal'] - $response['waiver'], 2),
                'moratorium_due' => round($_breakup['moratorium'], 2),
                'interest_due' => round($_breakup['interest']),
                'bounce_charges' => $response['bounce_charges'],
                'penal_charges' => $response['penal_interest'],
                'emi_due' => $emi_due,
                'pf_due' => $pf_due,
                'advance_due' => $advance_due,
                'total_foreclosure_amount' => round($foreclosure_amount),
            ];
        }
    }

    public function getPaymentsV2(Request $request, $id = 0, $ids = ''){

        $data = [];

        if($request->has('ids')){
            $application_id_array = json_decode(base64_decode($request->get('ids')));
            $applications = ConsumerApplication::with('merchant','application_element', 'highest_dpd')->whereIn('id', $application_id_array)->get(['id','name','merchant_id']);
            return view('admin.accounting.payment-view', ['applications' => $applications]);
        }

        (new LoanManagement())->paymentCalculateV2($id,'','all');

        $data['paymentsData'] = EmiPaymentTemp::with('transaction.bank','moratoriums')->where('application_id', $id)->orderBy('emi_date','asc')->get();
        $data['application'] = ConsumerApplication::with('application_element','proFormaInvoice','emi', 'lender')->where('id', $id)->first(['id','name','lender_id', 'state']);

        $overPayments = PaymentTransactionTemp::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', 'security_deposit', 'foreclosure_bpi', 'foreclosure_interest', 'foreclosure_principal', 'foreclosure_bounce', 'foreclosure_penal', 'foreclosure_over_payment'])->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;
        $foreclosure_payment_date = 0;
        $foreclosure_payment_reconcile_date = 0;
        $forecloser_payment_mode = 'NEFT';
        $forecloser_transaction_id = 0;
        $forecloser_id = 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;
                }
                $isGranular = strpos($overpayment->payment_for, 'foreclosure_') === 0;

                if ($overpayment->amount > 0 && ($overpayment->payment_for == "Over Payment" || $overpayment->payment_for == "Advance Payment"  || $overpayment->payment_for == "Foreclosure" || $isGranular) && $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" || $isGranular) && $overpayment->status != "rejected"){
                    $isForeclosed = 1;
                }

                if($request->has('job_raw') && ($overpayment->payment_for == "Foreclosure" || $isGranular)){
                    $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;
        }

        // Keep foreclosure_bounce / foreclosure_penal visible in the adhoc-transactions list, but hide
        // the other foreclosure splits (bpi/interest/principal/over_payment); the foreclosure lump is
        // surfaced via the foreclosed_info card.
        $data['adhoc_transactions'] = $overPayments->reject(function($t){ return strpos($t->payment_for, 'foreclosure_') !== false && !in_array($t->payment_for, ['foreclosure_bounce', 'foreclosure_penal'], true); })->values();
        $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['moratoriumsLogs'] = Moratorium::with('user','stopped')->where('application_id', $id)->get();
        $data['frequencyDetails'] = ApplicationEMICalculation::where('application_id', $id)->first(['payment_frequency']);
        $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'];
//        $auto_waive_amount = AutoWaiver::orderBy('created_at','desc')->first();
//
//        $data['auto_waive_amount'] = 0;
//        if($response['total_outstanding'] <= $auto_waive_amount->waive_off_amt ){
//            $data['auto_waive_amount'] = $response['total_outstanding'];
//            $response['total_outstanding'] = 0;
//        }
        /*if($data['application']->lender_id == AvanseServices::$lender_id){


        }else {*/
            $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;
        }
        $data['waived_off_data'] = (new LoanManagement())->getWaivedOff($id);
        $data['can_waive_off'] = static::canWaiveOff($id) ? 1 : 0;


        $foreclosedAmount = DB::select("select sum(amount) as 'amount' from payment_transactions_temp where trasanction_id=(select trasanction_id from payment_transactions_temp 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;
        }

        $payment_logs = PaymentLogs::where('application_id', $id)->orderBy('created_at','desc')->get();
        $data['payment_logs'] = [];
        foreach ($payment_logs as $payment_log){
            $data['payment_logs'][$id][$payment_log->emi_payment_id][] = $payment_log;
        }

        if ($request->has('job_raw')){
            $data['scheduleData'] = $schedule['schedule'];
            $data['foreclosure_amount_cals'] = $foreclosure_amount_cals;
            return $data;
        }
        $data['isForeclosed'] = $isForeclosed;
        $data['reference'] = AvanseCreateFinance::where('application_id', $id)->first();
        $data['lender_name'] = $data['application']->lender->name ?? '';
        $data['settled_sub_transactions'] = ParkedTransaction::where('application_id', $id)->where('payment_for', 'settlement_payment')->where('reconciliation_status', 'reconciled')->get();

        return view('admin.accounting.payment_v1', $data);
    }

    public function earlySettlement(Request $request){
        $response = (new AvanseServices($request))->earlySettlement();
        return \response()->json([ 'status' => 'OK', 'message' => $response],200);
    }


    public function getPayments(Request $request, $id = 0, $ids = ''){
        $isDue = $request->has('due') ? 1 : 0;
        $loan_management = new LoanManagement();

        if($id != 0){
            $loan_management->paymentCalculate($id,'','all');
        }
        if($ids != ""){
            $application_id_array = json_decode(base64_decode($ids));
            $applications = ConsumerApplication::with('merchant','application_element', 'highest_dpd')->whereIn('id', $application_id_array)->get(['id','name','merchant_id']);
            return view('admin.accounting.payment-view', ['applications' => $applications]);
        }
        if ($request->has('isPagination')) {
            $loan_management->isPagination = 10;
            $loan_management->isPaginationSkip = 10 * ($request->has('page') && $request->get('page') > 1  ? $request->get('page') : 0);
        }

        $loan_management = new LoanManagement();
        if($ids != "" && isset($application_id_array)){
            $EMIPaymentData = $loan_management->getPaymentDueHistory($id,"",1,$isDue,0,$application_id_array);
        }else {
            if($id > 0 && $isDue == 0){
                $EMIPaymentData = $loan_management->getPaymentDueHistory($id, "", 1, $isDue);
            }else {
                $EMIPaymentData = $loan_management->getPaymentDueHistory($id, "", "", $isDue);
            }
        }

        $data['payments'] = $EMIPaymentData;
        $response = [];
        $newPayments = [];
        $values = [];

        //$data['moratorium'] = Moratorium::with('user')->where('application_id', $id)->where('status',1)->first(['id','emi_date','user_id']);
        $moratorium = new Moratorium();

        foreach ($data['payments'] as $application_id => $payment) {
            foreach ($payment['payment'] as $emi_date => $item) {
                if (isset($item['payment_history'])) {
                    $paymentHistory = $item;
                    if (isset($item['payment_history']['transaction'])) {
                        $paymentHistory['transaction'] = $item['payment_history']['transaction'];
                    }
                } else {
                    $paymentHistory = $item;
                }

                // adding checker/verifier name and time in transaction
                foreach($item->transaction as $pay){
                    $t = str_replace("'","",$pay->trasanction_id);
                    $checkerInfo = DB::table('payments_maker_checker')
                            ->where('trasanction_id_virtual', $t)
                            ->where('application_id', $application_id)
                            ->whereNull('deleted_at')
                            ->get()
                            ->toArray();
                    // $checkerInfo = DB::select("select * from payments_maker_checker where json_extract(data, '$.trasanction_id')='$t' and application_id='$application_id' and deleted_at is null");
                    foreach($checkerInfo as $transaction){
                        if($transaction->checker_id > 0){
                            $userData = User::find($transaction->checker_id);
                        }
                        $pay->verifier_name = $userData->name ?? '';
                        $pay->verify_date = $transaction->verify_date ?? '';
                    }
                }

                if(isset($item->moratoriums) && count($item->moratoriums)){
                    foreach ($item->moratoriums as $moratoriumItem){
                        if($moratoriumItem->emi_date == Carbon::createFromFormat('Y-m-d', $item->emi_date)->subMonth(1)->toDateString()) {
                            $moratoriumAmount = $moratorium->getPrincipalOutstanding($application_id, $moratoriumItem);
                            $moratoriumItem['moratoriumAmount'] = $moratoriumAmount;
                            $paymentHistory['moratorium'] = $moratoriumItem;
                        }
                    }

                    unset($item->moratoriums);
                }

                $response[$application_id][$emi_date] = $paymentHistory;
                $foreclosure_data = $loan_management->getForeclosureAmount($application_id);
                $fore_closure_amount = (isset($foreclosure_data['total_outstanding'])) ? $foreclosure_data['total_outstanding'] : 0;
                $fore_closure_date = (isset($foreclosure_data['foreclosure_date'])) ? $foreclosure_data['foreclosure_date'] : 0;
                if(isset($payment['processing_fee_due']) && $payment['processing_fee_due'] > 0){
                    $fore_closure_amount = $fore_closure_amount + $payment['processing_fee_due'];
                }
                $newPayments[$application_id] = [
                    'name' => $payment['applicant_name'],
                    'amount_due' => $payment['amount_due'],
                    'max_payable' => $payment['max_payable'],
                    'over_payment' => $payment['over_payment'],
                    'adhoc_transaction' => $payment['adhoc_transaction'],
                    'waived_off_data' => $payment['waived_off_data'] ?? [],
                    'amount_paid' => $payment['amount_paid'],
                    'emi_due' => $payment['emi_due'],
                    'emi_paid' => $payment['emi_paid'],
                    'amount_pending' => $payment['amount_pending'],
                    'foreclosure_amount'=>$fore_closure_amount,
                    'foreclosure_date'=>$fore_closure_date,
                    'processing_fee_due' => $payment['processing_fee_due'],
                    'advance_amount_due' => $payment['advance_amount_due']
                ];
            }
        }

        foreach ($response as $id_index=>$item){

            usort($item, function ($a, $b){
                return $a->emi_date <=> $b->emi_date;
            });

            $values[] = [
                'id' => $id_index,
                'name' => $newPayments[$id_index]['name'],
                'amount_due' => $newPayments[$id_index]['amount_due'],
                'max_payable' => $newPayments[$id_index]['max_payable'],
                'over_payment' => $newPayments[$id_index]['over_payment'],
                'adhoc_transaction' => $newPayments[$id_index]['adhoc_transaction'],
                'payment' => $item,
                'waived_off_data' => $newPayments[$id_index]['waived_off_data'],
                'amount_paid' => $newPayments[$id_index]['amount_paid'],
                'emi_due' => $newPayments[$id_index]['emi_due'],
                'emi_paid' => $newPayments[$id_index]['emi_paid'],
                'amount_pending' => $newPayments[$id_index]['amount_pending'],
                'foreclosure_amount' => $newPayments[$id_index]['foreclosure_amount'],
                'foreclosure_date' => $newPayments[$id_index]['foreclosure_date'],
                'processing_fee_due' => $newPayments[$id_index]['processing_fee_due'],
                'advance_amount_due' => $newPayments[$id_index]['advance_amount_due']

            ];
        }

        $data['payments'] = $values;
        $data['paginationTotal'] = $loan_management->isPaginationTotal;
        $data['paginationLastPage'] = $loan_management->isPaginationLastPage;
        $data['application_id'] = $id;
        $data['can_waive_off'] = static::canWaiveOff($id) ? 1 : 0;

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

        $payment_logs = PaymentLogs::where('application_id', $id)->orderBy('created_at','desc')->get();
        $data['payment_logs'] = [];
        foreach ($payment_logs as $payment_log){
            $data['payment_logs'][$id][$payment_log->emi_payment_id][] = $payment_log;
        }

        $data['moratoriumsLogs'] = Moratorium::with('user','stopped')->where('application_id', $id)->get();
        $data['frequencyDetails'] = ApplicationEMICalculation::where('application_id', $id)->first(['payment_frequency']);
        return view('admin.accounting.payment', $data);
    }

    public function saveDPDManual(Request $request){
        $isUpdate = EmiPayment::where('id', $request->get('id'))->update(['dpd_reason' => implode(',', $request->get('reason'))]);
        return response(['status' => $isUpdate ? 'OK' : 'FAIL', 'message' => $isUpdate ? 'DPD Saved successfully' : 'Something went wrong']);
    }

    private function getPaginator(Request $request, $items, $total)
    {
        $page = $request->page ?? 1;
        $perPage = 10;

        return new LengthAwarePaginator($items, $total, $perPage, $page, [
            'path' => $request->url(),
            'query' => $request->query()
        ]);
    }

//    public function getClosedLoan($id = 0, Request $request){
////        $from_date = ($request->has('from_date') && !empty($request->get('from_date'))) ? Carbon::createFromFormat('Y-m-d',$request->get('from_date'))->startOfDay()->toDateTimeString() : Carbon::now()->startOfDay()->toDateTimeString();
////        $to_date = ($request->has('to_date') && !empty($request->get('to_date'))) ? Carbon::createFromFormat('Y-m-d',$request->get('to_date'))->endOfDay()->toDateTimeString() : Carbon::now()->endOfDay()->toDateTimeString();
////        $data['from_date'] = date('Y-m-d',strtotime($from_date));
////        $data['to_date'] = date('Y-m-d',strtotime($to_date));
//        $EMIPayment = new PaymentEmi();
//        if ($request->has('isPagination')) {
//            $EMIPayment->isPagination = 10;
//            $EMIPayment->isPaginationSkip = 10 * ($request->has('page') && $request->get('page') > 1  ? $request->get('page') : 0);
//        }
//        $EMIPayment->status = ['disbursed','nach registered'];
//        $EMIPaymentData = $EMIPayment->getPaymentDueHistory($id);
//        /*$EMIPayment = EmiPayment::with('application:id,name','transaction')->where('emi_date','>=',$from_date)->where('emi_date','<=',$to_date);
//            if($request->has('application_id') && $request->ge('application_id')){
//                $EMIPayment = $EMIPayment->where('application_id',$request->get('application_id'));
//            }
//        $EMIPayment = $EMIPayment->get();*/
//        $data['payments'] = $EMIPaymentData;
//        $response = [];
//        $newPayments = [];
//        $values = [];
//        foreach ($data['payments'] as $application_id => $payment) {
//            if (($payment['amount_pending'] < 100)  || ($payment['emi_due'] == 0) || (date('Y-m-d') > $payment['last_emi_date'])) {
//                foreach ($payment['payment'] as $emi_date => $item) {
//                    if (isset($item['payment_history'])) {
//                        $paymentHistory = $item;
//                        if (isset($item['payment_history']['transaction'])) {
//                            $paymentHistory['transaction'] = $item['payment_history']['transaction'];
//                        }
////                    $paymentHistory = $item['payment_history'];
////                    $paymentHistory['amount_received'] = $item['amount_received'];
////                    $paymentHistory['pending_amount'] = $item['pending_amount'];
//                    } else {
//                        $paymentHistory = $item;
//                    }
//                    $response[$application_id][$emi_date] = $paymentHistory;
//
//                    $newPayments[$application_id] = ['name' => $payment['applicant_name'], 'amount_due' => $payment['amount_due'], 'max_payable' => $payment['max_payable'], 'over_payment' => $payment['over_payment'], 'adhoc_transaction' => $payment['adhoc_transaction'], 'waived_off_data' => isset($payment['waived_off_data']) ? $payment['waived_off_data'] : [],'amount_paid' =>  $payment['amount_paid'],'emi_due' =>  $payment['emi_due'],'emi_paid' =>  $payment['emi_paid'],'amount_pending' =>  $payment['amount_pending'],'last_emi_date' => $payment['last_emi_date']];
//                }
//            }
//        }
//
//        if (empty($response)){
//            $request->request->add(['page' => $request->get('page') + 1]);
//            return $this->getClosedLoan($id, $request);
//        }
//
//        foreach ($response as $id_index=>$item){
//            $values[] = [
//                'id' => $id_index,
//                'name' => $newPayments[$id_index]['name'],
//                'amount_due' => $newPayments[$id_index]['amount_due'],
//                'max_payable' => $newPayments[$id_index]['max_payable'],
//                'over_payment' => $newPayments[$id_index]['over_payment'],
//                'adhoc_transaction' => $newPayments[$id_index]['adhoc_transaction'],
//                'payment' => $item,
//                'waived_off_data' => $newPayments[$id_index]['waived_off_data'],
//                'amount_paid' => $newPayments[$id_index]['amount_paid'],
//                'emi_due' => $newPayments[$id_index]['emi_due'],
//                'emi_paid' => $newPayments[$id_index]['emi_paid'],
//                'amount_pending' => $newPayments[$id_index]['amount_pending'],
//                'last_emi_date' => $newPayments[$id_index]['last_emi_date'],
//            ];
//        }
//
//        $data['payments'] = $values;
//        $data['paginationTotal'] = $EMIPayment->isPaginationTotal;
//        $data['paginationLastPage'] = $EMIPayment->isPaginationLastPage;
//        $data['application_id'] = $id;
//
//        if($request->has('raw')){
//            return $data;
//        }
//
//        return view('admin.accounting.closedloans', $data);
//    }

    public function reportClosedLoan(Request $request){

        $status = 'FAIL';
        $message = 'Failed to report loan, Please try after sometime';

        if($request->has('comment') && $request->has('user_id') && $request->has('id')){
            $status = 'OK';
            $message = 'Loan reported successfully. Now you can close the loan!';
            ReportCloseLoan::insert([
                'application_id' => $request->get('id'),
                'user_id' => $request->get('user_id'),
                'comment' => $request->get('comment'),
                'created_at' => Carbon::now()->toDateTimeString()
            ]);
        }

        return response(['status' => $status, 'message' => $message]);
    }

    public function closeSelectedLoans(Request $request){

        $status = 'FAIL';
        $message = 'Failed to close loan';

        if($request->get('applications') && $request->get('user_id')){
            $payloads = [];
            $closed = 0;
            $alreadyClosedState = 0;
            $applicationIds = [];
            $statusChange = [];
            $closedIds = [];
            $settledIds = [];

            $noc_insert = [];
            $applications = array_values(array_unique($request->get('applications')));
            foreach ($applications as $item){
                if($item){

                    if(!in_array($item, $applicationIds)) {
                        $isExists = JobProvider::where('application_id', $item)->where('is_available',0)->where('payload', 'like', '%"status":"closed"%')->first();

                        if (!isset($isExists->id)) {
                            $application = ConsumerApplication::with('settlement_payment')->where('id', $item)->first();
                            $payloads[] = [
                                'payload' => json_encode(["id" => $item, "status" => "closed", "previous_status" => $application->state, "auth_user_id" => $request->get('user_id'), "state" => "closed", "abort_reason" => null, 'cancel_nach' => true]),
                                'from' => 'statusChange',
                                'application_id' => $item,
                                'available_at' => Carbon::now()->addMinute($closed)->toDateTimeString(),
                                'created_at' => Carbon::now()->toDateTimeString()
                            ];
                            $statusChange[] = [
                                'application_id' => $item,
                                'user_id' => $request->get('user_id'),
                                'status' => 'closed',
                                'created_at' => Carbon::now()->toDateTimeString()
                            ];
                            if ($application->settlement_payment && $application->settlement_payment->sum('amount') > 0) {
                                $settlement_amount = $application->settlement_payment->sum('amount');
                                $settledIds[] = $item;
                                $latestSettlement = $application->settlement_payment->sortByDesc('created_at')->first();
                                $this->sendSettledCommunication($application->email, $item, $application->name, $settlement_amount, $latestSettlement->payment_date, $latestSettlement->settlement_date);
                            }
                            $closedIds[] = $item;

                            if($application->lender_id == AvanseServices::$lender_id){
                                $noc_insert[] = [
                                    'application_id' => $item,
                                    'is_available' => 0,
                                    'execution_status'=>'pending',
                                    'created_at' => Carbon::now()->toDateTimeString()
                                ];
                            }

                            $closed++;
                        } else {
                            $alreadyClosedState++;
                        }

                        $applicationIds[] = $item;
                    }

                }
            }


            if($statusChange) {
                StatusLogs::insert($statusChange);
                ConsumerApplication::whereIn('id',$closedIds)->update(['state' => 'closed']);
            }
            if($settledIds){
                // ConsumerApplicationAdditional::whereIn('application_id',$settledIds)->update(['secondary_status' => 'settled']);
                ConsumerApplication::whereIn('id',$settledIds)->update(['secondary_status' => 'settled']);
            }
            if($noc_insert){
                AvanseNOC::insert($noc_insert);
                event(new EventAvanseNoc());
            }

            if($payloads) {
                JobProvider::insert($payloads);
            }

            $notClosed = count($request->get('applications')) - $closed;

            $status = 'OK';

            if($notClosed) {
                $message = $closed . ' Loan closed and '.$notClosed.' not closed';
            }else{
                $message = $closed . ' Loan closed successfully';
            }

            if($alreadyClosedState){
                $message = $closed . ' Loan closed and '.$alreadyClosedState.' is in Pending state';
            }
        }


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

    public function sendSettledCommunication($email, $application_id, $name, $amount, $payment_date, $settlement_date){
         if (isset($email)) {
            $body = '
            <div style="font-size:13px;font-family:verdana,arial;line-height:1.5">
            Dear ' . $name . ',
            We are writing to inform you that your loan with [NBFC Name] has been successfully settled. Below are the details of the settlement: <br><br>

                Borrower Name: ' .$name. ' <br><br>

                Loan Application ID: ' .$application_id. ' <br><br>

                Settlement Amount: ₹ ' .$amount. '  <br><br>

                Payment Date: ' .$payment_date. ' <br><br>

                Settlement Date: ' .$settlement_date. ' <br><br>

            With this settlement, your loan account is now considered settled, and no further payments are required. If you need any further assistance or documentation regarding this settlement, please do not hesitate to contact us.<br><br>

            We appreciate your cooperation throughout the loan process and wish you all the best in your future endeavors.<br><br>

            Thank you for choosing Credit Fair.<br>
            </div>';

            Mail::send('emails.reminders.basic_reminder',
                ['body' => $body]
                , function ($message) use ($email) {
                    $message->to([$email])->subject('Pay Legal Charges');
            });
        }
    }

    public function getClosedLoan($id = 0, Request $request){

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

        $loan_management = new LoanManagement();
        if ($request->has('isPagination')) {
            $loan_management->isPagination = 10;
            $loan_management->isPaginationSkip = 10 * ($request->has('page') && $request->get('page') > 1  ? $request->get('page') : 0);
        }
        $loan_management = new LoanManagement();
        $loan_management->excludeWriteoff = true;
        $loan_management->includeSettlements = true;
        $loan_management->lender_id_req = $request->has('lender_id') && $request->has('lender_id') ? $request->get('lender_id') : 9;
        $loan_management->emi_date_req = $request->has('emi_date_req') && $request->has('emi_date_req') ? $request->get('emi_date_req') : Carbon::now()->startOfMonth()->addDays(4)->toDateString();

        $EMIPaymentData = $loan_management->getPaymentDueHistory($id,"","",0,1, array(), 0, 1);
        $data['payments'] = $EMIPaymentData;
        $data['lenders'] = Lenders::all();
        $data['lender_id_req'] = $loan_management->lender_id_req;
        $data['emi_date_req'] = $loan_management->emi_date_req;
        $response = [];
        $newPayments = [];
        $values = [];
        $removeFromList_application_id =[];
        foreach ($data['payments'] as $application_id => $payment) {

            $is_emi_pending = true;
            foreach ($payment['payment'] as $emi_date => $item) {
                    if (isset($item['payment_history'])) {
                        $paymentHistory = $item;
                        if (isset($item['payment_history']['transaction'])) {
                            $paymentHistory['transaction'] = $item['payment_history']['transaction'];
                        }
                    } else {
                        $paymentHistory = $item;
                    }

                    $emi_due = $payment['amount_pending'] ?? 0;
                    $processing_due = $payment['processing_fee_due'] ?? 0;
                    $advance_due = $payment['advance_amount_due'] ?? 0;
                    $total_dues = $emi_due + $processing_due + $advance_due;

                    if ($emi_due == 0 && $is_emi_pending){
                        $removeFromList_application_id = $application_id;
                    }else{
                        $is_emi_pending = false;
                        $removeFromList_application_id = null;
                    }

                    $response[$application_id][$emi_date] = $paymentHistory;
//                    $remaining_amount = $this->getApplicationDueAmount($item->application_id);
                    $newPayments[$application_id] = ['name' => $payment['applicant_name'], 'amount_due' => $payment['amount_due'], 'remaining_amount' => $total_dues, 'max_payable' => $payment['max_payable'], 'over_payment' => $payment['over_payment'], 'adhoc_transaction' => $payment['adhoc_transaction'], 'waived_off_data' => isset($payment['waived_off_data']) ? $payment['waived_off_data'] : [],'amount_paid' =>  $payment['amount_paid'],'emi_due' =>  $payment['emi_due'],'emi_paid' =>  $payment['emi_paid'],'amount_pending' =>  $payment['amount_pending'],'last_emi_date' => $payment['last_emi_date'],'agreement_no' => $payment['loan_agreement_no'], 'is_emi_due' => $emi_due];
                }

                if($removeFromList_application_id){
                    //unset($newPayments[$removeFromList_application_id]);
                    //unset($response[$removeFromList_application_id]);
                }
        }



        if (empty($response)){
            $data['application_id'] = 0;
            return view('admin.accounting.closedloans', $data);

        }

        foreach ($response as $id_index=>$item){

            $reportClose = ReportCloseLoan::where('application_id',$id_index)->first();

            $values[] = [
                'id' => $id_index,
                'name' => $newPayments[$id_index]['name'],
                'amount_due' => $newPayments[$id_index]['amount_due'],
                'remaining_amount' => $newPayments[$id_index]['remaining_amount'],
                'max_payable' => $newPayments[$id_index]['max_payable'],
                'over_payment' => $newPayments[$id_index]['over_payment'],
                'adhoc_transaction' => $newPayments[$id_index]['adhoc_transaction'],
                'payment' => $item,
                'waived_off_data' => $newPayments[$id_index]['waived_off_data'],
                'agreement_no' => $newPayments[$id_index]['agreement_no'],
                'amount_paid' => $newPayments[$id_index]['amount_paid'],
                'emi_due' => $newPayments[$id_index]['emi_due'],
                'emi_paid' => $newPayments[$id_index]['emi_paid'],
                'amount_pending' => $newPayments[$id_index]['amount_pending'],
                'last_emi_date' => $newPayments[$id_index]['last_emi_date'],
                'is_reported' => isset($reportClose->id) ? $reportClose->comment : 0
            ];
        }

        $data['payments'] = $values;
        $data['paginationTotal'] = $loan_management->isPaginationTotal;
        $data['paginationLastPage'] = $loan_management->isPaginationLastPage;
        $data['application_id'] = $id;

        if($request->has('raw')){
            return $data;
        }
        if($request->input('exportData')){
            $usid = $request->input('user_id');
            if(count($values)) {
                $header[] = ['ID','Agreement Number', 'Name', 'Amount Due','Amount OverPaid','Max Payable','Emi Due','Total Due Amount','EMI Paid','Total Paid','Last EMI Date'];
                foreach ($values as $key => $exportPayment) {
                    $exportData[] = [
                        'id' => $exportPayment['id'],
                        'agreement_number' => $exportPayment['agreement_no'],
                        'name' => $exportPayment['name'],
                        'amount_due' => $exportPayment['amount_due'],
                        'amount_overpaid' => $exportPayment['over_payment'],
                        'max_payable' => $exportPayment['max_payable'],
                        'emi_due' => $exportPayment['emi_due'],
                        'total_due_amount' => $exportPayment['amount_pending'],
                        'emi_paid' => $exportPayment['emi_paid'],
                        'total_paid' => $exportPayment['amount_paid'],
                        'last_emi_date' => $exportPayment['last_emi_date']
                    ];
                }
                $request = new Request(['data' => array_merge($header, $exportData), 'sheet' => 'Sheet1']);
                $file = 'Closed Loans Data_'. time() . '.xls';
                Excel::store(new Exporter($request), $file);
                Storage::disk('s3')->put('/collection/'.$file, file_get_contents(storage_path() . '/app/' . $file));
                event(new EventSendDbBackupEmail('excel-mail',['usrid'=>$usid,'exf'=>$file]));
                unlink(storage_path() . '/app/' . $file);
            }else{
                $information['exportStatus'] = "error";
                $information['exportMsg'] = "Nothing to export!!!!";
                return response()->json($information);
            }

            $information['exportStatus'] = "success";
            $information['exportMsg'] = "Excel file will sent to your mail shortly";
            return response()->json($information);
        }

        return view('admin.accounting.closedloans', $data);
    }

    public function exportClosedLoanExcel($requestId,$file){
        try{
            $UsermailID = User::where('id',$requestId)->whereNull('deleted_at')->first(['email']);

            $s3 = Storage::disk('s3');

            if ($s3->exists('/collection/'.$file)) {
                $doc = $s3->get('/collection/'.$file);
                $mail_ids = _env('APP_CONNECTION') ? [$UsermailID->email] : ['himanshubamania@creditfair.in', 'pratik@creditfair.in', 'suyog@creditfair.in'];
                Mail::send('emails.reminders.basic_reminder',
                    ['body' => 'Please find the below file enclosed as per your request for closed loans']
                    , function ($message) use ($file, $mail_ids,$doc) {
                        $message->to($mail_ids)->subject('Requested Closed Loan Data');
                        $message->attachData($doc, $file);
                    });


                $information['exportStatus'] = "success";
                $information['exportMsg'] = "Excel file will sent to your mail shortly";
                return response()->json($information);
            }
        }catch(Exception $e){
            $information['exportStatus'] = "error";
            $information['exportMsg'] = "Failed to sent excel file";
            return response()->json($information);
        }
    }

    public function isPrePayment(Request $request){
        return $request->has('is_pre_part_payment') ? $request->get('is_pre_part_payment') : 0;
    }

    public function addPayments($id, Request $request){

        $data['users'] = User::where('user_type', '>=', 5)->get(['id','name']);
        $data['application'] = ConsumerApplication::with('application_element','lender.banks')->where('id',$id)->first();
        $rps_log = RPS_Logs::where('application_id', $id)->where('bpi_interest','>',0)->first(['bpi_interest']);
        $disbCtrl = (new DisbursementController(new Request()));
        $legal_charges = $disbCtrl->getLegalChargesAmount($data['application']) + $disbCtrl->getCersaiHypothecationCharge($data['application']);


        //$EMIPayment = (new PaymentEmi())->getPaymentDueHistory($id);
        $EMIPayment = (new LoanManagement())->getPaymentDueHistory($id);

        if (isset($EMIPayment[$id])){
            $EMIPayment = $EMIPayment[$id];
        }
        $data['amount_due'] = $EMIPayment['amount_due'] ?? 0;
        $data['max_payable'] = $EMIPayment['max_payable'] ?? 0;
        $data['amount_pending'] = $EMIPayment['amount_pending'] ?? 0;
        $data['over_payment'] = $EMIPayment['over_payment'] ?? 0;
        $data['processing_fee_due'] = $EMIPayment['processing_fee_due'] ?? 0;
        $data['insurance_fee_due'] = $EMIPayment['insurance_fee_due'] ?? 0;
        $data['advance_amount_due'] = $EMIPayment['advance_amount_due'] ?? 0;
        $data['pre_emi_received'] = $EMIPayment['pre_emi_received'] ?? 0;
        $data['pre_emi_amount'] = $rps_log != null && $rps_log->bpi_interest > 0 ? $rps_log->bpi_interest : 0;
        $data['legal_charges'] = $legal_charges;
        $data['emi_amount'] = $EMIPayment['emi_amount'] ?? 0;
        $emi_payment_amount = EmiPayment::where('application_id', $id)->where('payment_status', 'pending')->orderBy('emi_date', 'asc')->first(['emi_amount']);
        $data['current_emi_amount'] = $emi_payment_amount->emi_amount ?? 0;

        $data['application_id'] = $id;
        return view('admin.accounting.editPayment', $data);
    }

    public function rejectPaymentScene(Request $request){
        $status = 'FAIL';
        $message = 'Something went wrong';
        $checker_id = isset(Auth::user()->id) ? Auth::user()->id : 0;

        if ($request->has('id')){
            try {

                $payment = PaymentMakerChecker::where('id', $request->get('id'))->first();
                PaymentMakerChecker::where('id', $request->get('id'))->update(['checker_id' => $checker_id, 'updated_at'=> Carbon::now()->toDateTimeString()]);
                $this->PTPDelete($payment);
                $payment = PaymentMakerChecker::where('id', $request->get('id'))->delete();



                if ($payment) {
                    $status = 'OK';
                    $message = 'Successfully rejected the payment';
                    (new Slack(new Request(['title' => 'Payment entry rejected', 'fields' => ['ID' => $request->get('id'),'rejected_by' => Auth::user()->name],'group' => Slack::$PAYMENT_RECONCILIATION])))->send();
                }
            }catch (\Exception $e){
                $message = $e->getTraceAsString();
            }
        }

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

    public function PTPDelete($payment){
        $data = json_decode($payment->data, 1);
        if (isset($data['ptp_id'])) {
            PromiseToPay::where('id', $data['ptp_id'])->update(['payment_received' => 0, 'payment_received_date' => '']);
        }
    }

    public function syncHomeVilleRPS(Request $request){
        $repaymentController = new RepaymentController();
        $response = $repaymentController->fetchHomeVilleRPS($request->get('application_id'));
        return response()->json($response ? $response : ['status' => 'FAIL', 'message' => 'Failed to get the data'], 200);
    }

    public function verifyPaymentScene(Request $request){
        $status = 'FAIL';
        $message = 'Something went wrong';
        if ($request->has('id')){
            $payment = PaymentMakerChecker::where('id', $request->get('id'))->first();
            try {
                $data = json_decode($payment->data, 1);
                $message = 'Successfully reconcile the payment';
                if (isset($data['trasanction_id']) && $data['trasanction_id']){
                    $PaymentTransaction = PaymentTransaction::where('trasanction_id', $data['trasanction_id'])->whereNull('deleted_by')->first(['id']);
                    if (isset($PaymentTransaction->id) && $PaymentTransaction->id){
                        $message .= '. Transaction ID has been used earlier.';
                    }
                }

                unset($data['go_maker_check']);
                if($request->get('type') == 'payment_waive_off'){
                    $data = array_merge($data, ['no_maker_checker' => true]);
                    $this->updateWaiveOff(new Request($data));
                }else{
                    if(isset($data['is_pre_part_payment']) && $data['is_pre_part_payment']){
                        (new RepaymentController())->checkIfRPSExists($payment->application_id);
                        $response = $this->process_pre_payment($payment->application_id, $data);
                        $message = $response ? ($response->getData()->message ?? 'Successfully updated') : 'Something went wrong';
                        if ($response && isset($response->getData()->status) && $response->getData()->status == 'FAIL') {
                            return response()->json(['status' => 'FAIL', 'message' => $message]);
                        }else if($message == 'Something went wrong' || strpos($message, 'Error') !== false){
                            $status = 'FAIL';
                            return response()->json(['status' => 'FAIL', 'message' => $message]);
                        }
                    }else {
                        $res = (new LoanManagement())->paymentReconcile($data);
                    }
                }
                $status = 'OK';

                // if (isset($res) && isset($res['status']) && isset($res['message']) && $res['status'] == "FAILED") {
                //     return response()->json(['status' => $res['status'], 'message' => $res['message']]);
                // }
                PaymentMakerChecker::reconcile($request->get('id'), ['status' => 0,'checker_id' => Auth::user()->id,'verify_date' => Carbon::now()->toDateTimeString()]);
            }catch (\Exception $e){
                $message = $e->getTraceAsString();
            }
        }

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

    public function saveReceiptAck($receipt_ack, $id, $payment_date, $amount, $_fileName){

        $s3 = Storage::disk('s3');

        $originalName = $receipt_ack->getClientOriginalName();
        $extension = $receipt_ack->getClientOriginalExtension();

        $filename = pathinfo($originalName, PATHINFO_FILENAME) . '_' . time() . '.' . $extension;

        $filename = $_fileName.'_'.str_replace(' ', '_', $filename);

        $file_path = '/'.$id.'/'.$payment_date."/{$filename}";

        $s3->put($file_path, file_get_contents($receipt_ack), [
            'ContentType' => $receipt_ack->getMimeType()
        ]);

        return $file_path;





        $s3 = Storage::disk('s3');
            $extension = $receipt_ack->getClientOriginalExtension();
            $file_path = '/'.$id.'/'.$payment_date.'/'.$fileName.$amount.".".$extension;
            $s3->put($file_path, $receipt_ack);
            $files = $s3->listContents($file_path);
            return $files[0]['path'];
    }

    public function process_pre_payment($application_id, $paymentData){
        if (!empty($paymentData['trasanction_acknowledgement'])) {
            return $this->process_pre_payment_rps_file($application_id, $paymentData);
        }else{
            return $this->getPrePaymentRevisedRPS(new Request(array_merge($paymentData,
                [
                    'type' => $paymentData['pre_part_payment_type'] == 1 ? 'emi': 'tenure',
                    'is_preview_flag' => false,
                    'user_id' => Auth::check() ? Auth::user()->id : 107
                ]
            )));
        }
    }

    public function process_pre_payment_rps_file($application_id, $paymentData){
        ini_set('max_execution_time', -1);
        set_time_limit(0);
        ini_set('memory_limit', '-1');

        $fileNameList = explode("/", $paymentData['trasanction_acknowledgement']);
        $fileName = $fileNameList[count($fileNameList) - 1];
        $tempPath = storage_path('app/'.$fileName);
        file_put_contents($tempPath, Storage::disk('s3')->get($paymentData['trasanction_acknowledgement']));

        $curl = curl_init();

        $fileFields = [];

        /*if(!isset($_FILES['pre_payment_file']['tmp_name']) || !$_FILES['pre_payment_file']['tmp_name']){
            \Session::flash('error', 'Please upload RPS File');
            return \redirect()->back();
        }

        $tmpName = $_FILES['pre_payment_file']['tmp_name'];
        $name = $_FILES['pre_payment_file']['name'];
        $type = mime_content_type($tmpName);

        $fileFields["file"] = new \CURLFile($tmpName, $type, $name);*/

        $fileFields["file"] = new \CURLFile($tempPath,'application/vnd.ms-excel',$fileName);

        $fileFields['user_id'] = Auth::check() ? Auth::user()->id : 107;

        $application = ConsumerApplication::where('id', $application_id)->first(['id', 'name']);
        $cf_transaction_id = $application_id.strtoupper(substr($application->name, 0, 2)).time();

        $payment_date = $paymentData['payment_date'];


        $fileFields = array_merge($fileFields, [
            'amount' => $paymentData['amount'],
            'mode' => $paymentData['mode'],
            'paid_by' => $paymentData['paid_by'],
            'payment_reconciliation_date' => $paymentData['payment_reconciliation_date'] ?? $payment_date,
            'umrn' => $paymentData['umrn'] ?? '',
            'collected_by' => $paymentData['collected_by'],
            'collected_by_type' => $paymentData['collected_by_type'] ?? 1,
            'adjust_with_disbursement' => $paymentData['adjust_with_disbursement'] ?? 0,
            'online_payment_id' => $paymentData['online_payment_id'],
            'wallet_name' => $paymentData['wallet_name'],
            'reason' => $paymentData['reason'] ?? '',
            'trasanction_id' => $paymentData['trasanction_id'],
            'trasanction_acknowledgement' => $paymentData['trasanction_acknowledgement'],
            'application_id' => $paymentData['application_id'],
            'payment_for' => $paymentData['payment_type'] ?? "credit",
            'payment_date' => Carbon::parse($payment_date)->format('Y-m-d'),
            'cf_transaction_id' => $cf_transaction_id,
            'bank_id' => $paymentData['bank_id'] ?? "",
            'status' => $paymentData['status'] ?? 'success',
        ]);



        curl_setopt_array($curl, array(
            CURLOPT_URL => _env('PY_SCRIPT_SERVER_HOST').'/api/pre_part_payment',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $fileFields
        ));

        $error_msg = '';
        $response = curl_exec($curl);
        if (curl_error($curl)) {
            $error_msg = curl_error($curl);
        }
        curl_close($curl);

        $responseString = json_encode($response);

        $cwFactory = new CloudWatchLoggerFactory();
        $_data = array(
            'exception' => 'PrePart Payment upload',
            'error' => $error_msg,
            'fields' => $fileFields,
            'response' => $responseString
        );
        $cwFactory->logger(json_encode($_data));

        if($error_msg){
            return $error_msg. $responseString;
        }

        $responseData = json_decode($response);

        if(isset($responseData->message) && $responseData->message == 'RPS updated for application_id: '.$application_id){
            $this->updatePaymentAttribute($application_id, $responseData);
            //(new LoanManagement())->sendPaymentMessage($application_id, $paymentData, 'success', strtolower($paymentData['payment_type']));
            return 'Processed '.$responseData->message;
        }

        return 'Error found '.$responseString;
    }

    public function updatePaymentAttribute($application_id, $response){

        ConsumerApplicationElement::where('application_id', $application_id)->update([
            'amount_over_due' => $response->amount_over_due ?? 0,
            'total_amount_due' => $response->total_amount_due ?? 0,
            'last_emi_date' => $response->last_emi_date ?? '',
            'emi_paid' => $response->emi_paid ?? 0,
            'emi_pending' => $response->remaining_emi ?? 0,
            'principal_due' => $response->principal_due ?? 0,
            'total_principal_due' => $response->total_principal_due ?? 0
        ]);
    }

    public function validateSettlementEntry(Request $request) {
        $application_id = $request->get('paid_by_value');
        $secondary_status = DB::selectOne("select secondary_status from consumer_application where id = ?", [$application_id]);
        $apiData = [
            'payment_type' => $request->get('payment'),
            'mode' => $request->get('payment_mode'),
            'paid_by' => ($request->has('pay_by_type') && $request->get('pay_by_type') == 2) ? $request->get('paid_by_other') : '',
            'application_id' => $application_id,
            'collected_by' => $request->get('collected_by_value'),
            'collected_by_type' => $request->get('collected_by_merchant'),
            'adjust_with_disbursement' => $request->get('adjust_with_disbursement') == 'on' ? 1 : 0,
            'trasanction_id' => $request->get('transaction_id'),
            'go_maker_check' => true,
            'bank_id' => $request->get('bank_id'),
            'wallet_name' => $request->has('wallet_name') ? (!empty($request->get('wallet_name')) && !is_null($request->get('wallet_name')) ? $request->get('wallet_name') : '') : '',
            'payment_date' => $request->get('payment_date'),
            'payment_reconciliation_date' => $request->get('payment_reconciliation_date'),
            'fore_closure_date' => $request->get('foreclosure_date'),
            'amount' => $request->get('amount_collected'),
            'advance_amount' => 0,
            'trasanction_acknowledgement' => null,
            'online_payment_id' => '',
            'is_pre_part_payment' => $request->has('is_pre_part_payment') ? $request->get('is_pre_part_payment') : 0,
            'pre_part_payment_type' => $request->has('pre_part_payment_type') ? $request->get('pre_part_payment_type') : 0,
            'is_verify' => 0,
            'secondary_status' => $secondary_status->secondary_status,
        ];
        $validationResponse = (new RepaymentController())->callReconcileApi($application_id, $apiData);
        if (isset($validationResponse['status'])) {
            return \response()->json(['message' => $validationResponse['message'], 'status' => 'OK'],200);
        }
        return \response()->json(['message' => null, 'status' => 'OK'],200);
    }

    public function addPayment(Request $request){

        $secondaryStatus = DB::selectOne("SELECT secondary_status FROM consumer_application WHERE id = ".$request->get('paid_by_value'));
        if (!empty($secondaryStatus) && in_array($secondaryStatus->secondary_status, ['settled', 'settlement-done', 'settlement-in-progress']) && $request->get('payment') != 'settlement_payment' && $request->get('payment') != 'processing_fee') {
            \Session::flash('error', 'Application settlement under progress, cannot add EMI, foreclosure, Collection charges entry.');
            return \redirect()->to('/admin/payment/start_v1/'.$request->get('paid_by_value'));
        }

        if ($request->has('payment') && $request->get('payment') == 'settlement_payment') {
            if (empty($secondaryStatus->secondary_status) || $secondaryStatus->secondary_status != 'settlement-in-progress') {
                \Session::flash('error', 'Please move the secondary status to settlement-in-progress before adding settlement payment.');
                return \redirect()->to('/admin/payment/add/'.$request->get('paid_by_value'));
            }
            if ($request->has('transaction_id')) {
                $paymentTxn = PaymentTransaction::where('application_id', $request->get('paid_by_value'))->where('trasanction_id', $request->get('trasanction_id'))->whereNull('deleted_at')->get();
                if (count($paymentTxn) >= 1) {
                    \Session::flash('error', 'Payment with same transaction ID already present');
                    return \redirect()->to('/admin/payment/add/'.$request->get('paid_by_value'));
                }
            }
            if ($request->has('payment_date') && !empty($request->get('payment_date'))) {
                $settlementAction = CollectionAction::where('application_id', $request->get('paid_by_value'))
                    ->where('dispo_code', 'Settlement')->whereNull('deleted_at')->orderBy('created_at', 'desc')->first();

                if ($settlementAction && !empty($settlementAction->ptp_date)) {
                    try {
                        $paymentDate = Carbon::parse($request->get('payment_date'))->startOfDay();
                    } catch (\Exception $e) {
                        $paymentDate = null;
                    }

                    if ($paymentDate && $paymentDate->gt($settlementAction->ptp_date)) {
                        \Session::flash('error', 'Payment date must be before the installment date ('.$settlementAction->ptp_date->format('d-m-Y').').');
                        return \redirect()->to('/admin/payment/add/'.$request->get('paid_by_value'));
                    }
                }
            }
        }

        if(!$request->has('pre_part_payment_type') && $this->isPrePayment($request)){
            $prePayment = new PrePaymentController();
            $prePayment->application_id = $request->get('paid_by_value');
            $isError = $prePayment->beforeFileProcessing($request);
            if($isError){
                \Session::flash('error', $isError);
                return \redirect()->to('/admin/payment/start_v1/'.$request->get('paid_by_value'));
            }
        }

        $file_path = '';
        if($request->hasFile('receipt_ack')) {
            $file_path = $this->saveReceiptAck($request->file('receipt_ack'), $request->get('paid_by_value'), $request->get('payment_date'), $request->get('amount_collected'),'_emi_receipt_ack_'.time());
        }
        $advance_amount = 0;
        $amount = $request->get('amount_collected');
        if($request->has('redirect_link') && !empty($request->get('redirect_link'))){
            $amount = $request->has('amount_due') ? $request->get('amount_due') : 0;
            if($request->has('only_restructure') && ($request->get('only_restructure') == 1)){
                $advance_amount = $request->get('amount_collected');
                $amount = 0;
            }elseif($request->get('amount_collected') > $amount){
                $advance_amount = $request->get('amount_collected') - $amount;
            }
        }


        if(!empty($request->get('foreclosure_date'))){
            $amount = $request->get('amount_collected');
            $advance_amount = 0;
        }

        $paymentMakerCheckerId = (new LoanManagement())->paymentReconcile([
        //    (new PaymentEmi())->updateEmiPayment([
            'payment_type' => $request->get('payment'),
            'mode' => $request->get('payment_mode'),
            'paid_by' => ($request->has('pay_by_type') && $request->get('pay_by_type') == 2) ? $request->get('paid_by_other') : '',
            'application_id' => $request->get('paid_by_value'),
            'collected_by' => $request->get('collected_by_value'),
            'collected_by_type' => $request->get('collected_by_merchant'),
            'adjust_with_disbursement' => $request->get('adjust_with_disbursement') == 'on' ? 1 : 0,
            'trasanction_id' => $request->get('transaction_id'),
            'go_maker_check' => true,
            'bank_id' => $request->get('bank_id'),
            'wallet_name' => $request->has('wallet_name') ? (!empty($request->get('wallet_name')) && !is_null($request->get('wallet_name')) ? $request->get('wallet_name') : '') : '',
            'payment_date' => $request->get('payment_date'),
            'payment_reconciliation_date' => $request->get('payment_reconciliation_date'),
            'fore_closure_date' => $request->get('foreclosure_date'),
            'amount' => $amount,
            'advance_amount' => $advance_amount,
            'trasanction_acknowledgement' => $file_path,
            'online_payment_id' => '',
            'is_pre_part_payment' => $request->has('is_pre_part_payment') ? $request->get('is_pre_part_payment') : 0,
            'pre_part_payment_type' => $request->has('pre_part_payment_type') ? $request->get('pre_part_payment_type') : 0,
            'is_verify' => 1 // flag 1 means settlement entry will be created
        ]);

        if($request->has('redirect_link') && !empty($request->get('redirect_link'))){
            return \redirect()->to($request->get('redirect_link'));
        }

        $this->updatePaymentToAvanse($request, $amount, $paymentMakerCheckerId);


        \Session::flash('success', 'Payment added successfully');
        return \redirect()->to('/admin/payment/start_v1/'.$request->get('paid_by_value'));
    }

    public function addPaymentThroughExcel(Request  $request){
        try {
            if ($request->has('payment_file')) {

                if($request->files->get('payment_file') != null) {
                    if(filesize($request->files->get('payment_file')) > 18874368){
                    Session::flash('error', 'Uploaded file is too large');
                    return redirect()->back();
                    }
                }

            }

            $file_path = $this->saveReceiptAck($request->file('payment_file'), 'payments', $request->get('emi_date'), '', '_payment_processed_manual_'.rand(999, 9999));
            $name = $request->get('emi_date').'_'.time().'_payment_processed_manual.'.$request->file('payment_file')->getClientOriginalExtension();
            $file_path_local = storage_path('cron_payments');
            $file = $request->file('payment_file');
            $file->move($file_path_local, $name);
            $data = $request->all();
            $data['file_path'] = $file_path;
            $data['file_name'] = $name;
            $data['user_id'] = Auth::user()->id;
            $jobs = new CampaignsJobProvider();
            $jobs->from = 'payment_file_manual';
            $jobs->payload = json_encode($data);
            $jobs->available_at = Carbon::now()->toDateTimeString();
            $jobs->application_id = 181;
            $jobs->created_at = Carbon::now()->toDateTimeString();
            $jobs->is_available = 0;
            $jobs->save();

            if (!file_exists(storage_path().'/cron_payments/'.$name)) {
                mkdir(storage_path().'/cron_payments/'.$name, 0777, true);
            }

            \Session::flash('success', 'You we\'ll notify you once all the payments are avaliable to verify');
            return redirect()->back();
        }catch (\Exception $e){
            \Session::flash('error', 'Something went wrong, '.$e->getFile().$e->getLine());
            return redirect()->back();
        }
    }

    public function editPayment($id, Request $request){
        $data['users'] = User::where('user_type','>=',5)->get(['id','name']);
        $data['payment'] = PaymentTransaction::find($id);
        return view('admin.accounting.editPayment', $data);
    }

    public function checkDuplicacy($id, Request  $request){
        $PaymentTransaction = PaymentTransaction::where('trasanction_id', $request->get('transaction_id'))->whereNull('deleted_by')->first(['id']);
        return \response()->json(['payment_id'=> $PaymentTransaction->id ?? 0, 'message' => 'ID has been used earlier. Do you want proceed?', 'status' => 'OK'],200);
    }

    public function importPTPFile(Request $request){
        // Start a query builder instance
        $query = CollectionAction::latest();

        // Check if the user has entered an Application ID
        if ($request->has('search_app_id') && !empty($request->search_app_id)) {
            $query->where('application_id', 'like', "%{$request->search_app_id}%");
        }

        if ($request->filled('search_action_date')) {
            $query->whereDate('action_date', $request->search_action_date);
        }

        // Paginate results and preserve the search query in pagination links
        $collectionActions = $query->paginate(20)->appends($request->all());

        return view('admin.accounting.ptpData', compact('collectionActions'));
    }

    public function processPTPFile(Request $request){

        $file = $request->file('ptp_file');
        $userId = Auth::user() ? Auth::user()->id : '!Session';
        $url = rtrim(_env('PY_SCRIPT_SERVER_HOST'), '/') . '/api/process-ptp-excel';

        try {
            if ($request->has('ptp_file') && $request->file('ptp_file') != null) {
                if(filesize($request->file('ptp_file')) > 18874368){
                    Session::flash('error', 'Uploaded file is too large');
                    return redirect()->back();
                }
            } else {
                Session::flash('error', 'Please select a file');
                return redirect()->back();
            }

            ### S3 saving logic  

            // $extension = $file->getClientOriginalExtension();
            // $rawUserName = (Auth::user()) ? Auth::user()->name : '!Session';
            // $cleanUserName = preg_replace('/[^A-Za-z0-9\-]/', '', $rawUserName);
            // $fileName = $cleanUserName . '_' . time() . '.' . $extension;

            // $s3Folder = 'Collection PTP Data/' . date('Y') . '/' . strtolower(date('M')); 
            // $s3FilePath = $s3Folder . '/' . $fileName;
            
            // $s3 = Storage::disk('s3');
            // $s3->put($s3FilePath, file_get_contents($file));

            $client = new Client();

            $response = $client->request('POST', $url, [
                'timeout' => 120, 
                'multipart' => [
                    [
                        'name'     => 'file',
                        'contents' => fopen($file->getRealPath(), 'r'),
                        'filename' => $file->getClientOriginalName()
                    ],
                    [
                        'name'     => 'user_id',
                        'contents' => $userId
                    ]
                ]
            ]);

            if ($response->getStatusCode() >= 200 && $response->getStatusCode() < 300) {
                return redirect()->back()->with('success', 'File uploaded and processed successfully.');
            } else {
                return redirect()->back()->with('error', 'Processing Failed with status: ' . $response->getStatusCode());
            }

        }catch (RequestException $e) {
            $genericError = 'Something went wrong while processing the file. Please try again.';

            if ($e->hasResponse()) {
                $responseBody = (string) $e->getResponse()->getBody();
                $decoded = json_decode($responseBody, true);
                if (json_last_error() === JSON_ERROR_NONE && isset($decoded['detail']) && is_array($decoded['detail'])) {
                    return redirect()->back()->with('validation_errors', $decoded['detail']);
                }

                if (json_last_error() === JSON_ERROR_NONE && isset($decoded['message'])) {
                    return redirect()->back()->with('error', $decoded['message']);
                }

                return redirect()->back()->with('error', $responseBody);
            }
            return redirect()->back()->with('error', $genericError);
        }

        catch (\Exception $e) {
            return redirect()->back()->with('error', 'System Error: ' . $e->getMessage());
        }
    }

    public function updateBatch(Request $request)
    {
        $data = $request->input('data');
        
        foreach ($data as $row) {
            $action = CollectionAction::find($row['id']);
            if ($action) {
                $action->update([
                    'user_id' => $row['user_id'],
                    'action_date' => $row['action_date'],
                    'next_action_date' => $row['next_action_date'], 
                    'ptp_date' => $row['ptp_date'],
                    'dispo_code' => $row['dispo_code'],
                    'actual_amount_to_be_collected' => $row['actual_amount_to_be_collected'],
                    'remarks' => $row['remarks'],
                ]);
            }
        }
        
        return response()->json(['success' => true]);
    }

    public function importPaymentFile(){
        return view('admin.accounting.importPayment');
    }

    public function startPaymentFile(Request $request){
        try {
            if ($request->has('payment_file')) {

                if($request->files->get('payment_file') != null) {
                    if(filesize($request->files->get('payment_file')) >18874368){
                    Session::flash('error', 'Uploaded file is too large');
                    return redirect()->back();
                    }
                }

            }

            $file_path = $this->saveReceiptAck($request->file('payment_file'), 'payments', $request->get('emi_date'), '', 'payment_processed_'.rand(999, 9999));
            $name = $request->get('emi_date').'_'.time().'_payment_processed.'.$request->file('payment_file')->getClientOriginalExtension();
            $file_path_local = storage_path('cron_payments');
            $file = $request->file('payment_file');
            $file->move($file_path_local, $name);
            $data = $request->all();
            $data['file_path'] = $file_path;
            $data['file_name'] = $name;
            $jobs = new CampaignsJobProvider();
            $jobs->from = 'payment_file_nach';
            $jobs->payload = json_encode($data);
            $jobs->available_at = Carbon::now()->toDateTimeString();
            $jobs->application_id = 181;
            $jobs->created_at = Carbon::now()->toDateTimeString();
            $jobs->is_available = 0;
            $jobs->save();

            if (!file_exists(storage_path().'/cron_payments/'.$name)) {
                mkdir(storage_path().'/cron_payments/'.$name, 0777, true);
            }

            \Session::flash('success', 'You we\'ll notify you once all the payments are processed');
            return redirect()->back();
        }catch (\Exception $e){
            \Session::flash('error', 'Something went wrong, '.$e->getFile().$e->getLine());
            return redirect()->back();
        }
    }

    public function startPaymentFileProcess(Request $request){
        try {
            $request->attributes->add(['file_path' => $request->get('file_path')]);

            //$file_path = storage_path('cron_payments/'.$request->get('file_name'));

           /* $s3 = Storage::disk('s3');
            $fileData = $s3->get($request->get('file_path'));*/

            /*if (file_exists($file_path)) {
                chmod($file_path, 0777);
            }*/

            /*$file_path = storage_path(time().'.'.explode('.',$request->get('file_name'))[1]);
            $file = fopen($file_path, "w");
            fwrite($file, $fileData);
            fclose($file);


            $finfo = new \finfo(FILEINFO_MIME_TYPE);

            $file = new UploadedFile(
                $file_path,
                $request->get('file_name'),
                $finfo->file($file_path),
                filesize($file_path),
                0,
                false
            );*/
            Excel::import(new BulkPaymentFile($request), $request->get('file_path'), 's3');


            $jobs = new CampaignsJobProvider();
            $jobs->from = 'payment_file_nach_process';
            $jobs->payload = json_encode($request->input());
            $jobs->available_at = Carbon::now()->toDateTimeString();
            $jobs->application_id = 181;
            $jobs->created_at = Carbon::now()->toDateTimeString();
            $jobs->is_available = 0;
            $jobs->save();

        }catch (\Exception $e){
            (new Slack(new Request(['title' => 'Payment Can\'t be processed', 'fields' => ['message' => $e->getMessage(), 'line' => $e->getLine(),'file' => $e->getFile()], 'group' => 'payment_collection'])))->send();
        }

    }

    public function startManualPaymentFileProcess(Request $request){
        try{
            $request->attributes->add(['file_path' => $request->get('file_path')]);

            Excel::import(new BulkManualPaymentFile($request), $request->get('file_path'), 's3');

        }catch (\Exception $e){
            (new Slack(new Request(['title' => 'Payment Can\'t be processed', 'fields' => ['message' => $e->getMessage(), 'line' => $e->getLine(),'file' => $e->getFile()], 'group' => 'payment_collection'])))->send();
        }
    }

    public function importMoratoriumFile(){
        return view('admin.accounting.importMoratorium');
    }

    public function startMoratoriumFile(Request $request){
        if ($request->has('moratorium_file')) {

            if($request->files->get('moratorium_file') != null) {
                if(filesize($request->files->get('moratorium_file')) >18874368){
                Session::flash('error', 'Uploaded file is too large');
                return redirect()->back();
                }
            }

        }
        Excel::import(new MoratoriumImport(new Request(['from' => __FUNCTION__])), $request->file('moratorium_file'));
        return redirect()->back();
    }

    public function createCommunicationJob(Request $request, $jobId){
        $payload = $request->input();
        $payload['job_id'] = $jobId;
        $jobs = new CampaignsJobProvider();
        $jobs->from = 'payment_file_communication_process';
        $jobs->payload = json_encode($payload);
        $jobs->available_at = Carbon::now()->toDateTimeString();
        $jobs->application_id = 181;
        $jobs->created_at = Carbon::now()->toDateTimeString();
        $jobs->is_available = 0;
        $jobs->save();
    }

    public function startPaymentCommunication(){
        $payments = BulkPayments::where('communication', 0)->where('created_at', '>=', Carbon::now()->subDays(5)->toDateTimeString())->whereNotNull('communication_data')->limit(50)->get();

        $data = [];
        $ids = [];

        if(count($payments)) {
            foreach ($payments as $item) {
                $payload = json_decode($item->communication_data, 1);
                if($payload) {
                    $data[] = ['item' => $payload['communicationData'], 'bulk_payment_id' => $item->id];
                    //$ids[] = $item->id;
                }
                $ids[] = $item->id;
            }

            BulkPayments::whereIn('id', $ids)->update(['communication' => 1]);
            $loanManagement = new LoanManagement();
            foreach ($data as $dataItem) {
                try {
                    $loanManagement->sendPaymentMessage($dataItem['item']['application_id'], $dataItem['item']['data'], $dataItem['item']['payment_status'], $dataItem['item']['payment_type']);
                }catch (\Exception $e){

                }
            }
        }
    }

    public function startPaymentFileProcessing(Request $request){
        $payments = BulkPayments::where('is_available', 0)->where('created_at', '>=', Carbon::now()->subDays(5)->toDateTimeString())->limit(500)->get();

        $data = [];
        $ids = [];

        foreach ($payments as $item){
            $payload = json_decode($item->payload);
            $data[] = ['item' => $payload->item, 'bulk_payment_id' => $item->id];
            $ids[] = $item->id;
        }

        BulkPayments::whereIn('id',$ids)->update(['is_available' => 1]);
        if($request->has('transaction_type')) {
            $paymentFile = new LotusPayPaymentFile($request);
            $paymentFile->collection($data);
        }else{
            $paymentFile = new PaymentFile($request);
            $paymentFile->collection($data);
        }
    }

    public function getDueAmount($id){
        $data = ConsumerApplicationElement::where('application_id',$id)->first();
//        $payment = new PaymentEmi();
//        $response = $payment->getPaymentDueHistory($id);
        return \response()->json(['amount'=>isset($data->amount_over_due) ? $data->amount_over_due : 0],200);

    }

    public function sendPaymentLink($id, Request $request){

        $isSMS = 0;
        $isEmail = 0;
        $message = '';
        if($request->has('type') && $request->get('type') > 0){
            if($request->get('type') == 1){
                $isSMS = $isEmail = 1;
            }else if($request->get('type') == 2){
                $isEmail = 1;
            }else if($request->get('type') == 3){
                $isSMS = 1;
            }
        }
        $is_foreclosure  = $request->get('is_foreclosure');
        $is_foreclosure_date  = $request->get('foreclosure_date');

        $payable_amount_for_link = $request->get('payable_amount_for_link');
        $amount_due = $request->get('amount_due');

        try {
            if(($payable_amount_for_link > 0) || ($is_foreclosure == 1)){
                $consumer = ConsumerApplication::with('merchant','lender.bank_details','proFormaInvoice')->where('id',$id)->first();
                if($consumer) {
                    $data['applicant_name'] = $consumer->name;
                    $data['lender_id'] = $consumer->lender->id;
                    $data['id'] = $consumer->id;
                    $data['email'] = $consumer->email;
                    $data['co_applicant_name'] = $consumer->co_applicant_name ?? "";
                    $data['amount'] = $payable_amount_for_link;
                    $data['merchant_name'] = $consumer->merchant->merchant_name ?? '';
                    $data['account_holder'] = $consumer->lender->bank_details->account_holder ?? '';
                    $data['bank'] = $consumer->lender->bank_details->bank_name ?? '';
                    $data['branch'] = $consumer->lender->bank_details->branch_name ?? '';
                    $data['account_number'] = $consumer->lender->bank_details->account_number ?? '';
                    $data['ifsc'] = $consumer->lender->bank_details->ifsc_code ?? '';
                    $loan_application_no = isset($consumer->proFormaInvoice->loan_application_no) && !empty($consumer->proFormaInvoice->loan_application_no) ? $consumer->proFormaInvoice->loan_application_no : '';
                    if ($loan_application_no) {
                        if($data['lender_id'] == AvanseServices::$lender_id) {
                            $data['data']['bank-details'] = [
                                'Beneficiary account number' => '918020009293418',
                                'Beneficiary name' => 'Avanse Financial Services Ltd',
                                'IFSC code' => 'UTIB0000028',
                                'Bank Name' => 'Axis Bank'
                            ];
                        }else if($data['lender_id'] == Lendbox::$lender_id || $data['lender_id'] == LendboxLSP::$lender_id){
                            $data['data']['bank-details'] = [
                                'Beneficiary account number' => '000705047644',
                                'Beneficiary name' => 'Transactree Technologies Private Limited',
                                'IFSC code' => 'ICIC0000007',
                                'Bank Name' => 'ICICI BANK LTD'
                            ];
                        }else if($data['lender_id'] == Services::$lender_id){
                            $data['data']['bank-details'] = [
                                'Beneficiary account number' => '200999509663',
                                'Beneficiary name' => 'Aditya Birla Finance LTD',
                                'IFSC code' => 'INDB0000001',
                                'Bank Name' => 'INDUSIND BANK LTD'
                            ];
                        }else if($data['lender_id'] == KMGP2P::$lender_id){
                            $data['data']['bank-details'] = [
                                'Beneficiary account number' => '409002234039',
                                'Beneficiary name' => 'K M GLOBAL P2P FINANCE PRIVATE LIMITED COLLECTION ACCOUNT',
                                'IFSC code' => 'RATN0000088',
                                'Bank Name' => 'RBL Bank'
                            ];
                        }else if($data['lender_id'] == BlackSoil::$lender_id){
                            $data['data']['bank-details'] = [
                                'Beneficiary account number' => '10245910063',
                                'Beneficiary name' => 'Blacksoil Capital Private Limited',
                                'IFSC code' => 'IDFB0040101',
                                'Bank Name' => 'IDFC First Bank'
                            ];
                        }else {
                            $data['data']['bank-details'] = [
                                'Beneficiary account number' => '10245910063',
                                'Beneficiary name' => 'BLACKSOIL CAPITAL PRIVATE LIMITED',
                                'IFSC code' => 'IDFB0040101',
                                'Bank Name' => 'IDFC FIRST Bank'
                            ];
                        }
                    }
                    $data['loan_application_no'] = $consumer->proFormaInvoice->loan_application_no ?? '';
                    $data['purpose'] = $this->getPaymentPurpose($request);
                    $data['foreclosure_date'] = $is_foreclosure == 1 ? $is_foreclosure_date : '';
                    $data['is_foreclosure'] = $is_foreclosure;
                    $data['custom_date'] = date('Y-m-d');
                    $data['pre_part_payment_type'] = $request->get('type_of_pre_payment');
                    $data['payment_link'] = (new ConsumerApplicationController())->getrazorpaylink($data);

                    if($is_foreclosure == 1 && $is_foreclosure_date) {
                        ConsumerApplicationElement::where('application_id', $consumer->id)->update([
                            'foreclosure_amount_sent' => $payable_amount_for_link,
                            'foreclosure_link_sent_by' => Auth::user() ? Auth::user()->id : 107
                        ]);
                        ForeclosureBreakup::where('application_id', $consumer->id)->delete();

                        ForeclosureBreakup::insert([
                            'application_id' => $consumer->id,
                            'pre_emi_due' => $request->get('pre_emi_due_to_foreclose'),
                            'principal_due' => $request->get('principal_due_to_foreclose'),
                            'interest_due' => $request->get('interest_due_to_foreclose'),
                            'moratorium_due' => $request->get('morat_due_to_foreclose'),
                            'bounce_due' => $request->get('bounce_due_to_foreclose'),
                            'penal_due' => $request->get('penal_due_to_foreclose'),
                            'pf_due' => $request->get('pf_due_to_foreclose'),
                            'advance_due' => $request->get('advance_due_to_foreclose'),
                            'foreclosure_amount' => $request->get('payable_amount_for_link'),
                            'foreclosure_date' => $request->get('foreclosure_date'),
                            'created_by' => Auth::user()->id,
                            'created_at' => Carbon::now()->toDateTimeString(),
                        ]);
                    }

//                    $hashids = new Hashids('Creditfair by CS', 20);
//                    $hashed_id = $hashids->encode($id);
//                    if($is_foreclosure == 1){
//                        $amount_foreclosuredate = $payable_amount_for_link .'|'.$is_foreclosure_date;
//                    }else {
//                        $amount_foreclosuredate = $payable_amount_for_link;
//
//                    }
//                    $amount_foreclosuredate_encrypter = base64_encode(wall_encrypt($amount_foreclosuredate));
//                    try {
//                        $data['payment_link'] = \Bitly::getUrl(asset("paytm/" . $hashed_id . "?data=" . $amount_foreclosuredate_encrypter));
//                    }catch (\Exception $e){
//                        $data['payment_link'] = asset("paytm/" . $hashed_id . "?data=" . $amount_foreclosuredate_encrypter);
//                        }
                    


                    if (isset($consumer->email) && !empty($consumer->email) && $isEmail == 1) {
                        $view_data['applicant_email'] = $consumer->email;
                        $view_data['coapplicant_email'] = $consumer->co_applicant_email;
                            $view_data['body'] = view('emails.reminders.emi_due_reminder_with_payment_link_with_custom_amount', $data)->render();
                            $view_data['subject'] = "Payment Link for Rs.".$payable_amount_for_link." for loan account number ".$data['loan_application_no'];
                            \Mail::send('emails.blank',
                                ['body' => $view_data['body']]
                                , function ($message) use ($view_data) {
                                    $message->to($view_data['applicant_email'])->subject($view_data['subject']);

                                    if (isset($view_data['coapplicant_email']) && !empty($view_data['coapplicant_email'])) {
                                        $message->cc($view_data['coapplicant_email']);
//                                        $message->cc([$view_data['coapplicant_email'],'payments@creditfair.in']);
                                    }else{
//                                        $message->cc('payments@creditfair.in');
                                    }
                                });

                        }

                    $view_data['sms'] = "Dear " . $data['applicant_name'] . ",<br><br> Please pay amount of Rs." . \str_replace('.00', '', money_format('%!i', ($payable_amount_for_link))) . " by clicking on " . $data['payment_link'] . " Regards, Team Credit Fair";
                    $view_data['sms'] = str_replace('<br/>', "\n", $view_data['sms']);
                    $view_data['sms'] = str_replace('<br>', "\n", $view_data['sms']);
                    $view_data['templateDetails'] = ['templateid' => '1307161734987223962', 'entityid' => Templates::$entityid];

                    $templateId = Templates::$closure_link_share;
                    $args = [$data['applicant_name'], \str_replace('.00', '', money_format('%!i', ($payable_amount_for_link))),$data['payment_link']];

                    if (isset($consumer->mobile_number) && !empty($consumer->mobile_number) && $isSMS == 1) {
                        $mobile = '91' . $consumer->mobile_number;
                        if(isset($consumer->co_applicant_mobile_number) && !empty($consumer->co_applicant_mobile_number)){
                            $mobile.= $mobile.",91".$consumer->co_applicant_mobile_number;
                        }
                        send_sms($mobile, ['message'=>$view_data['sms'],'id'=>$consumer->id,'id_type'=>'application_id','message_type'=>"payment", 'templateId' => $templateId, 'args' => $args, 'templateDetails' => $view_data['templateDetails']]);
                    }
                    $message = isset($view_data['sms']) ? str_replace("\n", "%0A", $view_data['sms']) : '';
                    $status = 'OK';
                }

            }else {
                $payment = new LoanManagement();
                $application_ids = [$id];
                $paymentData = $payment->overDueReminder($application_ids, $isEmail, $isSMS,$send_anyways = 1);
                $message = isset($paymentData['sms']) ? str_replace("\n", "%0A", $paymentData['sms']) : '';
                $status = 'OK';
            }
        }catch (\Exception $e){
            $cwFactory = new CloudWatchLoggerFactory();
            $_data = array(
                    'exception' => 'Exception occurred while sending payment link',
                    'message' => $e->getMessage(),
                    'line' => $e->getLine(),
                    'trace' => $e->getTraceAsString()
                );
            $cwFactory->logger(json_encode($_data));
            $status = 'FAIL';
            $message = 'Exception occurred while sending payment link';
        }
        return \response()->json(['status'=>$status,'message'=>$message],200);
    }

    public function getPaymentPurpose(Request $request){
        if($request->has('purpose') && ($request->get('purpose') == 'pre_part_payment' || $request->get('purpose') == 'processing_fee' || $request->get('purpose') == 'settlement_payment')){
            return $request->get('purpose');
        }
        return 'EMI';
    }


    public function importMandateFile(){
        return view('admin.accounting.importMandate');
    }

    public function startMandateFile(Request $request){
        try {
            if ($request->has('mandate_file')) {

                if($request->files->get('mandate_file') != null) {
                    if(filesize($request->files->get('mandate_file')) > 18874368){
                    Session::flash('error', 'Uploaded file is too large');
                    return redirect()->back();
                    }
                }

            }
            $file_path = $this->saveReceiptAck($request->file('mandate_file'), 'mandate', $request->get('mandate_date'), '', 'mandate_processed');
            $request->attributes->add(['file_path' => $file_path]);
            $mandate = new MandateFile($request);
            Excel::import($mandate, $request->file('mandate_file'));
            \Session::flash('success', $mandate->nach_updated.' Mandate Updated successfully ');
            return redirect()->back();
        }catch (\Exception $e){
            \Session::flash('error', 'Something went wrong, '.$e->getFile().$e->getLine());
            return redirect()->back();
        }

    }

    public function updateWaiveOff(Request $request){

        $amount = $request->has('waive_amount') ? $request->get('waive_amount') : 0;
        $emi_id = $request->has('emi_id') ? $request->get('emi_id') : 0;

        if($amount > 0 and $emi_id > 0){
            $emi_data = EmiPayment::find($emi_id);

            $authId = Auth::user() ? Auth::user()->id : 107;
            if (!$request->has('go_maker_check') && !static::canWaiveOff($emi_data->application_id)) {
                PaymentMakerChecker::insert(['application_id' => $emi_data->application_id, 'payment_type' => $request->get('payment_type'), 'data' => json_encode($request->all()), 'maker_id' => $authId, 'checker_id' => 0, 'type' => 'payment_waive_off', 'status' => 1, 'created_at' => Carbon::now()->toDateTimeString(), 'emi_payment_id'=> $emi_id]);
                return response()->json("Updated",200);
            }else if (!$request->has('no_maker_checker')){
                PaymentMakerChecker::insert(['application_id' => $emi_data->application_id, 'payment_type' => $request->get('payment_type'), 'data' => json_encode($request->all()), 'maker_id' => $authId, 'checker_id' => $authId, 'type' => 'payment_waive_off', 'status' => 0, 'created_at' => Carbon::now()->toDateTimeString(), 'emi_payment_id'=> $emi_id]);
            }


            $waived_amount = $emi_data->charges_waived + $amount;
            $emi_data->charges_waived = $waived_amount;
            $payment_transaction = PaymentTransaction::where('emi_payment_id',$emi_id)->where('status',"success")->whereNull('is_deleted_at')->get();
            $amount_received = 0;
            if($payment_transaction){
                foreach ($payment_transaction as $payments){
                    $amount_received = $amount_received + $payments->amount;
                }
            }
            $total_payable = ($emi_data->emi_amount + $emi_data->bounce_charges + $emi_data->delay_penalty) - $waived_amount;
            $due = $total_payable - $amount_received;
            $emi_data->amount_due = $due;
            $emi_data->total_payable = $total_payable;
            if($due > 0){
                $emi_data->payment_status = "partial";
            }else{
                $emi_data->payment_status = "success";
            }
            $emi_data->save();

            $waive_log = new WaiveOffLog();
            $waive_log->emi_payment_id = $emi_id;
            $waive_log->amount = $amount;

            $waive_log->waived_by = Auth::user()->id;
            $waive_log->status = "Active";
            $waive_log->save();

            $loanManagement = new LoanManagement();
            $loanManagement->payment_entry_page = true;
            $loanManagement->paymentCalculate($emi_data->application_id);
            $loanManagement->isAllRepaymentReceived($emi_data->application_id);

            return response()->json("Updated",200);
        }
        return response()->json("Failed",200);
    }

    public static function canWaiveOff($application_id){
        $user_id = (Auth::user()) ? Auth::user()->id : '';
        if (!(in_array($user_id, [543,251,26,3344])))
            return false;
        $data = PaymentMakerChecker::where('application_id', $application_id)->where('type','payment_waive_off')->where('checker_id', $user_id)->where('status',0)->get();
        $inc_by = 0;
        if ($user_id == 543){
            $inc_by = 0;
        }else if ($user_id == 251 || $user_id == 3344){
            return true;//$inc_by = 1;
        }
        if ($user_id == 26){
            return true;
        }
        if (count($data) <= $inc_by){
            return true;
        }
        return false;
    }

    public function verifyPayments(){
        $ids = array();
        $bank_ids = array();
        $bank_names = array();

        $payments = PaymentMakerChecker::with(['application' => function($query){
            return $query->select(['id','name']);
        }, 'avanseManualPayment' => function($query){
            return $query->select(['id', 'bulk_id', 'application_id','status', 'message']);
        }])->where('status',1)->get();

        foreach($payments as $payment){
            $paymentData = json_decode($payment->data);

            try {
                $ids[] = $paymentData->bank_id;
                $bank_ids = array_unique($ids);

            }catch(\Exception $e){
                continue;
            }
        }
        $payment_banks = \App\LenderBank::whereIn('id',$bank_ids)->get(['bank_name','id']);
        foreach($bank_ids as $id){
            foreach($payment_banks as $payment){
                if($payment->id == $id){
                    $bank_names[$payment->id]['name'] = $payment->bank_name;
                }
            }
        }

        return view('admin.accounting.verify_payments', ['payments' => $payments,'bank_name' => $bank_names]);
    }

    public function checkSettlementPendingVerification($application_id){
        $paymentMakerCheckerDetails = DB::select("SELECT * FROM payment_transactions WHERE application_id = ? AND payment_for in ('settled_principal', 'settled_bounce', 'settled_penal', 'settled_interest') AND deleted_at IS NULL", [$application_id]);
        if (count($paymentMakerCheckerDetails) > 0) {
            return true;
        }
        return false;
    }

    public function getReceiptFile($id, Request $request){

        $path = $request->get('path');
        $filename = basename($path);

        if (!Storage::disk('s3')->exists($path)) {
            abort(404, "File not found on S3.");
        }

        $stream = Storage::disk('s3')->readStream($path);

        $tempPath = storage_path('app/temp_' . time() . '_' . $filename);
        $tempFile = fopen($tempPath, 'w');
        stream_copy_to_stream($stream, $tempFile);
        fclose($tempFile);

        return response()->download($tempPath, $filename)->deleteFileAfterSend(true);


        /*$s3 = Storage::disk('s3')->download($request->get('path'), $filename);
        $path = storage_path().'/'.time().'.pdf';
        $view = $s3->get($request->get('path'));
        $file = fopen($path, "w");
        fwrite($file, $view);
        fclose($file);
        return response()->file($path)->deleteFileAfterSend(true);*/
    }

    public function updatePaymentScene(Request $request){
        $isUpdated = 'FAIL';
        $message = 'There are no changes to save';
        try {
            if ($request->has('data')) {
                $paymentData = [];
                foreach ($request->get('data') as $payment) {
                    $paymentData[$payment['id']][] = $payment;
                }
                $payments = PaymentMakerChecker::whereIn('id', array_keys($paymentData))->get();
                foreach ($payments as $paymentItem) {
                    $isUpdatedDone = false;
                    if (isset($paymentData[$paymentItem->id])) {
                        $blockOld = json_decode($paymentItem->data);
                        foreach ($paymentData[$paymentItem->id] as $paymentDataItem) {
                            $blockUpdate = $paymentDataItem;
                            if ($blockUpdate['type'] == 'payment_reconciliation_date') {
                                if ($blockOld->payment_reconciliation_date != $blockUpdate['new']) {
                                    $blockOld->payment_reconciliation_date = $blockUpdate['new'];
                                    $isUpdatedDone = true;
                                }
                            }
                            if ($blockUpdate['type'] == 'trasanction_id') {
                                if ($blockOld->trasanction_id != $blockUpdate['new']) {
                                    $blockOld->trasanction_id = $blockUpdate['new'];
                                    $isUpdatedDone = true;
                                }
                            }
                        }

                        if ($isUpdatedDone) {
                            $message = 'Changes are updated successfully';
                            if (isset($blockOld->trasanction_id) && $blockOld->trasanction_id){
                                $PaymentTransaction = PaymentTransaction::where('trasanction_id', $blockOld->trasanction_id)->whereNull('deleted_by')->first(['id']);
                                if (isset($PaymentTransaction->id)){
                                    $message .= '. Transaction ID has been used earlier.';
                                }
                            }
                            PaymentMakerChecker::where('id', $paymentItem->id)->update(['data' => json_encode($blockOld)]);
                            $isUpdated = 'OK';
                        }
                    }
                }
            }
        }catch (\Exception $e){
            $message = 'Something went wrong, Please try again later';
        }

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

    public function startPaymentDiffer(Request $request){
        $status = 'FAIL';
        $message = 'Failed to adjust the entry';
        if($request->has('id') && $request->has('user_id') && $request->has('payment_id')){
            $paymentTransaction = PaymentTransaction::where('id', $request->get('id'))->first(['emi_payment_id', 'application_id']);
            $paymentTransactionDifferLogsId = PaymentTransactionDifferLogs::insertGetId([
                'transaction_id' => $request->get('id'),
                'emi_payment_id_old' => $paymentTransaction->emi_payment_id,
                'emi_payment_id_new' => $request->get('payment_id'),
                'user_id' => $request->get('user_id'),
                'created_at' => Carbon::now()->toDateTimeString()
            ]);
            PaymentTransaction::where('id', $request->get('id'))->update(['emi_payment_id' => $request->get('payment_id'), 'differ_id' => $paymentTransactionDifferLogsId]);

            $loanManagement = new LoanManagement();
            $loanManagement->payment_entry_page = true;
            $loanManagement->paymentCalculate($paymentTransaction->application_id);

            $status = 'OK';
            $message = 'Payment adjusted successfully';
        }

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

    public function settlmentInitiate($id){
        $application       = ConsumerApplication::where('id', $id)->first(['id', 'name', 'email', 'secondary_status']);
        $collectionActions = CollectionAction::where('application_id', $id)->orderBy('created_at', 'desc')->get();
        $makerCheckerLogs  = \App\SettlementMakerChecker::with('maker', 'checker', 'requestedTo')
            ->where('application_id', $id)
            ->orderBy('created_at', 'desc')
            ->get();

        // Per-Settlement-action: check whether payment was received by ptp_date
        $settledPaymentTypes = ['settled_principal', 'settled_interest', 'settled_bounce', 'settled_penal'];
        $settlementPaymentMap = [];  // collection_action_id => bool
        foreach ($collectionActions->where('dispo_code', 'Settlement') as $sa) {
            $received = (float) PaymentTransaction::where('application_id', $id)
                ->whereIn('payment_for', $settledPaymentTypes)
                ->where('payment_date', '<=', $sa->ptp_date)
                ->sum('amount');
            $settlementPaymentMap[$sa->id] = $received >= (float) $sa->amount_to_be_received;
        }

        // Check whether settled payments cover the agreed settlement amount (latest Settlement action)
        $settlementAction   = $collectionActions->where('dispo_code', 'Settlement')->sortByDesc('created_at')->first();
        $amountToBeReceived = $settlementAction ? (float) $settlementAction->amount_to_be_received : 0;
        $isSettlementPaid   = $settlementAction && ($settlementPaymentMap[$settlementAction->id] ?? false);

        return view('admin.accounting.payment_settlement', [
            'application'       => $application,
            'collectionActions' => $collectionActions,
            'makerCheckerLogs'  => $makerCheckerLogs,
            'isSettlementPaid'      => $isSettlementPaid,
            'settlementPaymentMap'  => $settlementPaymentMap,
        ]);
    }

    public function settlementLogsList(Request $request)
    {
        $applicationId = $request->input('application_id');
        $query = \App\SettlementMakerChecker::with(['maker', 'checker', 'requestedTo', 'collectionAction'])->orderBy('updated_at', 'desc');

        if ($applicationId) {
            $query->where('application_id', $applicationId);
        }

        $makerCheckerLogs = $query->paginate(50)->appends($request->only('application_id'));

        // Build per-log settlement payment status map
        $settledPaymentTypes = ['settled_principal', 'settled_interest', 'settled_bounce', 'settled_penal'];
        $settlementPaidMap   = [];  // log->id => bool
        $secondaryStatusMap  = [];  // application_id => secondary_status

        $appIds = $makerCheckerLogs->pluck('application_id')->unique()->values();

        // Fetch secondary_status for all applications in the page
        $applications = ConsumerApplication::whereIn('id', $appIds)
            ->get(['id', 'secondary_status', 'email'])
            ->keyBy('id');

        foreach ($makerCheckerLogs as $log) {
            if (!$log->collectionAction) {
                $settlementPaidMap[$log->id] = false;
                continue;
            }
            $sa = $log->collectionAction;
            $received = (float) PaymentTransaction::where('application_id', $log->application_id)
                ->whereIn('payment_for', $settledPaymentTypes)
                ->where('payment_date', '<=', $sa->ptp_date)
                ->sum('amount');
            $settlementPaidMap[$log->id] = $received >= (float) $sa->amount_to_be_received;
        }

        return view('admin.accounting.settlement_logs', [
            'makerCheckerLogs'   => $makerCheckerLogs,
            'settlementPaidMap'  => $settlementPaidMap,
            'applications'       => $applications,
            'filterAppId'        => $applicationId,
        ]);
    }

    public function updatePaymentToAvanse(Request $request, $amount = 0, $paymentMakerCheckerId = 0){
        if($request->has('payment_maker_checker_id')) {
            $status = 'FAIL';
            $message = 'Payment entry not found';
            $campaignsJobProvider = CampaignsJobProvider::where('from', 'manual_payment_avanse')->where(DB::raw("json_extract(payload, '$.bulk_id')"), (int)$request->get('payment_maker_checker_id'))->where('application_id', $request->get('id'))->first(['id']);
            if (isset($campaignsJobProvider->id)) {
                $status = 'OK';
                $message = 'Payment added in queue';
                CampaignsJobProvider::where('id', $campaignsJobProvider->id)->update(['is_available' => 0]);
            }
            return response()->json(['status' => $status, 'message' => $message], 200);
        }
        if($amount && $paymentMakerCheckerId) {
            $application_id = $request->get('paid_by_value');
            $reference = AvanseCreateFinance::where('application_id', $application_id)->first();
            if ($reference && $reference->finReference) {


                $payment = new \stdClass();
                $payment->id = $paymentMakerCheckerId;
                $payment->finReference = $reference;
                $item[0] = $amount;
                $item[1] = $request->get('payment_date');
                $item[3] = $request->get('transaction_id');
                $item[5] = $application_id;


                $jobs = new CampaignsJobProvider();
                $jobs->from = 'manual_payment_avanse';
                $jobs->payload = json_encode((new AvanseServices(new Request([
                    'id' => $application_id,
                    'payment_mode' => $request->get('payment_mode')
                ])))->getManualPaymentPayload($payment, $item)->all());
                $jobs->available_at = Carbon::now()->toDateTimeString();
                $jobs->application_id = $application_id;
                $jobs->created_at = Carbon::now()->toDateTimeString();
                $jobs->is_available = 0;
                $jobs->save();
            }
        }
    }

    public function getAccruedProfit(){

        $response = array();
        $status =  ['disbursed','nach registered','closed '];
        $consumerApplications = ConsumerApplicationRelation::with('logs','emi','emi.offer','emi_payment','emi_payment.transaction','lender')->wherein('state',$status)->whereNull('is_deleted')->whereIn('lender_id',[1,2]);

        $consumerApplications = $consumerApplications->get();
        $consumerDocument = new ConsumerDocument(new Request());
        //$merhchantcontroller = new MerchantController();

        foreach ($consumerApplications as $consumerApplication) {
            if(isset($consumerApplication->emi) and $consumerApplication->emi != null) {

                $gstDetails = $consumerDocument->getGSTDetails(
                    [
                        'amount' => $consumerApplication->emi->processing_fee,
                        'state' => (isset($consumerApplication->permanent_address_state) && !empty($consumerApplication->permanent_address_state)) ? $consumerApplication->permanent_address_state : (isset($consumerApplication->current_address_state) && !empty($consumerApplication->current_address_state) ? $consumerApplication->current_address_state : '')
                    ]
                );
                foreach ($gstDetails as $gst) {
                    $response[$consumerApplication->id]['processing_fees_net_amount'] = $gst['net_amount'];
                    $response[$consumerApplication->id][$gst['taxes']] = $gst['gst_amount'];
                }
                if (isset($consumerApplication->logs->created_at)) {
                    $disbursed_month = date('Y-m', strtotime($consumerApplication->logs->created_at));
                } else {
                    return $consumerApplication;
                }
                if (isset($response[$consumerApplication->lender_id][$disbursed_month]['processing_fees'])) {
                    $response[$consumerApplication->lender_id][$disbursed_month]['processing_fees'] = round($response[$consumerApplication->lender_id][$disbursed_month]['processing_fees'] + $response[$consumerApplication->id]['processing_fees_net_amount'], 2);
                } else {
                    $response[$consumerApplication->lender_id][$disbursed_month]['processing_fees'] = round($response[$consumerApplication->id]['processing_fees_net_amount'], 2);
                }
                if ($response[$consumerApplication->id]['processing_fees_net_amount'] > 0) {
                    $response[$consumerApplication->id][date('Y-m-d', strtotime($consumerApplication->logs->created_at))]['processing_fees'] = round($response[$consumerApplication->id]['processing_fees_net_amount'], 2);
                }
                if ($consumerApplication->emi_payment) {
                    foreach ($consumerApplication->emi_payment as $emi_payment) {
                        $emimonth = date('Y-m', strtotime($emi_payment->emi_date));
                        if ($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[$consumerApplication->id][$emi_payment->emi_date]['penal_interest'] = round($penal_interest, 2);
                                if (isset($response[$consumerApplication->lender_id][$emimonth]['penal_interest'])) {
                                    $response[$consumerApplication->lender_id][$emimonth]['penal_interest'] = round($response[$consumerApplication->lender_id][$emimonth]['penal_interest'] + $penal_interest, 2);
                                } else {
                                    $response[$consumerApplication->lender_id][$emimonth]['penal_interest'] = round($penal_interest, 2);
                                }
//                                $penal_interest_gstDetails = $consumerDocument->getGSTDetails(
//                                    [
//                                        'amount' => $penal_interest,
//                                        'state' => (isset($consumerApplication->permanent_address_state) && !empty($consumerApplication->permanent_address_state)) ? $consumerApplication->permanent_address_state : (isset($consumerApplication->current_address_state) && !empty($consumerApplication->current_address_state) ? $consumerApplication->current_address_state : '')
//                                    ]
//                                );
//                                if ($penal_interest_gstDetails) {
//                                    if ($penal_interest_gstDetails[0]['net_amount'] > 0) {
//                                        $response[$consumerApplication->id][$emi_payment->emi_date]['penal_interest'] = round($penal_interest_gstDetails[0]['net_amount'], 2);
//                                    }
//                                    if (isset($response[$consumerApplication->lender_id][$emimonth]['penal_interest'])) {
//                                        $response[$consumerApplication->lender_id][$emimonth]['penal_interest'] = round($response[$consumerApplication->lender_id][$emimonth]['penal_interest'] + $penal_interest_gstDetails[0]['net_amount'], 2);
//                                    } else {
//                                        $response[$consumerApplication->lender_id][$emimonth]['penal_interest'] = round($penal_interest_gstDetails[0]['net_amount'], 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;

                                }
                            }
                            //$bounce_charge = ($emi_payment->charges_waived > ($emi_payment->delay_penalty + $emi_payment->bounce_charges)) ? $emi_payment->bounce_charges : ($emi_payment->bounce_charges - ($emi_payment->delay_penalty - $emi_payment->charges_waived));
                            if ($bounce_charge > 0) {
                                    $response[$consumerApplication->id][$emi_payment->emi_date]['bounce_charges'] = round($bounce_charge, 2);

                                if (isset($response[$consumerApplication->lender_id][$emimonth]['bounce_charges'])) {
                                    $response[$consumerApplication->lender_id][$emimonth]['bounce_charges'] = round($response[$consumerApplication->lender_id][$emimonth]['bounce_charges'] + $bounce_charge, 2);
                                } else {
                                    $response[$consumerApplication->lender_id][$emimonth]['bounce_charges'] = round($bounce_charge, 2);
                                }
//                                $bounce_charges_gstDetails = $consumerDocument->getGSTDetails(
//                                    [
//                                        'amount' => $bounce_charge,
//                                        'state' => (isset($consumerApplication->permanent_address_state) && !empty($consumerApplication->permanent_address_state)) ? $consumerApplication->permanent_address_state : (isset($consumerApplication->current_address_state) && !empty($consumerApplication->current_address_state) ? $consumerApplication->current_address_state : '')
//                                    ]
//                                );
//                                if ($bounce_charges_gstDetails) {
//                                    if ($bounce_charges_gstDetails[0]['net_amount'] > 0) {
//                                        $response[$consumerApplication->id][$emi_payment->emi_date]['bounce_charges'] = round($bounce_charges_gstDetails[0]['net_amount'], 2);
//                                    }
//
//                                    if (isset($response[$consumerApplication->lender_id][$emimonth]['bounce_charges'])) {
//                                        $response[$consumerApplication->lender_id][$emimonth]['bounce_charges'] = round($response[$consumerApplication->lender_id][$emimonth]['bounce_charges'] + $bounce_charges_gstDetails[0]['net_amount'], 2);
//                                    } else {
//                                        $response[$consumerApplication->lender_id][$emimonth]['bounce_charges'] = round($bounce_charges_gstDetails[0]['net_amount'], 2);
//                                    }
//                                }
                            }
                        }

                    }
                }
                if (!isset($response[$consumerApplication->id]['name'])) {
                    $response[$consumerApplication->id]['name'] = $consumerApplication->name;
                }
                if (!isset($response[$consumerApplication->id]['lender'])) {
                    $response[$consumerApplication->id]['lender'] = $consumerApplication->lender->name;
                }
                if (!isset($response[$consumerApplication->id]['subvention_rate'])) {
                    $response[$consumerApplication->id]['subvention_rate'] = $consumerApplication->emi->subvention;
                }
                if (!isset($response[$consumerApplication->id]['approved_amount'])) {
                    $response[$consumerApplication->id]['approved_amount'] = $consumerApplication->approved_amount;
                }

                $loanschedule = json_decode(json_encode($this->viewloanschedule($consumerApplication->id, 1, 1, 1, 1)));
                $i = 1;
                if (isset($loanschedule->schedule)) {
                    foreach ($loanschedule->schedule as $loanemi) {
                        $emimonth = date('Y-m', strtotime($loanemi->emi_date));
                        $emi_start_date = strtotime($emimonth . "-1");
                        $disbursement_date = date('Y-m-d', (strtotime($consumerApplication->logs->created_at)));

                        while ((strtotime($disbursement_date) < $emi_start_date) && $i == 1) {
                            $disbursedmonth = date('Y-m', strtotime($disbursement_date));
                            $response[$consumerApplication->id][$disbursement_date]['outstanding'] = round($loanschedule->summary->loan_outstanding, 2);

                            if (isset($response[$consumerApplication->lender_id][$disbursedmonth]['principal_outstanding'])) {
                                $response[$consumerApplication->lender_id][$disbursedmonth]['principal_outstanding'] = round($response[$consumerApplication->lender_id][$disbursedmonth]['principal_outstanding'] + $loanschedule->summary->loan_outstanding, 2);
                            } else {
                                $response[$consumerApplication->lender_id][$disbursedmonth]['principal_outstanding'] = round($loanschedule->summary->loan_outstanding, 2);

                            }
                            $disbursement_date = date('Y-m-d', (strtotime("+1 months", strtotime($disbursement_date))));
                        }
                        $i++;
                        $response[$consumerApplication->id][$loanemi->emi_date]['emi_amount'] = $loanemi->amount;
                        $response[$consumerApplication->id][$loanemi->emi_date]['outstanding'] = $loanemi->principal_outstanding;
                        $response[$consumerApplication->id][$loanemi->emi_date]['subvention_amount_balance'] = $loanemi->subvention_amount_balance;
                        $response[$consumerApplication->id][$loanemi->emi_date]['revenue'] = round($loanemi->irr, 2);
                        $response[$consumerApplication->id][$loanemi->emi_date]['interest'] = round($loanemi->interest, 2);
                        $response[$consumerApplication->id][$loanemi->emi_date]['subvention'] = round($loanemi->subvention, 2);


                        $response[$consumerApplication->id][$loanemi->emi_date]['principal_payable'] = round($loanemi->principal, 2);
                        if (isset($response[$consumerApplication->lender_id][$emimonth]['revenue'])) {
                            $response[$consumerApplication->lender_id][$emimonth]['revenue'] = round($response[$consumerApplication->lender_id][$emimonth]['revenue'] + $response[$consumerApplication->id][$loanemi->emi_date]['revenue'], 2);
                        } else {
                            $response[$consumerApplication->lender_id][$emimonth]['revenue'] = round($response[$consumerApplication->id][$loanemi->emi_date]['revenue'], 2);
                        }
                        if (isset($response[$consumerApplication->lender_id][$emimonth]['interest'])) {
                            $response[$consumerApplication->lender_id][$emimonth]['interest'] = round($response[$consumerApplication->lender_id][$emimonth]['interest'] + $response[$consumerApplication->id][$loanemi->emi_date]['interest'], 2);
                        } else {
                            $response[$consumerApplication->lender_id][$emimonth]['interest'] = round($response[$consumerApplication->id][$loanemi->emi_date]['interest'], 2);
                        }

                        if (isset($response[$consumerApplication->lender_id][$emimonth]['subvention'])) {
                            $response[$consumerApplication->lender_id][$emimonth]['subvention'] = round($response[$consumerApplication->lender_id][$emimonth]['subvention'] + $response[$consumerApplication->id][$loanemi->emi_date]['subvention'], 2);
                        } else {
                            $response[$consumerApplication->lender_id][$emimonth]['subvention'] = round($response[$consumerApplication->id][$loanemi->emi_date]['subvention'], 2);

                        }
                        if (isset($response[$consumerApplication->lender_id][$emimonth]['principal_outstanding'])) {
                            $response[$consumerApplication->lender_id][$emimonth]['principal_outstanding'] = round($response[$consumerApplication->lender_id][$emimonth]['principal_outstanding'] + $loanemi->principal_outstanding, 2);
                        } else {
                            $response[$consumerApplication->lender_id][$emimonth]['principal_outstanding'] = round($loanemi->principal_outstanding, 2);
                        }
                    }
                } else {
                    (new Slack(new Request(['title' => 'Accured Renenue Loan Schedule ', 'fields' => ['ID' => $consumerApplication->id]])))->send();

                }
            }else {
                (new Slack(new Request(['title' => 'Accured Renenue Emi Not Generated ', 'fields' => ['ID' => $consumerApplication->id]])))->send();

            }
//            $irr = $merhchantcontroller->calculateIRR("", $consumerApplication->approved_amount, json_decode(($consumerApplication->emi), true), false);
//            $tenure = $consumerApplication->emi->remaining_emi;
//            $emi_date = $consumerApplication->emi->emi_date;
//            $count = 1;
//            $outsanding = ($consumerApplication->approved_amount * (1 - ($consumerApplication->emi->subvention / 100))) - $consumerApplication->emi->upfront_from_customer;
//            //return $consumerApplications[0]->emi;
//            if(!isset($response[$consumerApplication->id]['name'])){
//                $response[$consumerApplication->id]['name'] = $consumerApplication->name;
//            }
//            if(!isset($response[$consumerApplication->id]['lender'])){
//                $response[$consumerApplication->id]['lender'] = $consumerApplication->lender->name;
//            }
//            while ($count <= $tenure) {
//                if($count == 1){
//                    $emi_date = date('Y-m-d', strtotime($emi_date));
//                }else {
//                    $emi_date = date('Y-m-d', strtotime($emi_date . ' +1 month'));
//                }
//                    $emimonth = date('Y-m', strtotime($emi_date));
//
//                    $response[$consumerApplication->id][$emi_date]['emi_amount'] = $consumerApplication->emi->emi;
//                    $response[$consumerApplication->id][$emi_date]['outstanding'] = $outsanding;
//
//                    $response[$consumerApplication->id][$emi_date]['revenue'] = round(($response[$consumerApplication->id][$emi_date]['outstanding'] * $irr['irr']) / 100, 2);
//                    $response[$consumerApplication->id][$emi_date]['principal_payable'] = round($consumerApplication->emi->emi - $response[$consumerApplication->id][$emi_date]['revenue'],2);
//                    if(isset($response[$consumerApplication->lender_id][$emimonth]['revenue'])){
//                        $response[$consumerApplication->lender_id][$emimonth]['revenue'] = round($response[$consumerApplication->lender_id][$emimonth]['revenue'] + $response[$consumerApplication->id][$emi_date]['revenue'],2);
//                    }else{
//                        $response[$consumerApplication->lender_id][$emimonth]['revenue'] = round($response[$consumerApplication->id][$emi_date]['revenue'],2);
//                    }
//                    if(isset($response[$consumerApplication->lender_id][$emimonth]['principal_outstanding'])){
//                        $response[$consumerApplication->lender_id][$emimonth]['principal_outstanding'] = round($response[$consumerApplication->lender_id][$emimonth]['principal_outstanding'] + $outsanding,2);
//                    }else{
//                        $response[$consumerApplication->lender_id][$emimonth]['principal_outstanding'] = round($outsanding,2);
//                    }
//                    $outsanding = round($outsanding - $response[$consumerApplication->id][$emi_date]['principal_payable'], 2);
//                $count++;
//            }
        }


        $data_table =  "<table><tr><th>Application Id</th><th>Lender</th><th>Name</th><th>Emi_Date</th><th>principal_payable</th><th>emi_amount</th><th>outstanding</th><th>revenue</th><th>interest</th><th>subvention</th><th>Processing Fees</th><th>Bounce Charges</th><th>Penal Interest</th><th>Subvention Balance</th><th>Subvention Rate</th><th>Approved Rate</th></tr>";

        foreach ($response as $key => $application){
            foreach ($application as $emi_date => $emi_details){
                if((isset($emi_details['emi_amount']) || isset($emi_details['processing_fees']) || isset($emi_details['outstanding']) || isset($emi_details['bounce_charges']) || isset($emi_details['penal_interest'])) && $key != 1 and $key != 2) {
                    $data_table.= "<tr><td>" . $key . "</td><td>" . (isset($application['lender']) ? $application['lender'] : "") . "</td><td>" . (isset($application['name']) ? $application['name'] : "") . "</td><td>" . $emi_date . "</td><td>" . money_format('%!i',(isset($emi_details['principal_payable']) ? $emi_details['principal_payable'] : 0)) . "</td><td>" . money_format('%!i',(isset($emi_details['emi_amount']) ? $emi_details['emi_amount'] : 0)) . "</td><td>" . money_format('%!i',(isset($emi_details['outstanding']) ? $emi_details['outstanding'] : 0)) . "</td><td>" . money_format('%!i',(isset($emi_details['revenue']) ? $emi_details['revenue'] : 0)) . "</td><td>" . money_format('%!i',(isset($emi_details['interest']) ? $emi_details['interest'] : 0)) . "</td><td>" . money_format('%!i',(isset($emi_details['subvention']) ? $emi_details['subvention'] : 0)) . "</td><td>".money_format('%!i',(isset($emi_details['processing_fees']) ? $emi_details['processing_fees'] : 0))."</td><td>".money_format('%!i',(isset($emi_details['bounce_charges']) ? $emi_details['bounce_charges'] : 0))."</td><td>".money_format('%!i',(isset($emi_details['penal_interest']) ? $emi_details['penal_interest'] : 0))."</td><td>".money_format('%!i',(isset($emi_details['subvention_amount_balance']) ? $emi_details['subvention_amount_balance'] : 0))."</td><td>" . (isset($application['subvention_rate']) ? $application['subvention_rate'] : 0) . "</td><td>".money_format('%!i',(isset($application['approved_amount']) ? $application['approved_amount'] : 0))."</td></tr>";
                }
            }
        }
        setlocale(LC_MONETARY, 'en_IN.UTF-8');
        //(isset($emi_details['penal_interest']) ? $emi_details['penal_interest'] : 0) ;
        $data_table.= "</table>";


        $response[1]['final']['processing_fees'] = 0;
        $response[1]['final']['principal_outstanding'] = 0;
        $response[1]['final']['revenue'] = 0;
        $response[1]['final']['interest'] = 0;
        $response[1]['final']['subvention'] = 0;
        $response[1]['final']['bounce_charges'] = 0;
        $response[1]['final']['penal_interest'] = 0;
        $response[2]['final']['processing_fees'] = 0;
        $response[2]['final']['principal_outstanding'] = 0;
        $response[2]['final']['revenue'] = 0;
        $response[2]['final']['interest'] = 0;
        $response[2]['final']['subvention'] = 0;
        $response[2]['final']['bounce_charges'] = 0;
        $response[2]['final']['penal_interest'] = 0;

        $data_table_month_1 =  "<table><tr><th>Month</th><th>Processing Fees</th><th>outstanding</th><th>Interest Subvention Revenue</th><th>Subvention Revenue</th><th>Interest Revenue</th><th>Bounce Charges</th><th>Penal Interest</th></tr>";
        $data_table_month_2 =  "<table><tr><th>Month</th><th>Processing Fees</th><th>outstanding</th><th>Interest Subvention Revenue</th><th>Subvention Revenue</th><th>Interest Revenue</th><th>Bounce Charges</th><th>Penal Interest</th></tr>";

        ksort($response);
        foreach ($response as $lender=> $response_revenue) {
            foreach ($response_revenue as $month => $revenue) {
                if (isset($revenue['revenue']) || isset($revenue['processing_fees']) || isset($revenue['principal_outstanding']) || isset($revenue['bounce_charges']) || isset($revenue['penal_interest'])) {
                    if ($lender == 1) {
                        $data_table_month_1 .= "<tr><td>" . date('F - Y', strtotime($month)) . "</td><td>" . money_format('%!i', (isset($revenue['processing_fees']) ? $revenue['processing_fees'] : 0)) . "</td><td>" . money_format('%!i', (isset($revenue['principal_outstanding']) ? $revenue['principal_outstanding'] : 0)) . "</td><td>" . money_format('%!i', (isset($revenue['revenue']) ? $revenue['revenue'] : 0)) . "</td><td>" . money_format('%!i', (isset($revenue['subvention']) ? $revenue['subvention'] : 0)) . "</td><td>" . money_format('%!i', (isset($revenue['interest']) ? $revenue['interest'] : 0)) . "</td><td>" . money_format('%!i', (isset($revenue['bounce_charges']) ? $revenue['bounce_charges'] : 0)) . "</td><td>" . (money_format('%!i', isset($revenue['penal_interest']) ? $revenue['penal_interest'] : 0)) . "</td></tr>";
                        $response[1]['final']['processing_fees'] = $response[1]['final']['processing_fees'] + (isset($revenue['processing_fees']) ? $revenue['processing_fees'] : 0);
                        $response[1]['final']['principal_outstanding'] = $response[1]['final']['principal_outstanding'] + (isset($revenue['principal_outstanding']) ? $revenue['principal_outstanding'] : 0);
                        $response[1]['final']['revenue'] = $response[1]['final']['revenue'] + (isset($revenue['revenue']) ? $revenue['revenue'] : 0);
                        $response[1]['final']['interest'] = $response[1]['final']['interest'] + (isset($revenue['interest']) ? $revenue['interest'] : 0);
                        $response[1]['final']['subvention'] = $response[1]['final']['subvention'] + (isset($revenue['subvention']) ? $revenue['subvention'] : 0);

                        $response[1]['final']['bounce_charges'] = $response[1]['final']['bounce_charges'] + (isset($revenue['bounce_charges']) ? $revenue['bounce_charges'] : 0);
                        $response[1]['final']['penal_interest'] = $response[1]['final']['penal_interest'] + (isset($revenue['penal_interest']) ? $revenue['penal_interest'] : 0);
                    } elseif($lender == 2) {
                        $data_table_month_2 .= "<tr><td>" . date('F - Y', strtotime($month)) . "</td><td>" . money_format('%!i', (isset($revenue['processing_fees']) ? $revenue['processing_fees'] : 0)) . "</td><td>" . money_format('%!i', (isset($revenue['principal_outstanding']) ? $revenue['principal_outstanding'] : 0)) . "</td><td>" . money_format('%!i', (isset($revenue['revenue']) ? $revenue['revenue'] : 0)) . "</td><td>" . money_format('%!i', (isset($revenue['subvention']) ? $revenue['subvention'] : 0)) . "</td><td>" . money_format('%!i', (isset($revenue['interest']) ? $revenue['interest'] : 0)) . "</td><td>" . money_format('%!i', (isset($revenue['bounce_charges']) ? $revenue['bounce_charges'] : 0)) . "</td><td>" . (money_format('%!i', isset($revenue['penal_interest']) ? $revenue['penal_interest'] : 0)) . "</td></tr>";
                        $response[2]['final']['processing_fees'] = $response[2]['final']['processing_fees'] + (isset($revenue['processing_fees']) ? $revenue['processing_fees'] : 0);
                        $response[2]['final']['principal_outstanding'] = $response[2]['final']['principal_outstanding'] + (isset($revenue['principal_outstanding']) ? $revenue['principal_outstanding'] : 0);
                        $response[2]['final']['revenue'] = $response[2]['final']['revenue'] + (isset($revenue['revenue']) ? $revenue['revenue'] : 0);
                        $response[2]['final']['interest'] = $response[2]['final']['interest'] + (isset($revenue['interest']) ? $revenue['interest'] : 0);
                        $response[2]['final']['subvention'] = $response[2]['final']['subvention'] + (isset($revenue['subvention']) ? $revenue['subvention'] : 0);
                        $response[2]['final']['bounce_charges'] = $response[2]['final']['bounce_charges'] + (isset($revenue['bounce_charges']) ? $revenue['bounce_charges'] : 0);
                        $response[2]['final']['penal_interest'] = $response[2]['final']['penal_interest'] + (isset($revenue['penal_interest']) ? $revenue['penal_interest'] : 0);
                    }
                }
            }
        }
        $data_table_month_1.=  "<tr><td>Total</td><td>" . money_format('%!i',$response[1]['final']['processing_fees']) . "</td><td>" . money_format('%!i',$response[1]['final']['principal_outstanding']) . "</td><td>" . money_format('%!i',$response[1]['final']['revenue']) . "</td><td>" . money_format('%!i',$response[1]['final']['subvention']) . "</td><td>" . money_format('%!i',$response[1]['final']['interest']) . "</td><td>" . money_format('%!i',$response[1]['final']['bounce_charges']) . "</td><td>" . money_format('%!i',$response[1]['final']['penal_interest']) . "</td></tr>";

        $data_table_month_2.=  "<tr><td>Total</td><td>" . money_format('%!i',$response[2]['final']['processing_fees']) . "</td><td>" . money_format('%!i',$response[2]['final']['principal_outstanding']) . "</td><td>" . money_format('%!i',$response[2]['final']['revenue']) . "</td><td>" . money_format('%!i',$response[2]['final']['subvention']) . "</td><td>" . money_format('%!i',$response[2]['final']['interest']) . "</td><td>" . money_format('%!i',$response[2]['final']['bounce_charges']) . "</td><td>" . money_format('%!i',$response[2]['final']['penal_interest']) . "</td></tr>";
        $data_table_month_1.= "</table>";
        $data_table_month_2.= "</table>";
        echo "<style type='text/css'>";
        echo "table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
  padding:3px;
}";

        echo "</style>";
        echo "<h1>Customer Wise Revenue Calculation</h1>";
        echo $data_table;
        echo "<br>";
        echo "<h1>Month Wise Revenue Calculation -  Pride Financial Services Private Limited</h1>";
        echo  $data_table_month_1;
        echo "<br>";
        echo "<h1>Month Wise Revenue Calculation -  Blacksoil Capital Private Limited</h1>";
        echo  $data_table_month_2;
        //return $response;

    }

    public function getAccruedProfitOnEmail(Request $request){

        try {

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

            $from = Carbon::createFromDate($request->get('year'), $request->get('month'))->startOfMonth()->toDateTimeString();
            $to = Carbon::createFromDate($request->get('year'), $request->get('month'))->endOfMonth()->toDateTimeString();
            $lender_id = $request->has('lender_id') ? [(int)$request->get('lender_id')] : [2];
            if($request->has('user_email')){
                $user_mail = [$request->get('user_email')];
            }


            $apps = StatusLogs::select('application_id')->where('status', 'disbursed')->where('created_at', '>=', $from)->where('created_at', '<=', $to)
                ->where('is_reversed',0)->distinct()->get();

            $app_ids = [];
            foreach($apps as $app){
                $app_ids[] = $app->application_id;
            }

            $status = ['cancelled', 'cancellation in-process'];
            $cancelled_cases = ConsumerApplication::with('cancelled', 'disbursed')->whereIn('state', $status)->whereIn('id', $app_ids)->get();

            $skip_ids = [];
            foreach($cancelled_cases as $case){
                if($case->disbursed->created_at->format('F/Y') == $case->cancelled->created_at->format('F/Y')){
                    $skip_ids[] = $case->id;
                }
            }

            $emisPayemetnsData = EmiPayment::whereIn('application_id',$app_ids)->whereNotIn('application_id',$skip_ids)->groupBy('application_id')->get(['application_id']);

//            $emisPayemetnsData = EmiPayment::groupBy('application_id')->get(['application_id']);
            $idsData1 = [];
            foreach($emisPayemetnsData as $emisPayemetnsDatum){
                $idsData1[] = $emisPayemetnsDatum->application_id;
            }

            $excludeMerchant = _env('APP_CONNECTION') ? [6478, 7516] : [7875];

            foreach(array_chunk($idsData1,10000) as $idsData){
//                (new Slack(new Request(['title' => 'Accrued Started', 'fields' => ['Status' => 1], 'group' => Slack::$STAGE_TESTING])))->send();
                $ii = 0;
                $response = array();
                $status = ['disbursed'];
                $consumerApplications1 = ConsumerApplicationRelation::with('logs', 'emi', 'emi.offer', 'emi_payment', 'lender')->whereIn('id', $idsData)->wherein('state', $status)->whereNotNull('merchant_id')->whereNotIn('merchant_id', $excludeMerchant)->whereNull('is_deleted')->whereIn('lender_id', $lender_id);

                $consumerApplications1 = $consumerApplications1->get();

                $status = ['nach registered', 'closed'];

                $consumerApplications = ConsumerApplicationRelation::with('logs', 'emi', 'emi.offer', 'emi_payment', 'lender')->whereIn('id', $idsData)->wherein('state', $status)->whereNotNull('merchant_id')->whereNotIn('merchant_id', $excludeMerchant)->whereNull('is_deleted')->whereIn('lender_id', $lender_id);

                if ($idsData){
                    $consumerApplications = $consumerApplications->whereIn('id', $idsData);
                }

                if ($request->has('lender_id') /*isset($event['lender_id'])*/){
                    $consumerApplications = $consumerApplications->where('lender_id', $request->get('lender_id')/*$event['lender_id']*/);
                }else{
                    $consumerApplications = $consumerApplications->whereIn('lender_id', [2]);
                }

                $consumerApplications = $consumerApplications->get();

                $consumerApplications = $consumerApplications1->merge($consumerApplications);

                $consumerDocument = new ConsumerDocument(new Request());
                //$merhchantcontroller = new MerchantController();

                (new Slack(new Request(['title' => 'Accrued Started count', 'fields' => ['Status' => count($consumerApplications)], 'group' => Slack::$STAGE_TESTING])))->send();


                foreach ($consumerApplications as $__Key => $consumerApplication) {
                    if (isset($consumerApplication->emi) and $consumerApplication->emi != null) {

                        if ($__Key == 1000 || $__Key == 2000 || $__Key == 5000 || $__Key == 8000 || $__Key == 10000 || $__Key == 14000 || $__Key == 1600){
                            (new Slack(new Request(['title' => 'Accrued Started count sub', 'fields' => ['Status' => $__Key], 'group' => Slack::$STAGE_TESTING])))->send();
                        }

                        $gstDetails = $consumerDocument->getGSTDetails(
                            [
                                'amount' => $consumerApplication->emi->processing_fee,
                                'state' => (isset($consumerApplication->permanent_address_state) && !empty($consumerApplication->permanent_address_state)) ? $consumerApplication->permanent_address_state : (isset($consumerApplication->current_address_state) && !empty($consumerApplication->current_address_state) ? $consumerApplication->current_address_state : '')
                            ]
                        );
                        foreach ($gstDetails as $gst) {
                            $response[$consumerApplication->id]['processing_fees_net_amount'] = $gst['net_amount'];
                            $response[$consumerApplication->id][$gst['taxes']] = $gst['gst_amount'];
                        }
                        if (isset($consumerApplication->logs->created_at)) {
                            $disbursed_month = date('Y-m', strtotime($consumerApplication->logs->created_at));
                        } else {
                            return $consumerApplication;
                        }
                        if (isset($response[$consumerApplication->lender_id][$disbursed_month]['processing_fees'])) {
                            $response[$consumerApplication->lender_id][$disbursed_month]['processing_fees'] = round($response[$consumerApplication->lender_id][$disbursed_month]['processing_fees'] + $response[$consumerApplication->id]['processing_fees_net_amount'], 2);
                        } else {
                            $response[$consumerApplication->lender_id][$disbursed_month]['processing_fees'] = round($response[$consumerApplication->id]['processing_fees_net_amount'], 2);
                        }
                        if ($response[$consumerApplication->id]['processing_fees_net_amount'] > 0) {
                            $response[$consumerApplication->id][date('Y-m-d', strtotime($consumerApplication->logs->created_at))]['processing_fees'] = round($response[$consumerApplication->id]['processing_fees_net_amount'], 2);
                        }
                        if ($consumerApplication->emi_payment) {
                            foreach ($consumerApplication->emi_payment as $emi_payment) {
                                $emimonth = date('Y-m', strtotime($emi_payment->emi_date));
                                if ($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[$consumerApplication->id][$emi_payment->emi_date]['penal_interest'] = round($penal_interest, 2);
                                        if (isset($response[$consumerApplication->lender_id][$emimonth]['penal_interest'])) {
                                            $response[$consumerApplication->lender_id][$emimonth]['penal_interest'] = round($response[$consumerApplication->lender_id][$emimonth]['penal_interest'] + $penal_interest, 2);
                                        } else {
                                            $response[$consumerApplication->lender_id][$emimonth]['penal_interest'] = round($penal_interest, 2);
                                        }
//                                $penal_interest_gstDetails = $consumerDocument->getGSTDetails(
//                                    [
//                                        'amount' => $penal_interest,
//                                        'state' => (isset($consumerApplication->permanent_address_state) && !empty($consumerApplication->permanent_address_state)) ? $consumerApplication->permanent_address_state : (isset($consumerApplication->current_address_state) && !empty($consumerApplication->current_address_state) ? $consumerApplication->current_address_state : '')
//                                    ]
//                                );
//                                if ($penal_interest_gstDetails) {
//                                    if ($penal_interest_gstDetails[0]['net_amount'] > 0) {
//                                        $response[$consumerApplication->id][$emi_payment->emi_date]['penal_interest'] = round($penal_interest_gstDetails[0]['net_amount'], 2);
//                                    }
//                                    if (isset($response[$consumerApplication->lender_id][$emimonth]['penal_interest'])) {
//                                        $response[$consumerApplication->lender_id][$emimonth]['penal_interest'] = round($response[$consumerApplication->lender_id][$emimonth]['penal_interest'] + $penal_interest_gstDetails[0]['net_amount'], 2);
//                                    } else {
//                                        $response[$consumerApplication->lender_id][$emimonth]['penal_interest'] = round($penal_interest_gstDetails[0]['net_amount'], 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;

                                        }
                                    }
                                    //$bounce_charge = ($emi_payment->charges_waived > ($emi_payment->delay_penalty + $emi_payment->bounce_charges)) ? $emi_payment->bounce_charges : ($emi_payment->bounce_charges - ($emi_payment->delay_penalty - $emi_payment->charges_waived));
                                    if ($bounce_charge > 0) {
                                        $response[$consumerApplication->id][$emi_payment->emi_date]['bounce_charges'] = round($bounce_charge, 2);

                                        if (isset($response[$consumerApplication->lender_id][$emimonth]['bounce_charges'])) {
                                            $response[$consumerApplication->lender_id][$emimonth]['bounce_charges'] = round($response[$consumerApplication->lender_id][$emimonth]['bounce_charges'] + $bounce_charge, 2);
                                        } else {
                                            $response[$consumerApplication->lender_id][$emimonth]['bounce_charges'] = round($bounce_charge, 2);
                                        }
//                                $bounce_charges_gstDetails = $consumerDocument->getGSTDetails(
//                                    [
//                                        'amount' => $bounce_charge,
//                                        'state' => (isset($consumerApplication->permanent_address_state) && !empty($consumerApplication->permanent_address_state)) ? $consumerApplication->permanent_address_state : (isset($consumerApplication->current_address_state) && !empty($consumerApplication->current_address_state) ? $consumerApplication->current_address_state : '')
//                                    ]
//                                );
//                                if ($bounce_charges_gstDetails) {
//                                    if ($bounce_charges_gstDetails[0]['net_amount'] > 0) {
//                                        $response[$consumerApplication->id][$emi_payment->emi_date]['bounce_charges'] = round($bounce_charges_gstDetails[0]['net_amount'], 2);
//                                    }
//
//                                    if (isset($response[$consumerApplication->lender_id][$emimonth]['bounce_charges'])) {
//                                        $response[$consumerApplication->lender_id][$emimonth]['bounce_charges'] = round($response[$consumerApplication->lender_id][$emimonth]['bounce_charges'] + $bounce_charges_gstDetails[0]['net_amount'], 2);
//                                    } else {
//                                        $response[$consumerApplication->lender_id][$emimonth]['bounce_charges'] = round($bounce_charges_gstDetails[0]['net_amount'], 2);
//                                    }
//                                }
                                    }
                                }

                            }
                        }
                        if (!isset($response[$consumerApplication->id]['name'])) {
                            $response[$consumerApplication->id]['name'] = $consumerApplication->name;
                        }
                        if (!isset($response[$consumerApplication->id]['lender'])) {
                            $response[$consumerApplication->id]['lender'] = $consumerApplication->lender->name;
                        }
                        if (!isset($response[$consumerApplication->id]['subvention_rate'])) {
                            $response[$consumerApplication->id]['subvention_rate'] = $consumerApplication->emi->subvention;
                        }
                        if (!isset($response[$consumerApplication->id]['approved_amount'])) {
                            $response[$consumerApplication->id]['approved_amount'] = $consumerApplication->approved_amount;
                        }
                        if (!isset($response[$consumerApplication->id]['disbursed_date'])) {
                            $response[$consumerApplication->id]['disbursed_date'] = Carbon::parse($consumerApplication->logs->created_at)->toDateTimeString();
                        }

                        $loanschedule = json_decode(json_encode($this->viewloanschedule($consumerApplication->id, 1, 1, 1, 1)));
                        $i = 1;
                        if (isset($loanschedule->schedule)) {
                            foreach ($loanschedule->schedule as $loanemi) {
                                $emimonth = date('Y-m', strtotime($loanemi->emi_date));
                                $emi_start_date = strtotime($emimonth . "-1");
                                $disbursement_date = date('Y-m-d', (strtotime($consumerApplication->logs->created_at)));

                                while ((strtotime($disbursement_date) < $emi_start_date) && $i == 1) {
                                    $disbursedmonth = date('Y-m', strtotime($disbursement_date));
                                    $response[$consumerApplication->id][$disbursement_date]['outstanding'] = round($loanschedule->summary->loan_outstanding, 2);

                                    if (isset($response[$consumerApplication->lender_id][$disbursedmonth]['principal_outstanding'])) {
                                        $response[$consumerApplication->lender_id][$disbursedmonth]['principal_outstanding'] = round($response[$consumerApplication->lender_id][$disbursedmonth]['principal_outstanding'] + $loanschedule->summary->loan_outstanding, 2);
                                    } else {
                                        $response[$consumerApplication->lender_id][$disbursedmonth]['principal_outstanding'] = round($loanschedule->summary->loan_outstanding, 2);

                                    }
                                    $disbursement_date = date('Y-m-d', (strtotime("+1 months", strtotime($disbursement_date))));
                                }
                                $i++;
                                $response[$consumerApplication->id][$loanemi->emi_date]['emi_amount'] = $loanemi->amount;
                                $response[$consumerApplication->id][$loanemi->emi_date]['outstanding'] = $loanemi->principal_outstanding;
                                $response[$consumerApplication->id][$loanemi->emi_date]['subvention_amount_balance'] = $loanemi->subvention_amount_balance;
                                $response[$consumerApplication->id][$loanemi->emi_date]['revenue'] = round($loanemi->irr, 2);
                                $response[$consumerApplication->id][$loanemi->emi_date]['interest'] = round($loanemi->interest, 2);
                                $response[$consumerApplication->id][$loanemi->emi_date]['subvention'] = round($loanemi->subvention, 2);


                                $response[$consumerApplication->id][$loanemi->emi_date]['principal_payable'] = round($loanemi->principal, 2);
                                if (isset($response[$consumerApplication->lender_id][$emimonth]['revenue'])) {
                                    $response[$consumerApplication->lender_id][$emimonth]['revenue'] = round($response[$consumerApplication->lender_id][$emimonth]['revenue'] + $response[$consumerApplication->id][$loanemi->emi_date]['revenue'], 2);
                                } else {
                                    $response[$consumerApplication->lender_id][$emimonth]['revenue'] = round($response[$consumerApplication->id][$loanemi->emi_date]['revenue'], 2);
                                }
                                if (isset($response[$consumerApplication->lender_id][$emimonth]['interest'])) {
                                    $response[$consumerApplication->lender_id][$emimonth]['interest'] = round($response[$consumerApplication->lender_id][$emimonth]['interest'] + $response[$consumerApplication->id][$loanemi->emi_date]['interest'], 2);
                                } else {
                                    $response[$consumerApplication->lender_id][$emimonth]['interest'] = round($response[$consumerApplication->id][$loanemi->emi_date]['interest'], 2);
                                }

                                if (isset($response[$consumerApplication->lender_id][$emimonth]['subvention'])) {
                                    $response[$consumerApplication->lender_id][$emimonth]['subvention'] = round($response[$consumerApplication->lender_id][$emimonth]['subvention'] + $response[$consumerApplication->id][$loanemi->emi_date]['subvention'], 2);
                                } else {
                                    $response[$consumerApplication->lender_id][$emimonth]['subvention'] = round($response[$consumerApplication->id][$loanemi->emi_date]['subvention'], 2);

                                }
                                if (isset($response[$consumerApplication->lender_id][$emimonth]['principal_outstanding'])) {
                                    $response[$consumerApplication->lender_id][$emimonth]['principal_outstanding'] = round($response[$consumerApplication->lender_id][$emimonth]['principal_outstanding'] + $loanemi->principal_outstanding, 2);
                                } else {
                                    $response[$consumerApplication->lender_id][$emimonth]['principal_outstanding'] = round($loanemi->principal_outstanding, 2);
                                }
                            }
                        } else {
                            (new Slack(new Request(['title' => 'Accured Renenue Loan Schedule ', 'fields' => ['ID' => $consumerApplication->id]])))->send();

                        }
                    } else {
                        (new Slack(new Request(['title' => 'Accured Renenue Emi Not Generated ', 'fields' => ['ID' => $consumerApplication->id]])))->send();

                    }
//            $irr = $merhchantcontroller->calculateIRR("", $consumerApplication->approved_amount, json_decode(($consumerApplication->emi), true), false);
//            $tenure = $consumerApplication->emi->remaining_emi;
//            $emi_date = $consumerApplication->emi->emi_date;
//            $count = 1;
//            $outsanding = ($consumerApplication->approved_amount * (1 - ($consumerApplication->emi->subvention / 100))) - $consumerApplication->emi->upfront_from_customer;
//            //return $consumerApplications[0]->emi;
//            if(!isset($response[$consumerApplication->id]['name'])){
//                $response[$consumerApplication->id]['name'] = $consumerApplication->name;
//            }
//            if(!isset($response[$consumerApplication->id]['lender'])){
//                $response[$consumerApplication->id]['lender'] = $consumerApplication->lender->name;
//            }
//            while ($count <= $tenure) {
//                if($count == 1){
//                    $emi_date = date('Y-m-d', strtotime($emi_date));
//                }else {
//                    $emi_date = date('Y-m-d', strtotime($emi_date . ' +1 month'));
//                }
//                    $emimonth = date('Y-m', strtotime($emi_date));
//
//                    $response[$consumerApplication->id][$emi_date]['emi_amount'] = $consumerApplication->emi->emi;
//                    $response[$consumerApplication->id][$emi_date]['outstanding'] = $outsanding;
//
//                    $response[$consumerApplication->id][$emi_date]['revenue'] = round(($response[$consumerApplication->id][$emi_date]['outstanding'] * $irr['irr']) / 100, 2);
//                    $response[$consumerApplication->id][$emi_date]['principal_payable'] = round($consumerApplication->emi->emi - $response[$consumerApplication->id][$emi_date]['revenue'],2);
//                    if(isset($response[$consumerApplication->lender_id][$emimonth]['revenue'])){
//                        $response[$consumerApplication->lender_id][$emimonth]['revenue'] = round($response[$consumerApplication->lender_id][$emimonth]['revenue'] + $response[$consumerApplication->id][$emi_date]['revenue'],2);
//                    }else{
//                        $response[$consumerApplication->lender_id][$emimonth]['revenue'] = round($response[$consumerApplication->id][$emi_date]['revenue'],2);
//                    }
//                    if(isset($response[$consumerApplication->lender_id][$emimonth]['principal_outstanding'])){
//                        $response[$consumerApplication->lender_id][$emimonth]['principal_outstanding'] = round($response[$consumerApplication->lender_id][$emimonth]['principal_outstanding'] + $outsanding,2);
//                    }else{
//                        $response[$consumerApplication->lender_id][$emimonth]['principal_outstanding'] = round($outsanding,2);
//                    }
//                    $outsanding = round($outsanding - $response[$consumerApplication->id][$emi_date]['principal_payable'], 2);
//                $count++;
//            }
                }


                $responseData[] = ['Application Id', 'Lender', 'Name', 'Emi_Date', 'principal_payable', 'emi_amount', 'outstanding', 'revenue', 'interest', 'subvention', 'Processing Fees', 'Bounce Charges', 'Penal Interest', 'Subvention Balance', 'Subvention Rate', 'Approved Rate', 'Disbursed Date'];
                //$data_table =  "<table><tr><th>Application Id</th><th>Lender</th><th>Name</th><th>Emi_Date</th><th>principal_payable</th><th>emi_amount</th><th>outstanding</th><th>revenue</th><th>interest</th><th>subvention</th><th>Processing Fees</th><th>Bounce Charges</th><th>Penal Interest</th><th>Subvention Balance</th><th>Subvention Rate</th><th>Approved Rate</th></tr>";

                foreach ($response as $key => $application) {
                    foreach ($application as $emi_date => $emi_details) {
                        if ((isset($emi_details['emi_amount']) || isset($emi_details['processing_fees']) || isset($emi_details['outstanding']) || isset($emi_details['bounce_charges']) || isset($emi_details['penal_interest'])) && $key != 1 and $key != 2) {
                            $responseData[] = ['id' => $key, 'lender_id' => ($application['lender'] ?? ""),
                                'name' => ($application['name'] ?? ""), 'EMI Date' => $emi_date,
                                'principal_payable' => money_format('%!i', ($emi_details['principal_payable'] ?? 0)),
                                'emi_amount' => money_format('%!i', ($emi_details['emi_amount'] ?? 0)),
                                'outstanding' => money_format('%!i', ($emi_details['outstanding'] ?? 0)),
                                'revenue' => money_format('%!i', ($emi_details['revenue'] ?? 0)),
                                'interest' => money_format('%!i', ($emi_details['interest'] ?? 0)),
                                'subvention' => money_format('%!i', ($emi_details['subvention'] ?? 0)),
                                'Processing Fees' => money_format('%!i', ($emi_details['processing_fees'] ?? 0)),
                                'Bounce Charges' => money_format('%!i', ($emi_details['bounce_charges'] ?? 0)),
                                'Penal Interest' => money_format('%!i', ($emi_details['penal_interest'] ?? 0)),
                                'Subvention Balance' => money_format('%!i', ($emi_details['subvention_amount_balance'] ?? 0)),
                                'Subvention Rate' => ($application['subvention_rate'] ?? 0),
                                'Approved Rate' => money_format('%!i', ($application['approved_amount'] ?? 0)),
                                'Disbursed Date' => $application['disbursed_date'] ?? ''
                            ];
                        }
                    }
                }
                setlocale(LC_MONETARY, 'en_IN.UTF-8');
                //(isset($emi_details['penal_interest']) ? $emi_details['penal_interest'] : 0) ;
                //$data_table.= "</table>";


                $response[1]['final']['processing_fees'] = 0;
                $response[1]['final']['principal_outstanding'] = 0;
                $response[1]['final']['revenue'] = 0;
                $response[1]['final']['interest'] = 0;
                $response[1]['final']['subvention'] = 0;
                $response[1]['final']['bounce_charges'] = 0;
                $response[1]['final']['penal_interest'] = 0;
                $response[2]['final']['processing_fees'] = 0;
                $response[2]['final']['principal_outstanding'] = 0;
                $response[2]['final']['revenue'] = 0;
                $response[2]['final']['interest'] = 0;
                $response[2]['final']['subvention'] = 0;
                $response[2]['final']['bounce_charges'] = 0;
                $response[2]['final']['penal_interest'] = 0;


                $responseDataMonth1[] = ['Month', 'Processing Fees', 'outstanding', 'Interest Subvention Revenue', 'Subvention Revenue', 'Interest Revenue', 'Bounce Charges', 'Penal Interest'];
                $responseDataMonth2[] = ['Month', 'Processing Fees', 'outstanding', 'Interest Subvention Revenue', 'Subvention Revenue', 'Interest Revenue', 'Bounce Charges', 'Penal Interest'];
                //$data_table_month_1 =  "<table><tr><th>Month</th><th>Processing Fees</th><th>outstanding</th><th>Interest Subvention Revenue</th><th>Subvention Revenue</th><th>Interest Revenue</th><th>Bounce Charges</th><th>Penal Interest</th></tr>";
                //$data_table_month_2 =  "<table><tr><th>Month</th><th>Processing Fees</th><th>outstanding</th><th>Interest Subvention Revenue</th><th>Subvention Revenue</th><th>Interest Revenue</th><th>Bounce Charges</th><th>Penal Interest</th></tr>";

                ksort($response);
                foreach ($response as $lender => $response_revenue) {
                    foreach ($response_revenue as $month => $revenue) {
                        if (isset($revenue['revenue']) || isset($revenue['processing_fees']) || isset($revenue['principal_outstanding']) || isset($revenue['bounce_charges']) || isset($revenue['penal_interest'])) {
                            if ($lender == 1) {
                                $responseDataMonth1[] = ['Month' => date('F - Y', strtotime($month)), 'Processing Fees' => money_format('%!i', ($revenue['processing_fees'] ?? 0)), 'outstanding' => money_format('%!i', ($revenue['principal_outstanding'] ?? 0)), 'Interest Subvention Revenue' => money_format('%!i', ($revenue['revenue'] ?? 0)), 'Subvention Revenue' => money_format('%!i', ($revenue['subvention'] ?? 0)), 'Interest Revenue' => money_format('%!i', ($revenue['interest'] ?? 0)), 'Bounce Charges' => money_format('%!i', ($revenue['bounce_charges'] ?? 0)), 'Penal Interest' => (money_format('%!i', $revenue['penal_interest'] ?? 0))];
                                $response[1]['final']['processing_fees'] = $response[1]['final']['processing_fees'] + ($revenue['processing_fees'] ?? 0);
                                $response[1]['final']['principal_outstanding'] = $response[1]['final']['principal_outstanding'] + ($revenue['principal_outstanding'] ?? 0);
                                $response[1]['final']['revenue'] = $response[1]['final']['revenue'] + ($revenue['revenue'] ?? 0);
                                $response[1]['final']['interest'] = $response[1]['final']['interest'] + ($revenue['interest'] ?? 0);
                                $response[1]['final']['subvention'] = $response[1]['final']['subvention'] + ($revenue['subvention'] ?? 0);

                                $response[1]['final']['bounce_charges'] = $response[1]['final']['bounce_charges'] + ($revenue['bounce_charges'] ?? 0);
                                $response[1]['final']['penal_interest'] = $response[1]['final']['penal_interest'] + ($revenue['penal_interest'] ?? 0);
                            } elseif ($lender == 2) {
                                $responseDataMonth2[] = ['Month' => date('F - Y', strtotime($month)), 'Processing Fees' => money_format('%!i', ($revenue['processing_fees'] ?? 0)), 'outstanding' => money_format('%!i', ($revenue['principal_outstanding'] ?? 0)), 'Interest Subvention Revenue' => money_format('%!i', ($revenue['revenue'] ?? 0)), 'Subvention Revenue' => money_format('%!i', ($revenue['subvention'] ?? 0)), 'Interest Revenue' => money_format('%!i', ($revenue['interest'] ?? 0)), 'Bounce Charges' => money_format('%!i', ($revenue['bounce_charges'] ?? 0)), 'Penal Interest' => (money_format('%!i', $revenue['penal_interest'] ?? 0))];
                                $response[2]['final']['processing_fees'] = $response[2]['final']['processing_fees'] + ($revenue['processing_fees'] ?? 0);
                                $response[2]['final']['principal_outstanding'] = $response[2]['final']['principal_outstanding'] + ($revenue['principal_outstanding'] ?? 0);
                                $response[2]['final']['revenue'] = $response[2]['final']['revenue'] + ($revenue['revenue'] ?? 0);
                                $response[2]['final']['interest'] = $response[2]['final']['interest'] + ($revenue['interest'] ?? 0);
                                $response[2]['final']['subvention'] = $response[2]['final']['subvention'] + ($revenue['subvention'] ?? 0);
                                $response[2]['final']['bounce_charges'] = $response[2]['final']['bounce_charges'] + ($revenue['bounce_charges'] ?? 0);
                                $response[2]['final']['penal_interest'] = $response[2]['final']['penal_interest'] + ($revenue['penal_interest'] ?? 0);
                            }
                        }
                    }
                }
                $responseDataMonth1[] = ['Total' => 'Total', 'processing_fees' => money_format('%!i', $response[1]['final']['processing_fees']), 'principal_outstanding' => money_format('%!i', $response[1]['final']['principal_outstanding']), 'revenue' => money_format('%!i', $response[1]['final']['revenue']), 'subvention' => money_format('%!i', $response[1]['final']['subvention']), 'interest' => money_format('%!i', $response[1]['final']['interest']), 'bounce_charges' => money_format('%!i', $response[1]['final']['bounce_charges']), 'penal_interest' => money_format('%!i', $response[1]['final']['penal_interest'])];
                //$data_table_month_1.=  "<tr><td>Total</td><td>" . money_format('%!i',$response[1]['final']['processing_fees']) . "</td><td>" . money_format('%!i',$response[1]['final']['principal_outstanding']) . "</td><td>" . money_format('%!i',$response[1]['final']['revenue']) . "</td><td>" . money_format('%!i',$response[1]['final']['subvention']) . "</td><td>" . money_format('%!i',$response[1]['final']['interest']) . "</td><td>" . money_format('%!i',$response[1]['final']['bounce_charges']) . "</td><td>" . money_format('%!i',$response[1]['final']['penal_interest']) . "</td></tr>";

                $responseDataMonth2[] = ['Total' => 'Total', 'processing_fees' => money_format('%!i', $response[2]['final']['processing_fees']), 'principal_outstanding' => money_format('%!i', $response[2]['final']['principal_outstanding']), 'revenue' => money_format('%!i', $response[2]['final']['revenue']), 'subvention' => money_format('%!i', $response[2]['final']['subvention']), 'interest' => money_format('%!i', $response[2]['final']['interest']), 'bounce_charges' => money_format('%!i', $response[2]['final']['bounce_charges']), 'penal_interest' => money_format('%!i', $response[2]['final']['penal_interest'])];
                //$data_table_month_2.=  "<tr><td>Total</td><td>" . money_format('%!i',$response[2]['final']['processing_fees']) . "</td><td>" . money_format('%!i',$response[2]['final']['principal_outstanding']) . "</td><td>" . money_format('%!i',$response[2]['final']['revenue']) . "</td><td>" . money_format('%!i',$response[2]['final']['subvention']) . "</td><td>" . money_format('%!i',$response[2]['final']['interest']) . "</td><td>" . money_format('%!i',$response[2]['final']['bounce_charges']) . "</td><td>" . money_format('%!i',$response[2]['final']['penal_interest']) . "</td></tr>";
                //$data_table_month_1.= "</table>";
                //$data_table_month_2.= "</table>";
                /*echo "<style type='text/css'>";
                echo "table, th, td {
          border: 1px solid black;
          border-collapse: collapse;
          padding:3px;
        }";*/

                //echo "</style>";
                //echo "<h1>Customer Wise Revenue Calculation</h1>";
                //echo $data_table;
                //echo "<br>";
                //echo "<h1>Month Wise Revenue Calculation -  Pride Financial Services Private Limited</h1>";
                //echo  $data_table_month_1;
                //echo "<br>";
                //echo "<h1>Month Wise Revenue Calculation -  K. M. Global Credit Private Limited</h1>";
                //echo  $data_table_month_2;
                //return $response;
            }

        }catch (\Exception $e){
            //$event->comment('Error - '.$e->getMessage().$e->getLine().$e->getFile());

//            if(!$ii) {
//                (new Slack(new Request(['title' => 'Accured Report Debug', 'fields' => ['e' => $e->getMessage(), 'l' => $e->getLine(), 't' => $e->getTraceAsString()], 'group' => Slack::$STAGE_TESTING])))->send();
//                $ii = 1;
//            }
        }

        (new Slack(new Request(['title' => 'Accrued Data Ready', 'fields' => ['count' => 1], 'group' => Slack::$STAGE_TESTING])))->send();

        if(isset($responseData)) {

            try {

//                if ($request->get('lender_id') /*isset($event['lender_id'])*/){
//                    return [$responseData, $responseDataMonth1, $responseDataMonth2];
//                }

                $request = new Request([
                    'sheet' => ['CWRC', 'MWRC-PFSPL', 'MWRC-KMGCPL'],
                    'data' => [$responseData, $responseDataMonth1, $responseDataMonth2]
                ]);

                $file = 'Accrued Revenue ' . Carbon::now()->toDateTimeString() . '.xls';

                (new Slack(new Request(['title' => 'Accrued Data Storing', 'fields' => ['count' => count($responseData)], 'group' => Slack::$STAGE_TESTING])))->send();

                //Excel::store(new ExporterMultipleSheet($request), $file);

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

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

                fclose($file);

                $path2 = storage_path()."/MWRC-PFSPL".time().".csv";
                $file = fopen($path2,"w");

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

                fclose($file);


                $path3 = storage_path()."/MWRC-KMGCPL".time().".csv";
                $file = fopen($path3,"w");

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

                fclose($file);


                $details = "Accrued Revenue \n CWRC - Customer Wise Revenue Calculation \n MWRC-PFSPL - Month Wise Revenue Calculation -  Pride Financial Services Private Limited \n MWRC-KMGCPL - Month Wise Revenue Calculation -  K. M. Global Credit Private Limited";

                $to_mail = ['surbhi@creditfair.in','ravi.mehta@creditfair.in'];
                if(isset($user_mail)){
                    $to_mail = array_merge($user_mail, $to_mail);
                }

                Mail::send('emails.reminders.basic_reminder',
                    ['body' => $details]
                    , function ($message) use ($file, $path1, $path2, $path3, $to_mail) {
                        $message->to($to_mail)->cc(['sunil@creditfair.in'])->subject('Accrued Revenue');
                        //$message->cc(['sunil@creditfair.in']);
                        //$message->cc(['skjha@kmglobal.in']);
                        $message->attach($path1, ['as' => 'Accrued_CWRC']);
                        $message->attach($path2, ['as' => 'MWRC-PFSPL']);
                        $message->attach($path3, ['as' => 'MWRC-KMGCPL']);
                    });

                (new Slack(new Request(['title' => 'Accrued Mail Sent', 'fields' => ['count' => count($responseData)], 'group' => Slack::$STAGE_TESTING])))->send();
            }catch (\Exception $e){
                (new Slack(new Request(['title' => 'Accured Report Debug 1', 'fields' => ['e' => $e->getMessage(), 'l' => $e->getLine(), 't' => $e->getTraceAsString()], 'group' => Slack::$STAGE_TESTING])))->send();
            }
        }
    }

    public function payment_cron_element(){
        $ids = ConsumerApplication::whereIn('state', ['disbursed','nach registered'])->whereNull('is_deleted')->get(['id']);
        $appsLists = [];
        foreach($ids as $__ids){
            $appsLists[] = $__ids->id;
        }

        $filename = "payment_cron_logs.txt";
        file_put_contents($filename, "App Count Total Check: ".count($appsLists)."\n", FILE_APPEND);


        $query = DB::select("select application_id from consumer_application_element where application_id in (select application_id
                                                                    from emi_payments
                                                                    where (emi_date < current_date()) and (amount_due > emi_amount)
                                                                      and application_id not in (select payment_transactions.application_id from payment_transactions where payment_for = 'Foreclosure' and payment_transactions.application_id = emi_payments.application_id)
                                                                    group by 1
                                                                    having sum(amount_due) > 0) and amount_over_due = 0 and application_id in (".implode(',', $appsLists).")");

        $ids = [];
        foreach($query as $item){
            $ids[] = $item->application_id;
        }

        file_put_contents($filename, "App Count Element Check: ".count($ids)."\n", FILE_APPEND);


        if($ids) {
            foreach (array_chunk($ids, 1000) as $_ids) {
                $loan_management = new LoanManagement();
                $loan_management->isCron = true;
                $loan_management->paymentCalculate($_ids);
            }
        }
    }

    public function payment_cron($id = ""){
        //$loan_management = new LoanManagement();
        //$loan_management = new PaymentEmi();
        $data = true;
        if($id == "") {

            if($id == 0){
                $ids = ConsumerApplication::whereIn('state', ['disbursed','nach registered'])->whereNull('is_deleted')->get(['id']);
                $appsLists = [];
                foreach($ids as $__ids){
                    $appsLists[] = $__ids->id;
                }
                $filename = "payment_cron_logs.txt";
                file_put_contents($filename, "App Count: ".count($appsLists)."\n", FILE_APPEND);

                foreach(array_chunk($appsLists,1000) as $_ids){
                    $loan_management = new LoanManagement();
                    $loan_management->isCron = true;
                    $loan_management->paymentCalculate($_ids);
                }
            }
        }else{
            $loan_management = new LoanManagement();
            $loan_management->paymentCalculate($id);
        }
        return $data;
    }
    public function dpd_report_cron(){
        try{
            $request = new Request(['log' => true]);
            $data = $this->getDPDReport($request);
            if($data){
                DpdLogs::insert($data);
            }
        }catch (\Exception $exception){
            (new Slack(new Request(['title' => 'DPD Loggin failed' , 'fields' => ['e' => $exception->getMessage(),'l' => $exception->getLine(),'t' => $exception->getTraceAsString()], 'group' => Slack::$STAGE_TESTING])))->send();
        }

    }

    public function getAppIdUnpaidCharges(){
        $current_date = Carbon::now()->subMonths(1);
        $month = $current_date->format('m');
        $year = $current_date->year;
        $date = $year.'-'.$month.'-30 00:00:00';
        $query = "SELECT e.application_id
FROM emi_payments e
         LEFT JOIN consumer_application l
                   ON e.application_id = l.id
         INNER JOIN (
    SELECT application_id, MAX(emi_date) AS emi_date
    FROM emi_payments
    GROUP BY application_id
) t ON e.application_id = t.application_id and t.emi_date <= '".$date."'
WHERE l.state IN ('disbursed', 'nach registered')
  AND l.merchant_id NOT IN (48, 6746, 6754, 9421)
  AND e.emi_date <= '".$date."'
  and e.amount_due > 0
  AND e.pre_emi_amount = 0
GROUP BY e.application_id
HAVING MIN(e.total_payable - (e.amount_due - IF(e.moratorium_amount > 0, e.moratorium_amount, 0)) >= e.emi_amount) = 1
   AND SUM(e.bounce_charges + e.delay_penalty - e.charges_waived) >= SUM(e.amount_due);";
        $response = DB::select($query);
        $appIds = [];
        foreach($response as $item){
            $appIds[] = $item->application_id;
        }

        return $appIds;
    }

    public function calculate_delay_days($application){
        $is_emi_receiving = ($application->total_payable - $application->amount_due) >= $application->emi_amount;
        if(!$is_emi_receiving) {
            return Carbon::now()->diffInDays($application->emi_date);
        }
        return 0;

    }

    public function getDPDReport(Request $request){
        $request->attributes->add(['raw' => true]);
        $is_Queue = $request->has('is_queue') ? true : false;
        ini_set('max_execution_time', -1);
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $_date = Carbon::now()->toDateTimeString();

        if((!Session::has('Export_Bucket_Wise_Data|-23') && $request->get('export')) || $request->has('internal')){
            Session::flash('error', 'You don\'t have permission to access the page');
            if(!$request->has('is_queue')) {
                return \redirect()->to('/admin');
            }
        }

        $data_type = $request->has('data_type') ? (int)$request->get('data_type') : 1;
        $lender_id = $request->get('lender_id') ? $request->get('lender_id') : '';
        $advisor = $request->get('advisor') ? $request->get('advisor') : '';
        $disbursement_date_from = $request->get('disbursement_date_from') ? $request->get('disbursement_date_from') : '';
        $disbursement_date_to = $request->get('disbursement_date_to') ? $request->get('disbursement_date_to') : '';
        $merchant_category = $request->get('merchant_category') ? $request->get('merchant_category') : '';
        $merchant_id = $request->get('merchant_id') ? $request->get('merchant_id') : '';
        $anchor_merchant = $request->get('anchor_merchant') ? $request->get('anchor_merchant') : '';
        $credit_manager = $request->get('credit_manager') ? $request->get('credit_manager') : '';
        $this->with_unpaid_charges = $request->has('with_unpaid_charges');



        $export = $request->get('export');
        $log_data = $request->get('log');
        $report_data = $request->get('report');

        $lenders_data_all = Lenders::all();
        $lenders_data_all_list = [];
        foreach($lenders_data_all as $_lenders_data_item){
            $lenders_data_all_list[$_lenders_data_item->id] = $_lenders_data_item->name;
        }

        $merchant_categories_data = MerchantCategory::all();
        $merchant_categories_data_list = [];
        foreach($merchant_categories_data as $merchant_categories_data_item){
            $merchant_categories_data_list[$merchant_categories_data_item->id] = $merchant_categories_data_item->name;
        }


        if($export && !$is_Queue){
            $jobs = new CampaignsJobProvider();
            $jobs->from = 'getDPDReport';
            $jobs->payload = json_encode(array_merge($request->input(), ['is_queue' => true, 'user_email' => Auth::user()->email]));
            $jobs->available_at = $_date;
            $jobs->application_id = 181;
            $jobs->created_at = $_date;
            $jobs->is_available = 0;
            $jobs->save();

            \Session::flash('success', 'DPD Report will be sent to your email address');
            $export = false;
        }

        if (!$is_Queue && !$request->has('internal') && !$request->has('log') && !$request->has('report')) {
            $responseDataLoanDefault = LoanDefault::where('data_type', $data_type)->where('created_at', '>=', Carbon::now()->startOfDay()->toDateTimeString())->orderBy('created_at', 'desc')->limit(8)->get();
            if (!isset($responseDataLoanDefault[0]->id)) {
                $responseDataLoanDefault = LoanDefault::where('data_type', $data_type)->orderBy('created_at', 'desc')->limit(8)->get();
            }

            if (isset($responseDataLoanDefault[0]->id)) {
                $response['merchants'] = Merchant::where('status', 'active')->where('is_guest_active', 1)->orderBy('merchant_name', 'asc')->get(['id', 'merchant_name']);
                $response['categories'] = MerchantCategory::get();
                $response['lenders'] = Lenders::orderBy('id', 'desc')->get();
                $response['users'] = User::where('user_type', '>=', 5)->get();
                $response['disbursement_date_from'] = $disbursement_date_from;
                $response['disbursement_date_to'] = $disbursement_date_to;
                $response['data_type'] = $data_type;
                $response['report']['total']['delay_days'] = 0;
                $response['report']['total']['over_due'] = 0;
                $response['report']['total']['outstanding'] = 0;
                $response['report']['total']['fldg_hold_count'] = 0;
                $response['report']['total']['total_fldg_hold_amount'] = 0;
                $response['report']['total']['application_ids'] = [];
                foreach ($responseDataLoanDefault->toArray() as $dpdReport) {
                    $response['report'][$dpdReport['bucket']] = $dpdReport;
                    $response['report']['total']['delay_days'] += $dpdReport['delay_days'];
                    $response['report']['total']['over_due'] += $dpdReport['over_due'];
                    $response['report']['total']['outstanding'] += $dpdReport['outstanding'];
                    $response['report']['total']['fldg_hold_count'] += $dpdReport['fldg_hold_count'];
                    $response['report']['total']['total_fldg_hold_amount'] += $dpdReport['total_fldg_hold_amount'];
                    $response['report']['total']['application_ids'] = array_merge($response['report']['total']['application_ids'], json_decode($dpdReport['application_id'], 1));
                }

                $totalArrayKey = $response['report']['total'];
                unset($response['report']['total']);
                $response['report']['total'] = $totalArrayKey;

                return view('admin.accounting.dpd', $response);
            }
        }


        if($is_Queue && $export) {
            return $this->sendDPDReport(array_filter([
                'lender_id' => $lender_id,
                'merchant_id' => $merchant_id,
                'anchor_merchant' => $anchor_merchant,
                'merchant_category' => $merchant_category,
                'advisor' => $advisor,
                'disbursement_date_from' => $disbursement_date_from,
                'disbursement_date_to' => $disbursement_date_to,
                'unpaid_charges' => $this->with_unpaid_charges ? 1 : 0,
                'email_list' => $request->get('user_email')
            ]));
        }

        $data = EmiPayment::with('application_element','application.proFormaInvoice','application.proFormaInvoice.fldg_category','application.emi','application.merchant','application.logs','moratoriums', 'application.last_payment_date', 'application.checkmandate')
            ->whereHas('application', function ($q) {
                $q->whereIn('state', ['disbursed','nach registered']);
            })->whereHas('application_element', function ($q) {
                $q->whereNull('foreclosure_date');
            });

        if($lender_id){
            $data = $data->whereHas('application', function ($q) use ($lender_id) {
                $q->where('lender_id', $lender_id);
            });
        }

//        Insurance reimbursement, klub and BNPL case merchants
        $data = $data->whereHas('application.merchant', function ($q) {
            $q->whereNotIn('merchant_id', [6865, 6600, 6517, 6598, 1806, 6478, 6746, 6754,6418]);
        });

        if($merchant_id || $merchant_category || $advisor) {
            $data = $data->whereHas('application', function ($q) use ($merchant_id, $merchant_category, $advisor) {
                if ($merchant_id) {
                    $q->where('merchant_id', $merchant_id);
                }
                if ($merchant_category) {
                    $q->where('purpose', $merchant_category);
                }
                if ($advisor) {
                    $q->where('created_by', $advisor);
                }
            });
        }
        if($anchor_merchant) {
            $data = $data->whereHas('application.merchant', function ($q) use ($anchor_merchant) {
                $q->where('anchor_merchant_id', $anchor_merchant);
            });
        }
        if($credit_manager) {
            $data = $data->whereHas('application.logs', function ($q) use ($credit_manager) {
                $q->where('user_id', $credit_manager)->where('status','approved');
            });
        }
        if($disbursement_date_from && $disbursement_date_to) {
            $data = $data->whereHas('application.logs', function ($q) use ($disbursement_date_from, $disbursement_date_to) {
                $disbursement_date_from = Carbon::createFromFormat('Y-m-d', $disbursement_date_from)->startOfDay()->toDateTimeString();
                $disbursement_date_to = Carbon::createFromFormat('Y-m-d', $disbursement_date_to)->endOfDay()->toDateTimeString();
                $q->where('created_at', '>=', $disbursement_date_from)->where('created_at', '<=', $disbursement_date_to)->where('status','disbursed');
            });
        }

        if($this->with_unpaid_charges){
            $data = $data->whereIn('application_id', $this->getAppIdUnpaidCharges());
        }else{
            $data = $data->where('payment_status','!=','success')->where('delay_days', '>', 15);
        }

        $data = $data->orderBy('application_id', 'desc')->get();

        $dpd = array();
        $status =  ['disbursed','nach registered'];
        $delay_days_app_wise =  [];

        foreach ($data as $payments){

            try {

                if ((!empty($payments->delay_days) && $payments->application && in_array($payments->application->state, $status) && $payments->delay_days > 15) || $this->with_unpaid_charges) {
                    $total_paid = $payments->total_payable - $payments->amount_due;
                    if ($total_paid < $payments->emi_amount || $this->with_unpaid_charges) {
                        $delay_days_number = $this->calculate_delay_days($payments);
                        $delay_days_app_wise[$payments->application_id][] = $delay_days_number;
                        if (isset($dpd[$payments->application_id])) {
                            if ($dpd[$payments->application_id]['delay_days'] < $delay_days_number || $this->with_unpaid_charges) {
                                $dpd[$payments->application_id]['delay_days'] = $delay_days_number;//$payments->delay_days;
                                $dpd[$payments->application_id]['over_due'] = $data_type == 1 ? $payments->application_element->amount_over_due : $payments->application_element->principal_due;
                                $dpd[$payments->application_id]['principal_due'] = $payments->application_element->principal_due;
                                $dpd[$payments->application_id]['outstanding'] = $data_type == 1 ? $payments->application_element->total_amount_due :$payments->application_element->total_principal_due;
                                $dpd[$payments->application_id]['total_principal_due'] = $payments->application_element->total_principal_due;
                                $dpd[$payments->application_id]['application_data'] = $payments;
                                $dpd[$payments->application_id]['fldg_applied'] =  $payments->application->proFormaInvoice->fldg_applied;
                                if($payments->application->proFormaInvoice->fldg_applied_category != 0){
                                    $dpd[$payments->application_id]['fldg'] = $payments->application->proFormaInvoice->fldg_category->fldg;
                                }
                                $dpd[$payments->application_id]['hold_amount'] = $payments->application_element->hold_amount;
                                $dpd[$payments->application_id]['approved_amount'] = $payments->application->approved_amount;
                            }
                        } else {
                            $dpd[$payments->application_id]['delay_days'] = $delay_days_number;//$payments->delay_days;
                            $dpd[$payments->application_id]['over_due'] = $data_type == 1 ? $payments->application_element->amount_over_due : $payments->application_element->principal_due;
                            $dpd[$payments->application_id]['principal_due'] = $payments->application_element->principal_due;
                            $dpd[$payments->application_id]['outstanding'] = $data_type == 1 ? $payments->application_element->total_amount_due :$payments->application_element->total_principal_due;
                            $dpd[$payments->application_id]['total_principal_due'] = $payments->application_element->total_principal_due;
                            $dpd[$payments->application_id]['application_data'] = $payments;
                            $dpd[$payments->application_id]['fldg_applied'] =  $payments->application->proFormaInvoice->fldg_applied;
                            if($payments->application->proFormaInvoice->fldg_applied_category != 0){
                                $dpd[$payments->application_id]['fldg'] = $payments->application->proFormaInvoice->fldg_category->fldg ?? '';
                            }
                            $dpd[$payments->application_id]['hold_amount'] = $payments->application_element->hold_amount;
                            $dpd[$payments->application_id]['approved_amount'] = $payments->application->approved_amount;
                        }
                    }
                }
            }catch (\Exception $exception){
                (new Slack(new Request(['title' => $log_data ? 'DPD Report Loop 1' : 'DPD Report while logging Loop 1' , 'fields' => ['e' => $exception->getMessage(),'l' => $exception->getLine(),'t' => $exception->getTraceAsString(), 'id' => $payments->application_id], 'group' => Slack::$STAGE_TESTING])))->send();
            }
        }
        $total_amount_till_date = array();
        $payment_transaction = PaymentTransaction::select('application_id','amount')->where('status', 'success')->whereNull('is_deleted_at')->whereNull('refunded_at')->orderBy('application_id', 'desc')->get();
        foreach($payment_transaction as $val){
            $total_amount_till_date[$val->application_id][] = $val->amount;
        }
        $fifteen = '0-15';
        $thirty = '15-30';
        $sixty = '30-60';
        $ninety = '60-90';
        $oneTwenty = '90-120';
        $oneFifty = '120-150';
        $oneEighty = '150-180';
        $threeSixtyFive = '180-365';
        $threeSixtyFivePlus = '365+';
        $response['report'][$threeSixtyFivePlus]['delay_days'] = 0;
        $response['report'][$threeSixtyFive]['delay_days'] = 0;
        $response['report'][$oneEighty]['delay_days'] = 0;
        $response['report'][$oneFifty]['delay_days'] = 0;
        $response['report'][$oneTwenty]['delay_days'] = 0;
        $response['report'][$ninety]['delay_days'] = 0;
        $response['report'][$sixty]['delay_days'] = 0;
        $response['report'][$thirty]['delay_days'] = 0;
        $response['report'][$fifteen]['delay_days'] = 0;
        $response['report'][$threeSixtyFivePlus]['over_due'] = 0;
        $response['report'][$threeSixtyFive]['over_due'] = 0;
        $response['report'][$oneEighty]['over_due'] = 0;
        $response['report'][$oneFifty]['over_due'] = 0;
        $response['report'][$oneTwenty]['over_due'] = 0;
        $response['report'][$ninety]['over_due'] = 0;
        $response['report'][$sixty]['over_due'] = 0;
        $response['report'][$thirty]['over_due'] = 0;
        $response['report'][$fifteen]['over_due'] = 0;
        $response['report'][$threeSixtyFivePlus]['principal_due'] = 0;
        $response['report'][$threeSixtyFive]['principal_due'] = 0;
        $response['report'][$oneEighty]['principal_due'] = 0;
        $response['report'][$oneFifty]['principal_due'] = 0;
        $response['report'][$oneTwenty]['principal_due'] = 0;
        $response['report'][$ninety]['principal_due'] = 0;
        $response['report'][$sixty]['principal_due'] = 0;
        $response['report'][$thirty]['principal_due'] = 0;
        $response['report'][$fifteen]['principal_due'] = 0;
        $response['report'][$threeSixtyFivePlus]['outstanding'] = 0;
        $response['report'][$threeSixtyFive]['outstanding'] = 0;
        $response['report'][$oneEighty]['outstanding'] = 0;
        $response['report'][$oneFifty]['outstanding'] = 0;
        $response['report'][$oneTwenty]['outstanding'] = 0;
        $response['report'][$ninety]['outstanding'] = 0;
        $response['report'][$sixty]['outstanding'] = 0;
        $response['report'][$thirty]['outstanding'] = 0;
        $response['report'][$fifteen]['outstanding'] = 0;
        $response['report'][$threeSixtyFivePlus]['total_principal_due'] = 0;
        $response['report'][$threeSixtyFive]['total_principal_due'] = 0;
        $response['report'][$oneEighty]['total_principal_due'] = 0;
        $response['report'][$oneFifty]['total_principal_due'] = 0;
        $response['report'][$oneTwenty]['total_principal_due'] = 0;
        $response['report'][$ninety]['total_principal_due'] = 0;
        $response['report'][$sixty]['total_principal_due'] = 0;
        $response['report'][$thirty]['total_principal_due'] = 0;
        $response['report'][$fifteen]['total_principal_due'] = 0;
        $response['report'][$threeSixtyFivePlus]['application_ids'] = array();
        $response['report'][$threeSixtyFive]['application_ids'] = array();
        $response['report'][$oneEighty]['application_ids'] = array();
        $response['report'][$oneFifty]['application_ids'] = array();
        $response['report'][$oneTwenty]['application_ids'] = array();
        $response['report'][$ninety]['application_ids'] = array();
        $response['report'][$sixty]['application_ids'] = array();
        $response['report'][$thirty]['application_ids'] = array();
        $response['report'][$fifteen]['application_ids'] = array();
        $response['report'][$threeSixtyFivePlus]['fldg_hold_count'] = 0;
        $response['report'][$threeSixtyFive]['fldg_hold_count'] = 0;
        $response['report'][$oneEighty]['fldg_hold_count'] = 0;
        $response['report'][$oneFifty]['fldg_hold_count'] = 0;
        $response['report'][$oneTwenty]['fldg_hold_count'] = 0;
        $response['report'][$ninety]['fldg_hold_count'] = 0;
        $response['report'][$sixty]['fldg_hold_count'] = 0;
        $response['report'][$thirty]['fldg_hold_count'] = 0;
        $response['report'][$fifteen]['fldg_hold_count'] = 0;
        $response['report'][$threeSixtyFivePlus]['fldg_hold_amount'] = 0;
        $response['report'][$threeSixtyFive]['fldg_hold_amount'] = 0;
        $response['report'][$oneEighty]['fldg_hold_amount'] = 0;
        $response['report'][$oneFifty]['fldg_hold_amount'] = 0;
        $response['report'][$oneTwenty]['fldg_hold_amount'] = 0;
        $response['report'][$ninety]['fldg_hold_amount'] = 0;
        $response['report'][$sixty]['fldg_hold_amount'] = 0;
        $response['report'][$thirty]['fldg_hold_amount'] = 0;
        $response['report'][$fifteen]['fldg_hold_amount'] = 0;
        $response['report']['total']['delay_days'] = 0;
        $response['report']['total']['over_due'] = 0;
        $response['report']['total']['principal_due'] = 0;
        $response['report']['total']['outstanding'] = 0;
        $response['report']['total']['total_principal_due'] = 0;
        $response['report']['total']['application_ids'] = array();
        $response['report']['total']['fldg_hold_count'] = 0;
        $response['report']['total']['fldg_hold_amount'] = 0;


        if($log_data || $report_data){
            $responseData = [];
//            $responseData[] = ['Application ID','Bucket', 'DPD days', 'First EMI Date','Last EMI Date',
//                'EMI Amount','No of EMI Due','Total due','Max Payable','Total Outstanding', 'Principal Outstanding','last payment date',
//                'last payment amount'];
        } else{
            $responseData[] = ['Application ID','Agreement Number','Name','Merchant Name', 'Segment', 'Lender', 'Loan Amount', 'Manager', 'FLDG DPD','Contact Number', 'Bucket', 'DPD days',
                'Email','DOB', 'PAN','Product Name','First EMI Date','Last EMI Date','EMI Amount','No of EMI Due','Total due','Max Payable','Total Outstanding','Total Paid Amount till date',
                'Employment Status','Company Name','Residental Address', 'Office Address','City','State','Pincode','Reference Name 1','Reference Number 1',
                'Reference Name 2','Reference Number 2','Principal Outstanding', 'Interest Outstanding', 'last payment date', 'last payment amount', 'UMRN No', 'Fldg/Hold Case (Yes / No)', 'Amount (if the hold /FLDG amount is available)'];
            if($this->with_unpaid_charges){
                array_push($responseData[0], 'Unpaid Bounce amount', 'Unpaid Penal amount', 'Total unpaid Bounce and Penal amount');
            }
        }

        $applicationController = new ConsumerApplicationController();
        $defaultData = [];

        //(new Slack(new Request(['title' => 'DPD Report Count', 'fields' => ['DPD Data Count' => count($dpd)], 'group' => Slack::$STAGE_TESTING])))->send();

        foreach ($dpd as $application=>$dpd_count){

            try {
                $days = 0;
                //$dpd_days = $dpd_count['delay_days'];
                $dpd_days = max($delay_days_app_wise[$application]);

                if ($dpd_days > 365) {
                    $response['report'][$threeSixtyFivePlus]['delay_days'] = $response['report'][$threeSixtyFivePlus]['delay_days'] + 1;
                    $response['report'][$threeSixtyFivePlus]['over_due'] = $response['report'][$threeSixtyFivePlus]['over_due'] + $dpd_count['over_due'];
                    $response['report'][$threeSixtyFivePlus]['principal_due'] = $response['report'][$threeSixtyFivePlus]['principal_due'] + $dpd_count['principal_due'];
                    $response['report'][$threeSixtyFivePlus]['outstanding'] = $response['report'][$threeSixtyFivePlus]['outstanding'] + $dpd_count['outstanding'];
                    $response['report'][$threeSixtyFivePlus]['total_principal_due'] = $response['report'][$threeSixtyFivePlus]['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report'][$threeSixtyFivePlus]['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report'][$threeSixtyFivePlus]['fldg_hold_count']  = $response['report'][$threeSixtyFivePlus]['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report'][$threeSixtyFivePlus]['fldg_hold_amount']  = $response['report'][$threeSixtyFivePlus]['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report'][$threeSixtyFivePlus]['fldg_hold_count']  = $response['report'][$threeSixtyFivePlus]['fldg_hold_count'] + 1;
                        $response['report'][$threeSixtyFivePlus]['fldg_hold_amount'] = $response['report'][$threeSixtyFivePlus]['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $response['report']['total']['delay_days'] = $response['report']['total']['delay_days'] + 1;
                    $response['report']['total']['over_due'] = $response['report']['total']['over_due'] + $dpd_count['over_due'];
                    $response['report']['total']['principal_due'] = $response['report']['total']['principal_due'] + $dpd_count['principal_due'];
                    $response['report']['total']['outstanding'] = $response['report']['total']['outstanding'] + $dpd_count['outstanding'];
                    $response['report']['total']['total_principal_due'] = $response['report']['total']['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report']['total']['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report']['total']['fldg_hold_amount']  = $response['report']['total']['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + 1;
                        $response['report']['total']['fldg_hold_amount'] = $response['report']['total']['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $days = '365+';
                }
                else if ($dpd_days > 180 && $dpd_days <= 365) {
                    $response['report'][$threeSixtyFive]['delay_days'] = $response['report'][$threeSixtyFive]['delay_days'] + 1;
                    $response['report'][$threeSixtyFive]['over_due'] = $response['report'][$threeSixtyFive]['over_due'] + $dpd_count['over_due'];
                    $response['report'][$threeSixtyFive]['principal_due'] = $response['report'][$threeSixtyFive]['principal_due'] + $dpd_count['principal_due'];
                    $response['report'][$threeSixtyFive]['outstanding'] = $response['report'][$threeSixtyFive]['outstanding'] + $dpd_count['outstanding'];
                    $response['report'][$threeSixtyFive]['total_principal_due'] = $response['report'][$threeSixtyFive]['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report'][$threeSixtyFive]['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report'][$threeSixtyFive]['fldg_hold_count']  = $response['report'][$threeSixtyFive]['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report'][$threeSixtyFive]['fldg_hold_amount']  = $response['report'][$threeSixtyFive]['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report'][$threeSixtyFive]['fldg_hold_count']  = $response['report'][$threeSixtyFive]['fldg_hold_count'] + 1;
                        $response['report'][$threeSixtyFive]['fldg_hold_amount'] = $response['report'][$threeSixtyFive]['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $response['report']['total']['delay_days'] = $response['report']['total']['delay_days'] + 1;
                    $response['report']['total']['over_due'] = $response['report']['total']['over_due'] + $dpd_count['over_due'];
                    $response['report']['total']['principal_due'] = $response['report']['total']['principal_due'] + $dpd_count['principal_due'];
                    $response['report']['total']['outstanding'] = $response['report']['total']['outstanding'] + $dpd_count['outstanding'];
                    $response['report']['total']['total_principal_due'] = $response['report']['total']['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report']['total']['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report']['total']['fldg_hold_amount']  = $response['report']['total']['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + 1;
                        $response['report']['total']['fldg_hold_amount'] = $response['report']['total']['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $days = 365;
                }
                elseif ($dpd_days > 150 && $dpd_days <= 180) {
                    $response['report'][$oneEighty]['delay_days'] = $response['report'][$oneEighty]['delay_days'] + 1;
                    $response['report'][$oneEighty]['over_due'] = $response['report'][$oneEighty]['over_due'] + $dpd_count['over_due'];
                    $response['report'][$oneEighty]['principal_due'] = $response['report'][$oneEighty]['principal_due'] + $dpd_count['principal_due'];
                    $response['report'][$oneEighty]['outstanding'] = $response['report'][$oneEighty]['outstanding'] + $dpd_count['outstanding'];
                    $response['report'][$oneEighty]['total_principal_due'] = $response['report'][$oneEighty]['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report'][$oneEighty]['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report'][$oneEighty]['fldg_hold_count']  = $response['report'][$oneEighty]['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report'][$oneEighty]['fldg_hold_amount']  = $response['report'][$oneEighty]['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report'][$oneEighty]['fldg_hold_count']  = $response['report'][$oneEighty]['fldg_hold_count'] + 1;
                        $response['report'][$oneEighty]['fldg_hold_amount'] = $response['report'][$oneEighty]['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $response['report']['total']['delay_days'] = $response['report']['total']['delay_days'] + 1;
                    $response['report']['total']['over_due'] = $response['report']['total']['over_due'] + $dpd_count['over_due'];
                    $response['report']['total']['principal_due'] = $response['report']['total']['principal_due'] + $dpd_count['principal_due'];
                    $response['report']['total']['outstanding'] = $response['report']['total']['outstanding'] + $dpd_count['outstanding'];
                    $response['report']['total']['total_principal_due'] = $response['report']['total']['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report']['total']['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report']['total']['fldg_hold_amount']  = $response['report']['total']['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + 1;
                        $response['report']['total']['fldg_hold_amount'] = $response['report']['total']['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $days = 180;
                }
                elseif ($dpd_days > 120 && $dpd_days <= 150) {
                    $response['report'][$oneFifty]['delay_days'] = $response['report'][$oneFifty]['delay_days'] + 1;
                    $response['report'][$oneFifty]['over_due'] = $response['report'][$oneFifty]['over_due'] + $dpd_count['over_due'];
                    $response['report'][$oneFifty]['principal_due'] = $response['report'][$oneFifty]['principal_due'] + $dpd_count['principal_due'];
                    $response['report'][$oneFifty]['outstanding'] = $response['report'][$oneFifty]['outstanding'] + $dpd_count['outstanding'];
                    $response['report'][$oneFifty]['total_principal_due'] = $response['report'][$oneFifty]['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report'][$oneFifty]['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report'][$oneFifty]['fldg_hold_count']  = $response['report'][$oneFifty]['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report'][$oneFifty]['fldg_hold_amount']  = $response['report'][$oneFifty]['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report'][$oneFifty]['fldg_hold_count']  = $response['report'][$oneFifty]['fldg_hold_count'] + 1;
                        $response['report'][$oneFifty]['fldg_hold_amount'] = $response['report'][$oneFifty]['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $response['report']['total']['delay_days'] = $response['report']['total']['delay_days'] + 1;
                    $response['report']['total']['over_due'] = $response['report']['total']['over_due'] + $dpd_count['over_due'];
                    $response['report']['total']['principal_due'] = $response['report']['total']['principal_due'] + $dpd_count['principal_due'];
                    $response['report']['total']['outstanding'] = $response['report']['total']['outstanding'] + $dpd_count['outstanding'];
                    $response['report']['total']['total_principal_due'] = $response['report']['total']['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report']['total']['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report']['total']['fldg_hold_amount']  = $response['report']['total']['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + 1;
                        $response['report']['total']['fldg_hold_amount'] = $response['report']['total']['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $days = 150;
                }
                elseif ($dpd_days > 90 && $dpd_days <= 120) {
                    $response['report'][$oneTwenty]['delay_days'] = $response['report'][$oneTwenty]['delay_days'] + 1;
                    $response['report'][$oneTwenty]['over_due'] = $response['report'][$oneTwenty]['over_due'] + $dpd_count['over_due'];
                    $response['report'][$oneTwenty]['principal_due'] = $response['report'][$oneTwenty]['principal_due'] + $dpd_count['principal_due'];
                    $response['report'][$oneTwenty]['outstanding'] = $response['report'][$oneTwenty]['outstanding'] + $dpd_count['outstanding'];
                    $response['report'][$oneTwenty]['total_principal_due'] = $response['report'][$oneTwenty]['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report'][$oneTwenty]['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report'][$oneTwenty]['fldg_hold_count']  = $response['report'][$oneTwenty]['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report'][$oneTwenty]['fldg_hold_amount']  = $response['report'][$oneTwenty]['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report'][$oneTwenty]['fldg_hold_count']  = $response['report'][$oneTwenty]['fldg_hold_count'] + 1;
                        $response['report'][$oneTwenty]['fldg_hold_amount'] = $response['report'][$oneTwenty]['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $response['report']['total']['delay_days'] = $response['report']['total']['delay_days'] + 1;
                    $response['report']['total']['over_due'] = $response['report']['total']['over_due'] + $dpd_count['over_due'];
                    $response['report']['total']['principal_due'] = $response['report']['total']['principal_due'] + $dpd_count['principal_due'];
                    $response['report']['total']['outstanding'] = $response['report']['total']['outstanding'] + $dpd_count['outstanding'];
                    $response['report']['total']['total_principal_due'] = $response['report']['total']['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report']['total']['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report']['total']['fldg_hold_amount']  = $response['report']['total']['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + 1;
                        $response['report']['total']['fldg_hold_amount'] = $response['report']['total']['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $days = 120;
                }
                elseif ($dpd_days > 60 && $dpd_days <= 90) {
                    $response['report'][$ninety]['delay_days'] = $response['report'][$ninety]['delay_days'] + 1;
                    $response['report'][$ninety]['over_due'] = $response['report'][$ninety]['over_due'] + $dpd_count['over_due'];
                    $response['report'][$ninety]['principal_due'] = $response['report'][$ninety]['principal_due'] + $dpd_count['principal_due'];
                    $response['report'][$ninety]['outstanding'] = $response['report'][$ninety]['outstanding'] + $dpd_count['outstanding'];
                    $response['report'][$ninety]['total_principal_due'] = $response['report'][$ninety]['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report'][$ninety]['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report'][$ninety]['fldg_hold_count']  = $response['report'][$ninety]['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report'][$ninety]['fldg_hold_amount']  = $response['report'][$ninety]['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report'][$ninety]['fldg_hold_count']  = $response['report'][$ninety]['fldg_hold_count'] + 1;
                        $response['report'][$ninety]['fldg_hold_amount'] = $response['report'][$ninety]['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $response['report']['total']['delay_days'] = $response['report']['total']['delay_days'] + 1;
                    $response['report']['total']['over_due'] = $response['report']['total']['over_due'] + $dpd_count['over_due'];
                    $response['report']['total']['principal_due'] = $response['report']['total']['principal_due'] + $dpd_count['principal_due'];
                    $response['report']['total']['outstanding'] = $response['report']['total']['outstanding'] + $dpd_count['outstanding'];
                    $response['report']['total']['total_principal_due'] = $response['report']['total']['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report']['total']['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report']['total']['fldg_hold_amount']  = $response['report']['total']['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + 1;
                        $response['report']['total']['fldg_hold_amount'] = $response['report']['total']['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $days = 90;
                }
                elseif ($dpd_days > 30 && $dpd_days <= 60) {
                    $response['report'][$sixty]['delay_days'] = $response['report'][$sixty]['delay_days'] + 1;
                    $response['report'][$sixty]['over_due'] = $response['report'][$sixty]['over_due'] + $dpd_count['over_due'];
                    $response['report'][$sixty]['principal_due'] = $response['report'][$sixty]['principal_due'] + $dpd_count['principal_due'];
                    $response['report'][$sixty]['outstanding'] = $response['report'][$sixty]['outstanding'] + $dpd_count['outstanding'];
                    $response['report'][$sixty]['total_principal_due'] = $response['report'][$sixty]['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report'][$sixty]['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report'][$sixty]['fldg_hold_count']  = $response['report'][$sixty]['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report'][$sixty]['fldg_hold_amount']  = $response['report'][$sixty]['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report'][$sixty]['fldg_hold_count']  = $response['report'][$sixty]['fldg_hold_count'] + 1;
                        $response['report'][$sixty]['fldg_hold_amount'] = $response['report'][$sixty]['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $response['report']['total']['delay_days'] = $response['report']['total']['delay_days'] + 1;
                    $response['report']['total']['over_due'] = $response['report']['total']['over_due'] + $dpd_count['over_due'];
                    $response['report']['total']['principal_due'] = $response['report']['total']['principal_due'] + $dpd_count['principal_due'];
                    $response['report']['total']['outstanding'] = $response['report']['total']['outstanding'] + $dpd_count['outstanding'];
                    $response['report']['total']['total_principal_due'] = $response['report']['total']['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report']['total']['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report']['total']['fldg_hold_amount']  = $response['report']['total']['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + 1;
                        $response['report']['total']['fldg_hold_amount'] = $response['report']['total']['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $days = 60;
                }
                elseif ($dpd_days > 15 && $dpd_days <= 30) {
                    $response['report'][$thirty]['delay_days'] = $response['report'][$thirty]['delay_days'] + 1;
                    $response['report'][$thirty]['over_due'] = $response['report'][$thirty]['over_due'] + $dpd_count['over_due'];
                    $response['report'][$thirty]['principal_due'] = $response['report'][$thirty]['principal_due'] + $dpd_count['principal_due'];
                    $response['report'][$thirty]['outstanding'] = $response['report'][$thirty]['outstanding'] + $dpd_count['outstanding'];
                    $response['report'][$thirty]['total_principal_due'] = $response['report'][$thirty]['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report'][$thirty]['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report'][$thirty]['fldg_hold_count']  = $response['report'][$thirty]['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report'][$thirty]['fldg_hold_amount']  = $response['report'][$thirty]['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report'][$thirty]['fldg_hold_count']  = $response['report'][$thirty]['fldg_hold_count'] + 1;
                        $response['report'][$thirty]['fldg_hold_amount'] = $response['report'][$thirty]['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $response['report']['total']['delay_days'] = $response['report']['total']['delay_days'] + 1;
                    $response['report']['total']['over_due'] = $response['report']['total']['over_due'] + $dpd_count['over_due'];
                    $response['report']['total']['principal_due'] = $response['report']['total']['principal_due'] + $dpd_count['principal_due'];
                    $response['report']['total']['outstanding'] = $response['report']['total']['outstanding'] + $dpd_count['outstanding'];
                    $response['report']['total']['total_principal_due'] = $response['report']['total']['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report']['total']['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report']['total']['fldg_hold_amount']  = $response['report']['total']['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + 1;
                        $response['report']['total']['fldg_hold_amount'] = $response['report']['total']['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $days = 30;
                }else if($this->with_unpaid_charges && $dpd_days >= 0 && $dpd_days <= 15){
                    $response['report'][$fifteen]['delay_days'] = $response['report'][$fifteen]['delay_days'] + 1;
                    $response['report'][$fifteen]['over_due'] = $response['report'][$fifteen]['over_due'] + $dpd_count['over_due'];
                    $response['report'][$fifteen]['principal_due'] = $response['report'][$fifteen]['principal_due'] + $dpd_count['principal_due'];
                    $response['report'][$fifteen]['outstanding'] = $response['report'][$fifteen]['outstanding'] + $dpd_count['outstanding'];
                    $response['report'][$fifteen]['total_principal_due'] = $response['report'][$fifteen]['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report'][$fifteen]['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report'][$fifteen]['fldg_hold_count']  = $response['report'][$fifteen]['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report'][$fifteen]['fldg_hold_amount']  = $response['report'][$fifteen]['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report'][$fifteen]['fldg_hold_count']  = $response['report'][$fifteen]['fldg_hold_count'] + 1;
                        $response['report'][$fifteen]['fldg_hold_amount'] = $response['report'][$fifteen]['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $response['report']['total']['delay_days'] = $response['report']['total']['delay_days'] + 1;
                    $response['report']['total']['over_due'] = $response['report']['total']['over_due'] + $dpd_count['over_due'];
                    $response['report']['total']['principal_due'] = $response['report']['total']['principal_due'] + $dpd_count['principal_due'];
                    $response['report']['total']['outstanding'] = $response['report']['total']['outstanding'] + $dpd_count['outstanding'];
                    $response['report']['total']['total_principal_due'] = $response['report']['total']['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report']['total']['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report']['total']['fldg_hold_amount']  = $response['report']['total']['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + 1;
                        $response['report']['total']['fldg_hold_amount'] = $response['report']['total']['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $days = 15;
                }

                if ($days && (($export && $is_Queue) || $log_data || $report_data)) {
                    $applicationItem = $dpd_count['application_data'];

                    //$paymentItem = $this->getPayments($request, $application);
                    $last_emi_date = '';
                    /*$emiDues = (new LoanManagement())->generateDues($application, 0, $applicationItem->application);
                    $emiDues = array_reverse($emiDues);
                    foreach ($emiDues as $item){
                        $last_emi_date = $item['due_date'];
                        break;
                    }*/
                    $EmiPayment = EmiPayment::where('application_id', $application)->orderBy('emi_date', 'desc')->first(['emi_date']);
                    if (isset($EmiPayment->emi_date)) {
                        $last_emi_date = $EmiPayment->emi_date;
                    }

                    $loanamount = ((isset($applicationItem->application->approved_amount) && $applicationItem->application->approved_amount != 0) ? $applicationItem->application->approved_amount : $applicationItem->application->loan_amount) - ($applicationItem->application->emi ? $applicationItem->application->emi->upfront_from_customer : 0);

                    $application_element = $applicationItem->application_element;

                    if (!$request->has('internal') && ($log_data || ($export && $is_Queue))) {
                        $pos_data = (new TestingController())->getPrincipalsOutstandingAdityaV2($_date, true, $application);
                    }

                    $interest_outstanding = 0;
                    $b_p_rate = EmiPayment::where('application_id', $application)->get(['bounce_charges','delay_penalty']);
                    foreach($b_p_rate as $val){
                        $interest_outstanding += $val->bounce_charges + $val->delay_penalty;
                    }

//                    $emi_schedules = (new LoanManagement())->generateDues($application, 0, $applicationItem->application);
//                    $emis_array = array();
//                    array_push($emis_array, -$loanamount);
//
//                    if (isset($emi_schedules)) {
//                        foreach ($emi_schedules as $schedule) {
//                            array_push($emis_array, $schedule['amount']);
//                        }
//                    }
//
//                    $rate = (Finance::irr($emis_array)) * 100;
//                    if ($rate < 0 || !isset($rate) || $rate == 'NAN') {
//                        $rate = 0;
//                    }
//
//                    $principal_outstanding = $loanamount;
//                    $interest = $principal_outstanding * ($rate/100);
//                    $principal = $applicationItem->application->emi->emi - $interest;
//                    $principal_outstanding = $principal_outstanding - $principal;

                    if($log_data){
                        $responseData[] =  [
                            'application_id' => $application,
                            'bucket' => $days,
                            'dpd_days' => $dpd_days,
                            'first_emi_date' => ($applicationItem->application->emi) ? $applicationItem->application->emi->emi_date : '',
                            'last_emi_date' => $last_emi_date,
                            'emi_amount' => $applicationItem->application->emi && $applicationItem->application->emi->emi ? $applicationItem->application->emi->emi : 0,
                            'no_of_emi_due' => $application_element->emi_pending,
                            'total_due_with_penalties' => $dpd_count['over_due'],
                            'max_payable' => $application_element->total_amount_due,
                            'total_outstanding' => $dpd_count['outstanding'],
                            'principal_outstanding' => $pos_data[0]['after foreclosure p os'] ?? 0,
                            'last_payment_date' => $applicationItem->application->last_payment_date->payment_date ?? null,
                            'last_payment_amount' => $applicationItem->application->last_payment_date->amount ?? 0,
                            'created_at' => $_date,
                        ];
                    }else if($report_data) {
                        $responseData[] = [
                            'application_id' => $application,
                            'lender_id' => $applicationItem->application->lender_id,
                            'name' => $applicationItem->application->name,
                            'category_id' => $applicationItem->application->merchant->category_id,
                            'merchant_id' => $applicationItem->application->merchant_id ?? '',
                            'bucket' => $days,
                            'dpd_days' => $dpd_days,
                            'first_emi_date' => ($applicationItem->application->emi) ? $applicationItem->application->emi->emi_date : '',
                            'last_emi_date' => $last_emi_date,
                            'emi_amount' => $applicationItem->application->emi && $applicationItem->application->emi->emi ? $applicationItem->application->emi->emi : 0,
                            'no_of_emi_due' => $application_element->emi_pending,
                            'total_due_with_panelties' => $dpd_count['over_due'],
                            'max_payable' => $application_element->total_amount_due,
                            'total_outstanding' => $dpd_count['outstanding'],
                            'principal_outstanding' => $pos_data[0]['after foreclosure p os'] ?? '',
                            'interest_outstanding' => $interest_outstanding ?? '',
                        ];
                    }else {

                        $company_name = ($applicationItem->application && isset($applicationItem->application->company_name)) ? $applicationItem->application->company_name : '';

                        if ($company_name && !filter_var($company_name, FILTER_VALIDATE_INT) === false) {
                            $_company_name = Company::where('id', $company_name)->first(['company']);
                            if (isset($_company_name->company)) {
                                $company_name = $_company_name->company;
                            }
                        }

                        $product_name = $applicationItem->application_element ? $applicationItem->application_element->product_name : '';

                        $product_name = $applicationController->getProductName($product_name);
                        // Fldg/Hold Amount Calculation
                        $fh_amount = 0;
                        if($dpd_count['fldg_applied'] == 1){
                            $fh_amount = ($applicationItem->application->approved_amount * $dpd_count['fldg'])/100;
                        }
                        if($dpd_count['hold_amount'] != 0){
                            $fh_amount = $dpd_count['hold_amount'];
                        }
                        if($dpd_count['fldg_applied'] == 1 && $dpd_count['hold_amount'] != 0){
                            $fh_amount = (($applicationItem->application->approved_amount * $dpd_count['fldg'])/100) + $dpd_count['hold_amount'];
                        }

                        $agreement_no = ($applicationItem->application->proFormaInvoice) ? $applicationItem->application->proFormaInvoice->loan_application_no : '';

                        if($agreement_no === null){
                            $agreement_no = (new ConsumerApplicationController)->getLoanApplicationID($applicationItem->application->id, $applicationItem->application->merchant);
                            ProFormaInvoice::where('application_id', $applicationItem->application->id)->update(['loan_application_no'=>$agreement_no]);
                        }else if($agreement_no === ''){
                            $agreement_no = (new ConsumerApplicationController)->getLoanApplicationID($applicationItem->application->id, $applicationItem->application->merchant);
                            $newProforma = new ProFormaInvoice();
                            $newProforma->application_id = $applicationItem->application->id;
                            $newProforma->loan_application_no = $agreement_no;
                            $merchantInsuranceConfig = $this->getMerchantInsuranceConfig($applicationItem->application->id);
                            $newProforma->insurance_premium_by_merchant = $merchantInsuranceConfig['insurance_premium_by_merchant'];
                            $newProforma->insurance_premium_applicable = $merchantInsuranceConfig['insurance_premium_applicable'];
                            $newProforma->insurance_coverage = $merchantInsuranceConfig['insurance_coverage'];
                            $newProforma->processing_fee_by_merchant = $merchantInsuranceConfig['processing_fee_by_merchant'];
                            $newProforma->save();
                        }

                        $downPayment = $applicationItem->application->emi->upfront_from_customer ?? 0;

                        $res_data = [
                            'application_id' => $application,
                            'agreement_number' => $agreement_no,
                            'name' => $applicationItem->application->name,
                            'merchant_name' => ($applicationItem->application->merchant) ? $applicationItem->application->merchant->merchant_name : '',
                            'segment' => $merchant_categories_data_list[$applicationItem->application->purpose] ?? '',
                            'lender' => $lenders_data_all_list[$applicationItem->application->lender_id] ?? '',
                            'loan_amount' => ($applicationItem->application->approved_amount - $downPayment),
                            'manager' => '',
                            'fldg_dpd' => '',
                            'contact_no' => $applicationItem->application->mobile_number,
                            'bucket' => $days,
                            'dpd_days' => $dpd_days,
                            'email_id' => $applicationItem->application->email,
                            'DOB' => $applicationItem->application->dob,
                            'PAN' => $applicationItem->application->pan_card,
                            'product_name' => $product_name,
                            'first_emi_date' => ($applicationItem->application->emi) ? $applicationItem->application->emi->emi_date : '',
                            'last_emi_date' => $last_emi_date,
                            'emi_amount' => $applicationItem->application->emi && $applicationItem->application->emi->emi ? $applicationItem->application->emi->emi : 0,
                            'no_of_emi_due' => $application_element->emi_pending,
                            'total_due_with_panelties' => $dpd_count['over_due'],
                            'max_payable' => $application_element->total_amount_due,
                            'total_outstanding' => $dpd_count['outstanding'],
                            'total_paid_amount_till_date' => isset($total_amount_till_date[$application]) && !empty($total_amount_till_date[$application]) ? array_sum($total_amount_till_date[$application]) : '0',
                            'employment_status' => $applicationItem->application->employee_status,
                            'company_name' => $company_name,
                            'address' => $applicationItem->application->current_address_line_1 . ' ' . $applicationItem->application->current_address_landmark,
                            'office_addr' => $applicationItem->application->work_address_line_1 . ' ' . $applicationItem->application->work_address_landmark,
                            'city' => $applicationItem->application->current_address_city,
                            'state' => $applicationItem->application->current_address_state,
                            'pincode' => $applicationItem->application->current_address_pincode,
                            'reference Name 1' => $applicationItem->application_element->reference_name_1,
                            'reference Number 1' => $applicationItem->application_element->reference_contact_1,
                            'reference Name 2' => $applicationItem->application_element->reference_name_2,
                            'reference Number 2' => $applicationItem->application_element->reference_contact_2,
                            'principal_outstanding' => $pos_data[0]['after foreclosure p os'] ?? '',
                            'interest_outstanding' => $interest_outstanding ?? '',
                            'last_payment_date' => $applicationItem->application->last_payment_date->payment_date ?? '',
                            'last_payment_amount' => $applicationItem->application->last_payment_date->amount ?? '',
                            'umrn_no' => $applicationItem->application->checkmandate->umrn ?? '',
                            'fldg_hold_case' => ($dpd_count['fldg_applied'] == 1 || $dpd_count['hold_amount'] != 0) ? 'Yes' : 'No',
                            'fldg_hold_amount' => $fh_amount
                        ];

                        if($this->with_unpaid_charges){
                            $unpaidCharges = $this->getUnpaidCharges($applicationItem->application->id);
                            $res_data = array_merge($res_data, [
                                'unpaid_bounce_amount' => $unpaidCharges['unpaid_bounce_amount'],
                                'unpaid_penal_amount' => $unpaidCharges['unpaid_penal_amount'],
                                'total_unpaid_bounce_and_penal_amount' => $unpaidCharges['unpaid_charges_total']
                            ]);
                        }

                        $responseData[] = $res_data;
                    }
                }

            }catch (\Exception $exception){
                //(new Slack(new Request(['title' => $log_data ? 'DPD Report Loop 2' : 'DPD Report while logging Loop 2', 'fields' => ['e' => $exception->getMessage(),'l' => $exception->getLine(),'t' => $exception->getTraceAsString(), 'id' => $application], 'group' => Slack::$STAGE_TESTING])))->send();
            }
        }


        if ($request->has('internal')) {
            foreach ($response['report'] as $_bucket => $dpdItem) {
                if ($_bucket != 'total') {
                    $defaultData[] = ['bucket' => $_bucket, 'application_id' => json_encode($dpdItem['application_ids']), 'delay_days' => $dpdItem['delay_days'], 'over_due' => $dpdItem['over_due'], 'outstanding' => $dpdItem['outstanding'], 'data_type' => 1, 'fldg_hold_count' => $dpdItem['fldg_hold_count'],'total_fldg_hold_amount' => $dpdItem['fldg_hold_amount'], 'created_at' => $_date];
                    $defaultData[] = ['bucket' => $_bucket, 'application_id' => json_encode($dpdItem['application_ids']), 'delay_days' => $dpdItem['delay_days'], 'over_due' => $dpdItem['principal_due'], 'outstanding' => $dpdItem['total_principal_due'], 'data_type' => 2, 'fldg_hold_count' => $dpdItem['fldg_hold_count'],'total_fldg_hold_amount' => $dpdItem['fldg_hold_amount'], 'created_at' => $_date];
                }
            }
        }


        if($defaultData && $request->has('internal')) {
            foreach (array_chunk($defaultData,1000) as $t) {
                LoanDefault::insert($t);
            }
            return false;
        }

        //(new Slack(new Request(['title' => 'DPD Report Prepareing File', 'fields' => ['DPD Data Count' => count($dpd)], 'group' => Slack::$STAGE_TESTING])))->send();
        if($export && $request->has('is_queue')){
            $time = time();
            if ($responseData){
                $request = new Request(['data' => $responseData, 'sheet' => 'Sheet1', 'user_email' => $request->get('user_email')]);
                if($is_Queue){

                    (new Slack(new Request(['title' => 'DPD Report Sending File', 'fields' => ['DPD Data Count' => count($responseData)], 'group' => Slack::$STAGE_TESTING])))->send();
                    try {
                        $filePath = storage_path().'/app/exported/'.$time . '_bucket_wise_break.csv';
                        $file = fopen($filePath,"w");

                        foreach ($responseData as $line) {
                            fputcsv($file, $line);
                        }
                        fclose($file);
//                        Excel::store((new Exporter($request)), 'exported/' . $filePath);
                        // Storage::disk('s3')->put('/collection/exported/'.$filePath, file_get_contents(storage_path('app/exported/' . $filePath)));
                        $dpd_file = file_get_contents($filePath);
                        $this->sendDPDReportOverMail($dpd_file, $request);
                        unlink(storage_path().'/app/exported/' . $filePath);
                        (new Slack(new Request(['title' => 'DPD Report Sent', 'fields' => ['DPD Data Count' => count($responseData)], 'group' => Slack::$STAGE_TESTING])))->send();
                    }catch (\Exception $exception){
                        (new Slack(new Request(['title' => 'DPD Report Sent Error', 'fields' => ['e' => $exception->getMessage(),'l' => $exception->getLine(),'t' => $exception->getTraceAsString()], 'group' => Slack::$STAGE_TESTING])))->send();
                    }
                    return true;
                }else{
                    return Excel::download((new Exporter($request)), 'bucket_wise_break.xls');
                }
            }
        }elseif($log_data || $report_data){
            if($responseData){
                return $responseData;
            }
            return false;
        }


        $approverData = StatusLogs::where('status','approved')->get();
        $approverDataIds = [];
        foreach ($approverData as $item){
            if(!in_array($item->user_id, $approverDataIds)) {
                $approverDataIds[] = $item->user_id;
            }
        }

        $credit_managers = User::whereIn('id', $approverDataIds)->get(['id','name']);

        $response['disbursement_date_from'] = $disbursement_date_from;
        $response['disbursement_date_to'] = $disbursement_date_to;
        $response['merchant_category'] = $merchant_category;
        $response['merchant_id'] = $merchant_id;
        $response['lender_id'] = $lender_id;
        $response['data_type'] = $data_type;
        $response['anchor_merchant'] = $anchor_merchant;
        $response['credit_manager'] = $credit_manager;
        $response['advisor'] = $advisor;
        $response['credit_managers'] = $credit_managers;
        //return(array) $response;
        return view('admin.accounting.dpd', $response);
        //return json_encode($response);
    }

    public function getUnpaidCharges($id){

        $unpaidCharges = DB::select("WITH payment_transactions_cte AS (
                SELECT application_id, emi_payment_id, payment_date, amount, payment_for
                FROM payment_transactions
                WHERE deleted_at IS NULL
                AND is_deleted_at IS NULL
                AND refunded_at IS NULL
                AND payment_for IN ('Pre-EMI','EMI','Forclouser','Foreclosed','Foreclosure','Write-off')
            ),
            emi_payments_cte AS (
                SELECT
                    ep.application_id,
                    ep.emi_date,
                    ep.pre_emi_amount,
                    ep.emi_amount,
                    ep.bounce_charges,
                    ep.delay_penalty,
                    ep.charges_waived,
                    COALESCE(SUM(pt.amount), 0) as amount_paid
                FROM emi_payments ep
                LEFT JOIN payment_transactions_cte pt ON pt.emi_payment_id = ep.id
                WHERE ep.deleted_at IS NULL
                AND ep.emi_date < CURDATE()
                GROUP BY ep.application_id, ep.emi_date, ep.pre_emi_amount,
                         ep.emi_amount, ep.bounce_charges, ep.delay_penalty, ep.charges_waived
            ),
            bounce_penal_due_cte AS (
                SELECT
                    application_id,
                    emi_date,
                    pre_emi_amount,
                    emi_amount,
                    bounce_charges,
                    delay_penalty,
                    charges_waived,
                    amount_paid,
                    CASE
                        WHEN application_id IN (
                            SELECT DISTINCT application_id
                            FROM payment_transactions_cte
                            WHERE payment_for IN ('Forclouser','Foreclosed','Foreclosure','Write-off')
                        ) THEN 0
                        ELSE GREATEST(bounce_charges - GREATEST(0, (amount_paid + charges_waived) - pre_emi_amount - emi_amount), 0)
                    END as bounce_due,
                    CASE
                        WHEN application_id IN (
                            SELECT DISTINCT application_id
                            FROM payment_transactions_cte
                            WHERE payment_for IN ('Forclouser','Foreclosed','Foreclosure','Write-off')
                        ) THEN 0
                        ELSE GREATEST(delay_penalty - GREATEST(0, (amount_paid + charges_waived) - pre_emi_amount - emi_amount - bounce_charges), 0)
                    END as penal_due
                FROM emi_payments_cte
            )
SELECT
    application_id,
    SUM(bounce_due) as bounce_due,
    SUM(penal_due) as penal_due,
    SUM(bounce_due) + SUM(penal_due) as bounce_penal_due
FROM bounce_penal_due_cte
WHERE application_id = ".$id."
GROUP BY application_id");

        return [
          'unpaid_penal_amount' => $unpaidCharges[0]->penal_due ?? 0,
          'unpaid_bounce_amount' => $unpaidCharges[0]->bounce_due ?? 0,
          'unpaid_charges_total' => $unpaidCharges[0]->bounce_penal_due ?? 0,
        ];
    }

    public function getDPDReportV1(Request $request){
        $request->attributes->add(['raw' => true]);
        $is_Queue = $request->has('is_queue') ? true : false;
        ini_set('max_execution_time', -1);
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $_date = Carbon::now()->toDateTimeString();

        if((!Session::has('Export_Bucket_Wise_Data|-23') && $request->get('export')) || $request->has('internal')){
            Session::flash('error', 'You don\'t have permission to access the page');
            if(!$request->has('is_queue')) {
                return \redirect()->to('/admin');
            }
        }

        $data_type = $request->has('data_type') ? (int)$request->get('data_type') : 1;
        $lender_id = $request->get('lender_id') ? $request->get('lender_id') : '';
        $advisor = $request->get('advisor') ? $request->get('advisor') : '';
        $disbursement_date_from = $request->get('disbursement_date_from') ? $request->get('disbursement_date_from') : '';
        $disbursement_date_to = $request->get('disbursement_date_to') ? $request->get('disbursement_date_to') : '';
        $merchant_category = $request->get('merchant_category') ? $request->get('merchant_category') : '';
        $merchant_id = $request->get('merchant_id') ? $request->get('merchant_id') : '';
        $anchor_merchant = $request->get('anchor_merchant') ? $request->get('anchor_merchant') : '';
        $credit_manager = $request->get('credit_manager') ? $request->get('credit_manager') : '';

        $export = $request->get('export');
        $log_data = $request->get('log');
        $report_data = $request->get('report');


        $lenders_data_all = Lenders::all();
        $lenders_data_all_list = [];
        foreach($lenders_data_all as $_lenders_data_item){
            $lenders_data_all_list[$_lenders_data_item->id] = $_lenders_data_item->name;
        }

        $merchant_categories_data = MerchantCategory::all();
        $merchant_categories_data_list = [];
        foreach($merchant_categories_data as $merchant_categories_data_item){
            $merchant_categories_data_list[$merchant_categories_data_item->id] = -$merchant_categories_data_item->name;
        }


        if($export && !$is_Queue){
            $jobs = new CampaignsJobProvider();
            $jobs->from = 'getDPDReport';
            $jobs->payload = json_encode(array_merge($request->input(), ['is_queue' => true, 'user_email' => Auth::user()->email]));
            $jobs->available_at = $_date;
            $jobs->application_id = 181;
            $jobs->created_at = $_date;
            $jobs->is_available = 0;
            $jobs->save();

            \Session::flash('success', 'DPD Report will be sent to your email address');
            $export = false;
        }

        if (!$is_Queue && !$request->has('internal') && !$request->has('log') && !$request->has('report')) {
            $responseDataLoanDefault = LoanDefault::where('data_type', $data_type)->where('created_at', '>=', Carbon::now()->startOfDay()->toDateTimeString())->orderBy('created_at', 'desc')->limit(9)->get();
            if (!isset($responseDataLoanDefault[0]->id)) {
                $responseDataLoanDefault = LoanDefault::where('data_type', $data_type)->orderBy('created_at', 'desc')->limit(9)->get();
            }

            if (isset($responseDataLoanDefault[0]->id)) {
                $response['merchants'] = Merchant::where('status', 'active')->where('is_guest_active', 1)->orderBy('merchant_name', 'asc')->get(['id', 'merchant_name']);
                $response['categories'] = MerchantCategory::get();
                $response['lenders'] = Lenders::orderBy('id', 'desc')->get();
                $response['users'] = User::where('user_type', '>=', 5)->get();
                $response['disbursement_date_from'] = $disbursement_date_from;
                $response['disbursement_date_to'] = $disbursement_date_to;
                $response['data_type'] = $data_type;
                $response['report']['total']['delay_days'] = 0;
                $response['report']['total']['over_due'] = 0;
                $response['report']['total']['outstanding'] = 0;
                $response['report']['total']['fldg_hold_count'] = 0;
                $response['report']['total']['total_fldg_hold_amount'] = 0;
                $response['report']['total']['application_ids'] = [];
                foreach ($responseDataLoanDefault->toArray() as $dpdReport) {
                    $response['report'][$dpdReport['bucket']] = $dpdReport;
                    $response['report']['total']['delay_days'] += $dpdReport['delay_days'];
                    $response['report']['total']['over_due'] += $dpdReport['over_due'];
                    $response['report']['total']['outstanding'] += $dpdReport['outstanding'];
                    $response['report']['total']['fldg_hold_count'] += $dpdReport['fldg_hold_count'];
                    $response['report']['total']['total_fldg_hold_amount'] += $dpdReport['total_fldg_hold_amount'];
                    $response['report']['total']['application_ids'] = array_merge($response['report']['total']['application_ids'], json_decode($dpdReport['application_id'], 1));
                }

                $totalArrayKey = $response['report']['total'];
                unset($response['report']['total']);
                $response['report']['total'] = $totalArrayKey;
                return view('admin.accounting.dpd', $response);
            }
        }

        $data = EmiPayment::with('application_element', 'application.proFormaInvoice', 'application.proFormaInvoice.fldg_category', 'application.emi', 'application.merchant', 'application.logs', 'moratoriums', 'application.last_payment_date', 'application.checkmandate')
            ->whereHas('application', function ($q) use ($lender_id, $merchant_id, $merchant_category, $advisor, $anchor_merchant, $credit_manager, $disbursement_date_from, $disbursement_date_to) {
                $q->whereIn('state', ['disbursed', 'nach registered'])
                    ->when($lender_id, function ($q) use ($lender_id) {
                        $q->where('lender_id', $lender_id);
                    })
                    ->whereHas('merchant', function ($q) {
                        $q->whereNotIn('merchant_id', [6865, 6600, 6517, 6598, 1806, 6478, 6746, 6754, 6418]);
                    })
                    ->when($merchant_id || $merchant_category || $advisor, function ($q) use ($merchant_id, $merchant_category, $advisor) {
                        $q->where(function ($q) use ($merchant_id, $merchant_category, $advisor) {
                            if ($merchant_id) {
                                $q->where('merchant_id', $merchant_id);
                            }
                            if ($merchant_category) {
                                $q->where('purpose', $merchant_category);
                            }
                            if ($advisor) {
                                $q->where('created_by', $advisor);
                            }
                        });
                    })
                    ->when($anchor_merchant, function ($q) use ($anchor_merchant) {
                        $q->whereHas('merchant', function ($q) use ($anchor_merchant) {
                            $q->where('anchor_merchant_id', $anchor_merchant);
                        });
                    })
                    ->when($credit_manager, function ($q) use ($credit_manager) {
                        $q->whereHas('logs', function ($q) use ($credit_manager) {
                            $q->where('user_id', $credit_manager)->where('status', 'approved');
                        });
                    })
                    ->when($disbursement_date_from && $disbursement_date_to, function ($q) use ($disbursement_date_from, $disbursement_date_to) {
                        $q->whereHas('logs', function ($q) use ($disbursement_date_from, $disbursement_date_to) {
                            $disbursement_date_from = Carbon::parse($disbursement_date_from)->startOfDay()->toDateTimeString();
                            $disbursement_date_to = Carbon::parse($disbursement_date_to)->endOfDay()->toDateTimeString();
                            $q->where('created_at', '>=', $disbursement_date_from)
                                ->where('created_at', '<=', $disbursement_date_to)
                                ->where('status', 'disbursed');
                        });
                    });
            })
            ->whereHas('application_element', function ($q) {
                $q->whereNull('foreclosure_date');
            })
            ->where('payment_status', '!=', 'success')
            ->where('delay_days', '>=', 0)
            ->orderBy('application_id', 'desc')
            ->get();

        $dpd = array();
        $status =  ['disbursed','nach registered'];

        foreach ($data as $paymentKeyCount => $payments){

            try {
                if (!empty($payments->delay_days) && $payments->application && in_array($payments->application->state, $status) && $payments->delay_days >= 0) {
                    $total_paid = $payments->total_payable - $payments->amount_due;
                    if ($total_paid < $payments->emi_amount) {
                        if (isset($dpd[$payments->application_id])) {
                            if ($dpd[$payments->application_id]['delay_days'] < $payments->delay_days) {
                                $dpd[$payments->application_id]['delay_days'] = $payments->delay_days;
                                $dpd[$payments->application_id]['over_due'] = $data_type == 1 ? $payments->application_element->amount_over_due : $payments->application_element->principal_due;
                                $dpd[$payments->application_id]['principal_due'] = $payments->application_element->principal_due;
                                $dpd[$payments->application_id]['outstanding'] = $data_type == 1 ? $payments->application_element->total_amount_due :$payments->application_element->total_principal_due;
                                $dpd[$payments->application_id]['total_principal_due'] = $payments->application_element->total_principal_due;
                                $dpd[$payments->application_id]['application_data'] = $payments;
                                $dpd[$payments->application_id]['fldg_applied'] =  $payments->application->proFormaInvoice->fldg_applied;
                                if($payments->application->proFormaInvoice->fldg_category && $payments->application->proFormaInvoice->fldg_applied_category != 0){
                                    $dpd[$payments->application_id]['fldg'] = $payments->application->proFormaInvoice->fldg_category->fldg;
                                }
                                $dpd[$payments->application_id]['hold_amount'] = $payments->application_element->hold_amount;
                                $dpd[$payments->application_id]['approved_amount'] = $payments->application->approved_amount;
                            }
                        } else {
                            $dpd[$payments->application_id]['delay_days'] = $payments->delay_days;
                            $dpd[$payments->application_id]['over_due'] = $data_type == 1 ? $payments->application_element->amount_over_due : $payments->application_element->principal_due;
                            $dpd[$payments->application_id]['principal_due'] = $payments->application_element->principal_due;
                            $dpd[$payments->application_id]['outstanding'] = $data_type == 1 ? $payments->application_element->total_amount_due :$payments->application_element->total_principal_due;
                            $dpd[$payments->application_id]['total_principal_due'] = $payments->application_element->total_principal_due;
                            $dpd[$payments->application_id]['application_data'] = $payments;
                            $dpd[$payments->application_id]['fldg_applied'] =  $payments->application->proFormaInvoice->fldg_applied;
                            if($payments->application->proFormaInvoice->fldg_category && $payments->application->proFormaInvoice->fldg_applied_category != 0){
                                $dpd[$payments->application_id]['fldg'] = $payments->application->proFormaInvoice->fldg_category->fldg;
                            }
                            $dpd[$payments->application_id]['hold_amount'] = $payments->application_element->hold_amount;
                            $dpd[$payments->application_id]['approved_amount'] = $payments->application->approved_amount;
                        }
                    }
                }
            }catch (\Exception $exception){
                (new Slack(new Request(['title' => $log_data ? 'DPD Report Loop 1' : 'DPD Report while logging Loop 1' , 'fields' => ['e' => $exception->getMessage(),'l' => $exception->getLine(),'t' => $exception->getTraceAsString(), 'id' => $payments->application_id], 'group' => Slack::$STAGE_TESTING])))->send();
            }

            updateProgressBar($paymentKeyCount + 1, count($data), 'DPD Report Payment Loop');
        }
        $total_amount_till_date = array();
        $payment_transaction = PaymentTransaction::select('application_id','amount')->where('status', 'success')->whereNull('is_deleted_at')->whereNull('refunded_at')->orderBy('application_id', 'desc')->get();
        foreach($payment_transaction as $val){
            $total_amount_till_date[$val->application_id][] = $val->amount;
        }
        $fifteen = '0-15';
        $thirty = '15-30';
        $sixty = '30-60';
        $ninety = '60-90';
        $oneTwenty = '90-120';
        $oneFifty = '120-150';
        $oneEighty = '150-180';
        $threeSixtyFive = '180-365';
        $threeSixtyFivePlus = '365+';
        $response['report'][$threeSixtyFivePlus]['delay_days'] = 0;
        $response['report'][$threeSixtyFive]['delay_days'] = 0;
        $response['report'][$oneEighty]['delay_days'] = 0;
        $response['report'][$oneFifty]['delay_days'] = 0;
        $response['report'][$oneTwenty]['delay_days'] = 0;
        $response['report'][$ninety]['delay_days'] = 0;
        $response['report'][$sixty]['delay_days'] = 0;
        $response['report'][$thirty]['delay_days'] = 0;
        $response['report'][$fifteen]['delay_days'] = 0;
        $response['report'][$threeSixtyFivePlus]['over_due'] = 0;
        $response['report'][$threeSixtyFive]['over_due'] = 0;
        $response['report'][$oneEighty]['over_due'] = 0;
        $response['report'][$oneFifty]['over_due'] = 0;
        $response['report'][$oneTwenty]['over_due'] = 0;
        $response['report'][$ninety]['over_due'] = 0;
        $response['report'][$sixty]['over_due'] = 0;
        $response['report'][$thirty]['over_due'] = 0;
        $response['report'][$fifteen]['over_due'] = 0;
        $response['report'][$threeSixtyFivePlus]['principal_due'] = 0;
        $response['report'][$threeSixtyFive]['principal_due'] = 0;
        $response['report'][$oneEighty]['principal_due'] = 0;
        $response['report'][$oneFifty]['principal_due'] = 0;
        $response['report'][$oneTwenty]['principal_due'] = 0;
        $response['report'][$ninety]['principal_due'] = 0;
        $response['report'][$sixty]['principal_due'] = 0;
        $response['report'][$thirty]['principal_due'] = 0;
        $response['report'][$fifteen]['principal_due'] = 0;
        $response['report'][$threeSixtyFivePlus]['outstanding'] = 0;
        $response['report'][$threeSixtyFive]['outstanding'] = 0;
        $response['report'][$oneEighty]['outstanding'] = 0;
        $response['report'][$oneFifty]['outstanding'] = 0;
        $response['report'][$oneTwenty]['outstanding'] = 0;
        $response['report'][$ninety]['outstanding'] = 0;
        $response['report'][$sixty]['outstanding'] = 0;
        $response['report'][$thirty]['outstanding'] = 0;
        $response['report'][$fifteen]['outstanding'] = 0;
        $response['report'][$threeSixtyFivePlus]['total_principal_due'] = 0;
        $response['report'][$threeSixtyFive]['total_principal_due'] = 0;
        $response['report'][$oneEighty]['total_principal_due'] = 0;
        $response['report'][$oneFifty]['total_principal_due'] = 0;
        $response['report'][$oneTwenty]['total_principal_due'] = 0;
        $response['report'][$ninety]['total_principal_due'] = 0;
        $response['report'][$sixty]['total_principal_due'] = 0;
        $response['report'][$thirty]['total_principal_due'] = 0;
        $response['report'][$fifteen]['total_principal_due'] = 0;
        $response['report'][$threeSixtyFivePlus]['application_ids'] = array();
        $response['report'][$threeSixtyFive]['application_ids'] = array();
        $response['report'][$oneEighty]['application_ids'] = array();
        $response['report'][$oneFifty]['application_ids'] = array();
        $response['report'][$oneTwenty]['application_ids'] = array();
        $response['report'][$ninety]['application_ids'] = array();
        $response['report'][$sixty]['application_ids'] = array();
        $response['report'][$thirty]['application_ids'] = array();
        $response['report'][$fifteen]['application_ids'] = array();
        $response['report'][$threeSixtyFivePlus]['fldg_hold_count'] = 0;
        $response['report'][$threeSixtyFive]['fldg_hold_count'] = 0;
        $response['report'][$oneEighty]['fldg_hold_count'] = 0;
        $response['report'][$oneFifty]['fldg_hold_count'] = 0;
        $response['report'][$oneTwenty]['fldg_hold_count'] = 0;
        $response['report'][$ninety]['fldg_hold_count'] = 0;
        $response['report'][$sixty]['fldg_hold_count'] = 0;
        $response['report'][$thirty]['fldg_hold_count'] = 0;
        $response['report'][$fifteen]['fldg_hold_count'] = 0;
        $response['report'][$threeSixtyFivePlus]['fldg_hold_amount'] = 0;
        $response['report'][$threeSixtyFive]['fldg_hold_amount'] = 0;
        $response['report'][$oneEighty]['fldg_hold_amount'] = 0;
        $response['report'][$oneFifty]['fldg_hold_amount'] = 0;
        $response['report'][$oneTwenty]['fldg_hold_amount'] = 0;
        $response['report'][$ninety]['fldg_hold_amount'] = 0;
        $response['report'][$sixty]['fldg_hold_amount'] = 0;
        $response['report'][$thirty]['fldg_hold_amount'] = 0;
        $response['report'][$fifteen]['fldg_hold_amount'] = 0;
        $response['report']['total']['delay_days'] = 0;
        $response['report']['total']['over_due'] = 0;
        $response['report']['total']['principal_due'] = 0;
        $response['report']['total']['outstanding'] = 0;
        $response['report']['total']['total_principal_due'] = 0;
        $response['report']['total']['application_ids'] = array();
        $response['report']['total']['fldg_hold_count'] = 0;
        $response['report']['total']['fldg_hold_amount'] = 0;


        if($log_data || $report_data){
            $responseData = [];
//            $responseData[] = ['Application ID','Bucket', 'DPD days', 'First EMI Date','Last EMI Date',
//                'EMI Amount','No of EMI Due','Total due','Max Payable','Total Outstanding', 'Principal Outstanding','last payment date',
//                'last payment amount'];
        } else{
            $responseData[] = ['Application ID','Agreement Number','Name','Merchant Name','Segment', 'Lender', 'Loan Amount', 'Manager', 'FLDG DPD','Contact Number','Bucket', 'DPD days',
                'Email','DOB', 'PAN','Product Name','First EMI Date','Last EMI Date','EMI Amount','No of EMI Due','Total due','Max Payable','Total Outstanding','Total Paid Amount till date',
                'Employment Status','Company Name','Residental Address', 'Office Address','City','State','Pincode','Reference Name 1','Reference Number 1',
                'Reference Name 2','Reference Number 2','Principal Outstanding', 'Interest Outstanding', 'last payment date', 'last payment amount', 'UMRN No', 'Fldg/Hold Case (Yes / No)', 'Amount (if the hold /FLDG amount is available)'];
        }

        $applicationController = new ConsumerApplicationController();
        $defaultData = [];

        //(new Slack(new Request(['title' => 'DPD Report Count', 'fields' => ['DPD Data Count' => count($dpd)], 'group' => Slack::$STAGE_TESTING])))->send();

        $dpdCountLoop = 1;
        foreach ($dpd as $application=>$dpd_count){


            try {
                $days = 0;
                $dpd_days = $dpd_count['delay_days'];

                if ($dpd_count['delay_days'] >= 365) {
                    $response['report'][$threeSixtyFivePlus]['delay_days'] = $response['report'][$threeSixtyFivePlus]['delay_days'] + 1;
                    $response['report'][$threeSixtyFivePlus]['over_due'] = $response['report'][$threeSixtyFivePlus]['over_due'] + $dpd_count['over_due'];
                    $response['report'][$threeSixtyFivePlus]['principal_due'] = $response['report'][$threeSixtyFivePlus]['principal_due'] + $dpd_count['principal_due'];
                    $response['report'][$threeSixtyFivePlus]['outstanding'] = $response['report'][$threeSixtyFivePlus]['outstanding'] + $dpd_count['outstanding'];
                    $response['report'][$threeSixtyFivePlus]['total_principal_due'] = $response['report'][$threeSixtyFivePlus]['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report'][$threeSixtyFivePlus]['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report'][$threeSixtyFivePlus]['fldg_hold_count']  = $response['report'][$threeSixtyFivePlus]['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report'][$threeSixtyFivePlus]['fldg_hold_amount']  = $response['report'][$threeSixtyFivePlus]['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report'][$threeSixtyFivePlus]['fldg_hold_count']  = $response['report'][$threeSixtyFivePlus]['fldg_hold_count'] + 1;
                        $response['report'][$threeSixtyFivePlus]['fldg_hold_amount'] = $response['report'][$threeSixtyFivePlus]['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $response['report']['total']['delay_days'] = $response['report']['total']['delay_days'] + 1;
                    $response['report']['total']['over_due'] = $response['report']['total']['over_due'] + $dpd_count['over_due'];
                    $response['report']['total']['principal_due'] = $response['report']['total']['principal_due'] + $dpd_count['principal_due'];
                    $response['report']['total']['outstanding'] = $response['report']['total']['outstanding'] + $dpd_count['outstanding'];
                    $response['report']['total']['total_principal_due'] = $response['report']['total']['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report']['total']['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report']['total']['fldg_hold_amount']  = $response['report']['total']['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + 1;
                        $response['report']['total']['fldg_hold_amount'] = $response['report']['total']['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $days = '365+';
                }
                else if ($dpd_count['delay_days'] >= 180 && $dpd_count['delay_days'] < 365) {
                    $response['report'][$threeSixtyFive]['delay_days'] = $response['report'][$threeSixtyFive]['delay_days'] + 1;
                    $response['report'][$threeSixtyFive]['over_due'] = $response['report'][$threeSixtyFive]['over_due'] + $dpd_count['over_due'];
                    $response['report'][$threeSixtyFive]['principal_due'] = $response['report'][$threeSixtyFive]['principal_due'] + $dpd_count['principal_due'];
                    $response['report'][$threeSixtyFive]['outstanding'] = $response['report'][$threeSixtyFive]['outstanding'] + $dpd_count['outstanding'];
                    $response['report'][$threeSixtyFive]['total_principal_due'] = $response['report'][$threeSixtyFive]['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report'][$threeSixtyFive]['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report'][$threeSixtyFive]['fldg_hold_count']  = $response['report'][$threeSixtyFive]['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report'][$threeSixtyFive]['fldg_hold_amount']  = $response['report'][$threeSixtyFive]['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report'][$threeSixtyFive]['fldg_hold_count']  = $response['report'][$threeSixtyFive]['fldg_hold_count'] + 1;
                        $response['report'][$threeSixtyFive]['fldg_hold_amount'] = $response['report'][$threeSixtyFive]['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $response['report']['total']['delay_days'] = $response['report']['total']['delay_days'] + 1;
                    $response['report']['total']['over_due'] = $response['report']['total']['over_due'] + $dpd_count['over_due'];
                    $response['report']['total']['principal_due'] = $response['report']['total']['principal_due'] + $dpd_count['principal_due'];
                    $response['report']['total']['outstanding'] = $response['report']['total']['outstanding'] + $dpd_count['outstanding'];
                    $response['report']['total']['total_principal_due'] = $response['report']['total']['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report']['total']['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report']['total']['fldg_hold_amount']  = $response['report']['total']['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + 1;
                        $response['report']['total']['fldg_hold_amount'] = $response['report']['total']['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $days = 365;
                }
                elseif ($dpd_count['delay_days'] >= 150 && $dpd_count['delay_days'] < 180) {
                    $response['report'][$oneEighty]['delay_days'] = $response['report'][$oneEighty]['delay_days'] + 1;
                    $response['report'][$oneEighty]['over_due'] = $response['report'][$oneEighty]['over_due'] + $dpd_count['over_due'];
                    $response['report'][$oneEighty]['principal_due'] = $response['report'][$oneEighty]['principal_due'] + $dpd_count['principal_due'];
                    $response['report'][$oneEighty]['outstanding'] = $response['report'][$oneEighty]['outstanding'] + $dpd_count['outstanding'];
                    $response['report'][$oneEighty]['total_principal_due'] = $response['report'][$oneEighty]['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report'][$oneEighty]['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report'][$oneEighty]['fldg_hold_count']  = $response['report'][$oneEighty]['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report'][$oneEighty]['fldg_hold_amount']  = $response['report'][$oneEighty]['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report'][$oneEighty]['fldg_hold_count']  = $response['report'][$oneEighty]['fldg_hold_count'] + 1;
                        $response['report'][$oneEighty]['fldg_hold_amount'] = $response['report'][$oneEighty]['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $response['report']['total']['delay_days'] = $response['report']['total']['delay_days'] + 1;
                    $response['report']['total']['over_due'] = $response['report']['total']['over_due'] + $dpd_count['over_due'];
                    $response['report']['total']['principal_due'] = $response['report']['total']['principal_due'] + $dpd_count['principal_due'];
                    $response['report']['total']['outstanding'] = $response['report']['total']['outstanding'] + $dpd_count['outstanding'];
                    $response['report']['total']['total_principal_due'] = $response['report']['total']['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report']['total']['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report']['total']['fldg_hold_amount']  = $response['report']['total']['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + 1;
                        $response['report']['total']['fldg_hold_amount'] = $response['report']['total']['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $days = 180;
                }
                elseif ($dpd_count['delay_days'] >= 120 && $dpd_count['delay_days'] < 150) {
                    $response['report'][$oneFifty]['delay_days'] = $response['report'][$oneFifty]['delay_days'] + 1;
                    $response['report'][$oneFifty]['over_due'] = $response['report'][$oneFifty]['over_due'] + $dpd_count['over_due'];
                    $response['report'][$oneFifty]['principal_due'] = $response['report'][$oneFifty]['principal_due'] + $dpd_count['principal_due'];
                    $response['report'][$oneFifty]['outstanding'] = $response['report'][$oneFifty]['outstanding'] + $dpd_count['outstanding'];
                    $response['report'][$oneFifty]['total_principal_due'] = $response['report'][$oneFifty]['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report'][$oneFifty]['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report'][$oneFifty]['fldg_hold_count']  = $response['report'][$oneFifty]['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report'][$oneFifty]['fldg_hold_amount']  = $response['report'][$oneFifty]['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report'][$oneFifty]['fldg_hold_count']  = $response['report'][$oneFifty]['fldg_hold_count'] + 1;
                        $response['report'][$oneFifty]['fldg_hold_amount'] = $response['report'][$oneFifty]['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $response['report']['total']['delay_days'] = $response['report']['total']['delay_days'] + 1;
                    $response['report']['total']['over_due'] = $response['report']['total']['over_due'] + $dpd_count['over_due'];
                    $response['report']['total']['principal_due'] = $response['report']['total']['principal_due'] + $dpd_count['principal_due'];
                    $response['report']['total']['outstanding'] = $response['report']['total']['outstanding'] + $dpd_count['outstanding'];
                    $response['report']['total']['total_principal_due'] = $response['report']['total']['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report']['total']['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report']['total']['fldg_hold_amount']  = $response['report']['total']['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + 1;
                        $response['report']['total']['fldg_hold_amount'] = $response['report']['total']['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $days = 150;
                }
                elseif ($dpd_count['delay_days'] >= 90 && $dpd_count['delay_days'] < 120) {
                    $response['report'][$oneTwenty]['delay_days'] = $response['report'][$oneTwenty]['delay_days'] + 1;
                    $response['report'][$oneTwenty]['over_due'] = $response['report'][$oneTwenty]['over_due'] + $dpd_count['over_due'];
                    $response['report'][$oneTwenty]['principal_due'] = $response['report'][$oneTwenty]['principal_due'] + $dpd_count['principal_due'];
                    $response['report'][$oneTwenty]['outstanding'] = $response['report'][$oneTwenty]['outstanding'] + $dpd_count['outstanding'];
                    $response['report'][$oneTwenty]['total_principal_due'] = $response['report'][$oneTwenty]['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report'][$oneTwenty]['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report'][$oneTwenty]['fldg_hold_count']  = $response['report'][$oneTwenty]['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report'][$oneTwenty]['fldg_hold_amount']  = $response['report'][$oneTwenty]['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report'][$oneTwenty]['fldg_hold_count']  = $response['report'][$oneTwenty]['fldg_hold_count'] + 1;
                        $response['report'][$oneTwenty]['fldg_hold_amount'] = $response['report'][$oneTwenty]['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $response['report']['total']['delay_days'] = $response['report']['total']['delay_days'] + 1;
                    $response['report']['total']['over_due'] = $response['report']['total']['over_due'] + $dpd_count['over_due'];
                    $response['report']['total']['principal_due'] = $response['report']['total']['principal_due'] + $dpd_count['principal_due'];
                    $response['report']['total']['outstanding'] = $response['report']['total']['outstanding'] + $dpd_count['outstanding'];
                    $response['report']['total']['total_principal_due'] = $response['report']['total']['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report']['total']['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report']['total']['fldg_hold_amount']  = $response['report']['total']['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + 1;
                        $response['report']['total']['fldg_hold_amount'] = $response['report']['total']['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $days = 120;
                }
                elseif ($dpd_count['delay_days'] >= 60 && $dpd_count['delay_days'] < 90) {
                    $response['report'][$ninety]['delay_days'] = $response['report'][$ninety]['delay_days'] + 1;
                    $response['report'][$ninety]['over_due'] = $response['report'][$ninety]['over_due'] + $dpd_count['over_due'];
                    $response['report'][$ninety]['principal_due'] = $response['report'][$ninety]['principal_due'] + $dpd_count['principal_due'];
                    $response['report'][$ninety]['outstanding'] = $response['report'][$ninety]['outstanding'] + $dpd_count['outstanding'];
                    $response['report'][$ninety]['total_principal_due'] = $response['report'][$ninety]['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report'][$ninety]['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report'][$ninety]['fldg_hold_count']  = $response['report'][$ninety]['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report'][$ninety]['fldg_hold_amount']  = $response['report'][$ninety]['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report'][$ninety]['fldg_hold_count']  = $response['report'][$ninety]['fldg_hold_count'] + 1;
                        $response['report'][$ninety]['fldg_hold_amount'] = $response['report'][$ninety]['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $response['report']['total']['delay_days'] = $response['report']['total']['delay_days'] + 1;
                    $response['report']['total']['over_due'] = $response['report']['total']['over_due'] + $dpd_count['over_due'];
                    $response['report']['total']['principal_due'] = $response['report']['total']['principal_due'] + $dpd_count['principal_due'];
                    $response['report']['total']['outstanding'] = $response['report']['total']['outstanding'] + $dpd_count['outstanding'];
                    $response['report']['total']['total_principal_due'] = $response['report']['total']['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report']['total']['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report']['total']['fldg_hold_amount']  = $response['report']['total']['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + 1;
                        $response['report']['total']['fldg_hold_amount'] = $response['report']['total']['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $days = 90;
                }
                elseif ($dpd_count['delay_days'] >= 30 && $dpd_count['delay_days'] < 60) {
                    $response['report'][$sixty]['delay_days'] = $response['report'][$sixty]['delay_days'] + 1;
                    $response['report'][$sixty]['over_due'] = $response['report'][$sixty]['over_due'] + $dpd_count['over_due'];
                    $response['report'][$sixty]['principal_due'] = $response['report'][$sixty]['principal_due'] + $dpd_count['principal_due'];
                    $response['report'][$sixty]['outstanding'] = $response['report'][$sixty]['outstanding'] + $dpd_count['outstanding'];
                    $response['report'][$sixty]['total_principal_due'] = $response['report'][$sixty]['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report'][$sixty]['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report'][$sixty]['fldg_hold_count']  = $response['report'][$sixty]['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report'][$sixty]['fldg_hold_amount']  = $response['report'][$sixty]['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report'][$sixty]['fldg_hold_count']  = $response['report'][$sixty]['fldg_hold_count'] + 1;
                        $response['report'][$sixty]['fldg_hold_amount'] = $response['report'][$sixty]['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $response['report']['total']['delay_days'] = $response['report']['total']['delay_days'] + 1;
                    $response['report']['total']['over_due'] = $response['report']['total']['over_due'] + $dpd_count['over_due'];
                    $response['report']['total']['principal_due'] = $response['report']['total']['principal_due'] + $dpd_count['principal_due'];
                    $response['report']['total']['outstanding'] = $response['report']['total']['outstanding'] + $dpd_count['outstanding'];
                    $response['report']['total']['total_principal_due'] = $response['report']['total']['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report']['total']['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report']['total']['fldg_hold_amount']  = $response['report']['total']['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + 1;
                        $response['report']['total']['fldg_hold_amount'] = $response['report']['total']['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $days = 60;
                }
                elseif ($dpd_count['delay_days'] >= 15 && $dpd_count['delay_days'] < 30) {
                    $response['report'][$thirty]['delay_days'] = $response['report'][$thirty]['delay_days'] + 1;
                    $response['report'][$thirty]['over_due'] = $response['report'][$thirty]['over_due'] + $dpd_count['over_due'];
                    $response['report'][$thirty]['principal_due'] = $response['report'][$thirty]['principal_due'] + $dpd_count['principal_due'];
                    $response['report'][$thirty]['outstanding'] = $response['report'][$thirty]['outstanding'] + $dpd_count['outstanding'];
                    $response['report'][$thirty]['total_principal_due'] = $response['report'][$thirty]['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report'][$thirty]['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report'][$thirty]['fldg_hold_count']  = $response['report'][$thirty]['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report'][$thirty]['fldg_hold_amount']  = $response['report'][$thirty]['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report'][$thirty]['fldg_hold_count']  = $response['report'][$thirty]['fldg_hold_count'] + 1;
                        $response['report'][$thirty]['fldg_hold_amount'] = $response['report'][$thirty]['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $response['report']['total']['delay_days'] = $response['report']['total']['delay_days'] + 1;
                    $response['report']['total']['over_due'] = $response['report']['total']['over_due'] + $dpd_count['over_due'];
                    $response['report']['total']['principal_due'] = $response['report']['total']['principal_due'] + $dpd_count['principal_due'];
                    $response['report']['total']['outstanding'] = $response['report']['total']['outstanding'] + $dpd_count['outstanding'];
                    $response['report']['total']['total_principal_due'] = $response['report']['total']['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report']['total']['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report']['total']['fldg_hold_amount']  = $response['report']['total']['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + 1;
                        $response['report']['total']['fldg_hold_amount'] = $response['report']['total']['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $days = 30;
                }elseif ($dpd_count['delay_days'] >= 0 && $dpd_count['delay_days'] < 15) {
                    $response['report'][$fifteen]['delay_days'] = $response['report'][$fifteen]['delay_days'] + 1;
                    $response['report'][$fifteen]['over_due'] = $response['report'][$fifteen]['over_due'] + $dpd_count['over_due'];
                    $response['report'][$fifteen]['principal_due'] = $response['report'][$fifteen]['principal_due'] + $dpd_count['principal_due'];
                    $response['report'][$fifteen]['outstanding'] = $response['report'][$fifteen]['outstanding'] + $dpd_count['outstanding'];
                    $response['report'][$fifteen]['total_principal_due'] = $response['report'][$fifteen]['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report'][$fifteen]['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report'][$fifteen]['fldg_hold_count']  = $response['report'][$fifteen]['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report'][$fifteen]['fldg_hold_amount']  = $response['report'][$fifteen]['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report'][$fifteen]['fldg_hold_count']  = $response['report'][$fifteen]['fldg_hold_count'] + 1;
                        $response['report'][$fifteen]['fldg_hold_amount'] = $response['report'][$fifteen]['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $response['report']['total']['delay_days'] = $response['report']['total']['delay_days'] + 1;
                    $response['report']['total']['over_due'] = $response['report']['total']['over_due'] + $dpd_count['over_due'];
                    $response['report']['total']['principal_due'] = $response['report']['total']['principal_due'] + $dpd_count['principal_due'];
                    $response['report']['total']['outstanding'] = $response['report']['total']['outstanding'] + $dpd_count['outstanding'];
                    $response['report']['total']['total_principal_due'] = $response['report']['total']['total_principal_due'] + $dpd_count['total_principal_due'];
                    array_push($response['report']['total']['application_ids'], $application);
                    if($dpd_count['fldg_applied'] == 1 && isset($dpd_count['fldg'])){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + $dpd_count['fldg_applied'];
                        $response['report']['total']['fldg_hold_amount']  = $response['report']['total']['fldg_hold_amount'] + (($dpd_count['approved_amount'] * $dpd_count['fldg'])/100);
                    }
                    if($dpd_count['hold_amount'] != 0){
                        $response['report']['total']['fldg_hold_count']  = $response['report']['total']['fldg_hold_count'] + 1;
                        $response['report']['total']['fldg_hold_amount'] = $response['report']['total']['fldg_hold_amount'] + $dpd_count['hold_amount'];
                    }
                    $days = 15;
                }

                if ($days && (($export && $is_Queue) || $log_data || $report_data)) {
                    $applicationItem = $dpd_count['application_data'];

                    //$paymentItem = $this->getPayments($request, $application);
                    $last_emi_date = '';
                    /*$emiDues = (new LoanManagement())->generateDues($application, 0, $applicationItem->application);
                    $emiDues = array_reverse($emiDues);
                    foreach ($emiDues as $item){
                        $last_emi_date = $item['due_date'];
                        break;
                    }*/
                    $EmiPayment = EmiPayment::where('application_id', $application)->orderBy('emi_date', 'desc')->first(['emi_date']);
                    if (isset($EmiPayment->emi_date)) {
                        $last_emi_date = $EmiPayment->emi_date;
                    }

                    $loanamount = ((isset($applicationItem->application->approved_amount) && $applicationItem->application->approved_amount != 0) ? $applicationItem->application->approved_amount : $applicationItem->application->loan_amount) - ($applicationItem->application->emi ? $applicationItem->application->emi->upfront_from_customer : 0);

                    $application_element = $applicationItem->application_element;

                    if (!$request->has('internal') && ($log_data || ($export && $is_Queue))) {
                        $pos_data = (new TestingController())->getPrincipalsOutstandingAdityaV2($_date, true, $application);
                    }

                    $interest_outstanding = 0;
                    $b_p_rate = EmiPayment::where('application_id', $application)->get(['bounce_charges','delay_penalty']);
                    foreach($b_p_rate as $val){
                        $interest_outstanding += $val->bounce_charges + $val->delay_penalty;
                    }

//                    $emi_schedules = (new LoanManagement())->generateDues($application, 0, $applicationItem->application);
//                    $emis_array = array();
//                    array_push($emis_array, -$loanamount);
//
//                    if (isset($emi_schedules)) {
//                        foreach ($emi_schedules as $schedule) {
//                            array_push($emis_array, $schedule['amount']);
//                        }
//                    }
//
//                    $rate = (Finance::irr($emis_array)) * 100;
//                    if ($rate < 0 || !isset($rate) || $rate == 'NAN') {
//                        $rate = 0;
//                    }
//
//                    $principal_outstanding = $loanamount;
//                    $interest = $principal_outstanding * ($rate/100);
//                    $principal = $applicationItem->application->emi->emi - $interest;
//                    $principal_outstanding = $principal_outstanding - $principal;

                    if($log_data){
                        $responseData[] =  [
                            'application_id' => $application,
                            'bucket' => $days,
                            'dpd_days' => $dpd_days,
                            'first_emi_date' => ($applicationItem->application->emi) ? $applicationItem->application->emi->emi_date : '',
                            'last_emi_date' => $last_emi_date,
                            'emi_amount' => $applicationItem->application->emi && $applicationItem->application->emi->emi ? $applicationItem->application->emi->emi : 0,
                            'no_of_emi_due' => $application_element->emi_pending,
                            'total_due_with_penalties' => $dpd_count['over_due'],
                            'max_payable' => $application_element->total_amount_due,
                            'total_outstanding' => $dpd_count['outstanding'],
                            'principal_outstanding' => $pos_data[0]['after foreclosure p os'] ?? 0,
                            'last_payment_date' => $applicationItem->application->last_payment_date->payment_date ?? null,
                            'last_payment_amount' => $applicationItem->application->last_payment_date->amount ?? 0,
                            'created_at' => $_date,
                        ];
                    }else if($report_data) {
                        $responseData[] = [
                            'application_id' => $application,
                            'lender_id' => $applicationItem->application->lender_id,
                            'name' => $applicationItem->application->name,
                            'category_id' => $applicationItem->application->merchant->category_id,
                            'merchant_id' => $applicationItem->application->merchant_id ?? '',
                            'bucket' => $days,
                            'dpd_days' => $dpd_days,
                            'first_emi_date' => ($applicationItem->application->emi) ? $applicationItem->application->emi->emi_date : '',
                            'last_emi_date' => $last_emi_date,
                            'emi_amount' => $applicationItem->application->emi && $applicationItem->application->emi->emi ? $applicationItem->application->emi->emi : 0,
                            'no_of_emi_due' => $application_element->emi_pending,
                            'total_due_with_panelties' => $dpd_count['over_due'],
                            'max_payable' => $application_element->total_amount_due,
                            'total_outstanding' => $dpd_count['outstanding'],
                            'principal_outstanding' => $pos_data[0]['after foreclosure p os'] ?? '',
                            'interest_outstanding' => $interest_outstanding ?? '',
                        ];
                    }else {

                        $company_name = ($applicationItem->application && isset($applicationItem->application->company_name)) ? $applicationItem->application->company_name : '';

                        if ($company_name && !filter_var($company_name, FILTER_VALIDATE_INT) === false) {
                            $_company_name = Company::where('id', $company_name)->first(['company']);
                            if (isset($_company_name->company)) {
                                $company_name = $_company_name->company;
                            }
                        }

                        $product_name = $applicationItem->application_element ? $applicationItem->application_element->product_name : '';

                        $product_name = $applicationController->getProductName($product_name);
                        // Fldg/Hold Amount Calculation
                        $fh_amount = 0;
                        if($dpd_count['fldg_applied'] == 1){
                            $fh_amount = ($applicationItem->application->approved_amount * $dpd_count['fldg'])/100;
                        }
                        if($dpd_count['hold_amount'] != 0){
                            $fh_amount = $dpd_count['hold_amount'];
                        }
                        if($dpd_count['fldg_applied'] == 1 && $dpd_count['hold_amount'] != 0){
                            $fh_amount = (($applicationItem->application->approved_amount * $dpd_count['fldg'])/100) + $dpd_count['hold_amount'];
                        }

                        $agreement_no = ($applicationItem->application->proFormaInvoice) ? $applicationItem->application->proFormaInvoice->loan_application_no : '';

                        if($agreement_no === null){
                            $agreement_no = (new ConsumerApplicationController)->getLoanApplicationID($applicationItem->application->id, $applicationItem->application->merchant);
                            ProFormaInvoice::where('application_id', $applicationItem->application->id)->update(['loan_application_no'=>$agreement_no]);
                        }else if($agreement_no === ''){
                            $agreement_no = (new ConsumerApplicationController)->getLoanApplicationID($applicationItem->application->id, $applicationItem->application->merchant);
                            $newProforma = new ProFormaInvoice();
                            $newProforma->application_id = $applicationItem->application->id;
                            $newProforma->loan_application_no = $agreement_no;
                            $merchantInsuranceConfig = $this->getMerchantInsuranceConfig($applicationItem->application->id);
                            $newProforma->insurance_premium_by_merchant = $merchantInsuranceConfig['insurance_premium_by_merchant'];
                            $newProforma->insurance_premium_applicable = $merchantInsuranceConfig['insurance_premium_applicable'];
                            $newProforma->insurance_coverage = $merchantInsuranceConfig['insurance_coverage'];
                            $newProforma->processing_fee_by_merchant = $merchantInsuranceConfig['processing_fee_by_merchant'];
                            $newProforma->save();
                        }

                        $downPayment = $applicationItem->application->emi->upfront_from_customer ?? 0;

                        $responseData[] = [
                            'application_id' => $application,
                            'agreement_number' => $agreement_no,
                            'name' => $applicationItem->application->name,
                            'merchant_name' => ($applicationItem->application->merchant) ? $applicationItem->application->merchant->merchant_name : '',
                            'segment' => $merchant_categories_data_list[$applicationItem->application->purpose] ?? '',
                            'lender' => $lenders_data_all_list[$applicationItem->application->lender_id] ?? '',
                            'loan_amount' => ($applicationItem->application->approved_amount - $downPayment),
                            'manager' => '',
                            'fldg_dpd' => '',
                            'contact_no' => $applicationItem->application->mobile_number,
                            'bucket' => $days,
                            'dpd_days' => $dpd_days,
                            'email_id' => $applicationItem->application->email,
                            'DOB' => $applicationItem->application->dob,
                            'PAN' => $applicationItem->application->pan_card,
                            'product_name' => $product_name,
                            'first_emi_date' => ($applicationItem->application->emi) ? $applicationItem->application->emi->emi_date : '',
                            'last_emi_date' => $last_emi_date,
                            'emi_amount' => $applicationItem->application->emi && $applicationItem->application->emi->emi ? $applicationItem->application->emi->emi : 0,
                            'no_of_emi_due' => $application_element->emi_pending,
                            'total_due_with_panelties' => $dpd_count['over_due'],
                            'max_payable' => $application_element->total_amount_due,
                            'total_outstanding' => $dpd_count['outstanding'],
                            'total_paid_amount_till_date' => isset($total_amount_till_date[$application]) && !empty($total_amount_till_date[$application]) ? array_sum($total_amount_till_date[$application]) : '0',
                            'employment_status' => $applicationItem->application->employee_status,
                            'company_name' => $company_name,
                            'address' => $applicationItem->application->current_address_line_1 . ' ' . $applicationItem->application->current_address_landmark,
                            'office_addr' => $applicationItem->application->work_address_line_1 . ' ' . $applicationItem->application->work_address_landmark,
                            'city' => $applicationItem->application->current_address_city,
                            'state' => $applicationItem->application->current_address_state,
                            'pincode' => $applicationItem->application->current_address_pincode,
                            'reference Name 1' => $applicationItem->application_element->reference_name_1,
                            'reference Number 1' => $applicationItem->application_element->reference_contact_1,
                            'reference Name 2' => $applicationItem->application_element->reference_name_2,
                            'reference Number 2' => $applicationItem->application_element->reference_contact_2,
                            'principal_outstanding' => $pos_data[0]['after foreclosure p os'] ?? '',
                            'interest_outstanding' => $interest_outstanding ?? '',
                            'last_payment_date' => $applicationItem->application->last_payment_date->payment_date ?? '',
                            'last_payment_amount' => $applicationItem->application->last_payment_date->amount ?? '',
                            'umrn_no' => $applicationItem->application->checkmandate->umrn ?? '',
                            'fldg_hold_case' => ($dpd_count['fldg_applied'] == 1 || $dpd_count['hold_amount'] != 0) ? 'Yes' : 'No',
                            'fldg_hold_amount' => $fh_amount
                        ];
                    }
                }

            }catch (\Exception $exception){
                //(new Slack(new Request(['title' => $log_data ? 'DPD Report Loop 2' : 'DPD Report while logging Loop 2', 'fields' => ['e' => $exception->getMessage(),'l' => $exception->getLine(),'t' => $exception->getTraceAsString(), 'id' => $application], 'group' => Slack::$STAGE_TESTING])))->send();
            }

            updateProgressBar($dpdCountLoop, count($dpd), 'DPD Report Count Loop');
        }


        if ($request->has('internal')) {
            foreach ($response['report'] as $_bucket => $dpdItem) {
                if ($_bucket != 'total') {
                    $defaultData[] = ['bucket' => $_bucket, 'application_id' => json_encode($dpdItem['application_ids']), 'delay_days' => $dpdItem['delay_days'], 'over_due' => $dpdItem['over_due'], 'outstanding' => $dpdItem['outstanding'], 'data_type' => 1, 'fldg_hold_count' => $dpdItem['fldg_hold_count'],'total_fldg_hold_amount' => $dpdItem['fldg_hold_amount'], 'created_at' => $_date];
                    $defaultData[] = ['bucket' => $_bucket, 'application_id' => json_encode($dpdItem['application_ids']), 'delay_days' => $dpdItem['delay_days'], 'over_due' => $dpdItem['principal_due'], 'outstanding' => $dpdItem['total_principal_due'], 'data_type' => 2, 'fldg_hold_count' => $dpdItem['fldg_hold_count'],'total_fldg_hold_amount' => $dpdItem['fldg_hold_amount'], 'created_at' => $_date];
                }
            }
        }


        if($defaultData && $request->has('internal')) {
            foreach (array_chunk($defaultData,1000) as $t) {
                LoanDefault::insert($t);
            }
            return false;
        }

        //(new Slack(new Request(['title' => 'DPD Report Prepareing File', 'fields' => ['DPD Data Count' => count($dpd)], 'group' => Slack::$STAGE_TESTING])))->send();
        if($export && $request->has('is_queue')){
            $time = time();
            if ($responseData){
                $request = new Request(['data' => $responseData, 'sheet' => 'Sheet1', 'user_email' => $request->get('user_email')]);
                if($is_Queue){

                    (new Slack(new Request(['title' => 'DPD Report Sending File', 'fields' => ['DPD Data Count' => count($responseData)], 'group' => Slack::$STAGE_TESTING])))->send();
                    try {
                        $filePath = storage_path().'/app/exported/'.$time . '_bucket_wise_break.csv';
                        $file = fopen($filePath,"w");

                        foreach ($responseData as $line) {
                            fputcsv($file, $line);
                        }
                        fclose($file);
//                        Excel::store((new Exporter($request)), 'exported/' . $filePath);
                        // Storage::disk('s3')->put('/collection/exported/'.$filePath, file_get_contents(storage_path('app/exported/' . $filePath)));
                        $dpd_file = file_get_contents($filePath);
                        $this->sendDPDReportOverMail($dpd_file, $request);
                        unlink($filePath);
                        (new Slack(new Request(['title' => 'DPD Report Sent', 'fields' => ['DPD Data Count' => count($responseData)], 'group' => Slack::$STAGE_TESTING])))->send();
                    }catch (\Exception $exception){
                        (new Slack(new Request(['title' => 'DPD Report Sent Error', 'fields' => ['e' => $exception->getMessage(),'l' => $exception->getLine(),'t' => $exception->getTraceAsString()], 'group' => Slack::$STAGE_TESTING])))->send();
                    }
                    return true;
                }else{
                    return Excel::download((new Exporter($request)), 'bucket_wise_break.xls');
                }
            }
        }elseif($log_data || $report_data){
            if($responseData){
                return $responseData;
            }
            return false;
        }


        $approverData = StatusLogs::where('status','approved')->get();
        $approverDataIds = [];
        foreach ($approverData as $item){
            if(!in_array($item->user_id, $approverDataIds)) {
                $approverDataIds[] = $item->user_id;
            }
        }

        $credit_managers = User::whereIn('id', $approverDataIds)->get(['id','name']);

        $response['disbursement_date_from'] = $disbursement_date_from;
        $response['disbursement_date_to'] = $disbursement_date_to;
        $response['merchant_category'] = $merchant_category;
        $response['merchant_id'] = $merchant_id;
        $response['lender_id'] = $lender_id;
        $response['data_type'] = $data_type;
        $response['anchor_merchant'] = $anchor_merchant;
        $response['credit_manager'] = $credit_manager;
        $response['advisor'] = $advisor;
        $response['credit_managers'] = $credit_managers;
        //return(array) $response;
        return view('admin.accounting.dpd', $response);
        //return json_encode($response);
    }


    public function sendDPDReportOverMail($dpd_file, Request $request){
        // $url = URL::to('/').'/admin/export-cron-data/'.$filePath;
        // if ($s3->exists('/collection/'.$file)) {
        // $doc = $s3->get('/collection/'.$file);
        // $s3 = Storage::disk('s3');
        $user_email = $request->get('user_email');
        $time = time();
        $name = $time."_bucket_wise_break.xls";
         if ($dpd_file) {
            // $file = $s3->get('/collection/exported/'.$filePath);
             Mail::send('emails.reminders.basic_reminder',
            ['body' => "DPD Report attached below, Please find"]
            , function ($message) use ($user_email, $dpd_file, $name) {
                $message->to([trim($user_email)])->subject('DPD_Report');
                $message->attachData($dpd_file, $name);
            });
        }
    }
    //public function getAccruedProfit($month = 0,$year = 2019,$application_id = 0){
//    public function getAccruedProfit(){
//
//        $response = array();
//        $status =  ['disbursed','nach registered','closed '];
//        $consumerApplications = ConsumerApplicationRelation::with('logs','emi','emi.offer','emi_payment','emi_payment.transaction','lender')->wherein('state',$status)->whereNull('is_deleted')->where('id','!=','375');
//
//        $consumerApplications = $consumerApplications->get();
//        $consumerDocument = new ConsumerDocument(new Request());
//        $merhchantcontroller = new MerchantController();
//
//        foreach ($consumerApplications as $consumerApplication) {
//
//            $gstDetails = $consumerDocument->getGSTDetails(
//                [
//                    'amount' => $consumerApplication->emi->processing_fee,
//                    'state' => (isset($consumerApplication->permanent_address_state) && !empty($consumerApplication->permanent_address_state)) ? $consumerApplication->permanent_address_state : (isset($consumerApplication->current_address_state) && !empty($consumerApplication->current_address_state) ? $consumerApplication->current_address_state : '')
//                ]
//            );
//            foreach ($gstDetails as $gst){
//                $response[$consumerApplication->id]['processing_fees_net_amount'] = $gst['net_amount'];
//                $response[$consumerApplication->id][$gst['taxes']] = $gst['gst_amount'];
//            }
//            if(isset($consumerApplication->logs->created_at)) {
//                $disbursed_month = date('Y-m', strtotime($consumerApplication->logs->created_at));
//            }else{
//                return $consumerApplication;
//            }
//            if(isset($response[$consumerApplication->lender_id][$disbursed_month]['processing_fees'])){
//                $response[$consumerApplication->lender_id][$disbursed_month]['processing_fees'] = round($response[$consumerApplication->lender_id][$disbursed_month]['processing_fees'] + $response[$consumerApplication->id]['processing_fees_net_amount'],2);
//            }else{
//                $response[$consumerApplication->lender_id][$disbursed_month]['processing_fees'] = round($response[$consumerApplication->id]['processing_fees_net_amount'],2);
//            }
//            if($response[$consumerApplication->id]['processing_fees_net_amount'] > 0) {
//                $response[$consumerApplication->id][date('Y-m-d', strtotime($consumerApplication->logs->created_at))]['processing_fees'] = round($response[$consumerApplication->id]['processing_fees_net_amount'], 2);
//            }
//            if($consumerApplication->emi_payment) {
//                foreach ($consumerApplication->emi_payment as $emi_payment){
//                    $emimonth = date('Y-m', strtotime($emi_payment->emi_date));
//                    if($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) {
//                            $penal_interest_gstDetails = $consumerDocument->getGSTDetails(
//                                [
//                                    'amount' => $penal_interest,
//                                    'state' => (isset($consumerApplication->permanent_address_state) && !empty($consumerApplication->permanent_address_state)) ? $consumerApplication->permanent_address_state : (isset($consumerApplication->current_address_state) && !empty($consumerApplication->current_address_state) ? $consumerApplication->current_address_state : '')
//                                ]
//                            );
//                            if($penal_interest_gstDetails){
//                                if($penal_interest_gstDetails[0]['net_amount'] > 0) {
//                                    $response[$consumerApplication->id][$emi_payment->emi_date]['penal_interest'] = round($penal_interest_gstDetails[0]['net_amount'], 2);
//                                }
//                                if(isset($response[$consumerApplication->lender_id][$emimonth]['penal_interest'])){
//                                    $response[$consumerApplication->lender_id][$emimonth]['penal_interest'] = round($response[$consumerApplication->lender_id][$emimonth]['penal_interest'] + $penal_interest_gstDetails[0]['net_amount'],2);
//                                }else{
//                                    $response[$consumerApplication->lender_id][$emimonth]['penal_interest'] = round($penal_interest_gstDetails[0]['net_amount'],2);
//                                }
//                            }
//                        }
//                        $bounce_charge = ($emi_payment->charges_waived > ($emi_payment->delay_penalty + $emi_payment->bounce_charges)) ? $emi_payment->bounce_charges : ($emi_payment->bounce_charges - ($emi_payment->delay_penalty - $emi_payment->charges_waived));
//                        if($penal_interest > 0) {
//                            $bounce_charges_gstDetails = $consumerDocument->getGSTDetails(
//                                [
//                                    'amount' => $bounce_charge,
//                                    'state' => (isset($consumerApplication->permanent_address_state) && !empty($consumerApplication->permanent_address_state)) ? $consumerApplication->permanent_address_state : (isset($consumerApplication->current_address_state) && !empty($consumerApplication->current_address_state) ? $consumerApplication->current_address_state : '')
//                                ]
//                            );
//                            if($bounce_charges_gstDetails){
//                                if($bounce_charges_gstDetails[0]['net_amount'] > 0) {
//                                    $response[$consumerApplication->id][$emi_payment->emi_date]['bounce_charges'] = round($bounce_charges_gstDetails[0]['net_amount'], 2);
//                                }
//
//                                if(isset($response[$consumerApplication->lender_id][$emimonth]['bounce_charges'])){
//                                    $response[$consumerApplication->lender_id][$emimonth]['bounce_charges'] = round($response[$consumerApplication->lender_id][$emimonth]['bounce_charges'] + $bounce_charges_gstDetails[0]['net_amount'],2);
//                                }else{
//                                    $response[$consumerApplication->lender_id][$emimonth]['bounce_charges'] = round($bounce_charges_gstDetails[0]['net_amount'],2);
//                                }
//                            }
//                        }
//                    }
//
//                }
//            }
//            $irr = $merhchantcontroller->calculateIRR("", $consumerApplication->approved_amount, json_decode(($consumerApplication->emi), true), false);
//            $tenure = $consumerApplication->emi->remaining_emi;
//            $emi_date = $consumerApplication->emi->emi_date;
//            $count = 1;
//            $outsanding = ($consumerApplication->approved_amount * (1 - ($consumerApplication->emi->subvention / 100))) - $consumerApplication->emi->upfront_from_customer;
//            //return $consumerApplications[0]->emi;
//            if(!isset($response[$consumerApplication->id]['name'])){
//                $response[$consumerApplication->id]['name'] = $consumerApplication->name;
//            }
//            if(!isset($response[$consumerApplication->id]['lender'])){
//                $response[$consumerApplication->id]['lender'] = $consumerApplication->lender->name;
//            }
//            while ($count <= $tenure) {
//                if($count == 1){
//                    $emi_date = date('Y-m-d', strtotime($emi_date));
//                }else {
//                    $emi_date = date('Y-m-d', strtotime($emi_date . ' +1 month'));
//                }
//                    $emimonth = date('Y-m', strtotime($emi_date));
//
//                    $response[$consumerApplication->id][$emi_date]['emi_amount'] = $consumerApplication->emi->emi;
//                    $response[$consumerApplication->id][$emi_date]['outstanding'] = $outsanding;
//
//                    $response[$consumerApplication->id][$emi_date]['revenue'] = round(($response[$consumerApplication->id][$emi_date]['outstanding'] * $irr['irr']) / 100, 2);
//                    $response[$consumerApplication->id][$emi_date]['principal_payable'] = round($consumerApplication->emi->emi - $response[$consumerApplication->id][$emi_date]['revenue'],2);
//                    if(isset($response[$consumerApplication->lender_id][$emimonth]['revenue'])){
//                        $response[$consumerApplication->lender_id][$emimonth]['revenue'] = round($response[$consumerApplication->lender_id][$emimonth]['revenue'] + $response[$consumerApplication->id][$emi_date]['revenue'],2);
//                    }else{
//                        $response[$consumerApplication->lender_id][$emimonth]['revenue'] = round($response[$consumerApplication->id][$emi_date]['revenue'],2);
//                    }
//                    if(isset($response[$consumerApplication->lender_id][$emimonth]['principal_outstanding'])){
//                        $response[$consumerApplication->lender_id][$emimonth]['principal_outstanding'] = round($response[$consumerApplication->lender_id][$emimonth]['principal_outstanding'] + $outsanding,2);
//                    }else{
//                        $response[$consumerApplication->lender_id][$emimonth]['principal_outstanding'] = round($outsanding,2);
//                    }
//                    $outsanding = round($outsanding - $response[$consumerApplication->id][$emi_date]['principal_payable'], 2);
//                $count++;
//            }
//        }
//
//
//        $data_table =  "<table><tr><th>Application Id</th><th>Lender</th><th>Name</th><th>Emi_Date</th><th>principal_payable</th><th>emi_amount</th><th>outstanding</th><th>revenue</th><th>Processing Fees</th><th>Bounce Charges</th><th>Penal Interest</th><th>Principal Sense Check</th></tr>";
//
//        foreach ($response as $key => $application){
//            foreach ($application as $emi_date => $emi_details){
//                    if((isset($emi_details['emi_amount']) || isset($emi_details['processing_fees']) || isset($emi_details['bounce_charges']) || isset($emi_details['penal_interest'])) && $key != 1 and $key != 2) {
//                        $data_table.= "<tr><td>" . $key . "</td><td>" . (isset($application['lender']) ? $application['lender'] : "") . "</td><td>" . (isset($application['name']) ? $application['name'] : "") . "</td><td>" . $emi_date . "</td><td>" . money_format('%!i',(isset($emi_details['principal_payable']) ? $emi_details['principal_payable'] : 0)) . "</td><td>" . money_format('%!i',(isset($emi_details['emi_amount']) ? $emi_details['emi_amount'] : 0)) . "</td><td>" . money_format('%!i',(isset($emi_details['outstanding']) ? $emi_details['outstanding'] : 0)) . "</td><td>" . money_format('%!i',(isset($emi_details['revenue']) ? $emi_details['revenue'] : 0)) . "</td><td>".money_format('%!i',(isset($emi_details['processing_fees']) ? $emi_details['processing_fees'] : 0))."</td><td>".money_format('%!i',(isset($emi_details['bounce_charges']) ? $emi_details['bounce_charges'] : 0))."</td><td>".money_format('%!i',(isset($emi_details['penal_interest']) ? $emi_details['penal_interest'] : 0))."</td><td>".money_format('%!i',((isset ($emi_details['principal_payable'])) && (isset($emi_details['outstanding'])) ? $emi_details['outstanding'] - $emi_details['principal_payable'] : 0))."</td></tr>";
//                    }
//            }
//        }
//        setlocale(LC_MONETARY, 'en_IN.UTF-8');
//        //(isset($emi_details['penal_interest']) ? $emi_details['penal_interest'] : 0) ;
//        $data_table.= "</table>";
//
//
//        $response[1]['final']['processing_fees'] = 0;
//        $response[1]['final']['principal_outstanding'] = 0;
//        $response[1]['final']['revenue'] = 0;
//        $response[1]['final']['bounce_charges'] = 0;
//        $response[1]['final']['penal_interest'] = 0;
//        $response[2]['final']['processing_fees'] = 0;
//        $response[2]['final']['principal_outstanding'] = 0;
//        $response[2]['final']['revenue'] = 0;
//        $response[2]['final']['bounce_charges'] = 0;
//        $response[2]['final']['penal_interest'] = 0;
//        $data_table_month_1 =  "<table><tr><th>Month</th><th>Processing Fees</th><th>outstanding</th><th>Interest Subvention Revenue</th><th>Bounce Charges</th><th>Penal Interest</th></tr>";
//        $data_table_month_2 =  "<table><tr><th>Month</th><th>Processing Fees</th><th>outstanding</th><th>Interest Subvention Revenue</th><th>Bounce Charges</th><th>Penal Interest</th></tr>";
//
//        ksort($response);
//        foreach ($response as $lender=> $response_revenue) {
//            foreach ($response_revenue as $month => $revenue) {
//                if (isset($revenue['revenue']) || isset($revenue['processing_fees']) || isset($revenue['bounce_charges']) || isset($revenue['penal_interest'])) {
//                    if ($lender == 1) {
//                        $data_table_month_1 .= "<tr><td>" . date('F - Y', strtotime($month)) . "</td><td>" . money_format('%!i', (isset($revenue['processing_fees']) ? $revenue['processing_fees'] : 0)) . "</td><td>" . money_format('%!i', (isset($revenue['principal_outstanding']) ? $revenue['principal_outstanding'] : 0)) . "</td><td>" . money_format('%!i', (isset($revenue['revenue']) ? $revenue['revenue'] : 0)) . "</td><td>" . money_format('%!i', (isset($revenue['bounce_charges']) ? $revenue['bounce_charges'] : 0)) . "</td><td>" . (money_format('%!i', isset($revenue['penal_interest']) ? $revenue['penal_interest'] : 0)) . "</td></tr>";
//                        $response[1]['final']['processing_fees'] = $response[1]['final']['processing_fees'] + (isset($revenue['processing_fees']) ? $revenue['processing_fees'] : 0);
//                        $response[1]['final']['principal_outstanding'] = $response[1]['final']['principal_outstanding'] + (isset($revenue['principal_outstanding']) ? $revenue['principal_outstanding'] : 0);
//                        $response[1]['final']['revenue'] = $response[1]['final']['revenue'] + (isset($revenue['revenue']) ? $revenue['revenue'] : 0);
//                        $response[1]['final']['bounce_charges'] = $response[1]['final']['bounce_charges'] + (isset($revenue['bounce_charges']) ? $revenue['bounce_charges'] : 0);
//                        $response[1]['final']['penal_interest'] = $response[1]['final']['penal_interest'] + (isset($revenue['penal_interest']) ? $revenue['penal_interest'] : 0);
//                    } elseif($lender == 2) {
//                        $data_table_month_2 .= "<tr><td>" . date('F - Y', strtotime($month)) . "</td><td>" . money_format('%!i', (isset($revenue['processing_fees']) ? $revenue['processing_fees'] : 0)) . "</td><td>" . money_format('%!i', (isset($revenue['principal_outstanding']) ? $revenue['principal_outstanding'] : 0)) . "</td><td>" . money_format('%!i', (isset($revenue['revenue']) ? $revenue['revenue'] : 0)) . "</td><td>" . money_format('%!i', (isset($revenue['bounce_charges']) ? $revenue['bounce_charges'] : 0)) . "</td><td>" . (money_format('%!i', isset($revenue['penal_interest']) ? $revenue['penal_interest'] : 0)) . "</td></tr>";
//                        $response[2]['final']['processing_fees'] = $response[2]['final']['processing_fees'] + (isset($revenue['processing_fees']) ? $revenue['processing_fees'] : 0);
//                        $response[2]['final']['principal_outstanding'] = $response[2]['final']['principal_outstanding'] + (isset($revenue['principal_outstanding']) ? $revenue['principal_outstanding'] : 0);
//                        $response[2]['final']['revenue'] = $response[2]['final']['revenue'] + (isset($revenue['revenue']) ? $revenue['revenue'] : 0);
//                        $response[2]['final']['bounce_charges'] = $response[2]['final']['bounce_charges'] + (isset($revenue['bounce_charges']) ? $revenue['bounce_charges'] : 0);
//                        $response[2]['final']['penal_interest'] = $response[2]['final']['penal_interest'] + (isset($revenue['penal_interest']) ? $revenue['penal_interest'] : 0);
//                    }
//                }
//            }
//        }
//        $data_table_month_1.=  "<tr><td>Total</td><td>" . money_format('%!i',$response[1]['final']['processing_fees']) . "</td><td>" . money_format('%!i',$response[1]['final']['principal_outstanding']) . "</td><td>" . money_format('%!i',$response[1]['final']['revenue']) . "</td><td>" . money_format('%!i',$response[1]['final']['bounce_charges']) . "</td><td>" . money_format('%!i',$response[1]['final']['penal_interest']) . "</td></tr>";
//
//        $data_table_month_2.=  "<tr><td>Total</td><td>" . money_format('%!i',$response[2]['final']['processing_fees']) . "</td><td>" . money_format('%!i',$response[2]['final']['principal_outstanding']) . "</td><td>" . money_format('%!i',$response[2]['final']['revenue']) . "</td><td>" . money_format('%!i',$response[2]['final']['bounce_charges']) . "</td><td>" . money_format('%!i',$response[2]['final']['penal_interest']) . "</td></tr>";
//        $data_table_month_1.= "</table>";
//        $data_table_month_2.= "</table>";
//        echo "<style type='text/css'>";
//        echo "table, th, td {
//  border: 1px solid black;
//  border-collapse: collapse;
//  padding:3px;
//}";
//
//        echo "</style>";
//        echo "<h1>Customer Wise Revenue Calculation</h1>";
//        echo $data_table;
//        echo "<br>";
//        echo "<h1>Month Wise Revenue Calculation -  Pride Financial Services Private Limited</h1>";
//        echo  $data_table_month_1;
//        echo "<br>";
//        echo "<h1>Month Wise Revenue Calculation -  K. M. Global Credit Private Limited</h1>";
//        echo  $data_table_month_2;
//        //return $response;
//
//    }


    public function OverDueReminder($id = 0){
        $dayOfWeek = date('l',Carbon::now()->timestamp);
        $all_due_cases = 0;
        if($dayOfWeek == 'Monday'){
            $all_due_cases = 1;
        }

        $payments = PaymentMakerChecker::with('application')->where('status',1)->where('data','LIKE','%"payment_type":"credit"%')->get();

        $recon_id=array();
        foreach($payments as $payment){
            array_push($recon_id,$payment->application_id);
        }
        $loan_management = new LoanManagement();
        $data = $loan_management->overDueReminder(0,"",0,0,$all_due_cases);
        return view('admin.accounting.over_due_reminder', ['recon_id' => $recon_id,'response'=>$data['response'], 'application_ids' =>json_encode($data['application_ids']),'total_applications'=>$data['total_applications']]);

        //return $data;
    }

    public function OverDueReminderV1(Request $request){

        $lenders = Lenders::select('id', 'name')->get();

        // Get all data at once
        $data = $this->getOverdueApplications($request);

        $response = $data['applications'];
        $ids = $data['ids'];
        $totalCount = count($response); // Simple count since we have all data

        // Directly return the view with all data
        return view('admin.accounting.over_due_reminder_v1', [
            'response' => $response,
            'application_ids' => json_encode($ids),
            'totalCount' => $totalCount,
            'lenders' => $lenders
        ]);
    }

    private function getOverdueApplications(Request $request){
        // 1. Remove Page/Offset/Limit variables

        // Lenders to exclude
        $lender_id = Singularity::$lender_id;
        $capri_lender_id = Capri::$lender_id;
        $vivriti_lender_id = Vivriti::$lender_id;
        $avanse_lender_id = AvanseServices::$lender_id;
        $excludedLenderIds = [$capri_lender_id, $vivriti_lender_id, $avanse_lender_id];

        // Merchants to exclude
        $stopCommunication = (new AdvanceReminders())->stopCommunication ?? [];
        $excludedMerchantIds = array_filter(array_map('trim', explode(',', env('EXCLUDED_MERCHANT_FOR_OVERDUE_REMINDER', ''))));
        $finalExcludedMerchantIds = array_merge($stopCommunication, $excludedMerchantIds);

        // Applications to exclude
        $excludedApplicationIds = [
            181787, 196159, 164510, 187650, 202432, 216168, 124011, 184937, 217423, 198917,
            208259, 83737, 125951, 207488, 119202, 170752, 176027, 222553, 258206, 128379,
            113064,
        ];

        $selectedLenders = $request->get('lender_ids');
        $min_due_threshold = (int) ($request->get('total_due_amount') ?: 100);
        if ($min_due_threshold <= 0) {
            $min_due_threshold = 0;
        }

        // Convert arrays to comma-separated strings safely.
        $exLenderStr = implode(',', array_map('intval', $excludedLenderIds));
        $exMerchantStr = !empty($finalExcludedMerchantIds) ? implode(',', array_map('intval', $finalExcludedMerchantIds)) : '0';
        $exApplicationStr = implode(',', array_map('intval', $excludedApplicationIds));

        // Dynamic WHERE for selected lenders
        $selectedLenderCondition = "";
        if (!empty($selectedLenders)) {
            $selLenderStr = implode(',', array_map('intval', $selectedLenders));
            $selectedLenderCondition = "AND ca.lender_id IN ($selLenderStr)";
        }

        $cteBody = "
        WITH valid_applications AS (
            SELECT ca.id
            FROM consumer_application ca
            LEFT JOIN consumer_application_element ae ON ae.application_id = ca.id
            WHERE ca.state IN ('disbursed','nach registered')
            AND ca.deleted_at IS NULL
            AND ca.is_deleted IS NULL
            AND ca.lender_id NOT IN ($exLenderStr)
            AND ca.merchant_id NOT IN ($exMerchantStr)
            AND ca.id NOT IN ($exApplicationStr)
            $selectedLenderCondition

            AND NOT EXISTS (
                SELECT 1 FROM consumer_application_additional caa 
                WHERE caa.application_id = ca.id 
                AND caa.is_custody = 1
            )

            AND NOT EXISTS (
                SELECT 1 FROM payments_maker_checker pmc 
                WHERE pmc.application_id = ca.id 
                AND pmc.status = 1 
                AND pmc.payment_type = 'credit'
            )
            AND NOT EXISTS (
                SELECT 1 FROM consumer_application_follow_ups cafu
                WHERE cafu.application_id = ca.id
                AND cafu.id = (
                    SELECT MAX(cafu2.id) FROM consumer_application_follow_ups cafu2
                    WHERE cafu2.application_id = ca.id
                    AND cafu2.deleted_at IS NULL
                )
                AND cafu.follow_up_status = 'stopped'
                AND cafu.deleted_at IS NULL
            )
        ),
        payment_transactions_cte AS (
            SELECT pt.application_id, pt.emi_payment_id, pt.payment_for, pt.payment_date, pt.amount
            FROM payment_transactions pt
            JOIN valid_applications va ON va.id = pt.application_id
            WHERE (pt.deleted_at IS NULL AND pt.is_deleted_at IS NULL AND pt.refunded_at IS NULL)
            AND (pt.payment_for IN ('EMI','Forclouser','Foreclosed','Foreclosure','Write-off','Pre-EMI','settled_principal',
            'settled_interest','settled_bounce','settled_penal','written_off_principal','written_off_interest','waived_off_bounce','waived_off_penal'))
        ),
        foreclosure_cte AS (
            SELECT application_id
            FROM payment_transactions_cte
            WHERE payment_for IN ('Forclouser','Foreclosed','Foreclosure','Write-off','settled_principal',
            'settled_interest','settled_bounce','settled_penal','written_off_principal','written_off_interest','waived_off_bounce','waived_off_penal')
            GROUP BY 1
        ),
        emi_payments_cte AS (
            SELECT ep.id, ep.application_id, ep.emi_date, ep.due_date, ep.payment_status,
            LEAST(ep.emi_amount, (ep.emi_amount + ep.bounce_charges + ep.delay_penalty) - ep.charges_waived) - IFNULL(ep.moratorium_amount,0) as emi_amount_expected,
            ROUND((ep.pre_emi_amount + ep.emi_amount + ep.bounce_charges + ep.delay_penalty) - ep.charges_waived) - IFNULL(ep.moratorium_amount,0) as total_amount_expected,
            DATEDIFF(CURRENT_DATE, ep.due_date) as delay_days
            FROM emi_payments ep
            JOIN valid_applications va ON va.id = ep.application_id
        ),
        emi_cte1 AS (
            SELECT epc.application_id,
            epc.emi_date, epc.due_date,
            epc.payment_status,
            epc.emi_amount_expected,
            IF(
                IFNULL(SUM(ptc.amount),0) > epc.emi_amount_expected,
                epc.emi_amount_expected,
                IFNULL(SUM(ptc.amount),0)
            ) as emi_amount_received,
            epc.total_amount_expected,
            IFNULL(SUM(ptc.amount),0) as total_amount_received,
            epc.delay_days
            FROM emi_payments_cte epc
            LEFT JOIN payment_transactions_cte ptc ON ptc.application_id = epc.application_id
                AND ptc.emi_payment_id = epc.id
            GROUP BY 1,2,3,4,5,7
        ),
        emi_cte2 AS (
            SELECT application_id,
            SUM(emi_amount_expected) as total_emi_amount_expected,
            SUM(CASE WHEN due_date < CURRENT_DATE THEN emi_amount_expected ELSE 0 END) as total_emi_amount_expected_today,
            SUM(emi_amount_received) as total_emi_amount_received,
            SUM(total_amount_expected) as total_amount_expected,
            SUM(CASE WHEN due_date < CURRENT_DATE THEN total_amount_expected ELSE 0 END) as total_amount_expected_today,
            SUM(total_amount_received) as total_amount_received,
            MAX(CASE WHEN payment_status <> 'success' THEN delay_days ELSE 0 END) as delay_days
            FROM emi_cte1
            GROUP BY 1
        ),
        final_result AS (
            SELECT emi_cte2.application_id as id,
                ca.name as applicant_name,
                m.merchant_name,
                GREATEST(0, total_amount_expected_today - total_amount_received) as total_due_amount,
                GREATEST(0, total_emi_amount_expected_today - total_emi_amount_received) as emi_due_amount,
                GREATEST(0, GREATEST(0, total_amount_expected_today - total_amount_received) - GREATEST(0, total_emi_amount_expected_today - total_emi_amount_received)) as charges_due,
                delay_days
            FROM emi_cte2
            JOIN consumer_application ca ON ca.id = emi_cte2.application_id and ca.lender_id != 18 -- Siemens lender excluded
            LEFT JOIN foreclosure_cte fc ON fc.application_id = emi_cte2.application_id
            LEFT JOIN merchant m ON m.id = ca.merchant_id
            WHERE fc.application_id IS NULL
            HAVING total_due_amount >= :min_due_threshold
        )";

        // 2. Removed LIMIT and OFFSET
        $dataQuery = $cteBody . " SELECT * FROM final_result";

        $applications = DB::select($dataQuery, [
            'min_due_threshold' => $min_due_threshold
        ]);

        $response = [];
        $ids = [];

        foreach ($applications as $app) {
            $response[$app->id] = [
                'id' => $app->id,
                'applicant_name' => $app->applicant_name,
                'merchant_name' => $app->merchant_name,
                'total_due_amount' => $app->total_due_amount,
                'emi_due_amount' => $app->emi_due_amount,
                'charges_due' => $app->charges_due,
                'delay_days' => $app->delay_days,
            ];
            $ids[] = $app->id;
        }

        return [
            'applications' => $response,
            'ids' => $ids,
        ];
    }

    public function checkPaymentReminder(Request $request){
        $status = 'FAIL';
        $message = 'Something went wrong';
        try {
        $count = JobProvider::where('from','overDuePaymentReminder')->where('available_at','LIKE',date('Y-m-d').'%')->count();
        $status = 'OK';
         $message = 'Jobs Fetched';

        }catch (\Exception $e){

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

    public function sendPaymentReminder(Request $request) {
        $status = 'FAIL';
        $message = 'Something went wrong';

        // FIX: Safe check for User AND Email to prevent crash on null
        $user = Auth::user();
        $collectionEmail = '';

        if (!$user || empty($user->email)) {
            $collectionEmail = _env('COLLECTION_MAIL');
        } else {
            $collectionEmail = $user->email;
        }

        if ($request->has('application_ids')) {
            try {
                $rawIds = str_replace(['[', ']'], '', $request->get('application_ids'));
                $idArray = explode(',', $rawIds);

                $batches = array_chunk($idArray, 3000);
                $jobsToInsert = [];

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

                $scheduleTime = Carbon::now();

                foreach ($batches as $batch) {
                    $scheduleTime->addMinutes(5);

                    $jobsToInsert[] = [
                        'from'           => 'overDuePaymentReminder',
                        'payload'        => json_encode([
                            'id' => implode(',', $batch),
                            'collectionEmail'=> $collectionEmail
                        ]),
                        'available_at'   => $scheduleTime->toDateTimeString(),
                        'application_id' => 181,
                        'created_at'     => $createdAt,
                        'is_available'   => 0
                    ];
                }

                if (!empty($jobsToInsert)) {
                    JobProvider::insert($jobsToInsert);
                }

                $status = 'OK';
                $message = 'Payment Reminder(s) successfully added to Queue';

            } catch (\Exception $e) {
                $cwFactory = new CloudWatchLoggerFactory();
                $_data = array(
                    'exception' => 'Error while making OverDue Reminder Job',
                    'message' => $e->getMessage(),
                    'line' => $e->getLine(),
                    'trace' => $e->getTraceAsString()
                );
                $cwFactory->logger(json_encode($_data));
            }
        }

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

    public function getApplicationDueAmount($id){

        $data = (new LoanManagement())->getPaymentDueHistory($id,'',1);

        $response['emi_due'] = (isset($data[$id]['amount_pending']) ? $data[$id]['amount_pending'] : 0);
        $response['processing_fee_due'] = (isset($data[$id]['processing_fee_due']) ? $data[$id]['processing_fee_due'] : 0);
        $response['advance_amount_due'] = (isset($data[$id]['advance_amount_due']) ? $data[$id]['advance_amount_due'] : 0);
        $response['total_due'] = $response['emi_due'] + $response['processing_fee_due'] + $response['advance_amount_due'];

        return $response;
    }

    public function getMerchantCollectionReport()
    {
        try {
            $cwFactory = new CloudWatchLoggerFactory();
            $status = ['disbursed', 'nach registered'];
            $applications = ConsumerApplication::with('application_element', 'emi', 'last_payment_date', 'proFormaInvoice')
                ->whereHas('application_element', function ($query) {
                    $query->where('amount_over_due', '>=', 500);
                })->whereHas('merchant', function ($query) {
                    $query->where('pending_collection_report', 1);
                })->whereNull('is_deleted')->wherein('state', $status)->whereNotIn('lender_id', [Singularity::$lender_id, Capri::$lender_id, Vivriti::$lender_id])->get();
            $data = array();
            $i = 0;
            $lender = Lenders::where('id', 2)->first();
            $loan_management = new LoanManagement();
            $applicationController = new ConsumerApplicationController();
            $countEmailSent = 0;
            foreach ($applications as $application) {
                if (isset($application->merchant) && isset($application->merchant->pending_collection_report) && $application->merchant->pending_collection_report == 1) {

                    $loanManagementData = $loan_management->overDueReminder($application->id, "", 0, 0, 0);

                    if (isset($loanManagementData['response']) && isset($loanManagementData['response'][$application->id]) && isset($loanManagementData['response'][$application->id]['delay_days']) && $loanManagementData['response'][$application->id]['delay_days'] > 5) {

                        if (!isset($data[$application->merchant_id]['merchant_id'])) {
                            $data[$application->merchant_id]['merchant_id'] = $application->merchant->id;
                        }
                        if (!isset($data[$application->merchant_id]['merchant_name'])) {
                            $data[$application->merchant_id]['merchant_name'] = $application->merchant->merchant_name;
                        }
                        if (!isset($data[$application->merchant_id]['email'])) {
                            $data[$application->merchant_id]['email'] = $application->merchant->email;
                        }
                        if (!isset($data[$application->merchant_id]['contact_number'])) {
                            $data[$application->merchant_id]['contact_number'] = [$application->merchant->contact_number, $application->merchant->rcp_mobile, $application->merchant->sales_head_mobile, $application->merchant->finance_head_mobile];
                        }

                        $product_name = ($application->application_element && $application->application_element->product_name) ? $application->application_element->product_name : '';
                        $product_name = $applicationController->getProductName($product_name);

                        $data[$application->merchant_id]['cases'][$i]['application_id'] = $application->id;
                        $data[$application->merchant_id]['cases'][$i]['customer_name'] = $application->name;
                        $data[$application->merchant_id]['cases'][$i]['over_due_amount'] = $application->application_element->amount_over_due;
                        $data[$application->merchant_id]['cases'][$i]['last_payment_date'] = isset($application->last_payment_date->payment_date) ? date('jS F Y', strtotime(($application->last_payment_date->payment_date))) : "";
                        $data[$application->merchant_id]['cases'][$i]['emi_amount'] = $application->emi->emi;
                        $data[$application->merchant_id]['cases'][$i]['phone_number'] = $application->mobile_number;
                        $data[$application->merchant_id]['cases'][$i]['approved_amount'] = $application->approved_amount;
                        $data[$application->merchant_id]['cases'][$i]['product_name'] = $product_name;
                        $data[$application->merchant_id]['cases'][$i]['loan_application_no'] = isset($application->proFormaInvoice) && isset($application->proFormaInvoice->loan_application_no) ? $application->proFormaInvoice->loan_application_no : '-';
                        $i++;
                    }
                }
            }
            if (count($data) > 0) {

                foreach ($data as $merchant_data) {

                    $count = count($merchant_data['cases']);
                    $_data = array('merchant_id' => $merchant_data['merchant_id'], 'title'=> 'Pending Collection Merchant Wise', 'Total Cases' => $count);
                    $cwFactory->logger(json_encode($_data));

                    if ($merchant_data['email'] != "" && !(BNPL::is($merchant_data['merchant_id'])) && !in_array($merchant_data['merchant_id'], [6418, 6517, 6598, 6865, 6600])) {

                        $pdf = App::make('snappy.pdf.wrapper');
                        $statement = $pdf->loadView('front.application.collection_report', ['pendingReport' => $merchant_data, 'type' => '', 'lender' => $lender])->setOption('encoding', 'UTF-8')->setPaper('a4')->setOrientation('portrait');

                        $email_body = "Dear " . $merchant_data['merchant_name'] . ",<br/> 
                                    Please find your pending collection cases attached. We need your support to clear these cases as soon as possible. <br/>
                                    For discussing please call us on 8850077108 / 8928769161.";

                        if ($count < 6) {
                            $email_body .= "<br/><br/><table style=\"border:1px solid #000000; border-collapse: collapse;\">
                                    <tr>
                                    <th style=\"border:1px solid #000000;\">Loan Application ID</th>
                                    <th style=\"border:1px solid #000000;\">Customer Name</th>
                                    <th style=\"border:1px solid #000000;\">Phone Number</th>
                                    <th style=\"border:1px solid #000000;\">Over Due Amount</th>
                                    <th style=\"border:1px solid #000000;\">Installment Amount</th>
                                    <th style=\"border:1px solid #000000;\">Last Payment Date</th>
                                   
                                    </tr>";
                            foreach ($merchant_data['cases'] as $cases) {
                                $email_body .= "<tr>
                    <td style=\"padding: 0.55rem;vertical-align: top;border: 1px solid #000000;\">" . $cases['loan_application_no'] . "</td>
                    <td style=\"padding: 0.55rem;vertical-align: top;border: 1px solid #000000;\">" . $cases['customer_name'] . "</td>
                    <td style=\"padding: 0.55rem;vertical-align: top;border: 1px solid #000000;\">" . $cases['phone_number'] . "</td>
                    <td style=\"padding: 0.55rem;vertical-align: top;border: 1px solid #000000;\">" . $cases['over_due_amount'] . "</td>
                    <td style=\"padding: 0.55rem;vertical-align: top;border: 1px solid #000000;\">" . $cases['emi_amount'] . "</td>
                    <td style=\"padding: 0.55rem;vertical-align: top;border: 1px solid #000000;\">" . $cases['last_payment_date'] . "</td>
                    </tr>";
                            }
                            $email_body .= "</table>";
                        }

                        $mailData = ['email' => $merchant_data['email'], 'contact_number' => $merchant_data['contact_number'], 'id' => $merchant_data['merchant_id'], 'pdf' => $statement, 'fileName' => "Collection_Report_" . date('jS F Y') . ".pdf", 'body' => $email_body, 'subject' => "Pending Collection Cases for more than 5 days"];

                        $bcc = ['abhishek.shetty@creditfair.in', 'imran@creditfair.in', 'ketan@creditfair.in', 'amol@creditfair.in'];
                        Mail::send('emails.reminders.basic_reminder', [
                            'body' => $email_body,
                        ], function ($message) use ($mailData, $bcc) {
                            $message->to(explode(',', $mailData['email']));
                            $message->cc('collections@creditfair.in')->bcc($bcc)->subject($mailData['subject']);
                            $message->attachData($mailData['pdf']->output(), $mailData['fileName']);
                        });

                        $this->sendDocumentOnWhatsapp($mailData);
                        $countEmailSent++;
                    }

                }

            }

            (new Slack(new Request(['title' => 'Pending Collection Cases To Merchant', 'fields' => ['Total Email Sent' => $countEmailSent], 'group' => 'payment_collection'])))->send();
        }catch (\Exception $e){
            $_data = array(
                'exception' => 'Error while sending Pending Collection Report',
                'message' => $e->getMessage(),
                'line' => $e->getLine(),
                'trace' => $e->getTraceAsString()
            );
            $cwFactory->logger(json_encode($_data));
        }
    }

    public function sendDocumentOnWhatsapp($mailData){
        try {

            if ($mailData['contact_number']) {
                $name = str_replace(' ', '_', $mailData['fileName']);
                Storage::disk('storage')->put($name, $mailData['pdf']->output());


                $mailData['contact_number'] = array_filter(array_values(array_unique($mailData['contact_number'])));
                //(new Slack(new Request(['title' => 'Job Error', 'fields' => ['number' => implode(',', $mailData['contact_number'])]])))->send();
                $link = asset("stream/uploads/" . $name);
                foreach ($mailData['contact_number'] as $contact_number) {
                    sendWhatsAppMessage($contact_number, ['id' => $mailData['id'], 'caption' => 'Pending Collection Report', 'templateId' => Templates::$collection_report_doc, 'args' => [$link], 'templateType' => 'richTemplate']);
                }
                //Storage::disk('public_file')->delete($name);
            }
        }catch (\Exception $e){
                (new Slack(new Request(['title' => 'Job Error', 'fields' => ['M' => $e->getMessage(), 'L' => $e->getLine(), 'F' => $e->getFile()]])))->send();
        }
    }

    public function GSTFiling(){
        return view('admin.accounting.gst-filing');
    }

    public function exportGSTFiling(Request $request){
        ini_set("memory_limit", "-1");
        if(!$request->has('user_id')){

            $user = Auth::user();

            if(!$user->email){
                \Session::flash('error', 'Please add email in your account to receive report');
                return redirect()->back();
            }

            $payload[] = [
                'payload' => json_encode(['user_id' => $user->id, 'month' => $request->get('month'), 'year' => $request->get('year')]),
                'from' => 'gst_filing',
                'application_id' => 181,
                'available_at' => Carbon::now()->toDateTimeString(),
                'created_at' => Carbon::now()->toDateTimeString()
            ];

            $job = new Jobs();
            $job->insertQueue($payload);

            \Session::flash('success', 'You\'ll be receive the report on your email');
            return redirect()->back();
        }

        $user_id = $request->get('user_id');

        $filing_month = $request->get('month');
        $filing_year = $request->get('year');
        $filing_month = $filing_month + 1;
        $from = Carbon::createFromDate($filing_year, $filing_month)->startOfMonth()->toDateTimeString();
        $to = Carbon::createFromDate($filing_year, $filing_month)->endOfMonth()->toDateTimeString();

        $response = array();
        $status =  ['disbursed','nach registered','closed ','cancellation in-process'];

        $transactionsData = PaymentTransaction::where('payment_date','>=', $from)->where('payment_date','<=', $to)->groupBy('application_id')->get(['application_id']);

        $applicationIDs = [];
        foreach ($transactionsData as $transactionsItem){
            $applicationIDs[] = $transactionsItem->application_id;
        }

        $consumerApplications = ConsumerApplicationRelation::with('merchant','logs','emi', 'application_element','emi.offer','lender')->wherein('state',$status)->whereNull('is_deleted')->whereIn('id', $applicationIDs)->get();
        $consumerDocument = new ConsumerDocument(new Request());
        unset($applicationIDs, $transactionsData);
        foreach ($consumerApplications as $_keyIndex => $consumerApplication) {
            if (isset($consumerApplications[$_keyIndex - 1])){
                unset($consumerApplications[$_keyIndex - 1]);
            }
            if(isset($consumerApplication->emi) and $consumerApplication->emi != null && isset($consumerApplication->logs->created_at)) {
                if (!isset($response[$consumerApplication->id]['name'])) {
                    $response[$consumerApplication->id]['name'] = $consumerApplication->name;
                }
                if (!isset($response[$consumerApplication->id]['lender'])) {
                    $response[$consumerApplication->id]['lender'] = $consumerApplication->lender->name;
                }
                if (!isset($response[$consumerApplication->id]['subvention_rate'])) {
                    $response[$consumerApplication->id]['subvention_rate'] = $consumerApplication->emi->subvention;
                }
                if (!isset($response[$consumerApplication->id]['approved_amount'])) {
                    $response[$consumerApplication->id]['approved_amount'] = $consumerApplication->approved_amount;
                }
                $disbursed_month = date('Y-m', strtotime($consumerApplication->logs->created_at));
                $response[$consumerApplication->id]['month'][$disbursed_month]['processing_fees_net_amount'] = 0;
                if($consumerApplication->emi->processing_fee > 0) {
                    $gstDetails = $consumerDocument->getGSTDetails(
                        [
                            'amount' => $consumerApplication->emi->processing_fee,
                            'state' => (isset($consumerApplication->permanent_address_state) && !empty($consumerApplication->permanent_address_state)) ? $consumerApplication->permanent_address_state : (isset($consumerApplication->current_address_state) && !empty($consumerApplication->current_address_state) ? $consumerApplication->current_address_state : '')
                        ]
                    );
                    foreach ($gstDetails as $gst) {
                        $response[$consumerApplication->id]['month'][$disbursed_month]['processing_fees_net_amount'] = $gst['net_amount'];
                    }
                }
                $last_transaction_date = date('Y-m-d', strtotime($consumerApplication->logs->created_at));

                $loanschedule = json_decode(json_encode($this->getLoanSchedule($consumerApplication->id,1,1,$consumerApplication)));
                if($loanschedule) {
                    if (!isset($response[$consumerApplication->id]['interest_ror'])) {
                        $response[$consumerApplication->id]['revenue_ror'] = $loanschedule->summary->interest;
                    }
                    if (!isset($response[$consumerApplication->id]['interest_ror'])) {
                        $response[$consumerApplication->id]['interest_ror'] = $loanschedule->summary->irr;
                    }
                    foreach ($loanschedule->schedule as $emi_date => $payment) {
                        if($consumerApplication->application_element->foreclosure_date == "" || $consumerApplication->application_element->foreclosure_date >=$emi_date) {
                            $amount_received = $payment->total_payable - $payment->amount_due;
                            if ($amount_received > $payment->emi_amount) {
                                $total_received = 0;
                                $bounce_received = 0;
                                $penalty_received = 0;
                                $bounce_charges_payable = $payment->bounce_charges;
                                $penal_interest_payable = $payment->delay_penalty;

                                foreach ($payment->transaction as $payment_transaction) {
                                    // if (strtotime($payment_transaction->payment_date) >= strtotime($from) && strtotime($payment_transaction->payment_date) <= strtotime($to) && empty($payment_transaction->is_deleted_at) and empty($payment_transaction->refunded_at and $payment_transaction->created_at < date('Y-m-d 00:00:00'))) {
                                    // from and to payment date condition removed to include older transactions when calculting total recieved
                                    if (empty($payment_transaction->is_deleted_at) && empty($payment_transaction->refunded_at) && $payment_transaction->created_at < date('Y-m-d 00:00:00')) {
                                        $total_received = $total_received + $payment_transaction->amount;
                                        if ($total_received > $payment->emi_amount) {
                                            $bounce_received_instance = $bounce_charges_payable > 0 ? (($payment->bounce_charges < ($total_received - $payment->emi_amount)) ? ($payment->bounce_charges - $bounce_received) : ($total_received - $payment->emi_amount - $bounce_received)) : 0;
                                            $penalty_received_instance = $penal_interest_payable > 0 ? (($payment->delay_penalty < ($total_received - $payment->emi_amount - $payment->bounce_charges)) ? ($payment->delay_penalty - $penalty_received) : ($total_received - $payment->emi_amount - $payment->bounce_charges - $penalty_received)) : 0;
                                            if ($bounce_received_instance > 0) {
                                                $bounce_received = $bounce_received + $bounce_received_instance;
                                                $payment_month = date('Y-m', strtotime($payment_transaction->payment_date));
                                                if (isset($response[$consumerApplication->id]['month'][$payment_month]['bounces_charges'])) {
                                                    $response[$consumerApplication->id]['month'][$payment_month]['bounces_charges'] += $bounce_received_instance;
                                                    $response[$consumerApplication->id]['month'][$payment_month]['payment_date'] = $payment_transaction->payment_date;
                                                } else {
                                                    $response[$consumerApplication->id]['month'][$payment_month]['bounces_charges'] = $bounce_received_instance;
                                                    $response[$consumerApplication->id]['month'][$payment_month]['payment_date'] = $payment_transaction->payment_date;
                                                }
                                                $bounce_charges_payable = $bounce_charges_payable - $bounce_received_instance;
                                            }
                                            if($penalty_received_instance > 0){
                                                $penalty_received = $penalty_received + $penalty_received_instance;
                                                $payment_month = date('Y-m', strtotime($payment_transaction->payment_date));
                                                if (isset($response[$consumerApplication->id]['month'][$payment_month]['penal_interest'])) {
                                                    $response[$consumerApplication->id]['month'][$payment_month]['penal_interest'] += $penalty_received_instance;
                                                    $response[$consumerApplication->id]['month'][$payment_month]['payment_date'] = $payment_transaction->payment_date;
                                                } else {
                                                    $response[$consumerApplication->id]['month'][$payment_month]['penal_interest'] = $penalty_received_instance;
                                                    $response[$consumerApplication->id]['month'][$payment_month]['payment_date'] = $payment_transaction->payment_date;
                                                }
                                                $penal_interest_payable = $penal_interest_payable - $penalty_received_instance;

                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    foreach ($response[$consumerApplication->id]['month'] as $month => $monthly_data) {

                        if (!isset($response[$consumerApplication->id]['month'][$month]['principal_outstanding'])) {
                            if($month > date('Y-m',strtotime($consumerApplication->application_element->last_emi_day))) {
                                $response[$consumerApplication->id]['month'][$month]['principal_outstanding'] = 0;
                            }else{
                                $response[$consumerApplication->id]['month'][$month]['principal_outstanding'] = $loanschedule->summary->loan_outstanding;
                            }
                        }
                        if (isset($monthly_data['bounces_charges']) && $monthly_data['bounces_charges'] > 0) {
                            $state_name_bounces = (isset($consumerApplication->permanent_address_state) && !empty($consumerApplication->permanent_address_state)) ? $consumerApplication->permanent_address_state : (isset($consumerApplication->current_address_state) && !empty($consumerApplication->current_address_state) ? $consumerApplication->current_address_state : '');
                            $gstDetails = $consumerDocument->getGSTDetails(
                                [
                                    'amount' => $monthly_data['bounces_charges'],
                                    'state' => $state_name_bounces
                                ]
                            );
                            foreach ($gstDetails as $gst) {
                                $response[$consumerApplication->id]['month'][$month]['bounces_charges'] = $gst['net_amount'];
                                $response[$consumerApplication->id]['month'][$month]['charges_state'] = $state_name_bounces;
                            }
                        }
                        if (isset($monthly_data['penal_interest']) && $monthly_data['penal_interest'] > 0) {
                            $state_name_penal = (isset($consumerApplication->permanent_address_state) && !empty($consumerApplication->permanent_address_state)) ? $consumerApplication->permanent_address_state : (isset($consumerApplication->current_address_state) && !empty($consumerApplication->current_address_state) ? $consumerApplication->current_address_state : '');
                            // $gstDetails = $consumerDocument->getGSTDetails(
                            //     [
                            //         'amount' => $monthly_data['penal_interest'],
                            //         'state' => $state_name_penal
                            //     ]
                            // );
                            // foreach ($gstDetails as $gst) {
                                $response[$consumerApplication->id]['month'][$month]['penal_interest'] = $monthly_data['penal_interest'];
                                $response[$consumerApplication->id]['month'][$month]['charges_state'] = $state_name_penal;
                            // }
                        }
                    }

                    ksort($response[$consumerApplication->id]['month']);
                }

            }
        }

        $bounce_penal[] = ['#',	'Name', 'Invoice ID', 'Email', 'Phone', 'State', 'Total Subvention', 'Charges', 'Total Professing Fees', 'IGST', 'CGST', 'SGST', 'Processing Fees/Subvention', 'Invoice Date', 'Type'];

        foreach ($response as $application_id => $monthWiseItem){
            foreach ($monthWiseItem['month'] as $item) {
                if(isset($item['charges_state'])) {
                    $chargedInvoices = ChargedInvoices::where('application_id', $application_id)->where(function ($query) use ($item) {
                        $query->where('invoice_date',date('Y-m-d',strtotime($item['payment_date'])))
                            ->orWhere('invoice_date',$item['payment_date']);
                    })->get();

                    foreach ($chargedInvoices as $chargedInvoice){

                        $type = $chargedInvoice->type == 'bounce' ? 'bounces_charges' : 'penal_interest';

                        if(isset($item[$type])){
                            $total_amount = $item[$type] + $chargedInvoice->igst + $chargedInvoice->cgst + $chargedInvoice->sgst;

                            $bounce_penal[] =  [
                                '#' => $application_id,
                                'Name' => $monthWiseItem['name'],
                                'Lender Name' =>$consumerApplication->lender->name,
                                'Invoice ID' => isset($chargedInvoice->invoice_id) ? $chargedInvoice->invoice_id : '',
                                'Email' => '',
                                'Phone' => '',
                                'State' => $item['charges_state'],
                                'Total Subvention' => 0,
                                'Charges' => $total_amount,
                                'Total Professing Fees' => 0,
                                'IGST' => $chargedInvoice->igst,
                                'CGST' => $chargedInvoice->cgst,
                                'SGST' => $chargedInvoice->sgst,
                                'Processing Fees/Subvention' => $item[$type],
                                'Invoice Date' => $item['payment_date'],
                                'Type' => $type
                            ];
                        }
                    }
                    /*if(isset($item['bounces_charges']) && $item['bounces_charges']){
                        $bounce_penal[] = $this->getChargedData($application_id, $monthWiseItem, $item, 'bounces_charges');
                    }
                    if(isset($item['penal_interest']) && $item['penal_interest']){
                        $bounce_penal[] = $this->getChargedData($application_id, $monthWiseItem, $item, 'penal_interest');
                    }*/
                }
            }
        }

        $B2B = $this->getB2BInvoice($from, $to, $request);

        $B2C = $this->getB2CInvoice($from, $to, $request);

        $request = new Request([
            'sheet' => ['B2B','B2C','Penal & Bounce'],
            'data'  => [$B2B, $B2C, $bounce_penal]
        ]);

        $user = User::find($user_id);

        $file = time().'_'.Carbon::now()->toDateTimeString().'_gst_filing.xlsx';
        // $file = 'gst_filing.xlsx';
//        return Excel::download((new ExporterMultipleSheet($request)), $file);
        Excel::store(new ExporterMultipleSheet($request), $file);

        if($user->email) {
            Mail::send('emails.reminders.basic_reminder',
                ['body' => 'GST Filing of month ' . $filing_month]
                , function ($message) use ($file, $filing_month, $user) {
                    $message->to(_env('NOTIFY_EMAIL', ''))->subject('GST filing report of month '.$filing_month);
                    $message->cc([$user->email]);
                    $message->attachData(file_get_contents(storage_path() . '/app/' . $file), 'GST Filing of Month ' . $filing_month . '.xlsx');
                });
        }
    }

    public function confirmGSTFiling(Request $request){
        $user_id = '';
        if(!$request->has('user_id')){
            $user = Auth::user();
            $user_id = $user->id;
        }else{
            $user_id = $request->has('user_id') ? $request->get('user_id') : '';
        }

        $filing_month = $request->get('month');
        $filing_year = $request->get('year');
        $from = Carbon::createFromDate($filing_year, $filing_month)->startOfMonth()->toDateTimeString();
        $to = Carbon::createFromDate($filing_year, $filing_month)->endOfMonth()->toDateTimeString();

        $confirm_filing_date = !empty($request->get('filing_date')) ?
            Carbon::createFromFormat('Y-m-d', $request->get('filing_date'))->toDateTimeString() : Carbon::now()->toDateTimeString();

        $charged_invoices = ChargedInvoices::where('invoice_date','>=', $from)->where('invoice_date','<=', $to)->whereNull('gst_filing_confirmed');

        $log = [
            'month' => Carbon::parse($from)->format('F'),
            'year' => Carbon::parse($from)->format('Y'),
            'date_of_filing' => $confirm_filing_date,
            'filed_by' => $user_id,
            'created_at'=> Carbon::now()->toDateTimeString(),
            'updated_at'=> Carbon::now()->toDateTimeString(),
        ];

        (new \App\GSTFilingLog)->fill($log)->save();

        if(count($charged_invoices->get()) > 0){
            $charged_invoices->update(['gst_filing_confirmed' => $confirm_filing_date, 'gst_filing_confirmed_by' => $user_id]);
            \Session::flash('success', 'Filing date confirmed!');
            return redirect()->back();
        }else{
            \Session::flash('error', 'No invoices yet to be filed in the given period');
            return redirect()->back();
        }

    }

    public function getChargedData($application_id, $monthWiseItem, $item, $type){

        $amount = $item[$type];
        $state = $item['charges_state'];

        $IGST = $state != 'Maharashtra' ? ($amount/100) * 18 : 0;
        $CGST = $state == 'Maharashtra' ? ($amount/100) * 9 : 0;
        $SGST = $state == 'Maharashtra' ? ($amount/100) * 9 : 0;

        $total_amount = $amount + $IGST + $CGST + $SGST;

        $chargedInvoices = ChargedInvoices::where('application_id', $application_id)->where('invoice_date',date('Y-m-d',strtotime($item['payment_date'])))->where('amount',round($total_amount));
        if($type == 'bounces_charges'){
            $chargedInvoices = $chargedInvoices->where('type','bounce');
        }else{
            $chargedInvoices = $chargedInvoices->where('type','penal');
        }
        if($IGST){
            $chargedInvoices = $chargedInvoices->where('igst',round($IGST,2));
        }
        if($CGST){
            $chargedInvoices = $chargedInvoices->where('cgst',round($CGST,2));
        }
        if($SGST){
            $chargedInvoices = $chargedInvoices->where('sgst',round($SGST,2));
        }

        $chargedInvoices = $chargedInvoices->orderBy('created_at','desc')->first(['invoice_id']);

        return  [
            '#' => $application_id,
            'Name' => $monthWiseItem['name'],
            'Invoice ID' => isset($chargedInvoices->invoice_id) ? $chargedInvoices->invoice_id : '',
            'Email' => '',
            'Phone' => '',
            'State' => $state,
            'Total Subvention' => 0,
            'Charges' => $total_amount,
            'Total Professing Fees' => 0,
            'IGST' => $IGST,
            'CGST' => $CGST,
            'SGST' => $SGST,
            'Processing Fees/Subvention' => $amount,
            'Invoice Date' => $item['payment_date'],
            'Type' => $type
        ];
    }

    public function getB2BInvoice($from, $to, $request){

        $invoices = DB::select('select consumer_application.*, emi_calculation.subvention, emi_calculation.upfront_from_customer, merchant.merchant_name, merchant.gst_number, merchant.charge_subvention_remaining_amount, merchant.state as merchant_state, lenders.name as lender_name from consumer_application
left join merchant on merchant.id  =  consumer_application.merchant_id
left join lenders on lenders.id = consumer_application.lender_id
left join emi_calculation on emi_calculation.application_id  =  consumer_application.id
where consumer_application.id in (select application_id from emi_calculation where application_id in (
  select id from consumer_application where id in (select status_logs.application_id from status_logs where created_at >= "'.$from.'" and created_at <= "'.$to.'" and status = "disbursed" group by application_id order by created_at desc) and is_deleted is null
) and subvention > 0) and merchant.is_gst = 1');

        $response[] = ['#',	'Name', 'Lender Name',	'Invoice ID', 'GST Number', 'Email', 'Phone', 'State', 'Total Subvention', 'Total Professing Fees', 'IGST', 'CGST', 'SGST', 'Processing Fees/Subvention', 'Invoice Date'];
        $consumerDocument = new ConsumerDocument($request);
        foreach ($invoices as $invoice){

            $downPayment = 0;
            if($invoice->charge_subvention_remaining_amount){
                $downPayment = $invoice->upfront_from_customer;
            }

            $subvention_amount = (($invoice->approved_amount - $downPayment) * $invoice->subvention) / 100;

            if ($subvention_amount && (isset($invoice->current_address_state) || isset($invoice->permanent_address_state))) {
                $gstDetails = $consumerDocument->getGSTDetails(
                    [
                        'amount' => $subvention_amount,
                        'state' => $invoice->merchant_state
                    ],0
                );

                $disbursed_date = $consumerDocument->getDisbursedDate($invoice->id);

                $gstDetails = (isset($gstDetails[0])) ? $gstDetails[0] : 0;


                $invoiceDB = Invoices::where('application_id', $invoice->id)->where('type','subvention_invoice')->orderBy('created_at','desc')->first(['invoice_id']);

                if ($gstDetails) {

                    $IGST = $gstDetails['taxes'] == 'IGST' ? $gstDetails['gst_amount'] : 0;
                    $CGST = $gstDetails['taxes'] != 'IGST' ? $gstDetails['gst_amount'] : 0;
                    $SGST = $gstDetails['taxes'] != 'IGST' ? $gstDetails['gst_amount'] : 0;
                    $total_subvention_amount = $subvention_amount + $IGST + $CGST + $SGST;


                    $response[] = [
                        '#' => $invoice->id,
                        'Name' => $invoice->merchant_name,
                        'Lender Name' =>$invoice->lender_name,
                        'Invoice ID' => isset($invoiceDB->invoice_id) ? $invoiceDB->invoice_id : '',
                        'GST Number' => isset($invoice->gst_number) ? wall_decrypt($invoice->gst_number) : '',
                        'Email' => '',
                        'Phone' => '',
                        'State' => $invoice->merchant_state,
                        'Total Subvention' => $total_subvention_amount,
                        'Total Professing Fees' => 0,
                        'IGST' => $IGST,
                        'CGST' => $CGST,
                        'SGST' => $SGST,
                        'Processing Fees/Subvention' => $gstDetails['net_amount'],
                        'Invoice Date' => $disbursed_date,
                    ];
                }
            }
        }

        return $response;
    }

    public function getB2CInvoice($from, $to, $request){

        $invoices = DB::select('select consumer_application.*, emi_calculation.processing_fee, lenders.name as lender_name from emi_calculation left join consumer_application on consumer_application.id = emi_calculation.application_id 
                                left join lenders on lenders.id = consumer_application.lender_id where application_id in (
                                  select id from consumer_application where id in (select status_logs.application_id from status_logs where created_at >= "'.$from.'" and created_at <= "'.$to.'" and status = "disbursed" group by application_id order by created_at desc) and is_deleted is null
                                ) and processing_fee > 0');

        $response[] = ['#',	'Name', 'Lender Name', 'Invoice ID', 'Email', 'Phone', 'State', 'Total Subvention', 'Charges', 'Total Professing Fees', 'IGST', 'CGST', 'SGST', 'Processing Fees/Subvention', 'Invoice Date', 'Type'];
        $consumerDocument = new ConsumerDocument($request);
        foreach ($invoices as $invoice){


            if (($invoice->processing_fee) && (isset($invoice->current_address_state) || isset($invoice->permanent_address_state))) {
                $gstDetails = $consumerDocument->getGSTDetails(
                    [
                        'amount' => $invoice->processing_fee,
                        'state' => (isset($invoice->permanent_address_state) && !empty($invoice->permanent_address_state)) ? $invoice->permanent_address_state : (isset($invoice->current_address_state) && !empty($invoice->current_address_state) ? $invoice->current_address_state : '')
                    ]
                );

                $disbursed_date = $consumerDocument->getDisbursedDate($invoice->id);

                $gstDetails = (isset($gstDetails[0])) ? $gstDetails[0] : 0;

                $invoiceDB = Invoices::where('application_id', $invoice->id)->where('type','processing_invoice')->orderBy('created_at','desc')->first(['invoice_id']);

                if ($gstDetails) {

                    $response[] = [
                        '#' => $invoice->id,
                        'Name' => $invoice->name,
                        'Lender Name' => $invoice->lender_name,
                        'Invoice ID' => isset($invoiceDB->invoice_id) ? $invoiceDB->invoice_id : '',
                        'Email' => '',
                        'Phone' => '',
                        'State' => (isset($invoice->permanent_address_state) && !empty($invoice->permanent_address_state)) ? $invoice->permanent_address_state : (isset($invoice->current_address_state) && !empty($invoice->current_address_state) ? $invoice->current_address_state : ''),
                        'Total Subvention' => 0,
                        'Charges' => 0,
                        'Total Professing Fees' => $invoice->processing_fee,
                        'IGST' => $gstDetails['taxes'] == 'IGST' ? $gstDetails['gst_amount'] : 0,
                        'CGST' => $gstDetails['taxes'] != 'IGST' ? $gstDetails['gst_amount'] : 0,
                        'SGST' => $gstDetails['taxes'] != 'IGST' ? $gstDetails['gst_amount'] : 0,
                        'Processing Fees/Subvention' => $gstDetails['net_amount'],
                        'Invoice Date' => date('Y-m-d', strtotime($disbursed_date)),
                        'type' => 'Processing Fee'
                    ];
                }
            }
        }

        return $response;
    }

    public function getLastDayOfMOnth($toodate){
        $lastday = date('Y-m-d',strtotime(date('Y-m-',strtotime($toodate)).date('t',strtotime($toodate))));
        return $lastday;
    }

    public function getLoanSchedule($id,$json = 0,$foreclosure = 0,$application = Null)
    {
        if($application == Null) {
            $application = ConsumerApplication::with('merchant', 'emi', 'application_element', 'emi.offer', 'emi_payment.transaction','moratoriums')->where('id', $id)->whereNull('is_deleted')->first();
            $emiPaymentData = $application->emi_payment;
        }else{
            $emiPaymentData = EmiPayment::with('transaction')->where('application_id', $id)->get();//ConsumerApplication::with('emi_payment.transaction')->where('id', $id)->whereNull('is_deleted')->first();
        }
        if($application->emi){
            $loan_management = new LoanManagement();
            $loanamount = ((isset($application->approved_amount) && $application->approved_amount != 0) ? $application->approved_amount : $application->loan_amount) - $application->emi->upfront_from_customer;

            $payment_details = array();
            $emi_schedules = $loan_management->generateDues($id, 1, $application);
            foreach ($emiPaymentData as $payments) {
                $payment_details[$payments['emi_date']] = $payments;
            }

            $downPayment = 0;
            if($application->merchant && $application->merchant->charge_subvention_remaining_amount){
                $downPayment = $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) - $downPayment) * ($application->emi->subvention)) / 100) : 0;
            $amount_disbursed = $loanamount - $subvention_amount;

            $frequency_multiplier = $this->payment_frequency[$application->emi->payment_frequency];
//            if (isset($application->emi->rate) && !empty($application->emi->rate) && isset($application->emi->irr_rate) && !empty($application->emi->irr_rate)) {
//                $rate = $application->emi->rate;
//                $annualised_interest = $application->emi->annualised_interest;
//                $irr_rate = $application->emi->irr_rate;
//                $annualised_irr = $application->emi->annualised_irr;
//            } else {
            $emis_array = array();
            $emi_irr_array = array();
            array_push($emis_array, -$loanamount);
            array_push($emi_irr_array, -($amount_disbursed));

            if (isset($emi_schedules)) {
                foreach ($emi_schedules as $schedule) {
                    array_push($emis_array, $schedule['amount']);
                    array_push($emi_irr_array, $schedule['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;
            }

            $annualised_interest = round((((($rate + 1) * $frequency_multiplier) - $frequency_multiplier) * 100) / 100, 2);
            $annualised_irr = round((((($irr_rate + 1) * $frequency_multiplier) - $frequency_multiplier) * 100) / 100, 2);
//                if ($rate > 0 && $annualised_interest > 0 && $irr_rate > 0 && $annualised_irr > 0) {
//                    ApplicationEMICalculation::where('id', $application->emi->id)
//                        ->update(['rate' => $rate, 'annualised_interest' => $annualised_interest, 'irr_rate' => $irr_rate, 'annualised_irr' => $annualised_irr]);
//                }

            //   }
            $foreclosure_date = (isset($application->application_element->foreclosure_date) && !empty($application->application_element->foreclosure_date) && $application->application_element->foreclosure_date != "1970-01-01") ? $application->application_element->foreclosure_date : '';

            if(isset($payment_details)){
                $principal_oustanding = $loanamount;
                $principal_oustanding_subvention = $amount_disbursed;
                $subvention_amount_balance = $subvention_amount;
                foreach ($payment_details as $emi_date => $payment){
                    if($foreclosure_date == "" || $emi_date <= $foreclosure_date) {
                        $payment_details[$emi_date]->interest = $principal_oustanding * ($rate / 100);
                        $payment_details[$emi_date]->principal = $payment->emi_amount - $payment_details[$emi_date]->interest;
                        $payment_details[$emi_date]->irr = $principal_oustanding_subvention * ($irr_rate / 100);
                        $payment_details[$emi_date]->subvention = $payment_details[$emi_date]->irr - $payment_details[$emi_date]->interest;
                        $subvention_amount_balance = $subvention_amount_balance - $payment_details[$emi_date]->subvention;
                        $payment_details[$emi_date]->subvention_amount_balance = $subvention_amount_balance;
                        $principal_oustanding = $principal_oustanding - $payment_details[$emi_date]->principal;
                        $principal_oustanding_subvention = $principal_oustanding_subvention - $payment_details[$emi_date]->principal + $payment_details[$emi_date]->subvention;
                        $payment_details[$emi_date]->principal_outstanding = $principal_oustanding;
                        $payment_details[$emi_date]->principal_outstanding_subvention = $principal_oustanding_subvention;
                        if($foreclosure_date != "" && $emi_date == $foreclosure_date){
                            $payment_details[$emi_date]->principal_outstanding = 0;
                            $payment_details[$emi_date]->principal_outstanding_subvention = 0;
                        }

                        if ($foreclosure == 0) {
                            $foreclosuredetails = $loan_management->getForeclosureAmount($id, $emi_date);
                            $payment_details[$emi_date]->fore_closure_amount = isset($foreclosuredetails['future_emi']) ? $foreclosuredetails['future_emi'] : 0;
                        } else {
                            $payment_details[$emi_date]->fore_closure_amount = 0;
                        }
                    }
                }
            }

            $response['summary']['loan_amount'] = ((isset($application->approved_amount) && $application->approved_amount != 0) ? $application->approved_amount : $application->loan_amount);
            $response['summary']['loan_outstanding'] = $loanamount;
            $response['summary']['tenure'] = $application->emi->tenure;
            $response['summary']['remaining_emi'] = $application->emi->remaining_emi;
            $response['summary']['quoted_interest'] = $application->emi->interest_rate;
            $response['summary']['interest'] = $rate;
            $response['summary']['annualised_interest'] = $annualised_interest;
            $response['summary']['irr'] = $irr_rate;
            $response['summary']['annualised_irr'] = $annualised_irr;
            $response['summary']['subvention'] = $application->emi->subvention;
            $response['summary']['processing_fee'] = $application->emi->processing_fee;
            $response['summary']['emi'] = $application->emi->emi;
            $response['summary']['advance_due'] = $application->emi->upfront_from_customer;
            $response['summary']['last_emi_date'] = $application->emi->emi_date;
            $response['summary']['last_emi_date'] = $application->application_element->last_emi_date;
            $response['customer_name'] = $application->name;
            $response['id'] = $application->id;
            $response['summary']['merchant_name'] = $application->merchant ? $application->merchant->merchant_name : '';
            $response['summary']['net_disbursement_amount'] = (isset($application->emi->upfront_from_credit_fair) && $application->emi->upfront_from_credit_fair != 0) ? $application->emi->upfront_from_credit_fair : ((isset($application->approved_amount) && $application->approved_amount != 0) ? $application->approved_amount : $application->loan_amount);
            $response['schedule'] = $payment_details;
            if ($json == 0) {
                return view('admin.accounting.loanschedule', $response);
            } else {
                return $response;
            }
        }else {
//            (new Slack(new Request(['title' => 'Loan Schedule Emi Not Generated ', 'fields' => ['ID' => $id]])))->send();
        }
    }

    public function savePTPTaggingData(Request $request)
    {
        try {
            // Block duplicate Settlement entry for the same application
            if ($request->input('dispo_code') === 'Settlement') {
                $exists = CollectionAction::where('application_id', $request->input('application_id'))
                    ->where('dispo_code', 'Settlement')
                    ->where('ptp_date', '>=', Carbon::now()->startOfDay()->toDateTimeString())
                    ->exists();

                if ($exists) {
                    return response()->json(['status' => 'error', 'message' => 'Settlement entry already processed for this application.']);
                }
            }

            // Build installment details JSON if installments were provided
            $installmentDetails = null;
            $installments = $request->input('installments', []);
            if (!empty($installments)) {
                $installmentDetails = json_encode($installments);
            }

            // Map interaction_type radio value to on_field_visit flag
            $onFieldVisit = $request->input('interaction_type') === 'On-field (FOS)' ? 1 : 0;

            // Parse dates from DD-MM-YYYY to Y-m-d
            $actionDate     = $request->input('start_date')
                ? Carbon::createFromFormat('d-m-Y', $request->input('start_date'))->format('Y-m-d')
                : null;
            $ptpDate        = $request->input('ptp_date')
                ? Carbon::createFromFormat('d-m-Y', $request->input('ptp_date'))->format('Y-m-d')
                : null;
            $nextActionDate = $request->input('next_action_date')
                ? Carbon::createFromFormat('d-m-Y', $request->input('next_action_date'))->format('Y-m-d')
                : null;

            $action = CollectionAction::create([
                'application_id'          => $request->input('application_id'),
                'user_id'                 => Auth::id(),
                'dispo_code'              => $request->input('dispo_code'),
                'on_field_visit'          => $onFieldVisit,
                'action_date'             => $actionDate,
                'ptp_date'                => $ptpDate,
                'next_action_date'        => $nextActionDate,
                'amount_to_be_received'   => $request->input('amount_to_receive'),
                'remarks'                 => $request->input('remark'),
                'installment_details'     => $installmentDetails,
            ]);

            if ($request->input('dispo_code') === 'Settlement') {
                if (!empty($installments)) {
                    $makerCheckerResult = $this->triggerSettlementMakerChecker($action, $request->input('application_id'), $installments);
                    if (!is_null($makerCheckerResult)) {
                        return response()->json(['status' => 'error', 'message' => $makerCheckerResult]);
                    }
                }
            }

            return response()->json(['status' => 'success', 'message' => 'Data saved successfully.']);
        } catch (\Exception $e) {
            return response()->json(['status' => 'error', 'message' => $e->getMessage()]);
        }
    }

    public function updatePTPTaggingData(Request $request, $id)
    {
        try {
            $action = CollectionAction::find($id);

            if (!$action) {
                return response()->json(['status' => 'error', 'message' => 'Record not found.']);
            }

            // Only allow edit if ptp_date is not expired
            if ($action->ptp_date && $action->ptp_date->lt(Carbon::today())) {
                return response()->json(['status' => 'error', 'message' => 'Cannot edit an expired PTP record.']);
            }

            $installmentDetails = null;
            $installments = $request->input('installments', []);
            if (!empty($installments)) {
                $installmentDetails = json_encode($installments);
            }

            $onFieldVisit = $request->input('interaction_type') === 'On-field (FOS)' ? 1 : 0;

            $actionDate     = $request->input('start_date')
                ? Carbon::createFromFormat('d-m-Y', $request->input('start_date'))->format('Y-m-d')
                : null;
            $ptpDate        = $request->input('ptp_date')
                ? Carbon::createFromFormat('d-m-Y', $request->input('ptp_date'))->format('Y-m-d')
                : null;
            $nextActionDate = $request->input('next_action_date')
                ? Carbon::createFromFormat('d-m-Y', $request->input('next_action_date'))->format('Y-m-d')
                : null;

            $action->update([
                'dispo_code'            => $request->input('dispo_code'),
                'on_field_visit'        => $onFieldVisit,
                'action_date'           => $actionDate,
                'ptp_date'              => $ptpDate,
                'next_action_date'      => $nextActionDate,
                'amount_to_be_received' => $request->input('amount_to_receive'),
                'remarks'               => $request->input('remark'),
                'installment_details'   => $installmentDetails,
            ]);

            if ($request->input('dispo_code') === 'Settlement') {
                $this->upsertSettlementJob($action->id, $action->application_id, $ptpDate);
                if (!empty($installments)) {
                    $makerCheckerResult = $this->triggerSettlementMakerChecker($action, $action->application_id, $installments);
                    if (!is_null($makerCheckerResult)) {
                        return response()->json(['status' => 'error', 'message' => $makerCheckerResult]);
                    }
                }
            }

            return response()->json(['status' => 'success', 'message' => 'Record updated successfully.']);
        } catch (\Exception $e) {
            return response()->json(['status' => 'error', 'message' => $e->getMessage()]);
        }
    }

    private function triggerSettlementMakerChecker($collectionAction, $applicationId, $installments)
    {
        $settlementAmount = array_sum(array_values($installments));

        if ($settlementAmount <= 0) {
            return 'Settlement Amount less than zero';
        }

        $pos = (float) \App\ConsumerApplicationAdditional::where('application_id', $applicationId)
            ->value('principal_outstanding');

        if ($pos <= 0) {
            return 'Principal Outstanding Amount less than zero';
        }

        $waiverPercentage = (($pos - $settlementAmount) / $pos) * 100;

        // The request is visible to any user whose Maximum POS Waiver covers
        // this waiver percentage — no single assignee.
        $eligibleCheckers = User::where('max_pos_waiver', '>', 0)
            ->where('max_pos_waiver', '>=', round($waiverPercentage, 2))
            ->whereNull('deleted_at')
            ->get();

        // Upsert: one record per application
        \App\SettlementMakerChecker::updateOrCreate(
            ['application_id' => $applicationId],
            [
                'collection_action_id'  => $collectionAction->id,
                'maker_id'              => Auth::id(),
                'checker_id'            => null,
                'pos'                   => $pos,
                'settlement_amount'     => $settlementAmount,
                'waiver_percentage'     => round($waiverPercentage, 2),
                'requested_to_user_id'  => null,
                'status'                => 'pending',
                'remark'                => null,
                'action_at'             => null,
            ]
        );

        // Send approval request email to every eligible checker
        $checkerEmails = $eligibleCheckers->pluck('email')->filter()->unique()->values()->all();
        if (!empty($checkerEmails)) {
            $body = "Settlement Approval Request\n\n"
                . "Application ID     : {$applicationId}\n"
                . "POS                : ₹" . number_format($pos, 2) . "\n"
                . "Settlement Amount  : ₹" . number_format($settlementAmount, 2) . "\n"
                . "Waiver Percentage  : " . round($waiverPercentage, 2) . "%\n\n"
                . "Please review and approve / reject in the system.";

            \Mail::send('emails.blank', ['body' => nl2br($body)], function ($message) use ($checkerEmails, $applicationId) {
                $message->to($checkerEmails)
                    ->subject("Settlement Approval Required — Application #{$applicationId}");
            });
        }
        return null;
    }

    public function approveSettlementMakerChecker(Request $request, $id)
    {
        $record = \App\SettlementMakerChecker::find($id);
        if (!$record) {
            return response()->json(['status' => 'error', 'message' => 'Record not found.']);
        }
        if (!Auth::check() || !Auth::user()->canApproveSettlementWaiver($record->waiver_percentage)) {
            return response()->json(['status' => 'error', 'message' => 'You are not authorised to approve this request.']);
        }
        $record->update([
            'status'     => 'approved',
            'checker_id' => Auth::id(),
            'remark'     => $request->input('remark'),
            'action_at'  => Carbon::now()->toDateTimeString(),
        ]);
        request()->merge(['secondary_status' => 'settlement-in-progress', 'source' => 'settlement-maker-checker']);
        (new ConsumerApplicationController())->updateStatus($record->application_id);
        return response()->json(['status' => 'success', 'message' => 'Settlement request approved.']);
    }

    public function rejectSettlementMakerChecker(Request $request, $id)
    {
        $record = \App\SettlementMakerChecker::find($id);
        if (!$record) {
            return response()->json(['status' => 'error', 'message' => 'Record not found.']);
        }
        if (!Auth::check() || !Auth::user()->canApproveSettlementWaiver($record->waiver_percentage)) {
            return response()->json(['status' => 'error', 'message' => 'You are not authorised to reject this request.']);
        }
        // remove the settlement in progress status
        ConsumerApplication::where('id', $record->application_id)->update(['secondary_status' => null]);
        $record->update([
            'status'     => 'rejected',
            'checker_id' => Auth::id(),
            'remark'     => $request->input('remark'),
            'action_at'  => Carbon::now()->toDateTimeString(),
        ]);
        CollectionAction::where(['id' => $record->collection_action_id])->delete();
        return response()->json(['status' => 'success', 'message' => 'Settlement request rejected.']);
    }

    public function updateSettlementMakerCheckerRemark(Request $request, $id)
    {
        $record = \App\SettlementMakerChecker::find($id);
        if (!$record) {
            return response()->json(['status' => 'error', 'message' => 'Record not found.']);
        }
        if (!Auth::check() || !Auth::user()->canApproveSettlementWaiver($record->waiver_percentage)) {
            return response()->json(['status' => 'error', 'message' => 'You are not authorised to update this remark.']);
        }
        $record->update(['remark' => $request->input('remark')]);
        return response()->json(['status' => 'success', 'message' => 'Remark updated.']);
    }

    public function sendSettlementProposalLetter(Request $request, $id)
    {
        try {
            $log = \App\SettlementMakerChecker::find($id);
            if (!$log || $log->status !== 'approved') {
                return response()->json(['status' => 'error', 'message' => 'Record not found or not approved.']);
            }

            $collectionAction = CollectionAction::find($log->collection_action_id);
            if (!$collectionAction) {
                return response()->json(['status' => 'error', 'message' => 'Collection action not found.']);
            }

            $application = ConsumerApplication::where('id', $log->application_id)
                ->first(['id', 'name', 'email']);

            $installments    = $collectionAction->installment_details
                ? json_decode($collectionAction->installment_details, true)
                : [];
            $installmentCount = count($installments);
            $ptpDate          = $collectionAction->ptp_date;
            $settlementAmount = $log->settlement_amount;

            // Extract per-installment dates
            $installmentDates = [];
            $formattedInstallments = [];
            if ($installmentCount > 0) {
                foreach ($installments as $i => $inst) {
                    if (is_array($inst)) {
                        $installmentDates[$i] = $inst['date'] ?? null;
                        $formattedInstallments[$i] = $inst['amount'];
                    } else {
                        // Fallback: Generate monthly back from ptp_date
                        $installmentDates[$i] = $ptpDate 
                            ? Carbon::parse($ptpDate)->subMonths($installmentCount - $i)->format('d-m-Y')
                            : null;
                        $formattedInstallments[$i] = $inst;
                    }
                }
            }
            $installments = $formattedInstallments;

            // Generate PDF
            $pdf    = App::make('snappy.pdf.wrapper');
            $pdfHtml = view('admin.accounting.settlement_letter', [
                'customerName'     => $application->name ?? 'Customer',
                'applicationId'    => $log->application_id,
                'settlementAmount' => $settlementAmount,
                'ptpDate'          => $ptpDate ? Carbon::parse($ptpDate)->format('d-m-Y') : '-',
                'installmentCount' => $installmentCount,
                'installments'     => $installments,
                'installmentDates' => $installmentDates,
            ])->render();
            $pdfOutput = $pdf->loadHTML($pdfHtml);


            if($request->input('action') == 'download'){
                return $pdf->download('settlement_letter.pdf');
            }else{
                $pdfOutput = $pdf->output();
            }

            // Collect recipient emails
            $recipients = array_filter(array_unique([
                $application->email ?? null,
                trim($request->input('additional_email', '')),
            ]));

            if (empty($recipients)) {
                return response()->json(['status' => 'error', 'message' => 'No valid recipient email found.']);
            }

            $emailBody = "Dear " . $application->name . ",<br><br>" . "Greetings from Credit Fair.<br><br>"
                . "This is to inform you that a full and final settlement has been agreed upon for your loan account. "
                . "The agreed settlement amount is to be paid as per the mutually discussed terms.<br><br>"
                . "Upon successful receipt of the settlement amount:<br><br>"
                . "Your loan account will be marked as <strong>\"Settled\"</strong> in our records.<br><br>"
                . "The Settlement Letter will be issued after 30 working days from the date of payment realization.<br><br>"
                . "Please ensure that the payment is made within the agreed timeline to avail of the settlement benefits. "
                . "Failure to do so may result in the settlement terms being withdrawn.<br><br>"
                . "For any further queries or assistance, please feel free to contact us.<br><br>"
                . "Warm regards,<br>Team Credit Fair";

            \Mail::send('emails.blank', ['body' => $emailBody], function ($message) use ($recipients, $pdfOutput, $log) {
                $message->from('payments@creditfair.in', 'Credit Fair')
                    ->to($recipients)
                    ->subject('Full & Final Settlement Intimation')
                    ->attachData($pdfOutput, 'Settlement_Proposal_' . $log->application_id . '.pdf', [
                        'mime' => 'application/pdf',
                    ]);
            });

            return response()->json(['status' => 'success', 'message' => 'Settlement proposal letter sent successfully.']);
        } catch (\Exception $e) {
            return response()->json(['status' => 'error', 'message' => $e->getMessage()]);
        }
    }

    public function emailSettlementLetter(Request $request, $application_id)
    {
        try {
            $application = ConsumerApplication::where('id', $application_id)
                ->first(['id', 'name', 'email', 'secondary_status']);

            if (!$application) {
                return response()->json(['status' => 'error', 'message' => 'Application not found.']);
            }

            if (($application->secondary_status ?? '') !== 'settled') {
                return response()->json(['status' => 'error', 'message' => 'Application is not settled.']);
            }

            // Build the settlement letter PDF (same source as the download route).
            $docRequest = new Request();
            $docRequest->request->add([
                'type' => 'Settlement Letters',
                'bot'  => true,
            ]);
            $document        = new ConsumerDocument($docRequest);
            $documentDetails = $document->getDocument($application_id);

            $pdf = App::make('snappy.pdf.wrapper');
            $pdf->loadHTML(view('admin.documents.settlement_letter', $documentDetails)->render())
                ->setOption('encoding', 'UTF-8')
                ->setPaper('a4')
                ->setOrientation('portrait');
            $pdf->setOption('margin-bottom', 25);
            $pdf->setOption('footer-html', view('admin.editor.footer', [
                'type'   => 'Settlement Letters',
                'lender' => $documentDetails['lender'],
            ])->render());
            $pdfOutput = $pdf->output();

            // Collect recipient emails.
            $recipients = array_filter(array_unique([
                $application->email ?? null,
                trim($request->input('additional_email', '')),
            ]));

            if (empty($recipients)) {
                return response()->json(['status' => 'error', 'message' => 'No valid recipient email found.']);
            }

            $emailBody = view('emails.reminders.settlement_letter', $documentDetails)->render();
            $subject   = 'Settlement Letter of Your Loan (Agreement Number - ' . $documentDetails['user']['application_id'] . ')';

            \Mail::send('emails.blank', ['body' => $emailBody], function ($message) use ($recipients, $pdfOutput, $subject) {
                $message->from('payments@creditfair.in', 'Credit Fair')
                    ->to($recipients)
                    ->subject($subject)
                    ->attachData($pdfOutput, 'Settlement_Letter.pdf', [
                        'mime' => 'application/pdf',
                    ]);
            });

            return response()->json(['status' => 'success', 'message' => 'Settlement letter sent successfully.']);
        } catch (\Exception $e) {
            return response()->json(['status' => 'error', 'message' => $e->getMessage()]);
        }
    }

    public function markSettled($id)
    {
        try {
            $log = \App\SettlementMakerChecker::find($id);
            if (!$log || $log->status !== 'approved') {
                return response()->json(['status' => 'error', 'message' => 'Record not found or not approved.']);
            }

            $repaymentInstance = new RepaymentController();
            if ($repaymentInstance->checkSettlementEntry($log->application_id)) {
                return response()->json(['status' => 'error', 'message' => 'No settlement entry found, status change to settled not allowed']);
            }
            $data_update = [
                'application_id' => $log->application_id,
                'amount' => 0,
                'payment_date' => Carbon::parse(now())->format('Y-m-d'),
                'type' => 'settlement_payment',
                'mode' => 'Written-off',
                'trasanction_id' => null,
                'cf_transaction_id' => null,
                'payment_reconciliation_date' => Carbon::parse(now())->format('Y-m-d'),
                'payment_for' => null,
                'payment_mode' => 'Written-off',
                'paid_by' => null,
                'collected_by' => Auth::user()->id,
                'collected_by_type' => null,
                'online_payment_id' => null,
                'trasanction_acknowledgement' => null,
                'payment_status' => null,
                'wallet_name' => null,
                'bank_id' => null,
                'reason' => null,
                'umrn' => null,
                'status' => 'success',
                'secondary_status' => 'settled',
                'adjust_with_disbursement' => null,
                'is_verify' => 1,
            ];
            $settlementResponse = $repaymentInstance->callReconcileApi($log->application_id, $data_update);
            if ($settlementResponse && isset($settlementResponse['status']) && $settlementResponse['status'] == 'FAIL') {
                return response()->json(['status' => 'error','message'=>$settlementResponse['message']]);
            }

            $consumerApplication = ConsumerApplication::where('id', $log->application_id)->first(['id', 'secondary_status']);
            if ($consumerApplication->secondary_status != 'settlement-done') {
                return response()->json(['status' => 'error','message'=>'Settlement done status not updated, cannot mark as settled']);
            }

            ConsumerApplication::where('id', $log->application_id)
                ->update(['secondary_status' => 'settled']);
            SecondaryStatusLogs::insert([
                'application_id' => $log->application_id,
                'user_id'        => Auth::id(),
                'status'         => 'settled',
                'reason'         => 'Settlement instruction approved by checker.',
                'created_at'     => Carbon::now()->toDateTimeString(),
                'updated_at'     => Carbon::now()->toDateTimeString(),
            ]);
            return response()->json(['status' => 'success', 'message' => 'Application marked as settled.']);
        } catch (\Exception $e) {
            return response()->json(['status' => 'error', 'message' => 'Something went wrong.']);
        }
    }

    public function checkSettlementPayment($id)
    {
        try {
            $settledPaymentTypes = ['settled_principal', 'settled_interest', 'settled_bounce', 'settled_penal'];

            $collectionAction = CollectionAction::where('application_id', $id)
                ->where('dispo_code', 'Settlement')
                ->whereNotNull('ptp_date')
                ->whereNotNull('amount_to_be_received')
                ->orderBy('created_at', 'desc')
                ->first();

            if (!$collectionAction) {
                return response()->json(['status' => 'error', 'message' => 'No settlement entry found for this application.']);
            }

            $totalReceived = (float) PaymentTransaction::where('application_id', $id)
                ->whereIn('payment_for', $settledPaymentTypes)
                ->where('payment_date', '<=', $collectionAction->ptp_date)
                ->sum('amount');

            $amountToBeReceived = (float) $collectionAction->amount_to_be_received;

            if ($totalReceived >= $amountToBeReceived) {
                return response()->json(['status' => 'success']);
            }

            return response()->json(['status' => 'error', 'd' => $totalReceived, 'r' => $amountToBeReceived, 'message' => "You can't mark it as settlement done, payment is not yet received."]);
        } catch (\Exception $e) {
            return response()->json(['status' => 'error', 'message' => 'Something went wrong.']);
        }
    }

    private function upsertSettlementJob($collectionActionId, $applicationId, $ptpDate)
    {
        $availableAt = Carbon::parse($ptpDate)->addDay()->toDateTimeString();

        $existing = JobProvider::where('application_id', $applicationId)
            ->where('from', 'settlement_ptp_progress')
            ->first();

        if ($existing) {
            if ($existing->is_available == 0) {
                $existing->update(['available_at' => $availableAt]);
            }
        } else {
            $payload = [[
                'payload'        => json_encode(['id' => $collectionActionId]),
                'from'           => 'settlement_ptp_progress',
                'application_id' => $applicationId,
                'available_at'   => $availableAt,
                'created_at'     => Carbon::now()->toDateTimeString(),
            ]];

            $job = new Jobs();
            $job->insertQueue($payload);
        }
    }

    public function settlementPtpProgress($job, $payload)
    {
        $collection_action_id = $payload->id;
        $applicationId = $job->application_id;
        $application = ConsumerApplication::where('id', $applicationId)->first(['id', 'name', 'secondary_status']);

        // Get the Settlement collection action for this application
        $collectionAction = CollectionAction::where('id', $collection_action_id)
            ->where('dispo_code', 'Settlement')
            //->where('ptp_date', '>=', Carbon::now()->startOfDay()->toDateTimeString()) commentted as we need to check for all settled transactions
            ->latest()
            ->first();

        if (!$collectionAction) {
            return;
        }

        $amountToBeReceived = (float) $collectionAction->amount_to_be_received;

        // Sum all settled transactions for this application
        $settledPaymentTypes = ['settled_principal', 'settled_interest', 'settled_bounce', 'settled_penal'];

        $totalReceived = PaymentTransaction::where('application_id', $applicationId)
            ->whereIn('payment_for', $settledPaymentTypes)
            ->where('payment_date', '<=', $collectionAction->ptp_date)
            ->sum('amount');

        $totalReceived = (float) $totalReceived;

        if ($application->secondary_status == 'settlement-in-progress') {
            if ($totalReceived >= $amountToBeReceived) {
                // Mark application as settled
                (new SettlementController)->handleSettlementFulfilled($application_id);
            } else {
                // Check if there is any pending settlement payment in Maker Checker
                $pendingSettlementChecker = PaymentMakerChecker::where('application_id', $applicationId)
                    ->where('status', 1)->whereIn('payment_type', $settledPaymentTypes)->exists();

                if ($pendingSettlementChecker) {
                    return;
                }

                $shortfall = $amountToBeReceived - $totalReceived;
                ConsumerApplication::where('id', $applicationId)->update(['secondary_status' => 'settlement-aborted']);

                SecondaryStatusLogs::insert([
                    'application_id' => $applicationId,
                    'user_id'        => 107,
                    'status' => 'settlement-aborted',
                    'reason' => 'Settlement not received within the time',
                    'created_at' => Carbon::now()->toDateTimeString()
                ]);

                $body = "Settlement Not Received — Action Required\n\n"
                    . "Application ID   : {$applicationId}\n"
                    . "Customer Name    : " . ($application->name ?? 'N/A') . "\n"
                    . "Expected Amount  : ₹" . number_format($amountToBeReceived, 2) . "\n"
                    . "Amount Received  : ₹" . number_format($totalReceived, 2) . "\n"
                    . "Shortfall        : ₹" . number_format($shortfall, 2) . "\n\n"
                    . "Settlement has been aborted. Please review and take necessary action.";

                \Mail::send('emails.blank', ['body' => nl2br($body)], function ($message) use ($applicationId) {
                    $message->to('sunil@creditfair.in')
                        ->subject("Settlement Aborted — Application #{$applicationId}");
                });
            }
        }
    }

    public function getForeclosure($id){
        $avanseFinRef = AvanseDisbursement::where('application_id', $id)->first(['finReference']);
        $payload = array("id"=>$id,"finReference"=>$avanseFinRef->finReference, "days"=>1);
        $forecloserData = (new AvanseServices(new Request($payload)))->getForeclosureLetter();
        //print_r($forecloserData);die;
        $foreclosure_amount = 0;
        $message = '';
        if(isset($forecloserData->finance) && $forecloserData->returnStatus->returnCode == 0000) {
            foreach ($forecloserData->finance as $key => $value) {
                foreach ($value->foreClosures as $key1 => $value1) {
                    $foreclosure_amount = $value1->foreCloseAmount/100;
                }
            }
            if (!isset($foreclosure_amount) || empty($foreclosure_amount)) {
                $foreclosure_amount = 0;
            }

        }else{
            $message = $forecloserData->returnStatus->returnText;
        }
        echo json_encode(array('code'=>$forecloserData->returnStatus->returnCode,'foreclosure_amount' => $foreclosure_amount, 'message'=>$message));

    }

    public function startGetNOC(){
        $noc = AvanseNoc::where('is_available', 0)->limit(50)->get();
        $ids = array();
        $data = array();

        foreach ($noc as $item){
            $payment = AvanseCreateFinance::where('application_id',$item->application_id)->first(['finReference']);
            $noc_payload = ['id' => $item->application_id, 'fin_reference_id'=>$payment['finReference'],'type'=>'NOC'];
            $noc_response = (new AvanseProcesses(new Request($noc_payload)))->getStatement();
            if($noc_response == $payment['finReference']){
                $data[] = array('id'=>$item->application_id,'status'=>'success');
            }else{
                $data[] = array('id'=>$item->application_id, 'status' => 'failed');
            }
            $ids[] = $item->application_id;
        }
        foreach($data as $key=>$value){
            if($value['status'] == "success"){
                $s3 = Storage::disk('s3');
                $file_path = ConsumerApplicationFiles::where('consumer_application_id',$value['id'])->where('file_type','NOC')->first(['file_path']);
                if($s3->exists($file_path['file_path'])){
                    $noc_doc = $s3->get($file_path['file_path']);
                    $request = new Request();
                    $request->request->add([
                        'type' => "Closures Letters",
                        'bot' => true
                    ]);
                    $document = (new ConsumerDocument($request));
                    $documentDetails = $document->getDocument($value['id']);
                    $email = $documentDetails['user']['customer_email'];
                    Mail::send('emails.reminders.basic_reminder',
                    ['body' => view('emails.reminders.closure_letter', $documentDetails)]
                    , function ($message) use ($email, $noc_doc,$documentDetails) {
                        $message->to($email)->subject('Closure of Your Loan (Agreement Number - ' . $documentDetails['user']['application_id'] . ')');
                        $message->cc('centralops@creditfair.in');
                        if($noc_doc){
                            $message->attachData($noc_doc, 'NOC');
                        }
                    });
                }
                AvanseNoc::where('application_id',$value['id'])->update(['execution_status'=>'success','is_available' => 1]);
            }else{
                AvanseNoc::where('application_id',$value['id'])->update(['execution_status'=>'failed','is_available' => 1]);
            }
        }
        //AvanseNoc::whereIn('id',$ids)->update(['is_available' => 1]);


    }

    public function getNOC($id){
        $data = [];
        $payment = AvanseCreateFinance::where('application_id',$id)->first(['finReference']);
        //echo "<pre>";print_r($payment['finReference']);die;
        $noc_payload = ['id' => $id, 'fin_reference_id'=>$payment['finReference'],'type'=>'NOC'];
        $noc_response = (new AvanseProcesses(new Request($noc_payload)))->getStatement();
        if($noc_response == $payment['finReference']){
            $s3 = Storage::disk('s3');
            $file_path = ConsumerApplicationFiles::where('consumer_application_id',$id)->where('file_type','NOC')->first(['file_path']);
            if($s3->exists($file_path['file_path'])){
                $noc_doc = $s3->get($file_path['file_path']);
                $request = new Request();
                $request->request->add([
                    'type' => "Closures Letters",
                    'bot' => true
                ]);
                $document = (new ConsumerDocument($request));
                $documentDetails = $document->getDocument($id);
                $email = $documentDetails['user']['customer_email'];
                \Mail::send('emails.reminders.basic_reminder',
                ['body' => view('emails.reminders.closure_letter', $documentDetails)]
                , function ($message) use ($email, $noc_doc,$documentDetails) {
                    $message->to($email)->subject('Closure of Your Loan (Agreement Number - ' . $documentDetails['user']['application_id'] . ')');
                    $message->cc('centralops@creditfair.in');
                    if($noc_doc){
                        $message->attachData($noc_doc, 'NOC');
                    }
                });
                AvanseNoc::where('application_id',$id)->update(['execution_status'=>'success']);
            }
            $data = array('id'=>$id, 'status' => 'success');
        }else{
            $data = array('id'=>$id, 'status' => 'failed');
        }
        echo json_encode($data);
    }


    public function getPayoutReport(Request $request){
        $from_date = $request->get('from_date') ?? Carbon::now()->startOfMonth()->toDateString();
        $to_date = $request->get('to_date') ?? Carbon::now()->endOfMonth()->toDateString();
        $lender_id = $request->get('lender_id') ?? '';
        $merchant_id = $request->get('merchant_id') ?? '';

        if($request->get('export')){
            $lender_condition = $condition = $joiner = $merchant_condition = '';

            if(!empty($lender_id)){
                $lender_condition = "consumer_application.lender_id = $lender_id";
            }
            if(!empty($merchant_id)){
                $merchant_condition = "consumer_application.merchant_id = $merchant_id";
            }
            if(!empty($lender_id) || !empty($merchant_id)){
                $condition = 'WHERE';
            }
            if(!empty($lender_id) && !empty($merchant_id)){
                $joiner = 'AND';
            }

            $db_data = DB::select("SELECT DISTINCT 
                consumer_application.id, 
                pro_forma_invoice.loan_application_no, 
                avanse_finance.finReference, 
                consumer_application.name as customer_name, 
                consumer_application.co_applicant_name, 
                consumer_application.co_applicant_mobile_number, 
                merchant.merchant_name, 
                merchant.gst_number, 
                lenders.name, 
                consumer_application.email, 
                consumer_application.mobile_number, 
                consumer_application.approved_amount, 
                i.amount as subvention_taxable, 
                emi_calculation.tenure, 
                consumer_application_element.reference_number,
                emi_calculation.advance_emi, 
                emi_calculation.interest_rate, 
                emi_calculation.subvention, 
                emi_calculation.processing_fee, 
                emi_calculation.emi, 
                emi_calculation.subvention_igst, 
                emi_calculation.subvention_cgst, 
                emi_calculation.subvention_sgst, 
                ((emi_calculation.upfront_from_credit_fair - emi_calculation.subvention_igst - emi_calculation.subvention_cgst - emi_calculation.subvention_sgst) * (100 - COALESCE(ll.liability_percent, 0)))/ 100 as net_disbursment,
                (SELECT umrn FROM mandate WHERE mandate.consumer_application_id = consumer_application.id AND MODE != 'lotuspay' AND umrn != '' LIMIT 1) AS nach_status,
                users.name AS advisor, 
                collection_executive.name AS collection_executive, 
                consumer_application.current_address_city, 
                consumer_application.current_address_state, 
                consumer_application.state, 
                dl.disbAmount AS paid_amount, 
                log.created_at AS disbursed_date
                FROM
                    consumer_application
                LEFT JOIN
                    (SELECT application_id, loan_application_no FROM pro_forma_invoice) pro_forma_invoice ON pro_forma_invoice.application_id = consumer_application.id
                LEFT JOIN
                    (SELECT application_id, disbAmount FROM avanse_disbursement) dl ON dl.application_id = consumer_application.id
                LEFT JOIN
                    (SELECT collection_advisor, application_id,reference_number FROM consumer_application_element) consumer_application_element ON consumer_application_element.application_id = consumer_application.id
                LEFT JOIN
                    (SELECT id, name FROM users) AS collection_executive ON collection_executive.id = consumer_application_element.collection_advisor
                LEFT JOIN
                    (SELECT name,id FROM users) users ON users.id = consumer_application.created_by
                LEFT JOIN
                    (SELECT id, merchant_name, gst_number FROM merchant) merchant ON merchant.id = consumer_application.merchant_id
                LEFT JOIN
                    (SELECT name, id FROM lenders) lenders ON lenders.id = consumer_application.lender_id
                LEFT JOIN
                    (select application_id , liability_percent from liability_log) ll on ll.application_id = consumer_application.id
                LEFT JOIN
                    (SELECT application_id, tenure, advance_emi, interest_rate, subvention, processing_fee, emi, subvention_igst, subvention_cgst, subvention_sgst, upfront_from_credit_fair FROM emi_calculation) emi_calculation ON emi_calculation.application_id = consumer_application.id
                LEFT JOIN
                    (SELECT finReference, application_id FROM avanse_finance) avanse_finance ON avanse_finance.application_id = consumer_application.id
                LEFT JOIN
                    (SELECT i.application_id, i.amount FROM invoices i WHERE TYPE = 'subvention_invoice' and deleted_at is null) i ON i.application_id = consumer_application.id
                INNER JOIN
                    (SELECT created_at, application_id FROM status_logs log WHERE status = 'disbursed' and created_at >= '".$from_date."' and created_at <= '".$to_date."') log on log.application_id = consumer_application.id
                ".$condition." ".$lender_condition." ".$joiner." ".$merchant_condition." order by disbursed_date desc");

            $exporter[] = ['ID','Loan Application Number','Fin Reference', 'Customer Name', 'Co-Applicant Name', 'Co-Applicant Number',
                'Merchant Name', 'GST number', 'Name', 'Email', 'Mobile Number', 'Approved Amount', 'Subvention taxable', 'Tenure', 'UTR',
                'Advance Emi', 'Interest Rate', 'Subvention', 'Processing Fee', 'EMI', 'Subvention IGST', 'Subvention CGST', 'Subvention SGST',
                'Net Disbursement', 'Nach Status', 'Advisor', 'Collection Executive', 'Current Address City', 'Current Address State', 'State',
                'Paid Amount', 'Disbursed Date'];
            foreach ($db_data as $value){
                $exporter[] = [
                    'id' => $value->id,
                    'loan_application_number' => $value->loan_application_no,
                    'finReference' => $value->finReference,
                    'customer_name' => $value->customer_name,
                    'co_applicant_name' => $value->co_applicant_name,
                    'co_applicant_mobile_number' => wall_decrypt($value->co_applicant_mobile_number),
                    'merchant_name' => $value->merchant_name,
                    'gst_number' => wall_decrypt($value->gst_number),
                    'name' => $value->name,
                    'email' => wall_decrypt($value->email),
                    'mobile_number' => wall_decrypt($value->mobile_number),
                    'approved_amount' => $value->approved_amount,
                    'subvention_taxable' => $value->subvention_taxable,
                    'tenure' => $value->tenure,
                    'reference_number' => $value->reference_number,
                    'advance_emi' => $value->advance_emi,
                    'interest_rate' => $value->interest_rate,
                    'subvention' => $value->subvention,
                    'processing_fee' => $value->processing_fee,
                    'emi' => $value->emi,
                    'subvention_igst' => $value->subvention_igst,
                    'subvention_cgst' => $value->subvention_cgst,
                    'subvention_sgst' => $value->subvention_sgst,
                    'net_disbursment' => $value->net_disbursment,
                    'nach_status' => $value->nach_status,
                    'advisor' => $value->advisor,
                    'collection_executive' => $value->collection_executive,
                    'current_address_city' => $value->current_address_city,
                    'current_address_state' => $value->current_address_state,
                    'state' => $value->state,
                    'paid_amount' => $value->paid_amount,
                    'disbursed_date' => $value->disbursed_date,
                ];
            }

            $request = new Request(['data'=>$exporter,'sheet'=>'Sheet1']);
            $file = 'Payout_Report_'.$from_date.'_to_'.$to_date.'.xls';
//            return Excel::download((new Exporter($request)), 'Payout_Report_'.$from_date.'_to_'.$to_date.'.xls');
            Excel::store((new Exporter($request)), $file);

            Mail::send('emails.reminders.basic_reminder', [
                'body' => 'Payout Report',
            ], function ($message) use ($file) {
                $message->to(['surbhi@creditfair.in','ravi.mehta@creditfair.in'])
                    ->cc(['rohit@creditfair.in', 'vikas@creditfair.in', 'aditya@creditfair.in', 'sarah@creditfair.in', 'sunil@creditfair.in'])
                    ->subject('Payout Report');
                $message->attachData(file_get_contents(storage_path() . '/app/' . $file), $file);
            });
            unlink(storage_path() . '/app/' . $file);
            \Session::flash('success', 'You\'ll will receive the report on email');
        }

        $data['from_date'] = $from_date;
        $data['to_date'] = $to_date;
        $data['merchants'] = Merchant::where('status','active')->where('is_guest_active',1)->get(['id','merchant_name']);
        $data['lenders'] = Lenders::all();

        return view('admin.reports.payouts', $data);
    }


    public function getMonthlySubvention($send_mail = false){
        $inv_start_date = Carbon::now()->subMonth(1)->startOfMonth();
        $inv_end_date = Carbon::now()->subMonth(1)->endOfMonth();
        $invoice_date = Carbon::now()->subMonth(1);

        $lender = Lenders::with('bank_details')->where('id', 2)->first();

        $disb_logs = DisbursementLogs::where('phase', '>', 1)
            ->where('created_at', '>=', $inv_start_date)
            ->where('created_at', '<=', $inv_end_date)->whereNull('deleted_at')->get(['application_id']);

        $status_logs = StatusLogs::where('status', 'disbursed')->where('created_at', '>=', $inv_start_date)
            ->where('created_at', '<=', $inv_end_date)->where('is_reversed',0)->get(['application_id']);

        $applications=[];
        $common_apps=[];
        foreach($disb_logs as $log){
            if(!in_array($log->application_id, $applications))
                $applications[] = $log->application_id;
        }
        foreach($status_logs as $log){
            if(!in_array($log->application_id, $applications))
                $applications[] = $log->application_id;
            else
                $common_apps[] = $log->application_id;
        }


        $data = ConsumerApplication::with('proFormaInvoice','lender','merchant', 'emi', 'offer', 'lender.bank_details', 'application_element.merchant_center', 'application_emi_details')
            ->whereIn('id', $applications)->where('lender_id', 2)
            ->whereNotIn('merchant_id', [73,6478,7516])->whereIn('state', ['disbursed', 'nach registered', 'closed', 'cancelled'])
            ->whereNull('is_deleted')->get()->groupBy(['merchant.id', 'application_element.merchant_center.id']);

//        DB::statement("SET sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));");
//
//        $applications = DB::select("select * from status_logs
//                  left join consumer_application on status_logs.application_id=consumer_application.id
//                  left join consumer_application_element on consumer_application_element.application_id=consumer_application.id
//                  left join pro_forma_invoice on pro_forma_invoice.application_id=consumer_application.id
//                  left join lenders on lenders.id=consumer_application.lender_id
//                  left join merchant on merchant.id=consumer_application.merchant_id
//                  left join emi_calculation on emi_calculation.id=emi_calculation.application_id
//                  left join merchant_offers on merchant_offers.id=consumer_application.offer_id
//where consumer_application.id = status_logs.application_id and status_logs.status = 'disbursed' and consumer_application.state in ('disbursed', 'nach registered')
//  and consumer_application.merchant_id=26 and consumer_application.lender_id=2 and status_logs.created_at >= '2022-09-01 00:00:00'
//  and status_logs.created_at <= '2022-11-09 23:59:59' and status_logs.is_reversed = 0 group by status_logs.application_id;");
//
//        DB::statement("SET sql_mode=(SELECT CONCAT(@@sql_mode, ',ONLY_FULL_GROUP_BY'));");
//
//
//        return $data;
//
//        $data = ConsumerApplication::with('proFormaInvoice','lender','merchant', 'emi', 'offer', 'lender.bank_details', 'disbursement_log')
//            ->where(function ($query) {
////                $query->where(function ($x) {
//                $query->whereHas('logs', function ($q) use ($query){
//                    $query->where('status', 'disbursed')->where('created_at', '>=', '2022-11-01 00:00:00')
//                            ->where('created_at', '<=', '2022-11-30 23:59:59')->where('is_reversed', 0);
//                    })
////                })->orWhere(function ($y) {
//                    ->orWhereHas('disbursement_log', function ($z) use ($query) {
//                        $query->where('phase', 1)->where('created_at', '>=', '2022-11-01 00:00:00')
//                            ->where('created_at', '<=', '2022-11-30 23:59:59')->whereNull('deleted_at');
//                    });
////                });
//            })->where('lender_id', 2)->whereIn('state', ['disbursed', 'nach registered'])->whereNull('is_deleted')
//            ->get()->groupBy(['merchant.id']);

        $merchant_count = 0;
        foreach($data as $merchant => $m_applications) {
            $merchant_details = Merchant::with('centers')->where('id', $merchant)->first();
            if (!in_array($merchant, _env('APP_CONNECTION') ? [6478, 73] : []) && !in_array($merchant, [])) {

                $allItems = new \Illuminate\Database\Eloquent\Collection;
                $items = new \Illuminate\Database\Eloquent\Collection;

                if ($merchant_details->subv_inv_on_center == 1) {
                    $allItems = $m_applications;
                }else{
                    foreach ($m_applications as $center => $applications) {
                        $items = $items->concat($applications);
                    }
                    $allItems = $allItems->push($items);
                }

                foreach ($allItems as $center => $applications) {
                    $center = $center != "" ? $center : 0;

                    $center_details = MerchantLocation::where('id', $center)->first();
                    $type = 'subvention_invoice';

                    if ($merchant_details->subv_inv_on_center == 1) {
                        $invoiceExists = Invoices::where('application_id', 0)->where('merchant_id', $merchant)->where('center_id', $center)
                            ->where('invoice_date', $inv_end_date->toDateTimeString())->where('type', $type)->first(['id']);
                    } else {
                        $invoiceExists = Invoices::where('application_id', 0)->where('merchant_id', $merchant)
                            ->where('invoice_date', $inv_end_date->toDateTimeString())->where('type', $type)->first(['id']);
                    }

                    if (!isset($invoiceExists->id)) {
                        $request = new Request();
                        $request->request->add([
                            'type' => 'Merchant Disbursed',
                            'bot' => true,
                            'test_bot' => 1
                        ]);

                        $document = (new ConsumerDocument($request));
                        $documentDetails = [];
                        $inv_applications = [];
                        $net_total = 0;
                        $igst_total = 0;
                        $cgst_total = 0;
                        $sgst_total = 0;
                        $amount_total = 0;

                        $merchant_gst_number = $merchant_details->gst_number ?? '';
                        $center_gst_number = $center_details->gst_number ?? '';
                        $official_merchant_name = $merchant_details->merchant_name ?? '';
                        $center_name = $center_details->name ?? $official_merchant_name;
                        $merchant_address = isset($merchant_details->address) ? ucwords(strtolower($merchant_details->address)) : '';
                        $center_address = isset($center_details->location) ? ucwords(strtolower($center_details->location)) : $merchant_address;
                        $merchant_state = isset($merchant_details->state) && !empty($merchant_details->state) ? $merchant_details->state : '';
                        $center_state = isset($center_details->state) && !empty($center_details->state) ? $center_details->state : $merchant_state;

                        foreach ($applications as $key => $application) {
                            if (isset($application->emi->subvention) && !empty($application->emi->subvention) && isset($application->merchant->is_gst) && $application->merchant->is_gst == 1 && isset($application->merchant->state) && !empty($application->merchant->state) && isset($application->proFormaInvoice->loan_application_no)) {
                                if(isset($application->application_emi_details) && isset($application->application_emi_details->data)) {
                                    $app_log = json_decode($application->application_emi_details->data, 1);
                                    $application->merchant->charge_subvention_remaining_amount = $app_log['merchant']['charge_subvention_remaining_amount'];
                                }

                                $downPayment = 0;

                                if ($application->merchant->charge_subvention_remaining_amount) {
                                    $downPayment = $application->emi->upfront_from_customer;
                                }

                                $subvention_amount = (($application->approved_amount - $downPayment) * $application->emi->subvention) / 100;

                                if(!$application->offer){
                                    $application->offer = MerchantOffers::where('id', $application->offer_id)->withTrashed()->first();
                                }

//                                if (in_array($application->id, $common_apps)) {
//                                    unset($common_apps[$application->id]);
//                                } else {
                                    $multiStage = new MultiStageDisbursement();
                                    if ($multiStage->canPartialDisbursement($application->emi->offer_id, $application)) {
                                        $disbursement_phase = $multiStage->isPartialDisbursementforMonth($application, $inv_start_date, $inv_end_date);
                                        if (is_bool($disbursement_phase))
                                            return $subvention_amount;


                                        if(count($disbursement_phase) == 1) {
                                            $disbursementOffers = new DisbursementOffers();
                                            $disbursementOffersData = $disbursementOffers->getCurrentOfferDisbursement($application->emi->offer_id, $disbursement_phase[0]->phase, $application->id);
                                            if (!isset($disbursementOffersData->per_disbursement_amount)) {
                                                (new Slack(new Request(['title' => 'Disbursement log missing', 'fields' => ['app' => $application->id], 'group' => Slack::$STAGE_TESTING])))->send();
                                            }
                                            if ($application->merchant && $application->merchant->charge_subvention_remaining_amount /*&& count($disbursement_phase) == 1*/) {
                                                if ($disbursement_phase[0]->phase == 1) {
                                                    $multiStageSubventionAmount = ((($application->approved_amount * $disbursementOffersData->per_disbursement_amount) / 100) - $application->emi->upfront_from_customer) * $application->emi->subvention / 100;
                                                    $subventionAmountOLD = (($application->approved_amount - $application->emi->upfront_from_customer) * $application->emi->subvention) / 100;
                                                    if (round($multiStage->upFrontFromCreditFair($application, true)) == round($application->emi->upfront_from_credit_fair)) {
                                                        $newUpFrontFrontCreditFair = (($application->emi->upfront_from_credit_fair + $subventionAmountOLD) - $multiStageSubventionAmount);
                                                        ApplicationEMICalculation::where('application_id', $application->id)->update(['upfront_from_credit_fair' => $newUpFrontFrontCreditFair]);
                                                    }
                                                } else {
                                                    $multiStageSubventionAmount = (($application->approved_amount * $disbursementOffersData->per_disbursement_amount) / 100) * $application->emi->subvention / 100;
                                                }
                                            } else {
//                                                $downPayment = 0;
//                                                if ($application->merchant->charge_subvention_remaining_amount && count($disbursement_phase) == 1) {
//                                                    $downPayment = $application->emi->upfront_from_customer;
//                                                }
//                                                $subvention_amount = (($application->approved_amount - $downPayment) * $application->emi->subvention) / 100;
                                                $multiStageSubventionAmount = $multiStage->getMultiStageSubventionAmount($subvention_amount, $disbursementOffersData);
                                            }
                                            $subvention_amount = $multiStageSubventionAmount;
                                        }
                                    }
//                                }

                                $gstDetails = $document->getGSTDetails(
                                    [
                                        'amount' => $subvention_amount,
                                        'state' => $merchant_details->subv_inv_on_center == 1 ? $center_state : $merchant_state,
                                    ], 0
                                );

                                $amt = (isset($gstDetails[0])) ? $gstDetails[0]['amount'] : 0;
                                if ($amt) {
                                    if ($gstDetails) {
                                        $response = array();
                                        foreach ($gstDetails as $gst) {
                                            if (isset($gst['taxes']) && $gst['taxes'] == "CGST") {
                                                $response['subvention_cgst'] = $gst['gst_amount'];
                                            } elseif (isset($gst['taxes']) && $gst['taxes'] == "SGST") {
                                                $response['subvention_sgst'] = $gst['gst_amount'];
                                            } else {
                                                $response['subvention_igst'] = $gst['gst_amount'];
                                            }
                                        }
                                    }

                                    $igst = (isset($response['subvention_igst'])) ? $response['subvention_igst'] : 0;
                                    $cgst = (isset($response['subvention_cgst'])) ? $response['subvention_cgst'] : 0;
                                    $sgst = (isset($response['subvention_sgst'])) ? $response['subvention_sgst'] : 0;

                                    $inv_applications[$key] = [
                                        'disbursement_date' => $document->getDisbursedDate($application->id),
                                        'customer_name' => $application->name,
                                        'id' => $application->proFormaInvoice->loan_application_no,
                                        'net_amount' => (isset($gstDetails[0])) ? $gstDetails[0]['net_amount'] : 0,
                                        'igst' => $igst,
                                        'cgst' => $cgst,
                                        'sgst' => $sgst,
                                        'amount' => (isset($gstDetails[0])) ? $gstDetails[0]['net_amount']+$igst+$cgst+$sgst : 0,
                                    ];

                                    $net_total += (isset($gstDetails[0])) ? $gstDetails[0]['net_amount'] : 0;
                                    $igst_total += $igst;
                                    $cgst_total += $cgst;
                                    $sgst_total += $sgst;
                                    $amount_total += (isset($gstDetails[0])) ? $gstDetails[0]['net_amount']+$igst+$cgst+$sgst : 0;
                                }
                            }
                        }

                        if ($amount_total > 0 && $net_total > 0) {
                            try {

                                $created_at = Carbon::now()->toDateTimeString();
                                sleep(5);
                                $invoiceId = (new ConsumerApplicationController())->getInvoiceID($merchant, $type, true);
                                $invoiceDetails = [
                                    'application_id' => 0,
                                    'merchant_id' => $merchant,
                                    'center_id' => $center,
                                    'invoice_id' => $invoiceId,
                                    'amount' => $amount_total,
                                    'net_amount' => $net_total,
                                    'igst' => $igst_total,
                                    'cgst' => $cgst_total,
                                    'sgst' => $sgst_total,
                                    'lender_id' => 2 /*KM cases only*/,
                                    'type' => $type,
                                    'phase_id' => $multiStageDisbursement['phase_id'] ?? null,
                                    'status' => 1,
                                    'created_at' => $created_at,
                                    'invoice_date' => $inv_end_date
                                ];

                                Invoices::insert($invoiceDetails);

                                $getGSTDetailsSubvention = [];

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

                                $documentDetails = [
                                    'invoice_number' => $invoiceId,
                                    'total_subvention' => (isset($gstDetails[0])) ? $gstDetails[0]['amount'] : 0,
                                    'invoice_date' => $invoice_date->endOfMonth(),
                                    'net_amount' => (isset($gstDetails[0])) ? $gstDetails[0]['net_amount'] : 0,
                                    'lender' => $lender,
                                    'lender_bank' => $lender->bank_details,
                                    'getGSTDetailsSubvention' => $getGSTDetailsSubvention,
                                    'applications' => $inv_applications,
                                    'invoice' => $invoiceDetails,
                                    'merchant_name' => $merchant_details->subv_inv_on_center == 1 ? $center_name : $official_merchant_name,
                                    'merchant_address' => $merchant_details->subv_inv_on_center == 1 ? $center_address : $merchant_address,
                                    'merchant_gst_number' => $merchant_details->subv_inv_on_center == 1 ? $center_gst_number : $merchant_gst_number,
                                ];

                            } catch (\Exception $e) {
                                (new \App\Slack(new Request(['title' => 'Monthly Invoice Creation Error', 'fields' => [
                                    'error' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString(),
                                    'application_id' => $application->id, 'id_type' => 'application_id']])))->send();
                                $cwFactory = new CloudWatchLoggerFactory();
                                $_data = array(
                                    'exception' => 'Monthly Invoice Creation Error',
                                    'message' => $e->getMessage(),
                                    'line' => $e->getLine(),
                                    'trace' => $e->getTraceAsString(),
                                    'application_id' => $application->id, 'id_type' => 'application_id'
                                );
                                $cwFactory->logger(json_encode($_data));
                            }

                            if (!empty($documentDetails)) {
                                $data = [
                                    'txt' => view('admin.documents.merchant_subvention_fee_invoice', $documentDetails),
                                    'test_bot' => 1
                                ];

                                $request->request->add($data);
                                $document->isMerchantRequest = 1;


                                $merchant_email = explode(',', trim($merchant_details->email));
                                if($center > 0 && $center_details->email){
                                    $center_email = explode(',', trim($center_details->email));
                                }

                                $to = $merchant_email;
                                $cc = ['surbhi@creditfair.in', 'ravi.mehta@creditfair.in'];
//                                $cc = ['sarah@creditfair.in'];
                                if($center > 0 && isset($center_email)){
                                    $to = $center_email;
                                    $cc = array_merge($cc, $merchant_email);
                                }

                                // return $documentDetails;

                                $pdf = App::make('snappy.pdf.wrapper');
                                $pdf->loadHTML(view('admin.documents.merchant_subvention_fee_invoice', $documentDetails)
                                )->setOption('encoding', 'UTF-8')->setPaper('a4')->setOrientation('portrait')
                                    ->setTemporaryFolder(storage_path() . '/')->setOption('enable-local-file-access', true)->setOption('margin-bottom', 20);
                                $invoice = $pdf->setOption('footer-html', view('admin.editor.footer', ['type' => 'Merchant Disbursed',
                                    'lender' => $lender])->render());


                                // return $invoice->inline();

                                $file_name = str_replace(' ', '_', strtolower($request->get('type'))) . '_' . $invoice_date->format('M') . '_' . $invoice_date->format('Y') . '_' . $center . '.pdf';

                                if($send_mail) {
                                    $subject = $merchant_details->merchant_name . ': Subvention Invoice for ' . $invoice_date->format('M') . '-' . $invoice_date->format('Y');

                                    try {
                                        Mail::send('emails.reminders.basic_reminder', [
                                            'body' => view('emails.reminders.monthly_subvention_invoice_mail', ['merchant_name' => $official_merchant_name, 'date' => $invoice_date->format('M') . ' ' . $invoice_date->format('Y')]),
                                            'lender_id' => $lender->id,
                                        ], function ($message) use ($file_name, $to, $cc, $invoice, $subject) {
                                            $message->to($to)
                                                ->cc($cc)->bcc(['admin@creditfare.in', 'sarah@creditfair.in'])
                                                ->subject($subject);
                                            $message->attachData($invoice->output(), $file_name);
                                        });
                                    } catch (\Exception $e) {
                                        (new \App\Slack(new Request(['title' => 'Email id failed', 'fields' => ['Merchant ID' => $merchant_details->id, 'Merchant Name' => $merchant_details->merchant_name], 'group' => Slack::$STAGE_TESTING])))->send();
                                    }
                                }


                                $file_path = '/merchant/' . $merchant . '/subvention_invoices/' . $invoice_date->format('M') . '_' . $invoice_date->format('Y') . '/' . $file_name;
                                $s3 = Storage::disk('s3');
                                $s3->put($file_path, $invoice->output());
                                $merchant_count += 1;
                            }
                        }
                    }
                }
            }
        }
        (new \App\Slack(new Request(['title' => 'Monthly Invoice Generated and Sent', 'fields' => ['InvoiceCount' => $merchant_count], 'group' => Slack::$STAGE_TESTING])))->send();
        $cwFactory = new CloudWatchLoggerFactory();
        $_data = array(
            'message' => 'Monthly Invoice Generated and Sent',
            'InvoiceCount' => $merchant_count,
        );
        $cwFactory->logger(json_encode($_data));
        return true;
    }

    public function exportSubventionInvoice(Request $request){
        try {
            $invoice_date = $request->get('invoice_date');
            $date = Carbon::createFromDate($request->get('year'), $request->get('month'))->endOfMonth();
            $merchant_id = $request->get('merchant_id');
            $user_id = $request->get('user_id');
            $type = $request->get('type');


            $query = Invoices::with('merchant', 'center')->where('invoice_date', $invoice_date)->where('application_id', 0);
            if (!is_null($merchant_id) && $merchant_id != "") {
                $query = $query->where('merchant_id', $merchant_id);
            }
            $invoices = $query->get();

            $time = time();

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

            if ($type == 'zip') {
                $zip = new \ZipArchive();
                $zipFileName = storage_path() . '/app/Subv_invoices_' . $date->format('M') . '_' . $date->format('Y') . '_' . $time . '.zip';
                $res = $zip->open($zipFileName, \ZipArchive::CREATE);

                $s3 = Storage::disk('s3');
                $hasData = false;
                $type = 'merchant_disbursed';
                $filesPaths = [];
                foreach ($invoices as $invoice) {
                    if ($res === TRUE) {
//                        $file_name = str_replace(' ', '_', strtolower($type)) . '_' . $date->format('M') . '_' . $date->format('Y');
                        $file_path = '/merchant/' . $invoice->merchant->id . '/subvention_invoices/' . $date->format('M') . '_' . $date->format('Y');
                        $allfiles = Storage::disk('s3')->allFiles($file_path);

                        foreach ($allfiles as $key => $_file) {
                            if ($s3->exists($_file)) {
                                $s3_file = $s3->get($_file);
                                $path = storage_path() . '/' . $time . '_' . uniqid() . '.pdf';
                                $file = fopen($path, "w");
                                fwrite($file, $s3_file);
                                fclose($file);
                                if ($file) {
                                    //$zip->addFile($path, $file_name);
                                    $hasData = true;
                                }
                                //$s3_file = null;
                                //unlink($path);
                                $name = $invoice->merchant->merchant_name . '_' . $date->format('M') . '_' . $date->format('Y') . '_' . $key . '.pdf';
                                $filesPaths[$name] = $path;
                            }
                        }
                    } else {
                        return false;
                    }
                }

                foreach ($filesPaths as $file_name => $filesPath) {
                    $zip->addFile($filesPath, $file_name);
                }


                $zip->close();

                Mail::send('emails.reminders.basic_reminder',
                    ['body' => 'Please find the below ZIP file of Subvention Invoices ']
                    , function ($message) use ($zipFileName, $user) {
                        $message->to([$user->email])->bcc(['sarah@creditfair.in'])->subject('Exported Subvention Invoice');
                        $message->attachData(file_get_contents($zipFileName), 'Monthly_Invoice.zip');
                    });

                if (file_exists($zipFileName)) {
                    unlink($zipFileName);
                }
                foreach ($filesPaths as $file_name) {
                    unlink($file_name);
                }
                return true;
            } else if ($type == 'excel') {
                $response[] = ['DATE', 'INVOICE NO.', 'GSTN', 'MERCHANT NAME', 'CENTER NAME', 'TAXABLE AMOUNT', 'CGST', 'SGST', 'IGST', 'TOTAL'];
                foreach ($invoices as $invoice) {
                    $response[] = [
                        'date' => date('Y-m-d', strtotime($invoice->invoice_date)),
                        'invoice_id' => $invoice->invoice_id,
                        'gst' => $invoice->center->gst_number ?? $invoice->merchant->gst_number,
                        'name_on_invoice' => $invoice->merchant->merchant_name,
                        'center_on_invoice' => $invoice->center->name ?? '',
                        'taxable_value' => $invoice->net_amount,
                        'cgst' => $invoice->cgst,
                        'sgst' => $invoice->sgst,
                        'igst' => $invoice->igst,
                        'amount' => $invoice->amount,
                    ];
                }
                $request = new Request(['data' => $response, 'sheet' => 'Sheet1']);

                $name = 'Subv_invoices_' . $date->format('M') . '_' . $date->format('Y') . '.xls';
                Excel::store((new Exporter($request)), $name);

                Mail::send('emails.reminders.basic_reminder',
                    ['body' => 'Please find the below Excel file of Subvention Invoices ']
                    , function ($message) use ($name, $user) {
                        $message->to([$user->email])->bcc(['sarah@creditfair.in'])->subject('Exported Subvention Invoice');
                        $message->attachData(file_get_contents(storage_path() . '/app/' . $name), $name);
                    });

                if (!file_exists(storage_path() . '/app/' . $name)) {
                    unlink(storage_path() . '/app/' . $name);
                }

                return true;
            }
            return false;
        }catch (\Exception $e){
            return false;
        }
    }

    public function getAccountingReports(Request $request){
        $from_date = $request->get('from_date') ?? '';
        $month = $request->get('month') ?? '';
        $to_date = $request->get('to_date') ?? '';
        $year = $request->get('year') ?? '';
        $lender_id = $request->get('lender_id') ?? '';
        $selectedReportType = $request->get('selectedReportType') ?? '';
        $reportTypes = ['DPD Report', 'Book Debt Report', 'Accrued Revenue', 'Subvention Interest'];
        $_date = Carbon::now()->toDateTimeString();

        if($selectedReportType != ''){
            if((in_array($selectedReportType, ['Subvention Interest', 'Accrued Revenue']) && $month != "" && $year != "") || !in_array($selectedReportType, ['Subvention Interest', 'Accrued Revenue'])){
                $jobs = new CampaignsJobProvider();
                if ($selectedReportType == 'Subvention Interest') {
                    $jobs->from = 'getSubventionInterestReport';
                    $jobs->payload = json_encode(['year' => $year, 'month' => $month, 'lender_id' => $lender_id, 'user_email' => Auth::user()->email]);
                } else if ($selectedReportType == 'Accrued Revenue') {
                    $jobs->from = 'accrued_revenue';
                    $jobs->payload = json_encode(['year' => $year, 'month' => $month, 'lender_id' => $lender_id, 'user_email' => Auth::user()->email]);
//                    $jobs->payload = json_encode(['from_date' => $from_date, 'to_date' => $to_date, 'lender_id' => $lender_id, 'user_email' => Auth::user()->email]);
                } else {
                    $jobs->from = 'exportAccountingReport';
                    $jobs->payload = json_encode(array_merge($request->input(), ['user_email' => Auth::user()->email]));
                }
                $jobs->available_at = $_date;
                $jobs->application_id = 181;
                $jobs->created_at = $_date;
                $jobs->is_available = 0;
                $jobs->save();

                \Session::flash('success', 'The report will be sent to your email address');
            }else{
                \Session::flash('success', 'Please select the date range for generating the report');
            }
        }
        $request->merge(['user_email' =>Auth::user()->email]);
        $data['lenders'] = Lenders::get();
        $data['reportTypes'] = $reportTypes;
        $data['lender_id'] = $data['from_date'] = $data['month'] = $data['to_date'] = $data['year'] = $data['selectedReportType'] = '';
        return view('admin.accounting.accounting-reports', $data);
    }

    public function exportAccountingReport(Request $request){
        $from_date = $request->get('from_date') ?? '';
        $to_date = $request->get('to_date') ?? '';
        $lender_id = $request->get('lender_id') ?? '';
        $selectedReportType = $request->get('selectedReportType') ?? '';
        $time = time();
        $data_array = array();
        $user_email = $request->get('user_email');
        $_date = Carbon::now()->toDateTimeString();
        $exporter[] = ['Lender Name', 'Customer No', 'Name', 'purpose', 'State', 'Tenure', 'Loan Amount', 'Score', 'Profile', 'Income', 'Principal Overdue', 'Total DPD'];
        $exporter_debt[] = ['State', 'District', 'Branch', 'Application Id', 'Client Name', 'Account No.', 'Loan Purpose', 'Legal Form', 'Type Of Business', 'Monthly Income', 'Age', 'Gender', 'Credit Bureau Score', 'Sanction Amount', 'Loan Amount', 'ROI(%)', 'Disbursement Date', 'Disbursement Amount', 'Disbursement Phase', 'Payment Mode', 'Tenor (Months)', 'Maturity Date', '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', 'Outstanding Amount', 'Tagged Hypothicate to', 'Phone Number'];
        switch ($selectedReportType){
            case 'DPD Report':

                $data = EmiPayment::with('application_element','application.proFormaInvoice','application.emi', 'application.category','application.merchant','application.logs','application.lender','application.creditReport',
                    'moratoriums', 'application.last_payment_date', 'application.checkmandate')
                    ->whereHas('application', function ($q) {
                        $q->whereIn('state', ['disbursed','nach registered']);
                    });

                if($lender_id){
                    $data = $data->whereHas('application', function ($q) use ($lender_id) {
                        $q->where('lender_id', $lender_id);
                    });
                }
                if($from_date && $to_date) {
                    $data = $data->whereHas('application.logs', function ($q) use ($from_date, $to_date) {
                        $disbursement_date_from = Carbon::createFromFormat('Y-m-d', $from_date)->startOfDay()->toDateTimeString();
                        $disbursement_date_to = Carbon::createFromFormat('Y-m-d', $to_date)->endOfDay()->toDateTimeString();
                        $q->where('created_at', '>=', $disbursement_date_from)->where('created_at', '<=', $disbursement_date_to)->where('status','disbursed');
                    });
                }
                $data = $data->where('payment_status','!=','success')->orderBy('application_id', 'desc')->get();


                foreach($data as $val){
                    $data_array[$val->application->id]['application_data'] = $val;
                }
                foreach($data_array as $application){
                    //echo "<pre>";print_r($application['application_data']->application->id);die;
                    $pos_data = (new TestingController())->getPrincipalsOutstandingAdityaV2($_date, true, $application['application_data']->application->id);
                    /*$EMIPayment = new PaymentEmi();
                    $payments = $EMIPayment->getPaymentDueHistory($application['application_data']->application->id);
                    $payments = isset($payments[$application['application_data']->application->id]) ? $payments[$application['application_data']->application->id] : [];
                    $delay_penalty = 0;
                    if ($payments && isset($payments['payment'])) {
                        foreach ($payments['payment'] as $payment) {
                            if (isset($payment['delay_penalty']) && $payment['delay_penalty']) {
                                $delay_penalty++;
                            }
                        }
                    }*/
                    $exporter[] = [
                        'lender_name' => $application['application_data']->application->lender->name ?? '',
                        'customer_no' => $application['application_data']->application->id ?? '',
                        'name' => $application['application_data']->application->name ?? '',
                        'purpose' => $application['application_data']->application->category->name ?? '',
                        'state' => $application['application_data']->application->current_address_state ?? '',
                        'tenure' => $application['application_data']->application->emi->remaining_emi ?? '',
                        'loan_amount' => $application['application_data']->application->approved_amount ?? '',
                        'score' => $application['application_data']->application->creditReport[0]->Score ?? '',
                        'profile' => $application['application_data']->application->employee_status ?? '',
                        'income' => $application['application_data']->application->monthly_income ?? '',
                        'principal_overdue' => $pos_data[0]['after foreclosure p os'] ?? 0,
                        'total_dpd' => $application['application_data']->delay_days ?? '',
                    ];

                }

                $request = new Request(['data'=>$exporter,'sheet'=>'Sheet1']);
                //return Excel::download((new Exporter($request)), 'DPD_report_'.$from_date.'.xls');
                (new Slack(new Request(['title' => 'Accounting DPD Report Sending File', 'fields' => ['DPD Data Count' => count($exporter)], 'group' => Slack::$STAGE_TESTING])))->send();
                    try {
                        $filePath = $time.'_DPD_Data_'.$from_date.'.xls';
                        Excel::store((new Exporter($request)), 'exported/' . $filePath);
                        // Storage::disk('s3')->put('/collection/exported/'.$filePath, file_get_contents(storage_path('app/exported/' . $filePath)));
                        $dpd_file = file_get_contents(storage_path('app/exported/' . $filePath));
                        $name = time().'_DPD_Data_'.$from_date.'.xls';
                        Mail::send('emails.reminders.basic_reminder',
                        ['body' => "DPD Report attached below, Please find"]
                        , function ($message) use ($user_email, $dpd_file, $name) {
                            $message->to([$user_email])->subject('DPD_Report');
                            $message->cc('sarah@creditfair.in');
                            $message->attachData($dpd_file, $name);
                        });
                        (new Slack(new Request(['title' => 'DPD Report Sent', 'fields' => ['DPD Data Count' => count($exporter)], 'group' => Slack::$STAGE_TESTING])))->send();
                    }catch (\Exception $exception){
                        (new Slack(new Request(['title' => 'DPD Report Sent Error', 'fields' => ['e' => $exception->getMessage(),'l' => $exception->getLine(),'t' => $exception->getTraceAsString()], 'group' => Slack::$STAGE_TESTING])))->send();
                    }
                    return true;

                break;
            case 'Book Debt Report':

                $data = EmiPayment::with('application_element','application.proFormaInvoice','application.emi', 'application.category','application.merchant','application.logs','application.lender','application.creditReport',
                    'moratoriums', 'application.last_payment_date', 'application.checkmandate', 'application.disbursed', 'application.disbursement_log', 'application.disbursementV1','application.hypothecation_logs')
                    ->whereHas('application', function ($q) {
                        $q->whereIn('state', ['disbursed','nach registered']);
                    });

                if($lender_id){
                    $data = $data->whereHas('application', function ($q) use ($lender_id) {
                        $q->where('lender_id', $lender_id)->whereNull('deleted_at');
                    });
                }
                /*if($from_date && $to_date) {
                    $data = $data->whereHas('application.logs', function ($q) use ($from_date, $to_date) {
                        $disbursement_date_from = Carbon::createFromFormat('Y-m-d', $from_date)->startOfDay()->toDateTimeString();
                        $disbursement_date_to = Carbon::createFromFormat('Y-m-d', $to_date)->endOfDay()->toDateTimeString();
                        $q->where('created_at', '>=', $disbursement_date_from)->where('created_at', '<=', $disbursement_date_to)->where('status','disbursed');
                    });
                }*/
                if($to_date) {
                    $data = $data->whereHas('application.logs', function ($q) use ($to_date) {
                        $disbursement_date_to = Carbon::createFromFormat('Y-m-d', $to_date)->endOfDay()->toDateTimeString();
                        $q->where('created_at', '<=', $disbursement_date_to)->where('status','disbursed');
                    });
                }
                $data = $data->where('payment_status','!=','success')->orderBy('application_id', 'desc')->get();


                foreach($data as $val){
                    $data_array[$val->application->id]['application_data'] = $val;
                }
                $FDateE = '';//'2021-03-31 23:59:59';
                $FDateS = '';
                $FDate1E = '';
                $FDate1S = '';
                if(!empty($to_date) && !empty($from_date)){
                    $FDateE = Carbon::createFromFormat('Y-m-d', $to_date)->endOfDay();//'2021-03-31 23:59:59';
                    $FDateS = Carbon::createFromFormat('Y-m-d', $from_date)->startOfDay();
                    $FDate1E = Carbon::createFromFormat('Y-m-d', $to_date)->subMonth(1)->endOfDay();
                    $FDate1S = Carbon::createFromFormat('Y-m-d', $from_date)->subMonth(1)->startOfDay();
                }//'2021-03-01 00:00:00';
                foreach($data_array as $application){
                    //echo "<pre>";print_r($application['application_data']->application->id);die;
                    //$pos_data = (new TestingController())->getPrincipalsOutstandingAdityaV2($_date, true, $application['application_data']->application->id);
                    /*$EMIPayment = new PaymentEmi();
                    $payments = $EMIPayment->getPaymentDueHistory($application['application_data']->application->id);
                    $payments = isset($payments[$application['application_data']->application->id]) ? $payments[$application['application_data']->application->id] : [];
                    $delay_penalty = 0;
                    if ($payments && isset($payments['payment'])) {
                        foreach ($payments['payment'] as $payment) {
                            if (isset($payment['delay_penalty']) && $payment['delay_penalty']) {
                                $delay_penalty++;
                            }
                        }
                    }*/
                    $statusLog = StatusLogs::where('application_id', $application['application_data']->application->id)->whereIn('status', ['closed', 'cancelled'])->orderBy('created_at','desc')->first();
                    $isClosed = 0;
                    if($statusLog && $statusLog->created_at <= $FDateE){
                        $isClosed = 1;
                    }
                    $v = $this->getLoanScheduleDataV1($application['application_data']->application->id);
                    $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;
                    $dueAfterData = 0;
                    $interest_paid_during_MonthM2 = 0;

                    foreach($v['schedule'] as $vp => $c) {
                        $receivedOnMonth = 0;
                        if(isset($c['transaction'])){
                            foreach ($c['transaction'] as $transaction) {
                                if ($transaction->payment_date <= $FDateE && !$transaction->refunded_at) {
                                    $receivedOnMonth += $transaction->amount;
                                }
                            }
                        }
                        $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 ($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_paid_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'] ?? 0);
                        }
                    }
                    $t = new TestingController();
                    $dpdDaysCount = $isClosed ? 0 : $t->getDPDReport($application['application_data']->application->id, $FDateE);
                    $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;
                    }
                    $net_tenure = $application['application_data']->application->emi->tenure;
                    if ($application['application_data']->application->emi->advance_emi == 1){
                        $net_tenure = $application['application_data']->application->emi->tenure - $application['application_data']->application->emi->advance_emi;
                    }
                    if(count($application['application_data']->application->disbursement_log) > 0){
                        foreach($application['application_data']->application->disbursement_log as $val){
                            $exporter_debt[] = [
                                'state' => $application['application_data']->application->current_address_state ?? '',
                                'district' => $application['application_data']->application->current_address_city ?? '',
                                'branch' => 'Mumbai',
                                'application_id' => $application['application_data']->application->id ?? '',
                                'client_name' => $application['application_data']->application->name ?? '',
                                'loan_agreement_number' => $application['application_data']->application->proFormaInvoice->loan_application_no ?? '',
                                'loan_purpose' => $application['application_data']->application->category->name ?? '',
                                'legal_form' => '',
                                'type_of_business' => $application['application_data']->application->employee_status ?? '',
                                'monthly_income' => $application['application_data']->application->monthly_income ?? '',
                                'age' => (date('Y', strtotime($application['application_data']->application->created_at)) - date('Y', strtotime($application['application_data']->application->dob))) ?? 0,
                                'gender' => $application['application_data']->application->gender ?? '',
                                'credit_bureau_score' => isset($application['application_data']->application->creditReport[0]->Score) ? $application['application_data']->application->creditReport[0]->Score : '',
                                'sanction_amount' => $application['application_data']->application->approved_amount ?? '',
                                'loan_amount' => $application['application_data']->application->loan_amount ?? '',
                                'ROI' => ($application['application_data']->application->emi->interest_rate == "0.00") ? '0.00' : $application['application_data']->application->emi->interest_rate,
                                'disbursement_date' => $val->created_at ?? '',
                                'disbursed_amount' => $val->disbursement_amount ?? '',
                                'disbursement_phase' => $val->phase ?? '',
                                'payment_mode' => ($application['application_data']->application_element->is_payout == 1) ? 'Cashfree' : 'NEFT/RTGS/Online Payment',
                                'tenure' => $net_tenure ?? '',
                                'maturity_date' => $application['application_data']->application_element->last_emi_date ?? '',
                                'opening_principal_outstanding' => $OverduePrincipalo_sD2 ?? '',
                                'overdue_principal_outstanding' => $OverduePrincipalo_sE2 ?? '',
                                'principal_due_during_the_month' => $PrincipalDueduringthemonthF2 ?? '',
                                'principal_paid_during_the_month' => $principal_Paid_during_the_monthG2 ?? '',
                                'principal_overdue' => $principal_Overdue_H2 ?? '',
                                'dpd_days' => $dpdDaysCount ?? '',
                                'closing_principal_outstanding' => $PrincipalDueduringthemonthJ2 ?? '',
                                'interest_outstanding_begenning_of_month' => $interest_OS_beginning_OF_MonthK2 ?? '',
                                'interest_due_during_month' => $interest_due_during_MonthL2 ?? '',
                                'interest_paid_during_month' => $interest_paid_during_MonthM2 ?? '',
                                'interest_overdue' => $interest_overdueN2 ?? '',
                                'prepayments' => $foreclosureAmtReceived ?? '',
                                'outstanding_amount' => ($isClosed ? 0 : ($foreclosureAmtReceived > ($principalToBeReceivedTotal - $principalReceivedTotal) ? 0 : ($principalToBeReceivedTotal - ($principalReceivedTotal + $foreclosureAmtReceived)))) ?? '',
                                'tagged_hypothicate_to' => $application['application_data']->application->hypothecation_logs[0]->lender ?? '',
                                'phone_number' => $application['application_data']->application->mobile_number ?? ''
                            ];
                        }
                    }else{
                        if($application['application_data']->application->lender_id == Services::$lender_id){
                            $lender = new LenderServices(new Request());
                            $d_amt =  $lender->getPayloadValueByID($application['application_data']->application->id, 'actual_disbursement_amt');
                        }else{
                            $d_amt = $application['application_data']->application->emi->upfront_from_credit_fair - ($application['application_data']->application->emi->subvention_igst + $application['application_data']->application->emi->subvention_cgst + $application['application_data']->application->emi->subvention_sgst);
                            if (isset($application['application_data']->application->proFormaInvoice->processing_fee_by_merchant) && $application['application_data']->application->proFormaInvoice->processing_fee_by_merchant == 1) {
                                $d_amt = $d_amt - $application['application_data']->application->emi->processing_fee;
                            }

                            $insurance_premium_amount = isset($application['application_data']->application->proFormaInvoice->insurance_premium_amount) && $application['application_data']->application->proFormaInvoice->insurance_premium_applicable == 1 && $application['application_data']->application->proFormaInvoice->insurance_premium_by_merchant == 1 ? $application['application_data']->application->proFormaInvoice->insurance_premium_amount : 0;
                            if($insurance_premium_amount){
                                $d_amt = $d_amt - $insurance_premium_amount;
                            }

                            $upfront_from_customer = isset($application['application_data']->application->proFormaInvoice->merchant_collected_advance_amount) && $application['application_data']->application->proFormaInvoice->merchant_collected_advance_amount == 1 ? $application['application_data']->application->emi->upfront_from_customer : 0;
                            if($upfront_from_customer){
                                $d_amt = $d_amt + $upfront_from_customer;
                            }
                            if(isset($application['application_data']->application->disbursementV1->disbursed)){
                                $d_amt = $application['application_data']->application->disbursementV1->disbursed;
                            }
                            //$d_amt = (isset($application['application_data']->application->disbursementV1) && isset($application['application_data']->application->disbursementV1->disbursed) && $application['application_data']->application->disbursementV1->disbursed == 0) ? $application['application_data']->application->disbursementV1->upfront_from_credit_fair : (isset($application['application_data']->application->disbursementV1) && !empty($application['application_data']->application->disbursementV1) && isset($application['application_data']->application->disbursementV1->disbursed) ? $application['application_data']->application->disbursementV1->disbursed : '' );
                        }
                        $exporter_debt[] = [
                            'state' => isset($application['application_data']->application->current_address_state) ? $application['application_data']->application->current_address_state: '',
                            'district' => isset($application['application_data']->application->current_address_city) ? $application['application_data']->application->current_address_city : '',
                            'branch' => 'Mumbai',
                            'application_id' => $application['application_data']->application->id ?? '',
                            'client_name' => $application['application_data']->application->name ?? '',
                            'loan_agreement_number' => $application['application_data']->application->proFormaInvoice->loan_application_no ?? '',
                            'loan_purpose' => $application['application_data']->application->category->name ?? '',
                            'legal_form' => '',
                            'type_of_business' => $application['application_data']->application->employee_status ?? '',
                            'monthly_income' => $application['application_data']->application->monthly_income ?? '',
                            'age' => (date('Y', strtotime($application['application_data']->application->created_at)) - date('Y', strtotime($application['application_data']->application->dob))) ?? 0,
                            'gender' => $application['application_data']->application->gender ?? '',
                            'credit_bureau_score' => $application['application_data']->application->creditReport[0]->Score ?? '',
                            'sanction_amount' => $application['application_data']->application->approved_amount ?? '',
                            'loan_amount' => $application['application_data']->application->loan_amount ?? '',
                            'ROI' => ($application['application_data']->application->emi->interest_rate == "0.00") ? '0.00' : $application['application_data']->application->emi->interest_rate,
                            'disbursement_date' => $application['application_data']->application->disbursed->created_at ?? '',
                            'disbursed_amount' => $d_amt,
                            'disbursement_phase' => 'NA',
                            'payment_mode' => ($application['application_data']->application_element->is_payout == 1) ? 'Cashfree' : 'NEFT/RTGS/Online Payment',
                            'tenure' => $net_tenure ?? '',
                            'maturity_date' => $application['application_data']->application_element->last_emi_date ?? '',
                            'opening_principal_outstanding' => $OverduePrincipalo_sD2 ?? '',
                            'overdue_principal_outstanding' => $OverduePrincipalo_sE2 ?? '',
                            'principal_due_during_the_month' => $PrincipalDueduringthemonthF2 ?? '',
                            'principal_paid_during_the_month' => $principal_Paid_during_the_monthG2 ?? '',
                            'principal_overdue' => $principal_Overdue_H2 ?? '',
                            'dpd_days' => $dpdDaysCount ?? '',
                            'closing_principal_outstanding' => $PrincipalDueduringthemonthJ2 ?? '',
                            'interest_outstanding_begenning_of_month' => $interest_OS_beginning_OF_MonthK2 ?? '',
                            'interest_due_during_month' => $interest_due_during_MonthL2 ?? '',
                            'interest_paid_during_month' => $interest_paid_during_MonthM2 ?? '',
                            'interest_overdue' => $interest_overdueN2 ?? '',
                            'prepayments' => $foreclosureAmtReceived ?? '',
                            'outstanding_amount' => ($isClosed ? 0 : ($foreclosureAmtReceived > ($principalToBeReceivedTotal - $principalReceivedTotal) ? 0 : ($principalToBeReceivedTotal - ($principalReceivedTotal + $foreclosureAmtReceived)))) ?? '',
                            'tagged_hypothicate_to' => $application['application_data']->application->hypothecation_logs[0]->lender ?? '',
                            'phone_number' => $application['application_data']->application->mobile_number ?? ''
                        ];
                    }



                }

                $request = new Request(['data'=>$exporter_debt,'sheet'=>'Sheet1']);
                //return Excel::download((new Exporter($request)), 'DPD_report_'.$from_date.'.xls');
                (new Slack(new Request(['title' => 'Accounting Book Debt Report Sending File', 'fields' => ['Book Debt Data Count' => count($exporter_debt)], 'group' => Slack::$STAGE_TESTING])))->send();
                    try {
                        $filePath = $time.'_Book_Debt_Data_'.$from_date.'.xls';
                        Excel::store((new Exporter($request)), 'exported/' . $filePath);
                        // Storage::disk('s3')->put('/collection/exported/'.$filePath, file_get_contents(storage_path('app/exported/' . $filePath)));
                        $dpd_file = file_get_contents(storage_path('app/exported/' . $filePath));
                        $name = time().'_Book_Debt_Data_'.$from_date.'.xls';
                        Mail::send('emails.reminders.basic_reminder',
                        ['body' => "Book Debt Report attached below, Please find"]
                        , function ($message) use ($user_email, $dpd_file, $name) {
                            //$message->to([$user_email])->subject('Book_Debt_Report');
                            $message->to([$user_email])->subject('Book_Debt_Report');
                            $message->cc('sarah@creditfair.in');
                            $message->attachData($dpd_file, $name);
                        });
                        unlink(storage_path().'/app/exported/' . $filePath);
                        (new Slack(new Request(['title' => 'Book Debt Report Sent', 'fields' => ['DPD Data Count' => count($exporter)], 'group' => Slack::$STAGE_TESTING])))->send();
                    }catch (\Exception $exception){
                        (new Slack(new Request(['title' => 'Book Debt Report Sent Error', 'fields' => ['e' => $exception->getMessage(),'l' => $exception->getLine(),'t' => $exception->getTraceAsString()], 'group' => Slack::$STAGE_TESTING])))->send();
                    }
                    return true;

                break;
        }

        return true;
    }

    public function writeOffAmount(Request $request){
        if($request->has('id') && $request->has('write_off_amount') && $request->get('write_off_amount') > 0 && $request->has('user_id')){

            $paymentTranscation = PaymentTransaction::where('application_id', $request->get('id'))->whereNull('deleted_at')->where('payment_for', 'Write-off')->first(['id']);
            if(!isset($paymentTranscation->id)) {

                $consumerApplicationElement = ConsumerApplicationElement::where('application_id', $request->get('id'))->first(['total_amount_due']);
                if(isset($consumerApplicationElement->total_amount_due) && $request->get('write_off_amount') != $consumerApplicationElement->total_amount_due){
                    return response()->json(['status' => 'FAIL', 'message' => 'Total loan outstanding is '.$consumerApplicationElement->total_amount_due.'. Mismatch write-off amount.']);
                }else if(isset($consumerApplicationElement->total_amount_due) && $consumerApplicationElement->total_amount_due == 0){
                    return response()->json(['status' => 'FAIL', 'message' => 'You cant write-off the loan outstanding '.$consumerApplicationElement->total_amount_due.'. No Amount to write-off.']);
                }

                $date = Carbon::now();

                $data = [
                    'amount_received' => $request->get('write_off_amount'),
                    'mode' => 'Written-off',
                    'paid_by' => '',
                    'payment_reconciliation_date' => $date->toDateString(),
                    'umrn' => '',
                    'collected_by' => $request->get('user_id'),
                    'collected_by_type' => '1',
                    'adjust_with_disbursement' => 0,
                    'wallet_name' => '',
                    'reason' => $request->has('write_off_reason') && $request->get('write_off_reason') ? $request->get('write_off_reason') : '',
                    'trasanction_id' => 0,
                    'trasanction_acknowledgement' => '',
                    'application_id' => $request->get('id'),
                    'payment_type' => 'Write-off',
                    'payment_date' => $date->toDateString(),
                    'cf_transaction_id' => '',
                    'bank_id' => 5,
                    'status' => 'success',
                ];

                $this->makePaymentTransaction($data);

                return response()->json(['status' => 'OK', 'message' => 'Successfully Written-off the amount '.$request->get('write_off_amount')]);

            }
        }
        return response()->json(['status' => 'FAIL', 'message' => 'Failed to write-off the amount']);
    }

    private function makePaymentTransaction($data){
        $payment_transaction = new PaymentTransaction();
        $payment_transaction->emi_payment_id = 0;
        $payment_transaction->amount = $data['amount_received'];
        $payment_transaction->mode = $data['mode'];
        $payment_transaction->paid_by = $data['paid_by'];
        $payment_transaction->payment_reconciliation_date = $data['payment_reconciliation_date'];
        $payment_transaction->umrn = isset($data['umrn']) ? $data['umrn'] : '';
        $payment_transaction->collected_by = $data['collected_by'];
        $payment_transaction->collected_by_type = $data['collected_by_type'];
        $payment_transaction->adjust_with_disbursement = $data['adjust_with_disbursement'];
        $payment_transaction->wallet_name = $data['wallet_name'];
        $payment_transaction->reason = isset($data['reason']) ? $data['reason'] : '';
        $payment_transaction->trasanction_id = $data['trasanction_id'];
        $payment_transaction->trasanction_acknowledgement = $data['trasanction_acknowledgement'];
        $payment_transaction->application_id = $data['application_id'];
        $payment_transaction->payment_for = $data['payment_type'];
        $payment_transaction->payment_date = \Illuminate\Support\Carbon::parse($data['payment_date'])->format('Y-m-d');;
        $payment_transaction->cf_transaction_id = $data['cf_transaction_id'];
        $payment_transaction->bank_id = $data['bank_id'];
        $payment_transaction->status = isset($data['status']) ? $data['status'] : 'success';
        $payment_transaction->save();
    }

    public function generateInsuranceInvoice(){

        $inv_start_date = Carbon::now()->subMonth(1)->startOfMonth();
        $inv_end_date = Carbon::now()->subMonth(1)->endOfMonth();
        $applications = [];

        $status_logs = StatusLogs::where('status', 'disbursed')->where('created_at', '>=', $inv_start_date)
            ->where('created_at', '<=', $inv_end_date)->where('is_reversed',0)->get(['application_id']);


        foreach($status_logs as $log){
            if(!in_array($log->application_id, $applications)) {
                $applications[] = $log->application_id;
            }
        }

        $proforma = ProFormaInvoice::where('insurance_premium_amount', '>', 0)->whereIn('application_id', $applications)->get(['application_id','insurance_premium_amount']);

        $applicationController= new ConsumerApplicationController();

        foreach($proforma as $application){
            $data = ConsumerApplication::where('id', $application->id)->first(
                [
                    'permanent_address_state', 'current_address_state'
                ]
            );

            $gstDetails = (new ConsumerDocument(new Request()))->getGSTDetails(
                [
                    'amount' => $application->insurance_premium_amount,
                    'state' => (isset($data->permanent_address_state) && !empty($data->permanent_address_state)) ? $data->permanent_address_state : (isset($data->current_address_state) && !empty($data->current_address_state) ? $data->current_address_state : '')
                ]
            );
            $amt = (isset($gstDetails[0])) ? $gstDetails[0]['amount'] : 0;
            if ($amt) {
                if ($gstDetails) {
                    $response = array();
                    foreach ($gstDetails as $gst) {
                        if (isset($gst['taxes']) && $gst['taxes'] == "CGST") {
                            $response['cgst'] = $gst['gst_amount'];
                        } elseif (isset($gst['taxes']) && $gst['taxes'] == "SGST") {
                            $response['sgst'] = $gst['gst_amount'];
                        } else {
                            $response['igst'] = $gst['gst_amount'];
                        }
                    }
                }
                try {
                    $type = 'insurance_invoice';


                    $invoice = Invoices::where('application_id', $application->id)->where('type', $type)->whereNull('deleted_at')->first(['id']);
                    $_data = [
                        'application_id' => $application->id,
                        'invoice_id' => $applicationController->getInvoiceID($data, $type),
                        'amount' => (isset($gstDetails[0])) ? $gstDetails[0]['amount'] : 0,
                        'net_amount' => (isset($gstDetails[0])) ? $gstDetails[0]['net_amount'] : 0,
                        'igst' => (isset($response['igst'])) ? $response['igst'] : 0,
                        'cgst' => (isset($response['cgst'])) ? $response['cgst'] : 0,
                        'sgst' => (isset($response['sgst'])) ? $response['sgst'] : 0,
                        'lender_id' => $data->lender_id,
                        'type' => $type,
                        'status' => 1,
                        'created_at' => Carbon::now()->toDateTimeString()
                    ];

                    if (!isset($invoice->id)) {
                        Invoices::insert(
                            $_data
                        );
                    }
                } catch (\Exception $e) {

                }
            }
        }
    }

    public function getMerchantInsuranceConfig($id){
        $application = ConsumerApplication::where('id', $id)->first(['merchant_id', 'lender_id']);
        $merchant = Merchant::where('id', $application->merchant_id)->first(['insurance_premium', 'insurance_collection_method', 'is_collected']);
        if(isset($application->lender_id) && $application->lender_id) {
            $lender = Lenders::where('id', $application->lender_id)->first(['activate_insurance']);
            if (isset($lender->activate_insurance) && $lender->activate_insurance) {
                $application_element = ConsumerApplicationElement::where('application_id', $id)->first(['type_of_customer']);
                $insurance_coverage = in_array($application_element->type_of_customer, [1, 2]) ? 5 : 1;
                return [
                    'insurance_premium_applicable' => $merchant->insurance_premium ?? 0,
                    'insurance_premium_by_merchant' => $merchant->insurance_collection_method ?? 0,
                    'insurance_coverage' => $insurance_coverage,
                    'processing_fee_by_merchant' => $merchant->is_collected
                ];
            }
        }
        return [
            'insurance_premium_applicable' => 0,
            'insurance_premium_by_merchant' => 0,
            'insurance_coverage' => 0,
            'processing_fee_by_merchant' => $merchant->is_collected
        ];
    }

    public function downloadPrePaymentRevisedRPS(Request $request){
        $response = $this->getPrePaymentRevisedRPS($request);
        if($response->getData()->status == 'OK'){
            $data = $response->getData()->data;
            $pdf = App::make('snappy.pdf.wrapper');
            $proFormaInvoice = ProFormaInvoice::where('application_id', $request->get('application_id'))->first(['loan_application_no']);
            $revisedRPS = $pdf->loadHTML(view('front.sample-revised-rps', ['table' => $data, 'summary' => $request->all(), 'loan_agreement_number' => $proFormaInvoice->loan_application_no ?? '-']));
            return $revisedRPS->download('Sample Revised RPS.pdf');
        }else{
            \Session::flash('error', $response->getData()->message);
        }
    }

    public function getPrePaymentRevisedRPS(Request $request){
        if($request->get('amount') > 0){
            try {
                $repaymentController = new RepaymentController();
                $payload = $request->all();

                if (!$request->has('is_preview_flag')){
                    $payload = [
                        'application_id' => $request->get('application_id'),
                        'amount' => $request->get('amount'),
                        'payment_date' => $request->has('payment_date') ? $request->get('payment_date') : date('Y-m-d'),
                        'type' => $request->get('type') == 1 ? 'emi': 'tenure',
                        'is_preview_flag' => true,
                        'user_id' => Auth::check() ? Auth::user()->id : 107
                    ];
                }
                $response = $repaymentController->getRevisedRPS($payload);

                if(isset($response['status']) && $response['status'] == 'FAILED'){
                    return response()->json(['status' => 'FAIL', 'message' => $response['message']]);
                }


                $body = $this->generateTabularFormat($response);

                return response()->json(['status' => 'OK', 'message' => !$request->get('is_preview_flag') ? 'Pre Payment amount reconclied successfully' : 'Pre payment revised RPS fetched successfully', 'data' => $body]);
            }catch (\Exception $e){
                return response()->json(['status' => 'FAIL', 'message' => 'Something went wrong while preparing the RPS.']);
            }
        }

        return response()->json(['status' => 'FAIL', 'message' => 'Amount should be greater than zero']);
    }

    public function generateTabularFormat($response){
        $table = '<table class="table table-striped"><tr><td>Installment Number</td><td>EMI Date</td><td>Pre-EMI Amount</td><td>Interest Due</td><td>Principal Due</td><td>EMI Amount</td><td>Principal Outstanding</td><td>Foreclosure Amount</td></tr>';
        if(isset($response['data'])) {
            foreach ($response['data'] as $item) {
                $table .= '<tr><td>' . $item['installment_number'] . '</td><td>' . $item['emi_date'] . '</td><td>&#8377;' . str_replace('.00', '', money_format('%!i', $item['pre_emi_amount'])) . '</td><td>&#8377;' . str_replace('.00', '', money_format('%!i', $item['interest_due'])) . '</td><td>&#8377;' . str_replace('.00', '', money_format('%!i', $item['principal_due'])) . '</td><td>&#8377;' . str_replace('.00', '', money_format('%!i', $item['emi_amount'])) . '</td><td>&#8377;' . str_replace('.00', '', money_format('%!i', $item['principal_outstanding'])) . '</td><td>&#8377;' . str_replace('.00', '', money_format('%!i', $item['foreclosure_amount'])) . '</td></tr>';
            }
        }else{
            $table .= '<tr><td colspan="7" style="text-align: center;">No Data</td></tr>';
        }

        $table .= '</table>';

        return $table;
    }
}
