<?php
/**
 * Created by PhpStorm.
 * User: sunil
 * Date: 9/5/18
 * Time: 10:29 AM
 */

namespace App\Http\Controllers\Admin;

use App\ABFL\Services\Services;
use App\Avanse\Processes\AvanseProcesses;
use App\Avanse\Services\AvanseServices;
use App\BNPL;
use App\Imports\SettlementDateImport;
use App\LendBox;
use App\LendBoxLSP;
use App\CommunicationMapping;
use App\CommunicationService;
use App\ConsumerApplication;
use App\ConsumerApplicationElement;
use App\ConsumerApplicationFiles;
use App\Exports\Exporter;
use App\Http\Controllers\ConsentController;
use App\Http\Controllers\ApiController;
use App\Http\Controllers\Controller;
use App\KMGP2P;
use App\Merchant;
use App\Method\Vivriti\Payload\Payload;
use App\ProFormaInvoice;
use App\Shortio;
use App\Templates;
use App\Singularity\Singularity;
use Carbon\Carbon;
use Hashids\Hashids;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use MathPHP\Finance;
use App\ConsentLog;

class LenderServices extends Controller
{

    private $request;

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

    public function getReport(){

        if ($this->request->get('id')){
            $application = ConsumerApplication::with('lender')->where('id', $this->request->get('id'))->whereIn('lender_id', [Services::$lender_id,Singularity::$lender_id])->first();
            if (!isset($application->id)){
                Session::flash('error', 'You don\'t have permission to access the page');
                return \redirect()->to('/admin');
            }
        }

        $words = explode(" ", $application->lender->name);
        $firstLetters = array_map(function($word) {
            return substr($word, 0, 1); // Get the first letter of each word
        }, $words);
        $lenderName = implode("", $firstLetters);

        // $response[] = ['ID', 'Name'];
        $header[] = ['Field Name','Field Value'];
        // $data = ['data' => [$response], 'sheet' => $lenderName.' Loan Applications'];

        if (Auth::check() && 1) {
            // $data = ['data' => $this->getPayload(), 'sheet' => $lenderName.' Loan Applications'];
            $request = new Request(['data' => array_merge($header, $this->getPayload()), 'sheet' => $lenderName.' Loan Applications']);
        }

        // $request = new Request($data);
        $fileName = $lenderName.' Loan Applications ' . Carbon::now()->toDateTimeString() . '.xls';

        if ($this->request->get('id')){
            $applicationController = new ConsumerApplicationController();
            $applicationController->isInternal = true;
            $files = ConsumerApplicationFiles::where('consumer_application_id', $this->request->get('id'))->get();
            $zip = new \ZipArchive();
            $zipFileName = storage_path().'/app/'.$lenderName.' Loan Applications_'. $this->request->get('id').'_' . Carbon::now()->toDateTimeString() . '.zip';
            $res = $zip->open($zipFileName, \ZipArchive::CREATE);

            $i = 1;
            $list = [];
            foreach ($files as $file) {
                $path = $applicationController->viewFile($this->request->get('id'), str_replace($this->request->get('id').'/', '', $file->file_path));
                if ($res === True && $path) {
                    $paths = explode('/', $file->file_path);
                    $lPath = $paths[count($paths) - 1];
                    if (isset(explode('.', $lPath)[1])) {
                        $ex = explode('.', $lPath)[1];
                    }else{
                        $lPathLastChar = substr($lPath, -3);
                        if ($lPathLastChar == 'png'){
                            $ex = 'png';
                        }elseif ($lPathLastChar == 'jpg'){
                            $ex = 'jpg';
                        }elseif ($lPathLastChar == 'pdf'){
                            $ex = 'pdf';
                        }elseif (substr($lPath, -4) == 'jpeg'){
                            $ex = 'jpeg';
                        }
                    }
                    $zip->addFile($path, $i.' '.$file->file_type.'.'.$ex);
                    $list[] = $path;
                }
                $i++;
            }

            $bhp1 = (new ConsumerApplicationController)->getCibilReport($this->request->get('id'), 1,'',true);
            if($bhp1){
                $zip->addFile($bhp1, 'bureau_report_hard_1.pdf');
                $list[] = $bhp1;
            }
            $bsp1 = (new ConsumerApplicationController)->getSoftCibilReport($this->request->get('id'), 1,'',true);
            if($bsp1){
                $zip->addFile($bsp1, 'bureau_report_soft_1.pdf');
                $list[] = $bsp1;
            }
            $bhp2 = (new ConsumerApplicationController)->getCibilReport($this->request->get('id'), 2,'',true);
            if($bhp2){
                $zip->addFile($bhp2, 'bureau_report_hard_2.pdf');
                $list[] = $bhp2;
            }
            $bsp2 = (new ConsumerApplicationController)->getSoftCibilReport($this->request->get('id'), 2,'',true);
            if($bsp2){
                $zip->addFile($bsp2, 'bureau_report_soft_2.pdf');
                $list[] = $bsp2;
            }
            Excel::store((new Exporter($request)), $fileName);

            if ($res === True) {
                $zip->addFile(storage_path().'/app/'.$fileName, $fileName);
            }

            $zip->close();
            foreach($list as $d){
                unlink($d);
            }

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

        return Excel::download((new Exporter($request)), $fileName);
    }

//     public function sendConstantMessage($id){

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

//         $application = DB::connection('mysql_primary')
//             ->table('consumer_application')
//             ->where('id', $id)
//             ->first(['id', 'name', 'email', 'mobile_number', 'merchant_id']);

//         //$application = ConsumerApplication::connection('mysql_primary')->where('id', $id)->first(['id', 'name', 'email', 'mobile_number', 'merchant_id']);


//         if($application->merchant_id && !BNPL::is($application->merchant_id)) {
//             $email = isset($application->email) ? wall_decrypt($application->email) : null;
//             $merchant = Merchant::where('id', $application->merchant_id)->first(['merchant_name']);
//             $consent_key = array_search ('Consent', CommunicationService::$com_category);
//             $email_comm = CommunicationMapping::whereRaw('FIND_IN_SET('.$consent_key.',type_ids)')->where('communication_id',1)->where('merchant_id',$application->merchant_id)->count();
//             $communication = CommunicationMapping::where('merchant_id',$application->merchant_id)->count();
//             if (isset($email) && ($email_comm == 1 || $communication == 0)) {

//                 $body = '
//                                         <div style="font-size:13px;font-family:verdana,arial;line-height:1.5">
//                                             Dear ' . $application->name . ',
// By clicking "I Accept", I hereby declare all information provided by me is correct and hereby consent to K M Global Credit Private Limited and its <a href="' . asset('affiliate-partners') . '">affiliate lending partners</a> to receive my bureau details and other financial /KYC details for financing purpose for purchase made with ' . $merchant->merchant_name . '
// <div>Annual household Income > 3L</div>
// <table style="width:100%"><tbody><tr>
//             <td align="center" style="padding:30px 30px 30px 30px">
//              <table cellpadding="0" cellspacing="0" border="0">
//               <tbody><tr>
//                <td align="center" style="border-radius:3px;background-color:#0055cc;padding:11px 26px">
//                 <a href="' . asset("consent/" . $hashed_id) . '?em=true" style="color:white;text-decoration:none;text-transform:uppercase;font-size:16px" target="_blank" data-saferedirecturl="https://www.google.com/url?q=https://capitaluat.creditfair.in/login&amp;source=gmail&amp;ust=1637060221906000&amp;usg=AOvVaw3bBoklT_FpqO9DEsYxRg0q">
//                  I Agree</a>
//                </td>
//               </tr>
//              </tbody></table>
//             </td>
//            </tr></tbody></table>
//                                     </div>';

//             if ($application->merchant_id !=  _env("Finsall_id")){
//                 Mail::send('emails.reminders.basic_reminder',
//                     ['body' => $body]
//                     , function ($message) use ($email) {
//                         $message->to([$email])->subject('IMPORTANT: Consent required');
//                     });}
//             }

//             $link = Shortio::getUrl(asset("consent/" . $hashed_id));
//             $merchant_name = $merchant->merchant_name;
//             $affiliateLink = "https://lnk.creditfair.in/5jES";
//             // $sms_body = "By clicking on link ".$link.", I hereby declare all data provided by me is correct and hereby consent to K.M.Global Credit Pvt Ltd. and its affiliate lending partners (https://bit.ly/3TwDeS2) to receive my bureau and other financial /KYC details for financing purpose for purchase made with ".$merchant_name.". Regards, Credit fair";
//             $sms_body = "By clicking on link ".$link." I hereby declare all data provided by me is correct and hereby consent to K.M.Global Credit Pvt Ltd. and its affiliate lending partners ".$affiliateLink." to receive my bureau and other financial /KYC details for financing purpose for purchase made with ".$merchant_name.". Regards, Team Credit fair (KM Global)";
//             $args = [$link,$merchant_name];
//             $entity = ['templateid' => '1307173331891592692', 'entityid' => Templates::$entityid];
//             send_sms($application->mobile_number, ['message' => $sms_body,'id'=>$application->id,'id_type'=>'application_id',
//                 'templateDetails' => $entity, 'args' => $args]);

//             $WA_comm = CommunicationMapping::whereRaw('FIND_IN_SET("'.$consent_key.'",type_ids)')->where('communication_id',3)->where('merchant_id',$application->merchant_id)->count();
//             if ($application->mobile_number && ($WA_comm == 1 || $communication == 0)) {
//                 sendWhatsAppMessage($application->mobile_number, ['id' => $id, 'templateId' => Templates::$consent_bureau_pull_v1, 'args' => [$merchant->merchant_name, $hashed_id], 'templateType' => 'buttonTemplate']);
//             }
//         }
//     }

    public function sendConstantMessage($id, $applicant_type = 1)
    {
        (new ConsentController())->sendConsentMessage($id, $applicant_type);
    }

    // public function addConstantDocument($application_id, $applicant_type=1, $show_view=true){

    //     $hashids = new Hashids('Creditfair by CS', 20);
    //     $hashed_id = $hashids->decode($application_id);
    //     $message = 'Please try after sometime';
    //     $title = 'Sorry!';
    //     if(isset($hashed_id[0])) {

    //         $consumerApplicationElement = ConsumerApplicationElement::where('application_id', $hashed_id[0])->first(['is_consent']);

    //         if(isset($consumerApplicationElement->is_consent) && !$consumerApplicationElement->is_consent) {

    //             try {
    //                 $application = ConsumerApplication::with('proFormaInvoice')->where('id', $hashed_id[0])->first(['id', 'name', 'mobile_number', 'lender_id']);

    //                 $mobile = '';
    //                 $ip = '';
    //                 if ($this->request->has('em')) {
    //                     $ip = (new ApiController())->get_client_ip();
    //                 } else {
    //                     $mobile = $application->mobile_number;
    //                 }

    //                 if ($application) {
    //                     $consentExists = ConsentLog::where('application_id', $hashed_id[0])->where('applicant_type', $applicant_type)->first(['id', 'latitude', 'longitude']);
    //                     if (!$consentExists) {
    //                         $view = view('admin.consumer-application.consent_logs_document', ['data' =>
    //                             [
    //                                 'loan_application_no' => $application->proFormaInvoice && isset($application->proFormaInvoice->loan_application_no) ? ucwords($application->proFormaInvoice->loan_application_no) : '',
    //                                 'name' => $application->name,
    //                                 'mobile' => $mobile,
    //                                 'ip' => $ip,
    //                                 'consent_timestamp' => Carbon::now()->toDateTimeString(),
    //                                 'lender_id' => $application->lender_id
    //                             ]
    //                         ]);
    //                     } else {
    //                         $view = view('admin.consumer-application.consent_logs_document', ['data' =>
    //                             [
    //                                 'loan_application_no' => $application->proFormaInvoice && isset($application->proFormaInvoice->loan_application_no) ? ucwords($application->proFormaInvoice->loan_application_no) : '',
    //                                 'name' => $application->name,
    //                                 'mobile' => $mobile,
    //                                 'latitude' => $consentExists->latitude,
    //                                 'longitude' => $consentExists->longitude,
    //                                 'consent_timestamp' => Carbon::now()->toDateTimeString(),
    //                                 'lender_id' => $application->lender_id
    //                             ]
    //                         ]);
    //                     }

    //                     $pdf = App::make('snappy.pdf.wrapper');
    //                     (new ConsumerDocument(new Request()))->uploadToS3('consent_logs', $hashed_id[0], $pdf->loadHTML($view)->output());
    //                     $message = 'We have logged your Consent';
    //                     $title = 'Thank You!';
    //                     ConsumerApplicationElement::where('application_id', $application->id)->update(['is_consent' => 1]);
    //                 }
    //             } catch(\Exception $e) {
    //                     $cwFactory = new CloudWatchLoggerFactory();
    //                     $cwFactory->logger(json_encode(['application_id' => $application_id,'message' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()]));
    //             }
    //         }else{
    //             $message = 'We have already logged your Consent';
    //             $title = 'Thank You!';
    //         }
    //     }
    //     if (!$show_view) {
    //         return response()->json(['status'=>'OK', 'message'=>$message], 200);;
    //     }
    //     return view('front.message-redirect', ['message' => $message, 'title' => $title]);
    // }

    public function addConstantDocument($application_id, $applicant_type = 1, $show_view = true){
        $status = 'agree';
        (new ConsentController())->addConstantDocument($application_id, $applicant_type, $show_view, $status, $request = $this->request);
    }


    public function getPayload(){
        $applications = ConsumerApplication::with('proFormaInvoice','category','application_element','application_element.merchant_center','application_element.product','emi','activeOffer','company','bank_details','merchant');
        if ($this->request->get('id')){
            $applications = $applications->where('id', $this->request->get('id'));
        }
        $applications = $applications->whereIn('lender_id', [Services::$lender_id,Singularity::$lender_id])->whereNull('is_deleted')->get();
        $payload = [
            [''=>''],
            ['partner_application_id' => 'patner application id'],
            ['category' => 'Category'],
            ['location' => 'Location'],
            ['center_branch_name' => 'Center-Branch name'],
            ['actual_disbursement_amt' => 'Loan Amount'],
            ['scheme' => 'Scheme'],
            ['effective_tenure' => 'Effective Tenure'],
            ['total_tenure' => 'Total Tenure'],
            ['advance_emi_month' => 'Advance EMI month'],
            ['roi' => 'ROI'],
            ['advance_payment' => 'Advance payment'],
            ['loan_amount' => 'Loan Amount'],
            ['loan_amt_without_advance_payment' => 'Approved Amount'],
            ['proc_fee_including_gst' => 'Proc Fee including GST'],
            ['actual_disbursement_amt' => 'Actual Disbursement amt'],
            ['emi_amount' => 'EMI amount'],
//            ['subvention_%' => 'Subvention %'],
            ['subvention_amount_without_gst' => 'Subvention amount without GST'],
            ['subvention_amount_gst' => 'Subvention amount GST'],
            ['loan_applicant_first_name' => 'Loan applicant first Name'],
            ['middle_name' => 'Middle name'],
            ['last_name' => 'last name'],
            ['gender' => 'Gender'],
            ['dob' => 'DOB'],
            ['pan' => 'PAN'],
            ["father_husband_name" => "Father's- Husband name"],
            ["mother_maiden_name" => "Mother's maiden name"],
            ['marital_status' => 'Marital status'],
            ['student_name' => 'Student name'],
            ['personal_email_id' => 'Personal Email ID'],
            ['mobile_number' => 'Mobile number'],
            ['permanent_address' => 'Permanent Address'],
            ['pincode' => 'Pincode'],
            ['pincode_serviceable' => 'Pincode serviceable'],
            ['city' => 'City'],
            ['state' => 'state'],
            ['current_address_document_proof' => 'Current Address document proof'],
            ['net_monthly_income' => 'Net Monthly Income (INR)'],
            ['current_organization' => 'Current Organization'],
            ['employment_type' => 'Employment type'],
            ['office_address' => 'Office address'],
            ['office_pincode' => 'Office Pincode'],
            ['office_city' => 'Office City'],
            ['office_state' => 'Office State'],
            ['account_holder_name' => 'Account holder name'],
            ['ifsc_code' => 'IFSC code'],
            ['bank_name' => 'Bank name'],
            ['bank_branch' => 'Bank branch'],
            ['bank_account_number' => 'Bank account number'],
            ['type_of_account' => 'Type of account'],
            ['merchant_name' => 'Merchant Name – ABC Education/ XYZ Healthcare'],
            ['category' => 'Category – Education/Healthcare'],
            ['sub_category' => 'Sub-Category – Ed-Tech/ Non Critical'],
            ['product_description' => 'Product Description – AI/ML 2 Yr. Integrated course / Dental Treatment'],
            [''=>''],
            [''=>''],
            ['type_of_customer' => 'Type Of Customer'],
            ['type_of_solar_power' => 'Type Of Solar Power'],
            ['inverter' => 'Inverter to be Installed'],
            ['panel' => 'Panel to be Installed'],
            ['inverter_monthly_power_bill' => 'Monthly Power Bill'],
            ['inverter_KW_installation' => 'KW Installation'],
            ['inverter_gross_project_amount' => 'Gross Project Amount'],
            ['inverter_subsidy_amount' => 'Subsidy Amount'],
            ['inverter_power_savings' => 'Power Savings (Estimated)'],
            [''=>''],
            [''=>''],
            ['co_applicant_name' => 'Co Applicant Name'],
            ['co_applicant_relationship' => 'Co Applicant Relationship'],
            ['co_applicant_dob' => 'Co Applicant DOB'],
            ['co_applicant_father_name' => 'Co Applicant Father Name'],
            ['co_applicant_gender' => 'Co Applicant Gender'],
            ['co_applicant_pan_card' => 'Co Applicant Pan'],
            ['co_applicant_aadhaar_card' => 'Co Applicant Aadhaar'],
            ['co_applicant_email' => 'Co Applicant Email'],
            ['co_applicant_mobile_number' => 'Co Applicant Mobile Number'],
            ['co_applicant_address_status' => 'Co Applicant Address Status'],
            ['co_applicant_address_line_1' => 'Co Applicant Address'],
            ['co_applicant_address_state' => 'Co Applicant State'],
            ['co_applicant_address_pincode' => 'Co Applicant Pincode'],
            ['co_applicant_address_city' => 'Co Applicant Address State'],
            ['co_applicant_employee_status' => 'Co Applicant Employee Status'],
            ['co_applicant_monthly_income' => 'Co Applicant Monthly Income'],
            ['co_applicant_company_name' => 'Co Applicant Company Name']
        ];

        foreach ($applications as $application){
            foreach ($payload as $key => $item) {
                $payload[$key] = array_merge($payload[$key], ['value_'.$application->id => $this->getPayloadValue(key($item), $application)]);
            }
        }

        return $payload;
    }

    public function getPayloadValueByID($id, $key){
        $application = ConsumerApplication::where('id', $id)->with('proFormaInvoice','category','application_element.merchant_center','application_element.product','emi','activeOffer','company','bank_details','merchant')->first();
        return $this->getPayloadValue($key, $application);
    }

    public function getCategory($subCategory){
        $categories = [
            'Personal Loan'=>'Other',
            'Education'=>'Education',
            'Electronic Products'=>'Other',
            'Electronic Vehicles'=>'EV',
            'Other'=>'Other',
            'Loose Furniture'=>'Home Décor',
            'Dental Care'=>'Health',
            'Stemcell banking and treatment'=>'Health',
            'IVF and Fertility Treatments'=>'Health',
            'Multispeciality Treatments'=>'Health',
            'Modular Kitchen, wardrobes and Interior'=>'Home Décor',
            'Home Automation'=>'Home Décor',
            'Solar and Rooftop Solutions'=>'Home Décor',
            'Cosmetics'=>'Health',
            'Salary Advance'=>'Other',
            'Electronic Battery'=>'Other',
            'Dealer Financing'=>'Other',
            'PPE Suits'=>'Other',
            'Employee Travel'=>'Other',
            'K12 Education'=>'Education',
            'Upskilling Edtech'=>'Education',
            'Entrance prep'=>'Education',
            'K12 Edtech'=>'Education',
            'K12 Coaching'=>'Education',
            'Education consultancy leads'=>'Other',
            'Fertility Leads'=>'Health',
            'Painting Services'=>'Home Décor',
            'Equipment Financing'=>'Other',
            'Water Purifier'=>'Home Décor',
            'Jewelry'=>'Other',
            'SME'=>'Other',
            'Tours, Travels and Holidays'=>'Other',
            'Home Downpayment'=>'Other',
            'Travel and Leisure'=>'Other',
            'Revenue Based Financing'=>'Other',
            'Strategic partnerships & Alliances (Co-lending)'=>'Other',
        ];

        return $categories[$subCategory] ?? 'Other';
    }

    public function getPayloadValue($item, $application){
        switch ($item){
            case 'partner_application_id':
                return $application->proFormaInvoice ? $application->proFormaInvoice->loan_application_no : '';
                break;
            case 'category':
                return $application->category ? $this->getCategory($application->category->name) : '';
                break;
            case 'location':
                return $application->current_address_city;
                break;
            case 'center_branch_name':
                return $application->application_element && $application->application_element->merchant_center && $application->application_element->merchant_center->name ? $application->application_element->merchant_center->name : '';
                break;
            case 'loan_amount':
                if ($application->emi) {
                    $amt = ($application->approved_amount - $application->emi->upfront_from_customer);
                    if ($application->merchant->is_gst == 0) {
                        $amt = ($amt - (($amt) * $application->emi->subvention / 100));
                    }
                }
                return $amt ?? '';
                break;
            case 'scheme':
                return $application->emi && $application->emi->remaining_emi ? $application->emi->remaining_emi.' by 0' : '';
                break;
            case 'effective_tenure':
            case 'total_tenure':
                return $application->emi && $application->emi->remaining_emi ? $application->emi->remaining_emi : '';
                break;
            case 'advance_emi_month':
            case 'proc_fee_including_gst':
                return '0';
                break;
            case 'roi':
                $interest_rate = 0;
                try {
                    if ($application->merchant->is_gst == 0 && $application->activeOffer->subvention && $application->emi) {
                        $subvention = (new ConsumerApplicationController())->getSubventionDetails($application);
                        $amt = $application->approved_amount;
                        if ($application->merchant->charge_subvention_remaining_amount) {
                            $amt = $amt - $application->emi->upfront_from_customer;
                        }
                        //$sub = (($amt) * $application->emi->subvention /100);
                        $sub = $subvention['Net'];
                        $interest_rate = $this->getROI($application->emi->remaining_emi, $application, (($application->approved_amount - $application->emi->upfront_from_customer) - $sub));
                    } else if ($application->emi){
                        $interest_rate = $application->activeOffer->interest_rate;
                        if ($application->activeOffer->interest_type_id != 2) {
                            $amt = $application->approved_amount;
                            if ($application->merchant->charge_subvention_remaining_amount) {
                                $amt = $amt - $application->emi->upfront_from_customer;
                            }
                            //$sub = (($amt) * $application->emi->subvention /100);
                            //$sub = $subvention['WithGST'];
                            $interest_rate = $this->flatBalanceToReducing($application->emi->remaining_emi, $application, (($application->approved_amount - $application->emi->upfront_from_customer)));
                        }

                        //$interest_rate = $this->flatBalanceToReducing($application->emi->remaining_emi, $application, ($application->approved_amount - $application->emi->upfront_from_customer));
                    }
                }catch (\Exception $e){

                }
                return $interest_rate ? $interest_rate : '0';
                break;
            case 'advance_payment':
                //case: scheme
                //return $application->emi && in_array($application->activeOffer->advance_type, ['fixed_amount', 'percentage']) ? $application->emi->tenure : $application->emi->remaining_emi;
                return 0;
                //return $application->emi->upfront_from_customer;
                break;
            case 'loan_amount':
                return $application->loan_amount;
                break;
            case 'loan_amt_without_advance_payment':
                return $application->approved_amount - $application->emi->upfront_from_customer;
                break;
            case 'actual_disbursement_amt':
                if ($application->emi) {
                    $subvention = (new ConsumerApplicationController())->getSubventionDetails($application);


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

                    $upfront_from_customer = 0;
                    if (!$merchant_collected_advance_amount){
                        $upfront_from_customer = $application->emi->upfront_from_customer;
                    }

                    if ($application->merchant->is_gst == 0) {
                        return round($application->approved_amount - ($upfront_from_customer + ($subvention['Net'])));
                    }
                    return $application->approved_amount - ($upfront_from_customer);
                }
                return 0;
                break;
            case 'merchant_collected_upfront_from_customer':
                if ($application->emi) {

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

                    $upfront_from_customer = 0;
                    if (!$merchant_collected_advance_amount){
                        $upfront_from_customer = $application->emi->upfront_from_customer;
                    }

                    return$upfront_from_customer;
                }
                return 0;
                break;
            case 'actual_sanction_amt':
                if ($application->emi) {
                    $subvention = (new ConsumerApplicationController())->getSubventionDetails($application);


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

                    $upfront_from_customer = 0;
                    if (!$merchant_collected_advance_amount){
                        $upfront_from_customer = $application->emi->upfront_from_customer;
                    }

                    // if ($application->merchant->is_gst == 0) {
                    //     return round($application->approved_amount - ($upfront_from_customer + ($subvention['Net'])));
                    // }
                    return $application->approved_amount - ($upfront_from_customer);
                }
                return 0;
                break;
            case 'emi_amount':
                return $application->emi ? $application->emi->emi : 0;
                break;
//            case 'subvention_%':
//                return $application->emi->subvention;
                break;
            case 'subvention_amount_without_gst':
            case 'subvention_amount_gst':

                if ($application->merchant->is_gst){
                    $subvention = (new ConsumerApplicationController())->getSubventionDetails($application, false);
                    if ($item == 'subvention_amount_without_gst'){
                        return $subvention['Net'];
                    }
                    return $subvention['WithGST'];
                }

                return 0;
                if($application->emi->interest_rate){
                    return 0;
                }
                $subvention = (new ConsumerApplicationController())->getSubventionDetails($application);
                if ($item == 'subvention_amount_without_gst'){
                    return $subvention['Net'];
                }
                return $subvention['WithGST'];
                break;
            case 'loan_applicant_first_name':
            case 'middle_name':
            case 'last_name':
                $name = explode(' ', $application->name);
                if ($item == 'loan_applicant_first_name' && $name[0]){
                    return $name[0];
                }
                if ($item == 'middle_name' && count($name) > 2 && isset($name[1]) && $name[1]){
                    return $name[1];
                }
                if ($item == 'last_name' && count($name) > 2 && isset($name[2]) && $name[2]){
                    return $name[2];
                }elseif ($item == 'last_name' && count($name) > 1 && isset($name[1]) && $name[1]){
                    return $name[1];
                }
                return '';
                break;
            case 'gender':
                return $application->gender;
                break;
            case 'dob':
                return $application->dob;
                break;
            case 'pan':
                return $application->pan_card;
                break;
            case 'pincode_serviceable':
            case 'mother_maiden_name':
            case 'father_husband_name':
                return '';
                break;
            case 'marital_status':
                return $application->marital_status;
                break;
            case 'student_name':
                break;
            case 'personal_email_id':
                return $application->email;
                break;
            case 'mobile_number':
                return $application->mobile_number;
                break;
            case 'permanent_address':
                return $application->permanent_address_line_1;
                break;
            case 'pincode':
                return $application->permanent_address_pincode;
                break;
            case 'city':
                return $application->permanent_address_city;
                break;
            case 'state':
                return $application->permanent_address_state;
                break;
            case 'current_address_document_proof':
                break;
            case 'net_monthly_income':
                return $application->monthly_income;
                break;
            case 'current_organization':
                return $application->company->company;
                break;
            case 'employment_type':
                return $application->employee_status;
                break;
            case 'merchant_collected_advance_amount':
                return isset($application->proFormaInvoice->merchant_collected_advance_amount) ? $application->proFormaInvoice->merchant_collected_advance_amount : 0;
                break;
            case 'office_address':
                return $application->work_address_line_1;
                break;
            case 'office_pincode':
                return $application->work_address_pincode;
                break;
            case 'office_city':
                return $application->work_address_city;
                break;
            case 'office_state':
                return $application->work_address_state;
                break;
            case 'account_holder_name':
                return $application->bank_details ? $application->bank_details->name : '';
                break;
            case 'ifsc_code':
                return $application->bank_details ? $application->bank_details->ifsc_code : '';
                break;
            case 'bank_name':
                return $application->bank_details ? $application->bank_details->bank_name : '';
                break;
            case 'bank_branch':
                return $application->bank_details ? $application->bank_details->branch_name : '';
                break;
            case 'bank_account_number':
                return $application->bank_details ? $application->bank_details->account_number : '';
                break;
            case 'type_of_account':
                return $application->bank_details ? $application->bank_details->account_type : '';
                break;
            case 'merchant_name':
                return $application->merchant ? $application->merchant->merchant_name : '';
                break;
            case 'sub_category':
                return $application->category ? $application->category->name : '';
                break;
            case 'product_description':
                return $application->application_element && $application->application_element->product ? $application->application_element->product->name : ($application->application_element && $application->application_element->product_name ? $application->application_element->product_name : '');
                break;
            case 'type_of_customer':
                return $application->application_element && $application->application_element->type_of_customer ? $application->application_element->type_of_customer : '';
                break;
            case 'type_of_solar_power':
                return $application->application_element && $application->application_element->solar_power_type ? $application->application_element->solar_power_type : '';
                break;
            case 'inverter':
                return $application->application_element && $application->application_element->inverter ? $application->application_element->inverter : '';
                break;
            case 'panel':
                return $application->application_element && $application->application_element->panel ? $application->application_element->panel : '';
                break;
            case 'inverter_monthly_power_bill':
                return $application->application_element && $application->application_element->inverter_monthly_power_bill ? $application->application_element->inverter_monthly_power_bill : '';
                break;
            case 'inverter_KW_installation':
                return $application->application_element && $application->application_element->inverter_KW_installation ? $application->application_element->inverter_KW_installation : '';
                break;
            case 'inverter_gross_project_amount':
                return $application->application_element && $application->application_element->inverter_gross_project_amount ? $application->application_element->inverter_gross_project_amount : '';
                break;
            case 'inverter_subsidy_amount':
                return $application->application_element && $application->application_element->inverter_subsidy_amount ? $application->application_element->inverter_subsidy_amount : '';
                break;
            case 'inverter_power_savings':
                return $application->application_element && $application->application_element->inverter_power_savings ? $application->application_element->inverter_power_savings : '';
                break;
            case 'co_applicant_name':
                return $application->co_applicant_name  ?? '';
                break;
            case 'co_applicant_relationship':
                return $application->co_applicant_relationship  ?? '';
                break;
            case 'co_applicant_dob':
                return isset($application->co_applicant_name) ? $application->co_applicant_dob : '';
                break;
            case 'co_applicant_father_name':
                return $application->application_element && $application->application_element->co_applicant_father_name ? $application->application_element->co_applicant_father_name : '';
                break;
            case 'co_applicant_gender':
                return $application->co_applicant_gender  ?? '';
                break;
            case 'co_applicant_pan_card':
                return $application->co_applicant_pan_card  ?? '';
                break;
            case 'co_applicant_aadhaar_card':
                return $application->co_applicant_aadhaar_card  ?? '';
                break;
            case 'co_applicant_email':
                return $application->co_applicant_email  ?? '';
                break;
            case 'co_applicant_mobile_number':
                return $application->co_applicant_mobile_number  ?? '';
                break;
            case 'co_applicant_address_status':
                return $application->co_applicant_address_status  ?? '';
                break;
            case 'co_applicant_address_line_1':
                return $application->co_applicant_address_line_1  ?? '';
                break;
            case 'co_applicant_address_state':
                return $application->co_applicant_address_state  ?? '';
                break;
            case 'co_applicant_address_pincode':
                return $application->co_applicant_address_pincode  ?? '';
                break;
            case 'co_applicant_address_city':
                return $application->co_applicant_address_city  ?? '';
                break;
            case 'co_applicant_employee_status':
                return $application->co_applicant_employee_status  ?? '';
                break;
            case 'co_applicant_monthly_income':
                return $application->co_applicant_monthly_income  ?? '';
                break;
            case 'co_applicant_company_name':
                return $application->co_applicant_company_name  ?? '';
                break;

        }

        return '';
    }

    public static function accessible($id, $statusreversearray){
        if(!AvanseProcesses::accessible($id, $statusreversearray)){
            return false;
        }
        if(!static::isAccessible($id, $statusreversearray)){
            return false;
        }

        return true;
    }

    private static function isAccessible($id, $statusreversearray){
        if (Auth::user()->lender_id == Services::$lender_id) {
            $application = ConsumerApplication::where('id', $id)->where('lender_id', Services::$lender_id);
            if ($statusreversearray) {
                $application->whereNotIn('state', $statusreversearray['waiting for decision']);
            }else{
                $application->whereIn('state', ['cf approved','approved']);
            }
            $application = $application->first(['id']);
            return isset($application->id) ? $application->id : false;
        }

        return $id;
    }

    public function flatBalanceToReducingById($id){

        $application = ConsumerApplication::with('emi','activeOffer')->where('id', $id)->first(['id','merchant_id','offer_id', 'approved_amount']);

        $interest_rate = $application->activeOffer->interest_rate;
        if($application->activeOffer->interest_type_id != 2){
            $interest_rate = $this->flatBalanceToReducing($application->emi->remaining_emi, $application, ($application->approved_amount - $application->emi->upfront_from_customer));
        }
        return $interest_rate;
    }

    public function getROIById($id){

        $application = ConsumerApplication::with('emi','activeOffer')->where('id', $id)->first(['id','merchant_id','offer_id', 'approved_amount']);

        $interest_rate = $application->activeOffer->interest_rate;
        if($application->activeOffer->interest_type_id != 2){
            $amt = ($application->approved_amount - $application->emi->upfront_from_customer);
            $interest_rate = $this->getROI($application->emi->remaining_emi, $application, ($amt - (($amt) * $application->emi->subvention /100)));
        }
        return $interest_rate;
    }

    public function getROI($tenure, $application, $amount){
        //$merchant_collected_advance_amount = $application->proFormaInvoice && $application->proFormaInvoice->merchant_collected_advance_amount ? $application->proFormaInvoice->merchant_collected_advance_amount : 0;

        //$upfront_from_customer = 0;//$application->activeOffer->advance_type == 'emi' && $merchant_collected_advance_amount && $application->emi ? $application->emi->upfront_from_customer : 0;



        return round(Finance::rate($tenure, $application->emi->emi,(-$amount), 0)*12 * 100, 2);
    }

    public function flatBalanceToReducing($tenure, $application, $amount){

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

        $upfront_from_customer = 0;//$application->activeOffer->advance_type == 'emi' && $merchant_collected_advance_amount && $application->emi ? $application->emi->upfront_from_customer : 0;

        return round(Finance::rate($tenure, $application->emi->emi,(-$amount + $upfront_from_customer), 0)*12 * 100, 2);
    }

    public function documentUpload(){
        if ($this->request->get('lender_id') == AvanseServices::$lender_id){
            return (new AvanseController($this->request))->sendDocumentToAvanse();
        }else if ($this->request->get('lender_id') == Services::$lender_id){
            return (new ABFLController($this->request))->sendDocumentToABFL();
        }else if ($this->request->get('lender_id') == LendBox::$lender_id){
            $this->request->merge(['isLbLsp' => 'false']);
            return (new LendboxController($this->request))->SingleSendDocumentToLendbox();
        }else if ($this->request->get('lender_id') == LendBoxLSP::$lender_id){
            $this->request->merge(['isLbLsp' => 'true']);
            return (new LendboxController($this->request))->SingleSendDocumentToLendbox();
        }else if ($this->request->get('lender_id') == KMGP2P::$lender_id){
            return (new KMGP2PController($this->request))->SingleSendDocumentToKMGP2P();
        }else if ($this->request->get('lender_id') == Singularity::$lender_id){
            return (new HomevilleController($this->request))->getDocument();
        }

        return response()->json(['status' => 'FAIL', 'message' => 'Failed to send document']);
    }

    public function getDocumentBin(){

        $payload = new Payload();
        $hashids = new Hashids('Creditfair by CS', 20);
        $hash_id = $hashids->decode($payload->decode_jwt_token($this->request->get('access_token'))->session_string);
        if (isset($hash_id[0])){
            return $payload->returnDocument($hash_id[0]);
        }
        abort(404);
    }

    public function uploadSettlement(){
        $settlementDateImport = new SettlementDateImport($this->request);
        Excel::import($settlementDateImport, $this->request->file('file'));
        if ($settlementDateImport->status){
            \Session::flash('success', 'Settlement dates are updated. You can push the payments now');
            return redirect()->back();
        }else{
            \Session::flash('error', 'Failed to update the settlement date');
            return redirect()->back();
        }
    }
}
